branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>package com.example.grpc; import io.grpc.stub.StreamObserver; public class GreetingServiceImpl extends GreetingServiceGrpc.GreetingServiceImplBase { @Override public void greeting(GreetingServiceOuterClass.VehicleInfo request, StreamObserver<GreetingServiceOuterClass.VehicleResponse> responseObserver) { // VehicleRequest has toString auto-generated. System.out.println(request); // You must use a builder to construct a new Protobuffer object GreetingServiceOuterClass.VehicleResponse response = GreetingServiceOuterClass.VehicleResponse.newBuilder() .setGreeting(request.getSpeed()) .build(); // Use responseObserver to send a single response back responseObserver.onNext(response); responseObserver.onNext(response); responseObserver.onNext(response); responseObserver.onNext(response); // When you are done, you must call onCompleted. responseObserver.onCompleted(); } }
f8bcc4913ee6a74ca18fdb245265d8a4d8c6fab9
[ "Java" ]
1
Java
mladarsh/grpcJava
5378c179e59393d83ba09ba807c3649738eac7ab
585a1403aa0885e102a7920b78e986a72dc3fab1
refs/heads/master
<file_sep># R Style Ninja ---- www.rstyle.ninja # # HappyR library(ggplot2) # Head circleFun <- function(center = c(0,0),diameter = 1, npoints = 100){ r = diameter / 2 tt <- seq(0,2*pi,length.out = npoints) xx <- center[1] + r * cos(tt) yy <- center[2] + r * sin(tt) return(data.frame(x = xx, y = yy)) } # Smile! circleFun2 <- function(center = c(0,0),diameter = 1, npoints = 100){ r = diameter / 2 tt <- seq(0,2*(pi/-2),length.out = npoints) xx <- center[1] + r * cos(tt) yy <- center[2] + r * sin(tt) return(data.frame(x = xx, y = yy)) } # Smile! corner 1 circleFun3 <- function(center = c(0,0),diameter = 1, npoints = 100){ r = diameter / 2 tt <- seq(0,2*(pi/-2.5),length.out = npoints) xx <- center[1] + r * cos(tt) yy <- center[2] + r * sin(tt) return(data.frame(x = xx, y = yy)) } # Smile! corner 2 circleFun4 <- function(center = c(0,0),diameter = 1, npoints = 100){ r = diameter / 2 tt <- seq(-.5,2.5*(pi/-2.5),length.out = npoints) xx <- center[1] + r * cos(tt) yy <- center[2] + r * sin(tt) return(data.frame(x = xx, y = yy)) } data <- circleFun(c(1,-1),2.3,npoints = 100) #head data2 <- data.frame(x=c(.625,.625,.675,.575), y= c(-.59,-.41,-.5,-.5)) #eye data3 <- data.frame(x=c(1.375,1.375,1.325,1.425), y= c(-.59,-.41,-.5,-.5)) #eye data4 <- circleFun2(c(1,-1),1.7,npoints = 100) #smile data5 <- circleFun3(c(.13,-.90),.15,npoints = 100) #smile corner data6 <- circleFun4(c(1.87,-.90),.15,npoints = 100) #smile corner # plot all data with ggplot ggplot(data,aes(x,y)) + geom_polygon(color="black", fill="yellow", size=3) + stat_ellipse(data=data2, geom="polygon") + stat_ellipse(data=data3, geom="polygon") + geom_path(data=data4, size = 8, lineend="round") + geom_path(data=data5, size = 3, lineend="round") + geom_path(data=data6, size = 3, lineend="round") + theme(legend.position="none", panel.border = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_blank(), axis.text.x=element_blank(), axis.text.y=element_blank(), axis.ticks=element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank()) # END
d0b3bc7d0943ecc2b8db13d22a01899e73d62294
[ "R" ]
1
R
RStyleNinja/HappyR
d0af8139a654de1b8dbe511505a17eed09d71833
ff68a52cd371abb6b96a8b1fd16440e491570b03
refs/heads/master
<file_sep>"use strict"; let browserConfig = require("./config/webpack.browser.config"); let workerConfig = require("./config/webpack.workers.config"); module.exports = [ browserConfig(), workerConfig() ]; <file_sep>import {WorkerInput, WorkerResult, GerberParserOutput, GerberParserInput} from "../common/AsyncGerberParserAPI"; export class AsyncWorker<I, O> { protected worker:Worker; private workerData:Array<(output:O) => void> = []; protected init() { this.worker.onmessage = (e:MessageEvent) => { this.processResult(e.data as WorkerResult<O>); } } public scheduleWork(input:I, callback:(output:O) => void) { this.workerData.push(callback); let origin:string = "*"; if (window && window.location) { origin = window.location.origin; } let id = this.workerData.length - 1; let data = new WorkerInput<I>(id, origin, input); this.worker.postMessage(data); } public terminate() { this.worker.terminate(); } private processResult(result:WorkerResult<O>) { this.workerData[result.id](result.output); } } export class AsyncGerberParserInterface extends AsyncWorker<GerberParserInput, GerberParserOutput>{ constructor() { super(); this.worker = new Worker("AsyncGerberParser.worker.js"); this.init(); } } <file_sep>#!/bin/sh gsutil cp -Z *.html gs://www.pcbxprt.com/ gsutil cp -Z *.js gs://www.pcbxprt.com/ gsutil cp -Z *.wasm gs://www.pcbxprt.com/ gsutil -m setmeta -h "Cache-control: no-transform, max-age=3600" gs://www.pcbxprt.com/*.html gsutil -m setmeta \ -h "Content-Type: text/javascript; charset=utf-8" \ -h "Cache-control: no-transform, max-age=3600" \ gs://www.pcbxprt.com/*.js gsutil -m setmeta \ -h "Content-Type: application/wasm" \ -h "Cache-control: no-transform, max-age=3600" \ gs://www.pcbxprt.com/*.wasm gsutil acl ch -u AllUsers:R gs://www.pcbxprt.com/* echo all done!!! <file_sep>import {GerberToPolygons, Init, PolygonConverterResult} from "grbparser/dist/converters"; import {BoardLayer, BoardSide, GerberUtils, BoardFileType} from "grbparser/dist/gerberutils"; import {ExcellonParser} from "grbparser/dist/excellonparser"; import {KicadCentroidParser, KicadCentroidParserResult} from "grbparser/dist/kicadcentroidparser"; import * as JSZip from "jszip"; import {WorkerInput, GerberParserOutput, WorkerResult, ExcellonHoles, ComponentCenters, GerberParserInput} from "../common/AsyncGerberParserAPI"; import {Build} from "../common/build"; const ctx: Worker = self as any; interface ProcessingData { gerber?:PolygonConverterResult; holes?:ExcellonHoles; centers?:ComponentCenters; content?:string; side?:BoardSide; layer?:BoardLayer; exception?:string; unzipTime?:number; renderTime?:number; } class GerberRenderer { constructor(private inputData_:WorkerInput<GerberParserInput>) { this.processInput(); } gerberToPolygons( fileName:string, content:string, isOutline:boolean, unzipDuration:number) { Init.then(() => { try { let renderStart = performance.now(); let polygons = GerberToPolygons(content, isOutline); let renderEnd = performance.now(); let status = 'done'; if (((!polygons.solids || polygons.solids.length == 0) && (!polygons.thins || polygons.thins.length == 0)) || polygons.bounds == undefined) { status = 'empty'; } this.postStatusUpdate(fileName, status, { gerber:polygons, holes:undefined, unzipTime:unzipDuration, renderTime:renderEnd - renderStart }); } catch (e) { console.log(`Exception processing ${fileName}: ${e}`); this.postStatusUpdate(fileName, "error", { exception:e.toString(), unzipTime:unzipDuration }); } }); } excellonFile(fileName:string, content:string, unzipDuration:number) { try { //console.log(`Parsing '${fileName}'`); let renderStart = performance.now(); let parser = new ExcellonParser(); parser.parseBlock(content); parser.flush(); let renderEnd = performance.now(); let status = 'done'; let holes = parser.result(); if (holes.holes.length == 0) { status = 'empty'; } this.postStatusUpdate(fileName, status, { gerber:undefined, holes:holes, unzipTime:unzipDuration, renderTime:renderEnd - renderStart }); } catch (e) { console.log(`Exception processing ${fileName}: ${e}`); this.postStatusUpdate(fileName, "error", { exception:e.toString(), unzipTime:unzipDuration }); } } centroidFile(fileName:string, content:string, unzipDuration:number) { try { //console.log(`Parsing '${fileName}'`); let renderStart = performance.now(); let parser = new KicadCentroidParser(); parser.parseBlock(content); parser.flush(); let renderEnd = performance.now(); let status = 'done'; let centers = parser.result(); if (centers.components.length == 0) { status = 'empty'; } this.postStatusUpdate(fileName, status, { side:centers.side, gerber:undefined, centers:{centers:centers.components,bounds:centers.bounds}, unzipTime:unzipDuration, renderTime:renderEnd - renderStart }); } catch (e) { console.log(`Exception processing ${fileName}: ${e}`); this.postStatusUpdate(fileName, "error", { exception:e.toString(), unzipTime:unzipDuration }); } } processZipFiles(zip:JSZip) { for(let fileName in zip.files) { let zipObject = zip.files[fileName]; if (zipObject.dir) { continue; } if (fileName.endsWith('.DS_Store')) { continue; } if (fileName.indexOf('__MACOSX') >= 0) { continue; } fileName = GerberUtils.getFileName(fileName); let fileExt = GerberUtils.getFileExt(fileName.toLowerCase()); if (GerberUtils.bannedExtensions.indexOf(fileExt) >= 0) { console.log(`Ignoring known extension ${fileName}`); continue; } let fileInfo = GerberUtils.determineSideAndLayer(fileName); this.postStatusUpdate( fileName, "Processing", {side:fileInfo.side, layer:fileInfo.layer}); let startUnzip = performance.now(); zipObject .async("text") .then( (content) => { let endUnzip = performance.now(); this.postStatusUpdate(fileName, "Rendering", {content:content}); let fileType = GerberUtils.boardFileType(content); if ((fileInfo.layer == BoardLayer.Drill && fileType == BoardFileType.Unsupported) || fileType == BoardFileType.Drill) { fileInfo.layer = BoardLayer.Drill; fileInfo.side = BoardSide.Both; this.postStatusUpdate( fileName, "Rendering", {side:fileInfo.side, layer:fileInfo.layer}); this.excellonFile(fileName, content, endUnzip - startUnzip); } else if (fileType == BoardFileType.Centroid) { this.centroidFile(fileName, content, endUnzip - startUnzip); } else { this.gerberToPolygons( fileName, content, fileInfo.layer == BoardLayer.Outline || fileInfo.layer == BoardLayer.Mill, endUnzip - startUnzip); } }); } } processInput():void { if (this.inputData_.input.zipFileBuffer) { new JSZip() .loadAsync(this.inputData_.input.zipFileBuffer) .then(zip => this.processZipFiles(zip)); } else if (this.inputData_.input.files) { this.inputData_.input.files.forEach(file => { let fileName = file.fileName; if (fileName.endsWith('.DS_Store')) { return; } if (fileName.indexOf('__MACOSX') >= 0) { return; } fileName = GerberUtils.getFileName(fileName); let fileExt = GerberUtils.getFileExt(fileName.toLowerCase()); if (GerberUtils.bannedExtensions.indexOf(fileExt) >= 0) { console.log(`Ignoring known extension ${fileName}`); return; } let fileInfo = GerberUtils.determineSideAndLayer(fileName); this.postStatusUpdate( fileName, "Processing", {side:fileInfo.side, layer:fileInfo.layer}); this.postStatusUpdate(fileName, "Rendering", {content:file.content}); let fileType = GerberUtils.boardFileType(file.content); if ((fileInfo.layer == BoardLayer.Drill && fileType == BoardFileType.Unsupported) || fileType == BoardFileType.Drill) { fileInfo.layer = BoardLayer.Drill; fileInfo.side = BoardSide.Both; this.postStatusUpdate( fileName, "Rendering", {side:fileInfo.side, layer:fileInfo.layer}); this.excellonFile(fileName, file.content, -1); } else if (fileType == BoardFileType.Centroid) { this.centroidFile(fileName, file.content, -1); } else { this.gerberToPolygons( fileName, file.content, fileInfo.layer == BoardLayer.Outline || fileInfo.layer == BoardLayer.Mill, -1); } }); } } postStatusUpdate(fileName:string, status:string, data:ProcessingData) { let output = new GerberParserOutput( fileName, status, data.side, data.layer, data.content, data.gerber, data.holes, data.centers, data.exception, data.unzipTime, data.renderTime); ctx.postMessage(new WorkerResult<GerberParserOutput>(this.inputData_.id, output)); } } ctx.addEventListener("message", (e:MessageEvent) => { let data = e.data as WorkerInput<GerberParserInput>; const renderer = new GerberRenderer(data); }); console.log(`GerberView WK build ${Build}`);
466be24397f148d24050c8a92bf660aaf978d61a
[ "JavaScript", "TypeScript", "Shell" ]
4
JavaScript
erwzqsdsdsf/grbviewer
0a3a6be68632646667ad9d0038bf1ab6e18f7be4
5015da215fda26db458707c0f9799e08bafd9229
refs/heads/master
<repo_name>thorsager/jNetTelnet<file_sep>/src/main/java/dk/krakow/jnettelnet/samples/SampleCiscoClient.java /* * Copyright (c) 2013, <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * * Neither the name of Open Solutions nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package dk.krakow.jnettelnet.samples; import dk.krakow.jnettelnet.CiscoSession; /** * <p> * Sample usage of the <code>dk.krakow.net.telnet.CiscoSession</code> class * </p> * <pre> * // Create a session * CiscoSession cs = new CiscoSession("cisco.host.com",23); * * // Connect the session to the host * cs.connect(); * * // Login using username and password, if we are not asked * // for the user name, it will not be used. * cs.login("myusername", "Secret"); * * // Enable on the router using password * cs.enable("evenMoreSecret"); * * // Setup the terminal (to avoid the paging stuff) * cs.cmd("terminal length 0"); // ignoring output.. * * // Print the ios versino information * for (String line: cs.cmd("show version") ) { System.out.println("got: "+line); } * * // Print the running configuration of the host * for (String line: cs.cmd("show running") ) { System.out.println("got: "+line); } * * // Disconnect from remote host * cs.close(); * </pre> * * @author <NAME> &lt;<EMAIL>&gt; */ public class SampleCiscoClient { public static void main(String[] args) throws Exception { // Create a session CiscoSession cs = new CiscoSession("cisco.host.com",23); // Connect the session to the host cs.connect(); // Login using username and password, if we are not asked // for the user name, it will not be used. cs.login("myusername", "<PASSWORD>"); // Enable on the router using password cs.enable("evenMoreSecret"); // Setup the terminal (to avoid the paging stuff) cs.cmd("terminal length 0"); // ignoring output.. // Print the ios versino information for (String line: cs.cmd("show version") ) { System.out.println("got: "+line); } // Print the running configuration of the host for (String line: cs.cmd("show running") ) { System.out.println("got: "+line); } // Disconnect from remote host cs.close(); } } <file_sep>/README.md jNetTelnet ========== A java lookalike of the Net::Telnet Perl module<file_sep>/src/test/java/dk/krakow/jnettelnet/AlliedTelesisSessionTest.java package dk.krakow.jnettelnet; import org.junit.Test; /** * Simple testcase to test Connect Timeout */ public class AlliedTelesisSessionTest { @Test(expected = SessionException.class) public void not_connected() throws Exception { Session s = new AlliedTelesisSession("192.168.200.94",23); s.connect(); } }<file_sep>/src/main/java/dk/krakow/jnettelnet/SessionOptionHandler.java /* * Copyright (c) 2013, <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * * Neither the name of Open Solutions nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package dk.krakow.jnettelnet; /** * Describes the SessionOptionHandlers, all classes that are to handle * SessionOptions from the Session must implement this interface. * * @author <NAME> &lt;<EMAIL>&gt; */ public interface SessionOptionHandler { /** * Method that is call from the <code>Session</code> with a list of SessionOptions * read from the remote host. * <p> * The handler must read and "understand" all the options, and generate a new * set of options that are to be transmitted to the remote host. * </p> * <p> * Any options sent to remote host should confirm to the protocol described * in RFC-854 and RFC-855 * </p> * * @param optionList Options read from the remote host * @return Options to be sent to the remote host. */ public SessionOptionList onOptionsRead(SessionOptionList optionList); } <file_sep>/src/main/java/dk/krakow/jnettelnet/SessionOption.java /* * Copyright (c) 2013, <NAME> <<EMAIL>> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * * Neither the name of Open Solutions nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dk.krakow.jnettelnet; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Contains a Telnet Protocol option, and handles the unsigned byte * stuff of the protocol in the Java environment. * * @author <NAME> &lt;<EMAIL>&gt; */ class SessionOption { private int optionCode; private int option; public static int WILL = 0xFB; public static int WONT = 0xFC; public static int DO = 0xFD; public static int DONT = 0xFE; private static final Map<Integer,String> ocNames ; private static final Map<Integer,String> oNames ; static { Map<Integer, String> oc = new HashMap<Integer,String>(); oc.put(250, "Subnegotiation"); oc.put(251, "Will"); oc.put(252, "Won't"); oc.put(253, "Do"); oc.put(254, "Don't"); ocNames = Collections.unmodifiableMap(oc); Map<Integer, String> o = new HashMap<Integer,String>(); o.put(1, "Echo"); o.put(3, "Suppress Go Ahead"); o.put(5, "Status"); o.put(6, "Timing Mark"); o.put(10, "Output Carriage-Return Disposition"); o.put(11, "Output Horizontal Tab Stops"); o.put(12, "Output Horizontal Tab Stop Disposition"); o.put(13, "Output Formfeed Disposition"); o.put(14, "Output Vertical Tabstops"); o.put(15, "Output Vertical Tab Disposition"); o.put(16, "Output Linefeed Disposition"); o.put(17, "Extended ASCII"); o.put(24, "Terminal Type"); o.put(31, "Negotiate About Window Size"); o.put(32, "Terminal Speed"); o.put(33, "Remote Flow Control"); o.put(34, "Linemode"); o.put(34, "Linemode"); o.put(37, "Linemode"); oNames = Collections.unmodifiableMap(o); } /** * Create the option from two bytes * @param optionCode Option code byte * @param option option byte */ public SessionOption(byte optionCode, byte option) { this.optionCode |= optionCode & 0xFF ; this.option |= option & 0xFF; } /** * Create the option from two ints, as this is how java would like * us to handle unsigned bytes. * @param optionCode Option code byte * @param option Option byte */ public SessionOption(int optionCode, int option) { this.optionCode = optionCode; this.option = option; } /** * Get option part of the SessionOption * @return option byte (as an int) */ public int getOption() { return option; } /** * Get option code part of the SessionOption * @return option code byte (as an int) */ public int getOptionCode() { return optionCode; } /** * Convert the option to a byte array, ready to be transmitted to remote host * @return option as byte array. */ public byte[] getBytes() { return new byte[] {(byte)0xFF, (byte)optionCode, (byte)option}; } @Override public String toString() { return ocNames.get(optionCode)+"("+optionCode+") "+oNames.get(option) +"("+option+")"; } } <file_sep>/pom.xml <!-- ~ Copyright (c) 2013, <NAME> <<EMAIL>> ~ All rights reserved. ~ ~ Redistribution and use in source and binary forms, with or without modification, ~ are permitted provided that the following conditions are met: ~ ~ * Redistributions of source code must retain the above copyright notice, this ~ list of conditions and the following disclaimer. ~ ~ * Redistributions in binary form must reproduce the above copyright notice, this ~ list of conditions and the following disclaimer in the documentation and/or ~ other materials provided with the distribution. ~ ~ * Neither the name of Open Solutions nor the names of its contributors may be ~ used to endorse or promote products derived from this software without ~ specific prior written permission. ~ ~ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ~ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ~ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ~ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ~ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, ~ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ~ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ~ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE ~ OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED ~ OF THE POSSIBILITY OF SUCH DAMAGE. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>dk.krakow.jnettelnet</groupId> <artifactId>jNetTelnet</artifactId> <version>1.3</version> <packaging>jar</packaging> <name>jNetTelnet</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project>
a80009e6cfe261c6f2f076c49c1e4e7ddf91de7d
[ "Markdown", "Java", "Maven POM" ]
6
Java
thorsager/jNetTelnet
25c7c3ca706a8938031b19eab8b934d877ef88bb
a48bb9b972be5bc7a0d9a2595a7e310a163949c0
refs/heads/master
<file_sep>import Vue from 'vue' import VueRouter from 'vue-router' import MyCart from '../views/MyCart' import Checkout from "../views/Checkout" import HomePage from "../views/Home" Vue.use(VueRouter); const routes = [ { "path" : "/", "name" : "home", "component" : HomePage }, { "path" : "/cart", "name" : "cart", "component" : MyCart }, { "path" : "/checkout", "name" : "checkout", "component" : Checkout } ] const router = new VueRouter({ routes }) export default router<file_sep>import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios'; Vue.use(axios) Vue.use(Vuex); export const store = new Vuex.Store({ state: { products:[], cart: [] }, getters : { PRODUCTS: state => { return state.products }, CART: state => { return state.cart } }, mutations: { SET_PRODUCTS : (state,payload) => { state.products = payload }, TOCART :(state,payload) =>{ state.cart.push(payload) alert(JSON.stringify(state.cart)) } }, actions : { GET_PRODUCTS : async (context) => { let {data} = await axios.get( "http://localhost:5000/api/v1/product/allproducts" ); context.commit("SET_PRODUCTS",data) }, ADD_TOCART : async(context,payload) => { context.commit("TOCART",payload) } } })
985fa33f579bbce213ea72dd296804d294367dc0
[ "JavaScript" ]
2
JavaScript
7ananthan/ecommerce-website-frontend-vue
fea56167a7940d1e98065a8bfe61d115abc12668
65563fd6394ac9073861d2c144821cb266b4fc87
refs/heads/master
<repo_name>thejason40/octo-micro-site<file_sep>/Gemfile source 'https://rubygems.org' ruby '2.1.5' gem 'sinatra' gem 'sinatra-content-for' gem 'octocore', '~> 0.0.2', '0.0.2' gem 'rspec' <file_sep>/README.md # octo-micro-site This is what used to power the octo.ai main website. <file_sep>/app/controllers/root_controller.rb class RootController < ApplicationController get '/' do erb :home end post '/notifyme' do args = { email: params[:client_email], created_at: Time.now } # # opts = { # created_at: Time.now # } obj = Octo::Subscriber.new(args).save! if obj "success" else "error" end end end<file_sep>/app/controllers/privacy_controller.rb class PrivacyController < ApplicationController get '/' do erb :cookiepolicy end end<file_sep>/app/controllers/contact_us_controller.rb class ContactUsController < ApplicationController get '/' do erb :contactus end post '/' do args = { email: params[:emailid], created_at: Time.now, firstname: params[:fname], lastname: params[:lname], message: params[:contactusmessage], typeofrequest: params[:requesttype] } obj = Octo::ContactUs.new(args).save! if obj "success" else "error" end end end<file_sep>/config.ru # config.ru require 'sinatra/base' require 'sinatra/content_for' # pull in the helpers and controllers require './app/helpers/application_helper.rb' require './app/controllers/application_controller.rb' Dir.glob('./app/{helpers,controllers}/*.rb').each { |file| require file } # map the controllers to routes map('/') {run RootController} map('/about-us') {run AboutUsController} map('/contact') {run ContactUsController} map('/faq') {run FaqController} map('/jobs') {run JobsController} map('/privacy') {run PrivacyController} <file_sep>/app/controllers/jobs_controller.rb class JobsController < ApplicationController get '/' do erb :jobs end get '/dev' do erb :developer end get '/dataeng' do erb :dataeng end end<file_sep>/Dockerfile #Use ruby-2.1.5 official image FROM ruby:2.1.5 MAINTAINER <NAME> <<EMAIL>> #Install dependencies: # - build-essentials: to ensure certain gems can be compiled #RUN apt-get update && apt-get install -qq -y build-essential RUN apt-get update #Set ENV variable to store app inside the image ENV INSTALL_PATH /apps RUN mkdir -p $INSTALL_PATH #Ensure gems are cached and only get updated when they change. WORKDIR /tmp COPY Gemfile /tmp/Gemfile RUN bundle install #Copy application code from workstation to the working directory COPY . $INSTALL_PATH #Symlink central config to app config #COPY central-config . #RUN ln -s config-master/ config/config WORKDIR $INSTALL_PATH CMD ["rackup"] EXPOSE 9292<file_sep>/app/controllers/faq_controller.rb class FaqController < ApplicationController get '/' do erb :faq end end<file_sep>/app/public/assets/js/home.js $("#notifyform").submit(function(event){ event.preventDefault(); args = { "client_email": $('#client_email').val() }; $.post("/notifyme", args,function(data, status){ if(status=="success") { var text; if(data=="success") { text = "Hey, thanks for contacting us. We'll be in touch!" } else { text = "Sorry, some error occured, drop us a mail at <EMAIL>" } $("#notifyform").fadeOut( 100 , function() { $(this).html("<div class='formmsg " + data +"formc'>" + text + "</div>"); }).fadeIn( 1000 ); } }); }); $("#contactform").submit(function(event){ event.preventDefault(); // firstname: params[:fname], // lastname: params[:lname], // message: params[:contactusmessage], // typeofrequest: params[:requesttype], args = { "emailid": $('#email').val(), "fname": $('#firstname').val(), "lname": $('#lastname').val(), "contactusmessage": $('#message').val(), "requesttype": $("select[name='requesttype']").val() }; $.post("/contact", args,function(data, status){ if(status=="success") { var text; if(data=="success") { text = "Hey, thanks for contacting us. We'll be in touch!" } else { text = "Sorry, some error occured, drop us a mail at <EMAIL>" } $("#contactform").fadeOut( 100 , function() { $(this).html("<div class='formmsg " + data +"formc'>" + text + "</div>"); }).fadeIn( 1000 ); } }); });<file_sep>/app/helpers/application_helper.rb # application_helper.rb module ApplicationHelper end
d3c0a9d86ede693495d276f9666119f9eb651c9b
[ "Markdown", "JavaScript", "Ruby", "Dockerfile" ]
11
Ruby
thejason40/octo-micro-site
023197fe51dc630b05ff9e5192abe13fb6801b09
26ff2635fa3142fcf8f071c7ce772f6c1d6e4a1d
refs/heads/master
<repo_name>tathaibinh/SuperNetwork<file_sep>/README.md A Java implementation of the FTP protocol and WEB protocol with GUI . It contains a mutil-service and mutil-protocol super server and super client . 一个用Java实现的拥有GUI界面的FTP协议和WEB协议。它包括一个多服务、多协议的超级服务器和超级客户端。<file_sep>/src/com/isdaidi/ftpserver/FtpServer.java package com.isdaidi.ftpserver; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.net.InetAddress; import java.net.Socket; import java.util.Hashtable; import java.net.ServerSocket; import java.io.InputStream; import java.io.OutputStream; import java.io.FileInputStream; import java.awt.event.*; import java.net.*; import javax.swing.JTextArea; import javax.swing.JTextField; import com.isdaidi.superserver.ServerMain; public class FtpServer implements Runnable { public String rootDir = ServerMain.rootDir; // default ftp directory private int ftpPort = ServerMain.ftpPort; private JTextArea txtLog; Socket socket = null; public FtpServer(JTextArea txtLog) { this.txtLog = txtLog; } public void run() { txtLog.append("Ftp服务器正在启动...\n"); ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(ftpPort); } catch (IOException e) { txtLog.append("Ftp服务器启动失败!错误日志:\n" + e); e.printStackTrace(); } txtLog.append("Ftp服务器启动成功!正在监听"+ftpPort+"端口。\n"); while (true) { try { socket = serverSocket.accept(); new Thread(new FtpThread(socket, txtLog)).start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } <file_sep>/src/com/isdaidi/ftpserver/FtpThread.java package com.isdaidi.ftpserver; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import javax.swing.JTextArea; import com.isdaidi.superserver.ServerMain; public class FtpThread implements Runnable { private InputStream input = null; private OutputStream output = null; private JTextArea txtLog; private Socket socket = null; private String rootDir = ServerMain.rootDir; // default ftp directory private String username = "anonymous"; private String password = "<PASSWORD>"; public FtpThread(Socket socket, JTextArea txtLog) { this.socket=socket; this.txtLog=txtLog; } @Override public void run() { txtLog.append("Ftp服务器:用户 "+socket.getInetAddress()+":"+socket.getPort()+" 连接到FTP服务器上。\n"); try { input = socket.getInputStream(); output = socket.getOutputStream(); Request request = new Request(input, txtLog); Response response = new Response(output, txtLog); response.setRequest(request); response.setWorkingDir(rootDir); response.sendEventMsg(Response.WELCOME); request.getMsg(); // get user name boolean flag=true; if (request.getRequestType() != Request.LOGIN_USER) { response.sendEventMsg(Response.ERROR_CMD); socket.close(); flag=false; } response.sendEventMsg(Response.GET_PSW); // get user password request.getMsg(); if (request.getRequestType() != Request.LOGIN_PASS) { response.sendEventMsg(Response.ERROR_CMD); socket.close(); flag=false; } if (!request.getUser().equals(username) || !request.getPsw().equals(password)) { // user // password // uncorrect response.sendEventMsg(Response.PSW_ERROR); socket.close(); flag=false; } response.sendEventMsg(Response.LOGIN_SUCC); // login while (request.getRequestType() != Request.LOGOUT && flag) { System.out.println(request.getRequestType()); request.getMsg(); response.sendEventMsg(request.getRequestType()); } // Close the socket socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/src/com/isdaidi/superserver/ServerMain.java package com.isdaidi.superserver; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Hashtable; import javax.swing.*; import com.isdaidi.ftpserver.FtpServer; import com.isdaidi.webserver.WebServer; public class ServerMain extends JFrame implements ActionListener { private Thread ftpThread; private Thread webThread; private JTextField txtUri; private JButton btnStartFtp; private JButton btnStartWeb; private JButton btnExit; private JButton btnChoose; private JPanel contain; private JPanel contain1; private JTextArea txtLog; private JFileChooser fileChooser; public static final int ftpPort = 21; public static final int webPort = 8080; public static String rootDir = System.getProperty("user.dir") + File.separator + "root"; Hashtable userList = new Hashtable(); ServerSocket serverSocket = null, rServerSocket = null; Socket socket = null, rSocket = null; public ServerMain() { super("超级服务器");// 命名 Container container = getContentPane(); txtLog = new JTextArea(); txtLog.setLineWrap(true); txtUri = new JTextField(20); fileChooser = new JFileChooser(); btnStartFtp = new JButton("打开FTP服务器"); btnStartWeb = new JButton("打开WEB服务器"); btnExit = new JButton("退出"); btnChoose = new JButton("选择工作目录"); btnStartFtp.addActionListener(this); btnStartWeb.addActionListener(this); btnExit.addActionListener(this); btnChoose.addActionListener(this); contain = new JPanel(); contain1 = new JPanel(); container.setLayout(new BorderLayout()); container.add(contain1, BorderLayout.NORTH); contain1.add(txtUri); contain1.add(btnChoose); container.add(contain, BorderLayout.SOUTH); contain.add(btnStartFtp); contain.add(btnStartWeb); contain.add(btnExit); container.add(new JScrollPane(txtLog), BorderLayout.CENTER); setSize(500, 300); setVisible(true); this.validate(); setLocationRelativeTo(null);// 窗体居中 addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } public void actionPerformed(ActionEvent e) { if (e.getSource() == btnStartWeb) { if (webThread == null) { rootDir = txtUri.getText(); txtLog.append("尝试设定工作目录:" + rootDir + "\n"); if (rootDir == null || "".equals(rootDir)) { txtLog.append("设定失败,请检查是否设置工作目录。\n"); } else { WebServer webRunner = new WebServer(txtLog); txtLog.append("设定成功,尝试打开WEB服务…\n"); webThread = new Thread(webRunner); webThread.start(); } } else { txtLog.append("WEB服务已经启动,无需再次打开!\n"); } } else if (e.getSource() == btnStartFtp) { if (ftpThread == null) { rootDir = txtUri.getText(); txtLog.append("尝试设定工作目录:" + rootDir + "\n"); if (rootDir == null || "".equals(rootDir)) { txtLog.append("设定失败,请检查是否设置工作目录。\n"); } else { FtpServer ftpRunner = new FtpServer(txtLog); txtLog.append("设定成功,尝试打开FTP服务…\n"); ftpThread = new Thread(ftpRunner); ftpThread.start(); } } else { txtLog.append("FTP服务已经启动,无需再次打开!\n"); } } else if (e.getSource() == btnExit) { System.exit(0); } else if (e.getSource() == btnChoose) { fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int intRetVal = fileChooser.showOpenDialog(this); if (intRetVal == JFileChooser.APPROVE_OPTION) { txtUri.setText(fileChooser.getSelectedFile().getPath()); } } } public static void main(String[] args) { ServerMain sm = new ServerMain(); } } <file_sep>/src/com/isdaidi/client/ClientMain.java package com.isdaidi.client; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Desktop; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import com.isdaidi.ftpserver.FtpServer; import com.isdaidi.webserver.WebServer; public class ClientMain extends JFrame implements ActionListener { private JLabel lblUrl; private JTextField txtUrl; private JButton btnStartFtp; private JButton btnStartWeb; private JButton btnExit; public ClientMain() { super("超级客户端--并发测试");// 命名 Container container = getContentPane(); lblUrl = new JLabel("输入网址:"); txtUrl = new JTextField("http://localhost:8080/",20); btnStartFtp = new JButton("打开FTP客户端"); btnStartWeb = new JButton("打开WEB客户端"); btnExit = new JButton("退出"); btnStartFtp.addActionListener(this); btnStartWeb.addActionListener(this); btnExit.addActionListener(this); container.setLayout(null); lblUrl.setBounds(25, 25, 70, 40); txtUrl.setBounds(95, 25, 250, 40); btnStartWeb.setBounds(355, 25, 130, 40); btnStartFtp.setBounds(55, 95, 180, 40); btnExit.setBounds(270, 95, 180, 40); container.add(lblUrl); container.add(txtUrl); container.add(btnStartFtp); container.add(btnStartWeb); container.add(btnExit); setSize(530, 200); setVisible(true); this.validate(); setLocationRelativeTo(null);// 窗体居中 addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } public void actionPerformed(ActionEvent e) { if (e.getSource() == btnStartWeb) { try { Runtime.getRuntime().exec("cmd.exe /c start iexplore "+txtUrl.getText()); } catch (IOException e1) { e1.printStackTrace(); } } else if (e.getSource() == btnStartFtp) { new FtpClientFrame(); } else if (e.getSource() == btnExit) { System.exit(0); } } public static void main(String[] args) { new ClientMain(); } }
c12f354079dcab1689a5409ce97e915cbe7f8637
[ "Markdown", "Java" ]
5
Markdown
tathaibinh/SuperNetwork
55f198b9e2abc6d8c2cc799b2602bab4a18a64d4
3dcff76e8778c7daaf3cdee2aabab572bd853404
refs/heads/master
<file_sep><?php use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder { public function run() { factory(\App\User::class)->create([ 'email' => '<EMAIL>', 'password' => '<PASSWORD>', ]); factory(\App\User::class, 18)->create(); } } <file_sep># VueAxios Vue and Laravel Tutorial
3404781d1f9a9ad77f59ff2c79815188d463c321
[ "Markdown", "PHP" ]
2
PHP
junedc/VueAxios
295c44ef7cdab781263d9b6fab3d2e7a9d262b65
badcf871faa071cf26dd6557022dbc7e32a217e9
refs/heads/master
<file_sep><?php error_reporting(5); $dbHost = "localhost"; $dbUser = "root"; $dbPass = "<PASSWORD>"; $dbDatabase = "aquarium"; $db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database."); mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database."); $file = fopen("/proc/trafficsqueezer/dpi_http_access", "r") or exit("Unable to open file!"); while(!feof($file)) { $buffer = fgets($file, 14096); foreach (preg_split("/(\r?\n)/", $buffer) as $line) { //ignore any partial filled lines given by /proc !! if(substr_count($line, ",")>=7) //atleast this many columns should exist in this row ! { $array = split(",", $line); $jiffies = $array[0]; $request_type = $array[7]; if($request_type==NULL) { $request_type = '-'; } $src_ip = $array[5]; $dest_ip = $array[6]; $domain = $array[2]; $content = $array[3]; $browser = $array[4]; $query = "insert into dpi_http_access_log (jiffies,timestamp,request_type,src_ip,dst_ip,domain,content,browser) values ($jiffies, now(),'$request_type',\"$src_ip\",\"$dest_ip\",\"$domain\",\"$content\",\"$browser\")"; $result = mysql_query($query, $db); } } } fclose($file); ?> <file_sep><?php $page_title = "Statistics Overall"; include('c/c_header.php'); ?> <meta http-equiv='refresh' content="10"> </head><?php include('c/c_body.php'); ?> <?php $contentfile="content_stats_overall.php"; $help="nohelp";include('c/c_main.php'); ?><file_sep><?php include('c/c_check_login.php'); ?> <html><body style="font-family:arial;font-size:10px;"> <?php error_reporting(5); include("c/c_db_access.php"); include('c/c_bigpicture.php'); include("c/c_get_db_basic_config.php"); print "<div style=\"position:absolute;left:5;top:35;border:0;\">Remote IP-Subnet(s)/Machines</div>"; status_box_var($r_ip_ntwrk_machine_en, 156, 35); function short_subnet_mask($subnet_msk) { $short_subnet_mask = 0; $subnet_msk_octets = split('\.', $subnet_msk); $n = $subnet_msk_octets[0]; $n = ($n & 0x55555555) + (($n & 0xaaaaaaaa) >> 1); $n = ($n & 0x33333333) + (($n & 0xcccccccc) >> 2); $n = ($n & 0x0f0f0f0f) + (($n & 0xf0f0f0f0) >> 4); $n = ($n & 0x00ff00ff) + (($n & 0xff00ff00) >> 8); $n = ($n & 0x0000ffff) + (($n & 0xffff0000) >> 16); $short_subnet_mask += $n; $n = $subnet_msk_octets[1]; $n = ($n & 0x55555555) + (($n & 0xaaaaaaaa) >> 1); $n = ($n & 0x33333333) + (($n & 0xcccccccc) >> 2); $n = ($n & 0x0f0f0f0f) + (($n & 0xf0f0f0f0) >> 4); $n = ($n & 0x00ff00ff) + (($n & 0xff00ff00) >> 8); $n = ($n & 0x0000ffff) + (($n & 0xffff0000) >> 16); $short_subnet_mask += $n; $n = $subnet_msk_octets[2]; $n = ($n & 0x55555555) + (($n & 0xaaaaaaaa) >> 1); $n = ($n & 0x33333333) + (($n & 0xcccccccc) >> 2); $n = ($n & 0x0f0f0f0f) + (($n & 0xf0f0f0f0) >> 4); $n = ($n & 0x00ff00ff) + (($n & 0xff00ff00) >> 8); $n = ($n & 0x0000ffff) + (($n & 0xffff0000) >> 16); $short_subnet_mask += $n; $n = $subnet_msk_octets[3]; $n = ($n & 0x55555555) + (($n & 0xaaaaaaaa) >> 1); $n = ($n & 0x33333333) + (($n & 0xcccccccc) >> 2); $n = ($n & 0x0f0f0f0f) + (($n & 0xf0f0f0f0) >> 4); $n = ($n & 0x00ff00ff) + (($n & 0xff00ff00) >> 8); $n = ($n & 0x0000ffff) + (($n & 0xffff0000) >> 16); $short_subnet_mask += $n; return $short_subnet_mask; } $top = 50; print "<div style=\"position:absolute;left:5;top:0;border:0;\"><img src=\"i/cc/black/cloud_icon&32.png\" width=32 \"></div>"; $query = "select type, network_id, subnet_msk from remote_subnet "; $result=mysql_query($query, $db); if(mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $network_id = $row['network_id']; $subnet_msk = $row['subnet_msk']; $short_subnet_mask = short_subnet_mask($subnet_msk); print "<div style=\"position:absolute;left:5;top: $top;border:0;\"> $network_id/$short_subnet_mask </div>"; $top += 15; } } $top = 50; print "<div style=\"position:absolute;left:150;top:0;border:0;\"><img src=\"i/cc/black/comp_icon&32.png\" width=32 \"></div>"; $query = "select type, ip_addr from remote_ip_machine"; $result=mysql_query($query, $db); if(mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $ip_addr = $row['ip_addr']; print "<div style=\"position:absolute;left:160;top: $top;border:0;\"> $ip_addr </div>"; $top += 15; } } ?></body></html><file_sep><?php include("c/c_db_access.php"); include('c/c_g_var_set.php'); include("c/c_g_var_tcp_opt_set.php"); session_start(); error_reporting(5); $mode = $_GET['mode']; //Disable everything (initialize) set_mode("MODE_NONE", $query, $db); activate_router($query, $db); //disable (if not enabled) activate_bridge($query, $db); //disable (if not enabled) //unset ports set_port_lan_name("none", $query, $db); set_port_wan_name("none", $query, $db); if($mode=="reset") { /* do nothing since it is reset above */ print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=w_finish.php\">"; } else if($mode=="router") { set_mode("MODE_ROUTER", $query, $db); redirect(); } else if($mode=="bridge") { set_mode("MODE_BRIDGE", $query, $db); redirect(); } else if($mode=="local-device") { set_mode("MODE_LOCAL", $query, $db); print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=w_wan_port.php\">"; } else if($mode=="local-device-router") //router + local-device-mode (such as when Squid enabled and so on). { set_mode("MODE_ROUTER_LOCAL", $query, $db); redirect(); } else if($mode=="simulation") { set_mode("MODE_SIMULATE", $query, $db); print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=w_wan_port_simulation.php\">"; } else { redirect(); } function redirect() { print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=w_lan_port.php\">"; } ?><file_sep>GCC=gcc SOURCE_DIR=src OBJS_DIR=objs INCLUDE_DIR=inc #WALL=-Wall WALL= OBJS_DAEMON=$(OBJS_DIR)/core.o $(OBJS_DIR)/udp.o $(OBJS_DIR)/trafficsqueezerd.o HEADERS_DAEMON=$(INCLUDE_DIR)/core.h $(INCLUDE_DIR)/udp.h all: trafficsqueezerd clean-dirs: rm -rf $(OBJS_DIR)/* $(OBJS_DIR)/core.o: $(GCC) $(WALL) -c -o $(OBJS_DIR)/core.o $(SOURCE_DIR)/core.c $(OBJS_DIR)/udp.o: $(OBJS_DIR)/core.o $(GCC) $(WALL) -c -o $(OBJS_DIR)/udp.o $(SOURCE_DIR)/udp.c $(OBJS_DIR)/trafficsqueezerd.o: $(HEADERS_DAEMON) $(SOURCE_DIR)/trafficsqueezerd.c $(GCC) $(WALL) -c -o $(OBJS_DIR)/trafficsqueezerd.o $(SOURCE_DIR)/trafficsqueezerd.c trafficsqueezerd: $(OBJS_DAEMON) $(OBJS_DIR)/trafficsqueezerd.o $(GCC) $(WALL) -o trafficsqueezerd $(OBJS_DAEMON) -lpthread -lm clean: clean-dirs rm -rf trafficsqueezerd rm -rf ../*~ rm -rf ./*~ rm -rf ./src/*~ rm -rf ./inc/*~ install: make all rm -rf ../gui/trafficsqueezerd cp trafficsqueezerd ../gui/. <file_sep><?php include("/var/www/html/c/c_db_access.php"); function calculate_stats_pct($lan_rx, $lan_tx, $wan_rx, $wan_tx, & $lan_stats_pct, & $wan_stats_pct) { $lan_stats_pct=round((($lan_rx-$lan_tx)*100)/$lan_rx, 0); $wan_stats_pct=round((($wan_tx-$wan_rx)*100)/$wan_tx, 0); } $file = fopen("/proc/trafficsqueezer/stats", "r") or exit("Unable to open file!"); while(!feof($file)) { $buffer = fgets($file, 4096); if(!strncmp($buffer, "overall|", strlen("overall|"))) { $array = explode('|', $buffer); $lan_rx = $array[1]; $lan_tx = $array[2]; $wan_rx = $array[3]; $wan_tx = $array[4]; $lan_stats_pct = 0; $wan_stats_pct = 0; calculate_stats_pct($lan_rx, $lan_tx, $wan_rx, $wan_tx, $lan_stats_pct, $wan_stats_pct ); $lan_bytes_saved = $lan_rx-$lan_tx; $wan_bytes_saved = $wan_tx-$wan_rx; $lan_rx = round($lan_rx/1024, 0); $lan_tx = round($lan_tx/1024, 0); $wan_rx = round($wan_rx/1024, 0); $wan_tx = round($wan_tx/1024, 0); $lan_bytes_saved = round($lan_rx-$lan_tx, 0); $wan_bytes_saved = round($wan_tx-$wan_rx, 0); if($lan_stats_pct==0 && $wan_stats_pct==0 && $lan_rx==0 && $lan_tx==0 && $wan_rx==0 && $wan_tx==0 && $lan_bytes_saved==0 && $wan_bytes_saved==0) { print "overall| Complete zero entry, ignoring this data entry !\n"; } else { $query = "insert into stats_overall (timestamp, lan_stats_pct, wan_stats_pct, lan_rx, lan_tx, wan_rx, wan_tx, lan_bytes_saved, wan_bytes_saved) "; $query .= "values (now(), $lan_stats_pct, $wan_stats_pct, $lan_rx, $lan_tx, $wan_rx, $wan_tx, $lan_bytes_saved, $wan_bytes_saved)"; print "$query <br><hr>\n"; mysql_query($query, $db); } }else if(!strncmp($buffer, "ip_proto|", strlen("ip_proto|"))) { $array = explode('|', $buffer); $l_tcp_pkt_cnt = $array[1]; $l_udp_pkt_cnt = $array[2]; $l_icmp_pkt_cnt = $array[3]; $l_sctp_pkt_cnt = $array[4]; $l_others_pkt_cnt = $array[5]; $l_units_format = '-'; $w_tcp_pkt_cnt = $array[6]; $w_udp_pkt_cnt = $array[7]; $w_icmp_pkt_cnt = $array[8]; $w_sctp_pkt_cnt = $array[9]; $w_others_pkt_cnt = $array[10]; $w_units_format = '-'; if($l_tcp_pkt_cnt==0 && $l_udp_pkt_cnt==0 && $l_icmp_pkt_cnt==0 && $l_sctp_pkt_cnt==0 && $l_others_pkt_cnt==0 && $w_tcp_pkt_cnt==0 && $w_udp_pkt_cnt==0 && $w_icmp_pkt_cnt==0 && $w_sctp_pkt_cnt==0 && $w_others_pkt_cnt==0) { print "ip_proto| Complete zero entry, ignoring this data entry !\n"; } else { $query = "insert into stats_ip_proto ( timestamp, l_tcp_pkt_cnt, l_udp_pkt_cnt, l_icmp_pkt_cnt, l_sctp_pkt_cnt, l_others_pkt_cnt, l_units_format, w_tcp_pkt_cnt, w_udp_pkt_cnt, w_icmp_pkt_cnt, w_sctp_pkt_cnt, w_others_pkt_cnt, w_units_format)"; $query .= "values (now(), $l_tcp_pkt_cnt, $l_udp_pkt_cnt, $l_icmp_pkt_cnt, $l_sctp_pkt_cnt, $l_others_pkt_cnt, '$l_units_format', $w_tcp_pkt_cnt, $w_udp_pkt_cnt, $w_icmp_pkt_cnt, $w_sctp_pkt_cnt, $w_others_pkt_cnt, '$w_units_format')"; mysql_query($query, $db); print "$query<br><hr>\n"; } }else if(!strncmp($buffer, "pkt_sizes|", strlen("pkt_sizes|"))) { $array = explode('|', $buffer); $l_in_pkt_cnt_0_63 = $array[1]; $l_out_pkt_cnt_0_63 = $array[2]; $w_in_pkt_cnt_64_127 = $array[3]; $w_out_pkt_cnt_64_127 = $array[4]; $l_in_pkt_cnt_128_255 = $array[5]; $l_out_pkt_cnt_128_255 = $array[6]; $l_in_pkt_cnt_256_511 = $array[7]; $l_out_pkt_cnt_256_511 = $array[8]; $l_in_pkt_cnt_512_1023 = $array[9]; $l_out_pkt_cnt_512_1023 = $array[10]; $l_in_pkt_cnt_1024_above = $array[11]; $l_out_pkt_cnt_1024_above = $array[12]; $w_in_pkt_cnt_0_63 = $array[13]; $w_out_pkt_cnt_0_63 = $array[14]; $l_in_pkt_cnt_64_127 = $array[15]; $l_out_pkt_cnt_64_127 = $array[16]; $w_in_pkt_cnt_128_255 = $array[17]; $w_out_pkt_cnt_128_255 = $array[18]; $w_in_pkt_cnt_256_511 = $array[19]; $w_out_pkt_cnt_256_511 = $array[20]; $w_in_pkt_cnt_512_1023 = $array[21]; $w_out_pkt_cnt_512_1023 = $array[22]; $w_in_pkt_cnt_1024_above = $array[23]; $w_out_pkt_cnt_1024_above = $array[24]; $l_units_format = '-'; $e_units_format = '-'; if($l_in_pkt_cnt_0_63==0 && $l_out_pkt_cnt_0_63==0 && $w_in_pkt_cnt_0_63==0 && $w_out_pkt_cnt_0_63==0 && $l_in_pkt_cnt_64_127==0 && $l_out_pkt_cnt_64_127==0 && $w_in_pkt_cnt_64_127==0 && $w_out_pkt_cnt_64_127==0 && $l_in_pkt_cnt_128_255==0 && $l_out_pkt_cnt_128_255==0 && $w_in_pkt_cnt_128_255==0 && $w_out_pkt_cnt_128_255==0 && $l_in_pkt_cnt_256_511==0 && $l_out_pkt_cnt_256_511==0 && $w_in_pkt_cnt_256_511==0 && $w_out_pkt_cnt_256_511==0 && $l_in_pkt_cnt_512_1023==0 && $l_out_pkt_cnt_512_1023==0 && $w_in_pkt_cnt_512_1023==0 && $w_out_pkt_cnt_512_1023==0 && $l_in_pkt_cnt_1024_above==0 && $l_out_pkt_cnt_1024_above==0 && $w_in_pkt_cnt_1024_above==0 && $w_out_pkt_cnt_1024_above==0) { print "pkt_sizes| Complete zero entry, ignoring this data entry !\n"; } else { $query = "insert into stats_pkt_sizes ( timestamp, l_in_pkt_cnt_0_63, l_out_pkt_cnt_0_63, w_in_pkt_cnt_0_63, w_out_pkt_cnt_0_63, l_in_pkt_cnt_64_127, l_out_pkt_cnt_64_127, w_in_pkt_cnt_64_127, w_out_pkt_cnt_64_127, l_in_pkt_cnt_128_255, l_out_pkt_cnt_128_255, w_in_pkt_cnt_128_255, w_out_pkt_cnt_128_255, l_in_pkt_cnt_256_511, l_out_pkt_cnt_256_511, w_in_pkt_cnt_256_511, w_out_pkt_cnt_256_511, l_in_pkt_cnt_512_1023, l_out_pkt_cnt_512_1023, w_in_pkt_cnt_512_1023, w_out_pkt_cnt_512_1023, l_in_pkt_cnt_1024_above, l_out_pkt_cnt_1024_above, w_in_pkt_cnt_1024_above, w_out_pkt_cnt_1024_above, l_units_format, e_units_format)"; $query .= "values (now(), $l_in_pkt_cnt_0_63, $l_out_pkt_cnt_0_63, $w_in_pkt_cnt_0_63, $w_out_pkt_cnt_0_63, $l_in_pkt_cnt_64_127, $l_out_pkt_cnt_64_127, $w_in_pkt_cnt_64_127, $w_out_pkt_cnt_64_127, $l_in_pkt_cnt_128_255, $l_out_pkt_cnt_128_255, $w_in_pkt_cnt_128_255, $w_out_pkt_cnt_128_255, $l_in_pkt_cnt_256_511, $l_out_pkt_cnt_256_511, $w_in_pkt_cnt_256_511, $w_out_pkt_cnt_256_511, $l_in_pkt_cnt_512_1023, $l_out_pkt_cnt_512_1023, $w_in_pkt_cnt_512_1023, $w_out_pkt_cnt_512_1023, $l_in_pkt_cnt_1024_above, $l_out_pkt_cnt_1024_above, $w_in_pkt_cnt_1024_above, $w_out_pkt_cnt_1024_above, '$l_units_format', '$e_units_format')"; $result = mysql_query($query, $db); print "$query<br><hr>\n"; } }else if(!strncmp($buffer, "coal|", strlen("coal|"))) { $array = explode('|', $buffer); $lan_rx = $array[1]; $lan_tx = $array[2]; $wan_rx = $array[3]; $wan_tx = $array[4]; calculate_stats_pct($lan_rx, $lan_tx, $wan_rx, $wan_tx, $lan_stats_pct, $wan_stats_pct ); if($lan_stats_pct==0 && $wan_stats_pct==0 && $lan_rx==0 && $lan_tx==0 && $wan_rx==0 && $wan_tx==0) { print "coal| Complete zero entry, ignoring this data entry !\n"; } else { $query = "insert into stats_coalescing ( timestamp, lan_stats_pct, wan_stats_pct) values (now(), $lan_stats_pct, $wan_stats_pct)"; print "$query <br><hr>\n"; $result = mysql_query($query, $db); } }else if(!strncmp($buffer, "filter_dns|", strlen("filter_dns|"))) { $array = explode('|', $buffer); $lan_filter_dns_pkts = $array[1]; $wan_filter_dns_pkts = $array[2]; $lan_filter_dns_bytes_saved = $array[3]; $wan_filter_dns_bytes_saved = $array[4]; if($lan_filter_dns_pkts==0 && $wan_filter_dns_pkts==0 && $lan_filter_dns_bytes_saved==0 && $wan_filter_dns_bytes_saved==0) { print "filter_dns| Complete zero entry, ignoring this data entry !\n"; } else { $query = "insert into stats_filter_dns ( timestamp, lan_filter_dns_pkts, wan_filter_dns_pkts, lan_filter_dns_bytes_saved, wan_filter_dns_bytes_saved) values (now(), $lan_filter_dns_pkts, $wan_filter_dns_pkts, $lan_filter_dns_bytes_saved, $wan_filter_dns_bytes_saved)"; $result = mysql_query($query, $db); print "$query"; } } } fclose($file); ?> <file_sep><?php error_reporting(5); session_start(); session_unset(); session_destroy(); ?> <html><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <?php include('c/c_align.php'); ?> <link rel="shortcut icon" type="image/x-icon" href="i/favicon.ico"> <?php $color_light = "#8c9fff"; $color_lighter = "#8c9fff"; $color_dark = "#416182"; $language = "en"; print "<style>"; print "input.style00 {width:210px;height:18px;background-color:$color_lighter;color:white;border:0;height:22px;font-weight:bold;}"; print "select.style01 {width:210px;height:18px;background-color:$color_lighter;color:white;border:0px;height:19px;padding:2px;}"; print "select.style01 option {background-color:$color_lighter;color:white;border:0px;margin: 0px 0px;padding: 0px;}"; print "</style>"; ?> </head><body style="background-color:#B3C2FF;"> <center> <table border="0" align="center" width="600" bgcolor="white" cellpadding="5" cellspacing="5" > <tr><td align="center"><img src="i/logo.png" alt="" ></td></tr> <tr><td align="center" style="color:#111111;font-family:arial;font-size:16px;"><br>Admin Login<br> <br><br><form method="POST" action="c/c_login.php"> <table summary="" align="center" > <tr><td style="color:#111111;font-family:arial;font-size:14px;">Login: <input id="basic_font_style_14px_white" class="style00" type="text" name="username" ></td> <td width="10" style="color:#111111;font-family:arial;font-size:14px;"> </td> <td style="color:#111111;font-family:arial;font-size:14px;">Password: <input id="basic_font_style_14px_white" class="style00" type="password" name="password" ></td></tr> </table> <br><br> <input type="submit" style="border: 0px solid #000000; background-color:#000000;width:100px;height:24px;color:white;font-family:arial;font-size:12px;" name="login" value="Login" /> </form></td></tr></table> </center> <?php include('c/c_footer.php'); ?> </body></html><file_sep><?php error_reporting(5); system("php -f ./make_clean.php"); system('service trafficsqueezerd stop'); system('cp ./trafficsqueezerd /usr/sbin/.'); system('chmod 555 /usr/sbin/trafficsqueezerd'); system('cp ./etc/init.d/trafficsqueezerd /etc/init.d/.'); system('chmod 775 /etc/init.d/trafficsqueezerd'); system('update-rc.d trafficsqueezerd defaults 97 03'); system('service trafficsqueezerd start'); $home_dir = getcwd(); print "Installing TrafficSqueezer GUI in (/var/www/html) Apache default webroot folder ...\n"; ts_execute_squence( "cp -r html/* /var/www/html/. &", $home_dir, $home_dir); print "Done !\n"; print "Setting Appropriate Permissions in (/var/www/html) Apache default webroot folder ...\n"; ts_execute_squence( "chmod 777 /var/www/html/* -R &", $home_dir, $home_dir); print "Done !\n"; chdir($home_dir); exit(); function ts_execute_squence($task, $workdir, $homedir) { chdir($workdir); foreach(preg_split("/(\r?\n)/", $task) as $command) { system($command); } chdir($homedir); } function ts_setup($option, $task, $workdir, $homedir) { chdir($workdir); while(1) { print "\n$option "; $ret = fgets(STDIN); if($ret=="y\n") { ts_execute_squence($task, $workdir, $homedir); return $ret; } else if($ret=="n\n") { print "skipped ... !\n"; chdir($homedir); return $ret; } } } ?> <file_sep><?php error_reporting(5); $file = fopen("$argv[1]", "r"); if(!$file) { print "ERROR\n"; exit(); } while(!feof($file)) { $buffer = fgets($file, 4096); print "$buffer"; } fclose($file); ?><file_sep><?php include('c/c_check_login.php'); ?> <html><head><?php error_reporting(5); include("c/c_db_access.php"); include("c/c_get_db_basic_config.php"); include("c/c_get_db_dpi_config.php"); include("c/c_get_db_port_config.php"); include('c/c_bigpicture.php'); ?> </head><body style="font-family:arial;font-size:10px;"> <?php print "<div style=\"position:absolute;left:25;top:38;border:0;\"><img src=\"i/bigpicture_inline.png\" ></div>"; $counter = 0; $lan_left = 940; print "<div style=\"position:absolute;left:586;top:95;border:0;\">$port_wan_name</div>"; print "<div style=\"position:absolute;left:800;top:95;border:0;\">$port_lan_name</div>"; print "<iframe style=\"width:280px;border:0;height:300;left:0;top:120;position:absolute;\" scrolling=\"no\" src=\"bigpicture_inline_remote.php\"></iframe>"; print "<div style=\"position:absolute;left:360;top:160;border:0;\">Mode</div>"; if($mode=="MODE_NONE") $mode="None"; else if($mode=="MODE_ROUTER") $mode="Router"; else if($mode=="MODE_BRIDGE") $mode="Bridge"; else if($mode=="MODE_ROUTER_LOCAL") $mode="Router & Local-Device"; else if($mode=="MODE_LOCAL") $mode="Local-Device"; else if($mode=="MODE_SIMULATE") $mode="Simulation"; print "<div style=\"position:absolute;left:445;top:160;border:0;\">$mode</div>"; print "<div style=\"position: absolute;left:360;top:183;border:0;\">Compression</div>"; status_box(445, 183, "green"); print "<div style=\"position: absolute;left:360;top:206;border:0;\">Coalescing</div>"; status_box_var($coal_en, 445, 206); print "<div style=\"position:absolute;left:360;top:229;border:0;\">Templating</div>"; status_box(445, 229, "green"); print "<div style=\"position: absolute;left:360;top:252;border:0;\">DPI</div>"; if($dpi_enable=="1") { status_box(445, 252, "green"); } else { status_box(445, 252, "red"); } print "<div style=\"position: absolute;left:360;top:275;border:0;\">NAT</div>"; if($ip_forward_nat_enable=="1") { status_box(445, 275, "green"); } else { status_box(445, 275, "red"); } print "<div style=\"position: absolute;left:360;top:298;border:0;\">DNS Filter</div>"; if($dns_filter_enable=="1") { status_box(445, 298, "green"); } else { status_box(445, 298, "red"); } $dns_top = 272; if($buf!=NULL) { foreach (preg_split("/(\r?\n)/", $buf) as $line) { if ($line != NULL) { if($dns_filter_enable == "1") { print "<div style=\"position: absolute; left: 1148; top: $dns_top;border: 0;font-size: 11px;font-family: Arial;\">$line</div>"; } } $dns_top += 10; } } ?></body></html><file_sep>/* TRAFFICSQUEEZER provides dual licenses, designed to meet the usage and distribution requirements of different types of users. GPLv2 License: Copyright (C) (2006-2014) <NAME> (<EMAIL>) All Rights Reserved. TrafficSqueezer is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 2, and not any other version, as published by the Free Software Foundation. TrafficSqueezer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.You should have received a copy of the GNU General Public License along with TrafficSqueezer; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. BSD License (2-clause license): Copyright (2006-2014) <NAME>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY <NAME> ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KIRAN KANKIPATI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of <NAME>. * This license is applicable exclusive to the TrafficSqueezer components. TrafficSqueezer may bundle or include other third-party open-source components. Kindly refer these component README and COPYRIGHT/LICENSE documents, released by its respective authors and project/module owners. ** For more details about Third-party components, you can also kindly refer TrafficSqueezer project website About page. */ #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <ctype.h> #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include "../inc/udp.h" #include "../inc/core.h" extern int ts_udp_server_sock; extern BYTEx2 ts_udp_server_port; extern struct sockaddr_in ts_udp_server_servaddr; extern struct sockaddr_in ts_udp_server_cliaddr; BYTE udp_reply_buff[MAX_REPLY_BUFFER_SIZE]; //Reply to client UDP size_t udp_reply_buff_len; static int ts_execute_udp_command(BYTE *command_buff, size_t command_len); static int ts_start_udp_server() { ts_udp_server_sock = socket(AF_INET,SOCK_DGRAM,0); if(ts_udp_server_sock<=0) return FALSE; bzero(&ts_udp_server_servaddr, sizeof(ts_udp_server_servaddr)); ts_udp_server_servaddr.sin_family = AF_INET; ts_udp_server_servaddr.sin_addr.s_addr=htonl(INADDR_ANY); ts_udp_server_servaddr.sin_port=htons(ts_udp_server_port); bind( ts_udp_server_sock, (struct sockaddr *)&ts_udp_server_servaddr, sizeof(ts_udp_server_servaddr)); return TRUE; } void *udp_thread_start(void *a) { BYTE command_buff[2000]; ts_start_udp_server(); while(TRUE) { usleep(30); ts_receive_udp_command(command_buff); } } int ts_stop_udp_server() { if(ts_udp_server_sock>0) close(ts_udp_server_sock); return TRUE; } int ts_execute_system_command(BYTE *result_buff, size_t *result_len, BYTE *command, size_t command_len) { BYTE temp[2000]; strcpy(result_buff, ""); sprintf(temp, "%s 2> /dev/null > /dev/null &", command); system(temp); *result_len = strlen( result_buff); return TRUE; } /* ts_execute_system_command */ //Receive the command to be executed from the remote machine // execute the same in the local machine and send the status response SUCCESS/FAILURE // Flow: Fn. called from Server int ts_receive_udp_command(BYTE *command_buff) { //int status; int result = 0; size_t command_len; socklen_t len; bzero(command_buff, 2000); len = sizeof(ts_udp_server_cliaddr); result = recvfrom( ts_udp_server_sock, command_buff, 2000, 0,(struct sockaddr *)&ts_udp_server_cliaddr, &len); if(result>0) { command_len = result; if(!strncmp((char *)command_buff,"system ", 7)) { int execute_system_command_offset = 7; ts_execute_system_command(udp_reply_buff, &udp_reply_buff_len, (command_buff+execute_system_command_offset), (size_t)(command_len-execute_system_command_offset) ); sendto(ts_udp_server_sock, udp_reply_buff, udp_reply_buff_len, 0,(struct sockaddr *)&ts_udp_server_cliaddr, sizeof(ts_udp_server_cliaddr)); } } return TRUE; } <file_sep><?php include("/var/www/html/c/c_db_access.php"); $output="# Generated by Aquarium\n"; $query = "select nameserver_ip from nameserver"; $result=mysql_query($query, $db); if(mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $nameserver_ip = $row['nameserver_ip']; $output.="nameserver $nameserver_ip\n"; } } print "Saving file: /etc/resolv.conf\n$output\n"; file_put_contents("/etc/resolv.conf", $output); ?> <file_sep><?php include('c/c_check_login.php'); include("c/c_db_access.php"); include('c/c_g_var_set.php'); error_reporting(5); $query = "delete from kernel_jobs where 1=1"; mysql_query($query, $db); print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=engg_kernel_jobs.php\">"; ?><file_sep><?php include("/var/www/html/c/c_db_access.php"); $file = fopen("/etc/resolv.conf", "r") or exit("Unable to open file!"); while(!feof($file)) { $buffer = fgets($file, 4096); if(!strncmp($buffer, "nameserver ", strlen("nameserver "))) { $array = explode(' ', $buffer); $ip = trim($array[1]); $query = "insert into nameserver (nameserver_ip) values ('$ip')"; mysql_query($query, $db); } } fclose($file); ?> <file_sep><?php //Read the DB and push this job(config) into kernel via "io" /proc file $proc_io_file = "/proc/trafficsqueezer/io"; error_reporting(5); include("/var/www/html/c/c_db_access.php"); $query = "select id, kernel_job from kernel_jobs"; $result=mysql_query($query, $db); if(mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $kernel_job = $row['kernel_job']; $id = $row['id']; $command = "echo \"$kernel_job\" > $proc_io_file "; print "$command \n"; system($command); mysql_query("delete from kernel_jobs where id=$id", $db); } } mysql_close($db); <file_sep><html><?php include('c/c_body_bknd.php'); include("c/c_db_access.php"); error_reporting(5); session_start(); $_amount = $_POST['amount']; $_details = $_POST['details']; $_day=$_POST['day'];$_month=$_POST['month']; $_year=$_POST['year']; $_date = "$_year-$_month-$_day"; $query = "insert into purchase (purdate,amount,details) values ('$_date',$_amount,'$_details')"; //print $query; mysql_query($query, $db); mysql_close($db); print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=stock_purchase.php\">"; ?></body></html><file_sep><?php $page_title = "Help"; include('c/c_header.php'); ?> </head><?php include('c/c_body.php'); ?> <?php $contentfile="content_help.php"; include('c/c_main.php'); ?><file_sep><?php error_reporting(5); $dbHost = "localhost"; $dbUser = "root"; $dbPass = "<PASSWORD>"; $dbDatabase = "aquarium"; $db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database."); mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database."); generate_visible_hostname($db); generate_http_port($db); generate_cache_dir($db); generate_acl($db); generate_timeout($db); generate_wccp($db); generate_cache_tuning($db); generate_http_accel($db); function generate_cache_tuning($db) { print "\n# Cache Tuning:\n"; $query = "select wais_relay_host, wais_relay_port, request_header_max_size, request_body_max_size, reply_body_max_size, refresh_pattern, reference_age, quick_abort_min, quick_abort_max, quick_abort_pct, negative_ttl, positive_dns_ttl, negative_dns_ttl, range_offset_limit from squid_cache_tuning_cfg where id=1 "; $result = mysql_query($query, $db); $rowCheck = mysql_num_rows($result); if ($rowCheck > 0) { while ($row = mysql_fetch_array($result)) { if($row[wais_relay_host]!=NULL) print "wais_relay_host $row[wais_relay_host]\n"; if($row[wais_relay_port]!=NULL) print "wais_relay_port $row[wais_relay_port]\n"; if($row[request_header_max_size]!=NULL) print "request_header_max_size $row[request_header_max_size]\n"; if($row[request_body_max_size]!=NULL) print "request_body_max_size $row[request_body_max_size]\n"; if($row[reply_body_max_size]!=NULL) print "reply_body_max_size $row[reply_body_max_size]\n"; if($row[refresh_pattern]!=NULL) print "refresh_pattern $row[refresh_pattern]\n"; if($row[reference_age]!=NULL) print "reference_age $row[reference_age]\n"; if($row[quick_abort_min]!=NULL) print "quick_abort_min $row[quick_abort_min]\n"; if($row[quick_abort_max]!=NULL) print "quick_abort_max $row[quick_abort_max]\n"; if($row[quick_abort_pct]!=NULL) print "quick_abort_pct $row[quick_abort_pct]\n"; if($row[negative_ttl]!=NULL) print "negative_ttl $row[negative_ttl]\n"; if($row[positive_dns_ttl]!=NULL) print "positive_dns_ttl $row[positive_dns_ttl]\n"; if($row[negative_dns_ttl]!=NULL) print "negative_dns_ttl $row[negative_dns_ttl]\n"; if($row[range_offset_limit]!=NULL) print "range_offset_limit $row[range_offset_limit]\n"; } } print "#------------------------------------------------------\n"; } function generate_timeout($db) { print "\n# Timeouts:\n"; $query = "select connect_timeout, peer_connect_timeout, read_timeout, request_timeout, persistent_request_timeout, client_lifetime, half_closed_clients, pconn_timeout, ident_timeout, shutdown_lifetime from squid_timeout_cfg where id=1 "; $result = mysql_query($query, $db); $rowCheck = mysql_num_rows($result); if ($rowCheck > 0) { while ($row = mysql_fetch_array($result)) { if($row[connect_timeout]!=NULL) print "connect_timeout $row[connect_timeout]\n"; if($row[peer_connect_timeout]!=NULL) print "peer_connect_timeout $row[peer_connect_timeout]\n"; if($row[read_timeout]!=NULL) print "read_timeout $row[read_timeout]\n"; if($row[request_timeout]!=NULL) print "request_timeout $row[request_timeout]\n"; if($row[persistent_request_timeout]!=NULL) print "persistent_request_timeout $row[persistent_request_timeout]\n"; if($row[half_closed_clients]!=NULL) print "half_closed_clients $row[half_closed_clients]\n"; if($row[pconn_timeout]!=NULL) print "pconn_timeout $row[pconn_timeout]\n"; if($row[ident_timeout]!=NULL) print "ident_timeout $row[ident_timeout]\n"; if($row[shutdown_lifetime]!=NULL) print "shutdown_lifetime $row[shutdown_lifetime]\n"; } } print "#------------------------------------------------------\n"; } function generate_wccp($db) { print "\n# WCCP Settings:\n"; $query = "select wccp_router, wccp_version, wccp_incoming_address, wccp_outgoing_address, wccp2_router, wccp2_address, wccp2_forwarding_method, wccp2_assignment_method, wccp2_return_method, wccp2_service_standard from squid_wccp_cfg where id=1 "; $result = mysql_query($query, $db); $rowCheck = mysql_num_rows($result); if ($rowCheck > 0) { while ($row = mysql_fetch_array($result)) { if($row[wccp_router]!=NULL) print "wccp_router $row[wccp_router]\n"; if($row[wccp_version]!=NULL) print "wccp_version $row[wccp_version]\n"; if($row[wccp_incoming_address]!=NULL) print "wccp_incoming_address $row[wccp_incoming_address]\n"; if($row[wccp_outgoing_address]!=NULL) print "wccp_outgoing_address $row[wccp_outgoing_address]\n"; print "\n"; if($row[wccp2_address]!=NULL) print "wccp2_address $row[wccp2_address]\n"; if($row[wccp2_forwarding_method]!=NULL) print "wccp2_forwarding_method $row[wccp2_forwarding_method]\n"; if($row[wccp2_assignment_method]!=NULL) print "wccp2_assignment_method $row[wccp2_assignment_method]\n"; if($row[wccp2_return_method]!=NULL) print "wccp2_return_method $row[wccp2_return_method]\n"; if($row[wccp2_service_standard]!=NULL) print "wccp2_service_standard $row[wccp2_service_standard]\n"; } } print "#------------------------------------------------------\n"; } function generate_http_port($db) { print "\n"; $query = "select http_port, ts_squid_device_mode from squid_cfg where id=1 "; $result = mysql_query($query, $db); $rowCheck = mysql_num_rows($result); if ($rowCheck > 0) { while ($row = mysql_fetch_array($result)) { if($row[http_port]!=NULL) { print "http_port $row[http_port]"; if($row[ts_squid_device_mode]=="transparent") print " $row[ts_squid_device_mode]\n"; else print "\n"; } } } print "#------------------------------------------------------\n"; } function generate_visible_hostname($db) { print "\n"; $query = "select visible_hostname from squid_cfg where id=1 "; $result = mysql_query($query, $db); $rowCheck = mysql_num_rows($result); if ($rowCheck > 0) { while ($row = mysql_fetch_array($result)) { if($row[visible_hostname]!=NULL) { print "visible_hostname $row[visible_hostname]\n"; } } } print "#------------------------------------------------------\n"; } function generate_cache_dir($db) { print "\n# Basic Cache Directory settings:\n"; $query = "select cache_dir from squid_cfg where id=1 "; $result = mysql_query($query, $db); $rowCheck = mysql_num_rows($result); if ($rowCheck > 0) { while ($row = mysql_fetch_array($result)) { if($row[cache_dir]!=NULL) { print "cache_dir $row[cache_dir]\n"; } } } print "#------------------------------------------------------\n"; } /* generate_cache_dir */ function generate_acl($db) { print "\n# ACLs:\n"; $query = "select name, type from squid_acl_names_list "; $result = mysql_query($query, $db); $rowCheck = mysql_num_rows($result); if ($rowCheck > 0) { while ($row = mysql_fetch_array($result)) { if($row[type]!=NULL) { //Get ACL acls/rules list $query2 = "select value from squid_acl_list where name=\"$row[name]\" "; $result2 = mysql_query($query2, $db); $rowCheck2 = mysql_num_rows($result2); if ($rowCheck2 > 0) { while ($row2 = mysql_fetch_array($result2)) { print "acl $row[name] $row[type] $row2[value]\n"; } } //Get ACL permission $query3 = "select type, access from squid_access_list where acl_name_s=\"$row[name]\" "; $result3 = mysql_query($query3, $db); $rowCheck3 = mysql_num_rows($result3); if ($rowCheck3 > 0) { while ($row3 = mysql_fetch_array($result3)) { print "$row3[type] $row3[access] $row[name]\n"; } } print "\n"; } } } print "# Other Default regular Squid standard ACLs\n"; print "acl manager proto cache_object\n"; print "acl localhost src 127.0.0.1/32\n"; print "acl to_localhost dst 127.0.0.0/8 0.0.0.0/32\n"; print "\n"; print "# Example rule allowing access from your local networks.\n"; print "# Adapt to list your (internal) IP networks from where browsing\n"; print "# should be allowed\n"; print "acl localnet src 10.0.0.0/8 # RFC1918 possible internal network\n"; print "acl localnet src 172.16.0.0/12 # RFC1918 possible internal network\n"; print "acl localnet src 192.168.0.0/16 # RFC1918 possible internal network\n"; print "\n"; print "acl SSL_ports port 443\n"; print "acl Safe_ports port 80 # http\n"; print "acl Safe_ports port 21 # ftp\n"; print "acl Safe_ports port 443 # https\n"; print "acl Safe_ports port 70 # gopher\n"; print "acl Safe_ports port 210 # wais\n"; print "acl Safe_ports port 1025-65535 # unregistered ports\n"; print "acl Safe_ports port 280 # http-mgmt\n"; print "acl Safe_ports port 488 # gss-http\n"; print "acl Safe_ports port 591 # filemaker\n"; print "acl Safe_ports port 777 # multiling http\n"; print "acl CONNECT method CONNECT\n"; print "\n"; print "http_access allow all\n"; print "#------------------------------------------------------\n"; } function generate_http_accel($db) { print "\n# Squid HTTP Accelerator settings:\n"; $query = "select httpd_accel_host, httpd_accel_port, httpd_accel_with_proxy, httpd_accel_single_host, httpd_accel_uses_host_header from squid_cfg where id=1 "; $result = mysql_query($query, $db); $rowCheck = mysql_num_rows($result); if ($rowCheck > 0) { while ($row = mysql_fetch_array($result)) { $httpd_accel_host = $row[httpd_accel_host]; $httpd_accel_port = $row[httpd_accel_port]; $httpd_accel_with_proxy = $row[httpd_accel_with_proxy]; $httpd_accel_single_host = $row[httpd_accel_single_host]; $httpd_accel_uses_host_header = $row[httpd_accel_uses_host_header]; if($httpd_accel_host!=NULL) print "httpd_accel_host $httpd_accel_host\n"; if($httpd_accel_port!=NULL) print "httpd_accel_port $httpd_accel_port\n"; if($httpd_accel_with_proxy!=NULL) print "httpd_accel_with_proxy $httpd_accel_with_proxy\n"; if($httpd_accel_single_host!=NULL) print "httpd_accel_single_host $httpd_accel_single_host\n"; if($httpd_accel_uses_host_header!=NULL) print "httpd_accel_uses_host_header $httpd_accel_uses_host_header\n"; } } print "#------------------------------------------------------\n"; } /* generate_http_accel */ ?><file_sep><?php //Read the Static IP route (table) in DB and push into /proc files. error_reporting(5); $db = mysql_connect("localhost", "root", "welcome") or die ("Error connecting to database."); mysql_select_db("aquarium", $db) or die ("Couldn't select the database."); $query = "select type, network_id, subnet_msk, gateway, gateway_port from static_network_route_table where type=\"ipv4\" "; $result=mysql_query($query, $db); if(mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $network_id = $row['network_id']; $subnet_msk = $row['subnet_msk']; $gateway = $row['gateway']; $gateway_port = $row['gateway_port']; system("route add -net $network_id netmask $subnet_msk gw $gateway $gateway_port "); } } mysql_close($db); ?> <file_sep><?php //Read the TCP optimize settings in DB and push into /proc files. error_reporting(5); $db = mysql_connect("localhost", "root", "welcome") or die ("Error connecting to database."); mysql_select_db("aquarium", $db) or die ("Couldn't select the database."); $query = "select tcp_timestamps, tcp_sack, tcp_dsack, tcp_fack, tcp_window_scaling, ip_no_pmtu_disc, tcp_ecn, rmem_max, rmem_default, wmem_max, wmem_default, tcp_congestion_control from tcp_optimize_config where id=1 "; $result=mysql_query($query, $db); if(mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $tcp_timestamps = $row['tcp_timestamps']; $tcp_sack = $row['tcp_sack']; $tcp_dsack = $row['tcp_dsack']; $tcp_fack = $row['tcp_fack']; $tcp_window_scaling = $row['tcp_window_scaling']; $ip_no_pmtu_disc = $row['ip_no_pmtu_disc']; $tcp_ecn = $row['tcp_ecn']; $rmem_max = $row['rmem_max']; $rmem_default = $row['rmem_default']; $wmem_max = $row['wmem_max']; $wmem_default = $row['wmem_default']; $tcp_congestion_control = $row['tcp_congestion_control']; } } mysql_close($db); system("echo $tcp_timestamps > /proc/sys/net/ipv4/tcp_timestamps"); system("echo $tcp_sack > /proc/sys/net/ipv4/tcp_sack"); system("echo $tcp_dsack > /proc/sys/net/ipv4/tcp_dsack"); system("echo $tcp_fack > /proc/sys/net/ipv4/tcp_fack"); system("echo $tcp_window_scaling > /proc/sys/net/ipv4/tcp_window_scaling"); system("echo $ip_no_pmtu_disc > /proc/sys/net/ipv4/ip_no_pmtu_disc"); system("echo $tcp_ecn > /proc/sys/net/ipv4/tcp_ecn"); system("echo $tcp_congestion_control > /proc/sys/net/ipv4/tcp_congestion_control"); system("echo $rmem_max > /proc/sys/net/core/rmem_max"); system("echo $rmem_default > /proc/sys/net/core/rmem_default"); system("echo $wmem_max > /proc/sys/net/core/wmem_max"); system("echo $wmem_default > /proc/sys/net/core/wmem_default"); ?> <file_sep><?php include('c/c_check_login.php'); include("c/c_db_access.php"); include('c/c_g_var_set.php'); error_reporting(5); $r_ip_ntwrk_machine_en_before = $_POST['r_ip_ntwrk_machine_en_before']; $r_ip_ntwrk_machine_en = $_POST['r_ip_ntwrk_machine_en']; if($r_ip_ntwrk_machine_en==NULL)$r_ip_ntwrk_machine_en = 0; if($r_ip_ntwrk_machine_en_before != $r_ip_ntwrk_machine_en) { set_r_ip_ntwrk_machine_en($r_ip_ntwrk_machine_en, $query, $db); } $_operation = $_GET['operation']; if($_operation==NULL) $_operation = $_POST['operation']; $network_id = $_GET['network_id']; if($network_id==NULL) $network_id=$_POST['network_id']; $subnet_msk = $_GET['subnet_msk']; if($subnet_msk==NULL) $subnet_msk=$_POST['subnet_msk']; if($_operation=="remove_subnet") { set_del_r_ip_ntwrk_list_network_id($network_id, $query, $db); } else if($_operation=="add_subnet") { if (validate_ip_address($network_id)==false || validate_ip_address($subnet_msk)==false) { print "<span style=\"font-size:10px;color:white;\">Error: In-valid Address !<br></font</span>"; $page_delay = 4; } else { set_add_r_ip_ntwrk_list_network_id($network_id, $subnet_msk, $query, $db); } } $_ip_addr = $_GET['ip_addr']; if($_ip_addr==NULL) $_ip_addr = $_POST['ip_addr']; if($_operation=="remove_machine") { set_del_r_r_ip_machine_list($_ip_addr, $query, $db); } else if($_operation=="add_machine") { if(validate_ip_address($_ip_addr)==false) { print "<span style=\"font-size:10px;color:#333333;\">Error: In-valid IP Address !<br></span>"; $page_delay = 4; } else { set_add_r_ip_machine_list($_ip_addr, $query, $db); } } print "<meta HTTP-EQUIV=\"REFRESH\" content=\"".$page_delay."; url=remote.php\">"; function validate_ip_address($ip_addr) { //first of all the format of the ip address is matched if (preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $ip_addr)) { //now all the intger values are separated $parts = explode(".", $ip_addr); //now we need to check each part can range from 0-255 foreach ($parts as $ip_parts) { if (intval($ip_parts) > 255 || intval($ip_parts) < 0) return false; //if number is not within range of 0-255 } return true; } else return false; //if format of ip address doesn't matches } ?><file_sep>#!/bin/bash apt-get -y update apt-get -y install apache2 #remove default apache page. rm -f /var/www/html/index.html apt-get -y install php5 apt-get -y install libapache2-mod-php5 apt-get -y install php5-mcrypt apt-get -y install mysql-server apt-get -y install libapache2-mod-auth-mysql apt-get -y install php5-mysql #enable apache to load with php support. service apache2 restart apt-get -y install bridge-utils #mysqladmin -u root password '<PASSWORD>' mysql -uroot -pwelcome -e "create database ts;" mysql -uroot -pwelcome ts < ./db_scripts.sql #mysql -uroot -pwelcome -e "grant usage on *.* to root@localhost identified by 'welcome';" <file_sep><?php $page_title = "TrafficMaker - License"; include('c/c_header.php'); ?> </head><?php include('c/c_body.php'); ?> <?php $contentfile="content_license.php"; $help="nohelp"; include('c/c_main.php'); ?><file_sep><?php include("c/c_db_access.php"); include('c/c_g_var_set.php'); session_start(); error_reporting(5); //set wan port (to real port) set_port_wan_name($_GET['port'], $query, $db); //set lan port (to none) set_port_lan_name("none", $query, $db); //no remote ip subnet/machine settings since it is 100% testing. set_r_ip_ntwrk_machine_en(0, $query, $db); //no dns block. //execute_generic_command_set("l7filter dns block-domain disable"); print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=w_finish.php\">"; ?><file_sep><?php error_reporting(5); $source_type = $argv[1]; $domain_name = $argv[2]; $dest_ip = $argv[3]; $dbHost = "localhost"; $dbUser = "root"; $dbPass = "<PASSWORD>"; $dbDatabase = "aquarium"; $db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database."); mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database."); $query = "insert into dns_cache (timestamp, type, domain, dest) values (now(), \"$source_type\", \"$domain_name\", \"$dest_ip\")"; mysql_query($query, $db); mysql_close($db); ?> <file_sep><?php error_reporting(5); system('service trafficsqueezerd stop'); system('update-rc.d -f trafficsqueezerd remove'); system('rm -rf /etc/init.d/trafficsqueezerd'); system('rm -f /usr/sbin/trafficsqueezerd'); system("rm -rf ./*~"); system("rm -rf ./html/*~"); system("rm -rf ./html/c/*~"); system("rm -rf ./html/php/*~"); system("rm -rf ./etc/init.d/*~"); ?> <file_sep><?php include("c/c_db_access.php"); include('c/c_g_var_set.php'); include("c/c_get_db_basic_config.php"); session_start(); error_reporting(5); $squid = $_GET['squid']; set_port_wan_name($_GET['port'], $query, $db); //no remote ip subnet/machine settings since it is 100% testing. set_r_ip_ntwrk_machine_en(0, $query, $db); //now assuming both ports are set, if so check if bridging/routing is enabled, if so activate, else deactivate! if($mode=="MODE_ROUTER"||$mode=="MODE_ROUTER_LOCAL") activate_router($query, $db); else if($mode=="MODE_BRIDGE") activate_bridge($query, $db); print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=w_finish.php\">"; ?><file_sep><?php $page_title = "TrafficSqueezer - Contact"; include('c/c_header.php'); ?> </head><?php include('c/c_body.php'); ?> <?php $contentfile="content_contact.php"; $help="nohelp"; include('c/c_main.php'); ?><file_sep><?php //Read the TCP optimize settings in /proc config files and push this into DB error_reporting(5); $tcp_timestamps = `cat /proc/sys/net/ipv4/tcp_timestamps`; $tcp_sack = `cat /proc/sys/net/ipv4/tcp_sack`; $tcp_dsack = `cat /proc/sys/net/ipv4/tcp_dsack`; $tcp_fack = `cat /proc/sys/net/ipv4/tcp_fack`; $tcp_window_scaling = `cat /proc/sys/net/ipv4/tcp_window_scaling`; $ip_no_pmtu_disc = `cat /proc/sys/net/ipv4/ip_no_pmtu_disc`; $tcp_ecn = `cat /proc/sys/net/ipv4/tcp_ecn`; $tcp_congestion_control = `cat /proc/sys/net/ipv4/tcp_congestion_control`; $rmem_max = `cat /proc/sys/net/core/rmem_max`; $rmem_default = `cat /proc/sys/net/core/rmem_default`; $wmem_max = `cat /proc/sys/net/core/wmem_max`; $wmem_default = `cat /proc/sys/net/core/wmem_default`; $db = mysql_connect("localhost", "root", "welcome") or die ("Error connecting to database."); mysql_select_db("aquarium", $db) or die ("Couldn't select the database."); $query=""; $query = "update tcp_optimize_config set tcp_timestamps=$tcp_timestamps where id=1"; mysql_query($query, $db); $query = "update tcp_optimize_config set tcp_sack=$tcp_sack where id=1"; mysql_query($query, $db); $query = "update tcp_optimize_config set tcp_dsack=$tcp_dsack where id=1"; mysql_query($query, $db); $query = "update tcp_optimize_config set tcp_fack=$tcp_fack where id=1"; mysql_query($query, $db); $query = "update tcp_optimize_config set tcp_window_scaling=$tcp_window_scaling where id=1"; mysql_query($query, $db); $query = "update tcp_optimize_config set ip_no_pmtu_disc=$ip_no_pmtu_disc where id=1"; mysql_query($query, $db); $query = "update tcp_optimize_config set tcp_ecn=$tcp_ecn where id=1"; mysql_query($query, $db); $query = "update tcp_optimize_config set tcp_congestion_control=$tcp_congestion_control where id=1"; mysql_query($query, $db); $query = "update tcp_optimize_config set rmem_max=$rmem_max where id=1"; mysql_query($query, $db); $query = "update tcp_optimize_config set rmem_default=$rmem_default where id=1"; mysql_query($query, $db); $query = "update tcp_optimize_config set wmem_max=$wmem_max where id=1"; mysql_query($query, $db); $query = "update tcp_optimize_config set wmem_default=$wmem_default where id=1"; mysql_query($query, $db); mysql_close($db); ?> <file_sep><?php include('c/c_check_login.php'); include("c/c_db_access.php"); include('c/c_g_var_set.php'); error_reporting(5); session_start(); $username = $_SESSION['username']; $_stats_history = $_POST['stats_history']; $_stats_history_before = $_POST['stats_history_before']; if( ($_stats_history_before != $_stats_history) ) { $query = "update profile set stats_history=\"$_stats_history\" where username='$username'"; mysql_query($query, $db); } print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=stats_history.php\">"; ?> <file_sep>#!/bin/bash php -f ./make_install.php <file_sep>#!/bin/bash php -f ./make_clean.php <file_sep><?php $page_title = "You are done !"; include('c/c_header.php'); ?> </head><?php include('c/c_body.php'); ?> <?php $contentfile="content_w_finish.php"; $help="nohelp";include('c/c_main.php'); ?><file_sep>/* TRAFFICSQUEEZER provides dual licenses, designed to meet the usage and distribution requirements of different types of users. GPLv2 License: Copyright (C) (2006-2014) <NAME> (<EMAIL>) All Rights Reserved. TrafficSqueezer is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 2, and not any other version, as published by the Free Software Foundation. TrafficSqueezer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.You should have received a copy of the GNU General Public License along with TrafficSqueezer; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. BSD License (2-clause license): Copyright (2006-2014) <NAME>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY <NAME> ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KIRAN KANKIPATI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of <NAME>. * This license is applicable exclusive to the TrafficSqueezer components. TrafficSqueezer may bundle or include other third-party open-source components. Kindly refer these component README and COPYRIGHT/LICENSE documents, released by its respective authors and project/module owners. ** For more details about Third-party components, you can also kindly refer TrafficSqueezer project website About page. */ #ifndef __AQ_UDP__ #define __AQ_UDP__ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include "core.h" //5MB is the max reply buffer ! #define MAX_REPLY_BUFFER_SIZE 5242880 //For TS Auto-nego+DeviceGUI void *udp_thread_start(void *a); int ts_stop_udp_server(); int ts_receive_udp_command(); #endif<file_sep>/* TRAFFICSQUEEZER provides dual licenses, designed to meet the usage and distribution requirements of different types of users. GPLv2 License: Copyright (C) (2006-2014) <NAME> (<EMAIL>) All Rights Reserved. TrafficSqueezer is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 2, and not any other version, as published by the Free Software Foundation. TrafficSqueezer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.You should have received a copy of the GNU General Public License along with TrafficSqueezer; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. BSD License (2-clause license): Copyright (2006-2014) <NAME>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY <NAME> ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KIRAN KANKIPATI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of <NAME>. * This license is applicable exclusive to the TrafficSqueezer components. TrafficSqueezer may bundle or include other third-party open-source components. Kindly refer these component README and COPYRIGHT/LICENSE documents, released by its respective authors and project/module owners. ** For more details about Third-party components, you can also kindly refer TrafficSqueezer project website About page. */ #include <stdio.h> #include <string.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include <asm/types.h> #include <pthread.h> #include <fcntl.h> #include <errno.h> #include <syslog.h> #include <assert.h> #include "../inc/core.h" #include "../inc/udp.h" int ts_udp_server_sock = 0; BYTEx2 ts_udp_server_port = TS_UDP_SERVER_PORT; struct sockaddr_in ts_udp_server_servaddr; struct sockaddr_in ts_udp_server_cliaddr; pthread_t udp_thread; pthread_t generic_stats_thread; pthread_t generic_25_sec_thread; pthread_t generic_5_sec_thread; pthread_t generic_consolidate_thread; void *generic_stats_thread_start(void *a) { while(TRUE) { system("php -f /var/www/html/php/stats_load_stats.php"); sleep(30); // 30 seconds } } void *generic_consolidate_thread_start(void *a) { while(TRUE) { system("php -f /var/www/html/php/stats_consolidate_stats.php"); sleep(800); //once in 13 hours 20 mintues (almost 2 times a day a bit more than that) } } void *generic_25_sec_thread_start(void *a) { while(TRUE) { system("php -f /var/www/html/php/stats_dpi_load_dns_logs.php"); system("php -f /var/www/html/php/stats_dpi_load_pop_logs.php"); system("php -f /var/www/html/php/stats_dpi_load_http_access_logs.php"); system("php -f /var/www/html/php/db_execute_command_output.php &"); system("php -f /var/www/html/php/db_fill_port_list.php"); system("php -f /var/www/html/php/db_load_nameserver.php"); sleep(25); } } void *generic_5_sec_thread_start(void *a) { while(TRUE) { system("php -f /var/www/html/php/db_to_kernel_jobs_push.php"); system("php -f /var/www/html/php/db_execute_gui_jobs.php"); sleep(5); } } int exit_main() { ts_stop_udp_server(); remove("/var/ts_pid"); remove("/tmp/trafficsqueezerd.lock"); exit(1); } #define RUNNING_DIR "/tmp" #define LOCK_FILE "trafficsqueezerd.lock" #define LOG_FILE "/var/log/trafficsqueezerd.log" void signal_handler(int sig) { printf("\nAborted\n\n"); exit_main(); } void daemonize() { int i,lfp; char str[20]; if(getppid()==1) return; i=fork(); if (i<0) exit(1); if (i>0) exit(0); setsid(); for (i=getdtablesize();i>=0;--i) close(i); i=open("/dev/null",O_RDWR); dup(i); dup(i); umask(027); chdir(RUNNING_DIR); lfp=open(LOCK_FILE,O_RDWR|O_CREAT,0640); if (lfp<0) exit(1); if (lockf(lfp,F_TLOCK,0)<0) exit(0); sprintf(str,"%d\n",getpid()); write(lfp,str,strlen(str)); signal(SIGCHLD,SIG_IGN); signal(SIGTSTP,SIG_IGN); signal(SIGTTOU,SIG_IGN); signal(SIGTTIN,SIG_IGN); } int main( int argc, char ** argv ) { int __no_daemon = FALSE; int i=0; if(argc>=2) { for(i=1; i<argc; i++) { if(!strcmp(argv[i],"--no-daemon")) { __no_daemon = TRUE; printf("\nTrafficSqueezer Daemon executing in NON Daemon mode !\n\n"); } else if(!strcmp(argv[i],"--help")) { printf("\nTrafficSqueezer - Daemon optional command line parameters:\n"); printf(" --help (or) -? - Display this help and exit\n"); printf(" --no-daemon - foreground mode\n\n"); return TRUE; } } } if(__no_daemon==FALSE) { daemonize(); } ts_save_pid_file(); signal(SIGHUP,signal_handler); signal(SIGTERM,signal_handler); signal(SIGKILL,signal_handler); signal(SIGSTOP,signal_handler); signal(SIGINT,signal_handler); for(i=0;i<12;i++) { printf("Initial sleep: Sleeping 6 seconds [%d]!\n", i); sleep(6); } system("php -f /var/www/html/php/db_to_kernel_config_push.php"); system("php -f /var/www/html/php/db_to_file_tcp_optimize_config_push.php"); system("php -f /var/www/html/php/db_to_system_static_network_route_table_push.php"); system("php -f /var/www/html/php/db_to_system_forward_rule_iptables_push.php"); system("php -f /var/www/html/php/nameserver_load_db.php"); system("php -f /var/www/html/php/stats_consolidate_stats.php"); pthread_create(&udp_thread, NULL, udp_thread_start, NULL); pthread_create(&generic_stats_thread, NULL, generic_stats_thread_start, NULL); pthread_create(&generic_consolidate_thread, NULL, generic_consolidate_thread_start, NULL); pthread_create(&generic_25_sec_thread, NULL, generic_25_sec_thread_start, NULL); pthread_create(&generic_5_sec_thread, NULL, generic_5_sec_thread_start, NULL); pthread_join(udp_thread, NULL); return TRUE; } <file_sep><?php //Read the DB and execute the frequently used command, so that system status is syncd in DB error_reporting(5); include("/var/www/html/c/c_db_access.php"); function update_port($db, $port) { //get ip, subnet, mac and update in table $ip_addr = ` ifconfig $port | grep "inet " | sed 's/ / /g' | sed 's/ / /g' | sed 's/ / /g'|sed 's/ //g'|sed 's/netmask/,/g'|sed 's/inet//g' | sed 's/destination/,/g' | sed 's/broadcast/,/g' | cut -f1 -d,`; $subnet = ` ifconfig $port | grep "inet " | sed 's/ / /g' | sed 's/ / /g' | sed 's/ / /g'|sed 's/ //g'|sed 's/netmask/,/g'|sed 's/inet//g' | sed 's/destination/,/g' | sed 's/broadcast/,/g' | cut -f2 -d,`; $mac = `ifconfig $port | grep "ether " | sed 's/ / /g' | sed 's/ / /g' | sed 's/ / /g'|sed 's/ //g'|sed 's/ether//g'|sed 's/txqueuelen/,/g' | cut -f1 -d,`; $ether_type = `ifconfig $port | grep "ether " | sed 's/ / /g' | sed 's/ / /g' | sed 's/ / /g'|sed 's/ //g'|sed 's/ether//g'|sed 's/txqueuelen/,/g' | cut -f2 -d,`; $ip_addr = chop($ip_addr); $subnet = chop($subnet); $mac = chop($mac); $query = "update port_list set ip_addr=\"$ip_addr\" where name=\"$port\""; print "$query \n"; mysql_query($query, $db); $query = "update port_list set subnet_msk=\"$subnet\" where name=\"$port\""; print "$query \n"; mysql_query($query, $db); $query = "update port_list set mac=\"$mac\" where name=\"$port\""; print "$query \n"; mysql_query($query, $db); $found_in_db=true; $query2 = "select port_lan_name, port_wan_name from port_config"; $result2=mysql_query($query2, $db); if(mysql_num_rows($result2)>0) { while($row2 = mysql_fetch_array($result2)) { $port_lan_name = $row2['port_lan_name']; $port_wan_name = $row2['port_wan_name']; if($port_lan_name==$port) { $query3 = "update port_list set direction=\"LAN\" where name=\"$port\""; print "$query3 \n"; mysql_query($query3, $db); } else if($port_wan_name==$port) { $query3 = "update port_list set direction=\"WAN\" where name=\"$port\""; print "$query3 \n"; mysql_query($query3, $db); } else { $query3 = "update port_list set direction=\"None\" where name=\"$port\""; print "$query3 \n"; mysql_query($query3, $db); } } } } //$get_ports = `ifconfig | grep 'flags' | sed 's/ / /g' | sed 's/ / /g' | sed 's/ / /g'|sed 's/ //g' | cut -d ':' -f 1`; $get_ports = `cat /proc/net/dev | grep ":" | cut -d: -f1| sed 's/ / /g'| sed 's/ //g' | sed 's/ //g'`; $get_ports = chop($get_ports); $ports = explode("\n", $get_ports); foreach($ports as $port) { if($port==NULL || $port=="lo") continue; $found_in_db=false; //check if this port is there, if so then update its details, else populate in DB $query = "select name from port_list"; $result=mysql_query($query, $db); if(mysql_num_rows($result)>0) { while($row = mysql_fetch_array($result)) { $name = $row['name']; if($name==$port) { update_port($db, $port); } } } if($found_in_db==false) { $query = "insert into port_list (name) values (\"$port\")"; print "$query \n"; mysql_query($query, $db); update_port($db, $port); } } //delete any stray old entries which are no more in device $query = "select name from port_list"; $result=mysql_query($query, $db); if(mysql_num_rows($result)>0) { while($row = mysql_fetch_array($result)) { $name = $row['name']; $found=false; foreach($ports as $port) { if($port==NULL || $port=="lo") continue; if($name==$port) $found=true; } if($found==false) { $query3 = "delete from port_list where name=\"$name\""; print "$query3 \n"; mysql_query($query3, $db); } } } mysql_close($db); ?><file_sep><?php include("c/c_db_access.php"); include('c/c_g_var_set.php'); session_start(); error_reporting(5); $squid = $_GET['squid']; set_port_lan_name($_GET['port'], $query, $db); print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=w_wan_port.php\">"; ?><file_sep>#!/bin/bash #remove unwanted apt-get -y remove gnome-sudoku apt-get -y remove thunderbird apt-get -y remove gnome-mines apt-get -y remove aisleriot apt-get -y update apt-get -y install wireshark apt-get -y install bluefish apt-get -y install vim apt-get -y install kompare apt-get -y install kolourpaint apt-get -y install flashplugin-installer #kernel development apt-get -y install build-essential apt-get -y install kernel-package apt-get -y install libncurses5-dev apt-get -y install fakeroot apt-get -y install wget apt-get -y install bzip2 <file_sep><?php include('c/c_body_bknd.php'); include("c/c_db_access.php"); include('c/c_g_var_set.php'); error_reporting(5); $_port_direction = $_POST['port_direction']; $_port_name = $_POST['port_name']; set_port($_port_name, $_port_direction, $query, $db); print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=ports.php\">"; ?><file_sep><?php //Read the firewall (forward rule) iptables settings in DB and push into /proc files. error_reporting(5); $db = mysql_connect("localhost", "root", "welcome") or die ("Error connecting to database."); mysql_select_db("aquarium", $db) or die ("Couldn't select the database."); $query = "select protocol, port_type, port_no, rule_type from forward_rule "; $result=mysql_query($query, $db); if(mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $protocol = $row['protocol']; $port_type = $row['port_type']; $port_no = $row['port_no']; $rule_type = $row['rule_type']; if($port_type=="--both") { //for SPORT system("iptables -I FORWARD -p $protocol -s 0/0 -d 0/0 --source-port $port_no -j $rule_type "); //for DPORT system("iptables -I FORWARD -p $protocol -s 0/0 -d 0/0 --destination-port $port_no -j $rule_type "); } else { system("iptables -I FORWARD -p $protocol -s 0/0 -d 0/0 $port_type $port_no -j $rule_type "); } } } mysql_close($db); ?> <file_sep><?php //Read the DB and push this configuration into kernel via "io" /proc file $proc_io_file = "/proc/trafficsqueezer/io"; error_reporting(5); include("/var/www/html/c/c_db_access.php"); include('/var/www/html/c/c_g_var_set.php'); include("/var/www/html/c/c_get_db_port_config.php"); include("/var/www/html/c/c_get_db_basic_config.php"); include("/var/www/html/c/c_get_db_tcp_optimize_config.php"); set_port_lan_name($port_lan_name, $query, $db); set_port_wan_name($port_wan_name, $query, $db); set_mode($mode, $query, $db); if($mode=="MODE_ROUTER"||$mode=="MODE_ROUTER_LOCAL") activate_router($query, $db); else if($mode=="MODE_BRIDGE") activate_bridge($query, $db); set_r_ip_ntwrk_machine_en($r_ip_ntwrk_machine_en, $query, $db); $query = "select type, network_id, subnet_msk from remote_subnet "; $result=mysql_query($query, $db); if(mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $network_id = $row['network_id']; $subnet_msk = $row['subnet_msk']; set_add_r_ip_ntwrk_list_network_id($network_id, $subnet_msk, $query, $db); } } $query = "select type, ip_addr from remote_ip_machine"; $result=mysql_query($query, $db); if(mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $ip_addr = $row['ip_addr']; set_add_r_ip_machine_list($ip_addr, $query, $db); } } set_tcp_timestamps($tcp_timestamps, $query, $db); set_tcp_sack($tcp_sack, $query, $db); set_tcp_dsack($tcp_dsack, $query, $db); set_tcp_fack($tcp_fack, $query, $db); set_tcp_autocorking($tcp_autocorking, $query, $db); set_tcp_window_scaling($tcp_window_scaling, $query, $db); set_ip_no_pmtu_disc($ip_no_pmtu_disc, $query, $db); set_tcp_congestion_control($tcp_congestion_control, $query, $db); set_tcp_ecn($tcp_ecn, $query, $db); set_rmem_max($rmem_max, $query, $db); set_rmem_default($rmem_default, $query, $db); set_wmem_max($wmem_max, $query, $db); set_wmem_default($wmem_default, $query, $db); ?><file_sep>CREATE TABLE profile ( id int(10) unsigned NOT NULL AUTO_INCREMENT, profile varchar(200) NOT NULL DEFAULT 'NULL', username varchar(30) NOT NULL DEFAULT 'NULL', password varchar(30) NOT NULL DEFAULT 'NULL', firstname varchar(40) NOT NULL DEFAULT '', lastname varchar(40) NOT NULL DEFAULT '', db varchar(30) NOT NULL DEFAULT 'NULL', language varchar(4) NOT NULL DEFAULT 'en', color_id int(10) unsigned NOT NULL DEFAULT 1, stats_history int(10) unsigned NOT NULL DEFAULT 60, PRIMARY KEY (id) ); insert into profile (id, username, password) values (1, "root","<PASSWORD>"); CREATE TABLE color ( id int(10) unsigned NOT NULL AUTO_INCREMENT, box_color varchar(10) NOT NULL DEFAULT '', box_color_hover varchar(10) NOT NULL DEFAULT '', background_color varchar(10) NOT NULL DEFAULT '', name varchar(10) NOT NULL DEFAULT '', PRIMARY KEY (id) ); insert into color (id, box_color, box_color_hover, background_color, name) values (1, "#FFD800","#F1CC00", "#F1F1F1", "Yellow"); insert into color (id, box_color, box_color_hover, background_color, name) values (2, "#CECE0E","#C0C00D", "#F1F1F1", "Green"); insert into color (id, box_color, box_color_hover, background_color, name) values (3, "#FF836A","#FF755D", "#F1F1F1", "Brick Red"); insert into color (id, box_color, box_color_hover, background_color, name) values (4, "#85C8FF","#55B4FF", "#F1F1F1", "Blue"); # #mode: MODE_NONE, MODE_ROUTER, MODE_BRIDGE, MODE_LOCAL, MODE_ROUTER_LOCAL, MODE_SIMULATE # CREATE TABLE basic_config ( id int(10) unsigned NOT NULL AUTO_INCREMENT, mode varchar(35) NOT NULL DEFAULT 'MODE_NONE', coal_en int(4) unsigned NOT NULL DEFAULT '0', coalescing_protocol_dns_enable int(4) unsigned NOT NULL DEFAULT '0', encrypt_enabled int(4) unsigned NOT NULL DEFAULT '0', qos_enabled int(4) unsigned NOT NULL DEFAULT '0', qos_wan_bandwidth int(4) unsigned NOT NULL DEFAULT '0', qos_p0_bandwidth int(4) unsigned NOT NULL DEFAULT '0', qos_p1_bandwidth int(4) unsigned NOT NULL DEFAULT '0', qos_p2_bandwidth int(4) unsigned NOT NULL DEFAULT '0', qos_p3_bandwidth int(4) unsigned NOT NULL DEFAULT '0', qos_p4_bandwidth int(4) unsigned NOT NULL DEFAULT '0', bridge_ip_addr varchar(20) NOT NULL DEFAULT '192.168.127.12', bridge_subnet_msk varchar(20) NOT NULL DEFAULT '255.0.0.0', br_forward_enable int(4) unsigned NOT NULL DEFAULT '0', ip_forward_enable int(4) unsigned NOT NULL DEFAULT '0', ip_forward_nat_enable int(4) unsigned NOT NULL DEFAULT '0', r_ip_ntwrk_machine_en int(4) unsigned NOT NULL DEFAULT '0', host_name varchar(20) NOT NULL DEFAULT 'aquarium', filter_dns_enable int(4) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (id) ); insert into basic_config (id,host_name) values (1,"aquarium"); # #/proc/sys/net/ipv4 tcp optimization parameters # # tcp_congestion_control: cubic, reno, hybla, bic, westwood, vegas, htcp, scalable, yeah, illinois # CREATE TABLE tcp_optimize_config ( id int(10) unsigned NOT NULL AUTO_INCREMENT, tcp_timestamps int(12) unsigned NOT NULL DEFAULT '0', tcp_sack int(12) unsigned NOT NULL DEFAULT '0', tcp_dsack int(12) unsigned NOT NULL DEFAULT '0', tcp_fack int(12) unsigned NOT NULL DEFAULT '0', tcp_autocorking int(12) unsigned NOT NULL DEFAULT '1', tcp_window_scaling int(4) unsigned NOT NULL DEFAULT '0', ip_no_pmtu_disc int(4) unsigned NOT NULL DEFAULT '1', tcp_ecn int(4) unsigned NOT NULL DEFAULT '0', rmem_max int(12) unsigned NOT NULL DEFAULT '131071', rmem_default int(12) unsigned NOT NULL DEFAULT '112640', wmem_max int(12) unsigned NOT NULL DEFAULT '131071', wmem_default int(12) unsigned NOT NULL DEFAULT '112640', tcp_congestion_control varchar(12) NOT NULL DEFAULT 'cubic', PRIMARY KEY (id) ); insert into tcp_optimize_config (id) values (1); # # Filter-DNS Domain list # CREATE TABLE `filter_dns_list` ( `id` INT(4) UNSIGNED NOT NULL AUTO_INCREMENT, `domain` VARCHAR(40) NOT NULL DEFAULT '', `name` VARCHAR(40) NOT NULL DEFAULT '', PRIMARY KEY (`id`), UNIQUE INDEX `domain` (`domain`) ); #nameserver list: /etc/resolv.conf CREATE TABLE nameserver ( id int(10) unsigned NOT NULL AUTO_INCREMENT, nameserver_ip varchar(30) NOT NULL DEFAULT '', PRIMARY KEY (id), UNIQUE INDEX `nameserver_ip` (`nameserver_ip`) ); # # DPI Settings # CREATE TABLE dpi_config ( id int(4) unsigned NOT NULL AUTO_INCREMENT, dpi_enable int(4) unsigned NOT NULL DEFAULT '0', dpi_dns_request_enable int(4) unsigned NOT NULL DEFAULT '0', dpi_http_access_enable int(4) unsigned NOT NULL DEFAULT '0', dpi_pop_enable int(4) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (id) ); insert into dpi_config (id) values (1); # #port name: none_eth0, em1, .... # CREATE TABLE port_config ( id int(10) unsigned NOT NULL AUTO_INCREMENT, port_lan_name varchar(8) NOT NULL DEFAULT 'none', port_wan_name varchar(8) NOT NULL DEFAULT 'none', port_lan_ip_addr varchar(20) NOT NULL DEFAULT '0.0.0.0', port_wan_ip_addr varchar(20) NOT NULL DEFAULT '0.0.0.0', port_lan_mac varchar(26) NOT NULL DEFAULT '', port_wan_mac varchar(26) NOT NULL DEFAULT '', port_bridge_ip_addr varchar(20) NOT NULL DEFAULT '0.0.0.0', port_bridge_subnet_msk varchar(20) NOT NULL DEFAULT '0.0.0.0', PRIMARY KEY (id) ); insert into port_config (id) values (1); # # ifconfig -a -> store this updated info in this table. Delete any unknown/removed ports # direction -> lan/wan CREATE TABLE port_list ( name varchar(8) NOT NULL DEFAULT '', ip_addr varchar(20) NOT NULL DEFAULT '0.0.0.0', subnet_msk varchar(20) NOT NULL DEFAULT '0.0.0.0', mac varchar(26) NOT NULL DEFAULT '', direction varchar(26) NOT NULL DEFAULT '', UNIQUE INDEX `name` (`name`) ); # # type: ipv4, ipv6 # CREATE TABLE remote_subnet ( id int(10) unsigned NOT NULL AUTO_INCREMENT, type varchar(20) NOT NULL default 'ipv4', network_id varchar(20) NOT NULL DEFAULT '0.0.0.0', subnet_msk varchar(20) NOT NULL DEFAULT '0.0.0.0', PRIMARY KEY (id) ); # # type: ipv4, ipv6 # CREATE TABLE remote_ip_machine ( id int(10) unsigned NOT NULL AUTO_INCREMENT, type varchar(20) NOT NULL default 'ipv4', ip_addr varchar(20) NOT NULL DEFAULT '0.0.0.0', PRIMARY KEY (id) ); # # gateway_port: such as eth1, eth2, ... # CREATE TABLE static_network_route_table ( id int(10) unsigned NOT NULL AUTO_INCREMENT, type varchar(20) NOT NULL default 'ipv4', network_id varchar(20) NOT NULL DEFAULT '0.0.0.0', subnet_msk varchar(20) NOT NULL DEFAULT '0.0.0.0', gateway varchar(20) NOT NULL DEFAULT '0.0.0.0', gateway_port varchar(20) NOT NULL DEFAULT '', PRIMARY KEY (id) ); # forward_rule (iptable rules or firewall rules) # port_type: such as --destination-port, --source-port, --both ... # rule_type: ACCEPT, DROP # protocol: tcp, udp # CREATE TABLE forward_rule ( id int(10) unsigned NOT NULL AUTO_INCREMENT, protocol varchar(20) NOT NULL default 'tcp', port_type varchar(26) NOT NULL DEFAULT '--both', port_no int(8) unsigned NOT NULL DEFAULT '0', rule_type varchar(10) NOT NULL DEFAULT 'DROP', PRIMARY KEY (id) ); # qos_rule # port_type: such as --destination-port, --source-port, --both ... # priority: 0, 1, 2, 3, 4 # CREATE TABLE qos_rule ( id int(10) unsigned NOT NULL AUTO_INCREMENT, protocol varchar(20) NOT NULL default 'tcp', port_type varchar(26) NOT NULL DEFAULT '--both', port_no int(8) unsigned NOT NULL DEFAULT '0', priority int(8) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (id) ); #load in GB CREATE TABLE stats_mem ( id int(32) unsigned NOT NULL auto_increment, type int(10) unsigned NOT NULL default '0', timestamp datetime default NULL, total decimal(20,2) unsigned default '0.00', used decimal(20,2) unsigned default '0.00', PRIMARY KEY (id) ); CREATE TABLE stats_bandwidth ( id int(32) unsigned NOT NULL auto_increment, type int(10) unsigned NOT NULL default '0', timestamp datetime default NULL, lan_bytes_per_sec decimal(20,3) unsigned default '0.000', wan_bytes_per_sec decimal(20,3) unsigned default '0.000', PRIMARY KEY (id) ); CREATE TABLE stats_filter_dns ( id int(32) unsigned NOT NULL auto_increment, type int(10) unsigned NOT NULL default '0', timestamp datetime default NULL, lan_filter_dns_pkts int(8) unsigned NOT NULL DEFAULT '0', wan_filter_dns_pkts int(8) unsigned NOT NULL DEFAULT '0', lan_filter_dns_bytes_saved int(8) unsigned NOT NULL DEFAULT '0', wan_filter_dns_bytes_saved int(8) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (id) ); CREATE TABLE stats_overall ( id int(32) unsigned NOT NULL auto_increment, type int(10) unsigned NOT NULL default '0', timestamp datetime default NULL, lan_stats_pct int(20) default '0', wan_stats_pct int(20) default '0', lan_rx int(20) unsigned default '0', lan_tx int(20) unsigned default '0', lan_bytes_saved int(20) unsigned default '0', wan_rx int(20) unsigned default '0', wan_tx int(20) unsigned default '0', wan_bytes_saved int(20) unsigned default '0', PRIMARY KEY (id) ); CREATE TABLE stats_coalescing ( id int(32) unsigned NOT NULL auto_increment, type int(10) unsigned NOT NULL default '0', timestamp datetime default NULL, lan_stats_pct int(20) default '0', wan_stats_pct int(20) default '0', PRIMARY KEY (id) ); CREATE TABLE stats_ip_proto ( id int(32) unsigned NOT NULL auto_increment, type int(10) unsigned NOT NULL default '0', timestamp datetime default NULL, l_tcp_pkt_cnt decimal(10,3) unsigned default '0.000', l_udp_pkt_cnt decimal(10,3) unsigned default '0.000', l_icmp_pkt_cnt decimal(10,3) unsigned default '0.000', l_sctp_pkt_cnt decimal(10,3) unsigned default '0.000', l_others_pkt_cnt decimal(10,3) unsigned default '0.000', l_units_format varchar(6) default '-', w_tcp_pkt_cnt decimal(10,3) unsigned default '0.000', w_udp_pkt_cnt decimal(10,3) unsigned default '0.000', w_icmp_pkt_cnt decimal(10,3) unsigned default '0.000', w_sctp_pkt_cnt decimal(10,3) unsigned default '0.000', w_others_pkt_cnt decimal(10,3) unsigned default '0.000', w_units_format varchar(6) default '-', PRIMARY KEY (id) ); CREATE TABLE stats_pkt_sizes ( id int(32) unsigned NOT NULL auto_increment, type int(10) unsigned NOT NULL default '0', timestamp datetime default NULL, l_in_pkt_cnt_0_63 decimal(10,3) unsigned default '0.000', l_out_pkt_cnt_0_63 decimal(10,3) unsigned default '0.000', w_in_pkt_cnt_0_63 decimal(10,3) unsigned default '0.000', w_out_pkt_cnt_0_63 decimal(10,3) unsigned default '0.000', l_in_pkt_cnt_64_127 decimal(10,3) unsigned default '0.000', l_out_pkt_cnt_64_127 decimal(10,3) unsigned default '0.000', w_in_pkt_cnt_64_127 decimal(10,3) unsigned default '0.000', w_out_pkt_cnt_64_127 decimal(10,3) unsigned default '0.000', l_in_pkt_cnt_128_255 decimal(10,3) unsigned default '0.000', l_out_pkt_cnt_128_255 decimal(10,3) unsigned default '0.000', w_in_pkt_cnt_128_255 decimal(10,3) unsigned default '0.000', w_out_pkt_cnt_128_255 decimal(10,3) unsigned default '0.000', l_in_pkt_cnt_256_511 decimal(10,3) unsigned default '0.000', l_out_pkt_cnt_256_511 decimal(10,3) unsigned default '0.000', w_in_pkt_cnt_256_511 decimal(10,3) unsigned default '0.000', w_out_pkt_cnt_256_511 decimal(10,3) unsigned default '0.000', l_in_pkt_cnt_512_1023 decimal(10,3) unsigned default '0.000', l_out_pkt_cnt_512_1023 decimal(10,3) unsigned default '0.000', w_in_pkt_cnt_512_1023 decimal(10,3) unsigned default '0.000', w_out_pkt_cnt_512_1023 decimal(10,3) unsigned default '0.000', l_in_pkt_cnt_1024_above decimal(10,3) unsigned default '0.000', l_out_pkt_cnt_1024_above decimal(10,3) unsigned default '0.000', w_in_pkt_cnt_1024_above decimal(10,3) unsigned default '0.000', w_out_pkt_cnt_1024_above decimal(10,3) unsigned default '0.000', l_units_format varchar(6) default '-', e_units_format varchar(6) default '-', PRIMARY KEY (id) ); #DPI Logs CREATE TABLE `dpi_http_access_log` ( `id` INT(32) UNSIGNED NOT NULL AUTO_INCREMENT, `jiffies` INT(20) UNSIGNED ZEROFILL NULL DEFAULT NULL, `timestamp` DATETIME NULL DEFAULT NULL, `request_type` CHAR(1) NULL DEFAULT NULL COMMENT '//GET = G/POST = P', `src_ip` VARCHAR(20) NULL DEFAULT NULL COMMENT '//ASCII IP Address form', `dst_ip` VARCHAR(20) NULL DEFAULT NULL COMMENT '//ASCII IP Address form', `domain` VARCHAR(40) NULL DEFAULT NULL COMMENT '//www.abc.com (Host: )', `content` VARCHAR(90) NULL DEFAULT NULL COMMENT '//download.html in (http://www.abc.com/download.html) (or) URL without domain', `browser` VARCHAR(20) NULL DEFAULT NULL COMMENT '//firefox, ie, chrome', PRIMARY KEY (`id`), UNIQUE INDEX `jiffies` (`jiffies`, `domain`, `content`) ); CREATE TABLE `dpi_dns_request_log` ( `id` INT(32) UNSIGNED NOT NULL AUTO_INCREMENT, `jiffies` INT(20) UNSIGNED ZEROFILL NOT NULL, `timestamp` DATETIME NULL DEFAULT NULL, `request_type` CHAR(1) NULL DEFAULT NULL COMMENT '//GET = G/POST = P', `src_ip` VARCHAR(20) NULL DEFAULT NULL COMMENT '//ASCII IP Address form', `dst_ip` VARCHAR(20) NULL DEFAULT NULL COMMENT '//ASCII IP Address form', `domain` VARCHAR(40) NULL DEFAULT NULL COMMENT '//www.abc.com (Host: )', PRIMARY KEY (`id`), UNIQUE INDEX `jiffies` (`jiffies`, `domain`) ); CREATE TABLE `dpi_pop_log` ( `id` INT(32) UNSIGNED NOT NULL AUTO_INCREMENT, `jiffies` INT(20) UNSIGNED ZEROFILL NOT NULL, `timestamp` DATETIME NULL DEFAULT NULL, `src_ip` VARCHAR(20) NULL DEFAULT NULL COMMENT '//ASCII IP Address form', `dst_ip` VARCHAR(20) NULL DEFAULT NULL COMMENT '//ASCII IP Address form', `email_from` VARCHAR(20) NULL DEFAULT NULL COMMENT '//email from', `email_to` VARCHAR(20) NULL DEFAULT NULL COMMENT '//email to', `email_cc` VARCHAR(20) NULL DEFAULT NULL COMMENT '//email cc', `email_bcc` VARCHAR(20) NULL DEFAULT NULL COMMENT '//email bcc', `subject` VARCHAR(40) NULL DEFAULT NULL COMMENT '//subject', PRIMARY KEY (`id`), UNIQUE INDEX `jiffies` (`jiffies`, `email_from`, `email_to`, `subject`) ); CREATE TABLE `dpi_user_alias` ( `id` int(20) unsigned NOT NULL AUTO_INCREMENT, `cust_id` varchar(20) NOT NULL, `ip` varchar(20) NOT NULL, `mac` varchar(22) NOT NULL, `alias_user_name` varchar(40) NOT NULL, PRIMARY KEY (`id`) ); CREATE TABLE kernel_jobs ( id int(10) unsigned NOT NULL AUTO_INCREMENT, kernel_job varchar(200) NOT NULL DEFAULT 'NULL', PRIMARY KEY (id) ); CREATE TABLE gui_jobs ( id int(10) unsigned NOT NULL AUTO_INCREMENT, job varchar(500) NOT NULL DEFAULT 'NULL', job_result varchar(6000) NOT NULL DEFAULT 'NULL', job_pending int(3) unsigned default '1', PRIMARY KEY (id) ); CREATE TABLE command_output ( id int(10) unsigned NOT NULL, command varchar(500) NOT NULL DEFAULT 'NULL', output varchar(12000) NOT NULL DEFAULT 'NULL', PRIMARY KEY (id) ); insert into command_output (id, command) values (1, "cat /proc/cpuinfo | grep \"processor\\|vendor_id\\|model\\ name\\|cpu\\ M\\|cache\\ size\" | sed 's/\\t//g' | sed 's/: /:/g' | cut -f 2 -d \":\" "); insert into command_output (id, command) values (2, "ps -aef"); insert into command_output (id, command) values (3, "ifconfig -a"); #insert into command_output (id, command) values (4, "netstat -t | grep -E '^tcp|^udp' | sed 's/ / /g' | sed 's/ / /g'| sed 's/ / /g'| sed 's/ /,/g' | cut -f 1,4,5 -d ',' "); insert into command_output (id, command) values (5, "netstat -l | grep -E '^tcp|^udp' | sed 's/ / /g' | sed 's/ / /g'| sed 's/ / /g'| sed 's/ /,/g' | sed 's/:://g' | sed 's/:/,/g' | cut -f 1,4,5 -d ',' | sed 's/\\[\\]/\\[::\\]/g' "); insert into command_output (id, command) values (6, "arp | sed 's/ [ \\t ]*/,/g' | awk 'FNR>1'"); insert into command_output (id, command) values (7, "chkconfig --list | sed 's/\t/,/g' | sed 's/ //g' | sed 's/ //g' | sed 's/ //g' | sed 's/ //g' | sed 's/:off/:x/g' | sed 's/:on/:o/g' | sed 's/0://g' | sed 's/1://g' | sed 's/2://g' | sed 's/3://g' | sed 's/4://g' | sed 's/5://g' | sed 's/6://g' "); insert into command_output (id, command) values (8, "lsmod | cut -f1 -d' ' "); insert into command_output (id, command) values (9, "who -a"); insert into command_output (id, command) values (10, "iptables -L"); insert into command_output (id, command) values (11, "lspci"); insert into command_output (id, command) values (12, "cat /etc/squid/squid.conf"); insert into command_output (id, command) values (13, "route"); insert into command_output (id, command) values (14, "cat /boot/grub2/grub.cfg"); insert into command_output (id, command) values (15, "brctl show"); <file_sep><?php //Execute "root" context GUI jobs. error_reporting(5); include("/var/www/html/c/c_db_access.php"); $query = "select id, job from gui_jobs"; $result=mysql_query($query, $db); if(mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $job = $row['job']; $id = $row['id']; $output = `$job`; mysql_query("delete from gui_jobs where id=$id", $db); } } mysql_close($db);<file_sep>/* TRAFFICSQUEEZER provides dual licenses, designed to meet the usage and distribution requirements of different types of users. GPLv2 License: Copyright (C) (2006-2014) <NAME> (<EMAIL>) All Rights Reserved. TrafficSqueezer is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 2, and not any other version, as published by the Free Software Foundation. TrafficSqueezer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.You should have received a copy of the GNU General Public License along with TrafficSqueezer; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. BSD License (2-clause license): Copyright (2006-2014) <NAME>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY <NAME> ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL KIRAN KANKIPATI OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of <NAME>. * This license is applicable exclusive to the TrafficSqueezer components. TrafficSqueezer may bundle or include other third-party open-source components. Kindly refer these component README and COPYRIGHT/LICENSE documents, released by its respective authors and project/module owners. ** For more details about Third-party components, you can also kindly refer TrafficSqueezer project website About page. */ #include <sys/utsname.h> #include "../inc/core.h" #include "../inc/udp.h" int ts_save_pid_file() { char buff[300]; remove("/var/ts_pid"); sprintf(buff, "echo %d > /var/ts_pid", getpid()); system(buff); return TRUE; } int check_ts_process_active() { FILE *fp; char buff[300]; if(fp = fopen("/var/ts_pid", "r")) { while(fgets((char *)buff, 200, fp)) { int process_id = atoi(buff); BYTE buff2[100]; sprintf(buff2, "/proc/%d", process_id); if(dir_exists(buff2)==TRUE) { fclose(fp); return TRUE; } else //PID file exists but not the /proc dir, seems it is a bogus or stray file, so delete it ! { fclose(fp); system("rm -rf /var/ts_pid 2>/dev/null > /dev/null"); return FALSE; } } //PID file exists but not the /proc dir, seems it is a bogus or stray file, so delete it ! fclose(fp); system("rm -rf /var/ts_pid 2>/dev/null > /dev/null"); return FALSE; } return FALSE; } /* check_ts_process_active */ //Check if file exists return 0/1 int file_exists(const char *filename) { FILE *fp; if(fp = fopen(filename, "r")) { fclose(fp); return TRUE; } return FALSE; } /* file_exists */ //Check if dir exists return 0/1 int dir_exists(const char *dirname) { struct stat st; if(stat(dirname,&st) == 0) { return TRUE; } return FALSE; } /* dir_exists */ <file_sep><?php $file=$_GET['file']; $page_title = "Proc File $file"; include('c/c_header.php'); ?> </head><?php include('c/c_body.php'); ?> <?php $contentfile="content_engg_tsproc.php"; $help="nohelp";include('c/c_main.php'); ?><file_sep><?php include('c/c_check_login.php'); include("c/c_db_access.php"); include('c/c_g_var_set.php'); error_reporting(5); $_bridge_ip_addr_before = $_POST['bridge_ip_addr_before']; $_bridge_ip_addr = $_POST['bridge_ip_addr']; $_bridge_subnet_msk_before = $_POST['bridge_subnet_msk_before']; $_bridge_subnet_msk = $_POST['bridge_subnet_msk']; if( ($_bridge_ip_addr_before != $_bridge_ip_addr) || ($_bridge_subnet_msk_before != $_bridge_subnet_msk) ) { $query = "update basic_config set bridge_ip_addr=\"$_bridge_ip_addr\", bridge_subnet_msk=\"$_bridge_subnet_msk\" where id=1 "; mysql_query($query, $db); } print "<meta HTTP-EQUIV=\"REFRESH\" content=\"0; url=bridge.php\">"; ?> <file_sep><?php $page_title = "TrafficSqueezer Consolidated Report"; include('c/c_header.php'); ?> <meta http-equiv='refresh' content="10"> <script src="c/chart-js/Chart.js"></script> </head><?php include('c/c_body.php'); ?> <?php $contentfile="content_home.php"; $help="nohelp"; include('c/c_main.php'); ?><file_sep><?php //Read the DB and execute the frequently used command, so that system status is syncd in DB error_reporting(5); include("/var/www/html/c/c_db_access.php"); $query = "select id, command from command_output"; $result=mysql_query($query, $db); if(mysql_num_rows($result) > 0) { while($row = mysql_fetch_array($result)) { $command = $row['command']; $id = $row['id']; print "executing: $command\n"; $output = `$command`; mysql_query("update command_output set output=\"$output\" where id=$id", $db); } } mysql_close($db);
7381132d27b4a09e6cf46f01255ff3da6914103d
[ "SQL", "Makefile", "PHP", "C", "Shell" ]
48
PHP
mobilehunter/trafficsqueezer
22678cfacad7dd129b29d70a60c23436473e99e7
076454af54f7671215383db6330f05ef167a3d6b
refs/heads/master
<repo_name>hyhmaffia/algorithmic-puzzles<file_sep>/1.Wolf-Goat-Cabbage.py left_side = {"Wolf":True,"Goat":True,"Cabbage":True}
c0f014e92eeb952e39ee721c348e8129208ee70c
[ "Python" ]
1
Python
hyhmaffia/algorithmic-puzzles
7b05e95c93a2cd3d0d7d329a02006a75bb13977b
22efc4f2317bcabbf9bd0cda38ccc43d6424693a
refs/heads/master
<repo_name>liuyadong7/jfinal_rook<file_sep>/src/main/java/com/useradmin/common/enums/Driver.java package com.useradmin.common.enums; public enum Driver { postgresql, mysql, oracle, sqlserver, db2 } <file_sep>/src/main/java/com/useradmin/framework/aspectj/annotation/Controller.java package com.useradmin.framework.aspectj.annotation; import java.lang.annotation.*; /** * 控制器注解 * 说明:标注Controller和访问路径(自定义路径) * */ @Inherited @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE }) public @interface Controller { /** * 控制器路径,可以配置多个路径数组 * @return */ String[] controllerKey(); }<file_sep>/src/main/java/com/useradmin/framework/config/mapping/UserAdminMapping.java package com.useradmin.framework.config.mapping; import com.alibaba.druid.filter.stat.StatFilter; import com.alibaba.druid.wall.WallConfig; import com.alibaba.druid.wall.WallFilter; import com.demo.common.model.Blog; import com.jfinal.config.Plugins; import com.jfinal.kit.PropKit; import com.jfinal.plugin.activerecord.ActiveRecordPlugin; import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory; import com.jfinal.plugin.activerecord.dialect.*; import com.jfinal.plugin.druid.DruidPlugin; import com.useradmin.common.base.BaseMapping; import com.useradmin.common.constant.ConstantInit; import com.useradmin.common.dto.DataBase; import com.useradmin.common.enums.Driver; import com.useradmin.common.tools.ToolDataBase; import org.apache.log4j.Logger; public class UserAdminMapping extends BaseMapping { private static Logger log = Logger.getLogger(UserAdminMapping.class); /** * 数据库的连接处理 * * @param plugins */ public UserAdminMapping(Plugins plugins) { log.info("configPlugin 配置Druid数据库连接池连接属性"); Driver driver = Enum.valueOf(Driver.class, PropKit.get(ConstantInit.jfinal_datasource_db)); DataBase db = ToolDataBase.getDbInfo(driver); String driverClass = db.getDriverClass(); String jdbcUrl = db.getJdbcUrl(); String username = db.getUserName(); String password = <PASSWORD>(); DruidPlugin druidPlugin = new DruidPlugin(jdbcUrl, username, password, driverClass); log.info("configPlugin 配置Druid数据库连接池大小"); druidPlugin.set(PropKit.getInt(ConstantInit.datasource_db_initialSize), PropKit.getInt(ConstantInit.datasource_db_minIdle), PropKit.getInt(ConstantInit.datasource_db_maxActive)); log.info("configPlugin 配置Druid数据库连接池过滤器配制"); druidPlugin.addFilter(new StatFilter()); WallFilter wall = new WallFilter(); wall.setDbType(PropKit.get(ConstantInit.jfinal_datasource_db)); WallConfig config = new WallConfig(); config.setFunctionCheck(false); // 支持数据库函数 wall.setConfig(config); druidPlugin.addFilter(wall); log.info("注册useradmin ActiveRecordPlugin"); log.info("configPlugin 配置ActiveRecordPlugin插件"); // configName = ConstantInit.db_dataSource_main; // arp = new ActiveRecordPlugin(configName, druidPlugin); arp = new ActiveRecordPlugin(druidPlugin); // 临时处理 // arp.setTransactionLevel(4);//事务隔离级别 boolean devMode = Boolean.parseBoolean(PropKit.get(ConstantInit.config_constants_devMode)); arp.setDevMode(devMode); // 设置开发模式 arp.setShowSql(devMode); // 是否显示SQL arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));// 大小写不敏感 log.info("configPlugin 数据库类型判断"); switch (driver) { case postgresql: log.info("configPlugin 使用数据库类型是 postgresql"); arp.setDialect(new PostgreSqlDialect()); break; case mysql: log.info("configPlugin 使用数据库类型是 mysql"); arp.setDialect(new MysqlDialect()); break; case oracle: log.info("configPlugin 使用数据库类型是 oracle"); druidPlugin.setValidationQuery("select 1 FROM DUAL"); // 连接验证语句 arp.setDialect(new OracleDialect()); break; case sqlserver: log.info("configPlugin 使用数据库类型是 sqlserver"); arp.setDialect(new SqlServerDialect()); break; case db2: log.info("configPlugin 使用数据库类型是 db2"); druidPlugin.setValidationQuery("select 1 from sysibm.sysdummy1"); // 连接验证语句 arp.setDialect(new AnsiSqlDialect()); break; } log.info("configPlugin 添加druidPlugin插件"); plugins.add(druidPlugin); // 多数据源继续添加 log.info("configPlugin 表自动扫描映射"); scan(); log.info("configPlugin 表手工注册"); userAdminMapping(); log.info("configPlugin 注册ActiveRecordPlugin插件"); plugins.add(arp); } /** * 手动添加映射 */ private void userAdminMapping() { arp.addMapping("blog", Blog.class); //arp.addMapping("fg_recruit", "ids", Recruit.class); //arp.addMapping("fg_recruit", Recruit.class); } }<file_sep>/src/main/java/com/useradmin/common/constant/RexExp.java package com.useradmin.common.constant; import java.util.regex.Pattern; public interface RexExp { /** * 常用正则表达式:匹配非负整数(正整数 + 0) */ String regExp_integer_1 = "^\\d+$"; /** * 常用正则表达式:匹配由数字、26个英文字母、下划线、中划线、点组成的字符串 */ String regExp_letter_6 = "^([a-z_A-Z-.+0-9]+)$"; /** * 常用正则表达式:匹配正整数 */ String regExp_integer_2 = "^[0-9]*[1-9][0-9]*$"; /** * 常用正则表达式:匹配非正整数(负整数 + 0) */ String regExp_integer_3 = "^((-\\d+) ?(0+))$"; /** * 常用正则表达式:匹配负整数 */ String regExp_integer_4 = "^-[0-9]*[1-9][0-9]*$"; /** * 常用正则表达式:匹配整数 */ String regExp_integer_5 = "^-?\\d+$"; /** * 常用正则表达式:匹配非负浮点数(正浮点数 + 0) */ String regExp_float_1 = "^\\d+(\\.\\d+)?$"; /** * 常用正则表达式:匹配正浮点数 */ String regExp_float_2 = "^(([0-9]+\\.[0-9]*[1-9][0-9]*) ?([0-9]*[1-9][0-9]*\\.[0-9]+) ?([0-9]*[1-9][0-9]*))$"; /** * 常用正则表达式:匹配非正浮点数(负浮点数 + 0) */ String regExp_float_3 = "^((-\\d+(\\.\\d+)?) ?(0+(\\.0+)?))$"; /** * 常用正则表达式:匹配负浮点数 */ String regExp_float_4 = "^(-(([0-9]+\\.[0-9]*[1-9][0-9]*) ?([0-9]*[1-9][0-9]*\\.[0-9]+) ?([0-9]*[1-9][0-9]*)))$"; /** * 常用正则表达式:匹配浮点数 */ String regExp_float_5 = "^(-?\\d+)(\\.\\d+)?$"; /** * 常用正则表达式:匹配由26个英文字母组成的字符串 */ String regExp_letter_1 = "^[A-Za-z]+$"; /** * 常用正则表达式:匹配由26个英文字母的大写组成的字符串 */ String regExp_letter_2 = "^[A-Z]+$"; /** * 常用正则表达式:匹配由26个英文字母的小写组成的字符串 */ String regExp_letter_3 = "^[a-z]+$"; /** * 常用正则表达式:匹配由数字和26个英文字母组成的字符串 */ String regExp_letter_4 = "^[A-Za-z0-9]+$"; /** * 常用正则表达式:匹配由数字、26个英文字母或者下划线组成的字符串 */ String regExp_letter_5 = "^\\w+$"; /** * 常用正则表达式:匹配email地址 */ String regExp_email = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$"; /** * 常用正则表达式:匹配url */ String regExp_url_1 = "^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$"; /** * 常用正则表达式:匹配url */ String regExp_url_2 = "[a-zA-z]+://[^\\s]*"; /** * 常用正则表达式:匹配中文字符 */ String regExp_chinese_1 = "[\\u4e00-\\u9fa5]"; /** * 常用正则表达式:匹配双字节字符(包括汉字在内) */ String regExp_chinese_2 = "[^\\x00-\\xff]"; /** * 常用正则表达式:匹配空行 */ String regExp_line = "\\n[\\s ? ]*\\r"; /** * 常用正则表达式:匹配HTML标记 */ String regExp_html_1 = "/ <(.*)>.* <\\/\\1> ? <(.*) \\/>/"; /** * 常用正则表达式:匹配首尾空格 */ String regExp_startEndEmpty = "(^\\s*) ?(\\s*$)"; /** * 常用正则表达式:匹配帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线) */ String regExp_accountNumber = "^[a-zA-Z][a-zA-Z0-9_]{4,15}$"; /** * 常用正则表达式:匹配国内电话号码,匹配形式如 0511-4405222 或 021-87888822 */ String regExp_telephone = "\\d{3}-\\d{8} ?\\d{4}-\\d{7}"; /** * 常用正则表达式:腾讯QQ号, 腾讯QQ号从10000开始 */ String regExp_qq = "[1-9][0-9]{4,}"; /** * 常用正则表达式:匹配中国邮政编码 */ String regExp_postbody = "[1-9]\\d{5}(?!\\d)"; /** * 常用正则表达式:匹配身份证, 中国的身份证为15位或18位 */ String regExp_idCard = "\\d{15} ?\\d{18}"; /** * 常用正则表达式:IP */ String regExp_ip = "\\d+\\.\\d+\\.\\d+\\.\\d+"; /** * 处理提到某人 @xxxx */ Pattern referer_pattern = Pattern.compile("@([^@^\\s^:]{1,})([\\s\\:\\,\\;]{0,1})"); } <file_sep>/src/main/java/com/useradmin/framework/config/routes/UserAdminRoutes.java package com.useradmin.framework.config.routes; import com.demo.blog.BlogController; import com.demo.index.IndexController; import com.jfinal.config.Routes; import live.autu.plugin.jfinal.swagger.controller.SwaggerController; public class UserAdminRoutes extends Routes { @Override public void config() { // 配置默认的ViewPath setBaseViewPath("/WEB-INF/view"); // 配置swagger的路由 add("/swagger", SwaggerController.class); // add("/", IndexController.class, "/wp"); // 第三个参数为该Controller的视图存放路径 add("/blog", BlogController.class); // 第三个参数省略时默认与第一个参数值相同,在此即为 "/blog" } } <file_sep>/src/main/java/com/useradmin/project/mvc/blog/BlogController.java package com.useradmin.project.mvc.blog; import com.demo.common.model.Blog; import com.jfinal.aop.Before; import com.jfinal.aop.Inject; import com.jfinal.core.Controller; import live.autu.plugin.jfinal.swagger.annotation.Api; import live.autu.plugin.jfinal.swagger.annotation.ApiImplicitParam; import live.autu.plugin.jfinal.swagger.annotation.ApiImplicitParams; import live.autu.plugin.jfinal.swagger.annotation.ApiOperation; import live.autu.plugin.jfinal.swagger.config.RequestMethod; /** * 本 demo 仅表达最为粗浅的 jfinal 用法,更为有价值的实用的企业级用法 * 详见 JFinal 俱乐部: http://jfinal.com/club * <p> * 所有 sql 与业务逻辑写在 Service 中,不要放在 Model 中,更不 * 要放在 Controller 中,养成好习惯,有利于大型项目的开发与维护 */ @Api(tags = "test", description = "测试") @Before(BlogInterceptor.class) public class BlogController extends Controller { @Inject BlogService service; @ApiOperation(methods=RequestMethod.GET) @ApiImplicitParams({ @ApiImplicitParam(name="userName",required=false,description="这是学员的姓名") }) public void index() { setAttr("blogPage", service.paginate(getParaToInt(0, 1), 10)); render("/wp/view/blog/blog.html"); } public void add() { render("/wp/view/blog/add.html"); } /** * save 与 update 的业务逻辑在实际应用中也应该放在 service 之中, * 并要对数据进正确性进行验证,在此仅为了偷懒 */ @Before(BlogValidator.class) public void save() { getBean(Blog.class).save(); redirect("/blog"); } public void edit() { setAttr("blog", service.findById(getParaToInt())); render("/wp/view/blog/edit.html"); } /** * save 与 update 的业务逻辑在实际应用中也应该放在 service 之中, * 并要对数据进正确性进行验证,在此仅为了偷懒 */ @Before(BlogValidator.class) public void update() { getBean(Blog.class).update(); redirect("/blog"); } public void delete() { service.deleteById(getParaToInt()); redirect("/blog"); } @ApiOperation(methods=RequestMethod.GET) @ApiImplicitParams({ @ApiImplicitParam(name="userName",required=false,description="这是学员的姓名") }) public void test() { renderJson(); } } <file_sep>/src/main/java/com/useradmin/project/system/syslog/Syslog.java package com.useradmin.project.system.syslog; import org.apache.log4j.Logger; import java.sql.Timestamp; /** * 日志model * @author 董华健 */ @SuppressWarnings("unused") //@Table(tableName = "pt_syslog") public class Syslog /*extends BaseModel<Syslog> */{ private static final long serialVersionUID = 2051998642258015518L; private static Logger log = Logger.getLogger(Syslog.class); Syslog dao = new Syslog(); /** * 字段描述:主键 * 字段类型 :character varying */ String column_ids = "ids"; /** * 字段描述:版本号 * 字段类型 :bigint */ String column_version = "version"; /** * 字段描述:action结束时间 * 字段类型 :timestamp without time zone */ String column_actionenddate = "actionenddate"; /** * 字段描述:action结束时间 * 字段类型 :bigint */ String column_actionendtime = "actionendtime"; /** * 字段描述:action耗时 * 字段类型 :bigint */ String column_actionhaoshi = "actionhaoshi"; /** * 字段描述:action开始时间 * 字段类型 :timestamp without time zone */ String column_actionstartdate = "actionstartdate"; /** * 字段描述:action开始时间 * 字段类型 :bigint */ String column_actionstarttime = "actionstarttime"; /** * 字段描述:失败原因 : 0没有权限,1URL不存在,2未登录,3业务代码异常 * 字段类型 :character */ String column_cause = "cause"; /** * 字段描述:cookie数据 * 字段类型 :character varying */ String column_cookie = "cookie"; /** * 字段描述:描述 * 字段类型 :text */ String column_description = "description"; /** * 字段描述:结束时间 * 字段类型 :timestamp without time zone */ String column_enddate = "enddate"; /** * 字段描述:结束时间 * 字段类型 :bigint */ String column_endtime = "endtime"; /** * 字段描述:耗时 * 字段类型 :bigint */ String column_haoshi = "haoshi"; /** * 字段描述:客户端ip * 字段类型 :character varying */ String column_ips = "ips"; /** * 字段描述:访问方法 * 字段类型 :character varying */ String column_method = "method"; /** * 字段描述:源引用 * 字段类型 :character varying */ String column_referer = "referer"; /** * 字段描述:请求路径 * 字段类型 :text */ String column_requestpath = "requestpath"; /** * 字段描述:开始时间 * 字段类型 :timestamp without time zone */ String column_startdate = "startdate"; /** * 字段描述:开始时间 * 字段类型 :bigint */ String column_starttime = "starttime"; /** * 字段描述:账号状态 * 字段类型 :character */ String column_status = "status"; /** * 字段描述:useragent * 字段类型 :character varying */ String column_useragent = "useragent"; /** * 字段描述:视图耗时 * 字段类型 :bigint */ String column_viewhaoshi = "viewhaoshi"; /** * 字段描述:菜单对应功能ids * 字段类型 :character varying */ String column_operatorids = "operatorids"; /** * 字段描述:accept * 字段类型 :character varying */ String column_accept = "accept"; /** * 字段描述:acceptencoding * 字段类型 :character varying */ String column_acceptencoding = "acceptencoding"; /** * 字段描述:acceptlanguage * 字段类型 :character varying */ String column_acceptlanguage = "acceptlanguage"; /** * 字段描述:connection * 字段类型 :character varying */ String column_connection = "connection"; /** * 字段描述:host * 字段类型 :character varying */ String column_host = "host"; /** * 字段描述:xrequestedwith * 字段类型 :character varying */ String column_xrequestedwith = "xrequestedwith"; /** * 字段描述:pvids * 字段类型 :character varying */ String column_pvids = "pvids"; /** * 字段描述:访问用户ids * 字段类型 :character varying */ String column_userids = "userids"; /** * sqlId : platform.sysLog.view * 描述: */ String sqlId_view = "platform.sysLog.view"; /** * sqlId : platform.sysLog.splitPageSelect * 描述:分页select */ String sqlId_splitPageSelect = "platform.sysLog.splitPageSelect"; /** * sqlId : platform.sysLog.splitPageFrom * 描述:分页from */ String sqlId_splitPageFrom = "platform.sysLog.splitPageFrom"; /** * sqlId : platform.sysLog.clear * 描述:清除数据 */ String sqlId_clear = "platform.sysLog.clear"; private String ids; private String version; private String actionenddate; private String actionendtime; private String actionhaoshi; private String actionstartdate; private String actionstarttime; private String cause; private String cookie; private String description; private String enddate; private String endtime; private String haoshi; private String ips; private String method; private String referer; private String requestpath; private String startdate; private String starttime; private String status; private String useragent; private String viewhaoshi; private String operatorids; private String accept; private String acceptencoding; private String acceptlanguage; private String connection; private String host; private String xrequestedwith; private String pvids; private String userids; }
5523bd4042f7878ebb1f0f9ae98719826750dd3c
[ "Java" ]
7
Java
liuyadong7/jfinal_rook
c99722a3c21961259ea7f428633cc9c0a6760e23
326a817b93e91fd3474f5fc75a6975a48f2bbec1
refs/heads/master
<repo_name>BXHero/CGMSuShi<file_sep>/pages/test/test.js // pages/test/test.js Page({ /** * 页面的初始数据 */ data: { input1 : "你的名字", input2 : "对方名字", returnString : "返回结果" }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, onClick:function(){ console.log(this.data.input1 ) var name1 = this.data.input1; var name2 = this.data.input2; var returnname = ""; var sum = 0; if(name1 == "张晓华" && name2 == "卢展鹏"){ returnname = "天造地设" } else if (name1 == "张晓华" && name2 != "卢展鹏"){ returnname = "什么鬼" } else if (name1 != "张晓华" && name2 == "卢展鹏"){ returnname = "什么鬼" }else{ returnname = "看天气吧 哈哈哈" } this.setData({ returnString: returnname }) }, onInput:function(e){ var str1 = e.detail.value this.setData({ input1:str1 }) }, onInput2: function (e) { var str1 = e.detail.value this.setData({ input2:str1 }) } })
c22ea8f2c88bc5308c65abd8c81a3ea47f774ec7
[ "JavaScript" ]
1
JavaScript
BXHero/CGMSuShi
25a30fd81fe26801704a4fee2bc698d1e9577a78
2369204569912f4c507a9ff9c72a689e48379b85
refs/heads/master
<file_sep>package com.medical.iqcc.security.jurisdiction.service; import com.medical.iqcc.security.jurisdiction.entity.UserAuthority; import java.util.List; import java.util.Map; /** * Created by JiangZ on 2015-06-26. */ public interface UserAuthorityService { int deleteByPrimaryKey(Long id); int insert(UserAuthority record); int insertSelective(UserAuthority record); UserAuthority selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(UserAuthority record); int updateByPrimaryKey(UserAuthority record); List<UserAuthority> selectByMap(Map map); } <file_sep>package com.medical.iqcc.base.menu.mapper; import com.medical.iqcc.base.menu.entity.Menu; import com.medical.mybatis.annotation.MyBatisDao; import org.apache.ibatis.annotations.Param; @MyBatisDao public interface MenuMapper { int deleteByPrimaryKey(Long id); int insert(@Param("menu") Menu record); int insertSelective(@Param("menu") Menu record); Menu selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(@Param("menu") Menu record); int updateByPrimaryKey(@Param("menu") Menu record); }<file_sep>package com.medical.iqcc.security.jurisdiction.mapper; import com.medical.iqcc.security.jurisdiction.entity.Role; import com.medical.mybatis.annotation.MyBatisDao; import org.apache.ibatis.annotations.Param; @MyBatisDao public interface RoleMapper { int deleteByPrimaryKey(Long id); int insert(@Param("role") Role record); int insertSelective(@Param("role") Role record); Role selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(@Param("role") Role record); int updateByPrimaryKey(@Param("role") Role record); }<file_sep>package com.medical.iqcc.module.business.service.impl; import com.medical.iqcc.module.business.entity.ProjInfo; import com.medical.iqcc.module.business.mapper.ProjInfoMapper; import com.medical.iqcc.module.business.service.ProjInfoService; import com.medical.util.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by JiangZ on 2015-06-23. */ @Service @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class ProjInfoServiceImpl implements ProjInfoService { @Autowired private ProjInfoMapper projInfoMapper; @Override public int deleteByPrimaryKey(Long id) { return projInfoMapper.deleteByPrimaryKey(id); } @Override public int insert(ProjInfo record) { return projInfoMapper.insert(record); } @Override public int insertSelective(ProjInfo record) { return projInfoMapper.insertSelective(record); } @Override public ProjInfo selectByPrimaryKey(Long id) { return projInfoMapper.selectByPrimaryKey(id); } @Override public int updateByPrimaryKeySelective(ProjInfo record) { return projInfoMapper.updateByPrimaryKeySelective(record); } @Override public int updateByPrimaryKey(ProjInfo record) { return projInfoMapper.updateByPrimaryKey(record); } @Override public List<ProjInfo> selectListPage(PageInfo pageInfo) { return projInfoMapper.selectListPage(pageInfo); } } <file_sep>package com.medical.iqcc.module.user.entity; import com.medical.util.ValueEnum; /** * @author Sephy * @since: 2015-05-11 */ public enum UserState implements ValueEnum<UserState, Integer> { /** * 注册未激活 */ UNACTIVATED(0), /** * 激活 */ ACTIVATED(1), /** * 锁定 */ LOCKED(2); private int value; UserState(int value) { this.value = value; } public Integer value() { return this.value; } } <file_sep>package com.medical.iqcc.base.organization.service; import com.medical.iqcc.base.organization.entity.AclUser; import java.util.Map; /** * Created by JiangZ on 2015-06-29. */ public interface AclUserService { int deleteByPrimaryKey(Long id); int insert(AclUser record); AclUser selectByPrimaryKey(Long id); int updateByPrimaryKey(AclUser record); AclUser selectByMap(Map map); } <file_sep>package com.medical.iqcc.base.organization.mapper; import com.medical.iqcc.base.organization.entity.AclUser; import com.medical.mybatis.annotation.MyBatisDao; import org.apache.ibatis.annotations.Param; import java.util.Map; @MyBatisDao public interface AclUserMapper { int deleteByPrimaryKey(Long id); int insert(@Param("aclUser") AclUser record); // int insertSelective(@Param("aclUser") AclUser record); AclUser selectByPrimaryKey(Long id); //int updateByPrimaryKeySelective(@Param("aclUser") AclUser record); int updateByPrimaryKey(@Param("aclUser") AclUser record); AclUser selectByMap(Map map); }<file_sep>package com.medical.iqcc.module.user.entity; import com.medical.iqcc.module.common.entity.BaseEntity; /** * @author Sephy * @since: 2015-05-10 */ public class Department extends BaseEntity { private static final long serialVersionUID = -1044089170081207267L; private String name; private String description; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } <file_sep>/* * Copyright 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *//* package com.medical.iqcc.module.user.shiro; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.authz.Permission; */ /** * 规则 +资源字符串+权限位+实例ID * * 以+开头 中间通过+分割 * * 权限: 15(1111) 表示所有权限 1(0001) 查看 2(0010) 新增 4(0100) 修改 8(1000) 删除 * * 如 +user+10 表示对资源user拥有查看/删除权限 * * 不考虑一些异常情况 * * @author Sephy * @since: 2015-05-11 *//* public class BitPermission implements Permission { private String resId; private Integer permissionBit; private String instanceId; public BitPermission() { } public BitPermission(String permissionString) { String[] array = permissionString.split("\\+"); if (array.length > 1) { resId = array[1]; } setResId(resId); if (array.length > 2) { permissionBit = Integer.valueOf(array[2]); } if (array.length > 3) { instanceId = array[3]; } setInstanceId(instanceId); } public String getResId() { return resId; } public void setResId(String resId) { if (StringUtils.isEmpty(resId)) { this.resId = "*"; } else { this.resId = resId; } } public int getPermissionBit() { return permissionBit; } public void setPermissionBit(int permissionBit) { this.permissionBit = permissionBit; } public String getInstanceId() { return instanceId; } public void setInstanceId(String instanceId) { if (StringUtils.isEmpty(instanceId)) { this.instanceId = "*"; } else { this.instanceId = instanceId; } } @Override public boolean implies(Permission p) { if (!(p instanceof BitPermission)) { return false; } BitPermission other = (BitPermission) p; if (!("*".equals(this.resId) || this.resId.equals(other.resId))) { return false; } // 比较每一位 int m = 0; int n = 0; for (int i = 0; i < 4; i++) { int bit = 1 << i; m = this.permissionBit & bit; n = other.permissionBit & bit; if (m < n) { return false; } } if (!("*".equals(this.instanceId) || this.instanceId.equals(other.instanceId))) { return false; } return true; } @Override public String toString() { String str = null; if (instanceId == null) { str = String.format("BitPermission: { resId = \"%s\", permissionBit = \"%s\"}", resId, Integer.toBinaryString(permissionBit)); } else { str = String.format("BitPermission: { resId = \"%s\", permissionBit = \"%s\", instanceId = \"%s\" }", resId, Integer.toBinaryString(permissionBit), instanceId); } return str; } } */ <file_sep>/* * Copyright 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.medical.iqcc.module.user.entity; import com.medical.iqcc.module.common.entity.BaseEntity; /** * 用户、部门关系 * * @author Sephy * @since: 2015-05-11 */ public class UserDeptAssociate extends BaseEntity { private static final long serialVersionUID = -2596123108849106967L; private Long deptId; public Long getDeptId() { return deptId; } public void setDeptId(Long deptId) { this.deptId = deptId; } } <file_sep>package com.medical.iqcc.module.business.entity; import com.medical.iqcc.module.common.entity.BaseEntity; import org.joda.time.DateTime; import java.math.BigDecimal; import java.util.Date; public class TargetValue extends BaseEntity{ private Double mean; private Double sd; private String creator; private BigDecimal state; private String actionlog; private Date createdtime; private Long projinfoid; private Date begindate; private Date enddate; public Double getMean() { return mean; } public void setMean(Double mean) { this.mean = mean; } public Double getSd() { return sd; } public void setSd(Double sd) { this.sd = sd; } public String getCreator() { return creator; } public void setCreator(String creator) { this.creator = creator == null ? null : creator.trim(); } public BigDecimal getState() { return state; } public void setState(BigDecimal state) { this.state = state; } public String getActionlog() { return actionlog; } public void setActionlog(String actionlog) { this.actionlog = actionlog; } public Date getCreatedtime() { return createdtime; } public void setCreatedtime(Date createdtime) { this.createdtime = createdtime; } public Long getProjinfoid() { return projinfoid; } public void setProjinfoid(Long projinfoid) { this.projinfoid = projinfoid; } public Date getBegindate() { return begindate; } public void setBegindate(Date begindate) { this.begindate = begindate; } public Date getEnddate() { return enddate; } public void setEnddate(Date enddate) { this.enddate = enddate; } }<file_sep>package com.medical.iqcc.base.organization.entity; import java.io.Serializable; /** * 男女枚举值 * @author JiangZ * */ public class Gender implements Serializable{ public static final int GENDER_MALE = 1200; public static final int GENDER_WOMAN = 1201; } <file_sep>package com.medical.iqcc.module.user.web.controller; import com.fasterxml.jackson.databind.Module; import com.medical.iqcc.module.user.entity.User; import com.medical.iqcc.module.user.service.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by xiam on 2015/5/28. */ @Controller public class UserController { private static final Logger LOG = LoggerFactory.getLogger(UserController.class); @Autowired private UserService userService; /** * 用户注册 {@link ResponseBody} 注解表示返回 * json 数据 * @param email * @param password * @return */ @RequestMapping(value = "/signup", method = RequestMethod.POST) public Object signup(String email, String password, RedirectAttributes redirectAttributes) { User user = userService.register(email, password); redirectAttributes.addAttribute("email", user.getEmail()); LOG.debug("用户注册成功, 用户id为{}", user.getId()); return "redirect:/redirect"; } /** * 获取注册页面 * @return */ @RequestMapping(value = "/signup", method = RequestMethod.GET) public Object signup(HttpServletRequest request, HttpServletResponse response, Model model) { System.out.println(request.getParameter("name")); User user = userService.get(19L); model.addAttribute("user", user); return "signup"; } @RequestMapping("/redirect") public Object redirect(String email, Model model) { model.addAttribute("message", email); return "redirect"; } @RequestMapping("/login") public Object login() { return "login"; } @RequestMapping("/login_success") public Object loginSuccess(Model model) { model.addAttribute("message", "登录成功"); return "login_success"; } @ResponseBody @RequestMapping("/user/get") public Object get(Long userId) { User user = userService.get(userId); return user; } @RequestMapping("/") public Object test() { return ""; } @RequestMapping("/main") public Object main(){ return "main"; } @RequestMapping("/accessDeniedPage") public Object loginError(){ return "accessDeniedPage"; } } <file_sep>package com.medical.iqcc.module.baseInfo.service.impl; import com.medical.iqcc.module.baseInfo.entity.ControlMerInfo; import com.medical.iqcc.module.baseInfo.entity.T_LABINFO; import com.medical.iqcc.module.baseInfo.mapper.T_LABINFOMapper; import com.medical.iqcc.module.baseInfo.service.T_LABINFOService; import com.medical.util.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; /** * Created by JiangZ on 2015-06-01. */ @Service @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class T_LABINFOServiceImpl implements T_LABINFOService { @Autowired private T_LABINFOMapper t_labinfoMapper; @Override @Transactional public void save(T_LABINFO t_labinfo) { t_labinfoMapper.save(t_labinfo); } @Override @Transactional public void del(Long id) { t_labinfoMapper.del(id); } @Override @Transactional public void update(T_LABINFO t_labinfo) { t_labinfoMapper.update(t_labinfo); } @Override public List<T_LABINFO> getListByMap(Map filter) { return t_labinfoMapper.getListByMap(filter); } @Override public List<T_LABINFO> findByName(String LABNAME) { return t_labinfoMapper.findByName(LABNAME); } @Override public T_LABINFO getById(Long id) { return t_labinfoMapper.get(id); } @Override public T_LABINFO getObjById(Long id) { return null; } @Override public List<T_LABINFO> selectListPage(PageInfo pageInfo) { return t_labinfoMapper.selectListPage(pageInfo); } } <file_sep>package com.medical.iqcc.base.organization.service.impl; import com.medical.iqcc.base.organization.entity.AclOrg; import com.medical.iqcc.base.organization.mapper.AclOrgMapper; import com.medical.iqcc.base.organization.service.AclOrgService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * Created by JiangZ on 2015-06-29. */ @Service @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class AclOrgServiceImpl implements AclOrgService { @Autowired private AclOrgMapper aclOrgMapper; @Override @Transactional public int deleteByPrimaryKey(Long id) { return aclOrgMapper.deleteByPrimaryKey(id); } @Override @Transactional public int insert(AclOrg record) { return aclOrgMapper.insert(record); } @Override public AclOrg selectByPrimaryKey(Long id) { return aclOrgMapper.selectByPrimaryKey(id); } @Override @Transactional public int updateByPrimaryKey(AclOrg record) { return aclOrgMapper.updateByPrimaryKey(record); } } <file_sep>/* * Copyright 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.medical.iqcc.module.user.mapper; import com.medical.mybatis.annotation.MyBatisDao; import com.medical.iqcc.module.user.entity.User; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 用户实体 * * @author Sephy * @since: 2015-05-11 */ @MyBatisDao public interface UserMapper { /** * 插入一条用户记录 * @param user 用户对象 * @return */ int save(@Param("user") User user); /** * 根据电子邮件查找用户 * @param email * @return */ List<User> findByEmail(String email); /** * 根据用户ID查找用户记录 * @param id 用户ID * @return */ List<User> get(Long id); /** * 根据用户ID, 更新用户信息, 只更新不为 null 的字段 * @param user 用户对象 */ void update(@Param("user") User user); } <file_sep>package com.medical.iqcc.module.baseInfo.service.impl; import com.medical.iqcc.module.baseInfo.entity.T_DEPARTMENTINFO; import com.medical.iqcc.module.baseInfo.entity.T_LABINFO; import com.medical.iqcc.module.baseInfo.mapper.T_DEPARTMENTINFOMapper; import com.medical.iqcc.module.baseInfo.mapper.T_LABINFOMapper; import com.medical.iqcc.module.baseInfo.service.T_DEPARTMENTINFOService; import com.medical.iqcc.module.baseInfo.service.T_LABINFOService; import com.medical.util.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; /** * Created by JiangZ on 2015-06-01. */ @Service @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class T_DEPARTMENTServiceImpl implements T_DEPARTMENTINFOService { @Autowired private T_DEPARTMENTINFOMapper t_departmentinfoMapper; @Override @Transactional public void save(T_DEPARTMENTINFO t_departmentinfo) { t_departmentinfoMapper.save(t_departmentinfo); } @Override @Transactional public void del(Long id) { t_departmentinfoMapper.del(id); } @Override @Transactional public void update(T_DEPARTMENTINFO t_departmentinfo) { t_departmentinfoMapper.update(t_departmentinfo); } @Override public List<T_DEPARTMENTINFO> getListByMap(Map filter) { return t_departmentinfoMapper.getListByMap(filter); } @Override public List<T_DEPARTMENTINFO> findByLabId(Long LABID) { return t_departmentinfoMapper.findByLabId(LABID); } @Override public T_DEPARTMENTINFO get(Long id) { return t_departmentinfoMapper.get(id); } @Override public T_DEPARTMENTINFO getObjById(Long id) { return null; } @Override public List<T_DEPARTMENTINFO> selectListPage(PageInfo pageInfo) { return t_departmentinfoMapper.selectListPage(pageInfo); } } <file_sep>/* package com.medical.iqcc.module.user.shiro; import org.apache.shiro.util.ByteSource; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; */ /** * Created by xiam on 2015/5/28. *//* public class ByteSourceFactoryBean implements FactoryBean<ByteSource>, InitializingBean { private ByteSource byteSource; private String saltString; public void setSaltString(String saltString) { this.saltString = saltString; } @Override public ByteSource getObject() throws Exception { return null; } @Override public Class<?> getObjectType() { return ByteSource.class; } @Override public boolean isSingleton() { return true; } @Override public void afterPropertiesSet() throws Exception { byteSource = ByteSource.Util.bytes(saltString); } } */ <file_sep>/* * Copyright 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.medical.iqcc.module.common.service.impl; import java.util.Collections; import java.util.List; import com.medical.iqcc.module.common.Region; import com.medical.iqcc.module.common.entity.Area; import com.medical.iqcc.module.common.model.AreaCriteria; import com.medical.iqcc.module.common.consts.AreaConsts; import com.medical.iqcc.module.common.mapper.AreaMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.medical.iqcc.module.common.service.AreaService; /** * @author Sephy * @since: 2015-05-13 */ @Transactional(readOnly = true) @Service public class AreaServiceImpl implements AreaService { @Autowired(required=false) private AreaMapper areaMapper; @Override public void save(List<Area> areaList) { areaMapper.save(areaList); } @Override public List<? extends Region> getProvinceList() { return areaMapper.search(AreaCriteria.PROVINCE_ONLY); } @Override public List<? extends Region> getCityListUnderProvince(int code) { // 区域编码从 110000 开始 if (code < AreaConsts.RANGE_PROVINCE * 11) { return Collections.emptyList(); } long start = (code % AreaConsts.RANGE_PROVINCE) * AreaConsts.RANGE_PROVINCE; long end = code + AreaConsts.RANGE_PROVINCE; AreaCriteria criteria = new AreaCriteria(AreaConsts.LEVEL_CITY, start, end); criteria.setLevel(AreaConsts.LEVEL_CITY); return areaMapper.search(criteria); } @Override public List<? extends Region> getCountyUnderCity(int code) { // 区域编码从 110000 开始 if (code < AreaConsts.RANGE_PROVINCE * 11) { return Collections.emptyList(); } long start = (code % AreaConsts.RANGE_CITY) * AreaConsts.RANGE_CITY; long end = code + AreaConsts.RANGE_CITY; AreaCriteria criteria = new AreaCriteria(AreaConsts.LEVEL_COUNTY, start, end); return areaMapper.search(criteria); } } <file_sep>WEB_SECURITY /controlNumInfo/list=CONTROLNUMINFO_LIST /performStand/list=PERFORMSTAND_LIST WEB_SECURITY_END BUSINESS_SECURITY com.medical.iqcc.module.business.service.ControlNumInfoService.insert=CONTROLNUMINFO_SAVE com.medical.iqcc.module.business.service.ControlNumInfoService.selectListPage=CONTROLNUMINFO_LIST com.medical.iqcc.module.business.service.ControlNumInfoService.deleteByPrimaryKey=CONTROLNUMINFO_DEL com.medical.iqcc.module.business.service.PerformStandService.insert=PERFORMSTAND_SAVE com.medical.iqcc.module.business.service.PerformStandService.selectListPage=PERFORMSTAND_LIST com.medical.iqcc.module.business.service.PerformStandService.deleteByPrimaryKey=PERFORMSTAND_DEL BUSINESS_SECURITY_END<file_sep>WEB_SECURITY /baseMer/list=BASEMER_LIST /controlBaseInfo/list=CONTROLBASEINFO_LIST /controlMerInfo/list=CONTROLMERINFO_LIST /pro_MethodInfo/list=PROMETHODINFO_LIST /pro_ReagentInfo/list=PROREAGENTINFO_LIST /pro_UnitInfo/list=PROUNITINFO_LIST /projBaseInfo/list=PROJBASEINFO_LIST /baseInfo/actioninfo=ACTIONINFO_LIST /baseInfo/areainfo=AREAINFO_LIST /baseInfo/department=DEPARTMENT_LIST /baseInfo/instruinfo=INSTRUINFO_LIST /baseInfo/lab=LAB_LIST /baseInfo/methodinfo=METHODINFO_LIST /baseInfo/reagentinfo=REAGENTINFO_LIST /baseInfo/unitinfo=UNITINFO_LIST /baseInfo/userinfo=USERINFO_LIST /baseInfo/userstatueinfo=USERSTATUEINFO_LIST WEB_SECURITY_END BUSINESS_SECURITY com.medical.iqcc.module.baseInfo.service.BaseMerService.insert=BASEMER_SAVE com.medical.iqcc.module.baseInfo.service.BaseMerService.selectListPage=BASEMER_LIST com.medical.iqcc.module.baseInfo.service.BaseMerService.deleteByPrimaryKey=BASEMER_DEL com.medical.iqcc.module.baseInfo.service.ControlBaseInfoService.insert=CONTROLBASEINFO_SAVE com.medical.iqcc.module.baseInfo.service.ControlBaseInfoService.selectListPage=CONTROLBASEINFO_LIST com.medical.iqcc.module.baseInfo.service.ControlBaseInfoService.deleteByPrimaryKey=CONTROLBASEINFO_DEL com.medical.iqcc.module.baseInfo.service.ControlMerInfoService.save=CONTROLMERINFO_SAVE com.medical.iqcc.module.baseInfo.service.ControlMerInfoService.selectListPage=CONTROLMERINFO_LIST com.medical.iqcc.module.baseInfo.service.ControlMerInfoService.del=CONTROLMERINFO_DEL com.medical.iqcc.module.baseInfo.service.ProjBaseInfoService.insert=PROJBASEINFO_SAVE com.medical.iqcc.module.baseInfo.service.ProjBaseInfoService.selectListPage=PROJBASEINFO_LIST com.medical.iqcc.module.baseInfo.service.ProjBaseInfoService.deleteByPrimaryKey=PROJBASEINFO_DEL com.medical.iqcc.module.baseInfo.service.T_ACTIONINFOService.save=ACTIONINFO_SAVE com.medical.iqcc.module.baseInfo.service.T_ACTIONINFOService.del=ACTIONINFO_DEL com.medical.iqcc.module.baseInfo.service.T_ACTIONINFOService.selectListPage=ACTIONINFO_LIST com.medical.iqcc.module.baseInfo.service.T_AREAINFOService.save=AREAINFO_SAVE com.medical.iqcc.module.baseInfo.service.T_AREAINFOService.del=AREAINFO_DEL com.medical.iqcc.module.baseInfo.service.T_AREAINFOService.selectListPage=AREAINFO_LIST com.medical.iqcc.module.baseInfo.service.T_DEPART_INSTRUINFOService.save=DEPARTMENT_SAVE com.medical.iqcc.module.baseInfo.service.T_DEPART_INSTRUINFOService.del=DEPARTMENT_DEL com.medical.iqcc.module.baseInfo.service.T_DEPARTMENTINFOService.save=INSTRUINFO_SAVE com.medical.iqcc.module.baseInfo.service.T_DEPARTMENTINFOService.del=INSTRUINFO_DEL com.medical.iqcc.module.baseInfo.service.T_DEPARTMENTINFOService.selectListPage=INSTRUINFO_LIST com.medical.iqcc.module.baseInfo.service.T_INSTRUINFOService.save=INSTRUINFO_SAVE com.medical.iqcc.module.baseInfo.service.T_INSTRUINFOService.del=INSTRUINFO_DEL com.medical.iqcc.module.baseInfo.service.T_INSTRUINFOService.selectListPage=INSTRUINFO_LIST com.medical.iqcc.module.baseInfo.service.T_LAB_DEPART_USERINFOService.save=LAB_DEPART_SAVE com.medical.iqcc.module.baseInfo.service.T_LAB_DEPART_USERINFOService.del=LAB_DEPART_DEL com.medical.iqcc.module.baseInfo.service.T_LABINFOService.save=LAB_SAVE com.medical.iqcc.module.baseInfo.service.T_LABINFOService.del=LAB_DEL com.medical.iqcc.module.baseInfo.service.T_LABINFOService.selectListPage=LAB_LIST com.medical.iqcc.module.baseInfo.service.T_METHODINFOService.save=METHODINFO_SAVE com.medical.iqcc.module.baseInfo.service.T_METHODINFOService.del=METHODINFO_DEL com.medical.iqcc.module.baseInfo.service.T_METHODINFOService.selectListPage=METHODINFO_LIST com.medical.iqcc.module.baseInfo.service.T_REAGENTINFOService.save=REAGENTINFO_SAVE com.medical.iqcc.module.baseInfo.service.T_REAGENTINFOService.del=REAGENTINFO_DEL com.medical.iqcc.module.baseInfo.service.T_REAGENTINFOService.selectListPage=REAGENTINFO_LIST com.medical.iqcc.module.baseInfo.service.T_UNITINFOService.save=UNITINFO_SAVE com.medical.iqcc.module.baseInfo.service.T_UNITINFOService.del=UNITINFO_DEL com.medical.iqcc.module.baseInfo.service.T_UNITINFOService.selectListPage=UNITINFO_LIST com.medical.iqcc.module.baseInfo.service.T_USERINFOService.save=USERINFO_SAVE com.medical.iqcc.module.baseInfo.service.T_USERINFOService.del=USERINFO_DEL com.medical.iqcc.module.baseInfo.service.T_USERINFOService.selectListPage=USERINFO_LIST com.medical.iqcc.module.baseInfo.service.T_USERSTATUEINFOService.save=USERSTATUEINFO_SAVE com.medical.iqcc.module.baseInfo.service.T_USERSTATUEINFOService.del=USERSTATUEINFO_DEL com.medical.iqcc.module.baseInfo.service.T_USERSTATUEINFOService.selectListPage=USERSTATUEINFO_LIST BUSINESS_SECURITY_END<file_sep>package com.medical.iqcc.base.organization.entity; import com.medical.iqcc.module.common.entity.BaseEntity; public class AclOrg extends BaseEntity{ private String address; private String description; private String orgname; private String orgnum; private AclUser creator; private AclUser manager; private Long parentorg; public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description == null ? null : description.trim(); } public String getOrgname() { return orgname; } public void setOrgname(String orgname) { this.orgname = orgname == null ? null : orgname.trim(); } public String getOrgnum() { return orgnum; } public void setOrgnum(String orgnum) { this.orgnum = orgnum == null ? null : orgnum.trim(); } public AclUser getCreator() { return creator; } public void setCreator(AclUser creator) { this.creator = creator; } public AclUser getManager() { return manager; } public void setManager(AclUser manager) { this.manager = manager; } public Long getParentorg() { return parentorg; } public void setParentorg(Long parentorg) { this.parentorg = parentorg; } }<file_sep>/* package com.medical.iqcc.module.user.shiro; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.elasticsearch.common.collect.Sets; import org.springframework.beans.factory.annotation.Autowired; import com.medical.iqcc.module.user.entity.User; import com.medical.iqcc.module.user.entity.UserState; import com.medical.iqcc.module.user.service.ResPermissionSerivce; import com.medical.iqcc.module.user.service.UserRoleDeptAssociateService; import com.medical.iqcc.module.user.service.UserService; */ /** * @author Sephy * @since: 2015-05-10 *//* public class PasswordRealm extends AuthorizingRealm { @Autowired private UserService userService; @Autowired private UserRoleDeptAssociateService userRoleDeptAssociateService; @Autowired private ResPermissionSerivce resPermissionSerivce; */ /** * 获取权限角色信息 * @param principalCollection * @return *//* @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { return new SimpleAuthorizationInfo(Sets.newHashSet("admin")); } */ /** * 有用户名密码验证 * @param authenticationToken * @return * @throws AuthenticationException *//* @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; User user = userService.findByEmail(token.getUsername()); if (user != null) { return getAccount(user); } return null; } private SimpleAccount getAccount(User user) { SimpleAccount account = new SimpleAccount(user.getId(), user.getPassword(), getName()); // 是否锁定 if (user.getState() == UserState.LOCKED) { account.setLocked(true); } // List<Role> roles = // userRoleDeptAssociateService.findRolesByUserId(user.getId()); // Set<String> roleNames = new HashSet<>(roles.size()); // 角色名称 // List<Long> roleIds = new ArrayList<>(roles.size()); // for (Role role : roles) { // roleNames.add(role.getName()); // roleIds.add(role.getId()); // } // List<ResPermission> permissions = // resPermissionSerivce.getRolePermission(roleIds); // Set<Permission> permissionSet = new HashSet<>(permissions.size()); // for (ResPermission permission : permissions) { // permissionSet.add(new BitPermission(permission.toString())); // } // account.setObjectPermissions(permissionSet); // 设置权限 account.setRoles(Sets.newHashSet("admin")); // 设置角色 return account; } } */ <file_sep>package com.medical.iqcc.security.jurisdiction.entity; import com.medical.iqcc.base.organization.entity.AclUser; import com.medical.iqcc.module.common.entity.BaseEntity; import java.math.BigDecimal; public class UserRole extends BaseEntity{ private AclUser securityUser; private Role role; public AclUser getSecurityUser() { return securityUser; } public void setSecurityUser(AclUser securityUser) { this.securityUser = securityUser; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } }<file_sep>package com.medical.iqcc.module.business.service; import com.medical.iqcc.module.business.entity.ProjInfo; import com.medical.util.PageInfo; import java.util.List; /** * Created by JiangZ on 2015-06-23. */ public interface ProjInfoService { int deleteByPrimaryKey(Long id); int insert(ProjInfo record); int insertSelective(ProjInfo record); ProjInfo selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(ProjInfo record); int updateByPrimaryKey(ProjInfo record); List<ProjInfo> selectListPage(PageInfo pageInfo); } <file_sep>/* * Copyright 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.medical.iqcc.module.user.mapper; import java.util.List; import com.medical.iqcc.module.user.entity.Role; import com.medical.iqcc.module.user.entity.User; import com.medical.mybatis.annotation.MyBatisDao; /** * @author Sephy * @since: 2015-05-11 */ @MyBatisDao public interface UserRoleAssociateMapper { /** * 根据用户ID查找用户拥有的角色信息 * @param userId * @return */ List<Role> findRolesByUserId(Long userId); /** * 根据用户ID查找用户所在的部门信息 * @param userId * @return */ // List<Department> findDepartmentsByUserId(Long userId); /** * 根据角色ID查找拥有该角色的用户信息 * @param roleId * @return */ List<User> findUsersByRoleId(Long roleId); /** * 根据部门ID查找该部门下的用户信息 * @param deptId * @return */ // List<User> findUsersByDeptId(Long deptId); } <file_sep>package com.medical.iqcc.module.user.service.impl; import java.util.List; import com.medical.iqcc.module.user.service.UserRoleDeptAssociateService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.medical.iqcc.module.user.entity.Role; import com.medical.iqcc.module.user.mapper.UserRoleAssociateMapper; /** * @author Sephy * @since: 2015-05-27 */ @Service @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class UserRoleDeptAssociateServiceImpl implements UserRoleDeptAssociateService { @Autowired private UserRoleAssociateMapper userRoleAssociateMapper; @Override public List<Role> findRolesByUserId(Long userId) { return userRoleAssociateMapper.findRolesByUserId(userId); } } <file_sep>package com.medical.iqcc.module.baseInfo.web.controller; import com.medical.iqcc.module.baseInfo.entity.T_DEPARTMENTINFO; import com.medical.iqcc.module.baseInfo.entity.T_LABINFO; import com.medical.iqcc.module.baseInfo.entity.T_USERINFO; import com.medical.iqcc.module.baseInfo.service.T_DEPARTMENTINFOService; import com.medical.iqcc.module.baseInfo.service.T_LABINFOService; import com.medical.iqcc.module.baseInfo.service.T_USERINFOService; import com.medical.util.Json; import com.medical.util.PageInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.util.WebUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by JiangZ on 2015-06-01. */ @Controller @RequestMapping("/baseInfo") public class T_LABINFOController { private static final Logger LOG = LoggerFactory.getLogger(T_LABINFOController.class); @Autowired private T_LABINFOService t_labinfoService; @Autowired private T_USERINFOService t_userinfoService; @Autowired private T_DEPARTMENTINFOService t_departmentinfoService; @RequestMapping(value = "/saveLab", method = RequestMethod.POST) public Object save(HttpServletRequest request, HttpServletResponse response, String statue, T_LABINFO t_labinfo1, Model model) { Map map = new HashMap(); try { if (statue.equals("0")) { t_labinfoService.save(t_labinfo1); map.put("statue","0"); } if (statue.equals("1")) { t_labinfoService.update(t_labinfo1); map.put("statue", "1"); } } catch (Exception e) { e.printStackTrace(); } finally { } return map; } @RequestMapping("/lab") public Object lab() { return "baseInfo/lab"; } @RequestMapping("/delLab") public Object delLab(HttpServletRequest request, HttpServletResponse response, Long id, String ID1, T_LABINFO t_labinfo, Model model) { Map map = new HashMap(); Map map1 = new HashMap(); map1.put("LABID",id); List<T_USERINFO> t_userinfos = t_userinfoService.getListByMap(map1); List<T_DEPARTMENTINFO> t_departmentinfos = t_departmentinfoService.getListByMap(map1); if(t_userinfos.size()>0){ map.put("message","此实验室已被用户关联使用,请删除此用户再删除此实验室,或者直接停用该实验室"); } else if(t_departmentinfos.size()>0){ map.put("message","此实验室已被科室关联使用,请删除此科室再删除此实验室,或者直接停用该实验室"); } else { t_labinfoService.del(id); map.put("message","删除成功"); } return map; } protected Map getFilterMap(HttpServletRequest request) { Map map = WebUtils.getParametersStartingWith(request, "search_"); return map; } @RequestMapping("/jsonLab") public Object jsonList(HttpServletRequest request, HttpServletResponse response) { int currentPage = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page")); if (currentPage <= 0) { currentPage = 1; } int pageSize = request.getParameter("rows") == null ? 15 : Integer.parseInt(request.getParameter("rows")); Map filter = getFilterMap(request); int currentResult = (currentPage - 1) * pageSize; PageInfo pageInfo = new PageInfo(); pageInfo.setShowCount(pageSize); pageInfo.setCurrentResult(currentResult); pageInfo.setFilter(filter); pageInfo.setSortField("ID"); pageInfo.setOrder("asc"); pageInfo.setFilter(filter); List<T_LABINFO> t_labinfos = t_labinfoService.selectListPage(pageInfo); Json json = new Json(); //如果没有查询到数据,那么就清空表格 if (t_labinfos.size() == 0) { return null; } json.add("total", pageInfo.getTotalResult()); for (T_LABINFO t_labinfo : t_labinfos) { Json json_a = new Json(); json_a.add("ID", String.valueOf(t_labinfo.getId())); json_a.add("LABNAME", t_labinfo.getLABNAME()); json_a.add("PROVINCENAME", t_labinfo.getPROVINCENAME()); json_a.add("LABADDRESS", t_labinfo.getLABADDRESS()); json_a.add("LINKMAN", t_labinfo.getLINKMAN()); json_a.add("PHONE", t_labinfo.getPHONE()); json_a.add("CODE", t_labinfo.getCODE()); json_a.add("AREAID", String.valueOf(t_labinfo.getAREAID())); json_a.add("IFUSE", t_labinfo.getIFUSE()); json.add("rows", json_a); } response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter pw = null; try { pw = response.getWriter(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } pw.write(json.toString()); pw.flush(); return null; } @RequestMapping("/jsonLabByname") public Object jsonListByName(HttpServletRequest request, HttpServletResponse response, String LABNAME) { int currentPage = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page")); if (currentPage <= 0) { currentPage = 1; } int pageSize = request.getParameter("rows") == null ? 10 : Integer.parseInt(request.getParameter("rows")); int currentResult = (currentPage - 1) * pageSize; PageInfo pageInfo = new PageInfo(); pageInfo.setShowCount(pageSize); pageInfo.setCurrentResult(currentResult); pageInfo.setSortField("ID"); pageInfo.setOrder("asc"); Map filter = getFilterMap(request); filter.put("LABNAME", LABNAME); pageInfo.setFilter(filter); List<T_LABINFO> t_labinfos = t_labinfoService.selectListPage(pageInfo); Json json = new Json(); //如果没有查询到数据,那么就清空表格 if (t_labinfos.size() == 0) { return null; } json.add("total", pageInfo.getTotalResult()); for (T_LABINFO t_labinfo : t_labinfos) { Json json_a = new Json(); json_a.add("ID", String.valueOf(t_labinfo.getId())); json_a.add("LABNAME", t_labinfo.getLABNAME()); json_a.add("PROVINCENAME", t_labinfo.getPROVINCENAME()); json_a.add("LINKMAN", t_labinfo.getLINKMAN()); json_a.add("PHONE", t_labinfo.getPHONE()); json.add("rows", json_a); } response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter pw = null; try { pw = response.getWriter(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } pw.write(json.toString()); pw.flush(); return null; } }<file_sep>package com.medical.iqcc.module.baseInfo.web.webservice; import com.medical.iqcc.module.baseInfo.entity.ControlMerInfo; import com.medical.iqcc.module.baseInfo.service.ControlMerInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by JiangZ on 2015-06-15. */ @RestController @RequestMapping("/webService/controlMerInfo") public class ControMerInfo_WebServiceController { @Autowired private ControlMerInfoService controlMerInfoService; @RequestMapping("/getObject") public Object getControlMerInfo(@RequestParam(value="id",defaultValue="49") String id){ return controlMerInfoService.getObjById(Long.valueOf(id)); } @RequestMapping(method = RequestMethod.GET,headers="Accept=application/json") public List<ControlMerInfo> getList(){ Map map = new HashMap(); return controlMerInfoService.getListByMap(map); } } <file_sep>package com.medical.iqcc.module.business.web.controller; import com.medical.iqcc.module.business.entity.ProjInfo; import com.medical.iqcc.module.business.service.ProjInfoService; import com.medical.util.Json; import com.medical.util.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.util.WebUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Map; /** * Created by JiangZ on 2015-06-23. */ @Controller @RequestMapping("/projInfo") public class ProjInfoController { @Autowired private ProjInfoService projInfoService; @RequestMapping("/save") @ResponseBody public Object save(ProjInfo projInfo){ projInfoService.insert(projInfo); return projInfo; } @RequestMapping("/list") public Object list(){ return "business/projInfoList"; } @RequestMapping("/jsonList") public Object jsonList(HttpServletRequest request,HttpServletResponse response){ int currentPage = request.getParameter("page")==null?1:Integer.parseInt(request.getParameter("page")); if (currentPage<=0){ currentPage =1; } int pageSize = request.getParameter("rows")==null?10:Integer.parseInt(request.getParameter("rows")); Map filter = getFilterMap(request); int currentResult = (currentPage-1) * pageSize; PageInfo pageInfo = new PageInfo(); pageInfo.setShowCount(pageSize); pageInfo.setCurrentResult(currentResult); pageInfo.setFilter(filter); pageInfo.setSortField("id"); pageInfo.setOrder("asc"); List<ProjInfo> projInfos = projInfoService.selectListPage(pageInfo); if(pageInfo.getTotalResult() > 0){ Json json = new Json(); json.add("total", pageInfo.getTotalResult()); for(ProjInfo projInfo : projInfos){ Json json_a = new Json(); try { json_a.getObjectValue(projInfo,json_a); } catch (Exception e) { e.printStackTrace(); } json.add("rows", json_a); } response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter pw = null; try { pw = response.getWriter(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } pw.write(json.toString()); pw.flush(); } return null; } //从页面上获取到查询条件封装成Map private Map getFilterMap(HttpServletRequest request){ Map map = WebUtils.getParametersStartingWith(request, "search_"); return map; } } <file_sep>package com.medical.iqcc.security.jurisdiction.service.impl; import com.medical.iqcc.security.jurisdiction.entity.RoleAuthority; import com.medical.iqcc.security.jurisdiction.mapper.RoleAuthorityMapper; import com.medical.iqcc.security.jurisdiction.service.RoleAuthorityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * Created by JiangZ on 2015-06-29. */ @Service @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public class RoleAuthorityServiceImpl implements RoleAuthorityService { @Autowired private RoleAuthorityMapper roleAuthorityMapper; @Override @Transactional public int deleteByPrimaryKey(Long id) { return roleAuthorityMapper.deleteByPrimaryKey(id); } @Override @Transactional public int insert(RoleAuthority record) { return roleAuthorityMapper.insert(record); } @Override @Transactional public int insertSelective(RoleAuthority record) { return roleAuthorityMapper.insertSelective(record); } @Override public RoleAuthority selectByPrimaryKey(Long id) { return roleAuthorityMapper.selectByPrimaryKey(id); } @Override @Transactional public int updateByPrimaryKeySelective(RoleAuthority record) { return roleAuthorityMapper.updateByPrimaryKeySelective(record); } @Override @Transactional public int updateByPrimaryKey(RoleAuthority record) { return roleAuthorityMapper.updateByPrimaryKey(record); } }
e48378dd2806f9a2c8d3d55fc3a4921537f5a4e0
[ "Java", "INI" ]
31
Java
jiangzhe1984/meikang-p3
e580ead52f29f1cd0ada69c8204754c2efa8bacf
43c91e30fd7bc36bb644a6c7b00c3a526246e095
refs/heads/main
<file_sep>#define BUSMASTER_CONTROL_OFF 0 #define BUSMASTER_CONTROL_6502 1 #define BUSMASTER_CONTROL_SHIFTER 2 extern void busmaster_set_control(int busControl); extern int busmaster_get_control();<file_sep>#include "busmaster.h" #include "ic6502.h" #include "shifter.h" static int s_currentControl; void busmaster_set_control(int busControl) { switch(busControl) { case BUSMASTER_CONTROL_OFF: shifter_enable_bus(false); ic6502_enable_bus(false); break; case BUSMASTER_CONTROL_6502: shifter_enable_bus(false); ic6502_enable_bus(true); break; case BUSMASTER_CONTROL_SHIFTER: ic6502_enable_bus(false); shifter_enable_bus(true); break; default: break; } s_currentControl = busControl; } int busmaster_get_control() { return s_currentControl; }<file_sep>#include "hardware/uart.h" extern int uart_baudRate; extern int uart_irq; extern void uart_on_rx(); extern void uart_puts_ln(const char* szString); extern void uart_ready(); extern void uart_update(); <file_sep># LINK_01 The LINK_01 machine ## What is LINK_01 ? LINK_01 is my first hombrew computer. At the moment I'm not sure it will work... but I hope it will. ## Key Features * To explore 8-bit CPU technology by leveraging modern cheap microcontrollers. * To be fully software upgradeable * To let the microcontroller do the heavy lifting with I/O * To use modern compiler and debugging tools * To have fun programming the 6502 # Starting the monitor > minicom -b 115200 -o -D /dev/serial0 ctrl-a q to quit # Writing the EEPROM > minipro -p AT28C64B -w ROMFILE # Outputting a ROM > hexdump -C FILE # Raspberry Pi pins |pin|use| |---|---| |6|GND (board)| |8|UART-TX| |10|UART-RX| |18|SWDIO| |20|GND| |22|SWCLK| # Pico pins |use|GPIO|pin||pin|GPIO|use| |---|---|---|---|---|---|---| |UART TX|0|1|###|40|-|5V IN| |UART RX|1|2|###|39|-|| |GND|-|3|###|38|-|GND| ||2|4|###|37|-|| ||3|5|###|36|-|| ||4|6|###|35|-|| ||5|7|###|34|28|6502 PHI-2| |GND|-|8|###|33|-|GND| ||6|9|###|32|27|6502 RESB| ||7|10|###|31|26|6502 BE| ||8|11|###|30|-|| ||9|12|###|29|22|6502 IRQB| |GND|-|13|###|28|-|GND| |6502 RWB|10|14|###|27|21|6502 NMIB| |SHIFTER OUT|11|15|###|26|20|SHIFTER OE| |SHIFTER IN|12|16|###|25|19|SHIFTER S0| |VGA-B|13|17|###|24|18|SHIFTER S1| |GND|-|18|###|23|-|GND| |VGA-G|14|19|###|22|17|VGA v-sync| |VGA-R|15|20|###|21|16|VGA h-sync| Pin counts (available 28) UART 2 VGA 5 6502 5 Shifter 5 # VGA pins |pin|use| |---|---| |1|R| |2|G| |3|B| |4|-| |5|GND| |6|GND| |7|GND| |8|GND| |9|-| |10|GND| |11|-| |12|-| |13|H-SYNC| |14|V-SYNC| |15|-| # 65c02 pins |use|pin||pin|use| |---|---|---|---|---| |VPB|1|XXX|40|RESB| |RDY|2|XXX|39|PHI2O| |PHI1O|3|XXX|38|SOB| |IRQB|4|XXX|37|PHI2| |MLB|5|XXX|36|BE| |NMIB|6|XXX|35|NC| |SYNC|7|XXX|34|RWB| |VDD|8|XXX|33|D0| |A0|9|XXX|32|D1| |A1|10|XXX|31|D2| |A2|11|XXX|30|D3| |A3|12|XXX|29|D4| |A4|13|XXX|28|D5| |A5|14|XXX|27|D6| |A6|15|XXX|26|D7| |A7|16|XXX|25|A15| |A8|17|XXX|24|A14| |A9|18|XXX|23|A13| |A10|19|XXX|22|A12| |A11|20|XXX|21|VSS| # Voltage Shifter 1 - TSX0108E |pin|function| |---|---| |1|6502 PHI2| |2|6502 RESB| |3|6502 BE| |4|6502 IRQB| |5|6502 NMIB| |6|SHIFTER OE| |7|SHIFTER S0| |8|SHIFTER S1| # Voltage Shifter 2 - TSX0108E |pin|function| |---|---| |1|SHIFTER IN| |2|SHIFTER OUT| |3|6502 RWB| |4|| |5|| |6|| |7|| |8|| # Shift register - SN74F299N |use|pin|---|pin|use| |---|---|---|---|---| ||1|###|20|| ||2|###|19|| ||3|###|18|| ||4|###|17|| ||5|###|16|| ||6|###|15|| ||7|###|14|| ||8|###|13|| ||9|###|12|| ||10|###|11|| # AT28C64B EEPROM |pin|num|---|num|pin| |---|---|---|---|---| |NC|1|###|28|VCC| |A12|2|###|27|~WE| |A7|3|###|26|NC| |A6|4|###|25|A8| |A5|5|###|24|A9| |A4|6|###|23|A11| |A3|7|###|22|~OE| |A2|8|###|21|A10| |A1|9|###|20|~CE| |A0|10|###|19|I/O7| |I/O0|11|###|18|I/O6| |I/O1|12|###|17|I/O5| |I/O2|13|###|16|I/O4| |GND|14|###|15|I/O3| # AS6C6264 8K RAM <file_sep> /* SN74F299N explorer */ /* MODE CLR S1 S0 OE1 OE2 CLK SL SR QA QB QC QD QE QF QG QH QA' QH' Clear L X L L L X X X L L L L L L L L L L L L X L L X X X L L L L L L L L L L L H H X X X X X X X X X X X X X L L Hold H L L L L X X X QA0 QB0 QC0 QD0 QE0 QF0 QG0 QH0 QA0 QH0 H X X L L L X X QA0 QB0 QC0 QD0 QE0 QF0 QG0 QH0 QA0 QH0 < Shift H L H L L ^ X H H QAn QBn QCn QDn QEn QFn QGn H QGn Right H L H L L ^ X L L QAn QBn QCn QDn QEn QFn QGn L QGn Shift H H L L L ^ H X QBn QCn QDn QEn QFn QGn QHn H QBn H < Left H H L L L ^ L X QBn QCn QDn QEn QFn QGn QHn L QBn L < Load H H H X X ^ X X a b c d e f g h a h < */ #define PIN_S0 0 #define PIN_OE1 1 #define PIN_OE2 2 #define PIN_G 3 #define PIN_E 4 #define PIN_C 5 #define PIN_A 6 #define PIN_QA 7 #define PIN_CLR 8 #define PIN_SR 9 #define PIN_CLK 10 #define PIN_B 11 #define PIN_D 12 #define PIN_F 13 #define PIN_H 14 #define PIN_QH 15 #define PIN_SL 16 #define PIN_S1 17 int pin[18] = { 52, 50, 48, 46, 44, 42, 40, 38, 36, 37, 39, 41, 43, 45, 47, 49, 51, 53 }; void setup() { Serial.begin(112500); // pin directions pinMode(pin[PIN_S0], OUTPUT); pinMode(pin[PIN_OE1], OUTPUT); pinMode(pin[PIN_OE2], OUTPUT); pinMode(pin[PIN_CLR], OUTPUT); pinMode(pin[PIN_SR], OUTPUT); pinMode(pin[PIN_CLK], OUTPUT); pinMode(pin[PIN_SL], OUTPUT); pinMode(pin[PIN_S1], OUTPUT); pinMode(pin[PIN_QA], INPUT); pinMode(pin[PIN_QH], INPUT); set_bus(INPUT); } void set_bus(int value) { pinMode(pin[PIN_A], value); pinMode(pin[PIN_B], value); pinMode(pin[PIN_C], value); pinMode(pin[PIN_D], value); pinMode(pin[PIN_E], value); pinMode(pin[PIN_F], value); pinMode(pin[PIN_G], value); pinMode(pin[PIN_H], value); } void set_bus_value(int value) { digitalWrite(pin[PIN_A], value & 0x01); digitalWrite(pin[PIN_B], value & 0x02); digitalWrite(pin[PIN_C], value & 0x04); digitalWrite(pin[PIN_D], value & 0x08); digitalWrite(pin[PIN_E], value & 0x10); digitalWrite(pin[PIN_F], value & 0x20); digitalWrite(pin[PIN_G], value & 0x40); digitalWrite(pin[PIN_H], value & 0x80); } int read_bus_value() { int out = 0; out += digitalRead(pin[PIN_A]) == HIGH ? 0x01 : 0; out += digitalRead(pin[PIN_B]) == HIGH ? 0x02 : 0; out += digitalRead(pin[PIN_C]) == HIGH ? 0x04 : 0; out += digitalRead(pin[PIN_D]) == HIGH ? 0x08 : 0; out += digitalRead(pin[PIN_E]) == HIGH ? 0x10 : 0; out += digitalRead(pin[PIN_F]) == HIGH ? 0x20 : 0; out += digitalRead(pin[PIN_G]) == HIGH ? 0x40 : 0; out += digitalRead(pin[PIN_H]) == HIGH ? 0x80 : 0; return out; } void clock() { digitalWrite(pin[PIN_CLK], LOW); digitalWrite(pin[PIN_CLK], HIGH); } void load() { digitalWrite(pin[PIN_CLR], HIGH); digitalWrite(pin[PIN_S1], HIGH); digitalWrite(pin[PIN_S0], HIGH); clock(); } void hold() { digitalWrite(pin[PIN_CLR], HIGH); digitalWrite(pin[PIN_S0], LOW); digitalWrite(pin[PIN_S1], LOW); digitalWrite(pin[PIN_OE1], LOW); digitalWrite(pin[PIN_OE2], LOW); } void left() { digitalWrite(pin[PIN_CLR], HIGH); digitalWrite(pin[PIN_S1], HIGH); digitalWrite(pin[PIN_S0], LOW); digitalWrite(pin[PIN_OE1], LOW); digitalWrite(pin[PIN_OE2], LOW); // digitalWrite(pin[PIN_SL], HIGH); clock(); } void right() { digitalWrite(pin[PIN_CLR], HIGH); digitalWrite(pin[PIN_S1], LOW); digitalWrite(pin[PIN_S0], HIGH); digitalWrite(pin[PIN_OE1], LOW); digitalWrite(pin[PIN_OE2], LOW); // digitalWrite(pin[PIN_SR], HIGH); clock(); } void read_random_value() { // set bus to random value int write_value = random(0,256); set_bus(OUTPUT); set_bus_value(write_value); load(); // hold the value hold(); // set bus to write set_bus(INPUT); // roll value and rebuild number int read_value = 0; for(int i=0 ; i<8 ; i++) { read_value <<= 1; read_value += digitalRead(pin[PIN_H]) == HIGH ? 1 : 0; right(); } char buffer[32]; sprintf(buffer, "bus write %02x shift read %02x", write_value, read_value); Serial.println(buffer); } void write_random_value() { set_bus(INPUT); int write_value = random(0,256); // shift in a value for(int i=0 ; i<8 ; i++) { digitalWrite(pin[PIN_SR], (write_value & (0x80>>i)) == 0 ? LOW : HIGH ); right(); } // read value from bus int read_value = read_bus_value(); char buffer[32]; sprintf(buffer, "shift write %02x bus read %02x", write_value, read_value); Serial.println(buffer); } void loop() { Serial.println("---"); read_random_value(); write_random_value(); delay(1000); } <file_sep>user_name = input("What is your name ?") if user_name == "Bob": print("You are Bob!") else: print("You are not Bob!")<file_sep>#include <stdio.h> #include "pico/stdlib.h" #include "hardware/irq.h" #include "configuration.h" #include "uart.h" #include "ic6502.h" #include "system.h" #include "busmaster.h" #include "usercommand.h" #include "test.h" static void initUART() { // UART setup uart_init(UART_ID, UART_BAUD_RATE); gpio_set_function(UART_TX_PIN, GPIO_FUNC_UART); gpio_set_function(UART_RX_PIN, GPIO_FUNC_UART); uart_baudRate = uart_set_baudrate(UART_ID, UART_BAUD_RATE); uart_set_hw_flow(UART_ID, false, false); uart_set_format(UART_ID, UART_DATA_BITS, UART_STOP_BITS, UART_PARITY); uart_set_fifo_enabled(UART_ID, false); // TODO: probably want this on soon if(UART_ID == uart0) { uart_irq = UART0_IRQ; } else { uart_irq = UART1_IRQ; } irq_set_exclusive_handler(uart_irq, uart_on_rx); irq_set_enabled(uart_irq, true); uart_set_irq_enables(UART_ID, true, false); } int main() { stdio_init_all(); initUART(); uart_puts_ln("======================"); uart_puts_ln("Welcome to the LINK_01"); uart_puts_ln("======================"); uart_puts_ln(""); sleep_ms(1000); // just in case we power up first, let the rest of the board catch up... // initialise all the things ic6502_init(); shifter_init(); busmaster_set_control(BUSMASTER_CONTROL_OFF); ic6502_reset(); usercommand_init(); system_main(); uart_puts_ln("Exiting main() - this should never happen !"); }<file_sep>#include "pico/stdlib.h" extern void ic6502_init(); extern void ic6502_reset(); extern void ic6502_enable_bus(bool enable); // Ideally only call this from system.c extern void ic6502_tick(uint64_t microSeconds); <file_sep>#include "pico/stdlib.h" #include "test.h" #include "configuration.h" #include "ic6502.h" #include "shifter.h" #include "busmaster.h" void do6502Test(int iter) { while (iter-- > 0) { ic6502_tick(10000); } } void doShifterTest(int iter) { shifter_init(); while(true) { gpio_put(SHIFTER_IN_PIN, 1); for(int i=0 ; i<8 ; i++) { ic6502_tick(10000); ic6502_tick(10000); } gpio_put(SHIFTER_IN_PIN, 0); for(int i=0 ; i<8 ; i++) { ic6502_tick(10000); ic6502_tick(10000); } } } void runTest() { // busmaster_set_control(BUSMASTER_CONTROL_OFF); // sleep_ms(1000); // busmaster_set_control(BUSMASTER_CONTROL_SHIFTER); // sleep_ms(1000); // busmaster_set_control(BUSMASTER_CONTROL_6502); // sleep_ms(1000); busmaster_set_control(BUSMASTER_CONTROL_6502); do6502Test(99999999); busmaster_set_control(BUSMASTER_CONTROL_SHIFTER); doShifterTest(1000000); } <file_sep>#include <stdio.h> #include "pico/stdlib.h" #include "shifter.h" #include "configuration.h" #include "busmaster.h" #include "ic6502.h" #include "uart.h" void shifter_init() { // OE gpio_init(SHIFTER_OE_PIN); gpio_set_dir(SHIFTER_OE_PIN, GPIO_OUT); gpio_put(SHIFTER_OE_PIN, 0); // S0 gpio_init(SHIFTER_S0_PIN); gpio_set_dir(SHIFTER_S0_PIN, GPIO_OUT); gpio_put(SHIFTER_S0_PIN, 0); // S1 gpio_init(SHIFTER_S1_PIN); gpio_set_dir(SHIFTER_S1_PIN, GPIO_OUT); gpio_put(SHIFTER_S1_PIN, 1); // IN gpio_init(SHIFTER_IN_PIN); gpio_set_dir(SHIFTER_IN_PIN, GPIO_OUT); gpio_put(SHIFTER_IN_PIN, 1); // OUT gpio_init(SHIFTER_OUT_PIN); gpio_set_dir(SHIFTER_OUT_PIN, GPIO_IN); // CLK gpio_init(SHIFTER_CLK_PIN); gpio_set_dir(SHIFTER_CLK_PIN, GPIO_OUT); gpio_put(SHIFTER_CLK_PIN, 1); // BUS DIR gpio_init(SHIFTER_BUS_DIR_PIN); gpio_set_dir(SHIFTER_BUS_DIR_PIN, GPIO_OUT); gpio_put(SHIFTER_BUS_DIR_PIN, 1); // BUS DIR gpio_init(SHIFTER_BUS_OE_PIN); gpio_set_dir(SHIFTER_BUS_OE_PIN, GPIO_OUT); gpio_put(SHIFTER_BUS_OE_PIN, 1); } void shifter_enable_bus(bool enable) { gpio_put(SHIFTER_OE_PIN, enable ? 0 : 1); } void shifter_tick() { gpio_put(SHIFTER_CLK_PIN, 0); gpio_put(SHIFTER_CLK_PIN, 1); } void shifter_readbus(uint16_t *pAddress, uint8_t *pData) { *pAddress = 0; *pData = 0; // load gpio_put(SHIFTER_S0_PIN, 1); gpio_put(SHIFTER_S1_PIN, 1); gpio_put(SHIFTER_OE_PIN, 0); shifter_tick(); // hold gpio_put(SHIFTER_S0_PIN, 0); gpio_put(SHIFTER_S1_PIN, 0); ic6502_enable_bus(false); // store bus master and set to shifter // int oldBus = busmaster_get_control(); // busmaster_set_control(BUSMASTER_CONTROL_SHIFTER); // shift out uint32_t val = 0; // set left shift gpio_put(SHIFTER_S0_PIN, 0); gpio_put(SHIFTER_S1_PIN, 1); for(int i=0 ; i<24 ; i++) { val <<= 1; val += (gpio_get(SHIFTER_IN_PIN) == 0 ? 0 : 1); shifter_tick(); } // restore bus master // busmaster_set_control(oldBus); gpio_put(SHIFTER_OE_PIN, 1); ic6502_enable_bus(true); char buffer[32]; sprintf(buffer, "%08x", val); uart_puts_ln(buffer); } <file_sep>#include "pico/stdlib.h" extern void system_main(); extern void system_halt(); extern void system_continue(); extern void system_clock_tick(); extern void system_set_tick_rate(int rate); extern uint8_t system_read_memory(uint16_t address); extern void system_write_memory(uint16_t address, uint8_t data); <file_sep>#include "pico/stdlib.h" extern void usercommand_init(); extern void usercommand_registerautocomplete(const char* szString); extern void usercommand_add(const char* szCommand); <file_sep>#include <stdio.h> #include "usercommand.h" #include "uart.h" #include "system.h" #include "ic6502.h" void usercommand_init() { } void usercommand_add(const char* szCommand) { if(strcmp(szCommand, "help") == 0) { // print help uart_puts_ln(""); uart_puts_ln("HELP:"); uart_puts_ln(""); uart_puts_ln("NO ts <x> : Tick speed in Hz."); uart_puts_ln("h : halt"); uart_puts_ln("c : continue"); uart_puts_ln("reset : reset"); uart_puts_ln("t : single tick"); uart_puts_ln("rb : read busses"); uart_ready(); } else if(strcmp(szCommand, "h") == 0) { system_halt(); } else if(strcmp(szCommand, "c") == 0) { system_continue(); } else if(strcmp(szCommand, "reset") == 0) { ic6502_reset(); } else if(strcmp(szCommand, "t") == 0) { ic6502_tick(100000); } else if(strncmp(szCommand, "tr ", 3) == 0) { int count; sscanf(szCommand, "tr %d", &count); system_set_tick_rate(count); } else if(strcmp(szCommand, "rb") == 0) { uint16_t address; uint8_t data; shifter_readbus(&address, &data); } } void usercommand_registerautocomplete(const char* szString) { } <file_sep>#include "pico/stdlib.h" #include "hardware/uart.h" #include "uart.h" #include "configuration.h" #include "usercommand.h" #define MAX_READ_BUFFER 256 // TODO - Need a history buffer here too. static uint8_t s_inputBuffer[MAX_READ_BUFFER]; static uint16_t s_inputBufferPos = 0; static bool s_inputBufferReady = false; int uart_baudRate; int uart_irq; /* 13 RETURN 27 91 68 LEFT 27 91 67 RIGHT 27 91 65 UP 27 91 66 DOWN 27 91 51 DELETE 8 BACKSPCE 27 ESC */ void uart_on_rx() { static uint8_t keyCodeCache[3]; static int iKeyCodeCache = 0; // check for command ready to be submitted... if(s_inputBufferReady) return; while(uart_is_readable(UART_ID)) { keyCodeCache[iKeyCodeCache++] = uart_getc(UART_ID); // uart_putc(UART_ID, ch); // char buffer[8]; // sprintf(buffer, "%d ", keyCodeCache[iKeyCodeCache-1]); // uart_puts(UART_ID, buffer); } // key has been read - filter out special cases switch(iKeyCodeCache) { case 1: if(keyCodeCache[0] == 27) // esc { } else if(keyCodeCache[0] == 13) { // RETURN // terminate the current command s_inputBuffer[s_inputBufferPos] = 0; // process the command s_inputBufferReady = true; uart_ready(); iKeyCodeCache = 0; } else if(keyCodeCache[0] == 8) { // BACKSPACE uart_putc(UART_ID, 0x08); uart_putc(UART_ID, ' '); uart_putc(UART_ID, 0x08); iKeyCodeCache = 0; } else { // normal characters if(s_inputBufferPos < MAX_READ_BUFFER-1) { s_inputBuffer[s_inputBufferPos++] = keyCodeCache[0]; uart_putc(UART_ID, keyCodeCache[0]); iKeyCodeCache = 0; } } break; case 2: break; case 3: if((keyCodeCache[0] == 27) && (keyCodeCache[1] == 91)) { // special if(keyCodeCache[2] == 68) { // LEFT uart_puts(UART_ID, "[LEFT]"); } else if(keyCodeCache[2] == 67) { // RIGHT uart_puts(UART_ID, "[RIGHT]"); } else if(keyCodeCache[2] == 65) { // UP uart_puts(UART_ID, "[UP]"); } else if(keyCodeCache[2] == 66) { // DOWN uart_puts(UART_ID, "[DOWN]"); } else if(keyCodeCache[2] == 51) { // DELETE uart_puts(UART_ID, "[DELETE]"); } iKeyCodeCache = 0; } break; } } void uart_ready() { uart_puts(UART_ID, "\n\r"); uart_puts(UART_ID, "> "); } void uart_puts_ln(const char* szString) { uart_puts(UART_ID, szString); uart_puts(UART_ID, "\n\r"); } void uart_update() { if(s_inputBufferReady) { // submit command usercommand_add(s_inputBuffer); s_inputBufferPos = 0; s_inputBufferReady = false; } }<file_sep>/* EEPROM AT28C64B */ // 13 address lines = 8K int pin_A[13] = {29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53}; // 8 data lines int pin_D[8] = {2, 3, 4, 5, 6, 7, 8, 9}; int pin_CE = 27; int pin_OE = 25; int pin_WE = 23; void set_data_read() { // set data to read for(int i=0 ; i<8 ; i++) { pinMode(pin_D[i], INPUT); } } void set_data_write() { // set data to write for(int i=0 ; i<8 ; i++) { pinMode(pin_D[i], OUTPUT); } } void writebytes() { digitalWrite(pin_CE, HIGH); digitalWrite(pin_OE, HIGH); digitalWrite(pin_WE, HIGH); set_data_write(); delay(100); // write some data to the EEPROM for(int i=0 ; i<256 ; i++) { // set up the data bits for(int b=0 ; b<8 ; b++) { digitalWrite(pin_D[b], i & (1 << b) ? HIGH : LOW); } // set up the address bits for(int b=0 ; b<13 ; b++) { digitalWrite(pin_A[b], i & (1 << b) ? HIGH : LOW); } digitalWrite(pin_WE, LOW); digitalWrite(pin_WE, HIGH); delay(1); } } void readbytes() { set_data_read(); digitalWrite(pin_CE, LOW); digitalWrite(pin_OE, LOW); digitalWrite(pin_WE, HIGH); for(int b=0 ; b<8192 ; b++) { // set address for(int addresspin=0 ; addresspin<13 ; addresspin++) { if(b & (1 << addresspin)) digitalWrite(pin_A[addresspin], HIGH); else digitalWrite(pin_A[addresspin], LOW); } // read data int val = 0; for(int datapin=0 ; datapin<8 ; datapin++) { if(digitalRead(pin_D[datapin])) val += 1 << datapin; } char buffer[256]; sprintf(buffer, "%04x %02x\n", b, val); Serial.print(buffer); } } void setup() { Serial.begin(9600); delay(2000); for(int i=0 ; i<13 ; i++) { pinMode(pin_A[i], OUTPUT); } pinMode(pin_CE, OUTPUT); pinMode(pin_OE, OUTPUT); pinMode(pin_WE, OUTPUT); // writebytes(); readbytes(); } void loop() { } <file_sep>extern void runTest(void); <file_sep>#define BUS_SIZE 8 int bus_a_pins[BUS_SIZE] = {39, 41, 43, 45, 47, 49, 51, 53}; int bus_b_pins[BUS_SIZE] = {38, 40, 42, 44, 46, 48, 50, 52}; int dir_pin = 37; int oe_pin = 36; void set_a_to_b() { digitalWrite(dir_pin, HIGH); for(int i=0 ; i<BUS_SIZE ; i++) { pinMode(bus_a_pins[i], OUTPUT); pinMode(bus_b_pins[i], INPUT); } } void set_b_to_a() { digitalWrite(dir_pin, LOW); for(int i=0 ; i<BUS_SIZE ; i++) { pinMode(bus_a_pins[i], INPUT); pinMode(bus_b_pins[i], OUTPUT); } } void set_output_enable(bool enable) { if(enable) { digitalWrite(oe_pin, LOW); } else { digitalWrite(oe_pin, HIGH); } } void write_a(int value) { for(int i=0 ; i<BUS_SIZE ; i++) { digitalWrite(bus_a_pins[i], value & (1<<i) ? HIGH: LOW); } } int read_a() { int ret = 0; for(int i=0 ; i<BUS_SIZE ; i++) { ret += digitalRead(bus_a_pins[i]) == HIGH ? 1 << i : 0; } return ret; } void write_b(int value) { for(int i=0 ; i<BUS_SIZE ; i++) { digitalWrite(bus_b_pins[i], value & (1<<i) ? HIGH: LOW); } } int read_b() { int ret = 0; for(int i=0 ; i<BUS_SIZE ; i++) { ret += digitalRead(bus_b_pins[i]) == HIGH ? 1 << i : 0; } return ret; } void setup() { Serial.begin(115200); pinMode(dir_pin, OUTPUT); pinMode(oe_pin, OUTPUT); // buffer pins are set in the read/write methods } void loop() { // test a->b works delay(10); set_output_enable(true); set_a_to_b(); for(int i=0 ; i<10 ; i++) { int val = random(0,256); write_a(val); int readval = read_b(); if(val != readval) { Serial.println("a-b enabled failed"); } } write_a(0); // clear the values // test a->b disabled delay(10); set_output_enable(false); set_a_to_b(); for(int i=0 ; i<10 ; i++) { int val = random(1,256); write_a(val); int readval = read_b(); if(0 != readval) { Serial.println("a-b disabled failed"); } } // test b->a works delay(10); set_output_enable(true); set_b_to_a(); for(int i=0 ; i<10 ; i++) { int val = random(0,256); write_b(val); int readval = read_a(); if(val != readval) { Serial.println("b-a enabled failed"); } } write_b(0); // clear the values // test b->a disabled delay(10); set_output_enable(false); set_b_to_a(); for(int i=0 ; i<10 ; i++) { int val = random(1,256); write_b(val); int readval = read_a(); if(0 != readval) { Serial.println("b-a disabled failed"); } } delay(1000); } <file_sep>cmake_minimum_required(VERSION 3.13) include(pico_sdk_import.cmake) project(pico_kernel C CXX ASM) set(CMAKE_C_STANDARD 11) set(CMAKE_CXX_STANDARD 17) pico_sdk_init() add_executable(pico_kernel main.c uart.c test.c ic6502.c shifter.c busmaster.c system.c usercommand.c ) pico_enable_stdio_uart(pico_kernel 1) pico_add_extra_outputs(pico_kernel) target_link_libraries(pico_kernel pico_stdlib) <file_sep>#define UART_ID uart0 #define UART_BAUD_RATE 115200 #define UART_DATA_BITS 8 #define UART_STOP_BITS 1 #define UART_PARITY UART_PARITY_NONE // serial comms #define UART_TX_PIN 0 #define UART_RX_PIN 1 // 8-bit bus #define IC6502_PHI2_PIN 28 #define IC6502_RESB_PIN 27 /// Bus Enable /// /// LOW - high impedance /// HIGH - bus enabled #define IC6502_BE_PIN 26 #define IC6502_IRQB_PIN 22 #define IC6502_NMIB_PIN 21 #define IC6502_RWB_PIN 10 // Shifter complex #define SHIFTER_OE_PIN 20 #define SHIFTER_S0_PIN 19 #define SHIFTER_S1_PIN 18 #define SHIFTER_IN_PIN 12 #define SHIFTER_OUT_PIN 11 #define SHIFTER_CLK_PIN 9 #define SHIFTER_BUS_DIR_PIN 8 #define SHIFTER_BUS_OE_PIN 7 // 3V3 bus #define VGA_VSYNC 17 #define VGA_HSYNC 16 #define VGA_R 15 #define VGA_G 14 #define VGA_B 13 #define UNASSIGNED_1 8 #define UNASSIGNED_2 7 #define UNASSIGNED_3 6 #define UNASSIGNED_4 5 #define UNASSIGNED_5 4 #define UNASSIGNED_6 3 #define UNASSIGNED_7 2 <file_sep>#include "system.h" #include "ic6502.h" #include "uart.h" #include "shifter.h" static uint64_t tickDelayMicroSeconds; static bool fQuit = false; static uint64_t tickDelay = 500000; static uint64_t oldTickDelay = 0; void system_main() { uart_ready(); while(!fQuit) { if(tickDelay > 0) { ic6502_tick(tickDelay); } uart_update(); } } void system_halt() { if(tickDelay > 0) { oldTickDelay = tickDelay; tickDelay = 0; } } void system_continue() { tickDelay = oldTickDelay; } void system_clock_tick() { } void system_set_tick_rate(int rate) { tickDelay = 1000000 / rate; int bp=0; bp++; } uint8_t system_read_memory(uint16_t address) { return 0; } void system_write_memory(uint16_t address, uint8_t data) { } <file_sep> //--------------------------------- // --- read only pins //--------------------------------- // Address bus #define A_0 9 #define A_1 10 #define A_2 11 #define A_3 12 #define A_4 13 #define A_5 14 #define A_6 15 #define A_7 16 #define A_8 17 #define A_9 18 #define A_10 19 #define A_11 20 #define A_12 22 #define A_13 23 #define A_14 24 #define A_15 25 // Vector pull #define VPB 1 // Clock phase 1 out #define PHI1O 3 // Clock phase 2 out #define PHI2O 39 // Memory lock #define MLB 5 // Syncronize with opcode fetch #define SYNC 7 // Read/Write #define RWB 34 //--------------------------------- // --- write only pins //--------------------------------- // Interrupt request #define IRQB 4 // Non-Maskable interrupt #define NMIB 6 // Bus enable #define BE 36 // Clock input #define PHI2 37 // Set overflow #define SOB 38 // Reset #define RESB 40 //--------------------------------- // --- read/write pins //--------------------------------- // Ready #define RDY 2 // Data bus #define D_7 26 #define D_6 27 #define D_5 28 #define D_4 29 #define D_3 30 #define D_2 31 #define D_1 32 #define D_0 33 //--------------------------------- // --- non-functional pins //--------------------------------- // 5V #define VDD 8 // No-connect #define NC 35 // 0V #define VSS 21 // these are the actual pin numbers for the chip pins - starts from index 1 int pin[41] = { -1, 15, 14, 2, 3, 4, 5, 6, -1, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, -1, 47, 49, 51, 53, 36, 34, 32, 30, 28, 26, 24, 22, 7, -1, 8, 9, 10, 11, 12}; int bTickState = LOW; void setup() { Serial.begin(115200); // setup the RO pins pinMode(pin[A_0], INPUT); pinMode(pin[A_1], INPUT); pinMode(pin[A_2], INPUT); pinMode(pin[A_3], INPUT); pinMode(pin[A_4], INPUT); pinMode(pin[A_5], INPUT); pinMode(pin[A_6], INPUT); pinMode(pin[A_7], INPUT); pinMode(pin[A_8], INPUT); pinMode(pin[A_9], INPUT); pinMode(pin[A_10], INPUT); pinMode(pin[A_11], INPUT); pinMode(pin[A_12], INPUT); pinMode(pin[A_13], INPUT); pinMode(pin[A_14], INPUT); pinMode(pin[A_15], INPUT); pinMode(pin[VPB], INPUT); pinMode(pin[PHI1O], INPUT); pinMode(pin[PHI2O], INPUT); pinMode(pin[MLB], INPUT); pinMode(pin[SYNC], INPUT); pinMode(pin[RWB], INPUT); // setup the WO pins pinMode(pin[RWB], OUTPUT); pinMode(pin[NMIB], OUTPUT); pinMode(pin[BE], OUTPUT); pinMode(pin[PHI2], OUTPUT); pinMode(pin[SOB], OUTPUT); pinMode(pin[RESB], OUTPUT); // set the RW pins to read for now... pinMode(pin[RDY], INPUT); pinMode(pin[D_0], INPUT); pinMode(pin[D_1], INPUT); pinMode(pin[D_2], INPUT); pinMode(pin[D_3], INPUT); pinMode(pin[D_4], INPUT); pinMode(pin[D_5], INPUT); pinMode(pin[D_6], INPUT); pinMode(pin[D_7], INPUT); // temp set_data(0xea); Serial.println("6502 Test Initialised..."); } void print_status() { int address = get_address(); // print address char buffer[64]; sprintf(buffer, "%04x", address); Serial.println(buffer); } void set_data(int data) { digitalWrite(pin[D_0], data & 0x01 ? HIGH : LOW); digitalWrite(pin[D_1], data & 0x02 ? HIGH : LOW); digitalWrite(pin[D_2], data & 0x04 ? HIGH : LOW); digitalWrite(pin[D_3], data & 0x08 ? HIGH : LOW); digitalWrite(pin[D_4], data & 0x10 ? HIGH : LOW); digitalWrite(pin[D_5], data & 0x20 ? HIGH : LOW); digitalWrite(pin[D_6], data & 0x40 ? HIGH : LOW); digitalWrite(pin[D_7], data & 0x80 ? HIGH : LOW); } int get_data() { int ret = 0; ret += digitalRead(pin[D_0]) == HIGH ? 0x01 : 0; ret += digitalRead(pin[D_1]) == HIGH ? 0x02 : 0; ret += digitalRead(pin[D_2]) == HIGH ? 0x04 : 0; ret += digitalRead(pin[D_3]) == HIGH ? 0x08 : 0; ret += digitalRead(pin[D_4]) == HIGH ? 0x10 : 0; ret += digitalRead(pin[D_5]) == HIGH ? 0x20 : 0; ret += digitalRead(pin[D_6]) == HIGH ? 0x40 : 0; ret += digitalRead(pin[D_7]) == HIGH ? 0x80 : 0; return ret; } int get_address() { int ret = 0; ret += digitalRead(pin[A_0]) == HIGH ? 0x0001 : 0; ret += digitalRead(pin[A_1]) == HIGH ? 0x0002 : 0; ret += digitalRead(pin[A_2]) == HIGH ? 0x0004 : 0; ret += digitalRead(pin[A_3]) == HIGH ? 0x0008 : 0; ret += digitalRead(pin[A_4]) == HIGH ? 0x0010 : 0; ret += digitalRead(pin[A_5]) == HIGH ? 0x0020 : 0; ret += digitalRead(pin[A_6]) == HIGH ? 0x0040 : 0; ret += digitalRead(pin[A_7]) == HIGH ? 0x0080 : 0; ret += digitalRead(pin[A_8]) == HIGH ? 0x0100 : 0; ret += digitalRead(pin[A_9]) == HIGH ? 0x0200 : 0; ret += digitalRead(pin[A_10]) == HIGH ? 0x0400 : 0; ret += digitalRead(pin[A_11]) == HIGH ? 0x0800 : 0; ret += digitalRead(pin[A_12]) == HIGH ? 0x1000 : 0; ret += digitalRead(pin[A_13]) == HIGH ? 0x2000 : 0; ret += digitalRead(pin[A_14]) == HIGH ? 0x4000 : 0; ret += digitalRead(pin[A_15]) == HIGH ? 0x8000 : 0; return ret; } void loop() { bool bTick = true; // read the monitor input if(Serial.available()) { // parse command line } if(bTick) { if(bTickState == LOW) { digitalWrite(pin[PHI2], HIGH); bTickState = HIGH; } else { digitalWrite(pin[PHI2], LOW); bTickState = LOW; } } print_status(); } <file_sep># Memory Map |Range|Use| |---|---| |0x0000-0x00ff|Zero Page| |0x0100-0x01ff|Stack| |0x0200-0x03ff|Reserved for Kernel state| |0x0400-0x5fff|User| |0x6000-0x7fff|Video RAM| |0x8000-0xdfff|Unavailable| |0xe000-0xffff|8K Kernel ROM| <file_sep>#include "pico/stdlib.h" #include "uart.h" #include "configuration.h" #include "ic6502.h" static bool s_tickState = false; void ic6502_init() { // clock pin gpio_init(IC6502_PHI2_PIN); gpio_set_dir(IC6502_PHI2_PIN, GPIO_OUT); // reset gpio_init(IC6502_RESB_PIN); gpio_set_dir(IC6502_RESB_PIN, GPIO_OUT); // bus enable gpio_init(IC6502_BE_PIN); gpio_set_dir(IC6502_BE_PIN, GPIO_OUT); // IRQB gpio_init(IC6502_IRQB_PIN); gpio_set_dir(IC6502_IRQB_PIN, GPIO_OUT); // NMIB gpio_init(IC6502_NMIB_PIN); gpio_set_dir(IC6502_NMIB_PIN, GPIO_OUT); // RWB - input... is driven by 6502 // gpio_init(IC6502_RWB_PIN); // gpio_set_dir(IC6502_NMIB_PIN, GPIO_IN); } void ic6502_reset() { uart_puts_ln("6502: Begin Reset"); gpio_put(IC6502_RESB_PIN, 0); gpio_put(IC6502_IRQB_PIN, 1); gpio_put(IC6502_NMIB_PIN, 1); ic6502_enable_bus(true); for(int i=0 ; i<10 ; i++) { ic6502_tick(1000); } gpio_put(IC6502_RESB_PIN, 1); uart_puts_ln("6502: End Reset"); } void ic6502_tick(uint64_t microSeconds) { gpio_put(IC6502_PHI2_PIN, 0); if(microSeconds > 0) sleep_us(microSeconds/2); gpio_put(IC6502_PHI2_PIN, 1); if(microSeconds > 0) sleep_us(microSeconds/2); } void ic6502_enable_bus(bool enable) { gpio_put(IC6502_BE_PIN, enable ? 1 : 0); } <file_sep># 5V Bus |ID|Count|Description| |---|---|---| |GND|1|Ground 0V - VDD| |5V|1|5V Supply - VCC| |A0-A15|16|Address lines 0-15| |D0-D7|8|Data lines 0-7| |R/~W|1|Rear/Write - from 6502 or Pico| |~R|1|Read pulse| |~W|1|Write pulse| |CLK|1|Clock - from Pico| |RESET|1|6502 Reset - from Pico| |NMIB|1|Non-maskable interrupt - pulled up| |IRQB|1|Interrupt request - pulled up| |FREE|3|Left to assign| |TOTAL|36|Max lines on the veroboard| If things become tight the ~R and ~W channels could be retired. This would mean those signals would need to be generated locally per module rather than as part of the 6502 module. # 3V3 Bus |ID|Count|Description| |---|---|---| |GND|1|Ground 0V VDD| |3V3|1|3.3V Supply VCC| |B0-B15|16|General purpose signals| |TOTAL|18|| <file_sep>#include <LiquidCrystal.h> #define NUM_READ_PINS 32 #define NUM_DELAY_VALUES 4 #define NUM_DISPLAY_MODES 2 #define NUM_BUTTONS 3 #define BUTTON_DEBOUNCE 50 #define CLOCK_PIN 2 #define LCD_RS 8 #define LCD_EN 9 #define LCD_D4 10 #define LCD_D5 11 #define LCD_D6 12 #define LCD_D7 13 const String mnemonics[256] = { "BRK", "ORA(zp,x)", "", "", "TSB zp", "ORA zp", "ASL zp", "RMB0 zp", "PHP", "ORA #", "ASL A", "", "TSB a", "ORA $", "ASL $", "BBR0 r", "BPL r", "ORA (zp),y", "ORA (zp)", "", "TRB zp", "ORA zp,x", "ASL zp,x", "RMB1 zp", "CLC", "ORA $,y", "INC A", "", "TRB $", "ORA $,x", "ASL $,x", "BBR1 r", "JSR a", "AND (zp,x)", "", "", "BIT zp", "AND zp", "ROL zp", "RMB2 zp", "PLP", "AND #", "ROL A", "", "BIT $", "AND $", "ROL $", "BBR2 r", "BMI r", "AND (zp),y", "AND (zp)", "", "BIT zp,x", "AND zp,x", "ROL zp,x", "RMB3 zp", "SEC I", "AND $,y", "DEC A", "", "BIT $,x", "AND $,x", "ROL $,x", "BBR3 r", "RTI s", "EOR (zp,x)", "", "", "", "EOR zp", "LSR zp", "RMB4 zp", "PHA", "EOR #", "LSR A", "", "JMP $", "EOR $", "LSR $", "BBR4 r", "BVC r", "EOR (zp),y", "EOR (zp)", "", "", "EOR zp,x", "LSR zp,x", "RMB5 zp", "CLI", "EOR $,y", "PHY", "", "", "EOR $,x", "LSR $", "BBR5 r", "RTS s", "ADC (zp,x)", "", "", "STZ zp", "ADC zp", "ROR zp", "RMB6 zp", "PLA", "ADC #", "ROR A", "", "JMP ($)", "ADC $", "ROR $", "BBR6 r", "BVS r", "ADC (zp),y", "ADC (zp)", "", "STZ zp,x", "ADC zp,x", "ROR zp,x", "RMB7 zp", "SEI", "ADC $,y", "PLY", "", "JMP ($.x)", "ADC $,x", "ROR $,x", "BBR7 r", "BRA r", "STA (zp,x)", "", "", "STY zp", "STA zp", "STZ zp", "SMB0 zp", "DEY", "BIT #", "TXA", "", "STY $", "STA $", "STX $", "BBS0 r", "BCC r", "STA (zp),y", "STA (zp)", "", "STY zp,x", "STA zp,x", "STZ zp,y", "SMB1 zp", "TYA", "STA $,y", "TSX", "", "STZ $", "STA $,x", "STZ $,x", "BBS1 r", "LDY #", "LDA (zp,x)", "LDX #", "", "LDY zp", "LDA zp", "LDX zp", "SMB2 zp", "TAY", "LDA #", "TAX", "", "LDY $", "LDA $", "LDX $", "BBS2 r", "BCS r", "LDA (zp),y", "LDA (zp)", "", "LDY zp,x", "LDA zp,x", "LDX zp,y", "SMB3 zp", "CLV", "LDA A,y", "TSX", "", "LDY $,x", "LDA $,x", "LDX $,x", "BBS3 r", "CPY #", "CMP (zp,x)", "", "", "CPY zp", "CMP zp", "DEC zp", "SMB4 zp", "INY", "CMP #", "DEX", "WAI", "CPY $", "CMP $", "DEC $", "BBS4 r", "BNE r", "CMP (zp),y", "CMP (zp)", "", "", "CMP zp,x", "DEC zp,x", "SMB5 zp", "CLD", "CMP $,y", "PHX", "STP", "", "CMP $,x", "DEC $,x", "BBS5 r", "CPX #", "SBC (zp,x)", "", "", "CPX zp", "SBC zp", "INC zp", "SMB6 zp", "INX", "SBC #", "NOP", "", "CPX $", "SBC $", "INC $", "BBS6 r", "BEQ r", "SBC (zp),y", "SBC (zp)", "", "", "SBC zp,x", "INC zp,x", "SMB7 zp", "SED", "SBC $,y", "PLX", "", "", "SBC $,x", "INC $,x", "BBS7 r" }; const String symbolfile = ""; // input pins const int read_pins[NUM_READ_PINS] = { 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52 }; #define RW_PIN 24 #define SYNC_PIN 25 #define CPU_BE_PIN 26 int cached_read_pins[NUM_READ_PINS]; // button pins const int button_pins[NUM_BUTTONS] = { 7, 6, 5}; int last_button_state[NUM_BUTTONS] = { LOW, LOW, LOW}; unsigned long button_debounce[NUM_BUTTONS]; // clock interrupt LiquidCrystal lcd(LCD_RS, LCD_EN, LCD_D4, LCD_D5, LCD_D6, LCD_D7); int displayMode = 0; String command = ""; void setup() { // input pins for(int i=0 ; i<NUM_READ_PINS ; i++) { pinMode(read_pins[i], INPUT); } // button pins for(int i=0 ; i<NUM_BUTTONS ; i++) { pinMode(button_pins[i], INPUT); } // clear LCD lcd.begin(16,2); // clock interrupt pinMode(CLOCK_PIN, INPUT); attachInterrupt(0, onClock, RISING); Serial.begin(115200); } void onClock() { display(); } void draw_hex() { lcd.setCursor(0,0); int pin=0; char buffer [32]; // address int addrVal = 0; for(int nibble=0 ; nibble<4 ; nibble++) { for(int bit=0 ; bit < 4 ; bit++) { addrVal <<= 1; addrVal += cached_read_pins[pin] == HIGH ? 1 : 0; pin++; } } // data pin = 16; int dataVal = 0; for(int nibble=0 ; nibble<2 ; nibble++) { for(int bit=0 ; bit < 4 ; bit++) { dataVal <<= 1; dataVal += cached_read_pins[pin] == HIGH ? 1 : 0; pin++; } } sprintf(buffer, "A:0x%04X D:0x%02X ", addrVal, dataVal); lcd.print(buffer); Serial.print(buffer); String instruction = " "; if(digitalRead(read_pins[SYNC_PIN]) == HIGH) { instruction = mnemonics[dataVal]; } else { switch(addrVal) { case 0xfffc: case 0xfffd: instruction = "RESET"; break; } } // R/W sprintf(buffer, "%s%s %s", digitalRead(read_pins[RW_PIN]) == HIGH ? "R" : "W",digitalRead(read_pins[CPU_BE_PIN]) == HIGH ? "B" : "b", instruction.c_str()); lcd.setCursor(0,1); lcd.print(buffer); Serial.println(buffer); } void draw_raw() { char buffer [32]; // draw raw inputs on 32 pins lcd.setCursor(0,0); sprintf(buffer, "%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d", cached_read_pins[0], cached_read_pins[1], cached_read_pins[2], cached_read_pins[3], cached_read_pins[4], cached_read_pins[5], cached_read_pins[6], cached_read_pins[7], cached_read_pins[8], cached_read_pins[9], cached_read_pins[10], cached_read_pins[11], cached_read_pins[12], cached_read_pins[13], cached_read_pins[14], cached_read_pins[15]); lcd.print(buffer); lcd.setCursor(0,1); sprintf(buffer, "%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d", cached_read_pins[16], cached_read_pins[17], cached_read_pins[18], cached_read_pins[19], cached_read_pins[20], cached_read_pins[21], cached_read_pins[22], cached_read_pins[23], cached_read_pins[24], cached_read_pins[25], cached_read_pins[26], cached_read_pins[27], cached_read_pins[28], cached_read_pins[29], cached_read_pins[30], cached_read_pins[31]); lcd.print(buffer); } void display() { if(command.length() > 0) return; cache_pins(); // display to LCD switch(displayMode) { case 0: draw_hex(); break; case 1: draw_raw(); break; } } void cache_pins() { for(int i=0 ; i<NUM_READ_PINS ; i++) { cached_read_pins[i] = digitalRead(read_pins[i]); } } void loop() { if(command.length() > 0) { // display command lcd.begin(16,2); lcd.print(command); delay(750); // need to get rid of this too command = ""; } // read button 0 int val = digitalRead(button_pins[0]); if((val == HIGH) && (last_button_state[0] == LOW)) { if(button_debounce[0] + BUTTON_DEBOUNCE < millis()) { displayMode++; if(displayMode >= NUM_DISPLAY_MODES) displayMode = 0; switch(displayMode) { case 0: command="Display - HEX"; break; case 1: command="Display - RAW"; break; } button_debounce[0] = millis(); } } last_button_state[0] = val; // read button 0 val = digitalRead(button_pins[1]); if((val == HIGH) && (last_button_state[1] == LOW)) { if(button_debounce[1] + BUTTON_DEBOUNCE < millis()) { display(); button_debounce[1] = millis(); } } last_button_state[1] = val; delay(10); } <file_sep>#include "pico/stdlib.h" /* Need the shifter specs in here */ extern void shifter_init(); extern void shifter_enable_bus(bool enable); extern void shifter_read(uint16_t *pAddress, uint8_t *pData); <file_sep>from machine import Pin, Timer pin_clear = Pin(1, Pin.OUT) def init(): global.pin_clear pin_clear.
b13d6a356a7734e66e0974a7eb1d0619a0e25e68
[ "CMake", "Markdown", "Python", "C", "C++" ]
27
C
mslinklater/LINK_01
969860f113841e143735c4455e307ba19b23486a
f5248847c09c103b251bcd8430e875ce4d59da58
refs/heads/master
<file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import networkx as nx from operator import itemgetter from math import sin, cos, radians, sqrt from symmetries import find_microsymmetries, Segment import numpy as np def setup_canvas(height, width): import cairocffi as cairo surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, height, width) context = cairo.Context(surface) with context: context.set_source_rgb(1, 1, 1) # White context.paint() context.translate(height*0.1, width*0.1) context.scale(height*0.8, width*0.8) context.scale(1, -1) context.translate(0, -1) return surface, context def draw_segments_to_context(segments, context, frame): context.set_line_width(context.device_to_user_distance(3, 3)[0]) if frame: context.move_to(0,0) context.line_to(1,0) context.line_to(1,1) context.line_to(0,1) context.line_to(0,0) context.stroke() for a, b in segments: context.move_to(*a) context.line_to(*b) context.stroke() def draw_segments(segments, filename, frame = True): surface, context = setup_canvas(100, 100) draw_segments_to_context(segments, context, frame) surface.write_to_png(filename) def draw_in_grid(segments_list, grid_size, filename): import cairocffi as cairo slot_height = 100 slot_width = 100 Nx = grid_size[0] Ny = grid_size[1] surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, Nx*slot_height, Ny*slot_width) context = cairo.Context(surface) with context: context.set_source_rgb(1, 1, 1) # White context.paint() context.translate(slot_height*0.1, slot_width*0.1) context.scale(slot_height*0.8, slot_width*0.8) context.scale(1, -1) # Arrange a list of list of segments into a grid and outputs it to a file for k, segments in enumerate(segments_list): i = k % Nx j = int(k / Nx) with context: context.translate(i + i*0.25, -j-1.05 - j*0.2) segments = segments_list[i + j*Nx] draw_segments_to_context(segments, context, False) surface.write_to_png(filename) def draw_points(points, filename, frame = True): from math import pi surface, context = setup_canvas(1000, 1000) radius = context.device_to_user_distance(2, 2)[0] context.set_line_width(radius) for point in points: context.move_to(*point) context.arc(point[0], point[1], radius, 0, 2*pi) context.fill() surface.write_to_png(filename) def stroke(size, angle, initial): # print "Stroke of length {} at {}º, starting from {}".format(size, angle, initial) return initial[0] + size * cos(radians(angle)), initial[1] + size * sin(radians(angle)) def interpolate(a, b, x): return tuple(round(i + (j - i) * x, 6) for i, j in zip(a, b)) # Kudos to /u/Kakila for idea of use adjacency list for topology def parse(glyph): from itertools import chain def to_size(size_index): return glyph['sizes'][size_index] def to_angle(direction_index): return glyph['directions'][direction_index] * 90 def connected_subgraphs(graph): return nx.connected_component_subgraphs(graph) def lengths(g, nodes): try: return [(i, to_size(graph.node[i]['lengths'])) for i in nodes] except KeyError: print "OK", graph.node, i raise g_data = glyph['graph'] topology = g_data['adjacency'] roots = glyph['roots'] edge_list = [(i,j) for i, connected in enumerate(topology) for j in connected] #if not edge_list: # print "NO EDGES", [(i, connected) for i, connected in enumerate(topology)] if edge_list: #print "BUILDING FROM EDGES", glyph graph = nx.Graph(edge_list) elif topology: #print "BUILDING FROM NODES", glyph graph = nx.Graph() graph.add_nodes_from(range(len(topology))) for k in ('lengths', 'directions', 'positions'): try: nx.set_node_attributes(graph, k, dict(enumerate(g_data[k]))) except KeyError: print "graph ", edge_list print g_data, k raise def draw_strokes_from(main_edges): strokes = {} segments = [] for start, cluster_root in zip(main_edges, roots): for i,j,k in nx.dfs_labeled_edges(graph, start): if k['dir']!='forward': continue node_attr = graph.node[j] if i in strokes: last_start, last_finish = strokes[i] x = node_attr['positions'] if node_attr['positions'] else 0 stroke_start = interpolate(last_start, last_finish, x) else: stroke_start = cluster_root stroke_end = stroke(to_size(node_attr['lengths']), to_angle(node_attr['directions']), stroke_start) strokes[j] = Segment(np.array(stroke_start), np.array(stroke_end)) segments.append(strokes[j]) # print [nx.dfs_successors(graph, start) for i in nx.dfs_successors(graph, start)[start]] # draw_strokes_from(stroke_start, stroke_end, nx.dfs_predecessors(graph, start)) return segments # Start drawing from the longest node of each connected subgraph try: return chain(draw_strokes_from([max(lengths(graph, nodes), key = itemgetter(1))[0] for nodes in connected_subgraphs(graph)])) except KeyError: raise vertical = 1 original_runes = { 'fehu': { 'directions': (vertical, 0.5), 'sizes': (1, 0.94, 0.55), 'roots': ((0.3, 0),), 'graph': { # Each node is a stroke 'lengths': (0, 1, 2), # stroke lengths 'directions': (0, 1, 1), # stroke directions 'adjacency': ((), (0,), (0,)), # stroke adjacency 'positions': (None, 0.3, 0.6), # connection position } }, 'jera': { 'directions': (0.5, 1.5, 2.5, 3.5), 'sizes': (0.3, 0.2), 'roots': ((0.45, 0.25), (0.55, 0.75)), 'graph': { 'adjacency': ((), (0,), (), (2,)), 'lengths': (0, 1, 0, 1), 'directions': (0, 1, 2, 3), 'positions': (None, 1, None, 1), } }, 'perp': { 'directions': (1, 0.5, -0.5), 'sizes': (1, 0.4), 'roots': ((0.2, 0),), 'graph': { 'lengths': (0, 1, 1, 1, 1), 'directions': (0, 2, 1, 1, 2), 'adjacency': ((), (0,), (1,), (0,), (3,)), 'positions': (None, 1, 1, 0, 1), } } } def reproduce(rune, number_of_children): from random import gauss from math import pi size_drift_strength = 0.1 direction_drift_strength = 0.1 def clamp(x, smallest, greatest): return min(max(x, smallest), greatest) def normalize_angle(x): while x < 0: x += 4 while x > 4: x -= 4 return x def drift_length(x): return clamp(gauss(x, size_drift_strength), 0, 1) def drift_angle(x): return normalize_angle(gauss(x, direction_drift_strength)) def assign(origin, new_fields): ret = origin.copy() ret.update(new_fields) return ret directions = rune['directions'] sizes = rune['sizes'] positions = rune['graph']['positions'] children = [] for i in range(number_of_children): new_directions = tuple(drift_angle(angle) for angle in directions) new_sizes = tuple(drift_length(x) for x in sizes) new_positions = tuple(drift_length(x) if x else None for x in positions) keep = dict((k, j) for j, k in enumerate([i for i, length in enumerate(new_sizes) if length>0])) updated_graph_elements = {'positions': new_positions} if len(keep) == 0: continue if len(keep) < len(new_sizes): print "prune", keep, new_sizes new_sizes = tuple(length for length in new_sizes if length > 0) ls = rune['graph']['lengths'] ds = rune['graph']['directions'] ads = rune['graph']['adjacency'] nps = new_positions node_keep = dict((k, j) for j,k in enumerate(i for i, l_i in enumerate(ls) if l_i in keep)) print ads, node_keep new_lengths, new_direction_indexes, new_adjacency, new_positions = zip(*[(keep[l_i], d_i, map(keep.get, ad_i), np_i) for l_i, d_i, ad_i, np_i in zip(ls, ds, ads, nps) if l_i in keep]) new_adjacency = tuple(tuple(node_keep.get(a) for a in adj if a in node_keep) for adj in new_adjacency) print new_adjacency updated_graph_elements.update({ 'positions': new_positions, 'lengths': new_lengths, 'directions': new_direction_indexes, 'adjacency': new_adjacency }) assert len(new_positions) == len(new_lengths) assert len(new_direction_indexes) == len(new_lengths) assert len(new_adjacency) == len(new_lengths) else: assert len(directions) == len(new_directions) assert len(new_positions) == len(positions) assert len(new_sizes) == len(sizes) new_child = assign(rune, { 'directions': new_directions, 'sizes': new_sizes, 'graph': assign(rune['graph'], updated_graph_elements) }) children.append(new_child) return children def to_point_cloud(segments): from random import uniform from math import sqrt # Sample segments as points at a rate of 100 points per unit length points = [] for start, end in segments: length = sqrt(sum((j - i)**2 for i, j in zip(start, end))) samples = int(round(length*100)) phases = (uniform(0, 1) for i in range(samples)) points.extend(interpolate(start, end, s) for s in phases) return points def visual_rate(segments): symmetries = find_microsymmetries(segments, segment_split_length=0.2) return len(symmetries) def glyph_rate(glyph): return np.std(glyph['directions']) def rate(rune): return visual_rate(parse(rune))*glyph_rate(rune) runes = original_runes.values() generations = 10 CHILDREN_PER_GENERATION = 5 MAX_POOL = 100 for i in range(generations): print len(runes) children = [] for data in runes: children.extend(reproduce(data, CHILDREN_PER_GENERATION)) runes = sorted(children, key=rate, reverse=True)[:MAX_POOL] print map(rate, runes[:10]) print runes[:10] #draw_segments(segments, '{}.png'.format(name), frame=False) #draw_points(to_point_cloud(segments), '{}_cloud.png'.format(name), frame=True) draw_in_grid(map(parse, runes), (int(round(sqrt(len(runes)))), int(round(sqrt(len(runes))))), 'runes.png') <file_sep>import numpy as np from math import atan2, fabs, sqrt, floor from collections import namedtuple Axis = namedtuple('Axis', ['point', 'direction', 'cost']) Segment = namedtuple('Segment', ['start', 'end']) def microsymmetry_axis(P11, P12, P21, P22): ''' Given two pairs of segments starting and ending points, compute microsymmetry reflection axis along with a mean square error for that Returns starting point of mycrosymmetry axis Q, direction S, points P11 and P12 reflected through axis, endpoint of mycrosymmetry axis R and C2, the mean square error Based on: <NAME>. 1991. Symmetry analysis of line drawings using the Hough transform. Pattern Recogn. Lett. 12, 1 (January 1991), 9-12. DOI=http://dx.doi.org/10.1016/0167-8655(91)90022-E ''' V1 = P22 - P12 V2 = P21 - P11 V = P12 - P11 B = np.outer(V2, V2) + np.outer(V1, V1) A = V1/4.0 - V2/4.0 + V/2.0 (la, lb), (Ea, Eb) = np.linalg.eig(B - 8 * np.matmul(A, A)) candidates = [] for l2, E in ((la, Ea), (lb, Eb)): l1 = 8*np.matmul(A, E) n = np.matmul(E, V2)+0.25*l1 S = np.array([-E[1], E[0]]) Q = P11 + 0.5*n*E m = n-2*np.matmul(V, E) P11ref = P11 + n*E P12ref = P12 + m*E e1sq = np.linalg.norm(P12ref-P22) + np.linalg.norm(P11ref-P21) e2sq = np.linalg.norm(P12ref-P21) + np.linalg.norm(P11ref-P22) C2 = e1sq + e2sq candidates.append((Axis(Q, S, C2), P11ref, P12ref)) result1 = candidates[0] result2 = candidates[1] return result1 if result1[0].cost < result2[0].cost else result2 def hough_transform(axis): ''' Given axis; returns hough transform point of the axis ''' Sperp = np.array([-axis.direction[1], axis.direction[0]]) rho = fabs(np.dot(axis.point, Sperp)) R = Sperp*np.dot(axis.point, Sperp) return rho, atan2(R[1], R[0]) def inverse_hough_transform(rho, theta, cost): ''' Given rho and theta, returns an axis ''' direction = np.array((-np.sin(theta), np.cos(theta)), dtype=np.float) point = rho * np.array((np.cos(theta), np.sin(theta)), dtype=np.float) return Axis(point, direction, cost) def accumulate_transforms(axis_list, alpha=10, bins=(100, 100), range=None): transformed_points = map(hough_transform, axis_list) try: return np.histogram2d(*zip(*transformed_points), bins=bins, range=range, weights=[1.0/(1+axis.cost*alpha) for axis in axis_list]) except TypeError: print transformed_points raise def equal_segments(segmentA, segmentB): return np.array_equal(segmentA.start, segmentB.start) and np.array_equal(segmentA.end, segmentB.end) def split_segment(segment, length): split_segment = segment.end-segment.start r = np.linalg.norm(split_segment, ord=1)/length split_segment = split_segment/r points_to_split = int(floor(r)) split_points = [segment.start + split_segment*i for i in range(points_to_split)] if not split_points or not np.array_equal(split_points[-1], segment.end): split_points.append(segment.end) return [Segment(split_points[i], split_points[i+1]) for i in range(len(split_points)-1)] def get_local_maxima(H, threshold=1, neighborhood_size=5): import scipy.ndimage.filters as filters data_max = filters.maximum_filter(H, neighborhood_size) maxima = (H == data_max) data_min = filters.minimum_filter(H, neighborhood_size) diff = ((data_max - data_min) > threshold) maxima[diff == 0] = 0 return np.where(maxima) def find_microsymmetries(segment_list, segment_split_length=0.1): axis_list = [] for sA in segment_list: for sB in segment_list: if equal_segments(sA, sB): continue for ssA1, ssA2 in split_segment(sA, segment_split_length): for ssB1, ssB2 in split_segment(sB, segment_split_length): axis_list.append(microsymmetry_axis(ssA1, ssA2, ssB1, ssB2)[0]) if axis_list: aggregated_hugh, rho_edges, theta_edges = accumulate_transforms(axis_list, range=[[0, np.sqrt(2)], [-np.pi/2, np.pi/2]],) threshold = np.amax(aggregated_hugh) * 0.8 rho_maxs, theta_maxs = get_local_maxima(aggregated_hugh, threshold=threshold) maxima = [((rho_edges[rho_i]+rho_edges[rho_i+1])/2, (theta_edges[theta_i]+theta_edges[theta_i+1])/2, aggregated_hugh[rho_i][theta_i]) for rho_i, theta_i in zip(rho_maxs, theta_maxs)] # print "Found {} maxima".format(len(maxima)) # for rho, theta, strength in maxima: # print "Maximum at {}, {} with strength {}".format(rho, theta, strength) return [inverse_hough_transform(rho, theta, strength) for rho, theta, strength in maxima] return [] def debug_microsymmetries(): import matplotlib as mpl mpl.use('TkAgg') import matplotlib.pyplot as plt A1, A2, B1, B2 = [0, 0], [0.5, 1], [0.5, -0.5], [1.5, 0] S1 = Segment(np.array(A1, dtype = np.float), np.array(A2, dtype = np.float)) S2 = Segment(np.array(B1, dtype = np.float), np.array(B2, dtype = np.float)) maxima = find_microsymmetries([S1, S2], segment_split_length = 0.2) def debug_microsymmetry_axis(): import cairocffi as cairo surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200) context = cairo.Context(surface) context.translate(100*0.1, 100*0.1) context.scale(100*0.8, 100*0.8) context.scale(1, -1) context.translate(0, -1) context.set_line_width(context.device_to_user_distance(3, 3)[0]) A1, A2, B1, B2 = [0, 0], [0.5, 1], [0.5, -0.5], [1.5, 0] context.move_to(*A1) context.line_to(*A2) context.move_to(*B1) context.line_to(*B2) context.stroke() axis, P11ref, P12ref = microsymmetry_axis(*[np.array(v, dtype = np.float) for v in [A1, A2, B1, B2]]) context.set_source_rgb(1, 0, 0) context.move_to(*A1) context.line_to(*axis.point) context.stroke() context.set_source_rgb(0, 1, 0) context.move_to(*A1) context.line_to(*(A1+axis.direction)) context.stroke() context.set_source_rgb(0, 0, 1) context.move_to(*P11ref) context.line_to(*P12ref) context.stroke() surface.write_to_png("microsym.png") print axis.cost print hough_transform(axis) if __name__ == '__main__': debug_microsymmetries()<file_sep># glyphs Glyph, rune and symbols generator <file_sep>appdirs==1.4.2 cairocffi==0.8.0 cffi==1.9.1 cycler==0.10.0 decorator==4.0.11 functools32==3.2.3.post2 matplotlib==2.0.0 networkx==1.11 numpy==1.12.0 olefile==0.44 packaging==16.8 Pillow==4.0.0 pycparser==2.17 pyparsing==2.1.10 python-dateutil==2.6.0 pytz==2016.10 scipy==0.19.0 six==1.10.0 subprocess32==3.2.7
ef687913077f279728677d5275df4b132b4c1015
[ "Markdown", "Python", "Text" ]
4
Python
ezequielp/glyphy
278059fcd8ef0fe52798db4333ccd71933d82a61
09ceba49f3181f57091a0683a2613c68acb023b5
refs/heads/devel
<repo_name>nickmccoy/search-engine<file_sep>/word2vec/NumpyEmbeddingStorage.py #!/usr/bin/env -p python3 ## Wrapper around a numpy array of document or word embeddings. # # Why use this instead of just using the array directly? This class has a more # modular interface that could be implemented to wrap other storage methods as # well. For example, a storage that keeps data on disk and out of RAM as much # as possible (i.e., to reduce RAM usage). # class NumpyEmbeddingStorage: def __init__(self, embeddings_arr): self._embeddings_arr = embeddings_arr def as_numpy_array(self): return self._embeddings_arr def get_by_id(self, doc_id): return self._embeddings_arr[doc_id] def embedding_size(self): return self._embeddings_arr.shape[1] def __len__(self): return self._embeddings_arr.shape[0] def __iter__(self): return EmbeddingStorageIter(self) def __get__(self, i): return self._embeddings_arr[i] class EmbeddingStorageIter: def __init__(self, embedding_storage): self._storage = embedding_storage self._index = -1 self._storage_len = len(embedding_storage) def __iter__(self): return self def next(self): if self._index == self._storage_len: raise StopIteration() self._index += 1 return self._storage[self._index] <file_sep>/word2vec/QueryEngineCore.py #!/usr/bin/env -p python3 import heapq import numpy as np import sys class QueryEngineCore: def __init__(self, embedding_storage, comparator_func): self._embeddings = embedding_storage self._comparator_func = comparator_func def search(self, query_vector, max_results=sys.maxsize): if len(query_vector) != self._embeddings.embedding_size(): query_vector.resize(self._embeddings.embedding_size()) num_results = min(max_results, len(self._embeddings)) # Init the heap to a fixed size for efficient k-max scores_heap = [(-sys.maxsize,)] * num_results for doc_num in range(len(self._embeddings)): vec = self._embeddings.get_by_id(doc_num) # Note this is a min-heap, so top will be the WORST # match. We push the current score, then pop the top to # get rid of the worst match heapq.heappushpop(scores_heap, (self._comparator_func(vec, query_vector), doc_num)) # Note again that this is a min-heap, so initially the array # will be sorted in WORST first order for the top results, so # needs to be reversed results = [heapq.heappop(scores_heap) for i in range(num_results)] results.reverse() return results <file_sep>/word2vec/vectorize_doc.py #!/usr/bin/python3 import numpy as np import pickle import os import re import json import sys import scipy.sparse from NumpyEmbeddingStorage import NumpyEmbeddingStorage from QueryEngineCore import QueryEngineCore from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('--vectorizer_type', dest='vectorizer_type', action='store', type=str, default='word2vec') parser.add_argument('--no-tsv-output', dest='tsv_output', action='store_false', default=True) cmdargs = parser.parse_args(sys.argv[1:]) datasource = 'cranfield' data_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'largedata'); with open(os.path.join(data_dir, 'token2id.pickle'), 'rb') as f: token2id = pickle.load(f); with open(os.path.join(data_dir, 'id2freq.npy'), 'rb') as f: id2freq = np.load(f); with open(os.path.join(data_dir, 'doc2id.json'), 'r') as f: doc2id = json.load(f); class Word2vecDocVectorizer: def __init__(self): self._word_embeddings = None with open(os.path.join(data_dir, 'word2vec_vectors.npy'), 'rb') as f: self._word_embeddings = np.load(f); self._token_regex = re.compile(r"(?u)\b\w+\b") def make_doc_vector(self, text): word2vec = self._word_embeddings vec = np.zeros(word2vec.shape[1], dtype=np.float64) for token in self._token_regex.findall(text): if token in token2id: vec += word2vec[token2id[token]] return vec def make_doc_embedding_storage(self, texts): text_embeddings = [] for text in texts: text_embeddings.append(self.make_doc_vector(text)) text_embeddings_arr = np.array(text_embeddings) docs_norm = np.linalg.norm(text_embeddings_arr, axis=1).reshape(text_embeddings_arr.shape[0], 1) docs_norm = np.where(docs_norm==0, 1, docs_norm) unitvec_docs = text_embeddings_arr/docs_norm return NumpyEmbeddingStorage(unitvec_docs) class TfIdfDocVectorizer: def __init__(self, vocab_size): self._vocab_size = vocab_size self._token_regex = re.compile(r"(?u)\b\w+\b") def make_doc_vector(self, text): vec = np.zeros(self._vocab_size) for token in self._token_regex.findall(text): if token in token2id: vec[token2id[token]] += 1 return np.log(vec+1) def make_doc_embedding_storage(self, texts): text_embeddings = [] i = 0 text_embeddings_arr = np.zeros((len(texts), self._vocab_size)) for text in texts: #print(i) i += 1 text_embeddings_arr[i-1] = self.make_doc_vector(text) docs_norm = np.linalg.norm(text_embeddings_arr, axis=1).reshape(text_embeddings_arr.shape[0], 1) docs_norm = np.where(docs_norm==0, 1, docs_norm) unitvec_docs = text_embeddings_arr/docs_norm return NumpyEmbeddingStorage(unitvec_docs) if datasource == 'cranfield': with open('../cranfield_data/cran.json', 'r') as f: cran_data = json.load(f) with open('../cranfield_data/cran.qrel_full.json', 'r') as f: cran_qrel = json.load(f) doc_embeds = None query_engine = None query_vectors = {} if cmdargs.vectorizer_type in ['word2vec', 'tfidf']: docs = [] for doc in cran_data: docs.append(doc['W']) vectorizer = Word2vecDocVectorizer() if cmdargs.vectorizer_type == 'word2vec' else TfIdfDocVectorizer(len(id2freq)) doc_embeds = vectorizer.make_doc_embedding_storage(docs) query_engine = QueryEngineCore(doc_embeds, comparator_func=np.dot) for query in cran_qrel: query_vec = vectorizer.make_doc_vector(query); query_unitvec = query_vec/np.linalg.norm(query_vec) query_vectors[query] = query_unitvec elif cmdargs.vectorizer_type == 'paragraph2vec': para2vec = None with open(os.path.join(data_dir, 'paragraph_vectors.npy'), 'rb') as f: para2vec = np.load(f) docs = [] for doc in cran_data: docs.append(para2vec[doc2id['cran_doc_{}'.format(doc['I'])]]) doc_embeds = NumpyEmbeddingStorage(np.array(docs)) def comparator(vec1, vec2): sub = np.subtract(vec1,vec2) return 15/np.dot(sub, sub) #return float(np.dot(vec1, vec2)/np.linalg.norm(vec2)) query_engine = QueryEngineCore(doc_embeds, comparator_func = comparator) for query in cran_qrel: if len(cran_qrel[query]) == 0: query_vectors[query] = np.zeros(300) continue query_num = int(cran_qrel[query][0]['qnum']) query_vectors[query] = para2vec[doc2id['cran_qry_{}'.format(query_num)]] # print(query, query_num) nr = dict() for query in cran_qrel: query_id = cran_qrel[query][0]['qnum'] nr[query_id] = [] doc_rels = {} for d in cran_qrel[query]: doc_rels[int(d['dnum'])] = int(d['rnum']) query_unitvec = query_vectors[query] results = query_engine.search(query_unitvec) for result in results: doc_id = int(cran_data[result[1]]['I']) doc_rel = doc_rels[doc_id] if doc_id in doc_rels else 5 nr[query_id].append({'doc_id': doc_id, 'doc_rel': doc_rel, 'score': result[0]}) if cmdargs.tsv_output: print('{:d}\t{:d}\t{:d}\t{:0.16f}'.format(query_id, doc_id, doc_rel, result[0])) #with open('/dev/shm/tmp351.json', 'w') as f: # json.dump(nr, f, indent=4, sort_keys=True) <file_sep>/wiki_import/import_wiki.sh #!/bin/bash DIRECTORY=$1 FILES=./$DIRECTORY/* EXTRACT=wikiextractor-url/WikiExtractor.py OUTPUT=./$DIRECTORY/output JSONFILES=$OUTPUT/json COUNTER=0 if [ ! -d "$DIRECTORY" ]; then # Control will enter here if $DIRECTORY exists. echo "Directory $DIRECTORY does not exist" exit -1 fi if [ ! "$EXTRACT" ]; then echo "Cannot find $EXTRACT" exit -1 fi echo "Creating output directory: $OUTPUT" mkdir "$OUTPUT" if [ $? -ne 0 ] ; then echo "Failed to create output directory" exit -1 fi echo "Creating json output directory: $JSONFILES" mkdir "$JSONFILES" if [ ! -d "$OUTPUT" ]; then echo "Failed to create output directory" exit -1 fi echo "Processing files in $DIRECTORY" echo "Processing $FILES" for f in $FILES do echo "Processing $f file..." python $EXTRACT --json -o $OUTPUT $f for json in $OUTPUT/** do if [ ! -d $f ]; then echo "Importing $f into mongodb collection wiki" mv $json "$JSONFILES/$json_$COUNTER" COUNTER=$((COUNTER+1)) else echo "Entering directory $f..." fi done # take action on each file. $f store current file name # cat $f done shopt -s globstar for f in $OUTPUT/** do if [ ! -d $f ]; then echo "Importing $f into mongodb collection wiki" mongoimport --db sharesci --collection wiki --file $f else echo "Entering directory $f..." fi done
b4937e75dd0e1bd7113e04bc07a2fc314d7bf6ac
[ "Python", "Shell" ]
4
Python
nickmccoy/search-engine
2b9d2079fddd08eb1e4184d52f9551ac98fa0057
aef161bfa535abc3200d39c9f7e448e983df1992
refs/heads/master
<repo_name>DeSouzaSR/ShowTime<file_sep>/ShowCurrentTime.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 5 21:42:43 2016 @author: <NAME> Porpose: show hours from the system """ from time import time import os # Clear screen os.system('clear') # Get the current time currentTime = time() # Obtain the total seconds since midnight, Jan 1, 1970 totalSeconds = int(currentTime) # Get the current seconds currentSecond = totalSeconds % 60 # Obtain the total minuts totalMinutes = totalSeconds // 60 # Compute the current minute in the hour currentMinute = totalMinutes % 60 # Obtein the total hours totalHours = totalMinutes // 60 # Compute the current hours currentHour = totalHours % 24 print('Show Time') print('=========\n') print('This program show the local time from machine.') TimeZone = eval(input('Enter your time zone (e.g. -3): ')) # Display results print('\nCurrent time is', currentHour, ':', currentMinute,':', currentSecond, 'GMT') # Display result, adjusting local time using modular arithmetic currentHourLocal = (currentHour + TimeZone) % 24 print('Current time is', currentHourLocal, ':', currentMinute,':', currentSecond, 'Local\n') <file_sep>/README.md # ShowTime This program show the local time from machine. The goal is to learn Python.
48d37ed8e1094609b67b9b73a77201924a228c7f
[ "Markdown", "Python" ]
2
Python
DeSouzaSR/ShowTime
45b6cb1d0322cf052284a25c06aaa584991a9ee2
b4969ffc13e1fffb5eae084a5a95737f6d747ae5
refs/heads/main
<repo_name>Yoonhee-Lee/FirstRPack<file_sep>/README.md # FirstRPack This has some data related functions <file_sep>/R/HealthData.R #'some World Bank Data #' #' @format 264 x 64 dataframe ... #' #' \describe{ #' \item{index}{Country Names} #' \item{column1}{Literacy rates} #'} "HealthData" HealthData = read.csv("World Health Data copy.csv") usethis::use_data( HealthData , overwrite = TRUE) <file_sep>/R/best_sellers_fiction.R #' Title #' #' @return Returns books that have fallen in rank on newyork times best seller list from hardcover-fiction #' @export #' #' @examples #' best_sellers_fiction() best_sellers_fiction <- function(){ APIkey = "<KEY>" date = "current" category = "hardcover-fiction" # Notation about the funtion to make this clearer URL = paste("https://api.nytimes.com/svc/books/v3/lists/" , date , "/", category , ".json?" , sep = "") PATH = paste(URL, "api-key=" , APIkey, sep ="") initialquery = jsonlite::fromJSON(PATH) books = initialquery$results ###Play around with this dataframe to create your own dataset### #The title of the books that have dropped in rank from the previous week. return(books) } <file_sep>/R/hello.R hello <- function() { print("Hello again World I'm Back, world!") #This is useless function # Delete please } <file_sep>/R/drop_columns.R #' Title #' #' @param df This is a dataframe with any datatypes #' @param threshold Between 0-1 for the amount of NAs we accept in a column #' #' @return Returns a df w droppe dcolumsn #' @export #'# Edits #' @examples #' drop_columns(df, .1) drop_columns = function(df, threshold){ num_obs = nrow(df) df_cut = df[ ,colSums(is.na(df)) < num_obs * threshold] return(df_cut) }
24eb68035f5e15267f6fda5cd12f67ef337dba1c
[ "Markdown", "R" ]
5
Markdown
Yoonhee-Lee/FirstRPack
0750e39d36222c4402d9273c6a002713257ee32e
29f762847e7076801558059c0018305fa6ee70be
refs/heads/master
<file_sep>#! /usr/bin/env python import numpy as np from scipy import optimize from collections import Sequence from itertools import chain, count import numbers import argparse def NumberQ(x): return isinstance(x, numbers.Number) def depth(seq): for level in count(): if not seq: return level seq = list(chain.from_iterable(s for s in seq if isinstance(s, Sequence))) class Info_Collapse: def __init__(self, a, b, c, d, e, f, Pi_T, Pi_C, Pi_A, Pi_G, ratevector_file): self.frequency = [Pi_T, Pi_C, Pi_A, Pi_G] self.len_freq = len(self.frequency) mu = 1 / 2 / (a * Pi_T * Pi_C + b * Pi_T * Pi_A + c * Pi_T * Pi_G + d * Pi_C * Pi_A + e * Pi_C * Pi_G + f * Pi_A * Pi_G) with open(ratevector_file) as infile: ratevector = [float(x) for x in infile.read().split(",")] clean_rate = ratevector[ratevector == 0] Q = mu * np.array([[-a * Pi_C - b * Pi_A - c * Pi_G, a * Pi_C, b * Pi_A, c * Pi_G], [a * Pi_T, -a * Pi_T - d * Pi_A - e * Pi_G, d * Pi_A, e * Pi_G], [b * Pi_T, d * Pi_C, -b * Pi_T - d * Pi_C - f * Pi_G, f * Pi_G], [c * Pi_T, e * Pi_C, f * Pi_A, -c * Pi_T - e * Pi_C - f * Pi_A]]) self.evals, py_v = np.linalg.eig(Q) # for some reason py_v seems to already be transposed self.tev = py_v self.itev = np.linalg.inv(self.tev) def P(self, lamda, T): output = np.dot(np.dot(self.tev, np.diag(np.exp(self.evals * lamda * T))), self.itev) return output ## RHS def _JointProb3(self, root, char1, char2, T1, T2, lamda): return self.frequency[root] * self.P(lamda, T1)[root, char1] * self.P(lamda, T2)[root, char2] def _CondProb3(self, root, char1, char2, T1, T2, lamda): output = self._JointProb3(root, char1, char2, T1, T2, lamda) output /= np.sum([self._JointProb3(i, char1, char2, T1, T2, lamda) for i in range(self.len_freq)]) return output def _CondEntropy3(self, T1, T2, lamda): output = 0 for root in range(self.len_freq): for char1 in range(self.len_freq): for char2 in range(self.len_freq): output += self._JointProb3(root, char1, char2, T1, T2, lamda) * \ np.log(self._CondProb3(root, char1, char2, T1, T2, lamda)) return -1 * output ## LHS def _JointProb2(self, rootprime, charprime, Tprime, lamda): return self.frequency[rootprime] * self.P(lamda, Tprime)[rootprime, charprime] def _CondProb2(self, rootprime, charprime, Tprime, lamda): output1 = self._JointProb2(rootprime, charprime, Tprime, lamda) output2 = np.sum([self._JointProb2(i, charprime, Tprime, lamda) for i in range(self.len_freq)]) # print() return output1 / output2 def _CondEntropy2(self, Tprime, lamda): output = 0 for root in range(self.len_freq): for charprime in range(self.len_freq): cprob = self._CondProb2(root, charprime, Tprime, lamda) output += self._JointProb2(root, charprime, Tprime, lamda) * np.log(cprob) return -1 * output def _InfoEquivalent(self, T1, T2, lamda): cond_entropy3 = self._CondEntropy3(T1, T2, lamda) def to_find_root(Tprime): cond_entropy2 = self._CondEntropy2(Tprime[0], lamda) return cond_entropy2 - cond_entropy3 output = optimize.root(to_find_root, np.min([T1, T2]), options={'maxfev': 500}).x[0] return output def BranchCollapse(self, branch, lamda): if not isinstance(branch, Sequence): return branch elif depth(branch[0]) == 1 and NumberQ(branch[-1]): return self._InfoEquivalent(branch[0][0], branch[0][-1], lamda) + branch[-1] elif not NumberQ(branch[0][0]): return self._InfoEquivalent(self.BranchCollapse(branch[0][0], lamda), self.BranchCollapse(branch[0][-1], lamda), lamda) + branch[-1] else: raise ValueError("Something went wrong") def TreeCollapse(self, Tree, lamda): output = [self.BranchCollapse(Tree[i], lamda) for i in range(len(Tree) - 1)] output.append(Tree[-1]) return output def main(): parser = argparse.ArgumentParser(description='''The program depends on scipy, and numpy.\n The positional arguments must be inputted in the correct order.\n If the arguments are named they can go in any order.\n All arguments also have default values and can be excluded\n Example runs would be:\n ./InfoCollapse.py 1 1 1 1 1 1 .25 .25 .25 .25 -i 1 2 3 4 5 -r .5 .6 .7 .8 ./InfoCollapse.py -a 1 -b 1 1 1 1 1 .25 .25 .25 .25 -i 1 2 3 4 5 -r .5 .6 .7 .8 ''') parser.add_argument("a", type=float, nargs='?', default=5.26) parser.add_argument("b", type=float, nargs='?', default=8.15) parser.add_argument("c", type=float, nargs='?', default=1) parser.add_argument("d", type=float, nargs='?', default=2.25) parser.add_argument("e", type=float, nargs='?', default=3.16) parser.add_argument("f", type=float, nargs='?', default=5.44) parser.add_argument("Pi_T", type=float, nargs='?', default=0.34) parser.add_argument("Pi_C", type=float, nargs='?', default=0.16) parser.add_argument("Pi_A", type=float, nargs='?', default=0.32) parser.add_argument("Pi_G", type=float, nargs='?', default=0.18) parser.add_argument("-r", "--ratevector_file", type=str, default='dummy_rate_vector', help="The string of , comma seperated") parser.add_argument("-t", "--tree_file", type=float, default='dummy_tree', help="The tree file in the Newick format") args = parser.parse_args() a = args.a b = args.bn c = args.c d = args.d e = args.e f = args.f Pi_T = args.Pi_T Pi_C = args.Pi_C Pi_A = args.Pi_A Pi_G = args.Pi_G ratevector_file = args.ratevector_file info_collapse = Info_Collapse(a, b, c, d, e, f, Pi_T, Pi_C, Pi_A, Pi_G, ratevector_file) return info_collapse def test(): info_collapse = main() testbranch2 = [[[[20, 15], 40], [[30, 30], 30]], 5] testTree = [[[[[10, 10], 30], [[10, 10], 30]], 5], [[[[20, 20], 30], [[10, 10], 30]], 5], [[[[10, 10], 30], [[20, 20], 30]], 5], [[[[20, 20], 30], [[20, 20], 30]], 5], 1] print("Branch Test: {}".format(info_collapse.BranchCollapse(testbranch2, .0008))) print() print("Tree Test: {}".format(info_collapse.TreeCollapse(testTree, .0008))) print() for i in np.arange(1 / 10000, 50 / 10000, 1 / 10000): print(info_collapse.TreeCollapse(testTree, i)) if __name__ == "__main__": info_collapse = main() <file_sep># We will need to create Qt4 items from PyQt4 import QtCore from PyQt4.QtGui import QGraphicsRectItem, QGraphicsSimpleTextItem, \ QColor, QPen, QBrush, QGraphicsRectItem from ete3 import Tree, faces, TreeStyle, NodeStyle # To play with random colors import colorsys import random class InteractiveItem(QGraphicsRectItem): def __init__(self, *arg, **karg): QGraphicsRectItem.__init__(self, *arg, **karg) self.node = None self.color_rect = None self.setCursor(QtCore.Qt.PointingHandCursor) def hoverEnterEvent (self, e): if self.color_rect is not None: self.color_rect.setBrush(QBrush(QColor(200, 100, 100, 100))) def hoverLeaveEvent(self, e): if self.color_rect is not None: self.color_rect.setBrush(QBrush(QColor(100, 100, 200, 100))) def mousePressEvent(self, e): print(self.node.name) print(self.node.dist) def ugly_name_face(node, *args, **kargs): """ This is my item generator. It must receive a node object, and returns a Qt4 graphics item that can be used as a node face. """ width = node.dist * 2.5 height = 12 masterItem = InteractiveItem(0, 0, width, height) masterItem.node = node masterItem.setPen(QPen(QtCore.Qt.NoPen)) color_rect = QGraphicsRectItem(masterItem.rect()) color_rect.setParentItem(masterItem) color_rect.setBrush(QBrush(QColor(100, 100, 200, 100))) color_rect.setPen(QPen(QtCore.Qt.NoPen)) masterItem.color_rect = color_rect return masterItem def master_ly(node): if not node.is_leaf() and not node.is_root(): F = faces.DynamicItemFace(ugly_name_face, 50) faces.add_face_to_node(F, node, 0, position="float") def get_example_tree(): with open("avian_tree", "r") as infile: data = infile.read() t = Tree(data) ts = TreeStyle() ts.layout_fn = master_ly ts.title.add_face(faces.TextFace("Drawing your own Qt Faces", fsize=15), 0) return t, ts def main(): t, ts = get_example_tree() t.show(tree_style=ts) if __name__ == "__main__": main()
5742b5faaf4014d5f8b116a0927cdc45ff7fc7b8
[ "Python" ]
2
Python
jtamagnan/informr
b2823799f5e58bf786f72718210f02da8fc10e71
4d9bab8b9a95923f9e6d962b1a92c9a12330c095
refs/heads/master
<file_sep>import java.util.Scanner; public class exDoWhile2{ public static void main(String[]args){ Scanner entrada = new Scanner(System.in); double gremio, inter, outro, geral, porGre, porInt; geral = 0; gremio = 0; inter = 0; outro = 0; porGre = 0; porInt = 0; char digito; do{ System.out.println("Selecione o seu time: \n"); System.out.println("1.Gremio___2.Inter___3.Outros___0.Fim"); digito = entrada.next().charAt(0); switch(digito){ case '1': gremio ++; geral ++;break; case '2': inter ++; geral ++;break; case '3': outro ++; geral ++;break; case '0': digito = 0;break; default: System.out.println("Digito invalido. Tente novamente."); } }while(digito != 0); porGre = (gremio / geral)*100; porInt = (inter / geral)*100; System.out.println("Operacao finalizada.\n\n"); System.out.println("Torcedores do Gremio: " + gremio + ", porcentagem: " + porGre + "%"); System.out.println("Torcedores do Inter: " + inter + ", porcentagem: " + porInt + "%"); System.out.println("Torcedores de outros times: " + outro); System.out.println("Numero geral de torcedores: " + geral); } }<file_sep># ifex-feitos-na-facom<file_sep>import java.util.Scanner; public class exMatriz{ public static void main(String args[]){ Scanner entrada = new Scanner(System.in); int M[][], k, n, nulo = 0, um=0, cont = 0; System.out.println("Informe a quantidade de testes que serao realizados: "); k = entrada.nextInt(); System.out.println("Informe qual sera a dimensao da matriz quadrada: "); n = entrada.nextInt(); M = new int[n][n]; for(int c = 0; c < k; c++){ for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ nulo = 0; um = 0; System.out.println("Insira o valor da matriz: "); M[i][j] = entrada.nextInt(); if(M[i][j] > 100 || M[i][j] < 0){ M[i][j] = 0; } } } for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(M[i][j] == 0){ nulo++; } if(M[i][j] == 1){ um++; } } } System.out.println(""); // IMPRIMINDO A MATRIZ for (int i = 0; i < n ; i++){ for (int j = 0; j < n ; j++){ System.out.print(M[i][j] + " "); cont++; if (cont == n){ cont = 0; System.out.println(); } } } if(nulo == (n-1) * n && um == n){ System.out.println("\n A matriz eh de permutacao.\n"); } else{ System.out.println("A matriz nao eh de permutacao.\n"); } } } } <file_sep>import java.util.Scanner; import java.math.*; public class ex04{ public static void main(String[]args){ Scanner ent = new Scanner(System.in); double x1, x2, y1, y2, distancia; x1 = ent.nextDouble(); y1 = ent.nextDouble(); x2 = ent.nextDouble(); y2 = ent.nextDouble(); distancia = Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1))); System.out.printf("%.4f\n", distancia); } }<file_sep>import java.util.Scanner; public class matriz02{ public static void main(String[]args){ Scanner entrada = new Scanner(System.in); double M[][], soma = 0, media; M = new double [4][4]; for(int i = 0 ; i< 4; i ++){ for(int j =0 ;j < 4; j++){ System.out.println("Informe o valor da matriz: "); M[i][j] = entrada.nextDouble(); } } for(int i = 0; i< 4; i++){ soma = soma + M[i][i]; } media = soma /4; System.out.println("Media da diagonal principal da matriz: " + media); } }<file_sep>import java.util.Scanner; public class Main{ public static void main(String[]args){ Scanner entrada = new Scanner(System.in); int qtdProvas=0; int qtdTrabalhos=0; System.out.println("Informe a quantidade de provas: "); qtdProvas = entrada.nextInt(); Prova[] provas = new Prova[qtdProvas]; for(int i = 0; i < qtdProvas; i++){ provas[i] = new Prova(); } for(int i = 0; i < qtdProvas; i++){ System.out.println("Qual e o peso da P" + (i+1) + "?"); provas[i].lerPeso(entrada.nextDouble()); System.out.println("Peso da prova: " + provas[i].getPeso()); } System.out.println("Informe a quantidade de trabalhos: "); qtdTrabalhos = entrada.nextInt(); Trabalho[] trabalhos = new Trabalho[qtdTrabalhos]; for(int i = 0; i < qtdTrabalhos; i++){ trabalhos[i] = new Trabalho(); } for(int i = 0; i < qtdTrabalhos; i++){ System.out.println("Qual e o peso do trabalho " + (i+1) + "?"); trabalhos[i].lerPeso(entrada.nextDouble()); System.out.println("Peso da prova: " + provas[i].getPeso()); } } }
ffce633e73ccda9a80955acdc9fb3bd0762f283a
[ "Markdown", "Java" ]
6
Java
Angenox/ifex-feitos-na-facom
c3330590c270ed49b7e16d60a17831d28b6b958a
3d34c0f30ecddc08ee320ad03d6a67c097668821
refs/heads/master
<repo_name>mifril/dl_models<file_sep>/dl_models/keras/unet.py from keras.optimizers import * from keras.layers import * from keras.callbacks import * from keras.models import Model # U-Net implementation # https://arxiv.org/pdf/1505.04597.pdf def double_conv_layer(x, size, dropout, batch_norm): if K.image_dim_ordering() == 'th': axis = 1 else: axis = 3 conv = Conv2D(size, (3, 3), padding='same')(x) if batch_norm: conv = BatchNormalization(axis=axis)(conv) conv = Activation('relu')(conv) conv = Conv2D(size, (3, 3), padding='same')(conv) if batch_norm: conv = BatchNormalization(axis=axis)(conv) conv = Activation('relu')(conv) if dropout > 0: conv = Dropout(dropout)(conv) return conv def get_unet(img_shape, dropout_val=0.0, batch_norm=False, init_filters=32, n_blocks=5): if K.image_dim_ordering() == 'th': axis = 1 else: axis = 3 inputs = Input(img_shape) x = inputs convs = [] # Contracting path for i in range(n_blocks): x = double_conv_layer(x, 2**i * init_filters, dropout_val, batch_norm) convs.append(x) x = MaxPooling2D(pool_size=(2, 2))(x) x = double_conv_layer(x, 2**(n_blocks) * init_filters, dropout_val, batch_norm) convs.append(x) # Expansive path for i in range(n_blocks - 1, -1, -1): x = Concatenate(axis=3)([UpSampling2D(size=(2, 2))(x), convs[i]]) x = double_conv_layer(x, 2**i * init_filters, dropout_val, batch_norm) x = Conv2D(1, (1, 1))(x) if batch_norm: x = BatchNormalization(axis=axis)(x) outputs = Activation('sigmoid')(x) model = Model(inputs=inputs, outputs=outputs) return model <file_sep>/README.md # Deep Learning models - Semantic segmentation - U-Net (Keras) [https://arxiv.org/pdf/1505.04597.pdf] - LinkNet (Keras) [https://arxiv.org/pdf/1707.03718.pdf] <file_sep>/dl_models/keras/linknet.py from keras.optimizers import * from keras.layers import * from keras.callbacks import * from keras.models import Model # LinkNet implementation # https://arxiv.org/pdf/1707.03718.pdf def encoder_block(i, n, m, batch_norm=False): if K.image_dim_ordering() == 'th': axis = 1 else: axis = 3 x = Conv2D(n, (3, 3), strides=2, padding='same')(i) if batch_norm: x = BatchNormalization(axis=axis)(x) x = Activation('relu')(x) x = Conv2D(n, (3, 3), padding='same')(x) if batch_norm: x = BatchNormalization(axis=axis)(x) x = Activation('relu')(x) shortcut = Conv2D(n, (1, 1), strides=2)(i) x = Add()([x, shortcut]) i = x x = Conv2D(n, (3, 3), padding='same')(x) if batch_norm: x = BatchNormalization(axis=axis)(x) x = Activation('relu')(x) x = Conv2D(n, (3, 3), padding='same')(x) if batch_norm: x = BatchNormalization(axis=axis)(x) x = Activation('relu')(x) x = Add()([x, i]) return x def decoder_block(i, n, m, batch_norm=False): if K.image_dim_ordering() == 'th': axis = 1 else: axis = 3 x = Conv2D(m // 4, (1, 1), padding='same')(i) if batch_norm: x = BatchNormalization(axis=axis)(x) x = Activation('relu')(x) x = Conv2DTranspose(m // 4, (3, 3), strides=2, padding='same')(x) if batch_norm: x = BatchNormalization(axis=axis)(x) x = Activation('relu')(x) x = Conv2D(n, (1, 1), padding='same')(x) if batch_norm: x = BatchNormalization(axis=axis)(x) x = Activation('relu')(x) return x def get_linknet(img_shape, n_out=1, batch_norm=False, dropout=0.0, batch_norm_in=False): if K.image_dim_ordering() == 'th': axis = 1 else: axis = 3 n = [64, 128, 256, 512] m = [64, 64, 128, 256] inputs = Input(img_shape) x = inputs if batch_norm_in: x = BatchNormalization(axis=axis)(x) x = Conv2D(64, (3, 3), strides=2, padding='same')(x) if batch_norm: x = BatchNormalization(axis=axis)(x) x = Activation('relu')(x) x = MaxPooling2D((3, 3), strides=2)(x) e1 = encoder_block(x, n[0], m[0], batch_norm) e2 = encoder_block(e1, n[1], m[1], batch_norm) e3 = encoder_block(e2, n[2], m[2], batch_norm) e4 = encoder_block(e3, n[3], m[3], batch_norm) d4 = decoder_block(e4, m[3], n[3], batch_norm) d4 = Add()([e3, d4]) d3 = decoder_block(d4, m[2], n[2], batch_norm) d3 = Add()([e2, d3]) d2 = decoder_block(d3, m[1], n[1], batch_norm) d2 = Add()([e1, d2]) d1 = decoder_block(d2, m[0], n[0], batch_norm) x = Conv2DTranspose(32, (3, 3), strides=2, padding='same')(d1) if batch_norm: x = BatchNormalization(axis=axis)(x) x = Activation('relu')(x) x = Conv2D(32, (3, 3), padding='same')(x) if batch_norm: x = BatchNormalization(axis=axis)(x) x = Activation('relu')(x) if dropout > 0: x = SpatialDropout2D(dropout)(x) x = Conv2DTranspose(n_out, (2, 2), strides=2, padding='same')(x) if batch_norm: x = BatchNormalization(axis=axis)(x) x = Activation('sigmoid')(x) model = Model(inputs=inputs, outputs=x) return model
f13de74d7f731909d790ef73c2a57b40222588c1
[ "Markdown", "Python" ]
3
Python
mifril/dl_models
ac276cf38cce1202324daebefa5cf426996dca55
b1104ef1cacb6eb84d64683d691f2fd61ce33310
refs/heads/master
<repo_name>qlcchain/WinQ-iOS<file_sep>/Qlink/Vender/QLC/qlc/mng/BlockMng.swift // // BlockMng.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import BigInt public class BlockMng { /** * * @Description get block root * @param block * @throws QlcException * @return String */ public static func getRoot(block:QLCStateBlock) -> String? { if block.type == QLCConstants.BLOCK_TYPE_OPEN { return QLCUtil.addressToPublicKey(address: block.address ?? "") } else { return block.previous } } /** * * @Description get block hash * @param block * @throws QlcException * @return byte[]:block hash */ public static func getHash(block:QLCStateBlock) -> Bytes { var source : Bytes = Bytes() let type = QLCBlock.QLCType.getIndex(type: block.type ?? "").toBytes_Big source.append(contentsOf: [type.last!]) let token = (block.token ?? "").hex2Bytes source.append(contentsOf: token) let addressB = QLCUtil.addressToPublicKey(address: block.address ?? "").hex2Bytes source.append(contentsOf: addressB) let balance:BigUInt = block.balance ?? BigUInt(0) let balanceB = [UInt8](balance.serialize()) source.append(contentsOf: balanceB) let vote:BigUInt = block.vote ?? BigUInt(0) source.append(contentsOf: [UInt8](vote.serialize())) let network:BigUInt = block.network ?? BigUInt(0) source.append(contentsOf: [UInt8](network.serialize())) let storage:BigUInt = block.storage ?? BigUInt(0) source.append(contentsOf: [UInt8](storage.serialize())) let oracle:BigUInt = block.oracle ?? BigUInt(0) source.append(contentsOf: [UInt8](oracle.serialize())) let previousB = (block.previous ?? "").hex2Bytes source.append(contentsOf: previousB) let linkB = (block.link ?? "").hex2Bytes source.append(contentsOf: linkB) //TODO:未检验 // var sender = Data() // if (block.sender != nil) { // sender = Data(base64Encoded: block.sender!, options: Data.Base64DecodingOptions(rawValue: 0)) ?? Data() // } // let senderB = sender.bytes let senderB = (block.sender ?? "").bytes source.append(contentsOf: senderB) //TODO:未检验 // var receiver = Data() // if (block.receiver != nil) { // receiver = Data(base64Encoded: block.receiver!, options: Data.Base64DecodingOptions(rawValue: 0)) ?? Data() // } // let receiverB = receiver.bytes let receiverB = (block.receiver ?? "").bytes source.append(contentsOf: receiverB) let messageB = (block.message ?? "").hex2Bytes source.append(contentsOf: messageB) var data = Data() if (block.data != nil) { data = Data(base64Encoded: block.data!, options: Data.Base64DecodingOptions(rawValue: 0)) ?? Data() } let dataB = data.bytes source.append(contentsOf: dataB) let timestamp = (block.timestamp ?? 0).toBytes_Big source.append(contentsOf: timestamp) let povHeight = (block.povHeight ?? 0).toBytes_Big source.append(contentsOf: povHeight) let extra = (block.extra ?? "").hex2Bytes source.append(contentsOf: extra) let representativeB = QLCUtil.addressToPublicKey(address: (block.representative ?? "")).hex2Bytes source.append(contentsOf: representativeB) let hashB = Blake2b.hash(outLength: 32, in: source) ?? Bytes() // let hashString = hashB.toHexString() return hashB } } <file_sep>/Qlink/Vender/QLC/qlc/mng/LedgerMng.swift // // LedgerMng.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation public class LedgerMng { /** * * @Description Return block info by block hash * @param blockHash:block hash * @throws QlcException * @throws IOException * @return StateBlock */ public static func blocksInfo(blockHash:Bytes, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) throws { let hashArr = [blockHash.toHexString()] LedgerRpc.blocksInfo(hashArr: hashArr, successHandler: { (response) in if response != nil { let dic = (response as! Array<Dictionary<String, Any>>)[0] let stateBlock = QLCStateBlock.deserialize(from: dic) successHandler(stateBlock) } else { successHandler(nil) } }) { (error, message) in failureHandler(error, message) } } /** * * @Description Return pending info for account * @param address:account * @throws QlcException * @throws IOException * @return Pending */ public static func accountsPending(address:String, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) throws { let addressArr = [address] LedgerRpc.accountsPending(addressArr: addressArr, successHandler: { (response) in if response != nil { let dic: Dictionary<String, Any?> = response as! Dictionary<String, Any?> if dic.count <= 0 { failureHandler(nil, nil) return } let infoArray : Array<Dictionary<String, Any>?>? = (dic[address] as! Array<Dictionary<String, Any>?>) if infoArray == nil { failureHandler(nil, nil) return } let pending = QLCPending() pending.address = address var infoList = Array<QLCPendingInfo>() if infoArray!.count > 0 { var info: QLCPendingInfo? for item in infoArray! { info = QLCPendingInfo.deserialize(from: item) infoList.append(info!) info = nil } pending.infoList = infoList } successHandler(pending) } else { successHandler(nil) } }) { (error, message) in failureHandler(error, message) } } // process public static func process(dic:Dictionary<String, Any>, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) throws { LedgerRpc.process(dic: dic, successHandler: { (response) in if response != nil { let result:String = response as! String successHandler(result) } else { successHandler(nil) } }) { (error, message) in failureHandler(error, message) } } } <file_sep>/Qlink/Vender/NEO/Contracts/ScriptBuilder.swift // // ScriptBuilder.swift // NeoSwift // // Created by <NAME> on 10/28/17. // Copyright © 2017 drei. All rights reserved. // import Foundation public class ScriptBuilder { private(set) public var rawBytes = [UInt8]() var rawHexString: String { return rawBytes.fullHexString } public init() { rawBytes = [] } private func pushOPCode(_ op: OpCode) { rawBytes.append(op.rawValue) } private func pushBool(_ boolValue: Bool) { pushOPCode(boolValue ? .PUSH1 : .PUSH0) } private func pushInt(_ intValue: Int) { switch intValue { case -1: pushOPCode(.PUSHM1) case 0: pushOPCode(.PUSH0) case 1..<16: let rawValue = OpCode.PUSH1.rawValue + UInt8(intValue) - 1 rawBytes.append(rawValue) default: let intBytes = toByteArray(intValue) pushData(intBytes.fullHexString) } } private func pushHexString(_ stringValue: String) { let stringBytes = stringValue.dataWithHexString().bytes if stringBytes.count < OpCode.PUSHBYTES75.rawValue { rawBytes += toByteArrayWithoutTrailingZeros(stringBytes.count) rawBytes += stringBytes } else if stringBytes.count < 0x100 { pushOPCode(.PUSHDATA1) rawBytes += toByteArrayWithoutTrailingZeros(stringBytes.count) rawBytes += stringBytes } else if stringBytes.count < 0x10000 { pushOPCode(.PUSHDATA2) rawBytes += toByteArrayWithoutTrailingZeros(stringBytes.count) rawBytes += stringBytes } else { pushOPCode(.PUSHDATA4) rawBytes += toByteArrayWithoutTrailingZeros(stringBytes.count) rawBytes += stringBytes } } private func pushArray(_ arrayValue: [Any?]) { for elem in arrayValue { pushData(elem) } pushInt(arrayValue.count) pushOPCode(.PACK) } private func pushTypedArray(_ arrayValue: [dAppProtocol.Arg?]) { for elem in arrayValue { pushTypedData(elem) } pushInt(arrayValue.count) pushOPCode(.PACK) } public func resetScript() { rawBytes.removeAll() } public func pushData(_ data: Any?) { if let boolValue = data as? Bool { pushBool(boolValue) } else if let intValue = data as? Int { pushInt(intValue) } else if let stringValue = data as? String { pushHexString(stringValue) } else if let arrayValue = data as? [Any?] { pushArray(arrayValue) } else if data == nil { pushBool(false) } else { fatalError("Unsupported Data Type Pushed on stack") } } public func pushTypedData(_ data: dAppProtocol.Arg?) { guard let unwrappedData = data else { pushBool(false) return } let type = unwrappedData.type.lowercased() if type == "string" || type == "hash160" { pushHexString(unwrappedData.value.toHexString()) } else if type == "address" { pushHexString(unwrappedData.value.hashFromAddress()) } else if type == "boolean" { pushBool(NSString(string: unwrappedData.value).boolValue) } else if type == "integer" { pushInt(Int(unwrappedData.value)!) } else if type == "bytearray" { pushHexString(unwrappedData.value) } else if type == "array" { let decoder = JSONDecoder() let responseData = try? JSONSerialization.data(withJSONObject: unwrappedData.value as Any, options: .prettyPrinted) let array = try! decoder.decode([dAppProtocol.Arg?].self, from: responseData!) pushTypedArray(array) } } public func pushContractInvoke(scriptHash: String, operation: String? = nil, args: Any? = nil, useTailCall: Bool = false) { pushData(args) if let operation = operation { let hex = operation.unicodeScalars.filter { $0.isASCII }.map { String(format: "%X", $0.value) }.joined() pushData(hex) } if scriptHash.count != 40 { fatalError("Attempting to invoke invalid contract") } if useTailCall { pushOPCode(.TAILCALL) } else { pushOPCode(.APPCALL) let toAppendBytes = scriptHash.dataWithHexString().bytes.reversed() rawBytes += toAppendBytes } } public func pushTypedContractInvoke(scriptHash: String, operation: String? = nil, args: [dAppProtocol.Arg?], useTailCall: Bool = false) { if (!args.isEmpty) { pushTypedArray(args.reversed()) } else { pushBool(false) } if let operation = operation { let hex = operation.unicodeScalars.filter { $0.isASCII }.map { String(format: "%X", $0.value) }.joined() pushData(hex) } if scriptHash.count != 40 { fatalError("Attempting to invoke invalid contract") } if useTailCall { pushOPCode(.TAILCALL) } else { pushOPCode(.APPCALL) let toAppendBytes = scriptHash.dataWithHexString().bytes.reversed() rawBytes += toAppendBytes } } } <file_sep>/Qlink/Vender/QLC/qlc/bean/QLCToken.swift // // Token.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import BigInt import HandyJSON public class QLCToken:HandyJSON { public var tokenId:String? public var tokenName:String? public var tokenSymbol:String? public var totalSupply:BigUInt? public var decimals:Int? public var owner:String? public var pledgeAmount:BigUInt? public var withdrawTime:Int? required public init() {} public func mapping(mapper: HelpingMapper) { mapper <<< totalSupply <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) mapper <<< pledgeAmount <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) } public static func getTokenByTokenName(tokenName:String, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) throws { LedgerRpc.tokenInfoByName(token: tokenName, successHandler: { (response) in if response != nil { let dic = response as! Dictionary<String, Any> let token = QLCToken.deserialize(from: dic) successHandler(token) } else { successHandler(nil) } }) { (error, message) in failureHandler(error, message) } } } <file_sep>/Qlink/Vender/NEO/Models/NeoScanBalance.swift // // NeoScanBalance.swift // NeoSwift // // Created by <NAME> on 4/2/18. // Copyright © 2018 O3 Labs Inc. All rights reserved. // import Foundation public struct NeoScanGetBalance: Codable { public let balance: [Balance] public let address: String enum CodingKeys: String, CodingKey { case balance = "balance" case address = "address" } } public struct Balance: Codable { public let unspent: [NeoScanUnspent] public let asset: String public let amount: Double enum CodingKeys: String, CodingKey { case unspent = "unspent" case asset = "asset" case amount = "amount" } } public struct NeoScanUnspent: Codable { public let value: Double public let txid: String public let n: Int enum CodingKeys: String, CodingKey { case value = "value" case txid = "txid" case n = "n" } } <file_sep>/Qlink/Vender/NEO/UserDefaultsManager.swift // // UserDefaultsManager.swift // O3 // // Created by <NAME> on 10/9/17. // Copyright © 2017 drei. All rights reserved. // import Foundation class UserDefaultsManager { private static let networkKey = "networkKey" static var network: NeoNetwork { #if TESTNET return .test #endif #if PRIVATENET return .privateNet #endif return .main } private static let useDefaultSeedKey = "usedDefaultSeedKey" static var useDefaultSeed: Bool { get { #if TESTNET return false #endif #if PRIVATENET return false #endif return UserDefaults.standard.bool(forKey: useDefaultSeedKey) } set { if newValue { if let bestNode = NEONetworkMonitor.autoSelectBestNode(network: AppState.network) { UserDefaults.standard.set(newValue, forKey: useDefaultSeedKey) AppState.bestSeedNodeURL = bestNode UserDefaultsManager.seed = bestNode } } else { UserDefaults.standard.set(newValue, forKey: useDefaultSeedKey) UserDefaults.standard.synchronize() } } } private static let seedKey = "seedKey" static var seed: String { get { return UserDefaults.standard.string(forKey: seedKey)! } set { UserDefaults.standard.set(newValue, forKey: seedKey) UserDefaults.standard.synchronize() NotificationCenter.default.post(name: Notification.Name("ChangedNetwork"), object: nil) } } private static let selectedThemeIndexKey = "selectedThemeIndex" static var themeIndex: Int { get { let intValue = UserDefaults.standard.integer(forKey: selectedThemeIndexKey) if intValue != 0 && intValue != 1 { return 0 } return intValue } set { UserDefaults.standard.set(newValue, forKey: selectedThemeIndexKey) UserDefaults.standard.synchronize() } } // static var theme: Theme { // return themeIndex == 0 ? Theme.light: Theme.dark // } private static let launchedBeforeKey = "launchedBeforeKey" static var launchedBefore: Bool { get { let value = UserDefaults.standard.bool(forKey: launchedBeforeKey) return value } set { UserDefaults.standard.set(newValue, forKey: launchedBeforeKey) UserDefaults.standard.synchronize() } } private static let o3WalletAddressKey = "o3WalletAddressKey" static var o3WalletAddress: String? { get { let stringValue = UserDefaults.standard.string(forKey: o3WalletAddressKey) return stringValue } set { UserDefaults.standard.set(newValue, forKey: o3WalletAddressKey) UserDefaults.standard.synchronize() } } private static let referenceFiatCurrencyKey = "referenceCurrencyKey" static var referenceFiatCurrency: Currency { get { let stringValue = UserDefaults.standard.string(forKey: referenceFiatCurrencyKey) if stringValue == nil { return Currency.usd } return Currency(rawValue: stringValue!)! } set { UserDefaults.standard.set(newValue.rawValue, forKey: referenceFiatCurrencyKey) UserDefaults.standard.synchronize() NotificationCenter.default.post(name: Notification.Name("ChangedReferenceCurrency"), object: nil) } } private static let reviewClaimsKey = "reviewClaimsKey" static var numClaims: Int { get { let intValue = UserDefaults.standard.integer(forKey: reviewClaimsKey) return intValue } set { UserDefaults.standard.set(newValue, forKey: reviewClaimsKey) UserDefaults.standard.synchronize() } } private static let numOrdersKey = "numOrdersKey" static var numOrders: Int { get { let intValue = UserDefaults.standard.integer(forKey: numOrdersKey) return intValue } set { UserDefaults.standard.set(newValue, forKey: numOrdersKey) UserDefaults.standard.synchronize() } } private static let hasAgreedDappDisclaimerKey = "hasAgreedDapps" static var hasAgreedDapps: Bool { get { let boolValue = UserDefaults.standard.bool(forKey: hasAgreedDappDisclaimerKey) return boolValue } set { UserDefaults.standard.set(newValue, forKey: hasAgreedDappDisclaimerKey) UserDefaults.standard.synchronize() } } private static let hasAgreedAnalyticsDisclaimerKey = "hasAgreedAnalytics" static var hasAgreedAnalytics: Bool { get { let boolValue = UserDefaults.standard.bool(forKey: hasAgreedAnalyticsDisclaimerKey) return boolValue } set { UserDefaults.standard.set(newValue, forKey: hasAgreedAnalyticsDisclaimerKey) UserDefaults.standard.synchronize() } } } <file_sep>/Qlink/Vender/NEO/Models/NEONetwork.swift // // NEONetwork.swift // NeoSwift // // Created by <NAME> on 10/21/17. // Copyright © 2017 drei. All rights reserved. // import Foundation struct Nodes: Codable { let neo: ChainNetwork let ontology: ChainNetwork enum CodingKeys: String, CodingKey { case neo case ontology } } struct ChainNetwork: Codable { let blockCount: Int let best: String let nodes: [String] enum CodingKeys: String, CodingKey { case blockCount case best case nodes } } <file_sep>/Qlink/Vender/NEO/Models/Peer.swift // // Peer.swift // NeoSwift // // Created by <NAME> on 10/21/17. // Copyright © 2017 drei. All rights reserved. // public struct Peer: Codable { public var address: String public var port: UInt enum CodingKeys: String, CodingKey { case address = "address" case port = "port" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let address: String = try container.decode(String.self, forKey: .address) let port: UInt = try container.decode(UInt.self, forKey: .port) self.init(address: address, port: port) } public init(address: String, port: UInt) { self.address = address self.port = port } } public struct GetPeersResult: Codable { public var unconnected: [Peer] public var connected: [Peer] public var bad: [Peer] enum CodingKeys: String, CodingKey { case unconnected = "unconnected" case connected = "connected" case bad = "bad" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let unconnected: [Peer] = try container.decode([Peer].self, forKey: .unconnected) let connected: [Peer] = try container.decode([Peer].self, forKey: .connected) let bad: [Peer] = try container.decode([Peer].self, forKey: .bad) self.init(unconnected: unconnected, connected: connected, bad: bad) } public init(unconnected: [Peer], connected: [Peer], bad: [Peer]) { self.unconnected = unconnected self.connected = connected self.bad = bad } } <file_sep>/Podfile source 'https://github.com/CocoaPods/Specs.git' platform :ios, '10.0' inhibit_all_warnings! use_frameworks! # shadowsock-----pod def model # 3.11.1 pod 'RealmSwift', '3.7.6' end def socket pod 'CocoaAsyncSocket', '~> 7.4.3' end def library pod 'KissXML', '~> 5.2.2' #pod 'ICSMainFramework', :path => "./Library/ICSMainFramework/" pod 'MMWormhole', '~> 2.0.0' pod 'KeychainAccess' end def tunnel pod 'MMWormhole', '~> 2.0.0' end def eth pod 'BigInt', '~> 3.0' pod 'R.swift' # pod 'JSONRPCKit', :git=> 'https://github.com/bricklife/JSONRPCKit.git' pod 'JSONRPCKit', '3.0.0' pod 'PromiseKit', '~> 6.0' pod 'APIKit' # pod 'Eureka' pod 'Eureka', '4.2.0' pod 'KeychainSwift' pod 'Moya', '~> 10.0.1' pod 'TrustCore', :git=>'https://github.com/TrustWallet/trust-core', :branch=>'master' pod 'TrustKeystore', :git=>'https://github.com/TrustWallet/trust-keystore', :branch=>'master' # pod 'TrezorCrypto' pod 'TrustWeb3Provider', :git=>'https://github.com/TrustWallet/trust-web3-provider', :commit=>'<PASSWORD>b8fa4<PASSWORD>babe85<PASSWORD>543dfd' pod 'TrustWalletSDK', :git=>'https://github.com/TrustWallet/TrustSDK-iOS', :branch=>'master' # pod 'Result', '~> 3.0' end target "Qlink" do pod 'AFNetworking' pod 'IQKeyboardManager' pod 'Masonry' pod 'MJExtension' pod 'MBProgressHUD' pod 'SDWebImage' # pod 'MJRefresh' pod 'Hero' # pod 'FMDB' pod 'BGFMDB' pod 'CocoaLumberjack/Swift' pod 'Bugly' pod 'OLImageView' pod 'Firebase/Core', '~> 5.4.1' # pod 'MMWormhole' # pod 'TagListView' pod 'TTGTagCollectionView' pod 'Charts', '3.1.0' pod 'SwiftTheme', '0.4.1' pod 'TYCyclePagerView' pod 'MJRefresh' # shadowsock pod 'SwiftColor' pod 'AsyncSwift' pod 'Appirater' pod 'HandyJSON' # pod 'NinaPagerView' # qlc_sign # pod 'TrezorCryptoEd25519WithBlake2b' tunnel library #fabric socket model eth end post_install do |installer| installer.pods_project.targets.each do |target| # if ['JSONRPCKit'].include? target.name # target.build_configurations.each do |config| # config.build_settings['SWIFT_VERSION'] = '3.0' # end # end if ['TrustKeystore'].include? target.name target.build_configurations.each do |config| config.build_settings['SWIFT_OPTIMIZATION_LEVEL'] = '-Owholemodule' end end # if target.name != 'Realm' # target.build_configurations.each do |config| # config.build_settings['MACH_O_TYPE'] = 'staticlib' # end # end end end <file_sep>/Qlink/Vender/QLC/qlc/network/LedgerServices.swift // // LedgerServices.swift // TestJsonRPC // // Created by <NAME> on 2019/5/29. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import APIKit import JSONRPCKit struct LedgerServiceRequest<Batch: JSONRPCKit.Batch>: APIKit.Request { let batch: Batch typealias Response = Batch.Responses var baseURL: URL { let environment:String? = UserDefaults.standard.object(forKey: QLCChain_Environment) as! String? if environment == nil || environment == "1" { return URL(string: qlc_seed_pro)! } else { return URL(string: qlc_seed_dev)! } } var method: HTTPMethod { return .post } var path: String { return "/" } var parameters: Any? { return batch.requestObject } public func intercept(urlRequest: URLRequest) throws -> URLRequest { var urlRequest = urlRequest urlRequest.timeoutInterval = timeoutInterval return urlRequest } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response { return try batch.responses(from: object) } } struct CastError<ExpectedType>: Error { let actualValue: Any let expectedType: ExpectedType.Type } struct AccountInfo: JSONRPCKit.Request { typealias Response = [String:Any] let address: String var method: String { return "ledger_accountInfo" } var parameters: Any? { return [address] } func response(from resultObject: Any) throws -> Response { if let response = resultObject as? Response { return response } else { throw CastError(actualValue: resultObject, expectedType: Response.self) } } } struct AccountHistoryTopn: JSONRPCKit.Request { typealias Response = [Any] let address: String var method: String { return "ledger_accountHistoryTopn" } var parameters: Any? { return [address,20,0] } func response(from resultObject: Any) throws -> Response { if let response = resultObject as? Response { return response } else { throw CastError(actualValue: resultObject, expectedType: Response.self) } } } struct TokenInfoByName: JSONRPCKit.Request { typealias Response = [String: Any] let token: String var method: String { return "ledger_tokenInfoByName" } var parameters: Any? { return [token] } func response(from resultObject: Any) throws -> Response { if let response = resultObject as? Response { return response } else { throw CastError(actualValue: resultObject, expectedType: Response.self) } } } struct BlocksInfo: JSONRPCKit.Request { typealias Response = [Any] let hashArr: Array<String> var method: String { return "ledger_blocksInfo" } var parameters: Any? { return [hashArr] } func response(from resultObject: Any) throws -> Response { if let response = resultObject as? Response { return response } else { throw CastError(actualValue: resultObject, expectedType: Response.self) } } } struct AccountsPending: JSONRPCKit.Request { typealias Response = [String: Any] let addressArr: Array<String> // let address : String var method: String { return "ledger_accountsPending" } var parameters: Any? { return [addressArr, -1] // return [[address], -1] } func response(from resultObject: Any) throws -> Response { if let response = resultObject as? Response { return response } else { throw CastError(actualValue: resultObject, expectedType: Response.self) } } } struct Process: JSONRPCKit.Request { typealias Response = String let dic: Dictionary<String, Any> var method: String { return "ledger_process" } var parameters: Any? { return [dic] } func response(from resultObject: Any) throws -> Response { if let response = resultObject as? Response { return response } else { throw CastError(actualValue: resultObject, expectedType: Response.self) } } } struct Tokens: JSONRPCKit.Request { typealias Response = [Any] var method: String { return "ledger_tokens" } var parameters: Any? { return [] } func response(from resultObject: Any) throws -> Response { if let response = resultObject as? Response { return response } else { throw CastError(actualValue: resultObject, expectedType: Response.self) } } } struct GetReceiveRewardBlock: JSONRPCKit.Request { typealias Response = [String: Any] let hashHex : String var method: String { return "rewards_getReceiveRewardBlock" } var parameters: Any? { return [hashHex] } func response(from resultObject: Any) throws -> Response { if let response = resultObject as? Response { return response } else { throw CastError(actualValue: resultObject, expectedType: Response.self) } } } <file_sep>/Qlink/Vender/QLC/qlc/utils/Ed25519.swift // // Ed25519.swift // libEd25519Blake2b // // Created by Stone on 2018/9/3. // import Foundation //import TrezorCryptoEd25519WithBlake2b import TrezorCrypto public struct Ed25519 { public static let secretKeyLength = 32 public static let publicKeyLength = 32 public static let signatureLength = 64 // public static let curved25519KeyLength = 32 // public static func generateKeypair() -> (secretKey: Bytes, publicKey: Bytes) { // let s = randombytesUnsafe(length: secretKeyLength) // let p = publicKey(secretKey: s) // return (s, p) // } // // public static func randombytesUnsafe(length: Int) -> Bytes { // var numbers = Bytes(count: length) // ed25519_randombytes_unsafe(&numbers, length) // return numbers // } public static func publicKey(secretKey: Bytes) -> Bytes { var publickey = Bytes(count: publicKeyLength) ed25519_publickey(secretKey, &publickey) return publickey } public static func sign(message: Bytes, secretKey: Bytes, publicKey: Bytes) -> Bytes { var signature = Bytes(count: signatureLength) ed25519_sign(message, Int(message.count), secretKey, publicKey, &signature) return signature } public static func signOpen(message: Bytes, publicKey: Bytes, signature: Bytes) -> Bool { return ed25519_sign_open(message, Int(message.count), publicKey, signature) == 0 } } <file_sep>/Qlink/Vender/QLC/qlc/utils/Helper.swift // // Helper.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/14. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation public class Helper { public static func getSeed() -> String { let uuid : String = UUID().uuidString.replacingOccurrences(of: "-", with: "") // let data : Data = uuid.data(using: String.Encoding.utf8) ?? "" let data = Data(hex: uuid) let seed : String = data.toHexString() return seed } public static func reverse(v: Bytes) -> Bytes { var result = Bytes(count: v.count) for (index, _) in v.enumerated() { result[index] = v[v.count-index-1]; } return result; } } extension Data { public init(hex: String) { self.init(bytes: Array<UInt8>(hex: hex)) } public var bytes_qlc: Array<UInt8> { return Array(self) } public func toHexString() -> String { return bytes_qlc.toHexString() } } extension Array { public init(reserveCapacity: Int) { self = Array<Element>() self.reserveCapacity(reserveCapacity) } var slice: ArraySlice<Element> { return self[self.startIndex ..< self.endIndex] } } extension Array where Element == UInt8 { public init(hex: String) { self.init(reserveCapacity: hex.unicodeScalars.lazy.underestimatedCount) var buffer: UInt8? var skip = hex.hasPrefix("0x") ? 2 : 0 for char in hex.unicodeScalars.lazy { guard skip == 0 else { skip -= 1 continue } guard char.value >= 48 && char.value <= 102 else { removeAll() return } let v: UInt8 let c: UInt8 = UInt8(char.value) switch c { case let c where c <= 57: v = c - 48 case let c where c >= 65 && c <= 70: v = c - 55 case let c where c >= 97: v = c - 87 default: removeAll() return } if let b = buffer { append(b << 4 | v) buffer = nil } else { buffer = v } } if let b = buffer { append(b) } } public func toHexString() -> String { return `lazy`.reduce("") { var s = String($1, radix: 16) if s.count == 1 { s = "0" + s } return $0 + s } } } //public typealias Bytes = Array<UInt8> // //public extension Bytes { // var bytes2Hex: String { // var hexResult : String = String() // for ten in self { // let hex = String(ten,radix:16) // hexResult.append(hex) // } // return hexResult // } // // var bytes2Binary: String { // var binaryResult : String = String() // for ten in self { // let binary = String(ten,radix:2) // binaryResult.append(binary) // } // return binaryResult // } //} // //extension Array where Element == UInt8 { // init (count bytes: Int) { // self.init(repeating: 0, count: bytes) // } //} // //public extension String { // var hex2Bytes: Bytes { // // if self.unicodeScalars.lazy.underestimatedCount % 2 != 0 { // return [] // } // // var bytes = Bytes() // bytes.reserveCapacity(self.unicodeScalars.lazy.underestimatedCount / 2) // // var buffer: UInt8? // var skip = self.hasPrefix("0x") ? 2 : 0 // for char in self.unicodeScalars.lazy { // guard skip == 0 else { // skip -= 1 // continue // } // guard char.value >= 48 && char.value <= 102 else { // return [] // } // let v: UInt8 // let c: UInt8 = UInt8(char.value) // switch c { // case let c where c <= 57: // v = c - 48 // case let c where c >= 65 && c <= 70: // v = c - 55 // case let c where c >= 97: // v = c - 87 // default: // return [] // } // if let b = buffer { // bytes.append(b << 4 | v) // buffer = nil // } else { // buffer = v // } // } // if let b = buffer { // bytes.append(b) // } // // return bytes // } // // var hex2Binary : String { // var resultBinary: String = "" // let byte = self.hex2Bytes // resultBinary = byte.bytes2Binary // return resultBinary // } //} public extension Dictionary { var JSONString : String { if (!JSONSerialization.isValidJSONObject(self)) { print("无法解析出JSONString") return "" } let data : NSData! = try! JSONSerialization.data(withJSONObject: self, options: []) as NSData? let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue) return JSONString! as String } } <file_sep>/Qlink/Vender/QLC/qlc/utils/Blake2.swift // // Blake2.swift // libEd25519Blake2b // // Created by Stone on 2018/9/4. // import Foundation import TrezorCrytoEd25519 public struct Blake2b { public static func hash(outLength: Int, in: Bytes, key: Bytes? = nil) -> Bytes? { var out = Bytes(count: outLength) if let key = key { blake2b_Key_qlc(`in`, UInt32(`in`.count), key, key.count, &out, outLength) } else { blake2b_qlc(`in`, UInt32(`in`.count), &out, outLength) } return out } } <file_sep>/Qlink/Vender/QLC/qlc/mng/TransactionMng.swift // // TransactionMng.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import BigInt import HandyJSON public class TransactionMng { /** * * @Description Return send block by send parameter and private key * @param * send parameter for the block * from: send address for the transaction * to: receive address for the transaction * tokenName: token name * amount: transaction amount * sender: optional, sms sender * receiver: optional, sms receiver * message: optional, sms message hash * string: private key * @return JSONObject send block * @throws QlcException * @throws IOException */ public static func sendBlock(from:String, tokenName:String, to:String, amount: BigUInt, sender:String, receiver:String, message:String, privateKeyB: Bytes, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) throws { // token info var token: QLCToken? = nil try? QLCToken.getTokenByTokenName(tokenName: tokenName, successHandler: { (response) in if response != nil { token = response as? QLCToken // send address token info var tokenMeta : QLCTokenMeta? = nil try? TokenMetaMng.getTokenMeta(tokenHash: token!.tokenId!, address: from, successHandler: { (response) in if response != nil { tokenMeta = response as? QLCTokenMeta if tokenMeta!.balance! < amount { print(QLCConstants.EXCEPTION_MSG_1000, "(balance:",String(tokenMeta!.balance!) ,", need:",String(amount),")") failureHandler(nil, nil) return } // previous block info var previousBlock : QLCStateBlock? try? LedgerMng.blocksInfo(blockHash: tokenMeta!.header!.hex2Bytes, successHandler: { (response) in if response != nil { previousBlock = response as? QLCStateBlock // create send block TransactionMng.fillSendBlock(token: token!, from: from, tokenMeta: tokenMeta!, amount: amount, to: to, sender: sender, receiver: receiver, message: message, previousBlock: previousBlock!, privateKeyB: privateKeyB, resultHandler: { (dic) in successHandler(dic) }) } else { failureHandler(nil, nil) } }, failureHandler: { (error, message) in print("getBlockInfoByHash = ",message ?? "") failureHandler(error, message) }) } else { failureHandler(nil, nil) } }, failureHandler: { (error, message) in print("getTokenMeta = ",message ?? "") failureHandler(error, message) }) } else { failureHandler(nil, nil) } }) { (error, message) in print("getTokenByTokenName = ",message ?? "") failureHandler(error, message) } } private static func fillSendBlock(token:QLCToken, from:String, tokenMeta:QLCTokenMeta, amount: BigUInt, to: String, sender: String, receiver: String, message: String, previousBlock: QLCStateBlock, privateKeyB:Bytes, resultHandler: @escaping ((Dictionary<String, Any>?) -> Void)) { let block = QLCStateBlock.factory(type: QLCConstants.BLOCK_TYPE_SEND, token: token.tokenId ?? "", address: from, balance: BigUInt(tokenMeta.balance!-amount), previous: tokenMeta.header ?? "", link: QLCUtil.addressToPublicKey(address: to), timestamp: Int64(Date().timeIntervalSince1970), representative: tokenMeta.representative ?? "") if !sender.isEmpty { block.sender = sender } if !receiver.isEmpty { block.receiver = receiver } if !message.isEmpty { block.message = message } else { block.message = QLCConstants.ZERO_HASH } block.vote = previousBlock.vote == nil ? BigUInt(0) : previousBlock.vote block.network = previousBlock.network == nil ? BigUInt(0) : previousBlock.network block.storage = previousBlock.storage == nil ? BigUInt(0) : previousBlock.storage block.oracle = previousBlock.oracle == nil ? BigUInt(0) : previousBlock.oracle block.povHeight = previousBlock.povHeight == nil ? 0 : previousBlock.povHeight if previousBlock.extra != nil && !previousBlock.extra!.isEmpty { block.extra = previousBlock.extra } else { block.extra = QLCConstants.ZERO_HASH } // block hash let hash = BlockMng.getHash(block: block) // let hashHex = hash.toHexString() if hash.count == 0 { print(QLCConstants.EXCEPTION_BLOCK_MSG_2000) resultHandler(nil) // return nil } let privateKey = privateKeyB.toHexString() if (privateKey.count == 64) { // send address info let sendAddress = QLCAddress.factory(address: from, publicKey: QLCUtil.addressToPublicKey(address: from), privateKey: privateKey) // set signature let priKey = sendAddress.privateKey!.replacingOccurrences(of: sendAddress.publicKey!, with: "") let pubKey = sendAddress.publicKey! let signature = QLCUtil.sign(message: hash.toHexString(), secretKey: priKey, publicKey: pubKey) let signCheck : Bool = QLCUtil.signOpen(message: hash.toHexString(), publicKey: pubKey, signature: signature) if !signCheck { print(QLCConstants.EXCEPTION_MSG_1005) resultHandler(nil) // return nil } block.signature = signature // set work let workHash = BlockMng.getRoot(block: block) ?? "" WorkUtil.generateWorkOfOperationRandom(hash: workHash) { (work,isTimeOut) in if isTimeOut == true { RequestService.testRequest(withBaseURLStr: "http://pow1.qlcchain.org/work", params: ["root":workHash], httpMethod: HttpMethodGet, userInfo: nil, successBlock: { (task, response) in block.work = (response as! String?) ?? "" resultHandler(block.toJSON()) }, failedBlock: { (task, error) in block.work = "" resultHandler(block.toJSON()) }) } else { block.work = work resultHandler(block.toJSON()) } } } } /** * * @Description Return receive block by send block and private key * @param sendBlock * @param privateKey * @throws QlcException * @throws IOException * @return JSONObject */ public static func receiveBlock(sendBlock:QLCStateBlock, receiveAddress:String, privateKeyB:Bytes, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) throws { // the block hash let sendBlockHash:Bytes = BlockMng.getHash(block: sendBlock) // is contract send block if (QLCConstants.BLOCK_TYPE_CONTRACTSEND == sendBlock.type && QLCConstants.LINNK_TYPE_AIRDORP == sendBlock.link) { // create reward block let hashHex = sendBlock.hash let hashHex1 = sendBlockHash.toHexString() try? RewardsMng.getReceiveRewardBlock(hashHex: hashHex, successHandler: { (response) in if response != nil { let receiveBlock:QLCStateBlock = response as! QLCStateBlock successHandler(receiveBlock.toJSON()) } else { failureHandler(nil, nil) } }) { (error, message) in print("rewards_getReceiveRewardBlock = ",message ?? "") failureHandler(error, message) } return } // check the receive address let tempReceiveAddress:String = QLCUtil.publicKeyToAddress(publicKey: sendBlock.link ?? "") if (tempReceiveAddress != receiveAddress) { print(QLCConstants.EXCEPTION_BLOCK_MSG_2000 + ", receive address is [" + tempReceiveAddress + "]") failureHandler(nil, nil) return } // is send block if (QLCConstants.BLOCK_TYPE_SEND != sendBlock.type ?? "") { print(QLCConstants.EXCEPTION_BLOCK_MSG_2002 + ", block hash[" + sendBlockHash.toHexString() + "]") failureHandler(nil, nil) return } // Does the send block exist var tempBlock:QLCStateBlock? try? LedgerMng.blocksInfo(blockHash: sendBlockHash, successHandler: { (response) in if response != nil { tempBlock = response as? QLCStateBlock if (tempBlock == nil) { print(QLCConstants.EXCEPTION_BLOCK_MSG_2003 + ", block hash[" + sendBlockHash.toHexString() + "]") failureHandler(nil, nil) return } // check private key and link let priKey = privateKeyB.toHexString() let pubKey = QLCUtil.privateKeyToPublicKey(privateKey: priKey) if pubKey != sendBlock.link { print(QLCConstants.EXCEPTION_BLOCK_MSG_2004) failureHandler(nil, nil) return } let receiveAddress = QLCUtil.publicKeyToAddress(publicKey: sendBlock.link ?? "") // pending info var info: QLCPendingInfo? var pending: QLCPending? try? LedgerMng.accountsPending(address: receiveAddress, successHandler: { (response) in if response != nil { pending = (response as! QLCPending) let itemList = pending?.infoList if itemList != nil && itemList!.count > 0 { var tempInfo:QLCPendingInfo? for item in itemList! { tempInfo = item if tempInfo?.Hash == sendBlockHash.toHexString() { info = tempInfo break } tempInfo = nil } } if info == nil { print(QLCConstants.EXCEPTION_BLOCK_MSG_2005) failureHandler(nil, nil) return } // has token meta var tokenMeta:QLCTokenMeta? try? TokenMetaMng.getTokenMeta(tokenHash: sendBlock.token!, address: receiveAddress, successHandler: { (response) in // if response != nil { tokenMeta = (response as! QLCTokenMeta?) var has = false if tokenMeta != nil { has = true } if has == true { // previous block info var previousBlock : QLCStateBlock? try? LedgerMng.blocksInfo(blockHash: tokenMeta!.header!.hex2Bytes, successHandler: { (response) in if response != nil { previousBlock = response as? QLCStateBlock // create receiver block TransactionMng.fillReceiveBlock(has: has, receiveAddress: receiveAddress, tokenMeta: tokenMeta!, info: info!, previousBlock: previousBlock!, sendBlockHash: sendBlockHash, sendBlock: sendBlock, privateKeyB: privateKeyB, resultHandler: { (dic) in successHandler(dic) }); } else { failureHandler(nil, nil) } }, failureHandler: { (error, message) in print("getBlockInfoByHash = ",message ?? "") failureHandler(error, message) }) } else { // has == false // create receiver block TransactionMng.fillReceiveBlock(has: has, receiveAddress: receiveAddress, tokenMeta: nil, info: info!, previousBlock: nil, sendBlockHash: sendBlockHash, sendBlock: sendBlock, privateKeyB: privateKeyB, resultHandler: { (dic) in successHandler(dic) }); } // } else { // failureHandler(nil, nil) // } }, failureHandler: { (error, message) in print("getTokenMeta = ",message ?? "") if message == "account not found" { // 第一次接收 let has = false // create receiver block TransactionMng.fillReceiveBlock(has: has, receiveAddress: receiveAddress, tokenMeta: nil, info: info!, previousBlock: nil, sendBlockHash: sendBlockHash, sendBlock: sendBlock, privateKeyB: privateKeyB, resultHandler: { (dic) in successHandler(dic) }); } else { failureHandler(error, message) } }) } else { failureHandler(nil, nil) } }, failureHandler: { (error, message) in print("getAccountPending = ",message ?? "") failureHandler(error, message) }) } else { failureHandler(nil, nil) } }) { (error, message) in print("getBlockInfoByHash = ",message ?? "") failureHandler(error, message) } } private static func fillReceiveBlock(has:Bool,receiveAddress:String,tokenMeta:QLCTokenMeta?,info:QLCPendingInfo,previousBlock:QLCStateBlock?,sendBlockHash:Bytes,sendBlock:QLCStateBlock, privateKeyB:Bytes, resultHandler: @escaping ((Dictionary<String, Any>?) -> Void)) { // create receive block let receiveBlock = QLCStateBlock() if (has) { // previous block info receiveBlock.type = QLCConstants.BLOCK_TYPE_RECEIVE receiveBlock.address = receiveAddress receiveBlock.balance = BigUInt(tokenMeta!.balance!+info.amount!) receiveBlock.vote = previousBlock!.vote receiveBlock.network = previousBlock!.network receiveBlock.storage = previousBlock!.storage receiveBlock.oracle = previousBlock!.oracle receiveBlock.previous = tokenMeta!.header receiveBlock.link = sendBlockHash.toHexString() receiveBlock.representative = tokenMeta!.representative receiveBlock.token = tokenMeta!.type receiveBlock.extra = QLCConstants.ZERO_HASH receiveBlock.timestamp = Int64(Date().timeIntervalSince1970) } else { receiveBlock.type = QLCConstants.BLOCK_TYPE_OPEN receiveBlock.address = receiveAddress receiveBlock.balance = info.amount receiveBlock.vote = QLCConstants.ZERO_BIG_INTEGER receiveBlock.network = QLCConstants.ZERO_BIG_INTEGER receiveBlock.storage = QLCConstants.ZERO_BIG_INTEGER receiveBlock.oracle = QLCConstants.ZERO_BIG_INTEGER receiveBlock.previous = QLCConstants.ZERO_HASH receiveBlock.link = sendBlockHash.toHexString() receiveBlock.representative = sendBlock.representative receiveBlock.token = sendBlock.token receiveBlock.extra = QLCConstants.ZERO_HASH receiveBlock.timestamp = Int64(Date().timeIntervalSince1970) } if sendBlock.message == nil || sendBlock.message!.isEmpty { receiveBlock.message = QLCConstants.ZERO_HASH } else { receiveBlock.message = sendBlock.message } receiveBlock.povHeight = QLCConstants.ZERO_LONG let privateKey = privateKeyB.toHexString() if (privateKey.count == 64) { // check private key and link let pubKey = QLCUtil.privateKeyToPublicKey(privateKey: privateKey) if pubKey != sendBlock.link { print(QLCConstants.EXCEPTION_BLOCK_MSG_2004) resultHandler(nil) } // set signature let receiveBlockHash = BlockMng.getHash(block: receiveBlock) let signature = QLCUtil.sign(message: receiveBlockHash.toHexString(), secretKey: privateKey, publicKey: pubKey) let signCheck : Bool = QLCUtil.signOpen(message: receiveBlockHash.toHexString(), publicKey: pubKey, signature: signature) if !signCheck { print(QLCConstants.EXCEPTION_MSG_1005) resultHandler(nil) } receiveBlock.signature = signature // set work let workHash = BlockMng.getRoot(block: receiveBlock) ?? "" WorkUtil.generateWorkOfOperationRandom(hash: workHash) { (work,isTimeOut) in if isTimeOut == true { RequestService.testRequest(withBaseURLStr: "http://pow1.qlcchain.org/work", params: ["root":workHash], httpMethod: HttpMethodGet, userInfo: nil, successBlock: { (task, response) in receiveBlock.work = (response as! String?) ?? "" resultHandler(receiveBlock.toJSON()) }, failedBlock: { (task, error) in receiveBlock.work = "" resultHandler(receiveBlock.toJSON()) }) } else { receiveBlock.work = work resultHandler(receiveBlock.toJSON()) } } } } /** * * @Description Return change block by account and private key * @param address:account address * @param representative:new representative account * @param chainTokenHash:chian token hash * @param privateKey:private key ,if not set ,will return block without signature and work * @return * @return JSONObject * @throws IOException * @throws QlcException */ public static func changeBlock(address:String, representative:String, chainTokenHash:String, privateKeyB:Bytes, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) throws { // check representative var representativeInfo : QLCAccount? try? TokenMetaMng.getAccountMeta(address: representative, successHandler: { (response) in if response != nil { representativeInfo = (response as! QLCAccount) // check address var addressInfo: QLCAccount? try? TokenMetaMng.getAccountMeta(address: address, successHandler: { (response) in if response != nil { addressInfo = (response as! QLCAccount) // account has chain token var tokenMeta:QLCTokenMeta? let tokens = addressInfo!.tokens for item in tokens ?? [] { tokenMeta = item if chainTokenHash == tokenMeta!.type { break } tokenMeta = nil } if tokenMeta == nil { print(QLCConstants.EXCEPTION_BLOCK_MSG_2008 + ", address:[" + address + "]") failureHandler(nil, nil) return } // previous block info var previousBlock:QLCStateBlock? try? LedgerMng.blocksInfo(blockHash: tokenMeta!.header!.hex2Bytes, successHandler: { (response) in if response != nil { previousBlock = response as? QLCStateBlock // create change block TransactionMng.fillChangeBlock(address: address, tokenMeta: tokenMeta!, previousBlock: previousBlock!, representative: representative, privateKeyB: privateKeyB, resultHandler: { (dic) in successHandler(dic) }); } else { print(QLCConstants.EXCEPTION_BLOCK_MSG_2009) failureHandler(nil, nil) } }, failureHandler: { (error, message) in print("getBlockInfoByHash = ",error!.localizedDescription) failureHandler(nil, nil) }) } else { print(QLCConstants.EXCEPTION_BLOCK_MSG_2007 + ", address:[" + address + "]") failureHandler(nil, nil) } }, failureHandler: { (error, message) in print("getAccountMeta = ",error!.localizedDescription) failureHandler(error, message) }) } else { print(QLCConstants.EXCEPTION_BLOCK_MSG_2006 + "[" + representative + "]") failureHandler(nil, nil) } }, failureHandler: { (error, message) in print("getAccountMeta = ",message) failureHandler(error, message) }) } private static func fillChangeBlock(address:String,tokenMeta:QLCTokenMeta,previousBlock:QLCStateBlock,representative:String, privateKeyB:Bytes, resultHandler: @escaping ((Dictionary<String, Any>?) -> Void)){ // create change block let changeBlock : QLCStateBlock = QLCStateBlock() changeBlock.type = QLCConstants.BLOCK_TYPE_CHANGE changeBlock.address = address changeBlock.balance = tokenMeta.balance changeBlock.vote = previousBlock.vote changeBlock.network = previousBlock.network changeBlock.storage = previousBlock.storage changeBlock.oracle = previousBlock.oracle changeBlock.previous = tokenMeta.header changeBlock.link = QLCConstants.ZERO_HASH changeBlock.representative = representative changeBlock.token = tokenMeta.type changeBlock.extra = QLCConstants.ZERO_HASH changeBlock.timestamp = Int64(Date().timeIntervalSince1970) changeBlock.message = QLCConstants.ZERO_HASH changeBlock.povHeight = QLCConstants.ZERO_LONG let privateKey = privateKeyB.toHexString() if (privateKey.count == 64 || privateKey.count == 128) { // check private key and link let priKey = privateKey.toHexString() let pubKey = QLCUtil.privateKeyToPublicKey(privateKey: priKey) if address != QLCUtil.publicKeyToAddress(publicKey: pubKey) { // throw new QlcException(Constants.EXCEPTION_BLOCK_CODE_2004, Constants.EXCEPTION_BLOCK_MSG_2004); print(QLCConstants.EXCEPTION_BLOCK_MSG_2004) resultHandler(nil) } // set signature let changeBlockHash = BlockMng.getHash(block: changeBlock) let signature = QLCUtil.sign(message: changeBlockHash.toHexString(), secretKey: priKey, publicKey: pubKey) let signCheck : Bool = QLCUtil.signOpen(message: changeBlockHash.toHexString(), publicKey: pubKey, signature: signature) if !signCheck { print(QLCConstants.EXCEPTION_MSG_1005) resultHandler(nil) } changeBlock.signature = signature // set work let workHash = BlockMng.getRoot(block: changeBlock) ?? "" WorkUtil.generateWorkOfOperationRandom(hash: workHash) { (work,isTimeOut) in if isTimeOut == true { RequestService.testRequest(withBaseURLStr: "http://pow1.qlcchain.org/work", params: ["root":workHash], httpMethod: HttpMethodGet, userInfo: nil, successBlock: { (task, response) in changeBlock.work = (response as! String?) ?? "" resultHandler(changeBlock.toJSON()) }, failedBlock: { (task, error) in changeBlock.work = "" resultHandler(changeBlock.toJSON()) }) } else { changeBlock.work = work resultHandler(changeBlock.toJSON()) } } } } } <file_sep>/README.md # WinQ WinQ is a dApp developed by QLC team, dedicated to WiFi and VPN sharing powered by blockchain technology. WinQ is powered by NEO blockchain at the current stage. Features of WinQ - Wallet that holds QLC, NEO, GAS, BNB - WiFi Sharing - Crowd-sourced VPN Market Place ## Bugs/Feedback If you run into any issues, please use the [GitHub Issue Tracker](https://github.com/qlcchain/WinQ-iOS/issues) We are continually improving and adding new features based on the feedback you provide, so please let your opinions be known! ## Links & Resources - [QLC Website](https://qlcchain.org) - [Discord Chat](https://discord.gg/JnCnhjr) - [Reddit](https://www.reddit.com/r/Qlink/) - [Medium](https://medium.com/qlc-chain) - [Twitter](https://twitter.com/QLCchain) - [Telegram](https://t.me/qlinkmobile) ## License MIT <file_sep>/Qlink/Vender/NEO/NEOGasUtil.swift // // NEOGasUtil.swift // Qlink // // Created by <NAME> on 2018/11/20. // Copyright © 2018 pan. All rights reserved. // import UIKit class NEOGasUtil: NSObject { static let swiftSharedInstance = NEOGasUtil() //在oc中这样写才能被调用 @objc open class func sharedInstance() -> NEOGasUtil { return NEOGasUtil.swiftSharedInstance } // var claims: Claims? var claims: Claimable? var isClaiming: Bool = false var neoBalance: Int? = 0 // var gasBalance: Double? // var refreshClaimableGasTimer: Timer? func configInit() { loadClaimableGAS { (amount) in } // refreshClaimableGasTimer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(NEOGasUtil.loadClaimableGAS), userInfo: nil, repeats: true) // refreshClaimableGasTimer?.fire() } @objc func reloadAllData() { loadClaimableGAS { (amount) in } } func claimGas() { // self.enableClaimButton(enable: false) //refresh the amount of claimable gas // self.loadClaimableGAS { (amount) in // } NEOWalletManage.sharedInstance().account?.claimGas(network: AppState.network, seedURL: AppState.bestSeedNodeURL, completion: { (_, error) in // <#code#> // }) // NEOWalletManage.sharedInstance().account?.claimGas { _, error in if error != nil { //if error then try again in 10 seconds DispatchQueue.main.asyncAfter(deadline: .now() + 10) { self.claimGas() } return } DispatchQueue.main.async { //HUD something to notify user that claim succeeded //done claiming DispatchQueue.main.async { print("Your claim has succeeded, it may take a few minutes to be reflected in your transaction history. You can claim again after 5 minutes") } //save latest claim time interval here to limit user to only claim every 5 minutes let now = Date().timeIntervalSince1970 UserDefaults.standard.set(now, forKey: "lastetClaimDate") UserDefaults.standard.synchronize() self.isClaiming = false //if claim succeeded then fire the timer to refresh claimable gas again. // self.refreshClaimableGasTimer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(NEOGasUtil.loadClaimableGAS), userInfo: nil, repeats: true) // self.refreshClaimableGasTimer?.fire() self.loadClaimableGAS({ (amount) in }) } }) } // func enableClaimButton(enable: Bool) { //// claimButton.isEnabled = enable && isClaiming == false // } @objc open func neoClaimGas(_ complete:@escaping (_ success : Bool) ->()) { print("Claiming GAS, This might take a little while...") //select best node // if let bestNode = NEONetworkMonitor.autoSelectBestNode() { // UserDefaultsManager.seed = bestNode // UserDefaultsManager.useDefaultSeed = false // } let network = NeoNetwork.main var node = AppState.bestSeedNodeURL if let bestNode = NEONetworkMonitor.autoSelectBestNode(network: network) { node = bestNode UserDefaultsManager.seed = node UserDefaultsManager.useDefaultSeed = false AppState.bestSeedNodeURL = bestNode } //we are able to claim gas only when there is data in the .claims array if self.claims != nil && self.claims!.claims.count > 0 { DispatchQueue.main.async { let account1 = NEOWalletManage.sharedInstance().account if (account1 != nil) { account1!.claimGas(network: AppState.network, seedURL: AppState.bestSeedNodeURL, completion: { (_, error) in if error != nil { //if error then try again in 10 seconds // DispatchQueue.main.asyncAfter(deadline: .now() + 10) { // self.claimGas() // } DispatchQueue.main.async { complete(false) } return } DispatchQueue.main.async { //HUD something to notify user that claim succeeded //done claiming DispatchQueue.main.async { print("Your claim has succeeded, it may take a few minutes to be reflected in your transaction history. You can claim again after 5 minutes") } //save latest claim time interval here to limit user to only claim every 5 minutes // let now = Date().timeIntervalSince1970 // UserDefaults.standard.set(now, forKey: "lastetClaimDate") // UserDefaults.standard.synchronize() DispatchQueue.main.async { self.isClaiming = false //if claim succeeded then fire the timer to refresh claimable gas again. // self.refreshClaimableGasTimer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(NEOGasUtil.loadClaimableGAS), userInfo: nil, repeats: true) // self.refreshClaimableGasTimer?.fire() self.claims = nil complete(true) } } }) } else { complete(false) } } } else { complete(false) } } // func prepareClaimingGAS() { //// if self.neoBalance == nil || self.neoBalance == 0 { //// return //// } //// refreshClaimableGasTimer?.invalidate() // //disable the button after tapped // enableClaimButton(enable: false) // // print("Claiming GAS, This might take a little while...") // // //select best node //// if let bestNode = NEONetworkMonitor.autoSelectBestNode() { //// UserDefaultsManager.seed = bestNode //// UserDefaultsManager.useDefaultSeed = false //// } // let network = NeoNetwork.main // var node = AppState.bestSeedNodeURL // if let bestNode = NEONetworkMonitor.autoSelectBestNode(network: network) { // node = bestNode // UserDefaultsManager.seed = node // UserDefaultsManager.useDefaultSeed = false // AppState.bestSeedNodeURL = bestNode // } // // //we are able to claim gas only when there is data in the .claims array // if self.claims != nil && self.claims!.claims.count > 0 { // DispatchQueue.main.async { // self.claimGas() // } // return // } // let mainNet = true // let assetHash = "" // let remarkStr:String? = nil // let fee = NEO_fee // //to be able to claim. we need to send the entire NEO to ourself. // NEOWalletManage.sharedInstance().account?.sendAssetTransaction(assetHash: assetHash, asset: AssetId.neoAssetId, amount: Double(self.neoBalance!), toAddress: (NEOWalletManage.sharedInstance().account?.address)!, mainNet: mainNet, remarkStr: remarkStr, network: network, fee:fee) { (txHex, error) in // if error == nil { //// HUD.hide() // //HUD or something // //in case it's error we then enable the button again. // self.enableClaimButton(enable: true) // return // } // // DispatchQueue.main.async { // //if completed then mark the flag that we are claiming GAS // self.isClaiming = true // //disable button and invalidate the timer to refresh claimable GAS //// self.refreshClaimableGasTimer?.invalidate() // //try to claim gas after 10 seconds // DispatchQueue.main.asyncAfter(deadline: .now() + 10) { // self.claimGas() // } // } // } // } @objc open func loadClaimableGAS(_ complete:@escaping (_ amount : String) ->()) { if NEOWalletManage.sharedInstance().haveDefaultWallet() == false { return } let network = NeoNetwork.main O3APIClient(network: network).getClaims(address: (NEOWalletManage.sharedInstance().account?.address)!) { result in switch result { case .failure: DispatchQueue.main.async { complete("0") } case .success(let claims): self.claims = claims // let amount: Double = Double(claims.totalUnspentClaim) / 100000000.0 let gasDec = NSDecimalNumber(decimal: self.claims!.gas) let amount: String = gasDec.stringValue DispatchQueue.main.async { complete(amount) // self.showClaimableGASAmount(amount: amount) } } } } func showClaimableGASAmount(amount: Double) { DispatchQueue.main.async { // amountLabel.text = amount.string(8) //only enable button if latestClaimDate is more than 5 minutes let latestClaimDateInterval: Double = UserDefaults.standard.double(forKey: "lastetClaimDate") let latestClaimDate: Date = Date(timeIntervalSince1970: latestClaimDateInterval) let diff = Date().timeIntervalSince(latestClaimDate) if diff > (5 * 60) { // claimButton.isEnabled = true } else { // claimButton.isEnabled = false } //amount needs to be more than zero // claimButton.isEnabled = amount > 0 } } } <file_sep>/Qlink/Vender/QLC/qlc/bean/QLCAddress.swift // // QLCAddress.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import HandyJSON public class QLCAddress : HandyJSON { public var address:String? public var publicKey:String? public var privateKey:String? required public init() {} public static func factory(address:String, publicKey:String, privateKey:String) -> QLCAddress { let addressM:QLCAddress = QLCAddress() addressM.address = address addressM.publicKey = publicKey addressM.privateKey = privateKey return addressM } } <file_sep>/Qlink/Vender/QLC/qlc/rpc/LedgerRpc.swift // // LedgerRpc.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/15. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import APIKit public class LedgerRpc : NSObject { /** * Return number of blocks for a specific account * @param url * @param params string : the account address * @return * @throws QlcException * @throws IOException */ @objc public static func accountBlocksCount(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_accountBlocksCount", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return blocks for the account, include each token of the account and order of blocks is forward from the last one * @param url * @param params string : the account address, int: number of blocks to return, int: optional , offset, index of block where to start, default is 0 * @return * @throws QlcException * @throws IOException */ @objc public static func accountHistoryTopn(address : String, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let request = AccountHistoryTopn( address: address ) let client : QlcClient = QlcClient() client.call(request, successHandler: successHandler, failureHandler: failureHandler) } /** * Return account detail info, include each token in the account * @param url * @param params string : the account address * @return * @throws QlcException * @throws IOException */ @objc public static func accountInfo(address : String, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let request = AccountInfo( address: address ) let client : QlcClient = QlcClient() client.call(request, successHandler: successHandler, failureHandler: failureHandler) } /** * Return the representative address for account * @param url * @param params string : the account address * @return * @throws QlcException * @throws IOException */ @objc public static func accountRepresentative(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_accountRepresentative", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return the vote weight for account * @param url * @param params string : the vote weight for the account (if account not found, return error) * @return * @throws QlcException * @throws IOException */ @objc public static func accountVotingWeight(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_accountVotingWeight", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return account list of chain * @param url * @param params int: number of accounts to return int: optional , offset, index of account where to start, default is 0 * @return []address: addresses list of accounts * @throws QlcException * @throws IOException */ @objc public static func accounts(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_accounts", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Returns balance and pending (amount that has not yet been received) for each account * @param url * @param params []string: addresses list * @return balance and pending amount of each token for each account * @throws QlcException * @throws IOException */ @objc public static func accountsBalance(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_accountsBalance", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return pairs of token name and block hash (representing the head block ) of each token for each account * @param url * @param params []string: addresses list * @return token name and block hash for each account * @throws QlcException * @throws IOException */ @objc public static func accountsFrontiers(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_accountsFrontiers", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return pending info for accounts * @param url * @param params []string: addresses list for accounts int: get the maximum number of pending for each account, if set -1, return all pending * @return pending info for each token of each account, means: tokenName : token name type : token type source : sender account of transaction amount : amount of transaction hash : hash of send block timestamp: timestamp * @throws QlcException * @throws IOException */ // @objc public static func accountsPending(addressArr: Array<String>, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { @objc public static func accountsPending(addressArr: Array<String>, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let request = AccountsPending( addressArr: addressArr // address: address ) let client : QlcClient = QlcClient() client.call(request, successHandler: successHandler, failureHandler: failureHandler) } /** * Return total number of accounts of chain * @param url * @param params * @return: total number of accounts * @throws QlcException * @throws IOException */ @objc public static func accountsCount(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_accountsCount", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return the account that the block belong to * @param url * @param params string: block hash * @return: string: the account address (if block not found, return error) * @throws QlcException * @throws IOException */ @objc public static func blockAccount(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_blockAccount", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return hash for the block * @param url * @param params block: block info * @return: string: block hash * @throws QlcException * @throws IOException */ @objc public static func blockHash(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_blockHash", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return blocks list of chain * @param url * @param params int: number of blocks to return int: optional, offset, index of block where to start, default is 0 * @return: []block: blocks list * @throws QlcException * @throws IOException */ @objc public static func blocks(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_blocks", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return the number of blocks (include smartcontrant block) and unchecked blocks of chain * @param url * @param params int: number of blocks to return int: optional, offset, index of block where to start, default is 0 * @return: number of blocks, means: count: int, number of blocks , include smartcontrant block unchecked: int, number of unchecked blocks * @throws QlcException * @throws IOException */ @objc public static func blocksCount(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_blocksCount", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Report number of blocks by type of chain * @param url * @param params * @return: number of blocks for each type * @throws QlcException * @throws IOException */ @objc public static func blocksCountByType(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_blocksCountByType", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return blocks info for blocks hash * @param url * @param params []string: blocks hash * @return: []block: blocks info * @throws QlcException * @throws IOException */ @objc public static func blocksInfo(hashArr : Array<String>, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let request = BlocksInfo( hashArr: hashArr ) let client : QlcClient = QlcClient() client.call(request, successHandler: successHandler, failureHandler: failureHandler) } /** * Accept a specific block hash and return a consecutive blocks hash list, starting with this block, and traverse forward to the maximum number * @param url * @param params string : block hash to start at int: get the maximum number of blocks, if set n to -1, will list blocks to open block * @return: []string: block hash list (if block not found, return error) * @throws QlcException * @throws IOException */ @objc public static func chain(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_chain", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return a list of pairs of delegator and it's balance for a specific representative account * @param url * @param params string: representative account address * @return: each delegator and it's balance * @throws QlcException * @throws IOException */ @objc public static func delegators(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_delegators", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return number of delegators for a specific representative account * @param url * @param params string: representative account address * @return: int: number of delegators for the account * @throws QlcException * @throws IOException */ @objc public static func delegatorsCount(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_delegatorsCount", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return send block by send parameter and private key * @param url * @param params send parameter for the block from: send address for the transaction to: receive address for the transaction tokenName: token name amount: transaction amount sender: optional, sms sender receiver: optional, sms receiver message: optional, sms message hash string: private key * @return: block: send block * @throws QlcException * @throws IOException */ @objc public static func generateSendBlock(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_generateSendBlock", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return receive block by send block and private key * @param url * @param params block: send block string: private key * @return: block: receive block * @throws QlcException * @throws IOException */ @objc public static func generateReceiveBlock(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_generateReceiveBlock", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return change block by account and private key * @param url * @param params string: account address string: new representative account string: private key * @return: block: change block * @throws QlcException * @throws IOException */ @objc public static func generateChangeBlock(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_generateChangeBlock", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Check block base info, update chain info for the block, and broadcast block * @param url * @param params block: block * @return: string: hash of the block * @throws QlcException * @throws IOException */ @objc public static func process(dic : Dictionary<String, Any>, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let request = Process( dic: dic ) let client : QlcClient = QlcClient() client.call(request, successHandler: successHandler, failureHandler: failureHandler) } /** * Return pairs of representative and its voting weight * @param url * @param params bool , optional, if not set or set false, will return representatives randomly, if set true, will sorting represetntative balance in descending order * @return: each representative and its voting weight * @throws QlcException * @throws IOException */ @objc public static func representatives(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_representatives", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return tokens of the chain * @param url * @param params * @return: []token: the tokens info * @throws QlcException * @throws IOException */ @objc public static func tokens(successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let request = Tokens() let client : QlcClient = QlcClient() client.call(request, successHandler: successHandler, failureHandler: failureHandler) } /** * Return token info by token id * @param url * @param params string: token id * @return: token: token info * @throws QlcException * @throws IOException */ @objc public static func tokenInfoById(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_tokens", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return token info by token name * @param url * @param params string: token name * @return: token: token info * @throws QlcException * @throws IOException */ @objc public static func tokenInfoByName(token : String, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let request = TokenInfoByName( token: token ) let client : QlcClient = QlcClient() // let callbackQueue : CallbackQueue? = isMainQueue ? .main : nil client.call(request, successHandler: successHandler, failureHandler: failureHandler) } /** * Return the number of blocks (not include smartcontrant block) and unchecked blocks of chain * @param url * @param params * @return: count: int, number of blocks , not include smartcontrant block unchecked: int, number of unchecked blocks * @throws QlcException * @throws IOException */ @objc public static func transactionsCount(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "ledger_transactionsCount", params: params, successHandler: successHandler, failureHandler: failureHandler) } @objc public static func rewards_getReceiveRewardBlock(hashHex: String, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let request = GetReceiveRewardBlock(hashHex: hashHex) let client : QlcClient = QlcClient() client.call(request, successHandler: successHandler, failureHandler: failureHandler) } } <file_sep>/Qlink/Vender/NEO/Util/NEP9.swift // // NEP9.swift // NeoSwift // // Created by <NAME> on 2/21/18. // Copyright © 2018 drei. All rights reserved. // import Foundation import Neoutils public class NEP9 { public typealias NEP9 = NeoutilsSimplifiedNEP9 public func parse(uri: String) -> NEP9? { var error: NSError? guard let uri = NeoutilsParseNEP9URI(uri, &error) else { return nil } return uri } } <file_sep>/Qlink/Vender/QLC/qlc/rpc/WalletRpc.swift // // WalletRpc.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/15. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation public class WalletRpc { /** * Return balance for each token of the wallet * @param url * @param params string: master address of the wallet string: passphrase * @return balance of each token in the wallet * @throws QlcException * @throws IOException */ public static func getBalances(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "wallet_getBalances", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Returns raw key (public key and private key) for a account * @param url * @param params string: account address string: passphrase * @return private key and public key for the address * @throws QlcException * @throws IOException */ public static func getRawKey(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "wallet_getRawKey", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Generate new seed * @param url * @param params null * @return string: hex string for seed * @throws QlcException * @throws IOException */ public static func newSeed(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "wallet_newSeed", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Create new wallet and Return the master address * @param url * @param params string: passphrase string: optional, hex string for seed, if not set, will create seed randomly * @return string : master address of the wallet * @throws QlcException * @throws IOException */ public static func newWallet(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "wallet_newWallet", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Change wallet password * @param url * @param params string: master address of the wallet string: old passphrase string: new passphrase * @return null * @throws QlcException * @throws IOException */ public static func changePassword(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "wallet_changePassword", params: params, successHandler: successHandler, failureHandler: failureHandler) } } <file_sep>/Qlink/Vender/NEO/NEOSignUtil.swift // // CryptoUtil.swift // Qlink // // Created by <NAME> on 2018/12/17. // Copyright © 2018 pan. All rights reserved. // import UIKit import CryptoSwift import Neoutils public class NEOSignUtil: NSObject { // NEO @objc static public func neoutilsign(dataHex:String, privateKey:String) -> String? { var error: NSError? let data = NeoutilsHexTobytes(dataHex) let signatureData = NeoutilsSign(data, privateKey, &error) let signatureHex = NeoutilsBytesToHex(signatureData) return signatureHex } } <file_sep>/Qlink/Vender/EOS/EOSNetwork/Common/Constant/RequestUrlConstant.h // // RequestUrlConstant.h // pocketEOS // // Created by oraclechain on 2018/2/3. // Copyright © 2018年 oraclechain. All rights reserved. // #ifndef RequestUrlConstant_h #define RequestUrlConstant_h // release 环境 // 请求路径: api_oc_personal || api_oc_blockchain || REQUEST_CONTRACT_BASEURL //#define REQUEST_BASEURL @"https://api6.pocketeos.top" #define REQUEST_BASEURL @"http://api-mainnet.starteos.io" //#define REQUEST_BASEURL @"http://api.bitmars.one" // java interface //#define REQUEST_APIPATH [NSString stringWithFormat: @"/api_oc_blockchain-v1.3.0%@", [self requestUrlPath]] // java interface #define REQUEST_APIPATH [NSString stringWithFormat: @"/v1/chain%@",[self requestUrlPath]] #define REQUEST_HTTP_BASEURL @"http://api6.pocketeos.top" #define REQUEST_HTTP_STATIC_BASEURL @"http://static6.pocketeos.top" #define REQUEST_REDPACKET_BASEURL @"https://api6.pocketeos.top/api_oc_redpacket" #define REQUEST_PERSONAL_BASEURL @"https://api6.pocketeos.top/api_oc_personal/v1.0.0" #define REQUEST_CANDYSYSTEM_BASEURL @"https://api6.pocketeos.top/api_oc_pe_candy_system" #define REQUEST_CONTRACT_BASEURL @"https://api6.pocketeos.top" #define REQUEST_BP_BASEURL @"https://api6.pocketeos.top" #define REQUEST_TRANSACTION_RECORDS @"https://history6.pocketeos.top" #define REQUEST_HISTORY_HTTP @"http://history6.pocketeos.top" #define REQUEST_MESSAGE_PUSH_BASEURL @"https://api6.pocketeos.top" #define REQUEST_PAY_CREATEACCOUNT_BASEURL @"http://pay6.pocketeos.top/oulianeosaccount" #define REQUEST_TOKENPAY_BASEURL @"http://pay6.pocketeos.top/tokenpay" #endif /* RequestUrlConstant_h */ <file_sep>/Qlink/Vender/NEO/Models/AccountState.swift // // AccountState.swift // NeoSwift // // Created by <NAME> on 9/13/17. // Copyright © 2017 drei. All rights reserved. // public struct AccountState: Codable { public var version: Int public var scriptHash: String public var frozen: Bool //var votes: it's there in JSON response but I don't know what type is it. public var balances: [Asset] enum CodingKeys : String, CodingKey { case version = "version" case scriptHash = "script_hash" case frozen = "frozen" case balances = "balances" } public init(version: Int, scriptHash: String, frozen: Bool, balances: [Asset]) { self.version = version self.scriptHash = scriptHash self.frozen = frozen self.balances = balances } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let version: Int = try container.decode(Int.self, forKey: .version) let scriptHash: String = try container.decode(String.self, forKey: .scriptHash) let frozen: Bool = try container.decode(Bool.self, forKey: .frozen) let balances: [Asset] = try container.decode([Asset].self, forKey: .balances) self.init(version: version, scriptHash: scriptHash, frozen: frozen, balances: balances) } } <file_sep>/Qlink/Vender/QLC/qlc/mng/RewardsMng.swift // // RewardsMng.swift // Qlink // // Created by <NAME> on 2019/7/4. // Copyright © 2019 pan. All rights reserved. // import Foundation public class RewardsMng { /** * * returns airdrop contract reward block by contract send block hash * @param client:qlc client * @param blockHash send block hash * @throws IOException io exception * @return StateBlock:contract reward block */ public static func getReceiveRewardBlock(hashHex:String?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) throws { if (hashHex == nil) { failureHandler(nil, nil) return } LedgerRpc.rewards_getReceiveRewardBlock(hashHex: hashHex!, successHandler: { (response) in let dic : Dictionary<String, Any?>? = response as! Dictionary<String, Any?>? if (dic != nil) { let block : QLCStateBlock = QLCStateBlock.deserialize(from: dic! as [String : Any])! successHandler(block) } }) { (error, message) in failureHandler(error, message) } } } <file_sep>/Qlink/Vender/QLC/qlc/rpc/PledgeRpc.swift // // PledgeRpc.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/15. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation public class PledgeRpc { /** * Return pledge data by pledge parameters ,if there are multiple identical pledge in the query result, it will be returned in time order * @param url * @param params pledgeParams: pledge parameters * beneficial:beneficial account * amount:amount of pledge * pType:type of pledge * @return * @throws QlcException * @throws IOException */ public static func searchPledgeInfo(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "pledge_searchPledgeInfo", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return all pledge info * @param url * @param params pledgeParams: no * @return * @throws QlcException * @throws IOException */ public static func pledge_searchAllPledgeInfo(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "pledge_searchAllPledgeInfo", params: params, successHandler: successHandler, failureHandler: failureHandler) } } <file_sep>/Qlink/Vender/QLC/qlc/sign/QLCUtil.swift // // QLCUtil.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/23. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import TrezorCrytoEd25519 import BigInt //import libsodium public class QLCUtil: NSObject { private static let signatureLength = 64 private static let addressCodeArray : String = "13456789abcdefghijkmnopqrstuwxyz" private static var addressCodeCharArray: Array<String> { return addressCodeArray.map { String($0) } } // sign @objc public static func sign(message: String, secretKey: String, publicKey: String) -> String { let messageB : Bytes = message.hex2Bytes let secretKeyB : Bytes = secretKey.hex2Bytes let publicKeyB : Bytes = publicKey.hex2Bytes var signature = Bytes(count: signatureLength) ed25519_sign_qlc(messageB, Int(messageB.count), secretKeyB, publicKeyB, &signature) let signHex : String = signature.toHexString() return signHex } // check sign @objc public static func signOpen(message: String, publicKey: String, signature: String) -> Bool { let messageB : Bytes = message.hex2Bytes let signatureB : Bytes = signature.hex2Bytes let publicKeyB : Bytes = publicKey.hex2Bytes return ed25519_sign_open_qlc(messageB, Int(messageB.count), publicKeyB, signatureB) == 0 } // seed @objc public static func generateSeed() -> String { let seed = RandomString.getRandomStringOfLength(length: 64) // let seed = RandomString.sharedInstance.getRandomStringOfLength(length: 64) return seed } // seed @objc public static func isValidSeed(seed:String) -> Bool { return seed.count == 64 } // privatekey @objc public static func seedToPrivateKey(seed:String, index:UInt8) -> String { var privateKeySource = Bytes() let seedB = seed.hex2Bytes privateKeySource.append(contentsOf: seedB) let indexB = Bytes(arrayLiteral: 0x00,0x00,0x00,index) privateKeySource.append(contentsOf: indexB) let hashB = Blake2b.hash(outLength: 32, in: privateKeySource) ?? Bytes() let privateKey = hashB.toHexString() // print("privateKey = " + privateKey) return privateKey } // publickey @objc public static func privateKeyToPublicKey(privateKey:String) -> String { var public_key_b = Bytes(count: 32) let private_key_b = privateKey.hex2Bytes ed25519_publickey_qlc(private_key_b, &public_key_b) let publicKey = public_key_b.toHexString() return publicKey } // address @objc public static func publicKeyToAddress(publicKey:String) -> String { let encodedAddress = QLCUtil.encode(hex_data: publicKey) var source = Bytes() let bytePublic = publicKey.hex2Bytes source.append(contentsOf: bytePublic) let check = Blake2b.hash(outLength: 5, in: source)! let checkReverse = QLCUtil.reverse(bytes: check) let checkReverseStr = checkReverse.toHexString() var resultAddress = String() resultAddress.insert(contentsOf: "qlc_", at: resultAddress.startIndex) resultAddress.append(encodedAddress) let check_str = QLCUtil.encode(hex_data: checkReverseStr) resultAddress.append(check_str) return resultAddress } // publickey @objc public static func addressToPublicKey(address: String) -> String { // let addressB : Bytes = address.hex2Bytes var str:String = String(address.split(separator: "_")[1]) let data = str.slice(from: 0, to: 52) let pubkey = decodeAddressCharacters(data: data) var source = Bytes() let data_b = pubkey.hex2Bytes source.append(contentsOf: data_b) let check = Blake2b.hash(outLength: 5, in: source)! let checkReverse = QLCUtil.reverse(bytes: check) let checkReverseStr = checkReverse.toHexString() // left pad byte array with zeros var pk = String(data_b.toHexString()) while pk.count < 64 { pk.insert(contentsOf: "0", at: pk.startIndex) } return pk } // address @objc public static func isValidAddress(address:String) -> Bool { let parts : Array<Substring> = address.split(separator: "_") if parts.count != 2 { return false } if parts[0] != "qlc" { return false } if parts[1].count != 60 { return false } checkCharacters: for i in 0..<parts[1].count { var str = String(parts[1].lowercased()) let letter = str.slice(from: i, length: 1) for j in 0..<addressCodeCharArray.count { if (addressCodeCharArray[j] == letter) { continue checkCharacters } } return false } // efbeb3ba0457574f4ad578367192da3b651d1c6de6c0a4b912c33b75fb38516136c20e9cd3 // 9ce6f608ebb5de240aaf850fd9247eeece06b3c7e4d17810277ea3c90c7a6bf3271bef51f let shortBytes = decodeAddressCharactersOf74(data: String(parts[1])).hex2Bytes var bytes = Bytes(count: 37) // total:37 // Restore leading null bytes let range = Range<Int>(NSMakeRange(37 - shortBytes.count, shortBytes.count))! bytes.replaceSubrange(range, with: shortBytes) // System.arraycopy(shortBytes, 0, bytes, bytes.length - shortBytes.length, shortBytes.length); var source = Bytes() source.append(contentsOf: bytes[0...31]) let check = Blake2b.hash(outLength: 5, in: source)! for i in 0..<check.count { if (check[i] != bytes[bytes.count - 1 - i]) { return false } } return true } // Mnemonic @objc public static func seedToMnemonic(seed:String) -> String { let entropy = Data(hex: seed) let mnemonic = Mnemonic.generator(entropy: entropy) return mnemonic } // Mnemonic @objc public static func mnemonicToSeed(mnemonic:String) -> String { let entropy = Mnemonic.mnemonicsToEntropy(mnemonic) let seed = (entropy ?? Data()).dataToHexString() print(seed) return seed } // Mnemonic @objc public static func isValidMnemonic(mnemonic:String) -> Bool { let arr = mnemonic.components(separatedBy: " ") if (arr.count == 24) { return true } return false } // Send @objc public static func sendAsset(from:String, tokenName:String, to:String, amount:UInt, sender: String?, receiver:String?, message:String?, privateKey:String, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let privateKeyB = privateKey.hex2Bytes let amountB = BigUInt(amount) try? TransactionMng.sendBlock(from: from, tokenName: tokenName, to: to, amount: amountB, sender: sender ?? "", receiver: receiver ?? "", message: message ?? "", privateKeyB: privateKeyB, successHandler: { (response) in if response != nil { let dic = response as! Dictionary<String, Any> try? LedgerMng.process(dic: dic, successHandler: { (response) in if response != nil { successHandler(response) } else { failureHandler(nil, nil) } }) { (error, message) in failureHandler(error, message) } } else { failureHandler(nil, nil) } }) { (error, message) in failureHandler(error, message) } } // Receive @objc public static func receive_accountsPending(address:String,successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { // pending info var pending: QLCPending? try? LedgerMng.accountsPending(address: address, successHandler: { (response) in if response != nil { pending = (response as! QLCPending) let itemList = pending?.infoList if itemList != nil && itemList!.count > 0 { successHandler(itemList!.toJSON()) } else { successHandler(nil) } } else { failureHandler(nil, nil) } }, failureHandler: { (error, message) in print("getAccountPending = ",message ?? "") failureHandler(error, message) }) } // Receive @objc public static func receive_blocksInfo(blockHash:String, receiveAddress:String ,privateKey:String,successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let blockHashB = blockHash.hex2Bytes try? LedgerMng.blocksInfo(blockHash: blockHashB, successHandler: { (response) in if response != nil { let tempBlock:QLCStateBlock = response as! QLCStateBlock let privateKeyB = privateKey.hex2Bytes try? TransactionMng.receiveBlock(sendBlock: tempBlock, receiveAddress: receiveAddress, privateKeyB: privateKeyB, successHandler: { (response) in if response != nil { let dic = response as! Dictionary<String, Any> try? LedgerMng.process(dic: dic, successHandler: { (response) in if response != nil { successHandler(response) } else { failureHandler(nil, nil) } }) { (error, message) in failureHandler(error, message) } } else { failureHandler(nil, nil) } }, failureHandler: { (error, message) in failureHandler(error, message) }) } else { print(QLCConstants.EXCEPTION_BLOCK_MSG_2003 + ", block hash[" + blockHashB.toHexString() + "]") failureHandler(nil, nil) } }) { (error, message) in print("getBlockInfoByHash = ",message ?? "") failureHandler(error, message) } } private static func decodeAddressCharacters(data: String) -> String { var muStr = String() for (i,_) in data.enumerated() { var dataMu = String(data) let dataSub:String = dataMu.slice(from: i, to: i+1) let index:Int = addressCodeArray.positionOfSubstring(dataSub) var binaryStr = String((0x20 | index), radix: 2) let binarySub = binaryStr.slice(from: 1, to: binaryStr.count) muStr.append(binarySub) } var result = String(BigInt(muStr, radix: 2)!, radix: 16) return result } private static func decodeAddressCharactersOf74(data: String) -> String { var muStr = String() for (i,_) in data.enumerated() { var dataMu = String(data) let dataSub:String = dataMu.slice(from: i, to: i+1) let index:Int = addressCodeArray.positionOfSubstring(dataSub) var binaryStr = String((0x20 | index), radix: 2) let binarySub = binaryStr.slice(from: 1, to: binaryStr.count) muStr.append(binarySub) } var result = String(BigInt(muStr, radix: 2)!, radix: 16) if result.count < 74 { // 不足74位前面加0 (自己理解) var temp = String() for _ in 0..<74-result.count { temp.append("0") } temp.append(result) result = temp } return result } private static func encode(hex_data:String) -> String { var bits = String() let dataBinary = String(BigInt(hex_data, radix: 16)!,radix:2) bits.insert(contentsOf: dataBinary, at: bits.startIndex) while bits.count < hex_data.count*4 { bits.insert(contentsOf: "0", at: bits.startIndex) } var data = String() data.insert(contentsOf: bits, at: data.startIndex) while data.count % 5 != 0 { data.insert(contentsOf: "0", at: data.startIndex) } var output = String() let slice = data.count / 5 for this_slice in 0..<slice { var dataMu = String(data) let dataSub = dataMu.slice(from: this_slice * 5, to:this_slice * 5 + 5) let subInt = Int(BigInt(dataSub, radix: 2)!) let appendStr : String = addressCodeCharArray[subInt] output.append(appendStr) } return output } public static func reverse(bytes:Bytes) -> Bytes { var bytesArr = Bytes(bytes) var i = 0 var j = bytes.count - 1 var temp : UInt8 while j > i { temp = bytesArr[j] bytesArr[j] = bytesArr[i] bytesArr[i] = temp j = j - 1 i = i + 1 } return bytesArr } } /// 随机字符串生成 public class RandomString:NSObject { // let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" static let characters = "0123456789abcdef" /** 生成随机字符串, - parameter length: 生成的字符串的长度 - returns: 随机生成的字符串 */ @objc static func getRandomStringOfLength(length: Int) -> String { var ranStr = "" for _ in 0..<length { let index = Int(arc4random_uniform(UInt32(characters.count))) var charactersMu = String(characters) let character = charactersMu.slice(from: index, length: 1) ranStr.append(character) } return ranStr } // static let sharedInstance = RandomString() } <file_sep>/Qlink/Vender/QLC/qlc/mnemonic/MnemonicCodeBook.swift // // WordList.swift // Vite-keystore_Example // // Created by Water on 2018/8/29. // Copyright © 2018年 Water. All rights reserved. // //https://github.com/trezor/python-mnemonic/tree/master/mnemonic/wordlist //助记词密码本,2048个单词的字典做对应 public enum MnemonicCodeBook { case english case simplifiedChinese case traditionalChinese // case japanese // case korean // case spanish // case french // case italian public var words: [String] { switch self { case .english: return englishWords // case .japanese: // return japaneseWords // case .korean: // return koreanWords // case .spanish: // return spanishWords case .simplifiedChinese: return simplifiedChineseWords case .traditionalChinese: return traditionalChineseWords // case .french: // return frenchWords // case .italian: // return italianWords } } } <file_sep>/Qlink/Utils/KeyChainUitl.swift // // KeyChainUitl.swift // Qlink // // Created by 旷自辉 on 2018/4/3. // Copyright © 2018年 pan. All rights reserved. // import Foundation import KeychainAccess class KeychainUtil: NSObject { // 获取和存储密码 private static let WalletPassKey : String = "walletPassKey" private static let OldKeyService : String = "network.o3.neo.wallet" // private static let KeyService : String = "com.qlink.winq.keyservice" private static let KeyService : String = "com.qlcchain.qwallet.keyservice" @objc public static func isExistWalletPass() -> Bool { return isExistKey(keyName: KeychainUtil.WalletPassKey) } @objc public static func saveWalletPass(keyValue value:String) -> Bool { return saveValueToKey(keyName: value, keyValue: KeychainUtil.WalletPassKey) } // 清除指定key @objc public static func removeKey(keyName key:String) -> Bool { let keychain = Keychain(service:KeychainUtil.KeyService) do { //save pirivate key to keychain try keychain .remove(key) } catch _ { return false } return true } // 清除所有key @objc public static func removeAllKey() -> Bool { let keychain = Keychain(service:KeychainUtil.KeyService) do { //save pirivate key to keychain try keychain .removeAll() } catch _ { return false } return true } @objc public static func isExistKey(keyName key:String) -> Bool { let keychain = Keychain(service:KeychainUtil.KeyService) do { //save pirivate key to keychain let keyValue : String = try keychain .get(key)! if keyValue.isEmpty { return false } } catch _ { return false } return true } @objc public static func getKeyValue(keyName key:String) -> String { let keychain = Keychain(service:KeychainUtil.KeyService) do { //save pirivate key to keychain let keyValue = try keychain .getString(key) if keyValue == nil { return "" } return keyValue! } catch _ { return "" } } @objc public static func getKeyDataValue(keyName key:String) -> Data? { let keychain = Keychain(service:KeychainUtil.KeyService) do { //save pirivate key to keychain let keyValue :Data? = (try keychain .getData(key)) return keyValue } catch _ { return nil } } @objc public static func saveValueToKey(keyName key:String, keyValue value:String) -> Bool { let keychain = Keychain(service: KeychainUtil.KeyService) do { //save pirivate key to keychain try keychain .accessibility(.whenUnlockedThisDeviceOnly) .set(value, key: key) } catch _ { return false } return true } @objc public static func saveDataKeyAndData(keyName key:String, keyValue value:Data) -> Bool { let keychain = Keychain(service: KeychainUtil.KeyService) do { //save pirivate key to keychain try keychain .accessibility(.whenUnlockedThisDeviceOnly) .set(value, key: key) } catch _ { return false } return true } // 获取和存储密码 private static let WalletPrivateKey : String = "walletPrivateKey" static func isExistWalletPrivate() -> Bool { return isExistKey(keyName: KeychainUtil.WalletPrivateKey) } static func saveWalletPrivate(keyValue value:String) -> Bool { return saveValueToKey(keyName: value, keyValue: KeychainUtil.WalletPrivateKey) } // 将旧的KeyService替换掉 @objc static public func resetKeyService() { let oldKeychain = Keychain(service:KeychainUtil.OldKeyService) for (_, oldKey) in oldKeychain.allKeys().enumerated() { do { print("keychain: key=",oldKey) let keyValueString = try oldKeychain .getString(oldKey) if keyValueString != nil { print("keychain: 存在字符串 Value=",keyValueString!) let success = self.saveValueToKey(keyName: oldKey, keyValue: keyValueString!) if success { print("保存string成功") } else { print("保存string失败") } } } catch _ { do { let keyValueData = try oldKeychain.getData(oldKey) if keyValueData != nil { print("keychain: 存在Data Value=",keyValueData!) let success = self.saveDataKeyAndData(keyName: oldKey, keyValue: keyValueData!) if success { print("保存data成功") } else { print("保存data失败") } } } catch _ { } } } // 移除所有old do { try oldKeychain.removeAll() } catch _ { } } @objc static public func showKeyChain(keyservice:String) { let keychain = Keychain(service:keyservice) for (_, key) in keychain.allKeys().enumerated() { do { print("keychain: key=",key) let keyValueString = try keychain .getString(key) if keyValueString != nil { print("keychain: 存在字符串 Value=",keyValueString!) } } catch _ { } } } } <file_sep>/Qlink/Vender/QLC/qlc/utils/QLCConstants.swift // // QLCConstants.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import BigInt public class QLCConstants { // basic node public static let URL:String = "http://192.168.1.122:19735" // exception code public static let EXCEPTION_CODE_1000:Int = 1000 public static let EXCEPTION_MSG_1000:String = "Not enought balance" public static let EXCEPTION_CODE_1001:Int = 1001 public static let EXCEPTION_MSG_1001:String = "Seed can`t be empty" public static let EXCEPTION_CODE_1002:Int = 1002 public static let EXCEPTION_MSG_1002:String = "Public key can`t be empty" public static let EXCEPTION_CODE_1003:Int = 1003 public static let EXCEPTION_MSG_1003:String = "Address can`t be empty" public static let EXCEPTION_CODE_1004:Int = 1004 public static let EXCEPTION_MSG_1004:String = "Address format error" public static let EXCEPTION_CODE_1005:Int = 1005 public static let EXCEPTION_MSG_1005:String = "Signature verification failed" public static let EXCEPTION_CODE_1006:Int = 1006; public static let EXCEPTION_MSG_1006:String = "Seed generation not supported"; public static let EXCEPTION_CODE_1007:Int = 1007; public static let EXCEPTION_MSG_1007:String = "Mnemonics can`t be empty"; public static let EXCEPTION_BLOCK_CODE_2000:Int = 2000 public static let EXCEPTION_BLOCK_MSG_2000:String = "Parameter error for send block" public static let EXCEPTION_BLOCK_CODE_2001:Int = 2001 public static let EXCEPTION_BLOCK_MSG_2001:String = "Parameter error for receive block" public static let EXCEPTION_BLOCK_CODE_2002:Int = 2002 public static let EXCEPTION_BLOCK_MSG_2002:String = "The block is not send block" public static let EXCEPTION_BLOCK_CODE_2003:Int = 2003 public static let EXCEPTION_BLOCK_MSG_2003:String = "Send block does not exist" public static let EXCEPTION_BLOCK_CODE_2004:Int = 2004 public static let EXCEPTION_BLOCK_MSG_2004:String = "receive address is mismatch private key" public static let EXCEPTION_BLOCK_CODE_2005:Int = 2005 public static let EXCEPTION_BLOCK_MSG_2005:String = "Pending not found" public static let EXCEPTION_BLOCK_CODE_2006:Int = 2006 public static let EXCEPTION_BLOCK_MSG_2006:String = "Invalid representative" public static let EXCEPTION_BLOCK_CODE_2007:Int = 2007 public static let EXCEPTION_BLOCK_MSG_2007:String = "Account is not exist" public static let EXCEPTION_BLOCK_CODE_2008:Int = 2008 public static let EXCEPTION_BLOCK_MSG_2008:String = "Account has no chain token" public static let EXCEPTION_BLOCK_CODE_2009:Int = 2009 public static let EXCEPTION_BLOCK_MSG_2009:String = "Token header block not found" public static let EXCEPTION_BLOCK_CODE_2010:Int = 2010 public static let EXCEPTION_BLOCK_MSG_2010:String = "Parameter error for change block" // system code public static let EXCEPTION_SYS_CODE_3000:Int = 3000 public static let EXCEPTION_SYS_MSG_3000:String = "Need initialize qlc client" // block type public static let BLOCK_TYPE_OPEN:String = "Open" public static let BLOCK_TYPE_SEND:String = "Send" public static let BLOCK_TYPE_RECEIVE:String = "Receive" public static let BLOCK_TYPE_CHANGE:String = "Change" public static let BLOCK_TYPE_CONTRACTSEND:String = "ContractSend" public static let BLOCK_TYPE_CONTRACTREWARD:String = "ContractReward" // block parameter default value public static let ZERO_HASH:String = "0000000000000000000000000000000000000000000000000000000000000000" public static let ZERO_BIG_INTEGER:BigUInt = BigUInt(0) public static let ZERO_LONG:Int64 = 0 // link type public static let LINNK_TYPE_AIRDORP:String = "d614bb9d5e20ad063316ce091148e77c99136c6194d55c7ecc7ffa9620dbcaeb" } <file_sep>/Qlink/Vender/NEO/Util/Array+Util.swift // // Array+Util.swift // NeoSwift // // Created by <NAME> on 26/09/17. // Copyright © 2017 drei. All rights reserved. // import Foundation extension Array where Element == UInt8 { public var hexString: String { return self.map { return String(format: "%x", $0) }.joined() } public var hexStringWithPrefix: String { return "0x\(hexString)" } public var fullHexString: String { return self.map { return String(format: "%02x", $0) }.joined() } public var fullHexStringWithPrefix: String { return "0x\(fullHexString)" } func toWordArray() -> [UInt32] { return arrayUtil_convertArray(self, to: UInt32.self) } mutating public func removeTrailingZeros() { for i in (0..<self.endIndex).reversed() { guard self[i] == 0 else { break } self.remove(at: i) } } func xor(other: [UInt8]) -> [UInt8] { assert(self.count == other.count) var result: [UInt8] = [] for i in 0..<self.count { result.append(self[i] ^ other[i]) } return result } } extension Array where Element == UInt32 { func toByteArrayFast() -> [UInt8] { return arrayUtil_convertArray(self, to: UInt8.self) } func toByteArray() -> [UInt8] { return arrayUtil_convertArray(self, to: UInt8.self) } } func arrayUtil_convertArray<S, T>(_ source: [S], to: T.Type) -> [T] { let count = source.count * MemoryLayout<S>.stride/MemoryLayout<T>.stride return source.withUnsafeBufferPointer { $0.baseAddress!.withMemoryRebound(to: T.self, capacity: count) { Array(UnsafeBufferPointer(start: $0, count: count)) } } } <file_sep>/Qlink/Vender/QLC/qlc/bean/QLCAccount.swift // // QLCAccount.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import BigInt import HandyJSON public class QLCAccount : HandyJSON { public var account:String? // the account address public var coinBalance:BigUInt? // balance of main token of the account (default is QLC) public var vote:BigUInt? public var network:BigUInt? public var storage:BigUInt? public var oracle:BigUInt? public var representative:String? // representative address of the account public var tokens:Array<QLCTokenMeta>? required public init() {} public func mapping(mapper: HelpingMapper) { mapper <<< coinBalance <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) mapper <<< vote <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) mapper <<< network <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) mapper <<< storage <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) mapper <<< oracle <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) } } <file_sep>/Qlink/Vender/QLC/qlc/utils/Bytes.swift // // Bytes.swift // libEd25519Blake2b // // Created by Stone on 2018/9/3. // import Foundation public typealias Bytes = Array<UInt8> extension Array where Element == UInt8 { init (count bytes: Int) { self.init(repeating: 0, count: bytes) } } public extension Bytes { var bytesToUInt64_Little : UInt64 { var value : UInt64 = 0 let data = NSData(bytes: self, length: 8) data.getBytes(&value, length: 8) value = UInt64(littleEndian: value) return value } var bytesToUInt64_Big : UInt64 { var value : UInt64 = 0 let data = NSData(bytes: self, length: 8) data.getBytes(&value, length: 8) value = UInt64(bigEndian: value) return value } } extension FixedWidthInteger { public var toBytes_Big: Bytes { var bigEndian = self.bigEndian let data = Data(bytes: &bigEndian, count: MemoryLayout.size(ofValue: bigEndian)) let bytes = [UInt8](data) return bytes } public var toBytes_Little: Bytes { var littleEndian = self.littleEndian let data = Data(bytes: &littleEndian, count: MemoryLayout.size(ofValue: littleEndian)) let bytes = [UInt8](data) return bytes } } public extension String { var hex2Bytes: Bytes { if self.unicodeScalars.lazy.underestimatedCount % 2 != 0 { return [] } var bytes = Bytes() bytes.reserveCapacity(self.unicodeScalars.lazy.underestimatedCount / 2) var buffer: UInt8? var skip = self.hasPrefix("0x") ? 2 : 0 for char in self.unicodeScalars.lazy { guard skip == 0 else { skip -= 1 continue } guard char.value >= 48 && char.value <= 102 else { return [] } let v: UInt8 let c: UInt8 = UInt8(char.value) switch c { case let c where c <= 57: v = c - 48 case let c where c >= 65 && c <= 70: v = c - 55 case let c where c >= 97: v = c - 87 default: return [] } if let b = buffer { bytes.append(b << 4 | v) buffer = nil } else { buffer = v } } if let b = buffer { bytes.append(b) } return bytes } } <file_sep>/Qlink/Vender/QLC/qlc/rpc/P2PRpc.swift // // P2PRpc.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/15. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation public class P2PRpc { /** * Return online representative accounts that have voted recently * @param url * @param params null * @return * @throws QlcException * @throws IOException */ public static func onlineRepresentatives(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "net_onlineRepresentatives", params: params, successHandler: successHandler, failureHandler: failureHandler) } } <file_sep>/Qlink/Vender/NEO/AppState.swift // // AppState.swift // O3 // // Created by <NAME> on 5/23/18. // Copyright © 2018 O3 Labs Inc. All rights reserved. // import UIKit class AppState: NSObject { static var network: NeoNetwork { #if TESTNET return .test #endif #if PRIVATENET return .privateNet #endif return .main } static var bestSeedNodeURL: String = "" static var bestOntologyNodeURL: String = "" enum ClaimingState: String { case Fresh = "" case WaitingForClaimableData = "0" case ReadyToClaim = "1" } static func claimingState(address: String) -> ClaimingState { if UserDefaults.standard.value(forKey: address + "_claimingState") == nil { return ClaimingState.Fresh } return AppState.ClaimingState(rawValue: UserDefaults.standard.string(forKey: address + "_claimingState") ?? "")! } static func setClaimingState(address: String, claimingState: ClaimingState) { UserDefaults.standard.setValue(claimingState.rawValue, forKey: address + "_claimingState") UserDefaults.standard.synchronize() } static func dismissBackupNotification() -> Bool { if UserDefaults.standard.value(forKey: "dismissedBackupNotification_1.0") == nil { return false } return UserDefaults.standard.bool(forKey: "dismissedBackupNotification_1.0") } static func setDismissBackupNotification(dismiss: Bool) { UserDefaults.standard.setValue(dismiss, forKey: "dismissedBackupNotification_1.0") UserDefaults.standard.synchronize() } enum verificationType: Int { case screenshot = 0 case byHand = 1 case other = 2 } static func getManualVerifyType(address: String) -> [verificationType] { if UserDefaults.standard.value(forKey: address + "_manualVerifyTypeArray") == nil { return [] } else { let listType = UserDefaults.standard.array(forKey: address + "_manualVerifyTypeArray") return (listType as! [Int]).map { verificationType(rawValue: $0)! } } } static func setManualVerifyType(address: String, types: [verificationType]) { let typesRaw = types.map{ $0.rawValue } UserDefaults.standard.setValue(typesRaw, forKey: address + "_manualVerifyTypeArray") UserDefaults.standard.synchronize() } // static let protectedKeyValue = NEP6.getFromFileSystem() != nil ? "ozoneActiveNep6Password" : "ozonePrivateKey" } <file_sep>/Qlink/Vender/NEO/O3APIClient.swift // // O3APIClient.swift // O3 // // Created by <NAME> on 5/23/18. // Copyright © 2018 drei. All rights reserved. // import UIKit import Neoutils public enum O3APIClientError: Error { case invalidSeed, invalidBodyRequest, invalidData, invalidRequest, noInternet, invalidAddress var localizedDescription: String { switch self { case .invalidSeed: return "Invalid seed" case .invalidBodyRequest: return "Invalid body Request" case .invalidData: return "Invalid response data" case .invalidRequest: return "Invalid server request" case .noInternet: return "No Internet connection" case .invalidAddress: return "Invalid address" } } } public enum O3APIClientResult<T> { case success(T) case failure(O3APIClientError) } class O3APIClient: NSObject { public var apiBaseEndpoint = "https://platform.o3.network/api" public var apiWithCacheBaseEndpoint = "https://api.o3.network" public var network: NeoNetwork = .main public var useCache: Bool = false init(network: NeoNetwork, useCache: Bool = false) { self.network = network self.useCache = useCache } static var shared: O3APIClient = O3APIClient(network: AppState.network) enum o3APIResource: String { case getBalances = "balances" case getUTXO = "utxo" case getClaims = "claimablegas" case getInbox = "inbox" case postTokenSaleLog = "tokensales" } func queryString(_ value: String, params: [String: String]) -> String? { var components = URLComponents(string: value) components?.queryItems = params.map { element in URLQueryItem(name: element.key, value: element.value) } return components?.url?.absoluteString } func sendRESTAPIRequest(_ resourceEndpoint: String, data: Data?, requestType: String = "GET", params: [String: String] = [:], completion :@escaping (O3APIClientResult<JSONDictionary>) -> Void) { var fullURL = useCache ? apiWithCacheBaseEndpoint + resourceEndpoint : apiBaseEndpoint + resourceEndpoint var updatedParams = params if network == .test { updatedParams["network"] = "test" } else if network == .privateNet { updatedParams["network"] = "private" } fullURL = self.queryString(fullURL, params: updatedParams)! let request = NSMutableURLRequest(url: URL(string: fullURL)!) request.httpMethod = requestType request.timeoutInterval = 60 request.cachePolicy = .reloadIgnoringLocalCacheData request.httpBody = data let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, result, err) in #if DEGUB print(result) #endif if err != nil { completion(.failure(.invalidRequest)) return } if data == nil { completion(.failure(.invalidData)) return } guard let json = ((try? JSONSerialization.jsonObject(with: data!, options: []) as? JSONDictionary) as JSONDictionary??) else { completion(.failure(.invalidData)) return } if json == nil { completion(.failure(.invalidData)) return } if let code = json!["code"] as? Int { if code != 200 { completion(.failure(.invalidData)) return } } let resultJson = O3APIClientResult.success(json!) completion(resultJson) } task.resume() } public func getUTXO(for address: String, completion: @escaping(O3APIClientResult<Assets>) -> Void) { // 交易的地址 let dict = ["address" : address] // 获取所有未花费的交易输出 var url:String = allUnpspentAsset_v2_url // 正式接口(neo及其token转账) // if mainNet == false { // 注册和连接vpn用测试接口 // url = "/api/neo/allUnpspentAsset.json" // } RequestService.request(withUrl: url, params: dict, httpMethod: HttpMethodPost, successBlock: { (request, responseObject) in var endDatas = Array<Any>() let responser = responseObject as! Dictionary<String,AnyObject> if (responser == nil && responser.count == 0) { completion(.failure(.invalidData)) return } let amountFormatter = NumberFormatter() amountFormatter.minimumFractionDigits = 0 amountFormatter.maximumFractionDigits = 8 amountFormatter.numberStyle = .decimal if responser["data"] == nil { completion(.failure(.invalidData)) return } let dataArr = responser["data"] as! Array<AnyObject> if dataArr != nil { for valueDic in dataArr { let assetDic = NSMutableDictionary(dictionary: valueDic as! Dictionary<String , AnyObject>) let valueStr = assetDic["value"] var str:String = "0.00000001"; if let strTemp = valueStr { if strTemp is String { let num = NSDecimalNumber(string: (strTemp as! String)) str = num.stringValue } else if strTemp is NSNumber { str = amountFormatter.string(from:strTemp as! NSNumber)! } } assetDic["value"] = str endDatas.append(assetDic) } } // let dataDic = responser["data"] as! Dictionary<String,AnyObject> // if dataDic != nil { // var gasDic = dataDic["GAS"] as! Dictionary<String,AnyObject> // if gasDic != nil { // let dataArr = gasDic["unspent"] as! Array<AnyObject> // if dataArr != nil // { // for valueDic in dataArr // { // let assetDic = NSMutableDictionary(dictionary: valueDic as! Dictionary<String , AnyObject>) // // var indexValue:Int = 0 // if let indexTemp = assetDic["index"] { // indexValue = Int(indexTemp as! String) ?? 0 // } // // let valueStr = assetDic["value"] // var str:String = "0.00000001"; // if let strTemp = valueStr { // if strTemp is String { // let num = NSDecimalNumber(string: (strTemp as! String)) // str = num.stringValue // } else if strTemp is NSNumber { // str = amountFormatter.string(from:strTemp as! NSNumber)! // } // } // print("valuestr = \(str)") // // let gass:[String : Any] = ["asset":"0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7","index":indexValue,"txid":assetDic["txid"] as! String,"value":str,"createdAtBlock":0] // // endDatas.append(gass) // // } // } // } // } // // var neoDic = dataDic["NEO"] as! Dictionary<String,AnyObject> // if neoDic != nil { // let dataArr1 = neoDic["unspent"] as! Array<AnyObject> // if dataArr1 != nil { // for valueDic in dataArr1 // { // let assetDic = NSMutableDictionary(dictionary: valueDic as! Dictionary<String , AnyObject>) // // var indexValue = 0 // if let indexTemp = assetDic["index"] { // indexValue = Int(indexTemp as! String) ?? 0 // } // // let valueStr = assetDic["value"] // var str:String = "0.00000001"; // if let strTemp = valueStr { // if strTemp is String { // let num = NSDecimalNumber(string: (strTemp as! String)) // str = num.stringValue // } else if strTemp is NSNumber { // str = amountFormatter.string(from:strTemp as! NSNumber)! // } // } // print("valuestr = \(str)") // // let neos:[String : Any] = ["asset":"0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b","index":indexValue,"txid":assetDic["txid"] as! String,"value":str,"createdAtBlock":0] // endDatas.append(neos) // // } // } // } if endDatas.count == 0 { completion(.failure(.invalidData)) return } let jsonObject:[String:Any] = ["data":endDatas] let decoder = JSONDecoder() guard let data = try? JSONSerialization.data(withJSONObject:jsonObject, options: .prettyPrinted), let assets = try? decoder.decode(Assets.self, from: data) else { completion(.failure(.invalidData)) return } let result = O3APIClientResult.success(assets) completion(result) }) { (request, error) in completion(.failure(O3APIClientError.noInternet)) } // let url = "/v1/neo/" + address + "/" + o3APIResource.getUTXO.rawValue // sendRESTAPIRequest(url, data: nil) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let data = try? JSONSerialization.data(withJSONObject: response["result"] as Any, options: .prettyPrinted), // let assets = try? decoder.decode(Assets.self, from: data) else { // completion(.failure(.invalidData)) // return // } // // let result = O3APIClientResult.success(assets) // completion(result) // } // } } public func getClaims(address: String, completion: @escaping(O3APIClientResult<Claimable>) -> Void) { // 交易的地址 let dict = ["address" : address] // let dict = ["address" : "AZRSCc47KuUae93AFowfdBTHr77KZGSnqp"] RequestService.request(withUrl: "/api/neo/getClaims.json", params: dict, httpMethod: HttpMethodPost, successBlock: { (request, responseObject) in var responser: Dictionary<String,AnyObject>? = nil if responseObject is NSDictionary { responser = responseObject as? Dictionary<String,AnyObject> } else { return } var claimsArr = Array<Any>() var gas : String = "0" let codeInt: Int = Int(responser!["code"] as! String)! if codeInt != 0 { // let msg : String = responser!["msg"] as! String? ?? "" completion(.failure(O3APIClientError.invalidBodyRequest)) return } let dataDic = responser!["data"] as! Dictionary<String,AnyObject> if dataDic.count > 0 { let dataArr = dataDic["claims"] as! Array<AnyObject> if dataArr.count > 0 { // for (idx,tempDic) in dataArr.enumerated() { for tempDic in dataArr { let claimsDic = NSMutableDictionary(dictionary: tempDic as! Dictionary<String , AnyObject>) let num = NSDecimalNumber(string: claimsDic["claim"] as? String) let gasNum = NSDecimalNumber(string: gas) let allGasNum = (gasNum.decimalValue + num.decimalValue) gas = NSDecimalNumber(decimal: allGasNum).stringValue var indexValue:Int = 0 if let indexTemp = claimsDic["index"] { indexValue = (indexTemp as! NSNumber).intValue } var valueStr:String = "0.00000001"; if let strTemp = claimsDic["value"] { let num = NSDecimalNumber(string: (strTemp as! NSNumber).stringValue) valueStr = num.stringValue } let createdAtBlock: Int = Int(claimsDic["end"] as! String) ?? 0 let txid = "0x" + (claimsDic["txid"] as! String) let claim:[String : Any] = ["asset":"0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b","index":indexValue,"txid":txid,"value":valueStr,"createdAtBlock":createdAtBlock] claimsArr.append(claim) } } } let jsonObject:[String:Any] = ["gas":gas,"claims":claimsArr] let decoder = JSONDecoder() guard let data = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted), let claims = try? decoder.decode(Claimable.self, from: data) else { completion(.failure(.invalidData)) return } let result = O3APIClientResult.success(claims) completion(result) }) { (request, error) in completion(.failure(O3APIClientError.noInternet)) } // let url = "/v1/neo/" + address + "/" + o3APIResource.getClaims.rawValue // sendRESTAPIRequest(url, data: nil) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // // guard let dictionary = response["result"] as? JSONDictionary, // let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), // let claims = try? decoder.decode(Claimable.self, from: data) else { // completion(.failure(.invalidData)) // return // } // // let claimsResult = O3APIClientResult.success(claims) // completion(claimsResult) // } // } } func getAccountState(address: String, completion: @escaping(O3APIClientResult<AccountState>) -> Void) { let url = "/v1/neo/" + address + "/" + o3APIResource.getBalances.rawValue sendRESTAPIRequest(url, data: nil) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(let response): let decoder = JSONDecoder() guard let dictionary = response["result"] as? JSONDictionary, let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), let accountState = try? decoder.decode(AccountState.self, from: data) else { return } let balancesResult = O3APIClientResult.success(accountState) completion(balancesResult) } } } // func getInbox(address: String, completion: @escaping(O3APIClientResult<Inbox>) -> Void) { // let url = "/v1/inbox/" + address // sendRESTAPIRequest(url, data: nil) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let data = try? JSONSerialization.data(withJSONObject: response["result"] as Any, options: .prettyPrinted), // let decoded = try? decoder.decode(Inbox.self, from: data) else { // completion(.failure(.invalidData)) // return // } // let success = O3APIClientResult.success(decoded) // completion(success) // } // } // } func getNodes(completion: @escaping(O3APIClientResult<Nodes>) -> Void) { let url = "/v1/nodes" sendRESTAPIRequest(url, data: nil) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(let response): let decoder = JSONDecoder() guard let dictionary = response["result"] as? JSONDictionary, let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), let decoded = try? decoder.decode(Nodes.self, from: data) else { return } let success = O3APIClientResult.success(decoded) completion(success) } } } // func checkVerifiedAddress(address: String, completion: @escaping(O3APIClientResult<VerifiedAddress>) -> Void) { // let validAddress = NeoutilsValidateNEOAddress(address) // if validAddress == false { // completion(.failure(.invalidAddress)) // return // } // let url = "/v1/verification/" + address // sendRESTAPIRequest(url, data: nil) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let dictionary = response["result"] as? JSONDictionary, // let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), // let decoded = try? decoder.decode(VerifiedAddress.self, from: data) else { // return // } // let success = O3APIClientResult.success(decoded) // completion(success) // } // } // } // func postTokenSaleLog(address: String, companyID: String, tokenSaleLog: TokenSaleLog, // completion: @escaping(O3APIClientResult<Bool>) -> Void) { // let url = "/v1/neo/" + address + "/tokensales/" + companyID // let encoder = JSONEncoder() // encoder.outputFormatting = .sortedKeys // let data = try? encoder.encode(tokenSaleLog) // sendRESTAPIRequest(url, data: data!, requestType: "POST") { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let dictionary = response["result"] as? JSONDictionary, // let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), // let _ = try? decoder.decode(String.self, from: data) else { // return // } // let success = O3APIClientResult.success(true) // completion(success) // } // } // } func getTxHistory(address: String, pageIndex: Int, completion: @escaping(O3APIClientResult<TransactionHistory>) -> Void) { let url = String(format:"/v1/history/%@?p=%d", address, pageIndex) sendRESTAPIRequest(url, data: nil) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(let response): let decoder = JSONDecoder() guard let dictionary = response["result"] as? JSONDictionary, let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), let decoded = try? decoder.decode(TransactionHistory.self, from: data) else { completion(.failure(O3APIClientError.invalidData)) return } let success = O3APIClientResult.success(decoded) completion(success) } } } // func tradingBalances(address: String, completion: @escaping(O3APIClientResult<TradingAccount>) -> Void) { // let validAddress = NeoutilsValidateNEOAddress(address) // if validAddress == false { // completion(.failure(.invalidAddress)) // return // } // let url = "/v1/trading/" + address // sendRESTAPIRequest(url, data: nil, params: ["version": "3"]) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let dictionary = response["result"] as? JSONDictionary, // let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), // let decoded = try? decoder.decode(TradingAccount.self, from: data) else { // return // } // let success = O3APIClientResult.success(decoded) // completion(success) // } // } // } // // func loadPricing(symbol: String, currency: String, completion: @escaping(O3APIClientResult<AssetPrice>) -> Void) { // let url = String(format: "/v1/pricing/%@/%@", symbol, currency) // sendRESTAPIRequest(url, data: nil) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let dictionary = response["result"] as? JSONDictionary, // let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), // let decoded = try? decoder.decode(AssetPrice.self, from: data) else { // return // } // let success = O3APIClientResult.success(decoded) // completion(success) // } // } // } // // let cache = NSCache<NSString, AnyObject>() // func loadSupportedTokenSwitcheo(completion: @escaping(O3APIClientResult<[TradableAsset]>) -> Void) { // let cacheKey: NSString = "SUPPORTED_TOKENS_SWITCHEO" // if let cached = cache.object(forKey: cacheKey) { // // use the cached version // let decoded = cached as! [TradableAsset] // let w = O3APIClientResult.success(decoded) // completion(w) // return // } // // let url = String(format: "/v1/trading/%@/tokens", "switcheo") // sendRESTAPIRequest(url, data: nil, params: ["version": "3"]) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let dictionary = response["result"] as? JSONDictionary, // let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), // let decoded = try? decoder.decode([TradableAsset].self, from: data) else { // return // } // self.cache.setObject(decoded as AnyObject, forKey: cacheKey) // let success = O3APIClientResult.success(decoded) // completion(success) // } // } // } // // func loadTradablePairsSwitcheo(completion: @escaping(O3APIClientResult<[TradablePair]>) -> Void) { // let cacheKey: NSString = "TRADABLE_PAIRS_SWITCHEO" // if let cached = cache.object(forKey: cacheKey) { // // use the cached version // let decoded = cached as! [TradablePair] // let w = O3APIClientResult.success(decoded) // completion(w) // return // } // // let url = String(format: "/v1/trading/%@/pairs?show_details=1", "switcheo") // sendRESTAPIRequest(url, data: nil, params: ["version": "3"]) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let dictionary = response["result"] as? JSONDictionary, // let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), // let decoded = try? decoder.decode([TradablePair].self, from: data) else { // return // } // self.cache.setObject(decoded as AnyObject, forKey: cacheKey) // let success = O3APIClientResult.success(decoded) // completion(success) // } // } // } // // func loadSwitcheoOrders(address: String, status: SwitcheoOrderStatus, pair: String? = nil, completion: @escaping(O3APIClientResult<TradingOrders>) -> Void) { // // let url = String(format: "/v1/trading/%@/orders", address) // var params: [String: String] = [:] // if status.rawValue != "" { // params["status"] = status.rawValue // } // // if pair != nil { // params["pair"] = pair! // } // params["version"] = "3" // // sendRESTAPIRequest(url, data: nil, params: params) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let dictionary = response["result"] as? JSONDictionary, // let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), // let decoded = try? decoder.decode(TradingOrders.self, from: data) else { // return // } // let success = O3APIClientResult.success(decoded) // completion(success) // } // } // } // // func loadDapps(completion: @escaping(O3APIClientResult<[Dapp]>) -> Void) { // let url = String(format: "/v1/dapps") // sendRESTAPIRequest(url, data: nil) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let dictionary = response["result"] as? JSONDictionary, // let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), // let decoded = try? decoder.decode([Dapp].self, from: data) else { // return // } // let success = O3APIClientResult.success(decoded) // completion(success) // } // } // } // // func domainLookup(domain: String, completion: @escaping(O3APIClientResult<String>) -> Void) { // struct domainInfo: Codable { // let address, expiration: String // } // let url = String(format: "/v1/neo/nns/%@", domain) // sendRESTAPIRequest(url, data: nil) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let dictionary = response["result"] as? JSONDictionary, // let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), // let decoded = try? decoder.decode(domainInfo.self, from: data) else { // return // } // let success = O3APIClientResult.success(decoded.address) // completion(success) // } // } // } // // struct reverseDomainInfo: Codable { // let address, expiration, domain: String // } // // func reverseDomainLookup(address: String, completion: @escaping(O3APIClientResult<[reverseDomainInfo]>) -> Void) { // let url = String(format: "/v1/neo/nns/%@/domains", address) // sendRESTAPIRequest(url, data: nil) { result in // switch result { // case .failure(let error): // completion(.failure(error)) // case .success(let response): // let decoder = JSONDecoder() // guard let dictionary = response["result"] as? JSONDictionary, // let data = try? JSONSerialization.data(withJSONObject: dictionary["data"] as Any, options: .prettyPrinted), // let decoded = try? decoder.decode([reverseDomainInfo].self, from: data) else { // return // } // let success = O3APIClientResult.success(decoded) // completion(success) // } // } // } } <file_sep>/Qlink/Vender/NEO/Util/validator.swift // // validator.swift // NeoSwift // // Created by <NAME> on 2/21/18. // Copyright © 2018 drei. All rights reserved. // import Foundation import Neoutils public class NEOValidator { public static func validateNEOAddress(_ address: String) -> Bool{ return NeoutilsValidateNEOAddress(address) } } <file_sep>/Qlink/Vender/QLC/qlc/bean/QLCTokenMeta.swift // // TokenMate.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import BigInt import HandyJSON public class QLCTokenMeta : HandyJSON { public var type:String? // token hash public var header:String? // the latest block hash for the token chain public var representative:String? // representative address public var open:String? // the open block hash for the token chain public var balance:BigUInt? // balance for the token public var account:String? // account that token belong to public var modified:Int? // timestamp public var blockCount:Int? // total block number for the token chain public var tokenName:String? // the token name public var pending:String? // pending amount required public init() {} public func mapping(mapper: HelpingMapper) { mapper <<< balance <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) } } <file_sep>/Qlink/Vender/QLC/qlc/rpc/AccountRpc.swift // // AccountRpc.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/15. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation public class AccountRpc { // /** // * Create a new account by seed and index // * @param seed // * @param index : optional, index for account, if not set, default value is 0 // * @return account: the private and public key for account // privKey: private key for the new account // pubKey: public key for the new account // * @throws QlcException // */ // public static String create(String seed, Integer index) throws QlcException { // // AccountMng mng = new AccountMng(); // return mng.keyPairFromSeed(seed, index); // // } // // /** // * Return account address by public key // * @param publicKey: public key // * @return account address // * @throws QlcException // */ // public static String publicKeyToAddress(String publicKey) throws QlcException { // // AccountMng mng = new AccountMng(); // return mng.publicKeyToAddress(publicKey); // // } // // /** // * Return public key for account address // * @param address:account address // * @return public key // * @throws QlcException // */ // public static String addressToPublicKey(String address) throws QlcException { // // AccountMng mng = new AccountMng(); // return mng.addressToPublicKey(address); // // } } <file_sep>/Qlink/Vender/QLC/qlc/bean/QLCBlock.swift // // QLCBlock.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import HandyJSON public class QLCBlock : HandyJSON { public enum QLCType { case State,Send,Receive,Change,Open,ContractReward,ContractSend,ContractRefund,ContractError,SmartContract,Invalid public static func getIndex(type:String) -> Int { switch (type.lowercased()) { case "state": return 0 case "send": return 1 case "receive": return 2 case "change": return 3 case "open": return 4 case "contractreward": return 5 case "contractsend": return 6 case "contractrefund": return 7 case "contracterror": return 8 case "smartcontract": return 9 default: return 10 } } } required public init() {} } <file_sep>/Qlink/Vender/QLC/qlc/rpc/UtilRpc.swift // // UtilRpc.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/15. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation public class UtilRpc { /** * Decrypt the cryptograph string by passphrase * @param url * @param params string : cryptograph, encoded by base64 string : passphrase * @return * @throws QlcException * @throws IOException */ public static func decrypt(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "util_decrypt", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Encrypt encrypt raw data by passphrase * @param url * @param params string : cryptograph, encoded by base64 string : passphrase * @return * @throws QlcException * @throws IOException */ public static func encrypt(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "util_encrypt", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return balance by specific unit for raw value * @param url * @param params string: raw value string: unit string: optional, token name , if not set , default is QLC * @return * @throws QlcException * @throws IOException */ public static func rawToBalance(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "util_rawToBalance", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return raw value for the balance by specific unit * @param url * @param params string: balance string: unit string: optional, token name , if not set , default is QLC * @return * @throws QlcException * @throws IOException */ public static func balanceToRaw(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "util_balanceToRaw", params: params, successHandler: successHandler, failureHandler: failureHandler) } } <file_sep>/Qlink/Vender/NEO/CommonCrypto/NeoTest5-Bridging-Header.h // // Use this file to import your target's public headers that you would like to expose to Swift. // #ifndef _CommonCrypto_h #define _CommonCrypto_h #include <CommonCrypto/CommonCrypto.h> #endif /* _CommonCrypto_h */ <file_sep>/Qlink/Vender/QLC/qlc/mnemonic/Mnemonic.swift // // Mnemonic.swift // Vite-keystore_Example // // Created by Water on 2018/8/29. // Copyright © 2018年 Water. All rights reserved. // import Foundation // https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki Mnemonic prd //https://iancoleman.io/bip39/ check Mnemonic by this link public final class Mnemonic { //pwd strength public enum Strength: Int { case weak = 128 //12 words case strong = 256 //24 words } //random create mnemonic words public static func randomGenerator(strength: Strength = .weak, language: MnemonicCodeBook = .english) -> String { let byteCount = strength.rawValue / 8 let bytes = Data.randomBytes(length: byteCount) //random create entropy return generator(entropy: bytes, language: language) } //create mnemonic words by data public static func generator(entropy: Data, language: MnemonicCodeBook = .english) -> String { precondition(entropy.count % 4 == 0 && entropy.count >= 16 && entropy.count <= 32) let entropybits = String(entropy.flatMap { ("00000000" + String($0, radix: 2)).suffix(8) }) let hashBits = String(entropy.sha256().flatMap { ("00000000" + String($0, radix: 2)).suffix(8) }) let checkSum = String(hashBits.prefix((entropy.count * 8) / 32)) let words = language.words let concatenatedBits = entropybits + checkSum var mnemonic: [String] = [] for index in 0..<(concatenatedBits.count / 11) { let startIndex = concatenatedBits.index(concatenatedBits.startIndex, offsetBy: index * 11) let endIndex = concatenatedBits.index(startIndex, offsetBy: 11) let wordIndex = Int(strtoul(String(concatenatedBits[startIndex..<endIndex]), nil, 2)) mnemonic.append(String(words[wordIndex])) } return mnemonic.joined(separator: " ") } //mnemonic to entropy public static func mnemonicsToEntropy(_ mnemonics: String, language: MnemonicCodeBook = .english) -> Data? { let mnemonicWordsList = mnemonics.components(separatedBy: " ") return QLCMnemonicBit.entropy(fromWords: mnemonicWordsList, wordLists: language.words) } //BIP39 Seed public static func createBIP39Seed(mnemonic: String, withPassphrase passphrase: String = "") -> Data { precondition(passphrase.count <= 256, "Password too long") //handle mnemonic guard let password = mnemonic.decomposedStringWithCompatibilityMapping.data(using: .utf8) else { fatalError("Nomalizing password failed in \(self)") } //handle password add salt guard let salt = ("mnemonic" + passphrase).decomposedStringWithCompatibilityMapping.data(using: .utf8) else { fatalError("Nomalizing salt failed in \(self)") } return QLCMnemonicCrypto.PBKDF2SHA512(password: <PASSWORD>, salt: salt.bytes) } /// Determines if a mnemonic string is valid. /// /// - Parameter string: mnemonic string /// - Returns: `true` if the string is valid; `false` otherwise. public static func mnemonic_check(_ mnemonicStr: String) -> Bool { if mnemonicStr.isEmpty { return false } let mnemonicWordsList = mnemonicStr.components(separatedBy: " ") let data = QLCMnemonicBit.entropy(fromWords: mnemonicWordsList, wordLists: MnemonicCodeBook.english.words) return data != nil } } extension Data { static func randomBytes(length: Int) -> Data { var bytes = Data(count: length) _ = bytes.withUnsafeMutableBytes { SecRandomCopyBytes(kSecRandomDefault, length, $0) } return bytes } public func dataToHexString() -> String { return map { String(format: "%02x", $0) }.joined() } } <file_sep>/Qlink/Vender/QLC/qlc/bean/QLCStateBlock.swift // // QLCStateBlock.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import BigInt import HandyJSON public class QLCStateBlock : HandyJSON { public var type:String? public var token:String? public var address:String? public var balance:BigUInt? public var vote:BigUInt? public var network:BigUInt? public var storage:BigUInt? public var oracle:BigUInt? public var previous:String? public var link:String? public var sender:String? public var receiver:String? public var message:String? public var data:String? public var povHeight:Int64? public var quota:Int? public var timestamp:Int64? public var extra:String? public var representative:String? public var work:String? public var signature:String? public var tokenName:String? public var amount:BigUInt? public var hash:String? required public init() {} public func mapping(mapper: HelpingMapper) { mapper <<< balance <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) mapper <<< vote <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) mapper <<< network <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) mapper <<< storage <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) mapper <<< oracle <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) mapper <<< amount <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) } public static func factory(type:String, token:String,address:String,balance:BigUInt,previous:String,link:String,timestamp:Int64,representative:String) -> QLCStateBlock { let stateB:QLCStateBlock = QLCStateBlock() stateB.type = type stateB.token = token stateB.address = address stateB.balance = balance stateB.previous = previous stateB.link = link stateB.timestamp = timestamp stateB.representative = representative return stateB } } <file_sep>/Qlink/Vender/QLC/qlc/rpc/MinitageRpc.swift // // MinitageRpc.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/15. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation public class MinitageRpc { /** * Return mintage data by mintage parameters * @param url * @param params mintageParams: mintage parameters * @return * @throws QlcException * @throws IOException */ public static func getMintageData(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "mintage_getMintageData", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return contract send block by mintage parameters * @param url * @param params mintageParams: mintage parameters * @return * @throws QlcException * @throws IOException */ public static func getMintageBlock(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "mintage_getMintageBlock", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return contract reward block by contract send block * @param url * @param params block: contract send block * @return * @throws QlcException * @throws IOException */ public static func getRewardBlock(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "mintage_getRewardBlock", params: params, successHandler: successHandler, failureHandler: failureHandler) } } <file_sep>/Qlink/Vender/NEO/Models/Block.swift // // Block.swift // NeoSwift // // Created by <NAME> on 8/19/17. // Copyright © 2017 drei. All rights reserved. // import Foundation public struct Block: Codable { public var confirmations: Int64 public var hash: String public var index: Int64 public var merkleRoot: String public var nextBlockHash: String public var nextConsensus: String public var nonce: String public var previousBlockHash: String public var size: Int64 public var time: Int64 public var version: Int64 public var script: Script public var transactions: [Transaction] enum CodingKeys : String, CodingKey { case confirmations = "confirmations" case hash = "hash" case index = "index" case merkleRoot = "merkleroot" case nextBlockHash = "nextblockhash" case nextConsensus = "nextconsensus" case nonce = "nonce" case previousBlockHash = "previousblockhash" case size = "size" case time = "time" case version = "version" case script = "script" case transactions = "tx" } public init (confirmations: Int64, hash: String, index: Int64, merkleRoot: String, nextBlockHash: String, nextConsensus: String, nonce: String, previousBlockHash: String, size: Int64, time: Int64, version: Int64, script: Script, transactions: [Transaction]) { self.confirmations = confirmations self.hash = hash self.index = index self.merkleRoot = merkleRoot self.nextBlockHash = nextBlockHash self.nextConsensus = nextConsensus self.nonce = nonce self.previousBlockHash = previousBlockHash self.size = size self.time = time self.version = version self.script = script self.transactions = transactions } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let confirmations: Int64 = try container.decode(Int64.self, forKey: .confirmations) let hash: String = try container.decode(String.self, forKey: .hash) let index: Int64 = try container.decode(Int64.self, forKey: .index) let merkleRoot: String = try container.decode(String.self, forKey: .merkleRoot) let nextBlockHash: String = try container.decode(String.self, forKey: .nextBlockHash) let nextConsensus: String = try container.decode(String.self, forKey: .nextConsensus) let nonce: String = try container.decode(String.self, forKey: .nonce) let previousBlockHash: String = try container.decode(String.self, forKey: .previousBlockHash) let size: Int64 = try container.decode(Int64.self, forKey: .size) let time: Int64 = try container.decode(Int64.self, forKey: .time) let version: Int64 = try container.decode(Int64.self, forKey: .version) let script: Script = try container.decode(Script.self, forKey: .script) let transactions: [Transaction] = try container.decode([Transaction].self, forKey: .transactions) self.init(confirmations: confirmations, hash: hash, index: index, merkleRoot: merkleRoot, nextBlockHash: nextBlockHash, nextConsensus: nextConsensus, nonce: nonce, previousBlockHash: previousBlockHash, size: size, time: time, version: version, script: script, transactions: transactions) } } <file_sep>/Qlink/Vender/NEO/dAppProtocol.swift // // dAppProtocol.swift // O3 // // Created by <NAME> on 11/20/18. // Copyright © 2018 O3 Labs Inc. All rights reserved. // import UIKit extension Encodable { subscript(key: String) -> Any? { return dictionary[key] } var dictionary: [String: Any] { return (try? JSONSerialization.jsonObject(with: JSONEncoder().encode(self))) as? [String: Any] ?? [:] } } public class dAppProtocol: NSObject { static let availableCommands: [String] = ["getProvider", "getNetworks", "getAccount", "getBalance", "getStorage", "invokeRead", "invoke", "disconnect", "send"] static let needAuthorizationCommands: [String] = ["getAccount", "getAddress", "invoke", "send"] struct RequestData<T: Codable>: Codable { let network: String let params: T? } struct GetProviderResponse: Codable { let compatibility: [String] let name: String let version: String let website: String let extra: [String: String] enum CodingKeys: String, CodingKey { case compatibility = "platform" case name = "name" case version = "version" case website = "website" case extra = "extra" } init(name: String, version: String, website: String, compatibility: [String], theme: String) { self.name = name self.version = version self.website = website self.compatibility = compatibility self.extra = ["theme": theme] } } // typealias GetNetworksResponse = [String] struct GetNetworksResponse: Codable { let networks: [String] let defaultNetwork: String enum CodingKeys: String, CodingKey { case networks = "networks" case defaultNetwork = "defaultNetwork" } init(networks: [String]) { self.networks = networks self.defaultNetwork = AppState.network == NeoNetwork.main ? "MainNet" : "TestNet" } } struct GetAccountResponse: Codable { let address: String let publicKey: String enum CodingKeys: String, CodingKey { case address = "address" case publicKey = "publicKey" } init(address: String, publicKey: String) { self.address = address self.publicKey = publicKey } } struct GetBalanceRequest: Codable { let address: String let assets: [String]? let fetchUTXO: Bool? = false enum CodingKeys: String, CodingKey { case address = "address" case assets = "assets" case fetchUTXO = "fetchUTXO" } } typealias GetBalanceResponse = [String: [GetBalanceResponseElement]] struct GetBalanceResponseElement: Codable { let amount, scriptHash, symbol: String let unspent: [Unspent]? init(amount: String, scriptHash: String, symbol: String, unspent: [Unspent]?) { self.amount = amount self.scriptHash = scriptHash self.symbol = symbol self.unspent = unspent } } struct Unspent: Codable { let n: Int let txid, value: String init(n: Int, txid: String, value: String) { self.n = n self.txid = txid self.value = value } } struct GetStorageRequest: Codable { let scriptHash: String let key: String let network: String? } struct GetStorageResponse: Codable { let result: String enum CodingKeys: String, CodingKey { case result = "result" } } struct InvokeReadRequest: Codable { let operation, scriptHash: String let args: [Arg] let network: String } public struct Arg: Codable { var type: String var value: String enum CodingKeys: String, CodingKey { case type case value } public init(from decoder: Decoder) throws { do { let container = try decoder.container(keyedBy: CodingKeys.self) type = try! container.decode(String.self, forKey: .type) if let stringProperty = try? container.decode(String.self, forKey: .value) { value = stringProperty } else if let intProperty = try? container.decode(Int.self, forKey: .value) { value = String(intProperty) } else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: container.codingPath, debugDescription: "Not a JSON")) } } } public init(type: String, value: String) { self.type = type self.value = value } } typealias InvokeReadResponse = JSONDictionary public struct InvokeRequest: Codable { let operation, scriptHash: String let assetIntentOverrides: AssetIntentOverrides? let attachedAssets: AttachedAssets? let triggerContractVerification: Bool var fee: String let args: [Arg]? let network: String enum CodingKeys: String, CodingKey { case operation = "operation" case scriptHash = "scriptHash" case assetIntentOverrides = "assetIntentOverrides" case attachedAssets = "attachedAssets" case triggerContractVerification = "triggerContractVerification" case fee = "fee" case args = "args" case network = "network" } init(operation: String, scriptHash: String, assetIntentOverrides: AssetIntentOverrides?, attachedAssets: AttachedAssets?, triggerContractVerification: Bool, fee: String, args: [Arg]?, network: String) { self.operation = operation self.scriptHash = scriptHash self.assetIntentOverrides = assetIntentOverrides self.attachedAssets = attachedAssets self.triggerContractVerification = triggerContractVerification self.fee = fee self.args = args self.network = network } //this is here to validate type. sometime developers could send in a wrong type. e.g. args:"" and Swift won't parse it properly and throw an error public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let operation: String = try container.decode(String.self, forKey: .operation) let scriptHash: String = try container.decode(String.self, forKey: .scriptHash) let assetIntentOverrides: AssetIntentOverrides? = try? container.decode(AssetIntentOverrides.self, forKey: .assetIntentOverrides) let attachedAssets: AttachedAssets? = try? container.decode(AttachedAssets.self, forKey: .attachedAssets) let triggerContractVerification: Bool? = try? container.decode(Bool.self, forKey: .triggerContractVerification) let fee: String = try container.decode(String.self, forKey: .fee) let args: [Arg]? = try! container.decode([Arg].self, forKey: .args) let network: String = try container.decode(String.self, forKey: .network) self.init(operation: operation, scriptHash: scriptHash, assetIntentOverrides: assetIntentOverrides, attachedAssets: attachedAssets, triggerContractVerification: triggerContractVerification ?? false, fee: fee, args: args, network: network) } struct AssetIntentOverrides: Codable { let inputs: [Input] let outputs: [Output] } struct Input: Codable { let txid: String let index: Int } struct Output: Codable { let asset, address, value: String } struct AttachedAssets: Codable { let gas: String? let neo: String? enum CodingKeys: String, CodingKey { case gas = "GAS" case neo = "NEO" } } } struct InvokeResponse: Codable { let txid: String let nodeUrl: String init(txid: String, nodeUrl: String) { self.txid = txid self.nodeUrl = nodeUrl } } struct SendRequest: Codable { let amount, toAddress: String var fromAddress: String? let network, asset: String let remark: String? var fee: String? //allow override from the user side } struct SendResponse: Codable { let txid: String let nodeUrl: String init(txid: String, nodeUrl: String) { self.txid = txid self.nodeUrl = nodeUrl } } struct errorResponse: Codable { let error: String } } class O3DappAPI { func getStorage(request: dAppProtocol.GetStorageRequest) -> dAppProtocol.GetStorageResponse { let network = request.network!.lowercased().contains("test") ? NeoNetwork.test : NeoNetwork.main var node = AppState.bestSeedNodeURL if let bestNode = NEONetworkMonitor.autoSelectBestNode(network: network) { node = bestNode } var response = "" let requestGroup = DispatchGroup() requestGroup.enter() NeoClient(seed: node).getStorage(scriptHash: request.scriptHash, key: request.key) { result in switch result { case .failure(_): response = "" requestGroup.leave() case .success(let storageValue): response = storageValue requestGroup.leave() } } requestGroup.wait() return dAppProtocol.GetStorageResponse(result: response) } func invokeRead(request: dAppProtocol.InvokeReadRequest) -> dAppProtocol.InvokeReadResponse? { let network = request.network.lowercased().contains("test") ? NeoNetwork.test : NeoNetwork.main var node = AppState.bestSeedNodeURL if let bestNode = NEONetworkMonitor.autoSelectBestNode(network: network) { node = bestNode } var response: NeoClient.InvokeFunctionResult? var args: [[String: String]] = [] for a in request.args { args.append(["type": a.type, "value": a.value]) } let requestGroup = DispatchGroup() requestGroup.enter() NeoClient(seed: node).invokeFunction(scriptHash: request.scriptHash, operation: request.operation, arguments: args) { result in switch result { case .failure(_): requestGroup.leave() case .success(let requestResult): response = requestResult requestGroup.leave() } } requestGroup.wait() return response.dictionary as JSONDictionary } func invoke(request: dAppProtocol.InvokeRequest) -> dAppProtocol.InvokeResponse { return dAppProtocol.InvokeResponse(txid: "implement this", nodeUrl: "https://o3.network") } // func getBalance(request: dAppProtocol.RequestData<[dAppProtocol.GetBalanceRequest]>) -> dAppProtocol.GetBalanceResponse { // // // var response: dAppProtocol.GetBalanceResponse = [:] // // let fetchBalanceGroup = DispatchGroup() // let fetchUTXOgroup = DispatchGroup() // // //prepare utxo first // var addressUTXO: [String:Assets] = [:] // // for p in request.params! { // fetchUTXOgroup.enter() // if p.fetchUTXO == false { // fetchUTXOgroup.leave() // continue // } // // //try to get cache object here // let cacheKey = (p.address + request.network + "utxo") as NSString // let cachedBalanced = O3Cache.memoryCache.object(forKey:cacheKey) // if cachedBalanced != nil { //if we found cache then asset to it and leave the group then tell the loop to continue // addressUTXO[p.address] = cachedBalanced as! Assets // fetchUTXOgroup.leave() // continue // } // // let o3client = O3APIClient(network: request.network.lowercased().contains("test") ? Network.test : Network.main) // DispatchQueue.global().async { // o3client.getUTXO(for: p.address, completion: { result in // switch result { // case .failure: // fetchUTXOgroup.leave() // return // case .success(let utxo): // addressUTXO[p.address] = utxo // fetchUTXOgroup.leave() // O3Cache.memoryCache.setObject(addressUTXO[p.address]! as AnyObject, forKey: cacheKey) // } // }) // } // } // fetchUTXOgroup.wait() // // for p in request.params! { // fetchBalanceGroup.enter() // //try to get cache object here // let cacheKey = (p.address + request.network) as NSString // let cachedBalanced = O3Cache.memoryCache.object(forKey:cacheKey) // if cachedBalanced != nil { // //if we found cache then asset to it and leave the group then tell the loop to continue // response[p.address] = cachedBalanced as! [dAppProtocol.GetBalanceResponseElement] // fetchBalanceGroup.leave() // continue // } // // response[p.address] = [] // let o3client = O3APIClient(network: request.network.lowercased().contains("test") ? Network.test : Network.main, useCache: false) // DispatchQueue.global().async { // // o3client.getAccountState(address: p.address) { result in // switch result { // case .failure: // fetchBalanceGroup.leave() // return // case .success(let accountState): // for t in accountState.assets { // var unspent: [dAppProtocol.Unspent] = [] // let utxo = t.symbol.lowercased() == "neo" ? addressUTXO[p.address]?.getSortedNEOUTXOs() : addressUTXO[p.address]?.getSortedGASUTXOs() // if utxo != nil { // for u in utxo! { // let unspentTx = dAppProtocol.Unspent(n: u.index, txid: u.txid, value: NSDecimalNumber(decimal: u.value).description(withLocale: Locale(identifier: "en_us"))) // unspent.append(unspentTx) // } // } // let amount = t.value.formattedStringWithoutSeparator(t.decimals, removeTrailing: true) // let element = dAppProtocol.GetBalanceResponseElement(amount: amount, scriptHash: t.id, symbol: t.symbol, unspent: unspent) // response[p.address]?.append(element) // } // for t in accountState.nep5Tokens { // let amount = t.value.formattedStringWithoutSeparator(t.decimals, removeTrailing: true) // let element = dAppProtocol.GetBalanceResponseElement(amount: amount, scriptHash: t.id, symbol: t.symbol, unspent: nil) // response[p.address]?.append(element) // } // O3Cache.memoryCache.setObject(response[p.address]! as AnyObject, forKey: cacheKey) // fetchBalanceGroup.leave() // } // } // } // } // // fetchBalanceGroup.wait() // return response // } } <file_sep>/Qlink/Vender/QLC/qlc/mng/AccountMng.swift // // AccountMng.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/14. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation //import TrezorCryptoEd25519WithBlake2b //import TrezorCrypto public final class AccountMng { public static let privateKeyLength = 64 public static let publicKeyLength = 64 // public static let signatureLength = 64 public static var ACCOUNT_ALPHABET : Array = "13456789abcdefghijkmnopqrstuwxyz".map ({ String($0) }) public static var NUMBER_CHAR_MAP = Dictionary<String, String>() public static var CHAR_NUMBER_MAP = Dictionary<String, String>() // init the NUMBER_CHAR_MAP and CHAR_NUMBER_MAP // private static func intMap() { // for i in 0..<ACCOUNT_ALPHABET.count { // var num : String = String(i, radix:2) // 十进制转二进制 // while (num.count < 5) { // Not enough 5 digits, add 0 // num = "0" + num // } // NUMBER_CHAR_MAP.updateValue(ACCOUNT_ALPHABET[i], forKey: num) // CHAR_NUMBER_MAP.updateValue(num, forKey: ACCOUNT_ALPHABET[i]) // } // } } <file_sep>/Qlink/Vender/QLC/qlc/rpc/TokenMateRpc.swift // // TokenMateRpc.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/15. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation public class TokenMateRpc { /* // return tokenmeta info by account and token hash public static TokenMate getTokenMate(String tokenHash, String address) { JSONArray params = new JSONArray(); params.add(address); QlcClient client = new QlcClient(Constants.URL); JSONObject json = client.call("ledger_accountInfo", params: params, successHandler: successHandler, failureHandler: failureHandler) if (json.containsKey("result")) { json = json.getJSONObject("result"); Account bean = new Gson().fromJson(json.toJSONString(), Account.class); List<TokenMate> tokens = bean.getTokens(); if (tokens!=null && tokens.size()>0) { TokenMate token = null; for (int i=0; i<tokens.size(); i++) { token = tokens.get(i); if (token.getType().equals(tokenHash)) return token; token = null; } } } return null; } */ } <file_sep>/Qlink/Vender/NEO/WIF.swift // // WIF.swift // NeoSwift // // Created by <NAME> on 8/23/17. // Copyright © 2017 drei. All rights reserved. // import Foundation public extension String { func hash160() -> String? { //NEO Address hash160 //skip the first byte which is 0x17, revert it then convert to full hex let bytes = self.base58CheckDecodedBytes! let reverse = Data(bytes: bytes[1...bytes.count - 1].reversed()) return reverse.fullHexString } func hashFromAddress() -> String { let bytes = self.base58CheckDecodedBytes! let shortened = bytes[0...20] //need exactly twenty one bytes let substringData = Data(bytes: shortened) let hashOne = substringData.sha256 let hashTwo = hashOne.sha256 let bytesTwo = [UInt8](hashTwo) let finalKeyData = Data(bytes: shortened[1...shortened.count - 1]) return finalKeyData.fullHexString } func scriptHash() -> Data { let bytes = self.base58CheckDecodedBytes! let shortened = bytes[0...20] //need exactly twenty one bytes let substringData = Data(bytes: shortened) let hashOne = substringData.sha256 let hashTwo = hashOne.sha256 let bytesTwo = [UInt8](hashTwo) let finalKeyData = Data(bytes: shortened[1...shortened.count - 1]) return finalKeyData } func toHexString() -> String { let data = self.data(using: .utf8)! let hexString = data.map{ String(format:"%02x", $0) }.joined() return hexString } func dataWithHexString() -> Data { var hex = self var data = Data() while(hex.characters.count > 0) { let c: String = hex.substring(to: hex.index(hex.startIndex, offsetBy: 2)) hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 2)) var ch: UInt32 = 0 Scanner(string: c).scanHexInt32(&ch) var char = UInt8(ch) data.append(&char, count: 1) } return data } } <file_sep>/Qlink/Vender/NEO/NeoClient.swift // // NeoClient.swift // NeoSwift // // Created by <NAME> on 8/19/17. // Copyright © 2017 drei. All rights reserved. // import Foundation import Neoutils typealias JSONDictionary = [String: Any] public enum NeoClientError: Error { case invalidSeed, invalidBodyRequest, invalidData, invalidRequest, noInternet var localizedDescription: String { switch self { case .invalidSeed: return "Invalid seed" case .invalidBodyRequest: return "Invalid body Request" case .invalidData: return "Invalid response data" case .invalidRequest: return "Invalid server request" case .noInternet: return "No Internet connection" } } } public enum NeoClientResult<T> { case success(T) case failure(NeoClientError) } public enum NeoNetwork: String { case test case main case privateNet } public class NEONetworkMonitor { public static let sharedInstance = NEONetworkMonitor() public static func autoSelectBestNode(network: NeoNetwork) -> String? { var bestNode = "" //load from https://platform.o3.network/api/v1/nodes instead let semaphore = DispatchSemaphore(value: 0) O3APIClient(network: network).getNodes { result in switch result { case .failure(let error): #if DEBUG print(error) #endif bestNode = "" case .success(let nodes): bestNode = nodes.neo.best } semaphore.signal() } semaphore.wait() return bestNode } } public class NeoClient { //make it a subclass of neoclient to make it more organize public struct InvokeFunctionResult: Codable { let script, state, gasConsumed: String let stack: [Stack] enum CodingKeys: String, CodingKey { case script, state case gasConsumed = "gas_consumed" case stack } } struct Stack: Codable { let type, value: String } public var seed = "http://seed3.o3node.org:10332" private init() {} private let tokenInfoCache = NSCache<NSString, AnyObject>() enum RPCMethod: String { case getConnectionCount = "getconnectioncount" case sendTransaction = "sendrawtransaction" case invokeContract = "invokescript" case getMemPool = "getrawmempool" case getStorage = "getstorage" case invokefunction = "invokefunction" case getContractState = "getcontractstate" } public init(seed: String) { self.seed = seed } func sendJSONRPCRequest(_ method: RPCMethod, params: [Any]?, completion: @escaping (NeoClientResult<JSONDictionary>) -> Void) { guard let url = URL(string: seed) else { completion(.failure(.invalidSeed)) return } let request = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json-rpc", forHTTPHeaderField: "Content-Type") request.cachePolicy = .reloadIgnoringLocalCacheData let requestDictionary: [String: Any?] = [ "jsonrpc": "2.0", "id": 2, "method": method.rawValue, "params": params ?? [] ] guard let body = try? JSONSerialization.data(withJSONObject: requestDictionary, options: []) else { completion(.failure(.invalidBodyRequest)) return } request.httpBody = body let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, _, err) in if err != nil { completion(.failure(.invalidRequest)) return } if data == nil { completion(.failure(.invalidData)) return } guard let json = ((try? JSONSerialization.jsonObject(with: data!, options: []) as? JSONDictionary) as JSONDictionary??) else { completion(.failure(.invalidData)) return } if json == nil { completion(.failure(.invalidData)) return } let resultJson = NeoClientResult.success(json!) completion(resultJson) } task.resume() } public func sendRawTransaction(with data: Data, completion: @escaping(NeoClientResult<Bool>) -> Void) { sendJSONRPCRequest(.sendTransaction, params: [data.fullHexString]) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(let response): guard let success = response["result"] as? Bool else { completion(.failure(.invalidData)) return } let result = NeoClientResult.success(success) completion(result) } } } public func getMempoolHeight(completion: @escaping(NeoClientResult<Int>) -> Void) { sendJSONRPCRequest(.getMemPool, params: []) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(let response): guard let mempool = response["result"] as? [String] else { completion(.failure(.invalidData)) return } let result = NeoClientResult.success(mempool.count) completion(result) } } } public func getContractState(scriptHash: String, completion: @escaping(NeoClientResult<ContractState>) -> Void) { sendJSONRPCRequest(.getContractState, params: [scriptHash]) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(let response): let decoder = JSONDecoder() guard let dictionary = response["result"] as? JSONDictionary, let data = try? JSONSerialization.data(withJSONObject: dictionary as Any, options: .prettyPrinted), let decoded = try? decoder.decode(ContractState.self, from: data) else { completion(.failure(.invalidData)) return } let result = NeoClientResult.success(decoded) completion(result) } } } public func getStorage(scriptHash: String, key: String, completion: @escaping(NeoClientResult<String>) -> Void) { sendJSONRPCRequest(.getStorage, params: [scriptHash, key]) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(let response): guard let s = response["result"] as? String else { completion(.failure(.invalidData)) return } let result = NeoClientResult.success(s) completion(result) } } } public func invokeFunction(scriptHash: String, operation: String, arguments: [[String: String]], completion: @escaping(NeoClientResult<InvokeFunctionResult>) -> Void) { sendJSONRPCRequest(.invokefunction, params: [scriptHash, operation, arguments]) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(let response): let decoder = JSONDecoder() guard let dictionary = response["result"] as? JSONDictionary, let data = try? JSONSerialization.data(withJSONObject: dictionary as Any, options: .prettyPrinted), let decoded = try? decoder.decode(InvokeFunctionResult.self, from: data) else { completion(.failure(.invalidData)) return } let result = NeoClientResult.success(decoded) completion(result) } } } } <file_sep>/Qlink/Vender/QLC/qlc/bean/QLCPending.swift // // QLCPending.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import BigInt import HandyJSON public class QLCPendingInfo : HandyJSON { public var source:String? public var amount:BigUInt? public var type:String? public var tokenName:String? public var Hash:String? public var timestamp:Int64? public var account:String? required public init() {} public func mapping(mapper: HelpingMapper) { // specify 'cat_id' field in json map to 'id' property in object mapper <<< self.Hash <-- "hash" mapper <<< amount <-- TransformOf<BigUInt, String>(fromJSON: { (rawString) -> BigUInt? in return BigUInt(rawString ?? "0") }, toJSON: { (bigUInt) -> String? in return String(bigUInt ?? BigUInt(0)) }) } } public class QLCPending : HandyJSON { public var address:String? public var infoList:Array<QLCPendingInfo>? required public init() {} } <file_sep>/Qlink/Vender/NEO/NEOWalletManage.swift // // WalletManage.swift // Qlink // // Created by 旷自辉 on 2018/5/9. // Copyright © 2018年 pan. All rights reserved. // import UIKit import Foundation //import NEOFramework //import NeoSwift class NEOWalletManage : NSObject { //-MARK: 单例:方法3 // static var shareInstance3 : WalletManage { // struct MyStatic { // static var instance : WalletManage = WalletManage() // } // return MyStatic.instance; // } static let swiftSharedInstance = NEOWalletManage() //在oc中这样写才能被调用 @objc open class func sharedInstance() -> NEOWalletManage { return NEOWalletManage.swiftSharedInstance } var account:Wallet? var transactionCompleted:Bool? //定义block //typealias fucBlock = (_ flag : Bool) ->() typealias fucBlock = (_ hex : String) ->() //定义Neo兑换返回block typealias neoTranQlcBlock = (_ hex : String) ->() //定义QLC交易返回block typealias tranQlcBlock = (_ hex : String) ->() //创建block变量 //var blockproerty:fucBlock! /// 创建钱包 /// /// - Returns: 创建钱包是否成功 @objc open func createWallet() -> Bool { account = Wallet() if (account != nil) { return true; } return false; } /// 根据privatekey 找回钱包 /// /// - Parameter privatekey: 私钥 /// - Returns: 钱包 @objc open func getWalletWithPrivatekey(privatekey:String) -> Bool { if privatekey.count == 52 { return self.getWalletWithPrivateWif(wif: privatekey) } else { account = Wallet(privateKey:privatekey) if (account != nil) { return true; } return false; } } /// 根据private wif 找回钱包 /// /// - Parameter privatekey: 私钥 /// - Returns: 钱包 @objc open func getWalletWithPrivateWif(wif:String) -> Bool { account = Wallet(wif: wif) if (account != nil) { return true; } return false; } @objc open func getTXWithAddress(isQLC:Bool, address:String, tokeHash:String, qlc:String , mainNet: Bool, remarkStr: String?, fee: Double, completeBlock:@escaping fucBlock) -> () { //print(account?.wif as Any); var decimal = 0 if isQLC { decimal = 8 } let amountFormatter = NumberFormatter() amountFormatter.minimumFractionDigits = 0 amountFormatter.maximumFractionDigits = decimal amountFormatter.numberStyle = .decimal var amount = amountFormatter.number(from:(qlc)) if (amount == nil) { amount = NSNumber.init(value: 0); } let amountDouble: Double = (amount?.doubleValue)! let assetName = "Qlink Token" if isQLC { // self.sendNEP5Token(tokenHash: tokeHash, assetName:assetName,amount:amountDouble, toAddress: address,completeBlock: completeBlock) self.sendNEP5Token(assetHash: tokeHash, decimals: decimal, assetName: assetName, amount: amountDouble, toAddress: address, mainNet: mainNet, remarkStr: remarkStr, fee: fee, completeBlock: completeBlock) } } // @objc open func sendNEP5Token(tokenHash: String, assetName: String, amount: Double, toAddress: String , completeBlock:@escaping fucBlock) { // // DispatchQueue.main.async { // if let bestNode = NEONetworkMonitor.autoSelectBestNode() { // UserDefaultsManager.seed = bestNode // UserDefaultsManager.useDefaultSeed = false // } // #if TESTNET // UserDefaultsManager.seed = "http://seed2.neo.org:20332" // UserDefaultsManager.useDefaultSeed = false // UserDefaultsManager.network = .test // Authenticated.account?.neoClient = NeoClient(network: .test) // #endif // // self.account?.sendNep5Token(tokenContractHash: tokenHash, amount: amount, toAddress: toAddress, completion: { (txHex, error, txId) in // completeBlock(txHex ?? "", txId ?? "") // }) // } // } @objc open func sendNEOTranQLCWithAddress( address:String, tokeHash:String, qlc:String, mainNet: Bool, remarkStr: String?, completeBlock:@escaping fucBlock) -> () { print(account?.wif as Any) let decimal = 0 let amountFormatter = NumberFormatter() amountFormatter.minimumFractionDigits = 0 amountFormatter.maximumFractionDigits = decimal amountFormatter.numberStyle = .decimal let amount = amountFormatter.number(from:(qlc)) self.sendNativeAsset(assetHash:tokeHash, assetId: AssetId(rawValue: AssetId.neoAssetId.rawValue)!, assetName: "NEO", amount: amount!.doubleValue, toAddress: address, mainNet: mainNet, remarkStr: remarkStr, completeBlock: completeBlock); // self.sendNativeAsset(asset:AssetId(rawValue: AssetId.neoAssetId.rawValue)!, assetName: "NEO", amount: amount!.doubleValue, toAddress: address,completeBlock: completeBlock) } // func sendNativeAsset(asset: AssetId, assetName: String, amount: Double, toAddress: String , completeBlock:@escaping neoTranQlcBlock) { // DispatchQueue.main.async { // self.account?.sendAssetTransaction(asset:asset, amount: amount, toAddress: toAddress, completion: { (completed, _) in // // //self.transactionCompleted = completed ?? nil // completeBlock(completed!) // // }) // // } // } @objc open func getWalletAddress() -> String { return (NEOWalletManage.swiftSharedInstance.account?.address)!; } @objc open func getWalletWif() -> String { return (NEOWalletManage.swiftSharedInstance.account?.wif)!; } @objc open func getWalletPrivateKey() -> String { let pkey:Data = (NEOWalletManage.swiftSharedInstance.account?.privateKey)!; let privatekeys:[String] = dataToHexStringArrayWithData(data: pkey as NSData) var result = "" for valueStr in privatekeys { result.append(valueStr) } return result; } @objc open func getWalletPublicKey() -> String { let pkey:Data = (NEOWalletManage.swiftSharedInstance.account?.publicKey)!; let privatekeys:[String] = dataToHexStringArrayWithData(data: pkey as NSData) var result = "" for valueStr in privatekeys { result.append(valueStr) } return result; } @objc open func haveDefaultWallet() -> Bool { if account != nil { return true } return false; } @objc static public func configO3Network(isMain: Bool) ->() { // 设置O3网络 // if isMain { // UserDefaultsManager.network = .main // } else { // UserDefaultsManager.network = .test // } // UserDefaultsManager.seed = "http://seed2.neo.org:20332" //self.tableNodes[indexPath.row].URL UserDefaultsManager.useDefaultSeed = false } // 初始化当前Account 信息 网络切换配置 @objc open func configureAccount(mainNet:Bool) -> Bool { // return account?.configureWalletNetwork(mianNet: mainNet) ?? false return true } @objc open func validateNEOAddress(address:String) -> Bool { var validate : Bool = false validate = NEOValidator.validateNEOAddress(address) return validate } // data 转 stirng[] @objc open func dataToHexStringArrayWithData(data: NSData) -> [String] { let byteArray:[Int] = DataToIntWithData(data: data) var byteStrings: [String] = [] for (_,value) in byteArray.enumerated() { byteStrings.append(ToHex(tmpid: value)) } return byteStrings } // Data -> 10 @objc open func DataToIntWithData(data: NSData) -> [Int] { var byteArray:[Int] = [] for i in 0..<data.length { var temp:Int = 0 data.getBytes(&temp, range: NSRange(location: i,length:1 )) byteArray.append(temp) } return byteArray } // 10 -> 16 @objc open func ToHex(tmpid: Int) -> String { let leftInt: Int = tmpid / 16 let rightInt: Int = tmpid % 16 var leftIndex: String = "" var rightIndex: String = "" let numberArray = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"] for i in 0..<numberArray.count { if i == leftInt { leftIndex = numberArray[i] } if i == rightInt { rightIndex = numberArray[i] } } return "\(leftIndex)\(rightIndex)" } // New Interface func sendNEP5Token(assetHash: String, decimals: Int, assetName: String, amount: Double, toAddress: String, mainNet: Bool, remarkStr: String?, fee: Double, completeBlock:@escaping fucBlock) { DispatchQueue.main.async { let network = NeoNetwork.main var node = AppState.bestSeedNodeURL if let bestNode = NEONetworkMonitor.autoSelectBestNode(network: network) { node = bestNode UserDefaultsManager.seed = node UserDefaultsManager.useDefaultSeed = false AppState.bestSeedNodeURL = bestNode } // if let bestNode = NEONetworkMonitor.autoSelectBestNode() { // UserDefaultsManager.seed = node // UserDefaultsManager.useDefaultSeed = false // } #if TESTNET UserDefaultsManager.seed = "http://seed2.neo.org:20332" UserDefaultsManager.useDefaultSeed = false UserDefaultsManager.network = .test Authenticated.account?.neoClient = NeoClient(network: .test) #endif self.account?.sendNep5Token(tokenContractHash: assetHash, amount: amount, toAddress: toAddress, mainNet: mainNet, remarkStr: remarkStr, decimals: decimals, fee: fee, network: network, completion: { (txHex, error) in print("--------neo tx error:" + "\(String(describing: error))") if txHex != nil { print(txHex!) } completeBlock(txHex ?? "") }) } } func sendNativeAsset(assetHash: String, assetId: AssetId, assetName: String, amount: Double, toAddress: String, mainNet: Bool, remarkStr: String?, completeBlock:@escaping fucBlock) { DispatchQueue.main.async { let network = NeoNetwork.main var node = AppState.bestSeedNodeURL if let bestNode = NEONetworkMonitor.autoSelectBestNode(network: network) { node = bestNode UserDefaultsManager.seed = node UserDefaultsManager.useDefaultSeed = false AppState.bestSeedNodeURL = bestNode } // if let bestNode = NEONetworkMonitor.autoSelectBestNode() { // UserDefaultsManager.seed = bestNode // UserDefaultsManager.useDefaultSeed = false // } #if TESTNET UserDefaultsManager.seed = "http://seed2.neo.org:20332" UserDefaultsManager.useDefaultSeed = false UserDefaultsManager.network = .test Authenticated.account?.neoClient = NeoClient(network: .test) #endif self.account?.sendAssetTransaction(assetHash: assetHash, asset: assetId, amount: amount, toAddress: toAddress, mainNet: mainNet, remarkStr: remarkStr, network: network, completion: { (txHex, error) in print("--------neo tx error:" + "\(String(describing: error))") if txHex != nil { print(txHex!) } completeBlock(txHex ?? "") }) } } @objc open func getNEOTX(assetHash: String, decimals: Int, assetName: String, amount: String, toAddress: String, assetType: Int, mainNet: Bool, remarkStr: String?, fee: Double, completeBlock:@escaping fucBlock) { // let assetId: String! = self.selectedAsset!.assetID! // let assetName: String! = self.selectedAsset?.name! let amountFormatter = NumberFormatter() amountFormatter.minimumFractionDigits = 0 // amountFormatter.maximumFractionDigits = self.selectedAsset!.decimal amountFormatter.maximumFractionDigits = decimals amountFormatter.numberStyle = .decimal var amount = amountFormatter.number(from:(amount)) if (amount == nil) { amount = NSNumber.init(value: 0); } let amountDouble: Double = (amount?.doubleValue)! if assetType == 0 { // NEO\GAS var assetId = AssetId(rawValue: AssetId.neoAssetId.rawValue)! if assetName == "GAS" { assetId = AssetId(rawValue: AssetId.gasAssetId.rawValue)! } self.sendNativeAsset(assetHash: assetHash, assetId: assetId, assetName: assetName, amount: amountDouble, toAddress: toAddress, mainNet: mainNet, remarkStr: remarkStr) { txHex in completeBlock(txHex) } } else if assetType == 1 { // token self.sendNEP5Token(assetHash: assetHash, decimals: decimals, assetName: assetName, amount: amountDouble, toAddress: toAddress, mainNet: mainNet, remarkStr: remarkStr, fee: fee) { txHex in completeBlock(txHex) } } } } <file_sep>/Qlink/Vender/QLC/qlc/mng/TokenMetaMng.swift // // TokenMetaMng.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation public class TokenMetaMng { // return token meta info by account and token hash public static func getTokenMeta(tokenHash:String, address:String, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) throws { LedgerRpc.accountInfo(address: address, successHandler: { (response) in if response != nil { let dic = response as! Dictionary<String, Any> let account = QLCAccount.deserialize(from: dic) let tokens = account?.tokens if (tokens != nil && tokens!.count > 0) { var token : QLCTokenMeta? = nil for item in tokens! { if item.type == tokenHash { token = item break } } successHandler(token) } else { successHandler(nil) } } else { successHandler(nil) } }) { (error, message) in failureHandler(error, message) } } // return account info by address public static func getAccountMeta(address:String, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) throws { LedgerRpc.accountInfo(address: address, successHandler: { (response) in if response != nil { let dic = response as! Dictionary<String, Any> let account = QLCAccount.deserialize(from: dic) successHandler(account) } else { successHandler(nil) } }) { (error, message) in failureHandler(error, message) } } } <file_sep>/Qlink/Vender/NEO/Global.swift // // Global.swift // O3 // // Created by <NAME> on 9/16/17. // Copyright © 2017 drei. All rights reserved. // import Foundation import UIKit struct Authenticated { static var wallet: Wallet? { didSet { if wallet != nil { //store current address in user default UserDefaultsManager.o3WalletAddress = wallet?.address } } } static var watchOnlyAddresses: [String]? //watch only addresses static var contacts: [(String, String)]? } struct Precision { static let usd = 2 static let jpy = 2 static let eur = 2 static let cny = 2 static let krw = 2 static let btc = 8 static let gas = 8 static let percent = 2 } enum Currency: String { case btc case usd case jpy case eur case cny case krw case aud case gbp case rub case cad var symbol: String { switch self { case .btc: return "btc" case .usd: return "$" case .jpy: return "¥" case .eur: return "€" case .cny: return "¥" case .krw: return "₩" case .aud: return "$" case .gbp: return "£" case .rub: return "₽" case .cad: return "$" } } var locale: String { switch self { case .btc: return "en_US" case .usd: return "en_US" case .jpy: return "ja_JP" case .eur: return "de_DE" case .cny: return "zh_Hans_CN" case .krw: return "ko_KR" case .aud: return "en_AU" case .gbp: return "en_GB" case .rub: return "ru_RU" case .cad: return "en_CA" } } } enum PriceInterval: String { case sixHours = "6h" case oneDay = "24h" case oneWeek = "1w" case oneMonth = "1m" case threeMonths = "3m" case all = "all" func minuteValue() -> Int { switch rawValue { case "6h": return 5 case "24h": return 20 case "1w": return 140 case "1m": return 560 case "3m": return 1680 case "all": return 2000 default: return 0 } } } <file_sep>/Qlink/Vender/ETH/ETHFramework.framework/Headers/TrustWalletManage.swift // // TrustWalletManage.swift // TestTrust // // Created by <NAME> on 2018/5/30. // Copyright © 2018年 qlink. All rights reserved. // import UIKit import TrustCore import TrustKeystore import BigInt import RealmSwift import Result public class WalletModel : NSObject { @objc public var name: String = "" @objc public var balance: String = "" @objc public var address: String = "" @objc public var isWatch: Bool = false @objc public var symbol : String = "" } public class TrustWalletManage: NSObject { var keystore: Keystore let coin: Coin = .ethereum private let shortFormatter = EtherNumberFormatter.short public static let swiftSharedInstance = TrustWalletManage() //在oc中这样写才能被调用 @objc public class func sharedInstance() -> TrustWalletManage { return TrustWalletManage.swiftSharedInstance } // init(keystore: Keystore) { // self.keystore = keystore // } override public init() { let sharedMigration = SharedMigrationInitializer() sharedMigration.perform() let realm = try! Realm(configuration: sharedMigration.config) let walletStorage = WalletStorage(realm: realm) self.keystore = EtherKeystore(storage: walletStorage) // self.keystore = EtherKeystore.shared } @objc public func createInstantWallet( _ export : @escaping (([String]?, String?) -> Void) ) { let password = PasswordGenerator.generateRandom() keystore.createAccount(with: password) { result in switch result { case .success(let account): print("create account success:\(account)") // self.markAsMainWallet(for: account) let address = self.keystore.wallets.last?.currentAccount.address.description self.keystore.exportMnemonic(wallet: account) { mnemonicResult in switch mnemonicResult { case .success(let words): print("exportMnemonic success:\(words)") export(words, address) case .failure(let error): print("exportMnemonic fail:\(error)") export(nil, address) } } case .failure(let error): print("create account fail:\(error)") export(nil, nil) } } } @objc public func importWallet(keystoreInput:String?,privateKeyInput:String?,addressInput:String?,mnemonicInput:String?,password:String?,_ importResult : @escaping ((Bool, String?) -> Void)) { var words : [String]? = nil var type : ImportSelectionType = .privateKey if (keystoreInput != nil) { type = .keystore } else if (privateKeyInput != nil) { type = .privateKey } else if (addressInput != nil) { type = .address } else if (mnemonicInput != nil) { type = .mnemonic words = mnemonicInput!.components(separatedBy: " ").map { $0.trimmed.lowercased() } } let importType: ImportType = { switch type { case .keystore: return .keystore(string: keystoreInput!, password: <PASSWORD>!) case .privateKey: return .privateKey(privateKey: privateKeyInput!) case .mnemonic: return .mnemonic(words: words!, password: <PASSWORD>!, derivationPath: coin.derivationPath(at: 0)) case .address: let address = EthereumAddress(string: addressInput!)! // EthereumAddress validated by form view. return .address(address: address) } }() keystore.importWallet(type: importType, coin: coin) { result in switch result { case .success(let account): print("import account success:\(account)") let address = account.currentAccount.address.description importResult(true, address) case .failure(let error): print("import account fail",error) importResult(false, nil) } } } @objc public func importWallet(privateKeyInput:String?,addressInput:String?,isWatch:Bool,_ importResult : @escaping ((Bool, String?) -> Void)) { var type : ImportSelectionType = .privateKey if isWatch == true { type = .address } else { type = .privateKey } let importType: ImportType = { if type == .privateKey { return .privateKey(privateKey: privateKeyInput!) } else { let address = EthereumAddress(string: addressInput!)! // EthereumAddress validated by form view. return .address(address: address) } }() keystore.importWallet(type: importType, coin: coin) { result in switch result { case .success(let account): print("import account success:\(account)") let address = account.currentAccount.address.description importResult(true, address) case .failure(let error): print("import account fail",error) importResult(false, nil) } } } @objc public func importWallet() { // let validatedError = keystoreRow?.section?.form?.validate() // guard let errors = validatedError, errors.isEmpty else { return } // let validatedAdressError = addressRow?.section?.form?.validate() // guard let addressErrors = validatedAdressError, addressErrors.isEmpty else { return } let keystoreInput = "{\"version\":3,\"id\":\"1a464fe8-b97f-4f47-ba43-ba11847447e8\",\"crypto\":{\"ciphertext\":\"55db45f95baa7ac08e0345f5488ba0ca4fb11ea0e91e7b9198ec736577aeb3d1\",\"cipherparams\":{\"iv\":\"ac7096897ca79119409c78ce3b7f1f38\"},\"kdf\":\"scrypt\",\"kdfparams\":{\"r\":8,\"p\":6,\"n\":4096,\"dklen\":32,\"salt\":\"5e47464718c002c05acd7cbd1c2a74407b159aa78f539e9ce0674fdf20b3b725\"},\"mac\":\"bdfce9e2250986cf98324b17fb5e04a71afb196e316ab97cc31b7cb55f560026\",\"cipher\":\"aes-128-ctr\"},\"type\":\"private-key\",\"address\":\"14758245C6E5F450e9fBED333F0d9C36AcE3Bc76\"}" let privateKeyInput = "<KEY>" let password = "<PASSWORD>" let addressInput = "" let mnemonicInput = "" let words = mnemonicInput.components(separatedBy: " ").map { $0.trimmed.lowercased() } // let type = ImportSelectionType(title: segmentRow?.value) // let type : ImportSelectionType = .keystore let type : ImportSelectionType = .privateKey let importType: ImportType = { switch type { case .keystore: return .keystore(string: keystoreInput, password: <PASSWORD>) case .privateKey: return .privateKey(privateKey: privateKeyInput) case .mnemonic: return .mnemonic(words: words, password: <PASSWORD>, derivationPath: coin.derivationPath(at: 0)) case .address: let address = EthereumAddress(string: addressInput)! // EthereumAddress validated by form view. return .address(address: address) } }() keystore.importWallet(type: importType, coin: coin) { result in switch result { case .success(let account): print("import account success:\(account)") case .failure(let error): print("import account fail",error) } } } @objc public func send(fromAddress:String,contractAddress:String,toAddress:String,name:String,symbol:String,amount:String,gasLimit:Int,gasPrice:Int,decimals:Int,value:String,isCoin:Bool,_ sendComplete : @escaping ((Bool, String?) -> Void)) { // let walletInfo : WalletInfo = self.keystore.wallets[0] var walletInfo : WalletInfo? = nil for tempWalletInfo in self.keystore.wallets { if fromAddress == tempWalletInfo.currentAccount.address.description { walletInfo = tempWalletInfo break } } if walletInfo == nil { print("找不到钱包") return } let config: Config = .current let migration = MigrationInitializer(account: walletInfo!) migration.perform() let sharedMigration = SharedMigrationInitializer() sharedMigration.perform() let realm = self.realm(for: migration.config) let sharedRealm = self.realm(for: sharedMigration.config) let session = WalletSession( account: walletInfo!, realm: realm, sharedRealm: sharedRealm, config: config ) session.transactionsStorage.removeTransactions(for: [.failed, .unknown]) let fullFormatter = EtherNumberFormatter.full let gasPriceBig = fullFormatter.number(from: String(Int(gasPrice)), units: UnitConfiguration.gasPriceUnit) ?? BigInt() let gasLimitBig = BigInt(String(Int(gasLimit)), radix: 10) ?? BigInt() let data = Data() let nonceBig = BigInt("0") ?? 0 let configuration = TransactionConfiguration( gasPrice: gasPriceBig, gasLimit: gasLimitBig, data: data, nonce: nonceBig ) var type: TokenObjectType = .ERC20 if isCoin == true { type = .coin } let token = TokenObject( contract: contractAddress, name: name, coin: .ethereum, type: type, symbol: symbol, decimals: decimals, value: value, isCustom: false, isDisabled: false) let transfer: Transfer = { let server = token.coin.server switch token.type { case .coin: return Transfer(server: server, type: .ether(token, destination: .none)) case .ERC20: return Transfer(server: server, type: .token(token)) } }() print("拿到transfer") // let balance = Balance(value: transfer.type.token.valueBigInt) let chainState: ChainState = ChainState(server: transfer.server) chainState.fetch() // let viewModel: SendViewModel = SendViewModel(transfer: transfer, config: session.config, chainState: chainState, storage: session.tokensStorage, balance: balance) let addressString = toAddress guard let address = EthereumAddress(string: addressString) else { print("拿不到address") return } let amountString = amount let parsedValue : BigInt? = { switch transfer.type { case .ether, .dapp: return EtherNumberFormatter.full.number(from: amountString, units: .ether) case .token(let token): return EtherNumberFormatter.full.number(from: amountString, decimals: token.decimals) } }() print("拿到parsedValue") guard let value = parsedValue else { print("拿不到parsedValue") return } let transaction = UnconfirmedTransaction( transfer: transfer, value: value, to: address, data: configuration.data, gasLimit: configuration.gasLimit, gasPrice: configuration.gasPrice, // nonce: configuration.nonce nonce: .none ) print("拿到transaction") switch session.account.type { case .privateKey, .hd: let first = session.account.accounts.filter { $0.coin == token.coin }.first guard let account = first else { print("拿不到account") return } let configurator = TransactionConfigurator( session: session, account: account, transaction: transaction, server: transfer.server, chainState: ChainState(server: transfer.server) ) let transaction1 = configurator.signTransaction let server = transfer.server let sendTransactionCoordinator : SendTransactionCoordinator = SendTransactionCoordinator(session: session, keystore: keystore, confirmType: .signThenSend, server: server) print("开始sendTransaction") sendTransactionCoordinator.send(transaction: transaction1) { result in print("转账结果:",result) switch result { case .success(let complete) : print("send success:\(complete)") // ConfirmResult var txId = "" switch complete { case .signedTransaction(let sentTransaction): txId = sentTransaction.id case .sentTransaction(let sentTransaction): txId = sentTransaction.id } sendComplete(true, txId) case .failure(let error) : print("send fail:\(error)") sendComplete(false, nil) } } case .address: sendComplete(false, nil) } } @objc public func send() { // let keystore = EtherKeystore.shared // let wallet : Wallet = keystore.recentlyUsedWallet ?? keystore.wallets.first! let walletInfo : WalletInfo = self.keystore.wallets[0] let config: Config = .current let migration = MigrationInitializer(account: walletInfo) migration.perform() let sharedMigration = SharedMigrationInitializer() sharedMigration.perform() let realm = self.realm(for: migration.config) let sharedRealm = self.realm(for: sharedMigration.config) let session = WalletSession( account: walletInfo, realm: realm, sharedRealm: sharedRealm, config: config ) session.transactionsStorage.removeTransactions(for: [.failed, .unknown]) // let tokensStorage = TokensDataStore(realm: realm, config: config) // let balanceCoordinator = TokensBalanceService() // let trustNetwork = TrustNetwork(provider: TrustProviderFactory.makeProvider(), balanceService: balanceCoordinator, account: wallet, config: config) // let balance = BalanceCoordinator(account: wallet, config: config, storage: tokensStorage) // let transactionsStorage = TransactionsStorage( // realm: realm, // account: wallet // ) // let nonceProvider = GetNonceProvider(storage: transactionsStorage) // let session = WalletSession( // account: wallet, // config: config, // balanceCoordinator: balance, // nonceProvider: nonceProvider // ) // transactionsStorage.removeTransactions(for: [.failed, .unknown]) // let transferType: TransferType = .ether(destination: .none) // let transferType: TransferType = .token( TokenObject(contract: "0xe41d2489571d322189246dafa5ebde1f4699f498", name: "0x project", symbol: "ZRX", decimals: 6, value: "30000000", isCustom: true, isDisabled: false)) // let transferType: TransferType = .token( TokenObject(contract: "0xB8c77482e45F1F44dE1745F52C74<KEY>2", name: "BNB", symbol: "BNB", decimals: 18, value: "420000000000000000", isCustom: false, isDisabled: false)) // let transferType: TransferType = .token( TokenObject(contract: "0x14758245C6E5F450e9fBED333F0d9C36AcE3Bc76", name: "0x project", symbol: "ZRX", decimals: 6, value: "3", isCustom: true, isDisabled: false)) // BNB // TokenObject { // contract = 0xB8c77482e45F1F44dE1745F52C74426C631bDD52; // name = BNB; // symbol = BNB; // decimals = 18; // value = 420000000000000000; // isCustom = 0; // isDisabled = 0; // balance = 0; // } let token = TokenObject( contract: "0x14758245C6E5F450e9fBED333F0d9C36AcE3Bc76", name: "YYC", coin: .ethereum, type: .coin, symbol: "YYC", decimals: 18, value: "20", isCustom: false, isDisabled: false) let transfer: Transfer = { let server = token.coin.server switch token.type { case .coin: return Transfer(server: server, type: .ether(token, destination: .none)) case .ERC20: return Transfer(server: server, type: .token(token)) } }() let data = Data() let balance = Balance(value: transfer.type.token.valueBigInt) let chainState: ChainState = ChainState(server: transfer.server) chainState.fetch() let viewModel: SendViewModel = SendViewModel(transfer: transfer, config: session.config, chainState: chainState, storage: session.tokensStorage, balance: balance) let addressString = "0x14758245C6E5F450e9fBED333F0d9C36AcE3Bc76" let amountString = "0.001" guard let address = EthereumAddress(string: addressString) else { return } let parsedValue: BigInt? = { switch transfer.type { case .ether, .dapp: return EtherNumberFormatter.full.number(from: amountString, units: .ether) case .token(let token): return EtherNumberFormatter.full.number(from: amountString, decimals: token.decimals) } }() guard let value = parsedValue else { return } let transaction = UnconfirmedTransaction( transfer: transfer, value: value, to: address, data: data, gasLimit: .none, gasPrice: viewModel.gasPrice, nonce: .none ) switch session.account.type { case .privateKey, .hd: let first = session.account.accounts.filter { $0.coin == token.coin }.first guard let account = first else { return } let configurator = TransactionConfigurator( session: session, account: account, transaction: transaction, server: transfer.server, chainState: ChainState(server: transfer.server) ) let transaction1 = configurator.signTransaction let server = transfer.server let sendTransactionCoordinator : SendTransactionCoordinator = SendTransactionCoordinator(session: session, keystore: keystore, confirmType: .signThenSend, server: server) sendTransactionCoordinator.send(transaction: transaction1) { result in // guard let `self` = self else { return } // self.didCompleted?(result) print(result) } case .address: break //nav.displayError(error: InCoordinatorError.onlyWatchAccount) } // let sendTransactionCoordinator : SendTransactionCoordinator = SendTransactionCoordinator(session: session, keystore: keystore, confirmType: .signThenSend) // break // case (.request(let token), _): // break // case (.send, .address): // // This case should be returning an error inCoordinator. Improve this logic into single piece. // break // } } @objc public func delete(address:String,_ deleteComplete : @escaping ((Bool) -> Void)) { for walletInfo in self.keystore.wallets { if address == walletInfo.currentAccount.address.description { self.keystore.delete(wallet: walletInfo) { result in print(result) switch result { case .success(let complete) : print("delete success:\(complete)") deleteComplete(true) case .failure(let error) : print("delete fail:\(error)") deleteComplete(false) } deleteComplete(true) } break } } } @objc public func getAllWalletModel() -> [WalletModel] { var modelArr = [WalletModel]() for walletInfo in self.keystore.wallets { let model = WalletModel() model.name = walletInfo.info.name model.symbol = walletInfo.coin!.server.symbol if !walletInfo.info.balance.isEmpty, let server = walletInfo.coin?.server { model.balance = WalletInfo.format(value: shortFormatter.string(from: BigInt(walletInfo.info.balance) ?? BigInt(), decimals: server.decimals), server: server) } else { model.balance = WalletInfo.format(value: "0.0", server: .main) } model.address = walletInfo.currentAccount.address.description model.isWatch = walletInfo.isWatch modelArr.append(model) } return modelArr } @objc public func isHavaWallet() -> Bool { return self.keystore.hasWallets } @objc public func isValidAddress(address:String) -> Bool { var valid = false if CryptoAddressValidator.isValidAddress(address) { valid = true } return valid } @objc public func getAddress() -> String { let walletInfo : WalletInfo = self.keystore.wallets[0] return walletInfo.currentAccount.address.description } @objc public func walletIsExist(address:String) -> Bool { var isExist : Bool = false for walletInfo in self.keystore.wallets { if address == walletInfo.currentAccount.address.description { isExist = true } } return isExist } @objc public func exportKeystore(address:String,newPassword:String,_ export : @escaping ((String?) -> Void)) { for walletInfo in self.keystore.wallets { if address == walletInfo.currentAccount.address.description { let currentPassword = self.keystore.getPassword(for: walletInfo.currentAccount.wallet!) self.keystore.export(account: walletInfo.currentAccount, password: <PASSWORD> ?? <PASSWORD>, newPassword: <PASSWORD>) { result in switch result { case .success(let value): print("exportKeystore success:\(value)") export(value) case .failure(let error): print("exportKeystore fail:\(error)") export(nil) } } break } } } @objc public func exportMnemonic(address:String,_ export : @escaping (([String]?) -> Void)) { for walletInfo in self.keystore.wallets { if address == walletInfo.currentAccount.address.description { self.keystore.exportMnemonic(wallet: walletInfo.currentAccount.wallet!) { result in switch result { case .success(let words): print("exportKeystore success:\(words)") export(words) case .failure(let error): print("exportKeystore fail:\(error)") export(nil) } } } } } @objc public func exportPrivateKey(address:String,_ export : @escaping ((String?) -> Void)) { for walletInfo in self.keystore.wallets { if address == walletInfo.currentAccount.address.description { self.keystore.exportPrivateKey(account: walletInfo.currentAccount) { result in switch result { case .success(let privateKey): print("exportPrivateKey success:\(privateKey)") export(privateKey.hexString) case .failure(let error): print("exportPrivateKey fail:\(error)") export(nil) } } break } } } @objc public func exportPublicKey(address:String,_ export : @escaping ((String?) -> Void)) { for walletInfo in self.keystore.wallets { if address == walletInfo.currentAccount.address.description { self.keystore.exportPublicKey(account: walletInfo.currentAccount) { result in switch result { case .success(let publicKey): print("exportPublicKey success:\(publicKey)") export(publicKey.hexString) case .failure(let error): print("exportPublicKey fail:\(error)") export(nil) } } break } } } @objc public func switchWallet(address : String) { var account : WalletInfo? = nil for walletInfo in self.keystore.wallets { if address == walletInfo.currentAccount.address.description { account = walletInfo } } if account == nil { return } let migration = MigrationInitializer(account: account!) migration.perform() let sharedMigration = SharedMigrationInitializer() sharedMigration.perform() let realm = self.realm(for: migration.config) let sharedRealm = self.realm(for: sharedMigration.config) let config: Config = .current let session = WalletSession( account: account!, realm: realm, sharedRealm: sharedRealm, config: config ) session.transactionsStorage.removeTransactions(for: [.failed, .unknown]) // Create coins based on supported networks let coins = Config.current.servers if let wallet = account!.currentWallet, account!.accounts.count < coins.count, account!.mainWallet { let derivationPaths = coins.map { $0.derivationPath(at: 0) } let _ = self.keystore.addAccount(to: wallet, derivationPaths: derivationPaths) } self.keystore.recentlyUsedWallet = account! } @objc public func signMessage(data:Data,address:String) -> Array<Any>? { var useAccount : Account? = nil for walletInfo in self.keystore.wallets { if address == walletInfo.currentAccount.address.description { useAccount = walletInfo.currentAccount break } } if useAccount == nil { return nil } let result: Result<Array<Any>, KeystoreError> = keystore.signData(data, account: useAccount!) // let result: Result<Data, KeystoreError> = keystore.signMessage(data, for: useAccount!) switch result { case .success(let data): return data case .failure( _): return nil } } private func realm(for config: Realm.Configuration) -> Realm { return try! Realm(configuration: config) } private func markAsMainWallet(for account: Wallet) { let type = WalletType.hd(account) let wallet = WalletInfo(type: type, info: keystore.storage.get(for: type)) markAsMainWallet(for: wallet) } private func markAsMainWallet(for wallet: WalletInfo) { let initialName = "R.string.localizable.mainWallet()" keystore.store(object: wallet.info, fields: [ .name(initialName), .mainWallet(true), ]) } } <file_sep>/Qlink/Vender/NEO/Crypto/SHA256.swift // // SHA256.swift // NeoSwift // // Created by <NAME> on 13/09/17. // Copyright © 2017 drei. All rights reserved. // import Foundation //import CommonCrypto extension Data { public var sha256: Data { let bytes = [UInt8](self) return Data(bytes.sha256) } } extension Array where Element == UInt8 { public var sha256: [UInt8] { let bytes = self let mutablePointer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_SHA256_DIGEST_LENGTH)) CC_SHA256(bytes, CC_LONG(bytes.count), mutablePointer) let mutableBufferPointer = UnsafeMutableBufferPointer<UInt8>.init(start: mutablePointer, count: Int(CC_SHA256_DIGEST_LENGTH)) let sha256Data = Data(buffer: mutableBufferPointer) mutablePointer.deallocate(capacity: Int(CC_SHA256_DIGEST_LENGTH)) return sha256Data.bytes } } extension String { public var sha256: Data? { return self.data(using: String.Encoding.utf8)?.sha256 } } <file_sep>/Qlink/Vender/QLC/qlc/utils/WorkUtil.swift // // WorkUtil.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import TrezorCrytoEd25519 public class WorkUtil : NSObject { private static let WorkSize:Int = 8 private static let THRESHOLD:UInt64 = 0xfffffe0000000000 private static var stopWork = false private static var isTimeOut = false private static var startTime:Date? private static var endTime:Date? // private static let ThreadLocalRandom RANDOM = ThreadLocalRandom.current() /* @objc public static func generateWorkOfOperation(hash:String ,handler:@escaping ((String) -> Void)) { var workResult = "" let count = 2 let queue = OperationQueue() for i in 0..<count { print(Date(),"work\(i) = 开始") let operation = BlockOperation(block: { [weak queue] in workResult = WorkUtil.generateWorkOfSingle(hash: hash, startWork: UInt64(i), offsetWork: UInt64(count)) if workResult.count > 0 { queue?.cancelAllOperations() handler(workResult) } }) queue.addOperation(operation) } } @objc public static func generateWorkOfSingle(hash:String, startWork:UInt64, offsetWork:UInt64) -> String { stopWork = false var workIsValid : Bool = false var work:UInt64 = startWork while !workIsValid { if stopWork == true { break } var source = Bytes() let workB = work.toBytes_Little // let workB = work.toBytes_Big source.append(contentsOf: workB) let hashB = hash.hex2Bytes source.append(contentsOf: hashB) let valueB = Blake2b.hash(outLength: WorkSize, in: source) ?? Bytes(count:WorkSize) let value = valueB.bytesToUInt64_Little // let valueBReverse = QLCUtil.reverse(bytes: valueB) // let value = valueBReverse.bytesToUInt64_Big workIsValid = value >= THRESHOLD if workIsValid { break } work = work + offsetWork } if stopWork == true { return "" } stopWork = true print(Date(),"startWork:",startWork,"offsetWork:",offsetWork,"work:",work, "开始---结束了") let workB = work.toBytes_Big return workB.toHexString() // let workBReverse = QLCUtil.reverse(bytes: workB) // return workBReverse.toHexString() } */ @objc static func getRandomNumFromNeg128ToPos126() -> String { // -128~126 var source = String() for _ in 0..<8 { var random = (-128 + (Int(arc4random()) % (126 + 128 + 1))) // print("\(random)") if random < 0 { random = 256 + random // print("\(random)") } var hex = String(random,radix:16) if hex.count < 2 { // 自动补0 hex = "0"+hex } source.append(hex) } // print(source) // print(source.hex2Bytes) return source } @objc public static func generateWorkOfOperationRandom(hash:String ,handler:@escaping ((String,Bool) -> Void)) { isTimeOut = false startTime = Date() // WorkUtil.startTimer() var workResult = "" let count = 2 let queue = OperationQueue() for i in 0..<count { print(Date(),"work\(i) = 开始") let operation = BlockOperation(block: { [weak queue] in workResult = WorkUtil.generateWorkOfSingleRandom(hash: hash) if isTimeOut == true { handler(workResult,true) } if workResult.count > 0 { queue?.cancelAllOperations() handler(workResult,false) } }) queue.addOperation(operation) } } @objc public static func generateWorkOfSingleRandom(hash:String) -> String { stopWork = false var workIsValid : Bool = false var workB:Bytes = Bytes(count: 8) while !workIsValid { endTime = Date() let seconds = startTime!.secondsBetweenDate(toDate: endTime!) if seconds >= 30 { isTimeOut = true stopWork = true } if stopWork == true { break } let workHex = WorkUtil.getRandomNumFromNeg128ToPos126() workB = workHex.hex2Bytes for i in 0..<254 { workB[7] = UInt8(i) var source = Bytes() source.append(contentsOf: workB) let hashB = hash.hex2Bytes source.append(contentsOf: hashB) let valueB = Blake2b.hash(outLength: WorkSize, in: source) ?? Bytes(count:WorkSize) let valueBReverse = QLCUtil.reverse(bytes: valueB) let value = valueBReverse.bytesToUInt64_Big // let value = valueB.bytesToUInt64_Little workIsValid = value >= THRESHOLD if workIsValid { break } } } if stopWork == true { return "" } stopWork = true print(Date(),"work:",workB.toHexString(), "开始---结束了") let workBReverse = QLCUtil.reverse(bytes: workB) return workBReverse.toHexString() // return workB.toHexString() } // static func startTimer() { // var timeCount = 30 // // 在global线程里创建一个时间源 // let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global()) // // 设定这个时间源是每秒循环一次,立即开始 // timer.schedule(deadline: .now(), repeating: .seconds(1)) // // 设定时间源的触发事件 // timer.setEventHandler(handler: { // if stopWork == true { // timer.cancel() // } // // 每秒计时一次 // timeCount = timeCount - 1 // // 时间到了取消时间源 // if timeCount <= 0 { // isTimeOut = true // stopWork = true // timer.cancel() // } // // 返回主线程处理一些事件,更新UI等等 // DispatchQueue.main.async { // print(Date(),"-------%d",timeCount); // } // }) // // 启动时间源 // timer.resume() // } } extension Date { func secondsBetweenDate(toDate: Date) -> Int { let components = Calendar.current.dateComponents([.second], from: self, to: toDate) return components.second ?? 0 } } <file_sep>/Qlink/Vender/QLC/qlc/network/QlcClient.swift // // QlcClient.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/14. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import APIKit import JSONRPCKit //public let qlc_seed:String = "https://rpc.qlcchain.online" // 测试 public let qlc_seed_pro:String = "http://wrpc.qlcchain.org:9735" // 生产 public let qlc_seed_dev:String = "http://172.16.58.3:19735" // 测试 //public let qlc_seed:String = "http://172.16.31.10:9735" // 欧洲生产 //public typealias JSONDictionary_qlc = [String: Any] let timeoutInterval: Double = 30.0 public struct StringIdGenerator: IdGenerator { private var currentId = 1 public mutating func next() -> Id { defer { currentId += 1 } return .string("id\(currentId)") } } //public enum QlcClientError: Error { // case invalidSeed, invalidBodyRequest, invalidData, invalidRequest, noInternet // // var localizedDescription: String { // switch self { // case .invalidSeed: // return "Invalid seed" // case .invalidBodyRequest: // return "Invalid body Request" // case .invalidData: // return "Invalid response data" // case .invalidRequest: // return "Invalid server request" // case .noInternet: // return "No Internet connection" // } // } //} // //public enum QlcClientResult<T> { // case success(T) // case failure(QlcClientError) //} public enum QlcNetwork: String { case test case main } //public class QlcNetworkMonitor { // // public static let sharedInstance = QlcNetworkMonitor() // // public static func autoSelectBestNode(network: QlcNetwork) -> String? { // // var bestNode = "" //load from https://platform.o3.network/api/v1/nodes instead // let semaphore = DispatchSemaphore(value: 0) // O3APIClient(network: network).getNodes { result in // switch result { // case .failure(let error): // // #if DEBUG // print(error) // #endif // bestNode = "" // case .success(let nodes): // bestNode = nodes.neo.best // } // semaphore.signal() // } // semaphore.wait() // return bestNode // } // //} public typealias QlcClientSuccessHandler = ((Any?) -> Void) //public typealias QlcClientFailureHandler = ((Error?) -> Void) public typealias QlcClientFailureHandler = ((Error?,String?) -> Void) public class QlcClient { // public var seed = testSeed // public init(seed: String?) { // self.seed = seed ?? testSeed // } public func call<Request: JSONRPCKit.Request>(_ request: Request, callbackQueue: CallbackQueue? = nil, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let batchFactory = BatchFactory(idGenerator: StringIdGenerator()) let batch = batchFactory.create(request) let httpRequest = LedgerServiceRequest(batch: batch) Session.send(httpRequest, callbackQueue: callbackQueue) { result in // Session.send(httpRequest) { result in switch result { case .success(let answer): print(httpRequest.baseURL,request.method,request.parameters ?? "","🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵🐵 = ",answer) // let isMain = Thread.isMainThread // if isMain { successHandler(answer) // } else { // DispatchQueue.main.sync { // successHandler(answer) // } // } case .failure(let error): print(httpRequest.baseURL,request.method,request.parameters ?? "","🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶 = ",error) // let isMain = Thread.isMainThread // if isMain { // // } else { DispatchQueue.main.async { var title:String? var message:String? switch error { case .connectionError(let error as NSError): title = error.localizedDescription message = error.localizedRecoverySuggestion case .responseError(let error as JSONRPCError): if case .responseError(_, let errorMessage, let data as String?) = error { title = errorMessage message = data } else { fallthrough } default: title = "Unknown error" message = nil } failureHandler(error,title) } // } } } } // public func call(method: String, params: [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { // // guard let url = URL(string: seed) else { //// failureHandler(.invalidSeed) // failureHandler("invalidSeed") // return // } // // let request = NSMutableURLRequest(url: url) // request.httpMethod = "POST" // request.setValue("application/json-rpc", forHTTPHeaderField: "Content-Type") // request.cachePolicy = .reloadIgnoringLocalCacheData // request.timeoutInterval = 30 // // let requestDictionary: [String: Any] = [ // "jsonrpc": "2.0", // "id": UUID().uuidString.replacingOccurrences(of: "-", with: ""), // "method": method, // "params": params ?? [] // ] // // guard let body = try? JSONSerialization.data(withJSONObject: requestDictionary, options: .prettyPrinted) else { //// failureHandler(.invalidBodyRequest) // failureHandler("invalidBodyRequest") // return // } // request.httpBody = body // print("url = ",url) // print("requestDictionary = ",requestDictionary) // let session = URLSession(configuration: .default) // let task = session.dataTask(with: request as URLRequest) { (data, response, err) in // print("err = ",err.debugDescription," data = ",data as Any) // if err != nil { //// failureHandler(.invalidRequest) // DispatchQueue.main.async { // failureHandler("invalidRequest") // } // return // } // // if data == nil { //// failureHandler(.invalidData) // DispatchQueue.main.async { // failureHandler("invalidData") // } // return // } // // guard let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers) else { //// failureHandler(.invalidData) // DispatchQueue.main.async { // failureHandler("invalidData") // } // return // } // // if json == nil { //// failureHandler(.invalidData) // DispatchQueue.main.async { // failureHandler("invalidData") // } // return // } // // DispatchQueue.main.async { // successHandler(json as! JSONDictionary_qlc) // } //// let resultJson = QlcClientResult.success(json!) //// completionHandler(resultJson) // } // task.resume() // } } <file_sep>/Qlink/Vender/QLC/qlc/mnemonic/Crypto/QLCMnemonicCrypto.swift // // Crypto.swift // Vite-keystore_Example // // Created by Water on 2018/8/29. // Copyright © 2018年 Water. All rights reserved. // import CryptoSwift final class QLCMnemonicCrypto { static func PBKDF2SHA512(password: [UInt8], salt: [UInt8]) -> Data { let output: [UInt8] do { output = try PKCS5.PBKDF2(password: <PASSWORD>, salt: salt, iterations: 2048, variant: .sha512).calculate() } catch let error { fatalError("PKCS5.PBKDF2 faild: \(error.localizedDescription)") } return Data(output) } /// Computes the Ethereum hash of a block of data (SHA3 Keccak 256 version). static func sha3keccak256(_ data: Data) -> Data { return Data(bytes: SHA3(variant: .keccak256).calculate(for: data.bytes)) } } <file_sep>/Qlink/Vender/QLC/qlc/rpc/SMSRpc.swift // // SMSRpc.swift // qlc-ios-sdk // // Created by <NAME> on 2019/5/15. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation public class SMSRpc { /** * Return blocks which the sender or receiver of block is the phone number * @param url * @param params string: phone number * @return * @throws QlcException * @throws IOException */ public static func phoneBlocks(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "sms_phoneBlocks", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return blocks which message field is the hash * @param url * @param params string: message hash * @return * @throws QlcException * @throws IOException */ public static func messageBlocks(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "sms_messageBlocks", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Return hash for message * @param url * @param params string: message * @return * @throws QlcException * @throws IOException */ public static func messageHash(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "sms_messageHash", params: params, successHandler: successHandler, failureHandler: failureHandler) } /** * Store message and return message hash * @param url * @param params string: message * @return * @throws QlcException * @throws IOException */ public static func messageStore(url : String?, params : [Any]?, successHandler: @escaping QlcClientSuccessHandler, failureHandler: @escaping QlcClientFailureHandler) { let client : QlcClient = QlcClient() //client.call(method: "sms_messageStore", params: params, successHandler: successHandler, failureHandler: failureHandler) } } <file_sep>/Qlink/Vender/QLC/qlc/bean/QLCTokenMate.swift // // TokenMate.swift // Qlink // // Created by <NAME> on 2019/5/30. // Copyright © 2019 pan. All rights reserved. // import Foundation import BigInt public class QLCTokenMeta { public var type:String? // token hash public var header:String? // the latest block hash for the token chain public var representative:String? // representative address public var open:String? // the open block hash for the token chain public var balance:BigInt? // balance for the token public var account:String? // account that token belong to public var modified:Int? // timestamp public var blockCount:Int? // total block number for the token chain public var tokenName:String? // the token name public var pending:String? // pending amount } <file_sep>/Qlink/Vender/NEO/Util/Data+Util.swift // // Data+Util.swift // NeoSwift // // Created by <NAME> on 13/09/17. // Copyright © 2017 drei. All rights reserved. // import Foundation extension Data { // MARK: Hex String public var hexString: String { return self.map { return String(format: "%x", $0) }.joined() } public var hexStringWithPrefix: String { return "0x\(hexString)" } public var fullHexString: String { return self.map { return String(format: "%02x", $0) }.joined() } public var fullHexStringWithPrefix: String { return "0x\(fullHexString)" } // MARK: Data to [UInt8] public var bytes: [UInt8] { return [UInt8](self) } } <file_sep>/Qlink/Vender/NEO/NeoScan.swift // // NeoScan.swift // NeoSwift // // Created by <NAME> on 4/2/18. // Copyright © 2018 drei. All rights reserved. // import UIKit public class NeoScan: NSObject { public let baseEndpoint = "https://neoscan.io/api/main_net" public enum NeoScanResult<T> { case success(T) case failure(NeoClientError) } public enum NeoScanError: Error { case invalidData var localizedDescription: String { switch self { case .invalidData: return "Invalid response data" } } } enum APIEndpoints: String { case getClaimable = "/v1/get_claimable/" // with address case getBalance = "/v1/get_balance/" // with address case getHistory = "/v1/get_address_abstracts/" //with address } func sendFullNodeRequest(_ url: String, params: [Any]?, completion :@escaping (NeoScanResult<JSONDictionary>) -> ()) { let request = NSMutableURLRequest(url: URL(string: url)!) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, _, err) in if err != nil { completion(.failure(.invalidRequest)) return } guard let json = try? JSONSerialization.jsonObject(with: data!, options: []) as! JSONDictionary else { completion(.failure(.invalidData)) return } let result = NeoScanResult.success(json) completion(result) } task.resume() } public func getClaimableGAS(address: String, completion: @escaping(NeoScanResult<Claimable>) -> ()) { let url = baseEndpoint + APIEndpoints.getClaimable.rawValue + address sendFullNodeRequest(url, params: nil) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(let response): let decoder = JSONDecoder() guard let data = try? JSONSerialization.data(withJSONObject: response, options: .prettyPrinted), let jsonResult = try? decoder.decode(Claimable.self, from: data) else { completion(.failure(.invalidData)) return } let result = NeoScanResult.success(jsonResult) completion(result) } } } public func getBalance(address: String, completion: @escaping(NeoScanResult<NeoScanGetBalance>) -> ()) { let url = baseEndpoint + APIEndpoints.getBalance.rawValue + address sendFullNodeRequest(url, params: nil) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(let response): let decoder = JSONDecoder() guard let data = try? JSONSerialization.data(withJSONObject: response, options: .prettyPrinted), let jsonResult = try? decoder.decode(NeoScanGetBalance.self, from: data) else { completion(.failure(.invalidData)) return } let result = NeoScanResult.success(jsonResult) completion(result) } } } public func getTransactionHistory(address: String, page: Int, completion: @escaping(NeoScanResult<NEOScanTransactionHistory>) -> ()) { let url = baseEndpoint + APIEndpoints.getHistory.rawValue + address + "/" + String(page) sendFullNodeRequest(url, params: nil) { result in switch result { case .failure(let error): completion(.failure(error)) case .success(let response): let decoder = JSONDecoder() guard let data = try? JSONSerialization.data(withJSONObject: response, options: .prettyPrinted), let jsonResult = try? decoder.decode(NEOScanTransactionHistory.self, from: data) else { completion(.failure(.invalidData)) return } let result = NeoScanResult.success(jsonResult) completion(result) } } } } <file_sep>/Qlink/Vender/NEO/ShamirSecret.swift // // ShamirSecret.swift // NeoSwift // // Created by <NAME> on 2/21/18. // Copyright © 2018 drei. All rights reserved. // import Foundation import Neoutils public class ShamirSecret { var secret: NeoutilsSharedSecret! init(wif: String) { var error: NSError? guard let secret = NeoutilsGenerateShamirSharedSecret(wif, &error) else { return } self.secret = secret } func getFirst() -> String { return secret.first().fullHexString } func getSecond() -> String { return secret.second().fullHexString } static func recoverWIFFromPieces(first: Data, second: Data) -> String? { var error: NSError? guard let secret = NeoutilsRecoverFromSharedSecret(first, second, &error) else { return nil } return secret } } <file_sep>/Qlink/Vender/NEO/ContractState.swift // // ContractState.swift // O3 // // Created by <NAME> on 2/14/19. // Copyright © 2019 O3 Labs Inc. All rights reserved. // import Foundation public struct ContractState: Codable { var version: Int var hash: String var script: String var parameters: [String] var returntype: String var name: String var code_version: String var author: String var email: String var description: String var properties: Properties public struct Properties: Codable { var storage: Bool var dynamic_invoke: Bool } }
99dc4c752ba1ca62dd712a09ab3de1bc51c67e70
[ "Swift", "C", "Ruby", "Markdown" ]
65
Swift
qlcchain/WinQ-iOS
2c245e56fabc3b36ee5c2d11c127fc8a96dece3f
89a4ece5d9b14f28e6c3d246f9a076159c7a2bba
refs/heads/master
<repo_name>antoniosumak/react-ecommerce<file_sep>/src/lib/styles/theme.js export const breakpoints = { mobileLarge: 'min-width: 576px', tablet: 'min-width: 768px', desktop: 'min-width: 1024px', desktopLarge: 'min-width: 1440px', }; export const boxShadow = 'rgba(149, 157, 165, 0.2) 0px 4px 24px;'; export const colors = { black: '#283149', gray: '#404B69', red: '#F73859', white: '#DBEDF3', darkRed: '#f50c34', }; <file_sep>/src/context/CartItemsContext.js import React, { useState, createContext } from 'react'; const CartItemsContext = createContext(); const CartItemsProvider = ({ children }) => { const [cartItems, setCartItems] = useState([]); return ( <CartItemsContext.Provider value={{ cartItems, setCartItems }}> {children} </CartItemsContext.Provider> ); }; export { CartItemsProvider, CartItemsContext }; <file_sep>/src/pages/Cart.js import React, { useContext } from 'react'; import Section from '../components/Section/Section'; import { CartRow, CartRowImage, CartRowItem } from './CartStyles'; import { CartItemsContext } from '../context/CartItemsContext'; const Cart = () => { const { cartItems } = useContext(CartItemsContext); return ( <Section> <CartRow> <CartRowItem></CartRowItem> <CartRowItem> <strong>Product</strong> </CartRowItem> <CartRowItem> <strong>Quantity</strong> </CartRowItem> <CartRowItem> <strong>Total</strong> </CartRowItem> <CartRowItem> <strong>Remove item</strong> </CartRowItem> </CartRow> {cartItems && cartItems.map((value, index) => ( <CartRow key={index}> <CartRowImage src={value.imageURL} /> <CartRowItem>{value.product}</CartRowItem> <CartRowItem>{value.quantity}</CartRowItem> <CartRowItem>{`$${value.quantity * value.price}`}</CartRowItem> </CartRow> ))} {console.log(cartItems)} </Section> ); }; export default Cart; <file_sep>/src/components/StoreItem/StoreItemStyles.js import styled from 'styled-components'; import { boxShadow, colors } from '../../lib/styles/theme'; export const Wrapper = styled.div` padding: 20px; box-shadow: ${boxShadow}; position: relative; `; export const ImageWrapper = styled.figure` width: 100%; height: 200px; `; export const Image = styled.img` height: 100%; width: 100%; object-fit: contain; `; export const Description = styled.div``; export const Product = styled.h2` color: ${colors.black}; text-align: center; padding: 8px 0px; `; export const Price = styled.p` font-weight: bold; padding: 8px 0px; padding-bottom: 16px; text-align: center; `; export const Category = styled.p` width: min-content; background-color: ${colors.black}; color: ${colors.white}; height: 35px; width: 35px; display: flex; justify-content: center; align-items: center; border-radius: 0px 10px 10px 10px; margin: -20px; font-size: 20px; box-shadow: ${boxShadow}; `; export const Quanty = styled.p` padding: 8px; `; <file_sep>/src/components/Header/HeaderStyles.js import styled from 'styled-components'; import { boxShadow, breakpoints, colors } from '../../lib/styles/theme'; import { FaShoppingCart } from 'react-icons/fa'; import { NavLink } from 'react-router-dom'; export const HeaderWrapper = styled.header` height: 72px; box-shadow: ${boxShadow}; @media screen and (${breakpoints.tablet}) { height: 96px; } `; export const HeaderInner = styled.div` height: 100%; display: flex; justify-content: space-between; align-items: center; padding: 0px 20px; @media screen and (${breakpoints.tablet}) { } @media screen and (${breakpoints.desktop}) { max-width: 944px; margin: 0 auto; } @media screen and (${breakpoints.desktopLarge}) { max-width: 1224px; } `; export const LogoContainer = styled.figure` width: 100px; height: 40px; `; export const Logo = styled.img` width: 100%; height: 100%; object-fit: contain; `; export const Nav = styled.nav` display: none; @media screen and (${breakpoints.tablet}) { display: block; } `; export const InnerNav = styled.div` display: flex; `; export const NavItems = styled(NavLink)` text-decoration: none; position: relative; color: ${colors.white}; padding: 24px 0px; font-size: 28px; font-weight: bold; @media screen and (${breakpoints.tablet}) { margin: 0px 18px; font-size: 16px; color: ${colors.black}; &:not(:last-child) { &:before { content: ''; width: 0%; transition: 0.3s ease-in-out; } &:hover { cursor: pointer; &:before { content: ''; position: absolute; display: block; bottom: -10px; background: ${colors.red}; height: 4px; width: 100%; } } } } `; export const Hamburger = styled.div` width: 32px; height: 24px; display: flex; flex-direction: column; align-items: center; justify-content: space-between; @media screen and (${breakpoints.tablet}) { display: none; } &:hover { cursor: pointer; } `; export const HamburgerLine = styled.div` width: 100%; height: 4px; background-color: ${colors.black}; border-radius: 10px; transition: 0.3s ease-in-out; transform-origin: 2px; &:first-child { transform: ${(p) => (p.opened ? 'rotate(45deg)' : 'rotate(0deg)')}; } &:nth-child(2) { opacity: ${(p) => (p.opened ? '0' : '1')}; transform: ${(p) => (p.opened ? 'translateX(30px)' : 'transformX(0px)')}; } &:last-child { transform: ${(p) => (p.opened ? 'rotate(-45deg)' : 'rotate(0deg)')}; } `; export const MobileMenu = styled.div` display: ${(props) => (props.visible ? 'flex' : 'none')}; display: flex; flex-direction: column; justify-content: center; align-items: center; position: absolute; width: 100%; height: calc(100% - 72px); margin-top: 72px; transition: 0.3s ease-in-out; right: ${(p) => (p.visible ? '0px' : '-100%')}; top: 0; z-index: 10; background-color: ${colors.black}; text-transform: uppercase; @media screen and (${breakpoints.tablet}) { display: none; } `; export const ItemsCounter = styled.p` position: absolute; color: white; top: 0px; right: -18px; width: 28px; height: 28px; background-color: ${colors.red}; border-radius: 50%; display: flex; justify-content: center; align-items: center; `; export const ShoppingCart = styled(FaShoppingCart)` font-size: 24px; color: ${colors.red}; `; export const Alltogether = styled.div` position: relative; `; export const CartSummary = styled.div` padding: 20px; height: min-content; position: absolute; right: 0; top: 32px; bottom: -40px; width: 400px; background-color: white; z-index: 20; box-shadow: ${boxShadow}; transition: 0.3s ease-in-out; display: none; ${NavItems}:hover & { display: flex; flex-direction: column; } `; export const CartSummaryRow = styled.div` display: grid; grid-template-columns: repeat(4, 1fr); grid-gap: 20px; align-items: center; border-bottom: 1px solid ${colors.gray}; padding: 12px 0px; &:first-child { border-bottom: none; } `; export const CartSummaryItems = styled.p` display: none; font-weight: normal; ${NavItems}:hover & { display: flex; } `; export const MiniImage = styled.img` width: 50px; height: 50px; object-fit: contain; `; export const CartTotal = styled.div` padding: 16px 0px; display: flex; justify-content: space-between; align-items: center; `; export const CartTotalValues = styled.p``; <file_sep>/src/lib/styles/generalStyles.js import styled from 'styled-components'; import { breakpoints, colors } from './theme'; export const Main = styled.main``; export const Grid = styled.div` display: grid; grid-template-columns: 1fr; row-gap: 40px; @media screen and (${breakpoints.tablet}) { grid-template-columns: repeat(2, 1fr); grid-gap: 40px; } @media screen and (${breakpoints.desktop}) { grid-template-columns: repeat(3, 1fr); } @media screen and (${breakpoints.desktopLarge}) { grid-template-columns: repeat(4, 1fr); } `; export const Button = styled.button` ${(p) => p.cardButton && `position: absolute`}; background-color: ${colors.red}; color: ${colors.white}; padding: 8px 24px; border: 1px solid ${colors.red}; left: 50%; ${(p) => p.cardButton && `transform: translate(-50%);`}; transition: 0.3s ease-in-out; &:hover { cursor: pointer; border: 1px solid ${colors.white}; background-color: ${colors.darkRed}; color: ${colors.white}; } `; export const ButtonInput = styled.button` background-color: ${colors.gray}; color: ${colors.white}; padding: 8px; border: 1px solid ${colors.gray}; left: 50%; transition: 0.3s ease-in-out; border-radius: 10px; font-weight: bold; &:hover { cursor: pointer; border: 1px solid ${colors.white}; background-color: ${colors.black}; color: ${colors.white}; } `; export const Center = styled.div` width: 100%; display: flex; justify-content: center; align-items: center; margin-bottom: 16px; `; <file_sep>/src/pages/Store.js import React from 'react'; import Section from '../components/Section/Section'; import StoreItem from '../components/StoreItem/StoreItem'; import { Grid } from '../lib/styles/generalStyles'; import { products } from './mock'; const Store = () => { return ( <Section> <Grid> {products && products.map((data, index) => <StoreItem key={index} data={data} />)} </Grid> </Section> ); }; export default Store; <file_sep>/src/pages/mock.js export const products = [ { product: 'Iphone X', category: 'Mobile', price: 1000, quantity: 10, imageURL: 'http://ayopayop.com/public/uploads/all/NhaqtMmr7CMC29mQtEFNHZnnOrEc6yFSBVIg1EFW.png', }, { product: 'Macbook Air M1', category: 'Laptop', price: 1500, quantity: 8, imageURL: 'https://www.nabava.net/slike/products/78/60/12706078/apple-macbook-air-mgnd3ze-a-apple-mac-os_48a6c098.png', }, { product: 'Airpods Pro', category: 'Headphones', price: 600, quantity: 15, imageURL: 'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/apple-airpods-pro-new-design-case-and-airpods-pro-102819-screen-1572556929.png?resize=480:*', }, { product: 'Airtag', category: 'Location', price: 20, quantity: 15, imageURL: 'https://assets.store.com.hr/spree/modules/1436/original/AirTag-coming-soon.png?1619096229', }, { product: 'Iphone X', category: 'Mobile', price: 1000, quantity: 10, imageURL: 'http://ayopayop.com/public/uploads/all/NhaqtMmr7CMC29mQtEFNHZnnOrEc6yFSBVIg1EFW.png', }, { product: 'Macbook Air M1', category: 'Laptop', price: 1500, quantity: 8, imageURL: 'https://www.nabava.net/slike/products/78/60/12706078/apple-macbook-air-mgnd3ze-a-apple-mac-os_48a6c098.png', }, { product: 'Airpods Pro', category: 'Headphones', price: 600, quantity: 15, imageURL: 'https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/apple-airpods-pro-new-design-case-and-airpods-pro-102819-screen-1572556929.png?resize=480:*', }, { product: 'Airtag', category: 'Location', price: 20, quantity: 15, imageURL: 'https://assets.store.com.hr/spree/modules/1436/original/AirTag-coming-soon.png?1619096229', }, ]; <file_sep>/src/components/StoreItem/StoreItem.js import React, { useState, useContext } from 'react'; import { Wrapper, ImageWrapper, Image, Description, Product, Price, Category, Quanty, } from './StoreItemStyles'; import { Button, Center, ButtonInput } from '../../lib/styles/generalStyles'; import { HiOutlineDeviceMobile } from 'react-icons/hi'; import { IoLaptopOutline, IoLocationOutline } from 'react-icons/io5'; import { RiHeadphoneLine } from 'react-icons/ri'; import { CartItemsContext } from '../../context/CartItemsContext'; const StoreItem = ({ data }) => { const [counter, setCounter] = useState(0); const { cartItems, setCartItems } = useContext(CartItemsContext); const categorieIcons = { Mobile: <HiOutlineDeviceMobile />, Laptop: <IoLaptopOutline />, Headphones: <RiHeadphoneLine />, Location: <IoLocationOutline />, }; const Increment = () => { if (counter < data.quantity) { setCounter(counter + 1); } else setCounter(counter); }; const Decrement = () => { if (counter > 0) { setCounter(counter - 1); } else setCounter(0); }; const handleCart = () => { const result = { product: data.product, price: data.price, imageURL: data.imageURL, quantity: counter, }; if (counter > 0) { setCartItems([...cartItems, result]); } else { console.log('Cant add 0 items!'); } }; return ( <Wrapper> <Category>{categorieIcons[data.category]}</Category> <ImageWrapper> <Image src={data.imageURL} /> </ImageWrapper> <Description> <Product>{data.product}</Product> <Price>{`$${data.price}`}</Price> <Center> <ButtonInput onClick={Decrement}>-</ButtonInput> <Quanty>{counter}</Quanty> <ButtonInput onClick={Increment}>+</ButtonInput> </Center> </Description> <Button cardButton onClick={() => handleCart()}> Add to cart </Button> </Wrapper> ); }; export default StoreItem; <file_sep>/src/components/Header/Header.js import React, { useState, useContext } from 'react'; import { HeaderWrapper, HeaderInner, LogoContainer, NavItems, Logo, Nav, InnerNav, ShoppingCart, Hamburger, HamburgerLine, MobileMenu, ItemsCounter, CartSummary, CartSummaryItems, Alltogether, CartSummaryRow, MiniImage, CartTotal, CartTotalValues, } from './HeaderStyles'; import logo from '../../assets/images/logo.png'; import { CartItemsContext } from '../../context/CartItemsContext'; const Header = () => { const [opened, setOpened] = useState(false); const { cartItems } = useContext(CartItemsContext); const cartTotal = cartItems.length > 0 && cartItems .map((value) => { return value.price * value.quantity; }) .reduce((sum, currentValue) => { return (sum += currentValue); }); const links = [ { label: 'Shop', path: '/' }, { label: 'Login', path: '/login' }, { label: 'Admin', path: '/admin' }, { label: <ShoppingCart />, path: '/cart' }, ]; const cartLabels = [ { label: '', }, { label: 'Product', }, { label: 'Quantity', }, { label: 'Total', }, ]; return ( <HeaderWrapper> <HeaderInner> <LogoContainer> <Logo src={logo} /> </LogoContainer> <Nav> <InnerNav> <NavItems exact to="/"> Shop </NavItems> <NavItems to="/login">Login</NavItems> <NavItems to="/admin">Admin</NavItems> <NavItems to="cart"> <ItemsCounter>{cartItems && cartItems.length}</ItemsCounter> <Alltogether> <ShoppingCart /> <CartSummary> <CartSummaryRow> {cartLabels.map((value, index) => ( <CartSummaryItems key={index}> {value.label} </CartSummaryItems> ))} </CartSummaryRow> {cartItems.length > 0 ? ( cartItems.map((value, index) => ( <CartSummaryRow key={index}> <MiniImage src={value.imageURL} /> <CartSummaryItems>{value.product}</CartSummaryItems> <CartSummaryItems>{value.quantity}</CartSummaryItems> <CartSummaryItems> {`$${value.price * value.quantity}`} </CartSummaryItems> </CartSummaryRow> )) ) : ( <h2>This bitch empty</h2> )} <CartTotal> <CartTotalValues>Your total is: </CartTotalValues> <CartTotalValues>{`$${cartTotal}`}</CartTotalValues> </CartTotal> </CartSummary> </Alltogether> </NavItems> </InnerNav> </Nav> <Hamburger onClick={() => setOpened(!opened)}> <HamburgerLine opened={opened} /> <HamburgerLine opened={opened} /> <HamburgerLine opened={opened} /> </Hamburger> </HeaderInner> <MobileMenu visible={opened}> {links.map((value, index) => ( <NavItems key={index} to={value.path}> {value.label} </NavItems> ))} </MobileMenu> </HeaderWrapper> ); }; export default Header; <file_sep>/src/pages/CartStyles.js import styled from 'styled-components'; import { breakpoints } from '../lib/styles/theme'; export const CartRow = styled.div` display: grid; grid-template-columns: repeat(3, 1fr); grid-row-gap: 20px; align-items: center; justify-items: center; @media screen and (${breakpoints.tablet}) { grid-template-columns: repeat(4, 1fr); justify-items: start; } @media screen and (${breakpoints.desktop}) { grid-template-columns: repeat(5, 1fr); } `; export const CartRowImage = styled.img` height: 100px; width: 100px; object-fit: contain; `; export const CartRowItem = styled.p` &:nth-child(3), &:nth-child(5) { display: none; } @media screen and (${breakpoints.tablet}) { &:nth-child(3) { display: block; } @media screen and (${breakpoints.desktop}) { &:nth-child(5) { display: block; } } `; <file_sep>/src/App.js import React from 'react'; import { Route } from 'react-router-dom'; import Login from './pages/Login'; import Cart from './pages/Cart'; import Store from './pages/Store'; import { Main } from './lib/styles/generalStyles'; import Header from './components/Header/Header'; function App() { return ( <> <Header /> <Main> <Route exact path="/" component={Store} /> <Route path="/login" component={Login} /> <Route path="/cart" component={Cart} /> </Main> </> ); } export default App;
9d4605f67e528f0a3df9f25ebab1107930ee80ea
[ "JavaScript" ]
12
JavaScript
antoniosumak/react-ecommerce
146b40401537f4085a3624257ae89f44b32122de
11562dd6eaa7ee69342b2e45d9ac3858ead632a7
refs/heads/master
<repo_name>differentialmanifold/vue-2048-backend<file_sep>/td/q_learning.py import sys import itertools import os import argparse import numpy as np from collections import namedtuple if "../" not in sys.path: sys.path.append("../") from boardWithoutTiles import BoardForTrain from tensorBoard.tensorBoardPlot import TensorBoardPlot from my_redis.my_redis import MyRedis def make_epsilon_greedy_policy(my_redis, epsilon, nA): """ Creates an epsilon-greedy policy based on a given Q-function and epsilon. Args: my_redis: A redis instance that maps from state -> action-values. Each value is a numpy array of length nA (see below) epsilon: The probability to select a random action . float between 0 and 1. nA: Number of actions in the environment. Returns: A function that takes the observation as an argument and returns the probabilities for each action in the form of a numpy array of length nA. """ def policy_fn(observation, available_direction, is_print=False): dir_arr = np.array(available_direction).astype(int) observation_value = my_redis.hget_q(observation) if np.sum(np.array(observation_value)) == 0: if is_print: print("observation {} is not trained".format(observation)) return dir_arr / np.sum(dir_arr) A = (np.ones(nA, dtype=float) * dir_arr) * epsilon / np.sum(dir_arr) best_action = np.argmax(np.array(observation_value) * dir_arr) A[best_action] += (1.0 - epsilon) return A return policy_fn def transferMatrixToState(matrix, env): state = env.transferMatrixToTuple(matrix) return state def q_learning(env, args, replay_memory_size=50000, replay_memory_init_size=5000, batch_size=32, discount_factor=1.0, alpha=0.5, epsilon=0.1): """ Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy while following an epsilon-greedy policy Args: env: environment. discount_factor: Gamma discount factor. alpha: TD learning rate. epsilon: Chance the sample a random action. Float betwen 0 and 1. Returns: Q is the optimal action-value function, a dictionary mapping state -> action values. """ q_learning_scope = args['scope'] # The final action-value function. # A nested dictionary that maps state -> (action -> action-value). my_redis = MyRedis(q_learning_scope) total_step = my_redis.get_step() tensorBoardPlot = TensorBoardPlot(scope=q_learning_scope, summaries_dir=args['summaries_dir']) # The policy we're following policy = make_epsilon_greedy_policy(my_redis, epsilon, env.action_space) # The replay memory replay_memory = [] Transition = namedtuple("Transition", ["state", "action", "reward", "next_state", "done"]) # Populate the replay memory with initial experience # print("Populating replay memory...") # matrix, can_move_dir = env.reset() # state = transferMatrixToState(matrix, env, Q) # for i in range(replay_memory_init_size): # action_probs = policy(state, can_move_dir) # action = np.random.choice(np.arange(len(action_probs)), p=action_probs) # next_matrix, reward, done, _, _, next_can_move_dir = env.step(action) # next_state = transferMatrixToState(next_matrix, env, Q) # replay_memory.append(Transition(state, action, reward, next_state, done)) # if done: # matrix, can_move_dir = env.reset() # state = transferMatrixToState(matrix, env, Q) # else: # state = next_state # can_move_dir = next_can_move_dir # print("Init replay finished") # added part saved to redis add_saved_obj = dict() for i_episode in itertools.count(start=total_step + 1): # Reset the environment and pick the first action matrix, can_move_dir = env.reset() state = transferMatrixToState(matrix, env) # One step in the environment episode_length = 0 for t in itertools.count(): # Take a step action_probs = policy(state, can_move_dir) action = np.random.choice(np.arange(len(action_probs)), p=action_probs) next_matrix, reward, done, _, _, next_can_move_dir = env.step(action) next_state = transferMatrixToState(next_matrix, env) # # If our replay memory is full, pop the first element # if len(replay_memory) == replay_memory_size: # replay_memory.pop(0) # # # Save transition to replay memory # replay_memory.append(Transition(state, action, reward, next_state, done)) # # # TD Update # # Sample a minibatch from the replay memory # samples = random.sample(replay_memory, batch_size) # for sample in samples: # best_next_action = np.argmax(Q[sample.next_state]) # td_target = sample.reward + discount_factor * Q[sample.next_state][best_next_action] # td_delta = td_target - Q[sample.state][sample.action] # Q[sample.state][sample.action] += alpha * td_delta state_value = my_redis.hget_q(state) next_state_value = my_redis.hget_q(next_state) if state not in add_saved_obj: add_saved_obj[state] = state_value best_next_action = np.argmax(next_state_value) td_target = reward + discount_factor * next_state_value[best_next_action] td_delta = td_target - state_value[action] add_saved_obj[state][action] += alpha * td_delta state = next_state can_move_dir = next_can_move_dir if done: break # save parameter to redis saved_obj = {'q': add_saved_obj, 'step': i_episode} my_redis.store_td(saved_obj) add_saved_obj = dict() # Print out which episode we're on, useful for debugging. if (i_episode + 1) % int(args['outputInterval']) == 0: print('----------') print("Episode {}.".format(i_episode + 1)) test_Q(tensorBoardPlot, env, my_redis, i_episode) def test_Q(tensorBoardPlot, env, my_redis, step): board_without_tiles = BoardForTrain(size=int(args['size'])) policy = make_epsilon_greedy_policy(my_redis, 0, board_without_tiles.action_space) score_map = {} max_value_map = {} test_episodes = 1000 for i in range(test_episodes): board_without_tiles = BoardForTrain(size=int(args['size'])) while not board_without_tiles.has_done(): status = transferMatrixToState(board_without_tiles.matrix(), env) action = np.argmax(policy(status, board_without_tiles.can_move_dir)) board_without_tiles.move(action) matrix = board_without_tiles.matrix() score = np.sum(matrix) max_value = np.max(matrix) if score in score_map: score_map[score] = score_map[score] + 1 else: score_map[score] = 1 if max_value in max_value_map: max_value_map[max_value] = max_value_map[max_value] + 1 else: max_value_map[max_value] = 1 print(score_map) print(max_value_map) weight_score = 0 for key in score_map: weight_score = weight_score + key * (score_map[key] / test_episodes) weight_max_value = 0 for key in max_value_map: weight_max_value = weight_max_value + key * (max_value_map[key] / test_episodes) q_length = my_redis.hlen_q() print("Q length is {}".format(q_length)) tensorBoardPlot.add_value('Q_length', q_length, step) tensorBoardPlot.add_value('weight_score', weight_score, step) tensorBoardPlot.add_value('weight_max_value', weight_max_value, step) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('--size', help='size of matrix, 2x2,3x3,4x4', default=2) parser.add_argument('--outputInterval', help='interval to print test value', default=100) parser.add_argument('--scope', help='scope for saving in redis and tensorboard', default='tencent2') parser.add_argument('--summaries_dir', help='directory for tensorboard', default=os.path.expanduser('~/tensorboard')) args = vars(parser.parse_args()) board_without_tiles = BoardForTrain(size=int(args['size'])) q_learning(board_without_tiles, args) <file_sep>/board.py import random import numpy as np class Tile: tile_id = 0 def __init__(self, value=0, row=-1, column=-1): self.value = value self.row = row self.column = column self.oldRow = -1 self.oldColumn = -1 self.markForDeletion = False self.mergedInto = None Tile.tile_id += 1 self.id = Tile.tile_id self.is_new = None self.has_moved = None self.from_row = None self.from_column = None self.to_row = None self.to_column = None def set_properties(self): self.is_new = self.oldRow == -1 and self.mergedInto is None self.from_row = self.row if self.mergedInto is not None else self.oldRow self.from_column = self.column if self.mergedInto is not None else self.oldColumn self.to_row = self.mergedInto['row'] if self.mergedInto is not None else self.row self.to_column = self.mergedInto['column'] if self.mergedInto is not None else self.column self.has_moved = (self.from_row != -1 and (self.from_row != self.to_row or self.from_column != self.to_column)) or ( self.mergedInto is not None) class Board: size = 2 fourProbability = 0.1 delta_x = [-1, 0, 1, 0] delta_y = [0, -1, 0, 1] def __init__(self): Tile.tile_id = 0 self.tiles = [] self.cells = [[self.add_tile() for _ in range(Board.size)] for _ in range(Board.size)] self.add_random_tile() self.set_positions() self.set_tiles_properties() self.has_changed = True self.won = False self.max_value = 0 self.gain_score = 0 self.total_score = 0 self.lost = False self.can_move_dir = [False, False, False, False] def rotate_left(self): rows = len(self.cells) columns = len(self.cells[0]) new_rows = columns new_columns = rows self.cells = [[self.cells[j][columns - i - 1] for j in range(new_columns)] for i in range(new_rows)] def add_tile(self, value=0): res = Tile(value) if value != 0: self.tiles.append(res) return res def move_left(self): has_changed = False self.gain_score = 0 for row in range(Board.size): current_row = [tile for tile in self.cells[row] if tile.value != 0] result_row = [None for _ in range(Board.size)] for target in range(Board.size): target_tile = current_row.pop(0) if len(current_row) > 0 else self.add_tile() if len(current_row) > 0 and current_row[0].value == target_tile.value: self.gain_score += target_tile.value tile1 = target_tile target_tile = self.add_tile(target_tile.value) tile1.mergedInto = target_tile.__dict__ tile2 = current_row.pop(0) tile2.mergedInto = target_tile.__dict__ target_tile.value += tile2.value result_row[target] = target_tile # self.won |= (target_tile.value == 2048) has_changed |= (target_tile.value != self.cells[row][target].value) self.cells[row] = result_row self.total_score += self.gain_score return has_changed def set_positions(self): for i in range(Board.size): for j in range(Board.size): tile = self.cells[i][j] tile.oldRow = tile.row tile.oldColumn = tile.column tile.row = i tile.column = j tile.markForDeletion = False def set_tiles_properties(self): for tile in self.tiles: tile.set_properties() def add_random_tile(self): empty_cells = [{'row': i, 'column': j} for i in range(Board.size) for j in range(Board.size) if self.cells[i][j].value == 0] _index = random.choice(range(len(empty_cells))) cell = empty_cells[_index] new_value = 4 if random.random() < Board.fourProbability else 2 self.cells[cell['row']][cell['column']] = self.add_tile(new_value) def clear_old_tiles(self): self.tiles = [tile for tile in self.tiles if tile.markForDeletion is False] for tile in self.tiles: tile.markForDeletion = True def move(self, direction): # 0 -> left, 1 -> up, 2 -> right, 3 -> down self.clear_old_tiles() for _ in range(direction): self.rotate_left() has_changed = self.move_left() for _ in range(direction, 4): self.rotate_left() if has_changed: self.add_random_tile() self.has_changed = has_changed self.set_positions() self.set_tiles_properties() def can_swipe_left(self): """ compare adjacent cells two condition can move: 1. first cell is empty and second cell is not empty 2. two cells not empty and value is equal """ for row in range(Board.size): for column in range(Board.size - 1): first_value = self.cells[row][column].value second_value = self.cells[row][column + 1].value if first_value == 0 and second_value != 0: return True if first_value != 0 and second_value != 0 and first_value == second_value: return True return False def check_swipe_all_direction(self): # left, up, right, down for i in range(4): self.can_move_dir[i] = self.can_swipe_left() self.rotate_left() def has_lost(self): return not any(self.can_move_dir) def has_done(self): return self.won or self.has_lost() def matrix(self): matrix_value = [[self.cells[row][column].value for column in range(Board.size)] for row in range(Board.size)] return np.array(matrix_value) def front_call_obj(self): tiles = [tile.__dict__ for tile in self.tiles] cells = [[tile.__dict__ for tile in row] for row in self.cells] return {'tiles': tiles, 'cells': cells, 'hasChanged': self.has_changed, 'won': self.won, 'done': self.has_done(), 'hasLost': self.has_lost()} def env_init(self): self.__init__() self.check_swipe_all_direction() _matrix = self.matrix() return _matrix, self.can_move_dir def step(self, _action): self.move(_action) self.check_swipe_all_direction() _matrix = self.matrix() _done = False if self.has_done(): _done = True self.max_value = np.max(_matrix) return _matrix, self.gain_score, _done, self.max_value, self.total_score, self.can_move_dir def print_matrix(_matrix): print('---') for i in range(len(_matrix)): print(_matrix[i]) print('---') if __name__ == "__main__": board = Board() index = 0 matrix = board.env_init() print('****') print('index {}'.format(index)) print_matrix(matrix) print('****') done = False while not done: action = random.choice(range(board.size)) matrix, reward, done, value, score, can_move_dir = board.step(action) index += 1 print('****') print('action {}'.format(action)) print('index {}'.format(index)) print_matrix(matrix) print('reward {}'.format(reward)) print('score {}'.format(score)) print('done {}'.format(done)) print('can move dir {}'.format(can_move_dir)) print('****') <file_sep>/model_save/model_save.py import os from keras.models import load_model class ModelSave: def __init__(self, scope="estimator"): self.scope = scope model_dir = os.path.expanduser('~/Developer/python/model_save/model_{}'.format(scope)) if not os.path.exists(model_dir): os.makedirs(model_dir) self.model_path = os.path.join(model_dir, 'model_{}.h5'.format(scope)) def exist(self): return os.path.isfile(self.model_path) def save(self, model): model.save(self.model_path) def load(self): return load_model(self.model_path) <file_sep>/dp/policyEvaluate.py import sys import numpy as np if "../" not in sys.path: sys.path.append("../") from boardWithoutTiles import BoardForTrain def policy_eval(policy, transition_probability, discount_factor=1.0, theta=0.00001): """ Evaluate a policy given an environment and a full description of the environment's dynamics. Args: policy: representing the policy. transition_probability: transition_probability represents the transition probabilities of the environment. transition_probability[s][a] is a list of transition tuples (prob, next_state, reward, done). theta: We stop evaluation once our value function change is less than theta for all states. discount_factor: Gamma discount factor. Returns: the value function. """ # Start with a random (all 0) value function V = {} for status in transition_probability.keys(): V[status] = 0 index = 0 while True: index = index + 1 print('index is {}'.format(index)) # print(V) delta = 0 # For each state, perform a "full backup" for s in transition_probability.keys(): v = 0 # Look at the possible next actions for a, action_prob in enumerate(policy[s]): # For each action, look at the possible next states... for prob, next_state, reward, done in transition_probability[s][a]: # Calculate the expected value. Ref: Sutton book eq. 4.6. v += action_prob * prob * (reward + discount_factor * V.get(next_state, 0)) # How much our value function changed (across any states) delta = max(delta, np.abs(v - V[s])) V[s] = v # Stop evaluating once our value function change is below a threshold if delta < theta: break return V def create_random_policy(transition_probability): random_policy = {} for s in transition_probability.keys(): random_policy[s] = np.ones(shape=4) / 4 return random_policy if __name__ == '__main__': board_without_tiles = BoardForTrain() transition_probability = board_without_tiles.createTransitionProbability() random_policy = create_random_policy(transition_probability) vfun = policy_eval(random_policy, transition_probability) print(vfun) <file_sep>/mcts/MonteCarloTreeSearch.py import time import os import sys from datetime import datetime if "../" not in sys.path: sys.path.append("../") from mcts.Tree import Tree, Node from mcts.State import State from boardWithoutTiles import BoardForTrain def select_promissing_node(root_node): node = root_node while len(node.children) > 0: node = node.find_best_node_with_utc() return node def expand_node(promising_node): board = promising_node.state.board can_move_dir = board.can_move_dir states = [] for i in range(len(can_move_dir)): if can_move_dir[i]: new_board = board.copy() new_board.step(i) state = State(new_board) states.append(state) for i in range(len(states)): new_node = Node(states[i]) new_node.parent = promising_node promising_node.children.append(new_node) def simulate_random_result(node_to_explore): state = node_to_explore.state new_state = State(state.board.copy()) done = new_state.board.has_done() total_score = new_state.board.total_score while not done: matrix, reward, done, max_value, total_score, _ = new_state.random_play() return total_score def back_propogation(node_to_explore, playout_result): temp_node = node_to_explore while temp_node is not None: temp_node.state.increment_visit() temp_node.state.add_score(playout_result) temp_node = temp_node.parent def print_matrix(_matrix): print('---') for i in range(4): print(_matrix[i]) print('---') class RecycleSolver: def __init__(self, recycle_type, value): self.recycle_type = recycle_type self.value = value self.current_milli_time = lambda: int(round(time.time() * 1000)) self.start = self.current_milli_time() self.end = self.start + self.value self.count = 0 def calculate(self): if self.recycle_type: return self.current_milli_time() < self.end self.count += 1 return self.count <= self.value class MonteCarloTreeSearch: def __init__(self, recycle_type=0, value=100): """ init monte carlo rollout way :param recycle_type: 0 for rollout a fixed number, 1 for rollout a fixed range of time(ms) :param value: count value or time value(ms) """ self.recycle_type = recycle_type self.value = value def find_next_move(self, matrix): tree = Tree() tree.node.state.board = BoardForTrain(matrix) recycle_solver = RecycleSolver(self.recycle_type, self.value) while recycle_solver.calculate(): # print('index is : {}'.format(i)) promising_node = select_promissing_node(tree.node) expand_node(promising_node) node_to_explore = promising_node if len(promising_node.children) > 0: node_to_explore = promising_node.get_random_child_node() playout_result = simulate_random_result(node_to_explore) back_propogation(node_to_explore, playout_result) best_node = tree.node.get_child_with_max_score() return best_node.state.board.last_action def complete_play(self): board = BoardForTrain() index = 0 board.env_init() done = False while not done: action = self.find_next_move(board.matrix()) matrix, reward, done, value, score, can_move_dir = board.step(action) index += 1 print('****') print('action {}'.format(action)) print('index {}'.format(index)) print_matrix(matrix) print('score {}'.format(score)) print('done {}'.format(done)) print('can move dir {}'.format(can_move_dir)) print('****') return value if __name__ == "__main__": b = range(100, 2000, 300) current_path = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(current_path, 'statistic.txt') for time_interval in b: total = 0 p512 = 0 p1024 = 0 p2048 = 0 p4096 = 0 for j in range(100): mcts1 = MonteCarloTreeSearch(1, time_interval) value = mcts1.complete_play() total += 1 if value >= 512: p512 += 1 if value >= 1024: p1024 += 1 if value >= 2048: p2048 += 1 if value >= 4096: p4096 += 1 with open(file_path, 'a+') as f: f.write( '{} time {} p512 {} p1024 {} p2048 {} p4096 {} total {} \n'.format(str(datetime.now()), time_interval, p512, p1024, p2048, p4096, total)) <file_sep>/dp/policyImprovement.py import sys import numpy as np if "../" not in sys.path: sys.path.append("../") from boardWithoutTiles import BoardForTrain from dp import policyEvaluate def policy_improvement(transition_probability, policy_eval_fn=policyEvaluate.policy_eval, discount_factor=1.0): """ Policy Improvement Algorithm. Iteratively evaluates and improves a policy until an optimal policy is found. Args: transition_probability: transition_probability envrionment. policy_eval_fn: Policy Evaluation function that takes 3 arguments: policy, env, discount_factor. discount_factor: gamma discount factor. Returns: A tuple (policy, V). policy is the optimal policy V is the value function for the optimal policy. """ def one_step_lookahead(state, V): """ Helper function to calculate the value for all action in a given state. Args: state: The state to consider V: The value to use as an estimator Returns: A vector containing the expected value of each action. """ A = np.zeros(4) for a in range(4): for prob, next_state, reward, done in transition_probability[state][a]: A[a] += prob * (reward + discount_factor * V.get(next_state, 0)) return A # Start with a random policy policy = policyEvaluate.create_random_policy(transition_probability) iterate = 0 while True: iterate = iterate + 1 print('iterate {}'.format(iterate)) # Evaluate the current policy V = policy_eval_fn(policy, transition_probability, discount_factor) # Will be set to false if we make any changes to the policy policy_stable = True total_status = len(transition_probability) diff_status = 0 # For each state... for s in transition_probability.keys(): # The best action we would take under the currect policy chosen_a = np.argmax(policy[s]) # Find the best action by one-step lookahead # Ties are resolved arbitarily action_values = one_step_lookahead(s, V) best_a = np.argmax(action_values) # Greedily update the policy if chosen_a != best_a: policy_stable = False diff_status = diff_status + 1 policy[s] = np.eye(4)[best_a] print('diff status is {}/{}'.format(diff_status, total_status)) # If the policy is stable we've found an optimal policy. Return it if policy_stable: return policy, V if __name__ == '__main__': board_without_tiles = BoardForTrain() transition_probability = board_without_tiles.createTransitionProbability() policy, V = policy_improvement(transition_probability, discount_factor=0.99) print('policy is:') print(policy) print('value function is:') print(V) print(board_without_tiles.matrix()) while not board_without_tiles.has_done(): status = board_without_tiles.transferMatrixToTuple(board_without_tiles.matrix()) action = np.argmax(policy[status]) board_without_tiles.move(action) print('---move action {} ---'.format(action)) print(board_without_tiles.matrix()) score_map = {} for i in range(1000): board_without_tiles = BoardForTrain() while not board_without_tiles.has_done(): status = board_without_tiles.transferMatrixToTuple(board_without_tiles.matrix()) action = np.argmax(policy[status]) board_without_tiles.move(action) print('---move action {} ---'.format(action)) print(board_without_tiles.matrix()) score = board_without_tiles.transferMatrixToTuple(board_without_tiles.matrix()) score = tuple(sorted(list(score), reverse=True)) if score in score_map: score_map[score] = score_map[score] + 1 else: score_map[score] = 1 print(score_map) <file_sep>/my_redis/my_redis.py import redis import numpy as np host = '127.0.0.1' port = 6379 password = <PASSWORD> class MyRedis: def __init__(self, scope): self.my_redis = redis.StrictRedis(host=host, port=port, db=0, password=<PASSWORD>) self.scope = scope self.store_batch = 100000 def store_td(self, saved_obj): my_dicts = saved_obj['q'] step = saved_obj['step'] self.my_redis.set(self.scope + ':step', step) i = 0 tmp = dict() for item in my_dicts.items(): tmp[item[0]] = '_'.join(['{:0.3f}'.format(value) for value in item[1]]) i = i + 1 if i % self.store_batch == 0: self.my_redis.hmset(self.scope + ':q', tmp) tmp = dict() if len(tmp) > 0: self.my_redis.hmset(self.scope + ':q', tmp) def restore_td(self): has_step = self.my_redis.exists(self.scope + ':step') has_q_dicts = self.my_redis.exists(self.scope + ':q') if not has_step or not has_q_dicts: return None restore_dicts = dict() restore_dicts['step'] = int(self.my_redis.get(self.scope + ':step').decode('utf-8')) q_dicts = self.my_redis.hgetall(self.scope + ':q') temp_dicts = dict() for pair in q_dicts.items(): temp_dicts[pair[0].decode('utf-8')] = np.array([float(item) for item in pair[1].decode('utf-8').split('_')]) restore_dicts['q'] = temp_dicts return restore_dicts def hlen_q(self): name = self.scope + ':q' value = self.my_redis.hlen(name) return value def hget_q(self, key): name = self.scope + ':q' value = self.my_redis.hget(name, key) if value is None: return np.zeros(4) return np.array([float(item) for item in value.decode('utf-8').split('_')]) def hset_q(self, key, value): name = self.scope + ':q' self.my_redis.hset(name, key, '_'.join(['{:0.3f}'.format(value) for value in value])) def get_step(self): value = self.my_redis.get(self.scope + ':step').decode('utf-8') if value is None: return -1 return int(value) def set_step(self, value): self.my_redis.set(self.scope + ':step', value) <file_sep>/app.py from flask import Flask, json, request, Response from flask_cors import CORS from board import Board from mcts.MonteCarloTreeSearch import MonteCarloTreeSearch app = Flask(__name__) CORS(app) board = Board() monte_carlo_tree_search = MonteCarloTreeSearch(1, 1000) @app.route('/init') def init(): board.env_init() return transfer_response(board.front_call_obj()) @app.route('/step/<int:direct>') def step(direct): board.step(direct) return transfer_response(board.front_call_obj()) @app.route('/autostep') def autostep(): direct = monte_carlo_tree_search.find_next_move(board.matrix()) board.step(direct) return transfer_response(board.front_call_obj()) def transfer_response(obj, status_code=200): predict_results = json.dumps(obj, ensure_ascii=False) return Response( response=predict_results, mimetype="application/json; charset=UTF-8", status=status_code ) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) <file_sep>/boardWithoutTiles.py import random import numpy as np LEFT = 0 UP = 1 RIGHT = 2 DOWN = 3 class TileForTrain: def __init__(self, value=0, row=-1, column=-1): self.value = value self.row = row self.column = column class BoardForTrain: action_space = 4 fourProbability = 0.1 delta_x = [-1, 0, 1, 0] delta_y = [0, -1, 0, 1] def __init__(self, matrix=None, size=2): self.size = size if matrix is None: self.cells = [[self.add_tile() for _ in range(self.size)] for _ in range(self.size)] self.add_random_tile() else: self.cells = [[self.add_tile(matrix[i][j]) for j in range(self.size)] for i in range(self.size)] self.set_positions() self.has_changed = True self.max_value = 0 self.total_score = 0 self.lost = False self.can_move_dir = self.check_swipe_all_direction() self.last_action = -1 self.reward = 0 self.num_status = 0 def copy(self): board_copy = BoardForTrain() board_copy.cells = [[TileForTrain(self.cells[i][j].value, i, j) for j in range(self.size)] for i in range(self.size)] board_copy.has_changed = self.has_changed board_copy.max_value = self.max_value board_copy.total_score = self.total_score board_copy.lost = self.lost board_copy.can_move_dir = self.can_move_dir[:] return board_copy def rotate_left(self): rows = len(self.cells) columns = len(self.cells[0]) new_rows = columns new_columns = rows self.cells = [[self.cells[j][columns - i - 1] for j in range(new_columns)] for i in range(new_rows)] def add_tile(self, value=0): res = TileForTrain(value) return res def move_left(self): has_changed = False for row in range(self.size): current_row = [tile for tile in self.cells[row] if tile.value != 0] result_row = [None for _ in range(self.size)] for target in range(self.size): target_tile = current_row.pop(0) if len(current_row) > 0 else self.add_tile() if len(current_row) > 0 and current_row[0].value == target_tile.value: target_tile = self.add_tile(target_tile.value) tile2 = current_row.pop(0) target_tile.value += tile2.value result_row[target] = target_tile has_changed |= (target_tile.value != self.cells[row][target].value) self.cells[row] = result_row return has_changed def set_positions(self): for i in range(self.size): for j in range(self.size): tile = self.cells[i][j] tile.row = i tile.column = j def add_random_tile(self): empty_cells = [{'row': i, 'column': j} for i in range(self.size) for j in range(self.size) if self.cells[i][j].value == 0] _index = random.choice(range(len(empty_cells))) cell = empty_cells[_index] new_value = 4 if random.random() < BoardForTrain.fourProbability else 2 self.cells[cell['row']][cell['column']] = self.add_tile(new_value) self.reward = new_value def move(self, direction): self.reward = 0 # 0 -> left, 1 -> up, 2 -> right, 3 -> down for _ in range(direction): self.rotate_left() has_changed = self.move_left() for _ in range(direction, 4): self.rotate_left() if has_changed: self.add_random_tile() self.last_action = direction self.has_changed = has_changed self.set_positions() self.can_move_dir = self.check_swipe_all_direction() def can_swipe_left(self): """ compare adjacent cells two condition can move: 1. first cell is empty and second cell is not empty 2. two cells not empty and value is equal """ for row in range(self.size): for column in range(self.size - 1): first_value = self.cells[row][column].value second_value = self.cells[row][column + 1].value if first_value == 0 and second_value != 0: return True if first_value != 0 and second_value != 0 and first_value == second_value: return True return False def check_swipe_all_direction(self): can_move_dir = [False, False, False, False] # left, up, right, down for i in range(4): can_move_dir[i] = self.can_swipe_left() self.rotate_left() return can_move_dir def has_lost(self): return not any(self.can_move_dir) def has_done(self): return self.has_lost() def matrix(self): matrix_value = [[self.cells[row][column].value for column in range(self.size)] for row in range(self.size)] return np.array(matrix_value) def env_init(self): self.__init__(size=self.size) _matrix = self.matrix() return _matrix, self.can_move_dir def reset(self): return self.env_init() def step(self, _action): self.move(_action) _matrix = self.matrix() _done = False if self.has_done(): _done = True self.max_value = np.max(_matrix) self.total_score = np.sum(_matrix) / 500 return _matrix, self.reward, _done, self.max_value, self.total_score, self.can_move_dir def createTransitionProbability(self): P = {} shape_length = self.power(self.size, 2) shape_value = shape_length + 2 shape = [] for i in range(shape_length): shape.append(shape_value) nS = np.prod(shape) grid = np.arange(nS).reshape(shape) it = np.nditer(grid, flags=['multi_index']) while not it.finished: multi_index = it.multi_index P[multi_index] = {a: [] for a in range(4)} matrix_value = self.transferTupleToMatrix(multi_index) for direction in [LEFT, UP, RIGHT, DOWN]: board_for_train = BoardForTrain(matrix_value) board_for_train.reward = 0 for _ in range(direction): board_for_train.rotate_left() has_changed = board_for_train.move_left() for _ in range(direction, 4): board_for_train.rotate_left() moved_matrix = board_for_train.matrix() if has_changed: empty_cells = [{'row': i, 'column': j} for i in range(self.size) for j in range(self.size) if board_for_train.cells[i][j].value == 0] for _index in range(len(empty_cells)): for new_value, probability in [(4, 0.1), (2, 0.9)]: board_for_train = BoardForTrain(moved_matrix) cell = empty_cells[_index] board_for_train.cells[cell['row']][cell['column']] = board_for_train.add_tile(new_value) board_for_train.reward = new_value board_for_train.set_positions() board_for_train.can_move_dir = board_for_train.check_swipe_all_direction() P[multi_index][direction].append( (probability / len(empty_cells), self.transferMatrixToTuple(board_for_train.matrix()), board_for_train.reward, board_for_train.has_done())) else: board_for_train.set_positions() board_for_train.can_move_dir = board_for_train.check_swipe_all_direction() P[multi_index][direction].append( (0.0, self.transferMatrixToTuple(moved_matrix), board_for_train.reward, board_for_train.has_done())) it.iternext() return P def power(self, a, b): result = 1 for i in range(b): result = result * a return result def log(self, sub, value): if value == 0: return 0 result = 0 cal_value = 1 while cal_value < value: result = result + 1 cal_value = cal_value * sub if cal_value != value: return -1 return result def transferTupleToMatrix(self, tuple_value): tuple_value = [int(item) for item in tuple_value.split('_')] if len(tuple_value) != self.power(self.size, 2): raise ValueError("tuple not match matrix") matrix_value = np.zeros(shape=[self.size, self.size]) for i in range(self.size): for j in range(self.size): tuple_item = tuple_value[self.size * i + j] if tuple_item != 0: matrix_value[i][j] = self.power(2, tuple_item) return matrix_value def transferMatrixToTuple(self, matrix_value): tuple_arr = np.zeros(shape=matrix_value.size) for i in range(self.size): for j in range(self.size): tuple_arr[self.size * i + j] = self.log(2, matrix_value[i][j]) return '_'.join(map(str, map(int, tuple_arr))) if __name__ == "__main__": board = BoardForTrain() print(board.matrix()) board.move(1) print(board.matrix()) board.move(2) print(board.matrix()) new_board = BoardForTrain(board.matrix()) print(new_board.matrix()) trainsition_probability = new_board.createTransitionProbability() print(trainsition_probability) <file_sep>/td/Readme.md The way to run td algorithm is: ``` cd td nohup python -u q_learning.py --size 2 --outputInterval 100 > nohup.out 2> nohup.err & ``` or run with docker: ``` nohup sudo docker run --rm --network=host -v ~/Developer/Python/vue-2048-backend:/tmp -v ~/tensorboard:/tensorboard -w /tmp/td my-tensorflow python -u q_learning.py --size 3 --outputInterval 20000 --summaries_dir /tensorboard > q_learning.out 2>&1 & ```<file_sep>/tensorBoard/tensorBoardPlot.py import tensorflow as tf import numpy as np import os class TensorBoardPlot: def __init__(self, scope="estimator", summaries_dir=None): self.scope = scope if summaries_dir is None: summaries_dir = os.path.dirname(os.path.abspath(__file__)) summary_dir = os.path.join(summaries_dir, 'summaries_{}'.format(scope)) if not os.path.exists(summary_dir): os.makedirs(summary_dir) self.summary_writer = tf.summary.FileWriter(summary_dir) def add_value(self, key, value, step): # Add summaries to tensorboard episode_summary = tf.Summary() episode_summary.value.add(simple_value=value, node_name=key, tag=key) self.summary_writer.add_summary(episode_summary, step) self.summary_writer.flush() <file_sep>/mcts/State.py import random class State: def __init__(self, board=None): self.board = board self.visit_count = 0 self.win_score = 0 def increment_visit(self): self.visit_count += 1 def add_score(self, score): self.win_score += score def play(self, action): return self.board.step(action) def random_play(self): can_move_dir = self.board.can_move_dir legal_dir = [] for i in range(len(can_move_dir)): if can_move_dir[i]: legal_dir.append(i) random_action = random.choice(legal_dir) return self.board.step(random_action) <file_sep>/Dockerfile FROM tensorflow/tensorflow:1.8.0-py3 COPY . /2048 WORKDIR /2048 RUN apt-get update && apt-get install -y --no-install-recommends \ vim RUN pip3 --no-cache-dir install \ flask \ flask-cors # TensorBoard EXPOSE 6006 EXPOSE 8888 CMD ["/bin/bash"]<file_sep>/mcts/Tree.py import math import random import sys from mcts.State import State def utc_value(total_visit, node_win_score, node_visit): if node_visit == 0: return sys.maxsize return (node_win_score / node_visit) + 1.41 * math.sqrt(math.log(total_visit) / node_visit) class Node: def __init__(self, state=None): if state is None: state = State() self.state = state self.parent = None self.children = [] def find_best_node_with_utc(self): parent_visit = self.state.visit_count return max(self.children, key=lambda item: utc_value(parent_visit, item.state.win_score, item.state.visit_count)) def get_random_child_node(self): child_node_size = len(self.children) if child_node_size == 0: return None index = random.choice(range(child_node_size)) return self.children[index] def get_child_with_max_score(self): for i in range(len(self.children)): child = self.children[i] print( 'direction {} visitcount {} winscore {}'.format(child.state.board.last_action, child.state.visit_count, child.state.win_score)) return max(self.children, key=lambda item: item.state.visit_count) class Tree: def __init__(self): self.node = Node() <file_sep>/dp/valueIteration.py import sys import numpy as np if "../" not in sys.path: sys.path.append("../") from boardWithoutTiles import BoardForTrain from dp import policyEvaluate def value_iteration(transition_probability, theta=0.0001, discount_factor=1.0): """ Value Iteration Algorithm. Args: transition_probability: transition_probability envrionment. theta: We stop evaluation once our value function change is less than theta for all states. discount_factor: Gamma discount factor. Returns: A tuple (policy, V) of the optimal policy and the optimal value function. """ def one_step_lookahead(state, V): """ Helper function to calculate the value for all action in a given state. Args: state: The state to consider V: The value to use as an estimator Returns: A vector containing the expected value of each action. """ A = np.zeros(4) for a in range(4): for prob, next_state, reward, done in transition_probability[state][a]: A[a] += prob * (reward + discount_factor * V.get(next_state, 0)) return A V = {} for status in transition_probability.keys(): V[status] = 0 index = 0 while True: index = index + 1 print('index is {}'.format(index)) # Stopping condition delta = 0 # Update each state... for s in transition_probability.keys(): # Do a one-step lookahead to find the best action A = one_step_lookahead(s, V) best_action_value = np.max(A) # Calculate delta across all states seen so far delta = max(delta, np.abs(best_action_value - V[s])) # Update the value function. Ref: Sutton book eq. 4.10. V[s] = best_action_value # Check if we can stop if delta < theta: break # Start with a random policy policy = policyEvaluate.create_random_policy(transition_probability) for s in transition_probability.keys(): # One step lookahead to find the best action for this state A = one_step_lookahead(s, V) best_action = np.argmax(A) # Always take the best action policy[s][best_action] = 1.0 return policy, V if __name__ == '__main__': board_without_tiles = BoardForTrain() transition_probability = board_without_tiles.createTransitionProbability() policy, V = value_iteration(transition_probability, discount_factor=0.99) print('policy is:') print(policy) print('value function is:') print(V) print(board_without_tiles.matrix()) while not board_without_tiles.has_done(): status = board_without_tiles.transferMatrixToTuple(board_without_tiles.matrix()) action = np.argmax(policy[status]) board_without_tiles.move(action) print('---move action {} ---'.format(action)) print(board_without_tiles.matrix()) score_map = {} for i in range(1000): board_without_tiles = BoardForTrain() while not board_without_tiles.has_done(): status = board_without_tiles.transferMatrixToTuple(board_without_tiles.matrix()) action = np.argmax(policy[status]) board_without_tiles.move(action) print('---move action {} ---'.format(action)) print(board_without_tiles.matrix()) score = board_without_tiles.transferMatrixToTuple(board_without_tiles.matrix()) score = tuple(sorted(list(score), reverse=True)) if score in score_map: score_map[score] = score_map[score] + 1 else: score_map[score] = 1 print(score_map) <file_sep>/fa/function_approximation.py import sys import itertools import random import time import argparse import numpy as np import keras from collections import namedtuple from keras.layers import Dense, Activation, Flatten, Input, Lambda, BatchNormalization from keras.optimizers import Adam if "../" not in sys.path: sys.path.append("../") from boardWithoutTiles import BoardForTrain from tensorBoard.tensorBoardPlot import TensorBoardPlot from model_save.model_save import ModelSave class Estimator: """Q-Value Estimator neural network. """ def __init__(self, model_size, scope): self.model_size = model_size self.model_save = ModelSave(scope=scope) self.model = None if self.model_save.exist(): self.model = self.model_save.load() else: self.model = self._build_model() def _build_model(self): """ Builds the Tensorflow graph. """ def preprocess(x): return 1 / (1 + keras.backend.log(1 + x)) main_input = Input(shape=(self.model_size, self.model_size), name='main_input') x = Flatten(name='flatten')(main_input) x = Lambda(preprocess, name='preprocess')(x) x = Dense(256, name='first_layer')(x) # x = BatchNormalization()(x) x = Activation('relu', name='relu')(x) x = Dense(256, name='second_layer')(x) # x = BatchNormalization()(x) x = Activation('relu', name='relu_2')(x) value_function_output = Dense(4, name='value_function_output')(x) action_input = Input(shape=(4,), name='action_input') def get_action_value(tensors): value_function_output_tensor = tensors[0] action_input_tensor = tensors[1] product_tensor = value_function_output_tensor * action_input_tensor return keras.backend.sum(product_tensor, axis=-1, keepdims=True) q_function_output = Lambda(get_action_value, name='q_function_output')([value_function_output, action_input]) model = keras.Model(inputs=[main_input, action_input], outputs=q_function_output) model.summary() model.compile(loss='mean_squared_error', optimizer=Adam()) return model def save(self): self.model_save.save(self.model) def predict(self, s, train=0): """ Predicts action values. Args: s: State input of shape [batch_size, 4, 4] Returns: Tensor of shape [batch_size, NUM_VALID_ACTIONS] containing the estimated action values. """ main_input = self.model.get_layer('main_input').input value_function_output = self.model.get_layer('value_function_output').output get_value_function = keras.backend.function(inputs=[main_input, keras.backend.learning_phase()], outputs=[value_function_output]) return get_value_function([s, train])[0] def predict_single(self, s): """ Predicts with single state. :param s: State input of shape [4, 4] :return: Tensor of shape [NUM_VALID_ACTIONS] containing the estimated action values. """ return self.predict(np.expand_dims(s, axis=0))[0] def update(self, s, a, y): """ Updates the estimator towards the given targets. Args: s: State input of shape [batch_size, 4, 4] a: Chosen actions of shape [batch_size, 4] y: Targets of shape [batch_size] Returns: The calculated loss on the batch. """ loss = self.model.train_on_batch(x={'main_input': s, 'action_input': a}, y={'q_function_output': y}) return loss def update_single(self, s, a, y): """ Updates the estimator towards the given targets. :param s: State input of shape [4, 4] :param a: Chosen actions of shape (4,) :param y: Targets of shape () :return: The calculated loss on the batch """ s = np.expand_dims(s, axis=0) a = np.expand_dims(a, axis=0) y = np.expand_dims(y, axis=0) return self.update(s, a, y) def copy_weights(from_model, to_model): for layer in to_model.layers: from_layer = from_model.get_layer(layer.name) layer.set_weights(from_layer.get_weights()) def make_epsilon_greedy_policy(estimator, epsilon, nA): """ Creates an epsilon-greedy policy based on a given Q-function and epsilon. Args: estimator: a estimator that predict state -> action-values. epsilon: The probability to select a random action . float between 0 and 1. nA: Number of actions in the environment. Returns: A function that takes the observation as an argument and returns the probabilities for each action in the form of a numpy array of length nA. """ def policy_fn(observation, available_direction): dir_arr = np.array(available_direction).astype(int) dir_index = np.array([i for i in range(len(available_direction)) if available_direction[i]]) A = (np.ones(nA, dtype=float) * dir_arr) * epsilon / np.sum(dir_arr) value_function = np.array(estimator.predict_single(observation)) best_action = dir_index[np.argmax(value_function[dir_index])] A[best_action] += (1.0 - epsilon) return A return policy_fn def q_learning(env, args, replay_memory_size=500, replay_memory_init_size=50, batch_size=32, discount_factor=1.0, alpha=0.5, update_target_estimator_every=10, epsilon=0.1): """ Q-Learning algorithm: Off-policy TD control. Finds the optimal greedy policy while following an epsilon-greedy policy Args: env: environment. discount_factor: Gamma discount factor. alpha: TD learning rate. epsilon: Chance the sample a random action. Float betwen 0 and 1. """ q_learning_scope = args['scope'] + str(args['size']) target_scope = 'target_state' estimator = Estimator(model_size=args['size'], scope=q_learning_scope) target_estimator = Estimator(model_size=args['size'], scope=target_scope) total_step = 0 tensorBoardPlot = TensorBoardPlot(scope=q_learning_scope) # The policy we're following policy = make_epsilon_greedy_policy(estimator, epsilon, env.action_space) # The replay memory replay_memory = [] Transition = namedtuple("Transition", ["state", "action", "reward", "next_state", "done"]) # Populate the replay memory with initial experience print("Populating replay memory...") state, can_move_dir = env.reset() for i in range(replay_memory_init_size): action_probs = policy(state, can_move_dir) action = np.random.choice(np.arange(len(action_probs)), p=action_probs) next_state, reward, done, _, _, next_can_move_dir = env.step(action) replay_memory.append(Transition(state, action, reward, next_state, done)) if done: state, can_move_dir = env.reset() else: state = next_state can_move_dir = next_can_move_dir print("Init replay finished") for i_episode in itertools.count(start=total_step): # update target estimator parameters if i_episode % update_target_estimator_every == 0: copy_weights(estimator.model, target_estimator.model) # Reset the environment and pick the first action state, can_move_dir = env.reset() # One step in the environment for t in itertools.count(): # Take a step action_probs = policy(state, can_move_dir) action = np.random.choice(np.arange(len(action_probs)), p=action_probs) action_array = np.zeros(shape=(4,)) action_array[action] = 1 next_state, reward, done, _, _, next_can_move_dir = env.step(action) # If our replay memory is full, pop the first element if len(replay_memory) == replay_memory_size: replay_memory.pop(0) # Save transition to replay memory replay_memory.append(Transition(state, action, reward, next_state, done)) # TD Update # Sample a minibatch from the replay memory batch_state = [] batch_next_state = [] batch_action_array = [] batch_done = [] batch_reward = [] samples = random.sample(replay_memory, batch_size) for sample in samples: batch_state.append(sample.state) action_array = np.zeros(shape=(4,)) action_array[sample.action] = 1 batch_action_array.append(action_array) batch_next_state.append(sample.next_state) batch_done.append(sample.done) batch_reward.append(sample.reward) batch_state = np.array(batch_state) batch_next_state = np.array(batch_next_state) batch_action_array = np.array(batch_action_array) batch_done = np.array(batch_done) batch_reward = np.array(batch_reward) batch_next_value_function = target_estimator.predict(batch_next_state) batch_next_q_value = np.amax(batch_next_value_function, axis=1) batch_next_q_value = batch_next_q_value * (batch_done.astype(float)) batch_target = batch_reward + discount_factor * batch_next_q_value loss = estimator.update(batch_state, batch_action_array, batch_target) # next_q_value = 0.0 # if not done: # next_value_function = estimator.predict_single(next_state) # best_next_action = np.argmax(next_value_function) # next_q_value = next_value_function[best_next_action] # # td_target = reward + discount_factor * next_q_value # loss = estimator.update_single(state, action_array, td_target) state = next_state can_move_dir = next_can_move_dir if done: tensorBoardPlot.add_value('episode_len', t, i_episode) tensorBoardPlot.add_value('episode_max', np.max(next_state), i_episode) tensorBoardPlot.add_value('episode_loss', loss, i_episode) break # Print out which episode we're on, useful for debugging. if (i_episode + 1) % int(args['outputInterval']) == 0: print('----------') print("Episode {}.".format(i_episode + 1)) test_Q(tensorBoardPlot, estimator, i_episode) if (i_episode + 1) % (int(args['outputInterval']) * 10) == 0: print('start saving') current_time = time.time() estimator.save() print('save cost {} second'.format(time.time() - current_time)) def test_Q(tensorBoardPlot, estimator, step): board_without_tiles = BoardForTrain(size=int(args['size'])) print('args size is {}'.format(args['size'])) policy = make_epsilon_greedy_policy(estimator, 0, board_without_tiles.action_space) score_map = {} max_value_map = {} test_episodes = 100 for i in range(test_episodes): board_without_tiles = BoardForTrain(size=int(args['size'])) while not board_without_tiles.has_done(): state = board_without_tiles.matrix() action = np.argmax(policy(state, board_without_tiles.can_move_dir)) board_without_tiles.move(action) matrix = board_without_tiles.matrix() score = np.sum(matrix) max_value = np.max(matrix) if score in score_map: score_map[score] = score_map[score] + 1 else: score_map[score] = 1 if max_value in max_value_map: max_value_map[max_value] = max_value_map[max_value] + 1 else: max_value_map[max_value] = 1 print(score_map) print(max_value_map) weight_score = 0 for key in score_map: weight_score = weight_score + key * (score_map[key] / test_episodes) weight_max_value = 0 for key in max_value_map: weight_max_value = weight_max_value + key * (max_value_map[key] / test_episodes) tensorBoardPlot.add_value('weight_score', weight_score, step) tensorBoardPlot.add_value('weight_max_value', weight_max_value, step) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Description of your program') parser.add_argument('--size', help='size of matrix, 2x2,3x3,4x4', default=2) parser.add_argument('--outputInterval', help='interval to print test value', default=100) parser.add_argument('--scope', help='scope for saving in redis and tensorboard', default='2048_fa_primal') args = vars(parser.parse_args()) board_without_tiles = BoardForTrain(size=int(args['size'])) q_learning(board_without_tiles, args)
fccce138df3f4d602475b60594010940eeaec147
[ "Markdown", "Python", "Dockerfile" ]
16
Python
differentialmanifold/vue-2048-backend
ca539919c9f2246eb0193365a0697fe858da4e1d
b6c0a2d6e4b9732d38c3c5eeca421399e5d156a4
refs/heads/master
<file_sep>using System; using System.Collections.Generic; namespace CoreSystem.Basic { public class CacheComponent { } } <file_sep>This is tools directory.<file_sep>This is server directory.
fe9eeaed80c728e5b0d9f7d8d83618637bf6450f
[ "C#", "Text" ]
3
C#
clayzx/MobileGame
2ef0519fc397b023c23ccdd9f0e14afa7080e592
cc1567def565898f5d8dca9f7276ae0604469327
refs/heads/master
<repo_name>liphardt/aTRAM<file_sep>/lib/db.py """Handle database functions.""" import sqlite3 import sys import os from os.path import basename, join, exists ATRAM_VERSION = '2.0.alpha.5' DB_VERSION = '2.0' BATCH_SIZE = 1e6 # How many sequence records to insert at a time def connect(blast_db, check_version=False, clean=False): """Create DB connection.""" db_name = '{}.sqlite.db'.format(blast_db) if clean and exists(db_name): os.remove(db_name) if check_version and not exists(db_name): err = 'Could not find the database file "{}".'.format(db_name) sys.exit(err) db_conn = sqlite3.connect(db_name) db_conn.execute("PRAGMA page_size = {}".format(2**16)) db_conn.execute("PRAGMA busy_timeout = 10000") db_conn.execute("PRAGMA journal_mode = OFF") db_conn.execute("PRAGMA synchronous = OFF") if check_version: check_versions(db_conn) return db_conn def aux_db(db_conn, temp_dir, blast_db, query_name): """Create & attach an temporary database to the current DB connection.""" db_dir = join(temp_dir, 'db') os.makedirs(db_dir, exist_ok=True) db_name = '{}_{}_temp.sqlite.db'.format( basename(blast_db), basename(query_name)) db_name = join(db_dir, db_name) sql = """ATTACH DATABASE '{}' AS aux""".format(db_name) db_conn.execute(sql) def aux_detach(db_conn): """Detach the temporary database.""" db_conn.execute('DETACH DATABASE aux') # ########################### misc functions ################################# # DB_VERSION != version in DB. Don't force DB changes until required. So # this version will tend to lag ATRAM_VERSION. def check_versions(db_conn): """Make sure the database version matches what we built it with.""" version = get_version(db_conn) if version != DB_VERSION: err = ('The database was built with version {} but you are running ' 'version {}. You need to rebuild the atram database by ' 'running atram_preprocessor.py again.').format( version, DB_VERSION) sys.exit(err) # ########################## metadata table ################################## def create_metadata_table(db_conn): """ Create the metadata table. A single record used to tell if we are running atram.py against the schema version we built with atram_preprocessor.py. """ db_conn.execute('''DROP TABLE IF EXISTS metadata''') sql = 'CREATE TABLE metadata (label TEXT, value TEXT)' db_conn.execute(sql) with db_conn: sql = '''INSERT INTO metadata (label, value) VALUES (?, ?)''' db_conn.execute(sql, ('version', DB_VERSION)) db_conn.commit() def get_version(db_conn): """Get the current database version.""" sql = '''SELECT value FROM metadata WHERE label = ?''' try: result = db_conn.execute(sql, ('version', )) return result.fetchone()[0] except sqlite3.OperationalError: return '1.0' # ########################## sequences table ################################## def create_sequences_table(db_conn): """Create the sequence table.""" db_conn.execute('''DROP TABLE IF EXISTS sequences''') sql = 'CREATE TABLE sequences (seq_name TEXT, seq_end TEXT, seq TEXT)' db_conn.execute(sql) def create_sequences_index(db_conn): """ Create the sequences index after we build the table. This speeds up the program significantly. """ sql = 'CREATE INDEX sequences_index ON sequences (seq_name, seq_end)' db_conn.execute(sql) def insert_sequences_batch(db_conn, batch): """Insert a batch of sequence records into the database.""" if batch: sql = '''INSERT INTO sequences (seq_name, seq_end, seq) VALUES (?, ?, ?) ''' db_conn.executemany(sql, batch) db_conn.commit() def get_sequence_count(db_conn): """Get the number of sequences in the table.""" result = db_conn.execute('SELECT COUNT(*) FROM sequences') return result.fetchone()[0] def get_shard_cut(db_conn, offset): """Get the sequence name at the given offset.""" sql = 'SELECT seq_name FROM sequences ORDER BY seq_name LIMIT 1 OFFSET {}' result = db_conn.execute(sql.format(offset)) cut = result.fetchone()[0] return cut def get_sequences_in_shard(db_conn, start, end): """Get all sequences in a shard.""" sql = ''' SELECT seq_name, seq_end, seq FROM sequences WHERE seq_name >= ? AND seq_name < ? ''' return db_conn.execute(sql, (start, end)) # ######################## sra_blast_hits table ############################### def create_sra_blast_hits_table(db_conn): """ Reset the DB. Delete the tables and recreate them. """ db_conn.execute('''DROP TABLE IF EXISTS aux.sra_blast_hits''') sql = ''' CREATE TABLE aux.sra_blast_hits (iteration INTEGER, seq_name TEXT, seq_end TEXT, shard TEXT) ''' db_conn.execute(sql) sql = ''' CREATE INDEX aux.sra_blast_hits_index ON sra_blast_hits (iteration, seq_name, seq_end) ''' db_conn.execute(sql) def insert_blast_hit_batch(db_conn, batch): """Insert a batch of blast hit records into the database.""" if batch: sql = ''' INSERT INTO aux.sra_blast_hits (iteration, seq_end, seq_name, shard) VALUES (?, ?, ?, ?) ''' db_conn.executemany(sql, batch) db_conn.commit() def sra_blast_hits_count(db_conn, iteration): """Count the blast hist for select the iteration.""" sql = ''' SELECT COUNT(*) AS count FROM aux.sra_blast_hits WHERE iteration = ? ''' result = db_conn.execute(sql, (iteration, )) return result.fetchone()[0] def get_sra_blast_hits(db_conn, iteration): """Get all blast hits for the iteration.""" sql = ''' SELECT seq_name, seq_end, seq FROM sequences WHERE seq_name IN (SELECT DISTINCT seq_name FROM aux.sra_blast_hits WHERE iteration = ?) ORDER BY seq_name, seq_end ''' db_conn.row_factory = sqlite3.Row return db_conn.execute(sql, (iteration, )) def get_blast_hits_by_end_count(db_conn, iteration, end_count): """Get all blast hits for the iteration.""" sql = ''' SELECT seq_name, seq_end, seq FROM sequences WHERE seq_name IN (SELECT seq_name FROM sequences WHERE seq_name IN (SELECT DISTINCT seq_name FROM aux.sra_blast_hits WHERE iteration = ?) GROUP BY seq_name HAVING COUNT(*) = ?) ORDER BY seq_name, seq_end ''' db_conn.row_factory = sqlite3.Row return db_conn.execute(sql, (iteration, end_count)) # ####################### contig_blast_hits table ############################# def create_contig_blast_hits_table(db_conn): """Reset the database. Delete the tables and recreate them.""" db_conn.execute('''DROP TABLE IF EXISTS aux.contig_blast_hits''') sql = ''' CREATE TABLE aux.contig_blast_hits (iteration INTEGER, contig_id TEXT, description TEXT, bit_score NUMERIC, len INTEGER, query_from INTEGER, query_to INTEGER, query_strand TEXT, hit_from INTEGER, hit_to INTEGER, hit_strand TEXT) ''' db_conn.execute(sql) sql = ''' CREATE INDEX aux.contig_blast_hits_index ON contig_blast_hits (iteration, bit_score, len) ''' db_conn.execute(sql) def insert_contig_hit_batch(db_conn, batch): """Insert a batch of blast hit records into the database.""" if batch: sql = ''' INSERT INTO aux.contig_blast_hits (iteration, contig_id, description, bit_score, len, query_from, query_to, query_strand, hit_from, hit_to, hit_strand) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''' db_conn.executemany(sql, batch) db_conn.commit() def get_contig_blast_hits(db_conn, iteration): """Get all blast hits for the iteration.""" sql = ''' SELECT iteration, contig_id, description, bit_score, len, query_from, query_to, query_strand, hit_from, hit_to, hit_strand FROM aux.contig_blast_hits WHERE iteration = ? ''' db_conn.row_factory = sqlite3.Row return db_conn.execute(sql, (iteration, )) # ####################### assembled_contigs table ############################# def create_assembled_contigs_table(db_conn): """Reset the database. Delete the tables and recreate them.""" db_conn.execute('''DROP TABLE IF EXISTS aux.assembled_contigs''') sql = ''' CREATE TABLE aux.assembled_contigs (iteration INTEGER, contig_id TEXT, seq TEXT, description TEXT, bit_score NUMERIC, len INTEGER, query_from INTEGER, query_to INTEGER, query_strand TEXT, hit_from INTEGER, hit_to INTEGER, hit_strand TEXT) ''' db_conn.execute(sql) sql = ''' CREATE INDEX aux.assembled_contigs_index ON assembled_contigs (iteration, contig_id) ''' db_conn.execute(sql) def assembled_contigs_count(db_conn, iteration, bit_score, length): """Count the blast hist for the iteration.""" sql = ''' SELECT COUNT(*) AS count FROM aux.assembled_contigs WHERE iteration = ? AND bit_score >= ? AND len >= ? ''' result = db_conn.execute(sql, (iteration, bit_score, length)) return result.fetchone()[0] def iteration_overlap_count(db_conn, iteration, bit_score, length): """Count how many assembled contigs match what's in the last iteration.""" sql = ''' SELECT COUNT(*) AS overlap FROM aux.assembled_contigs AS curr_iter JOIN aux.assembled_contigs AS prev_iter ON ( curr_iter.contig_id = prev_iter.contig_id AND curr_iter.iteration = prev_iter.iteration + 1) WHERE curr_iter.iteration = ? AND curr_iter.seq = prev_iter.seq AND curr_iter.bit_score >= ? AND prev_iter.bit_score >= ? AND curr_iter.len >= ? ''' result = db_conn.execute( sql, (iteration, bit_score, bit_score, length)) return result.fetchone()[0] def insert_assembled_contigs_batch(db_conn, batch): """Insert a batch of blast hit records into the database.""" if batch: sql = ''' INSERT INTO aux.assembled_contigs (iteration, contig_id, seq, description, bit_score, len, query_from, query_to, query_strand, hit_from, hit_to, hit_strand) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''' db_conn.executemany(sql, batch) db_conn.commit() def get_assembled_contigs(db_conn, iteration, bit_score, length): """ Get all assembled contigs for the iteration. We will use them as the queries in the next atram iteration. """ sql = ''' SELECT contig_id, seq FROM aux.assembled_contigs WHERE iteration = ? AND bit_score >= ? AND len >= ? ''' return db_conn.execute(sql, (iteration, bit_score, length)) def get_all_assembled_contigs(db_conn, bit_score=0, length=0): """Get all assembled contigs.""" sql = ''' SELECT iteration, contig_id, seq, description, bit_score, len, query_from, query_to, query_strand, hit_from, hit_to, hit_strand FROM aux.assembled_contigs WHERE bit_score >= ? AND len >= ? ORDER BY bit_score DESC, iteration ''' db_conn.row_factory = sqlite3.Row return db_conn.execute(sql, (bit_score, length)) <file_sep>/requirements.txt appdirs==1.4.3 astroid==1.5.3 autopep8==1.3.2 flake8==3.4.1 hypothesis==3.24.1 isort==4.2.15 jedi==0.10.2 lazy-object-proxy==1.3.1 mccabe==0.6.1 numpy==1.13.1 packaging==16.8 pep257==0.7.0 psutil==5.3.0 py==1.4.34 pycodestyle==2.3.1 pydocstyle==2.0.0 pyflakes==1.6.0 pylama==7.4.1 pylint==1.7.2 pyparsing==2.2.0 pytest==3.2.2 six==1.10.0 snowballstemmer==1.2.1 wrapt==1.10.11 biopython==1.70
a0b24f3b24e5ab101dcbbcd31a290fb685cc2bf8
[ "Python", "Text" ]
2
Python
liphardt/aTRAM
2bcd3a4da982c47398f9ac989dde55c16d21022c
879d187ea6ab234b42b22b1be84c510b5ae6fd3b
refs/heads/main
<repo_name>GT0221/battleship<file_sep>/src/battleShip.js import GameBoard from './gameBoard.js'; import Ship from './ship.js'; import handleEvents from './eventListeners.js'; function battleShip() { const userGrid = document.querySelector('.grid-user'); const cpuGrid = document.querySelector('.grid-cpu'); const startButton = document.querySelector('#start'); const replayButton = document.querySelector('#replay'); let turnDisplay = document.querySelector('#turn'); const gameStatus = document.querySelector('#game-status'); const userDestroyer = Ship(2); const userSubmarine = Ship(3); const userCruiser = Ship(3); const userBattleship = Ship(4); const userCarrier = Ship(5); const cpuDestroyer = Ship(2); const cpuSubmarine = Ship(3); const cpuCruiser = Ship(3); const cpuBattleship = Ship(4); const cpuCarrier = Ship(5); let userCells = []; let cpuCells = []; let cpuPickedCells = []; let isGameOver = false; let currentPlayer = 'user'; const shipArray = [ { name: 'carrier', directions: [ [0, 1, 2, 3, 4], [0, 10, 20, 30, 40], ], }, { name: 'battleship', directions: [ [0, 1, 2, 3], [0, 10, 20, 30], ], }, { name: 'submarine', directions: [ [0, 1, 2], [0, 10, 20], ], }, { name: 'cruiser', directions: [ [0, 1, 2], [0, 10, 20], ], }, { name: 'destroyer', directions: [ [0, 1], [0, 10], ], }, ]; GameBoard().createGrid(userGrid, userCells); GameBoard().createGrid(cpuGrid, cpuCells); handleEvents(userCells); startButton.addEventListener('click', () => { startButton.classList.add('hide'); cpuGrid.classList.remove('hide'); gameStatus.innerText = 'Red = Hit \nBlue = Missed'; startGame(); }); function generateCpuShips(ship) { let randomDirection = Math.floor( Math.random() * ship.directions.length ); let current = ship.directions[randomDirection]; const direction = randomDirection === 0 ? 1 : 10; let randomStart = Math.abs( Math.floor( Math.random() * cpuCells.length - ship.directions[0].length * direction ) ); const isTaken = current.some((index) => cpuCells[randomStart + index].classList.contains('occupied') ); const isAtRightEdge = current.some( (index) => (randomStart + index) % 10 === 10 - 1 ); const isAtLeftEdge = current.some( (index) => (randomStart + index) % 10 === 0 ); if (!isTaken && !isAtRightEdge && !isAtLeftEdge) { current.forEach((index) => cpuCells[randomStart + index].classList.add( 'occupied', ship.name ) ); } else { generateCpuShips(ship); } } shipArray.forEach((ship) => generateCpuShips(ship)); function startGame() { if (isGameOver === true) { return; } else if (currentPlayer === 'user') { turnDisplay.innerText = 'Your turn'; cpuCells.forEach((cell) => cell.addEventListener('click', playerGo) ); } else { turnDisplay.innerText = 'Computer\'s turn'; setTimeout(computerGo, 1000); } } function playerGo(e) { const cpuShipsArr = [ cpuDestroyer, cpuSubmarine, cpuCruiser, cpuBattleship, cpuCarrier, ]; const clickedCellId = e.target.dataset.id; cpuCells[clickedCellId].removeEventListener('click', playerGo); GameBoard().receiveAttack(cpuCells, clickedCellId, cpuShipsArr); checkWin(); currentPlayer = 'computer'; startGame(); } function computerGo() { let userShipsArr = [ userDestroyer, userSubmarine, userCruiser, userBattleship, userCarrier, ]; let randomCell = Math.floor(Math.random() * userCells.length); if (cpuPickedCells.includes(randomCell)) { computerGo(); } else { GameBoard().receiveAttack(userCells, randomCell, userShipsArr); cpuPickedCells.push(randomCell); } turnDisplay.innerText = 'Your turn'; } function checkWin() { if ( userDestroyer.isSunk() && userSubmarine.isSunk() && userCruiser.isSunk() && userBattleship.isSunk() && userCarrier.isSunk() ) { gameStatus.innerText = 'You lost!'; gameOver(); } else if ( cpuDestroyer.isSunk() && cpuSubmarine.isSunk() && cpuCruiser.isSunk() && cpuBattleship.isSunk() && cpuCarrier.isSunk() ) { gameStatus.innerText = 'You win!'; gameOver(); } } function gameOver() { isGameOver = true; turnDisplay.classList.add('hide'); cpuCells.forEach((cell) => cell.removeEventListener('click', playerGo)); replayButton.classList.remove('hide'); } } export default battleShip;<file_sep>/src/ship.js function Ship(length) { let hitArray = []; const shipLength = length; const hit = (position) => { if (position == undefined) { return hitArray; } hitArray.push(position); return hitArray; }; const isSunk = () => { if (hitArray.length == shipLength) { return true; } return false; }; return { shipLength, hit, isSunk }; } export default Ship;<file_sep>/src/index.js import renderPage from './renderPage.js'; import battleShip from './battleShip.js'; document.addEventListener('DOMContentLoaded', () => { renderPage(); battleShip(); });<file_sep>/src/eventListeners.js import battleShip from './battleShip.js'; import renderPage from './renderPage.js'; function handleEvents(userCells) { const replayButton = document.querySelector('#replay'); const shipDisplay = document.querySelector('.ship-display'); const ships = document.querySelectorAll('.ship'); const buttonDiv = document.querySelector('.buttons'); let shipNameAndIndex; let draggedShip; let draggedShipLength; // move around user ship replayButton.addEventListener('click', resetGame); ships.forEach((ship) => ship.addEventListener('dragstart', dragStart)); ships.forEach((ship) => ship.addEventListener('click', rotateShip)); ships.forEach((ship) => ship.addEventListener('mousedown', (e) => { shipNameAndIndex = e.target.id; }) ); userCells.forEach((cell) => cell.addEventListener('dragstart', dragStart)); userCells.forEach((cell) => cell.addEventListener('dragover', dragOver)); userCells.forEach((cell) => cell.addEventListener('dragenter', dragEnter)); userCells.forEach((cell) => cell.addEventListener('drop', dragDrop)); function rotateShip(e) { const currentContainer = e.target.parentNode.classList[1]; document .querySelector(`.${currentContainer}`) .classList.toggle(`${currentContainer}-vertical`); } function dragStart(e) { draggedShip = e.target; draggedShipLength = draggedShip.children.length; } function dragOver(e) { e.preventDefault(); } function dragEnter(e) { e.preventDefault(); } function dragDrop() { let shipNameLastId = draggedShip.children[draggedShipLength - 1].id; let shipClass = shipNameLastId.slice(0, -2); let lastShipIndex = parseInt(shipNameLastId.substr(-1)); let shipLastId = lastShipIndex + parseInt(this.dataset.id); let selectedShipIndex = parseInt(shipNameAndIndex.substr(-1)); shipLastId = shipLastId - selectedShipIndex; const notAllowedHorizontal = [ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 1, 11, 21, 31, 41, 51, 61, 71, 81, 91, 2, 12, 22, 32, 42, 52, 62, 72, 82, 92, 3, 13, 23, 33, 43, 53, 63, 73, 83, 93, ]; const notAllowedVertical = [ 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, ]; let newNotAllowedHorizontal = notAllowedHorizontal.splice( 0, 10 * lastShipIndex ); let newnotAllowedVertical = notAllowedVertical.splice( 0, 10 * lastShipIndex ); let toPopulate = []; for (let i = 0; i < draggedShipLength; i++) { if ( !draggedShip.classList.contains( `${shipClass}-container-vertical` ) ) { toPopulate.push( userCells[parseInt(this.dataset.id) - selectedShipIndex + i] ); } else if ( draggedShip.classList.contains( `${shipClass}-container-vertical` ) ) { toPopulate.push( userCells[ parseInt(this.dataset.id) - selectedShipIndex + i * 10 + 1 ] ); } } if ( !draggedShip.classList.contains( `${shipClass}-container-vertical` ) && !newNotAllowedHorizontal.includes(shipLastId) ) { if ( !toPopulate.some((cell) => cell.classList.contains('occupied')) ) { for (let i = 0; i < draggedShipLength; i++) { userCells[ parseInt(this.dataset.id) - selectedShipIndex + i ].classList.add('occupied', shipClass); } shipDisplay.removeChild(draggedShip); } } else if ( draggedShip.classList.contains(`${shipClass}-container-vertical`) && !newnotAllowedVertical.includes(shipLastId) ) { if ( !toPopulate.some((cell) => cell.classList.contains('occupied')) ) { for (let i = 0; i < draggedShipLength; i++) { userCells[ parseInt(this.dataset.id) - selectedShipIndex + i * 10 + 1 ].classList.add('occupied', shipClass); } shipDisplay.removeChild(draggedShip); } } else { return; } hideRevealElements(); } function hideRevealElements() { if (shipDisplay.children.length <= 1) { shipDisplay.classList.add('hide'); buttonDiv.classList.remove('hide'); } } function resetGame() { while (document.body.firstChild) { document.body.removeChild(document.body.firstChild); } renderPage(); battleShip(); } } export default handleEvents;<file_sep>/src/gameBoard.js function GameBoard() { function createGrid(grid, cells) { for (let i = 0; i < 10 * 10; i++) { const cell = document.createElement('div'); cell.classList.add('cell'); cell.dataset.id = i; grid.appendChild(cell); cells.push(cell); } } function receiveAttack(cells, cellNumber, ship) { let attackStatus; if ( !cells[cellNumber].classList.contains('hit') && !cells[cellNumber].classList.contains('miss') ) { if (cells[cellNumber].classList.contains('destroyer')) { cells[cellNumber].classList.add('hit'); ship[0].hit(cellNumber); attackStatus = 'Succesful hit on destroyer!'; } else if (cells[cellNumber].classList.contains('submarine')) { cells[cellNumber].classList.add('hit'); ship[1].hit(cellNumber); attackStatus = 'Succesful hit on submarine!'; } else if (cells[cellNumber].classList.contains('cruiser')) { cells[cellNumber].classList.add('hit'); ship[2].hit(cellNumber); attackStatus = 'Succesful hit on cruiser!'; } else if (cells[cellNumber].classList.contains('battleship')) { cells[cellNumber].classList.add('hit'); ship[3].hit(cellNumber); attackStatus = 'Succesful hit on battleship!'; } else if (cells[cellNumber].classList.contains('carrier')) { cells[cellNumber].classList.add('hit'); ship[4].hit(cellNumber); attackStatus = 'Succesful hit on carrier!'; } else if (!cells[cellNumber].classList.contains('occupied')) { cells[cellNumber].classList.add('miss'); attackStatus = 'Missed!'; } } return attackStatus; } return { createGrid, receiveAttack, }; } export default GameBoard;<file_sep>/tests/gameBoard.test.js import { test } from '@jest/globals'; import GameBoard from '../src/gameBoard'; import Ship from '../src/ship'; /* eslint-disable */ test('Check GameBoard Properties', () => { expect((GameBoard().hasOwnProperty('createGrid')) && (GameBoard().hasOwnProperty('receiveAttack'))).toBe(true); }); test('Total cells in grid and cells array', () => { const grid = document.createElement('div'); const cellsArray = []; GameBoard().createGrid(grid, cellsArray); expect((grid.children.length) && (cellsArray.length)).toBe(100); }) test('Missed shot', () => { const grid = document.createElement('div'); const cellsArray = []; GameBoard().createGrid(grid, cellsArray); expect(GameBoard().receiveAttack(cellsArray, 5, null)).toBe('Missed!'); }) test('Succescful hits', () => { const grid = document.createElement('div'); const cellsArray = []; const destroyer = Ship(2); const submarine = Ship(3); const cruiser = Ship(3); const battleship = Ship(4); const carrier = Ship(5); const shipsArray = [destroyer, submarine, cruiser, battleship, carrier] GameBoard().createGrid(grid, cellsArray); grid.children[11].classList.add('destroyer'); grid.children[12].classList.add('submarine'); grid.children[13].classList.add('cruiser'); grid.children[14].classList.add('battleship'); grid.children[15].classList.add('carrier'); expect(GameBoard().receiveAttack(cellsArray, 11, shipsArray)).toBe('Succesful hit on destroyer!'); expect(GameBoard().receiveAttack(cellsArray, 12, shipsArray)).toBe('Succesful hit on submarine!'); expect(GameBoard().receiveAttack(cellsArray, 13, shipsArray)).toBe('Succesful hit on cruiser!'); expect(GameBoard().receiveAttack(cellsArray, 14, shipsArray)).toBe('Succesful hit on battleship!'); expect(GameBoard().receiveAttack(cellsArray, 15, shipsArray)).toBe('Succesful hit on carrier!'); })<file_sep>/README.md # Battleship This project is part of [The Odin Project](https://www.theodinproject.com/) javascript curriculum. In this project I've build the classic board game Battleships. Leading up to the project I've learned about Javascript test (using jest), and how it can be of great use. Writing test for your code can save you time and ensures that your code is behaving the way you expect it to. Link to battleShip project assignment [here](https://www.theodinproject.com/paths/full-stack-javascript/courses/javascript/lessons/battleship) [Live preview](https://gt0221.github.io/battleship/)
0aec68c1b8193eef1ff89428243bb23ed5f7750b
[ "JavaScript", "Markdown" ]
7
JavaScript
GT0221/battleship
3dde7d295830787b2cf3f6466ab7669c98b4c355
4910e3e9161cf09539cd518153dd0f4426ce0f74
refs/heads/master
<file_sep>from django.shortcuts import render from testapp.models import employee from django.db.models.functions import Lower def display(request): e1=employee.objects.get_queryset1() #objects is not necessary we can write anything but then change in models.py dict={'e1':e1} return render(request,"Testapp/list.html",context=dict) <file_sep>from django.db import models class customManager(models.Manager): def get_queryset1(self): return super().get_queryset().order_by('esal') def get_emp_range(self,range1,range2): return super().get_queryset().filter(esal__range=(range1,range2)).order_by('esal') def get_emp_sorted(self,param): return super().get_queryset().order_by(param) class employee(models.Model): ename=models.CharField(max_length=20) eno=models.IntegerField() esal=models.IntegerField() ecity=models.CharField(max_length=20) objects=customManager()
d49952b1b578ba132d33f592b3deb1619de523e4
[ "Python" ]
2
Python
Aniket-Sharma99/Summertraining
350f368a4c357aafbca9f2811983605a60e62c03
dfc3dc9985596a902904c801f2f289aae62f7c92
refs/heads/master
<repo_name>dvgis/dc-react<file_sep>/src/loader/HttpLoader.js /** * @Author: Caven * @Date: 2021-07-01 20:10:00 */ import axios from 'axios' const instance = axios.create({ timeout: 15000, }) class HttpLoader { load() { global.Http = instance Object.freeze(global.Http) initInterceptors(instance) } } function initInterceptors(instance) { instance.interceptors.request.use( (config) => { return config }, (error) => { return Promise.reject(error) } ) instance.interceptors.response.use( (response) => { return response }, (error) => { return Promise.reject(error) } ) } export default HttpLoader <file_sep>/README.md # dc-react > 该脚手架是将 React 与 DC-SDK 结合,方便用户可以快速搭建 3DGis 项目 ## 启动 ```shell yarn run serve ``` ## 打包 ```shell yarn run build ``` ## 配置说明 > 请看 webpack.config.js <file_sep>/src/loader/index.js /** * @Author: Caven * @Date: 2021-07-01 20:10:00 */ export { default as DcLoader } from './DcLoader' export { default as HttpLoader } from './HttpLoader' <file_sep>/src/views/index.js /** * @Author: Caven * @Date: 2021-07-01 20:10:00 */ import React, { Component } from 'react' import Viewer from '../components/Viewer' import ViewerApi from '../api/ViewerApi' class Home extends Component { _onViewerCreated(viewer) { let viewerApi = new ViewerApi(viewer) viewerApi.addBaseLayer() global.viewerApi = viewerApi } componentDidMount() {} render() { return ( <div className="home"> <Viewer onViewerCreated={this._onViewerCreated.bind(this)} /> </div> ) } } export default Home <file_sep>/webpack.config.js /** * @Author: Caven * @Date: 2021-07-01 20:10:00 */ 'use strict' const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const CopywebpackPlugin = require('copy-webpack-plugin') const TerserPlugin = require('terser-webpack-plugin') const dvgisDist = './node_modules/@dvgis' module.exports = (env, argv) => { const IS_PROD = (argv && argv.mode === 'production') || false return { mode: IS_PROD ? 'production' : 'development', entry: { app: path.resolve(__dirname, 'src/index.js'), }, devServer: { hot: true, }, output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), publicPath: IS_PROD ? '/' : '/', }, devtool: IS_PROD ? false : 'cheap-module-source-map', module: { rules: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', options: { presets: ['@babel/preset-react', '@babel/preset-env'], plugins: ['@babel/transform-runtime'], compact: false, ignore: ['checkTree'], }, }, { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', }, { loader: 'sass-loader', }, ], }, { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, { loader: 'css-loader', }, { loader: 'sass-loader', }, ], }, { test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/, loader: 'url-loader', options: { limit: 20000, }, }, ], }, optimization: IS_PROD ? { minimize: true, minimizer: [ new TerserPlugin({ extractComments: false, }), ], splitChunks: { chunks: 'async', minSize: 30000, maxSize: 0, minChunks: 1, automaticNameDelimiter: '~', cacheGroups: { vendors: { name: 'chunk-vendors', test: /[\\/]node_modules[\\/]/, priority: -10, chunks: 'initial', }, common: { name: 'chunk-common', minChunks: 2, priority: -20, chunks: 'initial', reuseExistingChunk: true, }, }, }, } : {}, plugins: [ new MiniCssExtractPlugin(), new CopywebpackPlugin({ patterns: [ { from: path.join(__dirname, 'public'), to: path.join(__dirname, 'dist'), globOptions: { ignore: ['**/*index.html'], }, }, { from: path.join(dvgisDist, 'dc-sdk/dist/resources'), to: 'libs/dc-sdk/resources', }, ], }), new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'public/index.html'), }), ], resolve: { extensions: ['.js', '.json', '.css'], alias: { '@': path.resolve(__dirname, 'src'), }, }, } } <file_sep>/src/loader/DcLoader.js /** * @Author: Caven * @Date: 2021-07-01 20:10:00 */ import DC from '@dvgis/dc-sdk/dist/dc.base.min' import DcCore from '@dvgis/dc-sdk/dist/dc.core.min' import '@dvgis/dc-sdk/dist/dc.core.min.css' class DcLoader { load() { global.DC = DC DC.use(DcCore) } } export default DcLoader
5a355e7c4e8a0b151b81e9f220637540f4c0900d
[ "JavaScript", "Markdown" ]
6
JavaScript
dvgis/dc-react
0df7f4d239a6f7972b2be5e9c9cfb4a867f2677d
63550c78c716c63037030f5d708aa5dd86f5debb
refs/heads/master
<file_sep>angular.module('video-player') .controller('appCtrl', function(youTube) { this.videos = window.exampleVideoData; this.currentVideo = window.exampleVideoData[0]; console.log(this.currentVideo); var changeCurrentVideo = (obj) => { this.currentVideo = obj; console.log(this); console.log(this.currentVideo.snippet.title); }; var updateVideos = (query) => { youTube.search(query, (items) => { console.log('Searching... ' + query); this.videos = items; this.currentVideo = items[0]; }); }; this.onClick = changeCurrentVideo; updateVideos('doggie'); this.updateVideos = updateVideos; }) .directive('app', function() { return { scope: { // onClick:'<' }, controllerAs: 'appCtrl', //need controller As bindToController: true, controller: 'appCtrl', templateUrl: 'src/templates/app.html' }; });
f6a51ca1a1ec24037bedb9f13fd1b31e9eec7555
[ "JavaScript" ]
1
JavaScript
isabellatea/ng-cast
f12558d4735f255444766b616d1756c514ec5dd9
6f83f3084061122bcf71d758232aca1c7439620f
refs/heads/main
<file_sep>import { UpdateTaskDto } from './../DTO/update-task.dto'; import { TaskStatus } from './../Entity/task.entity'; import { TaskStatusValidationPipe } from './../pipes/TaskStatusValidation.pipe'; import { CreateTaskDto } from './../DTO/create-task.dto'; import { TasksService } from './tasks.service'; import { Body, Controller, Delete, Get, Param, ParseIntPipe, Patch, Post, ValidationPipe, } from '@nestjs/common'; @Controller('tasks') export class TasksController { constructor(private tasksService: TasksService) {} @Get() getAllTasks() { return this.tasksService.getAllTasks(); } @Post() createNewTask(@Body(ValidationPipe) data: CreateTaskDto) { return this.tasksService.createTask(data); } @Patch(':id') updateTask( @Body(ValidationPipe) data: UpdateTaskDto, @Body('status', TaskStatusValidationPipe) status: TaskStatus, @Param('id', ParseIntPipe) id: number, ) { return this.tasksService.updateTask(id, status); } @Delete(':id') deleteTask(@Param('id', ParseIntPipe) id: number) { return this.tasksService.deleteTask(id); } } <file_sep>import { TaskStatus } from './../Entity/task.entity'; import { ArgumentMetadata, BadRequestException, PipeTransform, } from '@nestjs/common'; export class TaskStatusValidationPipe implements PipeTransform { readonly allowedStatus = [TaskStatus.OPEN, TaskStatus.DONE]; transform(value: any): any { value = value.toUpperCase(); if (!this.isStatusValid(value)) { throw new BadRequestException(`${value} is an invalid status.`); } return value; } private isStatusValid(status: any) { const index = this.allowedStatus.indexOf(status); return index !== -1; } } <file_sep>import { TaskStatus } from './../Entity/task.entity'; import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface, } from 'class-validator'; import * as moment from 'moment'; export function TaskStatusDueDateValidator( property: string, validationOptions?: ValidationOptions, ) { return (object: any, propertyName: string) => { registerDecorator({ target: object.constructor, propertyName: propertyName, options: validationOptions, constraints: [property], validator: TaskStatusDueDateContraint, }); }; } @ValidatorConstraint({ name: 'TaskStatusDueDateValidator' }) export class TaskStatusDueDateContraint implements ValidatorConstraintInterface { readonly doneStatus = TaskStatus.DONE; validate(value: any, args: ValidationArguments) { const [relatedPropertyName] = args.constraints; const relatedValue = (args.object as any)[relatedPropertyName]; value = value.toUpperCase(); const now = new Date(); const today = moment(now).format('YYYY-MM-DD'); if (value === this.doneStatus) if (moment(relatedValue).isBefore(today)) return false; return true; } } <file_sep>import { TaskStatusDueDateValidator } from 'src/decorators/taskStatusDueDateValidator.decorator'; export class UpdateTaskDto { @TaskStatusDueDateValidator('due_date', { message: 'Due date already passed', }) status: string; } <file_sep>import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn, } from 'typeorm'; @Entity('tasks') export class TasksEntity { @PrimaryGeneratedColumn() id: number; @Column() title: string; @Column() description: string; @Column() status: TaskStatus; @Column({ type: 'date' }) due_date: Date; @CreateDateColumn() created_at: Date; @UpdateDateColumn() updated_at: Date; } export enum TaskStatus { OPEN = 'OPEN', DONE = 'DONE', } <file_sep>import { CreateTaskDto } from './../DTO/create-task.dto'; import { TasksEntity, TaskStatus } from './../Entity/task.entity'; import { Injectable, InternalServerErrorException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; @Injectable() export class TasksService { constructor( @InjectRepository(TasksEntity) private repo: Repository<TasksEntity>, ) {} async getAllTasks(): Promise<any> { return await this.repo.find(); } async createTask(createTaskDto: CreateTaskDto) { const task: TasksEntity = new TasksEntity(); const { title, description, due_date } = createTaskDto; task.title = title; task.description = description; task.due_date = due_date; task.status = TaskStatus.OPEN; this.repo.create(task); try { return await this.repo.save(task); } catch (err) { throw new InternalServerErrorException( 'Something went wrong, task not created', ); } } async updateTask(id: number, status: TaskStatus) { try { await this.repo.update({ id }, { status }); return this.repo.findOne({ id }); } catch (err) { throw new InternalServerErrorException('Something went wrong'); } } async deleteTask(id: number) { try { return await this.repo.delete({ id }); } catch (err) { throw new InternalServerErrorException('Something went wrong'); } } } <file_sep>## Introduction A task management tool build using NestJS. ## API URL http://localhost:3000/api ## Tradeoff and consideration Feature like role management, authentication etc are not taken into consideration, as they would take more than the estimated time and also is not part of the requirement. Swagger is not currently integrated and so we will have to use PostMan tool to test the api. MySql database is used as the backend. ## Steps followed for development Following CLI commands are used for development and for spinning up the project quicker. npm i -g @nestjs/cli nest new tmbackend nest g module tasks nest g controller tasks --no-spec nest g service tasks --no-spec npm install @nestjs/typeorm typeorm mysql npm install class-validator --save npm install class-transformer --save ## Installation ```bash $ npm install ``` ## Running the app ```bash # development $ npm run start # watch mode $ npm run start:dev # production mode $ npm run start:prod ``` ## Validating ```bash # To run the linter $ npm run lint # To fix common linting errors $ npm run lint -- --fix ``` ## MySql Docker # To start my sql docker docker run --name task-mysql -e MYSQL_ROOT_PASSWORD=<PASSWORD> -e MYSQL_DATABASE=taskmanagement -d -p 3306:3306 mysql:latest # To start compose NestJS docker docker compose up ## Support Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support). ## Stay in touch - Author - [<NAME>](https://kamilmysliwiec.com) - Website - [https://nestjs.com](https://nestjs.com/) - Twitter - [@nestframework](https://twitter.com/nestframework) ## License Nest is [MIT licensed](LICENSE). <file_sep>import { IsNotEmpty, MaxLength } from 'class-validator'; export class CreateTaskDto { @IsNotEmpty() @MaxLength(15, { message: 'Max length is 15 Characters.' }) title: string; @IsNotEmpty() description: string; @IsNotEmpty() due_date: Date; }
d3ef8436525392476a3cf466147b3225c9e12999
[ "Markdown", "TypeScript" ]
8
TypeScript
shajihamza88/saptmtaskback
6d2230380358aa2dfc8ddca8894ed881a6f2b43b
14cdbe78e9cae71d71852818016c74aef8e93d97
refs/heads/master
<file_sep>const proc = require('child_process'); const request = require('request'); const constants = require('../constants'); const resUtils = require('./response-utils'); module.exports = { initRepos: function() { return new Promise((resolve,reject) => { console.log('Initializing and syncing all local repos'); let options = { url: `${constants.GIT_REPO_SERVER_URL}/get-all-repos`, method: 'GET', headers: { 'x-server-key': constants.GIT_REPO_SERVER_KEY } }; request(options, function(error, response, body) { if (error) { console.log(`Encountered error during request: ${options.url}`); return reject(error); } // Get the remote collections let remoteCollections = JSON.parse(body).data; console.log('Remote Collections:'); console.log(remoteCollections); // Get any local collections let localCollections = module.exports.executeCommand(null, `sh ./scripts/get_all_repos.sh ${constants.GIT_PATH}`, 'Retrieve all repos', '', result => result.split(',').map(r => r.trim()).filter(item => item !== '') ).data; console.log('Local Collections:'); console.log(localCollections); // For each remote collection, clone if it doesn't exist locally, or pull remoteCollections.forEach(remoteRepoPath => { remoteRepoPath.replace(constants.GIT_PATH, '') localCollections.forEach(localRepo => { let localRepoName = localRepo.replace(constants.GIT_PATH, ''); if (remoteRepoPath.endsWith(`${localRepoName}.git`)) { console.log(`Pulling latest for repo ${localRepoName}`); module.exports.executeCommand(null, `sh ./scripts/git_pull.sh ${localRepo}`, 'Git Pull', '', result => result = 'Successfully pulled data' ); } }); }); return resolve(true); }); }); }, executeCommand: function(res, command, actionText, repoName, resCallback) { let returnRes = function (res, code, response) { if (res){ return res.status(code).send(response); } else { return response; } }; let result; try { result = proc.execSync(command).toString().trim(); } catch (error) { let errorText; if (error.stdout !== undefined) { errorText = error.stdout.toString().trim(); } switch (errorText) { case 'NO_REPO_NAME': return returnRes(res, 400, resUtils.errorResponse( `${actionText} failed!`, 'Parameter [repo_name] not provided' )); case 'REPO_EXISTS': return returnRes(res, 400, resUtils.errorResponse( `${actionText} failed!`, `Repo with name [${repoName}] already exists.` )); case 'REPO_NOT_EXISTS': return returnRes(res, 400, resUtils.errorResponse( `${actionText} failed!`, `Repo with name [${repoName}] does not exist.` )); default: return returnRes(res, 500, resUtils.errorResponse( `${actionText} failed!`, `Command failed [${command}] : ${errorText || error}` )); } } if (resCallback !== undefined) { result = resCallback(result); } return returnRes(res, 200, resUtils.dataResponse(result)); } };<file_sep>#!/bin/bash if [ -z "$1" ]; then echo 'NO_REPO_PATH' exit 1 fi echo $(find $1 -type d -name '*.git' | sed 's/\/.git//g' | tr '\n' ',')<file_sep>const resUtils = require('../utils/response-utils'); const repoCommandUtils = require('../utils/repo-command-utils'); const constants = require('../constants'); const request = require('request'); module.exports = function(app) { const gitPath = constants.GIT_PATH; app.post('/collection/create', function(req,res) { let collectionName = req.query.collection_name; if (collectionName === undefined) { return res.status(400).send(resUtils.errorResponse( 'Failed to create a new collection', 'Parameter [collection_name] not provided' )); } let options = { url: `${constants.GIT_REPO_SERVER_URL}/create-repo?repo_name=${collectionName}`, method: 'POST', headers: { 'Authorization': req.headers.authorization } }; request(options, function(error, response, body) { if (error) { console.log(error); // return whatever error we got from the create command return res.status(500).send(resUtils.errorResponse(`Error occurred creating collection named ${collectionName}`, error)); } if (response.statusCode === 400) { return res.status(400).send(resUtils.errorResponse(`Error occurred creating collection named ${collectionName}`, JSON.parse(body))); } let cloneAddress; try { cloneAddress = JSON.parse(body).data; cloneAddress = `${constants.GIT_REPO_SERVER_HOST}${cloneAddress}`; } catch(e) { console.log(e); return res.status(500).send(resUtils.errorResponse(`Error occurred creating collection named ${collectionName}`, e)); } return repoCommandUtils.executeCommand(res, `sh ./scripts/clone_repo.sh ${gitPath}/${req.id}/${collectionName} ${cloneAddress}`, 'Create new collection', collectionName, (() => `Successfully created collection named [${collectionName}]`) ); }); }); };<file_sep>#!/bin/bash if [ -z "$1" ]; then echo 'NO_REPO_PATH' exit 1 fi if [ -z "$2" ]; then echo 'NO_ADD_ARGUMENT' exit 1 fi WORKING_DIR=$(pwd) cd $1 echo "Running git add at location: `pwd`" git add $2 cd $WORKING_DIR echo "Complete, back at location: `pwd`"<file_sep>const express = require('express'); const logger = require('morgan'); const constants = require('./constants'); const repoCommandUtils = require('./utils/repo-command-utils'); const app = express(); app.use(logger('tiny')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); repoCommandUtils.initRepos().then(() => { console.log('Repo init complete!'); require('./routes/google-auth-filter')(app); require('./routes/collection-routes')(app); const port = process.env.PORT || 3001; app.listen(port, () => { console.log('git-repo-api is up and running on port ', port); console.log('Git API Path: ', constants.GIT_PATH); }); }).catch(error => { console.log(error) }); <file_sep>#!/bin/bash if [ -z "$1" ]; then echo 'NO_REPO_PATH' exit 1 fi if [ -z "$2" ]; then echo 'NO_REPO_ADDRESS' exit 1 fi git clone $2 $1 > /dev/null # Create an empty tmp file touch $1/.tmp ./scripts/git_add.sh $1 "." ./scripts/git_commit.sh $1 "Initial commit" ./scripts/git_push.sh $1<file_sep>#!/bin/bash if [ -z "$1" ]; then echo 'NO_REPO_PATH' exit 1 fi if [ -z "$2" ]; then echo 'NO_COMMIT_MESSAGE' exit 1 fi WORKING_DIR=$(pwd) cd $1 echo "Running git commit at location: `pwd`" git commit -m "$2" cd $WORKING_DIR echo "Complete, back at location: `pwd`"<file_sep>#!/bin/bash if [ -z "$1" ]; then echo 'NO_REPO_PATH' exit 1 fi WORKING_DIR=$(pwd) cd $1 git pull > /dev/null cd $WORKING_DIR
5bf23060841e1d7cf1b911c5c3db3761f43c360d
[ "JavaScript", "Shell" ]
8
JavaScript
matty-v/git-repo-api
dc53aa15f4e5cb2c3ab11e317e439449c9893572
acf25b7faf2b5d62c92eb3ff73ff1ad0c84de6e8
refs/heads/master
<repo_name>jahanpd/abstract<file_sep>/updated/migrations/0007_auto_20170107_0133.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-07 01:33 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('updated', '0006_auto_20170107_0128'), ] operations = [ migrations.AlterField( model_name='abstractdata', name='dateTime', field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='date added'), ), migrations.AlterField( model_name='wordlist', name='dateTime', field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='date added'), ), ] <file_sep>/updated/admin.py from django.contrib import admin from .models import Journal, Keyword, journalPreference, keywordPreference, wordList, abstractData admin.site.register(Journal) admin.site.register(Keyword) admin.site.register(journalPreference) admin.site.register(keywordPreference) admin.site.register(wordList) admin.site.register(abstractData) <file_sep>/updated/management/commands/collect_data.py from django.core.management.base import BaseCommand, CommandError from updated.models import Journal, abstractData, wordList from updated.RSSextract import collectFeeds import json import datetime class Command(BaseCommand): help = "Collect data from all RSS feeds for learning" def handle(self, **options): journalsRSS = Journal.objects.all() titlesCompare = abstractData.objects.all() feedData, wordLibrary = collectFeeds(journalsRSS, titlesCompare) wordLibraryObject = wordList.objects.last() if wordLibraryObject: wordLibraryOld = wordLibraryObject.words wordLibraryOld = json.loads(wordLibraryOld) wordLibrary = wordLibrary + wordLibraryOld wordLibrary = json.dumps(list(set(wordLibrary))) wordLibraryObject.delete() else: wordLibrary = json.dumps(list(set(wordLibrary))) newWords = wordList.objects.create( words=wordLibrary, dateTime=datetime.date.today(), ) for feed in feedData: if len(feed[2]) > 5: new_entry = abstractData.objects.create( journal=feed[0], title=feed[1], concatAbstract=feed[2], labels='null', dateTime=datetime.date.today(), ) <file_sep>/updated/management/commands/add_labels.py from django.core.management.base import BaseCommand, CommandError from updated.models import abstractData import json class Command(BaseCommand): help = "Manually add labels to data" def handle(self, **options): abstractz = abstractData.objects.filter(labels__exact='null') count=0 for abstract in abstractz: yolo = len(abstractz) - count self.stdout.write(str(yolo)) self.stdout.write(str(abstract.journal)) self.stdout.write(str(abstract.title)) self.stdout.write(str(abstract.concatAbstract)) labelOne = raw_input('label one: ') labelTwo = raw_input('label 2: ') labelThree = raw_input('label thr3e: ') labelFour = raw_input('label f4ur: ') labelFive = raw_input('label fiv5: ') labelz = json.dumps([labelOne, labelTwo, labelThree, labelFour, labelFive]) abstract.labels = labelz abstract.save() count += 1 <file_sep>/updated/migrations/0005_auto_20170107_0109.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-07 01:09 from __future__ import unicode_literals import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('updated', '0004_auto_20170106_0149'), ] operations = [ migrations.CreateModel( name='wordList', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('words', models.TextField()), ('dateTime', models.DateTimeField(default=datetime.date(2017, 1, 7), verbose_name='date added')), ], ), migrations.RemoveField( model_name='abstractdata', name='fullAbstract', ), migrations.RemoveField( model_name='abstractdata', name='label', ), migrations.AddField( model_name='abstractdata', name='dateTime', field=models.DateTimeField(default=datetime.date(2017, 1, 7), verbose_name='date added'), ), migrations.AddField( model_name='abstractdata', name='labels', field=models.CharField(default='null', max_length=100, null=True), ), ] <file_sep>/updated/migrations/0003_auto_20170106_0127.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-06 01:27 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('updated', '0002_auto_20170106_0104'), ] operations = [ migrations.CreateModel( name='journalPreference', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.CreateModel( name='keywordPreference', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), migrations.AlterField( model_name='journal', name='journal_name', field=models.CharField(max_length=50, null=True), ), migrations.AlterField( model_name='journal', name='journal_rss', field=models.URLField(max_length=100, null=True), ), migrations.AlterField( model_name='keyword', name='keywords', field=models.CharField(max_length=28, null=True), ), migrations.AddField( model_name='keywordpreference', name='keyword_choices', field=models.ForeignKey(on_delete=models.SET('empty'), to='updated.Keyword'), ), migrations.AddField( model_name='keywordpreference', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='journalpreference', name='journal_choices', field=models.ForeignKey(on_delete=models.SET('empty'), to='updated.Journal'), ), migrations.AddField( model_name='journalpreference', name='user', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ] <file_sep>/updated/migrations/0006_auto_20170107_0128.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-07 01:28 from __future__ import unicode_literals import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('updated', '0005_auto_20170107_0109'), ] operations = [ migrations.AlterField( model_name='abstractdata', name='dateTime', field=models.DateTimeField(default=datetime.datetime(2017, 1, 7, 1, 28, 2, 390105, tzinfo=utc), verbose_name='date added'), ), migrations.AlterField( model_name='wordlist', name='dateTime', field=models.DateTimeField(default=datetime.datetime(2017, 1, 7, 1, 28, 2, 391020, tzinfo=utc), verbose_name='date added'), ), ] <file_sep>/updated/views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required import feedparser from .models import journalPreference, keywordPreference from django.template import loader from .RSSextract import feedparsing from django.shortcuts import redirect def direct(request): if request.user.is_authenticated: return redirect('/feed/') else: return redirect('/index/') def index(request): template = loader.get_template('updated/index.html') context = { } return HttpResponse(template.render(context, request)) @login_required def feed(request): current_user = request.user user_RSS = journalPreference.objects.filter(user__exact=current_user) keywords = keywordPreference.objects.filter(user__exact=current_user) keywordList = [] for key in keywords: keyAppend = key.keyword_choices.keyword keywordList.append(keyAppend.encode("utf-8")) together = feedparsing(user_RSS,keywordList) template = loader.get_template('updated/feed.html') context = { 'user_RSS':user_RSS, 'together':together, } return HttpResponse(template.render(context, request)) <file_sep>/updated/migrations/0004_auto_20170106_0149.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-06 01:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('updated', '0003_auto_20170106_0127'), ] operations = [ migrations.CreateModel( name='abstractData', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('journal', models.CharField(max_length=50)), ('title', models.CharField(max_length=100)), ('fullAbstract', models.TextField()), ('concatAbstract', models.TextField()), ('label', models.CharField(max_length=28)), ], ), migrations.RenameField( model_name='keyword', old_name='keywords', new_name='keyword', ), ] <file_sep>/requirements.txt dj-database-url==0.4.1 Django==1.10.5 ez-setup==0.9 feedparser==5.2.1 gunicorn==19.6.0 nltk==3.2.2 psycopg2==2.6.2 six==1.10.0 whitenoise==3.2 <file_sep>/updated/management/commands/delete_duplicates.py from django.core.management.base import BaseCommand, CommandError from updated.models import abstractData for row in abstractData.objects.all(): if abstractData.objects.filter(title_id=row.title_id).count() > 1: row.delete() <file_sep>/updated/models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.conf import settings from django.utils import timezone """ Goals: Journals (name, RSS); Keywords Preferences(Username, Journals, Keywords); Data (Journal, Title, Full Abstract, Concatenated Abstract lower case) """ class Journal(models.Model): journal_name = models.CharField(max_length = 50,null=True) journal_rss = models.URLField(max_length = 100,null=True) def __str__(self): return self.journal_name class Keyword(models.Model): keyword = models.CharField(max_length = 28,null=True) def __str__(self): return self.keyword class journalPreference(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) journal_choices = models.ForeignKey(Journal, on_delete=models.SET('empty')) class keywordPreference(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) keyword_choices = models.ForeignKey(Keyword, on_delete=models.SET('empty')) class abstractData(models.Model): journal = models.CharField(max_length=50) title = models.TextField(default='a basic default title') concatAbstract = models.TextField(default='null') labels = models.CharField(max_length=100,null=True,default='null') #JSON list of 5 keywords dateTime = models.DateTimeField('date added',auto_now_add=True) class wordList(models.Model): words = models.TextField() #JSON list of all unique words for ML dateTime = models.DateTimeField('date added',auto_now_add=True) <file_sep>/updated/migrations/0008_remove_abstractdata_title.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-07 01:42 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('updated', '0007_auto_20170107_0133'), ] operations = [ migrations.RemoveField( model_name='abstractdata', name='title', ), ] <file_sep>/updated/migrations/0009_abstractdata_title.py # -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-01-07 01:45 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('updated', '0008_remove_abstractdata_title'), ] operations = [ migrations.AddField( model_name='abstractdata', name='title', field=models.TextField(default='null'), ), ] <file_sep>/updated/RSSextract.py import feedparser import string import re import nltk def striphtml(data): p = re.compile(r'<.*?>') return p.sub(' ', data) def stripNums(inputString): return not any(char.isdigit() for char in inputString) def stripUni(inputString): return ''.join([i if ord(i) < 128 else ' ' for i in inputString]) def concatenateAbstract(abstract): abstract = abstract.lower() splitz = nltk.word_tokenize(abstract) return filter(lambda x: len(x) > 7, splitz) def feedparsing(user_RSS, keywords): titles = [] description = [] for RSS in user_RSS: feedparse = feedparser.parse(RSS.journal_choices.journal_rss) for fe in feedparse.entries: concatz = set(concatenateAbstract(fe.title) + concatenateAbstract(fe.description)) keywordz = set(keywords) if any(i in keywords for i in concatz): titles.append(fe.title) description.append(striphtml(fe.description)) return zip(titles, description) def collectFeeds(user_RSS, titlesCompare): journals = [] titles = [] concatAbstracts = [] wordBag = [] allTitles = [] if titlesCompare: for title in titlesCompare: allTitles.append((title.title).encode("utf-8")) for RSS in user_RSS: feedparse = feedparser.parse(RSS.journal_rss) for fe in feedparse.entries: loneTitle = (fe.title).encode("utf-8") loneTitle = loneTitle.decode('unicode_escape').encode('ascii','ignore') loneTitle = stripUni(loneTitle) if loneTitle not in allTitles: descriptionz = (fe.description).encode("utf-8") descriptionz = descriptionz.decode('unicode_escape').encode('ascii','ignore') descriptionz = stripUni(descriptionz) concatz = set(concatenateAbstract(loneTitle) + concatenateAbstract(striphtml(descriptionz))) wordBag = list(wordBag) + list(concatz) wordBag = filter(stripNums, wordBag) wordBag = set(wordBag) journals.append(RSS.journal_name) titles.append(loneTitle) concatAbstracts.append(list(concatz)) return zip(journals, titles, concatAbstracts), list(wordBag)
5f3a3813ed7beaa3ec778d8940294270ac09cc8e
[ "Python", "Text" ]
15
Python
jahanpd/abstract
38e47e6b56a74984928103cbecb63654ed197e81
90aee97a29a6f1c44d535602cee8d5d867067572
refs/heads/master
<repo_name>and29/trueChart-Menubar4Sense<file_sep>/resource/translations/de_de/translations.js export default { "label": { "addButton": "Button hinzufügen", "addDimension": "Dimension hinzufügen", "addItem": "Element hinzufügen", "addSingleSelect": "Single-Select hinzufügen", "addState": "Status hinzufügen", "addVariableValue": "Variablenwert hinzufügen", "alphabetic": "Alphabetisch", "ascending": "Aufsteigend", "auto": "Automatisch", "automatic": "Automatisch", "backgroundColor": "Hintergrund", "borderSeperatorColor": "Rahmen und Separator", "bottom": "Unten", "button": "Button", "buttonContainer": "Button-Container", "buttonNameInput": "Name (nur Eigenschaftsfenster)", "calcCondVar": "Berechnungsvariable anderer Objekte", "center": "Mitte", "colors": "Farben", "condition": "Bedingung", "conditionNameInput": "Bedingungsname (nur Eigenschaftsfenster)", "configSettings": "Einstellungen", "confirm": "Bestätigen", "confirmed": "Bestätigt", "copy": "Kopieren", "custom": "Individuell", "customHeight": "Individuelle Höhe in Pixel", "customSize": "Individuelle Größe", "customWidth": "Individuelle Breite in Pixel/%", "descending": "Absteigend", "dimension": "Dimension", "dimensionCalculation": "Dimensionsberechnung", "dimensions": "Dimensionen", "dimensionTitel": "Dimensionstitel", "display": "Display", "displayShow": "Anzeigen", "displayHide": "Verstecke", "displayOptional": "Optional", "displaySenseMenuBar": "Sense Menu Bar Anzeigen", "displaySenseSelectionBar": "Sense Selection Bar Anzeigen", "displaySenseTitleBar": "Sense Title Bar Anzeigen", "dropdownItems": "Dropdown-Elemente", "duplicate": "Duplizieren", "expression": "Formel", "fields": "Felder", "fill": "Voll", "gapBottom": "Unten", "gapBottomSize": "Unten in Pixel", "gapLeft": "Links", "gapLeftSize": "Links in Pixel", "gapRight": "Rechts", "gapRightSize": "Rechts in Pixel", "gaps": "Position", "gapTop": "Oben", "gapTopSize": "Oben in Pixel", "getConfig": "Konfiguration Anzeigen", "group": "Gruppe", "heightSetting": "Einstellung der Höhe", "horizontal": "Horizontal", "hoverActiveColor": "Hervorheben und Aktiv", "icon": "Icon", "information": "Info", "items": "Elemente", "label": "Label", "labelAlignementHorizontal": "Label: Horizontale Ausrichtung", "labelAlignementVertical": "Label: Vertikale Ausrichtung", "layout": "Layout", "left": "Links", "menuMain": "Hauptelement", "menuSub": "Unterelement", "multi": "Multi", "next": "Nächster", "noDimension": "Keine Dimension", "noIcon": "Kein Icon", "numeric": "Numerisch", "off": "Aus", "on": "An", "orientation": "Ausrichtung", "panelHeight": "Panel-Höhe in Pixel", "panelWidth": "Panel-Breite in Pixel", "paste": "Einfügen", "predefined": "Vordefiniert", "repair": "Reparieren", "repairBtn": "Menu Reparieren", "repeatUpdateBtn": "Letztes Update wiederholen", "reset": "Zurücksetzen", "resolved": "Gelöst", "right": "Rechts", "save": "Speichern", "selectDimension": "Standardwert", "selectionLabel": "Auswahl-Label", "selectionLabelAlignementHorizontal": "Auswahl-Label: Horizontale Ausrichtung", "selectionLabelAlignementVertical": "Auswahl-Label: Vertikale Ausrichtung", "senseSelect": "Sense-Select", "senseMenuBar": "Sense Menu Bar", "senseSelectionBar": "Sense Selection Bar", "senseTitleBar": "Sense Title Bar", "showCondition": "Anzeigebedingung", "single": "Single", "singleSelect": "Single-Select", "sort": "Sortieren", "sortByAscii": "Alphabetisch", "sortByExpression": "Formel", "sortByFrequence": "Häufigkeit", "sortByLoad": "Ladereihenfolge", "sortByNumeric": "Numerisch", "sortByState": "Selektionsstatus", "sortOrder": "Sortierreihenfolge", "sortSwitch": "Sortierreihenfolge", "state": "Status", "states": "Status", "stateSettings": "Status-Einstellungen", "text": "Text", "textColor": "Text", "textFamily": "Schriftart", "textFont": "Stil", "textHoverColor": "Text-Hover", "textLayout": "Text-Layout", "textSize": "Größe", "textWeight": "Stärke", "tooltip": "Tooltip", "top": "Oben", "type": "Typ", "userdefined": "Benutzerdefiniert", "variableDropdown": "Variable-Dropdown", "variableName": "Variablenname", "variableValue": "Variablenwert", "vertical": "Vertikal", "verticalAlignment": "Vertikale Ausrichtung", "widthSetting": "Breiteneinstellung" }, "tooltip": { "bottom": "Unten", "calcCondVar": "Wird nach initialen Selektionen auf '1' gesetzt", "center": "Mitte", "copy": "Kopiert das aktuelle Element in die Zwischenablage", "customHeight": "Individuelle Höhe der Extension", "customWidth": "Individuelle Breite der Extension", "displayShow": "Element immer Anzeigen", "displayHide": "Element niemals Anzeigen", "displayOptional": "Element optional Anzeigen", "duplicate": "Dupliziert das aktuelle Element und fügt es am Listenende hinzu", "fullWidth": "Volle Breite der Extension", "fullHeight": "Volle Höhe der Extension", "left": "Links", "paste": "Ersetzt das Element mit dem zuvor kopierten Element", "pixel": "Pixel", "percent": "Prozent", "repairBtnTp": "Überprüft das Menu und repariert mögliche Fehler", "repeatUpdateBtn": "Führt das letzte Update für die Extension noch einmal durch", "right": "Rechts", "top": "Oben" }, "text": { "all": "Alles", "of": "von", "updateToVersion": "Aktualisiere trueChart-Menubar auf die aktuelle Version" }, "templates": { "dialog_update_1_1_0": "<div class=\"hico\">\n" + " <div class=\"hico-container-element\">\n" + " <p>Mit der Version 1.1.0 unterstützt trueChart-Menubar nun Master- und dynamische Dimensionen ohne Einschränkung." + " Einige Dimensions-Formeln müssen daher überprüft werden.</p>\n" + " </div>\n" + " <h4 class=\"hico-container-element hico-text-error\">\n" + " Folgende Punkte sollten beachtet werden:\n" + " </h4>\n" + " <div class=\"hico-container-element hico-list-dialog-padding\">\n" + " <ul class=\"hico-text-error\">\n" + " <li class=\"hico-text-error\">Keine (<b> ' oder \" </b>) vor und nach Felder- und Dimensionsnamen</li>\n" + " <li class=\"hico-text-error\">Formeln sollten mit einem <b>=</b> beginnen</li>\n" + " <li class=\"hico-text-error\">Groß- und Kleinschreibung bei Dimensions-/Feldnamen</li>\n" + " </ul>\n" + " </div>\n" + "</div>" } };<file_sep>/src/js/Directives/index.js import './ChangeBackground'; import './Container'; import './Group'; import './Label'; import './RepairDialog'; import './Scroll'; import './SenseSelect'; import './SingleSelect'; import './VariableDropdown';
2c8c1f84bf12dba9cba3e495bab4ccf5e6765487
[ "JavaScript" ]
2
JavaScript
and29/trueChart-Menubar4Sense
741ff2b3709751f3a2cb642c197c225b9b29b0cc
437973efce7f16c7331339a20b289a88854c5573
refs/heads/master
<repo_name>GGjin/algorithm_python<file_sep>/easy/38.外观数列.py #!/usr/bin/env python # -*- coding::utf-8 -*- # Author :GG # 给定一个正整数 n(1 ≤ n ≤ 30),输出外观数列的第 n 项。 # # 注意:整数序列中的每一项将表示为一个字符串。 # # 「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。前五项如下: # # 1. 1 # 2. 11 # 3. 21 # 4. 1211 # 5. 111221 # # # 第一项是数字 1 # # 描述前一项,这个数是 1 即 “一个 1 ”,记作 11 # # 描述前一项,这个数是 11 即 “两个 1 ” ,记作 21 # # 描述前一项,这个数是 21 即 “一个 2 一个 1 ” ,记作 1211 # # 描述前一项,这个数是 1211 即 “一个 1 一个 2 两个 1 ” ,记作 111221 # # # # 示例 1: # # 输入: 1 # 输出: "1" # 解释:这是一个基本样例。 # # 示例 2: # # 输入: 4 # 输出: "1211" # 解释:当 n = 3 时,序列是 "21",其中我们有 "2" 和 "1" 两组,"2" 可以读作 "12",也就是出现频次 = 1 而 值 = 2;类似 # "1" 可以读作 "11"。所以答案是 "12" 和 "11" 组合在一起,也就是 "1211"。 # Related Topics 字符串 # 👍 497 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def countAndSay(self, n: int) -> str: prev_num = "1" for i in range(1, n): next_num, num, count = "", prev_num[0], 1 for j in range(1, len(prev_num)): if prev_num[j] == num: count += 1 else: next_num += str(count) + num num = prev_num[j] count = 1 next_num += str(count) + num prev_num = next_num return prev_num # leetcode submit region end(Prohibit modification and deletion) a = Solution() print(a.countAndSay(2)) print(a.countAndSay(3)) print(a.countAndSay(4)) <file_sep>/easy/66.加一.py # 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。 # # 最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。 # # 你可以假设除了整数 0 之外,这个整数不会以零开头。 # # 示例 1: # # 输入: [1,2,3] # 输出: [1,2,4] # 解释: 输入数组表示数字 123。 # # # 示例 2: # # 输入: [4,3,2,1] # 输出: [4,3,2,2] # 解释: 输入数组表示数字 4321。 # # Related Topics 数组 # 👍 516 👎 0 # leetcode submit region begin(Prohibit modification and deletion) from typing import List class Solution: def plusOne(self, digits: List[int]) -> List[int]: a = 0 for i in range(0, len(digits)): a += digits[i] if i != len(digits) - 1: a *= 10 print(f"---${a}") a += 1 return [int(x) for x in str(a)] class Solution1: def plusOne(self, digits: List[int]) -> List[int]: a = 0 for i in range(0, len(digits)): a += digits[i] if i != len(digits) - 1: a *= 10 print(f"---${a}") a += 1 return [int(x) for x in str(a)] # leetcode submit region end(Prohibit modification and deletion) a = [4, 3, 2, 9] b = Solution().plusOne(a) print(b) <file_sep>/easy/136.只出现一次的数字.py # 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。 # # 说明: # # 你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗? # # 示例 1: # # 输入: [2,2,1] # 输出: 1 # # # 示例 2: # # 输入: [4,1,2,1,2] # 输出: 4 # Related Topics 位运算 哈希表 # 👍 1584 👎 0 from typing import List from functools import reduce # 这个数字与0异或运算以后还是自己, 然后数字与自己运算以后就变成0, 想要 # 不占用额外的空间 就只能使用位运算了, 这个想法简直了, # a^0 =0 a^a = 0 a^b^a = a^a^b =0^b =b 简直了。 # public int singleNumber(int[] nums) { # int single = 0; # for (int num : nums) { # single ^= num; # } # return single; # } # leetcode submit region begin(Prohibit modification and deletion) class Solution: def singleNumber(self, nums: List[int]) -> int: return reduce(lambda x, y: x ^ y, nums) # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/53最大子序和.py #!/usr/bin/env python # -*- coding::utf-8 -*- # Author :GG # 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 # # 示例: # # 输入: [-2,1,-3,4,-1,2,1,-5,4], # 输出: 6 # 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 # # # 进阶: # # 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 # Related Topics 数组 分治算法 动态规划 # 👍 2176 👎 0 # leetcode submit region begin(Prohibit modification and deletion) from typing import List class Solution: def maxSubArray(self, nums: List[int]) -> int: sum = 0 ans = nums[0] for num in nums: if sum + num > num: sum += num else: sum = num ans = max(sum, ans) return ans # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/107.二叉树的层次遍历II.py # 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) # # 例如: # 给定二叉树 [3,9,20,null,null,15,7], # # 3 # / \ # 9 20 # / \ # 15 7 # # # 返回其自底向上的层次遍历为: # # [ # [15,7], # [9,20], # [3] # ] # # Related Topics 树 广度优先搜索 # 👍 364 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]: res = [] def dfs(root: TreeNode, depth: int): if not root: return res if len(res) < depth + 1: res.append([]) res[depth].append(root.val) dfs(root.left, depth + 1) dfs(root.right, depth + 1) dfs(root, 0) return res[::-1] # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/69.x的平方根.py # 实现 int sqrt(int x) 函数。 # # 计算并返回 x 的平方根,其中 x 是非负整数。 # # 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 # # 示例 1: # # 输入: 4 # 输出: 2 # # # 示例 2: # # 输入: 8 # 输出: 2 # 说明: 8 的平方根是 2.82842..., #   由于返回类型是整数,小数部分将被舍去。 # # Related Topics 数学 二分查找 # 👍 465 👎 0 import math # leetcode submit region begin(Prohibit modification and deletion) class Solution: def mySqrt(self, x: int) -> int: if x == 0: return 0 ans = int(math.exp(0.5 * math.log(x))) return ans + 1 if (ans + 1) ** 2 <= x else ans # 二分查找法 class Solution1: def mySqrt(self, x: int) -> int: l, r, ans = 0, x, -1 while l <= r: mid = (l + r) // 2 if mid ** 2 <= x: ans = mid l = mid + 1 else: r = mid - 1 return ans # leetcode submit region end(Prohibit modification and deletion) print(True) <file_sep>/easy/83.删除排序链表中的重复元素.py #!/usr/bin/env python # -*- coding::utf-8 -*- # Author :GG # 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。 # # 示例 1: # # 输入: 1->1->2 # 输出: 1->2 # # # 示例 2: # # 输入: 1->1->2->3->3 # 输出: 1->2->3 # Related Topics 链表 # 👍 368 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: current = head while current and current.next: if current.val == current.next.val: current.next = current.next.next else: current = current.next return head # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/121.买卖股票的最佳时机.py # 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 # # 如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。 # # 注意:你不能在买入股票前卖出股票。 # # # # 示例 1: # # 输入: [7,1,5,3,6,4] # 输出: 5 # 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 # 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。 # # # 示例 2: # # 输入: [7,6,4,3,1] # 输出: 0 # 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 # # Related Topics 数组 动态规划 # 👍 1299 👎 0 from typing import List # leetcode submit region begin(Prohibit modification and deletion) class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 sum, p = 0, prices[0] for i in prices[1::]: if i < p: p = i if i - p > sum: sum = i - p return sum # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/169.多数元素.py # 给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。 # # 你可以假设数组是非空的,并且给定的数组总是存在多数元素。 # # # # 示例 1: # # 输入: [3,2,3] # 输出: 3 # # 示例 2: # # 输入: [2,2,1,1,1,2,2] # 输出: 2 # # Related Topics 位运算 数组 分治算法 # 👍 799 👎 0 from typing import List """ class Solution { public int majorityElement(int[] nums) { //1.初始化 int mode = nums[0]; int votes = 0; //2.遍历 for(int num : nums){ if(votes == 0){ //票数是否为0 mode = num; } if(num == mode){ //判断当前元素是否为众数 votes ++; }else{ votes --; } } return mode; } } 投票算法 """ # leetcode submit region begin(Prohibit modification and deletion) class Solution: """ 获取nums数组中指定范围内 某个元素出现的个数 """ def count(self, nums: List[int], num: int, l: int, r: int) -> int: count = 0 for i in range(l, r+1): if nums[i] == num: count += 1 return count def helper(self, nums: List[int], l: int, r: int) -> int: if l == r: return nums[l] mid = (r - l) // 2 + l left = self.helper(nums, l, mid) right = self.helper(nums, mid + 1, r) if left == right: return left leftCount = self.count(nums, left, l, r) rightCount = self.count(nums, right, l, r) return left if leftCount > rightCount else right def majorityElement(self, nums: List[int]) -> int: return self.helper(nums, 0, len(nums) - 1) # leetcode submit region end(Prohibit modification and deletion) a = Solution print(a.majorityElement(a, [7, 7, 7, 2])) <file_sep>/easy/58.最后一个单词的长度.py # 给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。 # # 如果不存在最后一个单词,请返回 0 。 # # 说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。 # # # # 示例: # # 输入: "<NAME>" # 输出: 5 # # Related Topics 字符串 # 👍 226 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def lengthOfLastWord(self, s: str) -> int: if not s: return 0 count = 0 for i in s[::-1]: if i != " ": count += 1 elif count == 0: continue else: break return count # leetcode submit region end(Prohibit modification and deletion) count = Solution().lengthOfLastWord("a ") print(count) <file_sep>/easy/119.杨辉三角II.py # 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。 # # # # 在杨辉三角中,每个数是它左上方和右上方的数的和。 # # 示例: # # 输入: 3 # 输出: [1,3,3,1] # # # 进阶: # # 你可以优化你的算法到 O(k) 空间复杂度吗? # Related Topics 数组 # 👍 197 👎 0 from typing import List # leetcode submit region begin(Prohibit modification and deletion) class Solution: def getRow(self, rowIndex: int) -> List[int]: if rowIndex == 0: return [] res = [[1]] while len(res[-1]) <= rowIndex: newRow = [a + b for a, b in zip(res[-1] + [0], [0] + res[-1])] res = [newRow] return res[-1] # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/09.回文数.py #!/usr/bin/env python # -*- coding::utf-8 -*- # Author :GG # 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 # # 示例 1: # # 输入: 121 # 输出: true # # # 示例 2: # # 输入: -121 # 输出: false # 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。 # # # 示例 3: # # 输入: 10 # 输出: false # 解释: 从右向左读, 为 01 。因此它不是一个回文数。 # # # 进阶: # # 你能不将整数转为字符串来解决这个问题吗? # Related Topics 数学 # 👍 1130 👎 0 def isPalindrome(x: int) -> bool: if x < 0: return False temp = 0 old = x while x > 0: temp = temp * 10 + x % 10 x //= 10 if temp == old: return True else: return False <file_sep>/easy/28.实现strStr().py #!/usr/bin/env python # -*- coding::utf-8 -*- # Author :GG # 实现 strStr() 函数。 # # 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如 # 果不存在,则返回 -1。 # # 示例 1: # # 输入: haystack = "hello", needle = "ll" # 输出: 2 # # # 示例 2: # # 输入: haystack = "aaaaa", needle = "bba" # 输出: -1 # # # 说明: # # 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。 # # 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。 # Related Topics 双指针 字符串 # 👍 496 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def strStr(self, haystack: str, needle: str) -> int: if not needle: return 0 try: return haystack.index(needle) except(ValueError): return -1 def strstr2(self, haystack: str, needle: str) -> int: if not needle: return 0 if not haystack: return -1 l1 = len(haystack) l2 = len(needle) if l1 < l2: return -1 for i in range(0, l1 - l2 + 1): k = i j = 0 while j < l2 and k < l1 and haystack[k] == needle[j]: k += 1 j += 1 if j == l2: return i return -1 # leetcode submit region end(Prohibit modification and deletion) a = Solution() b = a.strstr2("a", "a") print(b) <file_sep>/easy/110.平衡二叉树.py # 给定一个二叉树,判断它是否是高度平衡的二叉树。 # # 本题中,一棵高度平衡二叉树定义为: # # # 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。 # # # # # 示例 1: # # # 输入:root = [3,9,20,null,null,15,7] # 输出:true # # # 示例 2: # # # 输入:root = [1,2,2,3,3,null,null,4,4] # 输出:false # # # 示例 3: # # # 输入:root = [] # 输出:true # # # # # 提示: # # # 树中的节点数在范围 [0, 5000] 内 # -104 <= Node.val <= 104 # # Related Topics 树 深度优先搜索 # 👍 521 👎 0 # leetcode submit region begin(Prohibit modification and deletion) # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def isBalanced(self, root: TreeNode) -> bool: if not root: return True def height(node: TreeNode): if not node: return 0 left = height(node.left) if left == -1: return -1 right = height(node.right) if right == -1: return -1 if abs(left - right) > 1: return -1 return max(left, right) + 1 return height(root) != -1 # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/125.验证回文串.py # 给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。 # # 说明:本题中,我们将空字符串定义为有效的回文串。 # # 示例 1: # # 输入: "A man, a plan, a canal: Panama" # 输出: true # # # 示例 2: # # 输入: "race a car" # 输出: false # # Related Topics 双指针 字符串 # 👍 293 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def isPalindrome(self, s: str) -> bool: if not s: return True left, right = 0, len(s) - 1 while left < right: while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True # leetcode submit region end(Prohibit modification and deletion) <file_sep>/tag/贪心算法/1827.最少操作使数组递增.py # 给你一个整数数组 nums (下标从 0 开始)。每一次操作中,你可以选择数组中一个元素,并将它增加 1 。 # # # 比方说,如果 nums = [1,2,3] ,你可以选择增加 nums[1] 得到 nums = [1,3,3] 。 # # # 请你返回使 nums 严格递增 的 最少 操作次数。 # # 我们称数组 nums 是 严格递增的 ,当它满足对于所有的 0 <= i < nums.length - 1 都有 nums[i] < nums[i+1] # 。一个长度为 1 的数组是严格递增的一种特殊情况。 # # # # 示例 1: # # 输入:nums = [1,1,1] # 输出:3 # 解释:你可以进行如下操作: # 1) 增加 nums[2] ,数组变为 [1,1,2] 。 # 2) 增加 nums[1] ,数组变为 [1,2,2] 。 # 3) 增加 nums[2] ,数组变为 [1,2,3] 。 # # # 示例 2: # # 输入:nums = [1,5,2,4,1] # 输出:14 # # # 示例 3: # # 输入:nums = [8] # 输出:0 # # # # # 提示: # # # 1 <= nums.length <= 5000 # 1 <= nums[i] <= 104 # # Related Topics 贪心算法 数组 # 👍 7 👎 0 # leetcode submit region begin(Prohibit modification and deletion) from typing import List class Solution: def minOperations(self, nums: List[int]) -> int: temp = nums[0] n = 0 for i in nums[1::]: if i > temp: temp = i else: diff = temp - i + 1 n += diff temp = i + diff return n # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/27.移除元素.py #!/usr/bin/env python # -*- coding::utf-8 -*- # Author :GG # 给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。 # # 不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。 # # 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。 # # # # 示例 1: # # 给定 nums = [3,2,2,3], val = 3, # # 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。 # # 你不需要考虑数组中超出新长度后面的元素。 # # # 示例 2: # # 给定 nums = [0,1,2,2,3,0,4,2], val = 2, # # 函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。 # # 注意这五个元素可为任意顺序。 # # 你不需要考虑数组中超出新长度后面的元素。 # # # # # 说明: # # 为什么返回数值是整数,但输出的答案是数组呢? # # 请注意,输入数组是以「引用」方式传递的,这意味着在函数里修改输入数组对于调用者是可见的。 # # 你可以想象内部操作如下: # # // nums 是以“引用”方式传递的。也就是说,不对实参作任何拷贝 # int len = removeElement(nums, val); # # // 在函数里修改输入数组对于调用者是可见的。 # // 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。 # for (int i = 0; i < len; i++) { #     print(nums[i]); # } # # Related Topics 数组 双指针 # 👍 590 👎 0 from typing import List # leetcode submit region begin(Prohibit modification and deletion) class Solution: def removeElement(self, nums: List[int], val: int) -> int: i = 0 for j in range(0, len(nums)): if nums[j] != val: nums[i] = nums[j] i += 1 return i def removeElement2(self, nums: List[int], val: int) -> int: i = 0 n = len(nums) while i < n: if nums[i] == val: nums[i] = nums[n - 1] n -= 1 else: i += 1 return n def removeElement3(self, nums: List[int], val: int) -> int: for i in range(len(nums) - 1, -1, -1): if nums[i] == val: nums.pop(i) return len(nums) def removeElement4(self, nums: List[int], val: int) -> int: a = nums.count(val) for i in range(a): nums.remove(val) return len(nums) # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/70.爬楼梯.py #!/usr/bin/env python # -*- coding::utf-8 -*- # Author :GG # 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 # # 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? # # 注意:给定 n 是一个正整数。 # # 示例 1: # # 输入: 2 # 输出: 2 # 解释: 有两种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 # 2. 2 阶 # # 示例 2: # # 输入: 3 # 输出: 3 # 解释: 有三种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 + 1 阶 # 2. 1 阶 + 2 阶 # 3. 2 阶 + 1 阶 # # Related Topics 动态规划 # 👍 1176 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def climbStairs(self, n: int) -> int: p, q, r = 0, 0, 1 for i in range(1, n + 1): p = q q = r r = p + q return r # leetcode submit region end(Prohibit modification and deletion) a = Solution().climbStairs(3) print(a) <file_sep>/easy/07.整数反转.py """ 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。 示例 1: 输入: 123 输出: 321  示例 2: 输入: -123 输出: -321 示例 3: 输入: 120 输出: 21 注意: 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。 """ def reverse_force(x: int) -> int: str_x = str(x) if str_x[0] == "-": str_x = str_x[:0:-1] x = int(str_x) x = -x else: str_x = str_x[::-1] x = int(str_x) return x if -2 ** 31 < x < 2 ** 31 - 1 else 0 print(reverse_force(x=123)) <file_sep>/easy/171.Excel表列序号.py # 给定一个Excel表格中的列名称,返回其相应的列序号。 # # 例如, # # A -> 1 # B -> 2 # C -> 3 # ... # Z -> 26 # AA -> 27 # AB -> 28 # ... # # # 示例 1: # # 输入: "A" # 输出: 1 # # # 示例 2: # # 输入: "AB" # 输出: 28 # # # 示例 3: # # 输入: "ZY" # 输出: 701 # # 致谢: # 特别感谢 @ts 添加此问题并创建所有测试用例。 # Related Topics 数学 # 👍 186 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def titleToNumber(self, s: str) -> int: num = 0 for i in s: num = num * 26 + (ord(i) - 65) return num # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/01.两数之和.py """ 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。   示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1] """ from typing import List def twoSum(self, nums: List[int], target: int) -> List[int]: length = len(nums) for i in range(length): temp1 = nums[i] temp2 = target - temp1 if temp2 in nums and nums.index(temp2) != i: index1 = i index2 = nums.index(temp2) return index1, index2 <file_sep>/easy/67.二进制求和.py # 给你两个二进制字符串,返回它们的和(用二进制表示)。 # # 输入为 非空 字符串且只包含数字 1 和 0。 # # # # 示例 1: # # 输入: a = "11", b = "1" # 输出: "100" # # 示例 2: # # 输入: a = "1010", b = "1011" # 输出: "10101" # # # # 提示: # # # 每个字符串仅由字符 '0' 或 '1' 组成。 # 1 <= a.length, b.length <= 10^4 # 字符串如果不是 "0" ,就都不含前导零。 # # Related Topics 数学 字符串 # 👍 445 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def addBinary(self, a: str, b: str) -> str: return "{0:b}".format(int(a, 2) + int(b, 2)) class Solution1: def addBinary(self, a: str, b: str) -> str: r, p = "", 0 d = len(a) - len(b) a = "0" * -d + a b = "0" * d + b for i, j in zip(a[::-1], b[::-1]): s = int(i) + int(j) + p r = str(s % 2) + r p = s // 2 return "1" + r if p else r # leetcode submit region end(Prohibit modification and deletion) a = Solution1().addBinary("11", "1") print(a) print(-2 * "aa") print(2 * "aa") <file_sep>/tag/贪心算法/1725.可以形成最大正方形的矩形数量.py # 给你一个数组 rectangles ,其中 rectangles[i] = [li, wi] 表示第 i 个矩形的长度为 li 、宽度为 wi 。 # # 如果存在 k 同时满足 k <= li 和 k <= wi ,就可以将第 i 个矩形切成边长为 k 的正方形。例如,矩形 [4,6] 可以切成边长最大为 # 4 的正方形。 # # 设 maxLen 为可以从矩形数组 rectangles 切分得到的 最大正方形 的边长。 # # 请你统计有多少个矩形能够切出边长为 maxLen 的正方形,并返回矩形 数目 。 # # # # 示例 1: # # # 输入:rectangles = [[5,8],[3,9],[5,12],[16,5]] # 输出:3 # 解释:能从每个矩形中切出的最大正方形边长分别是 [5,3,5,5] 。 # 最大正方形的边长为 5 ,可以由 3 个矩形切分得到。 # # # 示例 2: # # # 输入:rectangles = [[2,3],[3,7],[4,3],[3,7]] # 输出:3 # # # # # 提示: # # # 1 <= rectangles.length <= 1000 # rectangles[i].length == 2 # 1 <= li, wi <= 109 # li != wi # # Related Topics 贪心算法 # 👍 8 👎 0 from typing import List # leetcode submit region begin(Prohibit modification and deletion) class Solution: def countGoodRectangles(self, rectangles: List[List[int]]) -> int: temp = 0 n = 0 for i in rectangles: diff = min(i[0], i[1]) if diff == temp: n += 1 elif diff > temp: temp = diff n = 1 return n # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/198.打家劫舍.py # 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上 # 被小偷闯入,系统会自动报警。 # # 给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。 # # # # 示例 1: # # 输入:[1,2,3,1] # 输出:4 # 解释:偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。 #   偷窃到的最高金额 = 1 + 3 = 4 。 # # 示例 2: # # 输入:[2,7,9,3,1] # 输出:12 # 解释:偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。 #   偷窃到的最高金额 = 2 + 9 + 1 = 12 。 # # # # # 提示: # # # 0 <= nums.length <= 100 # 0 <= nums[i] <= 400 # # Related Topics 动态规划 # 👍 1178 👎 0 from typing import List # leetcode submit region begin(Prohibit modification and deletion) class Solution: def rob(self, nums: List[int]) -> int: if not nums: return 0 n = len(nums) if n < 3: return max(nums) r1, r2 = nums[0], max(nums[0], nums[1]) for i in range(2, n): r1, r2 = r2, max(r1 + nums[i], r2) return r2 # leetcode submit region end(Prohibit modification and deletion) class Solution: def rob(self, nums: List[int]) -> int: y = 0 t = 0 for i in nums: y, t = t, max(y + i, t) return t <file_sep>/easy/118.杨辉三角.py # 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 # # # # 在杨辉三角中,每个数是它左上方和右上方的数的和。 # # 示例: # # 输入: 5 # 输出: # [ # [1], # [1,1], # [1,2,1], # [1,3,3,1], # [1,4,6,4,1] # ] # Related Topics 数组 # 👍 374 👎 0 from typing import List # leetcode submit region begin(Prohibit modification and deletion) class Solution: def generate(self, numRows: int) -> List[List[int]]: if numRows == 0: return [] res = [[1]] while len(res) < numRows: newRow = [a + b for a, b in zip([0] + res[-1], res[-1] + [0])] res.append(newRow) return res # leetcode submit region end(Prohibit modification and deletion) res = [[1, 2, 3, 4]] new = [a + b for a, b in zip([0] + res[-1], res[-1] + [0])] # # for a in [0] + res[-1]: # print(a) # for a in res[-1] + [0]: # print(a) # for a in res[-1] : # print(a) for a in [0] + [1, 2, 3]: print(a) for a in [1, 2, 3] + [0]: print(a) <file_sep>/tag/贪心算法/1221.分割平衡字符串.py # 在一个 平衡字符串 中,'L' 和 'R' 字符的数量是相同的。 # # 给你一个平衡字符串 s,请你将它分割成尽可能多的平衡字符串。 # # 注意:分割得到的每个字符串都必须是平衡字符串。 # # 返回可以通过分割得到的平衡字符串的 最大数量 。 # # # # 示例 1: # # # 输入:s = "RLRRLLRLRL" # 输出:4 # 解释:s 可以分割为 "RL"、"RRLL"、"RL"、"RL" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。 # # # 示例 2: # # # 输入:s = "RLLLLRRRLR" # 输出:3 # 解释:s 可以分割为 "RL"、"LLLRRR"、"LR" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。 # # # 示例 3: # # # 输入:s = "LLLLRRRR" # 输出:1 # 解释:s 只能保持原样 "LLLLRRRR". # # # 示例 4: # # # 输入:s = "RLRRRLLRLL" # 输出:2 # 解释:s 可以分割为 "RL"、"RRRLLRLL" ,每个子字符串中都包含相同数量的 'L' 和 'R' 。 # # # # # 提示: # # # 1 <= s.length <= 1000 # s[i] = 'L' 或 'R' # s 是一个 平衡 字符串 # # Related Topics 贪心算法 字符串 # 👍 95 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def balancedStringSplit(self, s: str) -> int: n = 0 temp = 0 for i in s: if i == "R": temp += 1 else: temp -= 1 if temp == 0: n += 1 return n # leetcode submit region end(Prohibit modification and deletion) <file_sep>/tag/贪心算法/1710.卡车上的最大单元数.py # 请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi, numberOf # UnitsPerBoxi] : # # # numberOfBoxesi 是类型 i 的箱子的数量。 # numberOfUnitsPerBoxi 是类型 i 每个箱子可以装载的单元数量。 # # # 整数 truckSize 表示卡车上可以装载 箱子 的 最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。 # # 返回卡车可以装载 单元 的 最大 总数。 # # # # 示例 1: # # # 输入:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 # 输出:8 # 解释:箱子的情况如下: # - 1 个第一类的箱子,里面含 3 个单元。 # - 2 个第二类的箱子,每个里面含 2 个单元。 # - 3 个第三类的箱子,每个里面含 1 个单元。 # 可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。 # 单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8 # # 示例 2: # # # 输入:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 # 输出:91 # # # # # 提示: # # # 1 <= boxTypes.length <= 1000 # 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000 # 1 <= truckSize <= 106 # # Related Topics 贪心算法 排序 # 👍 17 👎 0 from typing import List """ 先对二维数组进行排序,优先装size大的箱子 """ # leetcode submit region begin(Prohibit modification and deletion) class Solution: def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int: boxTypes.sort(key=lambda x: -x[1]) res = 0 for num, size in boxTypes: cnt = min(truckSize, num) res += cnt * size truckSize -= cnt if truckSize == 0: break return res # leetcode submit region end(Prohibit modification and deletion) <file_sep>/easy/35.搜索插入位置.py #!/usr/bin/env python # -*- coding::utf-8 -*- # Author :GG # 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。 # # 你可以假设数组中无重复元素。 # # 示例 1: # # 输入: [1,3,5,6], 5 # 输出: 2 # # # 示例 2: # # 输入: [1,3,5,6], 2 # 输出: 1 # # # 示例 3: # # 输入: [1,3,5,6], 7 # 输出: 4 # # # 示例 4: # # 输入: [1,3,5,6], 0 # 输出: 0 # # Related Topics 数组 二分查找 # 👍 555 👎 0 # leetcode submit region begin(Prohibit modification and deletion) from typing import List class Solution: def searchInsert(self, nums: List[int], target: int) -> int: if target in nums: return nums.index(target) nums.append(target) nums.sort() return nums.index(target) # leetcode submit region end(Prohibit modification and deletion)
b72cbafda25941a411a06bd688004fb6ec8b0397
[ "Python" ]
28
Python
GGjin/algorithm_python
de36824647a10199963c64b0d32b8fb581c9eef6
92d8ea04c8298bb2fcb65299d8f925a0c750209d
refs/heads/master
<repo_name>ECommProfscot/ECommerce4<file_sep>/ECommerc.Api.Products.Test/UnitTest1.cs using System; using Xunit; using ECommerce.Api.Products.Providers; using ECommerce.Api.Products.Db; using Microsoft.EntityFrameworkCore; using ECommerce.Api.Products.Profiles; using AutoMapper; using System.Linq; namespace ECommerc.Api.Products.Test { public class ProductsServiceTest { [Fact] public async void GetProductsReturnsAllProducts() { var options = new DbContextOptionsBuilder<ProductsDbContext>().UseInMemoryDatabase(nameof(GetProductsReturnsAllProducts)).Options; var dbContext = new ProductsDbContext( options ); CreateProducts(dbContext); var productProfile = new ProductProfile(); var configuration = new MapperConfiguration(cfg => cfg.AddProfile(productProfile)); var mapper = new Mapper(configuration); var productsProvider = new ProductsProvider(dbContext, null, mapper); var result = await productsProvider.GetProductsAsync(); Assert.True(result.IsSuccess); Assert.True(result.Products.Any()); Assert.Null(result.ErrorMessage); } [Fact] public async void GetProductsReturnsProductById() { var options = new DbContextOptionsBuilder<ProductsDbContext>().UseInMemoryDatabase(nameof(GetProductsReturnsProductById)).Options; var dbContext = new ProductsDbContext(options); CreateProducts(dbContext); var productProfile = new ProductProfile(); var configuration = new MapperConfiguration(cfg => cfg.AddProfile(productProfile)); var mapper = new Mapper(configuration); var productsProvider = new ProductsProvider(dbContext, null, mapper); var result = await productsProvider.GetProductAsync(4); Assert.True(result.IsSuccess); Assert.NotNull(result.Product); Assert.Null(result.ErrorMessage); Assert.True(result.Product.Id == 4); } [Fact] public async void GetProductsReturnsProductById2() { //Test var options = new DbContextOptionsBuilder<ProductsDbContext>().UseInMemoryDatabase(nameof(GetProductsReturnsProductById2)).Options; var dbContext = new ProductsDbContext(options); CreateProducts(dbContext); var productProfile = new ProductProfile(); var configuration = new MapperConfiguration(cfg => cfg.AddProfile(productProfile)); var mapper = new Mapper(configuration); var productsProvider = new ProductsProvider(dbContext, null, mapper); var result = await productsProvider.GetProductAsync(5); Assert.True(result.IsSuccess); Assert.NotNull(result.Product); Assert.Null(result.ErrorMessage); Assert.True(result.Product.Id == 4); } [Fact] public async void GetProductsReturnsProductByWrongId() { var options = new DbContextOptionsBuilder<ProductsDbContext>().UseInMemoryDatabase(nameof(GetProductsReturnsProductByWrongId)).Options; var dbContext = new ProductsDbContext(options); CreateProducts(dbContext); var productProfile = new ProductProfile(); var configuration = new MapperConfiguration(cfg => cfg.AddProfile(productProfile)); var mapper = new Mapper(configuration); var productsProvider = new ProductsProvider(dbContext, null, mapper); var result = await productsProvider.GetProductAsync(-4); Assert.False(result.IsSuccess); Assert.Null(result.Product); Assert.NotNull(result.ErrorMessage); } private void CreateProducts(ProductsDbContext dbContext) { foreach (var product in dbContext.Products) { dbContext.Products.Remove(product); } dbContext.SaveChanges(); for (int i = 3; i <= 10; i++) { dbContext.Products.Add(new Product() { Id = i, Inventory = i * 10, Name = "Product" + i, price = (decimal)(i * 1.5) }); } dbContext.SaveChanges(); } } } <file_sep>/ECommerce.Api.Products/Providers/ProductsProvider.cs using AutoMapper; using ECommerce.Api.Products.Db; using ECommerce.Api.Products.Interfaces; using ECommerce.Api.Products.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ECommerce.Api.Products.Providers { public class ProductsProvider : IProductsProvider { private readonly ProductsDbContext dbContext; private readonly ILogger<ProductsProvider> logger; private readonly IMapper mapper; public ProductsProvider( ProductsDbContext dbContext, ILogger<ProductsProvider> logger, IMapper mapper ) { this.dbContext = dbContext; this.logger = logger; this.mapper = mapper; SeedData(); } private void SeedData() { var length = 10; if (!dbContext.Products.Any()) { for (int i = 3; i < length; i++) { dbContext.Products.Add(new Db.Product() { Id = i, Name = "ProductName" + i, Inventory = i * 10, price = (decimal)(i * 15.5) }); } dbContext.SaveChanges(); } } public async Task<(bool IsSuccess, IEnumerable<Models.Product> Products, string ErrorMessage)> GetProductsAsync() { try { var products = await dbContext.Products.ToListAsync(); if (products != null && products.Any()) { var result = mapper.Map<IEnumerable<Db.Product>, IEnumerable<Models.Product>>(products); return (true, result, null); } else { return (false, null, "Not found"); } } catch (Exception ex) { logger?.LogError(ex.ToString()); return (false, null, ex.Message); } } public async Task<(bool IsSuccess, Models.Product Product, string ErrorMessage)> GetProductAsync(int id) { try { var product = await dbContext.Products.FirstOrDefaultAsync(p => p.Id == id); if (product!= null ) { var result = mapper.Map<Db.Product, Models.Product>(product); return (true, result, null); } else { return (false, null, "Not found"); } } catch (Exception ex) { logger?.LogError(ex.ToString()); return (false, null, ex.Message); } } } }
838f3d5339670cf997878984e6e29902777ac69b
[ "C#" ]
2
C#
ECommProfscot/ECommerce4
37f9960a89c374077204f82c9d9a9be00767061e
e0c0cc445753c31b69b0ca008e1686b04c078cff
refs/heads/master
<repo_name>SergeyShcherbakov95/spec_prog<file_sep>/laba1.py __author__ = 'sergey' import urllib2 from datetime import datetime import pandas as pd def dowl(i): index = str(i) if i < 10: index = '0' + index url="http://www.star.nesdis.noaa.gov/smcd/emb/vci/gvix/G04/ts_L1/ByProvince/Mean/L1_Mean_UKR.R" + index + ".txt" vhi_url = urllib2.urlopen(url) index = str(names[i]) out = open('vhi-' + index + '-' + datetime.strftime(datetime.now(), "--%m-%Y") + '.csv','wb') nameFiles.append('vhi-' + index + '-' + datetime.strftime(datetime.now(), "--%m-%Y") + '.csv') out.write(vhi_url.read()) out.close() print "VHI " + index + " is downloaded..." def readFiles(i): df = pd.read_csv('/home/sergey/PycharmProjects/laba1/' + i , index_col = False, header = 1) return df names = {1 : '22', 2: '24', 3 : '23', 4 : '25', 5 : '03', 6 : '04', 7 : '08', 8 : '19', 9 : '20', 10 : '21', 11 : '09', 13 : '10', 14 : '11', 15 : '12', 16 : '13', 17 : '14', 18 : '15', 19 : '16', 21 : '17', 22 : '18', 23 : '06', 24 : '01', 25 : '02', 26 : '07', 27 : '05'} def VHIYearMinMax(df, i, year): print "\n" print i print year list = df.VHI[(df['year'] == year) & (df['VHI'] != -1.00)].tolist() print "Year " + str(year) + " VHI_max = " + str(max(list)) print "Year " + str(year) + " VHI_min = " + str(min(list)) def VHI15(df, i, percent): print "\n" print i print "Max VHI(Area_LESS_15): " print df[(df['%Area_VHI_LESS_15'] > percent) & (df['VHI'] < 15)] def VHI35(df, i, percent): print "\n" print i print "Max VHI(Area_LESS_35): " print df[(df['%Area_VHI_LESS_35'] > percent) & (df['VHI'] < 35) & (df['VHI'] > 15)] def SummerVHI(df, i): print "\n" print i print "Summer: " list = df.year[(df['VHI'] > 60) & (df['week'] > 22) & (df['week'] < 27)].tolist() for i in list: index = list.count(i) if index == 4: list.remove(i) print i nameFiles = [] for i in range(1, 28): if(i == 12 or i == 20): continue #dowl(i) index = str(names[i]) nameFiles.append('vhi-' + index + '-' + datetime.strftime(datetime.now(), "--%m-%Y") + '.csv') for i in nameFiles: VHIYearMinMax(readFiles(i), i, 1995) VHI15(readFiles(i), i, 1) VHI35(readFiles(i), i, 1) SummerVHI(readFiles(i), i) <file_sep>/laba2.py from spyre import server import pandas as pd from datetime import datetime class StockExample(server.App): title = "VHI - lab2" inputs = [{ "input_type": 'dropdown', "label": 'Setting', "options": [{"label": "VHI", "value": "VHI"}, {"label": "TCI", "value": "TCI"}, {"label": "VCI", "value": "VCI"}], "variable_name": 'setting', "action_id": "update_data" }, { "input_type": 'dropdown', "label": 'Province', "options": [{"label": "Vinnickaya", "value": "01"}, {"label": "Volinskaya", "value": "02"}, {"label": "Dnepropetrovskaya", "value": "03"}, {"label": "Doneckaya", "value": "04"}, {"label": "Zhytomirskaya", "value": "05"}, {"label": "Zakarpatskaya", "value": "06"}, {"label": "Zaporojskaya", "value": "07"}, {"label": "Ivano-Frankovskaya", "value": "08"}, {"label": "Kievskaya", "value": "09"}, {"label": "Kirovogradskaya", "value": "10"}, {"label": "Luganskaya", "value": "11"}, {"label": "Lvovskaya", "value": "12"}, {"label": "Nikolaevskaya", "value": "13"}, {"label": "Odeskaya", "value": "14"}, {"label": "Poltavskaya", "value": "15"}, {"label": "Rovenskaya", "value": "16"}, {"label": "Summskaya", "value": "17"}, {"label": "Ternopol'skaya", "value": "18"}, {"label": "Khar'kovskaya", "value": "19"}, {"label": "Khersonskaya", "value": "20"}, {"label": "Hmel'nickaya", "value": "21"}, {"label": "Cherkasskaya", "value": "22"}, {"label": "Chernivec'ka", "value": "23"}, {"label": "Chernigovskaya", "value": "24"}, {"label": "Krim", "value": "25"},], "variable_name": 'province', "action_id": "update_data"}, { "input_type": 'text', "label": 'Year', "value": '1995', "variable_name": 'year', "action_id": "update_data" }, { "input_type": 'text', "label": 'Week from', "value": '1', "variable_name": 'week_start', "action_id": "update_data" }, { "input_type": 'text', "label": 'Week to', "value": '52', "variable_name": 'week_end', "action_id": "update_data" }, { "input_type": 'dropdown', "label": 'Summer', "options": [{"label": "No", "value": "no"}, {"label": "Yes", "value": "yes"},], "variable_name": 'summer', "action_id": "update_data" },] controls = [{ "control_type": "hidden", "label": "get historical value of VCI/TCI/VHI", "control_id": "update_data"}] tabs = ["Plot", "Table"] outputs = [{ "output_type": "plot", "output_id": "plot", "control_id": "update_data", "tab": "Plot", "on_page_load": True }, { "output_type": "table", "output_id": "table_id", "control_id": "update_data", "tab": "Table", "on_page_load": True }] def getData(self, params): setting = params['setting'] province = params['province'] year = int(params['year']) week_start = int(params['week_start']) week_end = int(params['week_end']) summer = params['summer'] df = pd.read_csv('vhi-' + province + '-' + datetime.strftime(datetime.now(), "--%m-%Y") + '.csv' , index_col = False, header = 1) df = df[(df['VHI'] != -1.00)] df = df[(df['VCI'] != -1.00)] df = df[(df['TCI'] != -1.00)] if(summer == "yes"): df = df[(df['VHI'] > 60) & (df['week'] > 22) & (df['week'] < 27)] list = df.year.tolist() for i in list: index = list.count(i) if index != 4: df = df[df['year'] != i] df = df[['year', 'VHI']] return df if (year > 2015) and (week_end > 5) or (year < 1982): year = 2008 if (week_start < 1) or (week_start > week_end) or (week_start > 52): week_start = 1 if (week_end > 52) or (week_end < 1): week_end = 52 df = df[df['year'] == int(year)] df = df[df['week'] >= int(week_start)] df = df[df['week'] <= int(week_end)] df = df[['week', setting]] return df def getPlot(self, params): df = self.getData(params) plt_obj = df.set_index('week').plot() plt_obj.set_ylabel(list(df[:0])[1]) plt_obj.set_title('VHI-TCI-VCI') fig = plt_obj.get_figure() return fig app = StockExample() app.launch(port=9093)
c78682eb0be9e367492333afc2206865f784037a
[ "Python" ]
2
Python
SergeyShcherbakov95/spec_prog
38b91ac2d433e3368eceeb8f0a8227fb0bc0a144
696b0a1acdeecc71353bcc91698c4a355dbc227c
refs/heads/master
<file_sep>var gulp = require('gulp'); var sass = require('gulp-sass'); var input = './src/scss/main.scss'; var output = './public/'; gulp.task('style', function () { return gulp .src(input) .pipe(sass()) .pipe(gulp.dest(output)); }); gulp.task('watch', function() { return gulp.watch('./src/scss/**/*.scss', ['style']); });<file_sep>import React from 'react'; import {getColor} from './dict/color' const Listing = ({limit, products, selectedItem, updateCart}) => { let items = Object.keys(products).slice(0, limit).map( id => { let {image, title, stock, price, color} = products[id]; return ( <div className="listing__item" key={id}> <img className="listing__itemImage" src={image} alt={title} onClick={() => selectedItem(id)}/> <p className="listing__itemPrice" style={{color : getColor(color)}}>{price}</p> <button className="listing__itemButton" type="button" onClick={ () => updateCart(id) } disabled={stock.remaining <= 0} >ADD TO CART</button> </div> ); }); return ( <div className="listing">{items}</div> ); }; export default Listing;<file_sep>import React, { Component } from 'react'; import Boutique from './Boutique'; class App extends Component { render() { return ( <Boutique api="https://next.json-generator.com/api/json/get/4kiDK7gxZ" /> ); } } export default App; <file_sep>This project was developed for LightSpeed's technical test. This prototype was created from [Create React App](https://github.com/facebookincubator/create-react-app) for effeciency. The front end stack that it comes with, fulfilled the needs for this project to be completed with gulp added to it. ## Table of Contents - [Get the app up and running](#get-the-app-up-and-running) - [Tools](#tools) - [UI behaviour cases](#ui-behaviour-cases) - [Thought process](#thought-process) - [Next Steps](#next-steps) - [Contact](#contact) ## Get the app up and running Follow the instruction below: `content in these quotes are to be executed in command line` 1. Clone this [repo's](https://github.com/yipsun/lightspeedboutique) master branch: `git clone https://github.com/yipsun/lightspeedboutique.git` 2. Install Node Modules preferably with yarn: `yarn` || `npm install` 3. Compile SCSS -> CSS by using gulp task manager: `./node_modules/.bin/gulp style`(local) || `gulp style`(global) 4. Start app: `yarn run start` || `npm run start` At this point, you'll be able to view the application with Create React App's stack. ## Tools After reading the criterias of the test, I've decided to take the plunge with Create React App, since it provides all the necessary basic stack to create a protoype application. Easy to use, less stack configuration and more coding! I've added gulp to the package.json since Create React App's philosphy is to include all resources directly in the components, while I'm just more comfortable writing my stylesheets seperately : more explicit structure by importing scss file in a specific order, sharing variables and mixins, etc. I've used Font Awesome for my icons, since it's practical with its CDN and easy use. I've used BootStrap's breakpoint as they seem to fit the standards in the web industry. ## UI behaviour cases * Adding all the remaining stock into your cart should disable the ADD TO CART button. * Checkout with no item in your cart should recommend you to shop. * Clicking on the image of a product in the listing should open the detail view. * In the code if you change the API prop of Boutique to make an error, the error view should appear in the app. ## Thoughts and process In this case `App`, is basically the shell around the whole application, if the app had more component such as header, footer, related articles, etc., they could have been added at this level just like `Boutique`. `Boutique` is a class component, since it needs its state property to dictate the views to be rendered and handling the events of sub components, such as updating the cart, selecting a product for the detailed view and checking out. My sub components `Detail`, `Listing` and `Cart` are functional classes/stateless component as they do not require state management within itself. Managing the events was quite simple by passing callbacks from the parent component to the child, by attaching events attribute on the JSX to call the callback function and passing the required parameters. The fetch API was used to make the initial request to the dummy API, but if it needed to be be supported on older browser, we would switch the call with XHR. Fetch was more convenient as it returns a Promise. As we get our response, before storing the data in our state to render the `Listing`, I've transform the array of products into an object. Instead of fetching a product by the array index, I've set the product's id as the key of the product inside of the new object. ```Javascript var responseFromAPI = [ { title : "Nintendo Switch", id : "urururrkkkfii9393i" }, {...}, {...} ]; var products = { urururrkkkfii9393i : { title : "Nintendo Switch", id : "urururrkkkfii9393i" }, iiifkfkgkgkkgkgkgk : { ... }, fififiif9jl1l10l11 : { ... } } ``` The purpose of this application is to update your cart as well as the remaining quantity of products and calculating the total amount, that requires to manipulate and fetch the products. Looping through an array to find your desired product can become quite costly perfomance wise, in this case we have about 30 products but in a real online store such as Amazon you have billions of items. Let's take calculating the total amount of your cart, if you have 4 items you would have to loop through your products 4 times before having the necessary data for your equation, while an object you can fetch directly your products just by storing you product ID. Manipulating items in an array can be risky as the index is not specific to an item, therefor if the index and/or length of the array starts to shift around, that index is not reliable. ## Next steps Developing application it's always best to think about your mvp functionalities but also the potential growth of your component, so what's next ? The boutique component has a function `updateCart` which takes as parameters `(itemId, quantity)`, for now when we call this function we always pass by default `1` as its quantity. Eventually we can add an input(num) in the `Detail` component to specify the quantity we want to add into our cart instead of the default value. The logic behind quantity parameter has already been implemented, the only thing left to do is integrate the DOM. `Boutique`'s state has a `listingLimit` property which is passed as prop to `Listing`, with CTAs we can modify this value to allow more products to be shown, example at [Simons](https://www.simons.ca/en). With the eventuality to add sorting and filtering methods to the listing, this one could become a class component as it'll require state management. The cart property of the `Boutique`'s state only store the ID of the product as it's key and the quantity, this way there's no duplicate in our application and there's only one true data for a product. The success message to the checkout functionality list all the products bought and the quantity. The next step would actually be to have a cart management UI to remove items and update quantities. ## Contact If you have any questions, comments and/or constructive feedback on this technical test, please write me at [<EMAIL>](mailto:<EMAIL>)<file_sep>import React from 'react'; import {getColor} from './dict/color'; const Detail = ({product, updateCart, setSelectedItem}) => { // destructuring product property into var for easier access let {title, description, color, image, stock, price} = product; return ( <div className="detail"> <span className="detail__close far fa-times-circle" onClick={ () => setSelectedItem(null) }></span> <div className="detail__container"> <div className="detail__itemImgWrap"> <img className="detail__itemImage" style={{border: `solid 3px ${getColor(color)}`}} src={ image } alt={ title } /> </div> <div className="detail__itemInfoWrap"> <h2 className="detail__itemTitle">{title}</h2> <p className="detail__itemDesc">{ description }</p> <ul className="detail__itemInfo"> <li><span>Price: </span>{price}</li> <li><span>In-stock: </span>{stock.remaining}</li> <li><span>Color: </span>{color}</li> </ul> <button className="detail__itemButton" type="button" onClick={ () => updateCart(product._id) } disabled={ stock.remaining <= 0 } >ADD TO CART</button> </div> </div> </div> ); }; export default Detail;
f3c79b3787d37cc85110ecf400195faffd360009
[ "JavaScript", "Markdown" ]
5
JavaScript
yipsun/lightspeedboutique
04c34c1d3eeea474b59c380877e365d671d26664
9834f3a190dbea2c59109c1a8a45d20689b472de
refs/heads/master
<file_sep>/**************************************************************************** ** Program name: Menu ** Author: <NAME> ** Date: 3/26/17 ** Description: This file contains the definition of the Menu class. This class ** has two contructors, a default constructor and a constructor ** that takes a vector of strings as a parameter. There are ** member functions for displaying the menu options as well as ** adding and removing options. There is also a function that ** validates a user choice by checking to see if it is in a ** valid range for the menu. *****************************************************************************/ #ifndef MENU_HPP #define MENU_HPP #include <string> #include <vector> class Menu { private: //A single member variable, a vector of strings, //that holds the menu options std::vector<std::string> menuOptions; public: //Two contructors Menu(); Menu(std::vector<std::string>); //Member functions void addOption(std::string); void removeOption(int); void printMenu(); bool validUserChoice(int); }; #endif<file_sep>/**************************************************************************** ** Program name: User Input Validation ** Author: <NAME> ** Date: 3/26/17 ---- Updated: 4/6/17 ** Description: This file contains the function definitions for separate ** functions designed to get and validate user input for ints. ** doubles, chars, and strings. Both functions take a prompt that ** is displayed to the user, which has a default value. ** ** One allows for a value to be returned from ** the function (note it will not exit until the user enters ** an appropriate value), and another version that modifies a ** reference variable and returns a boolean to indicate success ** or failure. Two versions for now since I'm not sure what is ** better necessarily. Functions will likely continue to be ** updated. *****************************************************************************/ #ifndef USER_INPUT_VALIDATION_HPP #define USER_INPUT_VALIDATION_HPP #include <string> int getInt(std::string promptForUser = "Enter an integer:"); bool getInt(int &userInt, std::string promptForUser = "Enter an integer:"); #endif <file_sep>/********************************************************************* ** Program name: Langton's Ant ** Author: <NAME> ** Date: 4/6/17 ** Description: This file contains the definition for the Ant class ** as well as a Direction enum which this class uses. *********************************************************************/ #ifndef LANGTONS_ANT_HPP #define LANGTONS_ANT_HPP #include <iostream> //Direction enum that is used to keep track of //which way the ant is currently facing. enum Direction { NORTH, EAST, SOUTH, WEST }; class Ant { private: //Declare the necessary integers this class needs. //All but currentSteps are initialized via the constructor int boardRows; int boardColumns; int maxSteps; int currentSteps; int antCurrentRow; int antCurrentColumn; //An array of chars that keeps track of the possible values //in the board. ' ' is a white square, '#' is a black square, //and '@' is the ant. Another char holds the value for whatever //square the ant is currently on (since it must be erased for '@' to be drawn there) char charList[3] = { ' ', '#', '@' }; char antCurrentSpotColor; //A char double pointer that is used to allocate //a 2D array of chars which represents the board //the ant will move in char** antBoard; //A direction enum which will be used to keep track of how the ant //is facing at any point Direction antCurrentDirection; public: //One constructor which take the necessary integers Ant(int boardRows, int boardColumns, int maxSteps, int antCurrentRow, int antCurrentColumn); //A destructor which will deallocate the memory allocated for the 2D array. Will prevent memory leaks. ~Ant(); //Member functions for the Ant class //These will control updating the board //and displaying reuslts to the screen bool takeStep(); void moveNorth(); void moveEast(); void moveSouth(); void moveWest(); void printAntBoard(); }; #endif<file_sep>/********************************************************************* ** Program name: Langton's Ant ** Author: <NAME> ** Date: 4/6/17 ** Description: This program simulates Langton's ant. It allows the ** user to set the size of the board and either explicitly ** choose an ant starting point or let it be random. ** Due to the board not having infinite space, if the ** ant ever would need to step outside the board, it is ** designed to "wrap around" to the other side of the board. *********************************************************************/ #include "LangtonsAnt.hpp" #include "UserInputValidation.hpp" #include "Menu.hpp" #include <time.h> //for using the time function to seed the random num generator //Function prototype for function that run through the simulation void playGame(bool playRandom); int main() { //Seed the random number with the time which //will result in different numbers each time //the program is run srand(time(0)); //Welcome the user std::cout << "Welcome to the Langton's Ant Simulator!" << std::endl << "Select the type of simulation you would like to run:" << std::endl << std::endl; //Declare a gameMenu object Menu gameMenu; //Use member functions to add options to the menu in the order they will be displayed gameMenu.addOption("Choose ant starting position"); gameMenu.addOption("Random ant starting position"); gameMenu.addOption("Quit program"); //Declare an int variable to hold the users choice for this menu int userMenuChoice; //Declare a bool to indicate whether the user wants to terminate the program bool programExit = false; //Program will run in loop until the user decides to terminate //Allowing for as many simulation runs as desired while (!programExit) { //Show the menu to the user, through the help of a member function gameMenu.printMenu(); //Prompt the user and use an input validation function to //get the user to enter an int. userMenuChoice = getInt("Select an option: "); //Using a member function to check if the integer was a valid choice, //the program will re-prompt the user if they need to pick again while (!gameMenu.validUserChoice(userMenuChoice)) { userMenuChoice = getInt("Please select a valid option: "); } //Use a switch statement to act upon the users choice. //If this statment is reached, the user's choice is an int and //it is a valid menu option switch (userMenuChoice) { case 1: //Calls the playGame function, passing in false playGame(false); break; case 2: //Calls the playGame function, passing in true playGame(true); break; case 3: //Set the boolean to allow loop to end which will cause program //to come to the end of main programExit = true; break; default: break; } } return 0; } //This function sets up the simulation per the user's specifications and then //creates an Ant object which runs the simulation. This function does not need to //return a value. The parameter it takes is a boolean which will indicate if the //ant starting position should be random or not. True means position will be random, //and false means the user will choose void playGame(bool playRandom) { //Establish all necessarily variables to set up the simualtion properly int boardRows; int boardColumns; int desiredSteps; int antStartRow; int antStartCol; //Prompt the user for the size of the board in rows and columns and the number of steps the //ant should take. At each point the input validation function guarentees the user enters an //integer before proceeding. Note that initially the user is warned about making the board too large. //All values are also checked for a range that makes sense and will not cause errors. std::cout << "You must decide the size of the board." << std::endl << "Please note that choosing a board size too large will cause" << std::endl << "the program to take more time to print to the screen." << std::endl << "Try to choose a number lower than 80 for columns as this is" << std::endl << "the default width of the window " << std::endl << std::endl << "First, how many rows would you like? "; boardRows = getInt(""); while (boardRows <= 0) { std::cout << "Please choose a number greater than 0: "; boardRows = getInt(""); } std::cout << "And how many columns? "; boardColumns = getInt(""); while (boardColumns <= 0) { std::cout << "Please choose a number greater than 0: "; boardColumns = getInt(""); } std::cout << "How many steps should the ant take? "; desiredSteps = getInt(""); while (desiredSteps < 0) { std::cout << "Please enter a non negative number: "; desiredSteps = getInt(""); } //If the function argument is false allow the user to choose the ant starting positon //via its row and column. This uses the same procedure as above. It also makes sure the //user does not try to place the ant outside the array if (!playRandom) { std::cout << "Now you will choose the starting position for the ant" << std::endl << "What row should the ant start in? "; antStartRow = getInt(""); while (antStartRow >= boardRows || antStartRow < 0) { std::cout << "That is outside of the board! Please choose again: "; antStartRow = getInt(""); } std::cout << "Now what column should the ant start in? "; antStartCol = getInt(""); while (antStartCol >= boardColumns || antStartCol < 0) { std::cout << "That is outside of the board! Please choose again: "; antStartCol = getInt(""); } } //If the user has expressed they want the position to be random the else if statement triggers else if (playRandom) { //Take the ant starting row and column and set it equal to the //result of the rand() function modulo the number of rows and columns the user has requested //This will result in a value that is within the array index since the modulo will result in a //value anywhere from 0 to boardRows/columns - 1 antStartRow = rand() % boardRows; antStartCol = rand() % boardColumns; } //Create an ant object with the integers needed for its constructor Ant currentAnt(boardRows, boardColumns, desiredSteps, antStartRow, antStartCol); //Based upon the user's specifications, the starting state of the board //is printed out. Only the ant will be visible though std::cout << "Start:" << std::endl; currentAnt.printAntBoard(); std::cout << std::endl; //The takeStep function returns a boolean if a step is taken. //While this function is returning true, it means the ant has //taken another step on the board. This board is then printed out while (currentAnt.takeStep()) { currentAnt.printAntBoard(); std::cout << std::endl; } }<file_sep>/********************************************************************* ** Program name: Langton's Ant ** Author: <NAME> ** Date: 4/6/17 ** Description: This file contains the implementation for the Ant class *********************************************************************/ #include "LangtonsAnt.hpp" //The only constructor for this class which takes five integer parameters Ant::Ant(int boardRows, int boardColumns, int maxSteps, int antCurrentRow, int antCurrentColumn) { //Using the this pointer, sets the member variable of the class appropriately this->boardRows = boardRows; this->boardColumns = boardColumns; this->maxSteps = maxSteps; this->antCurrentRow = antCurrentRow; this->antCurrentColumn = antCurrentColumn; //At the start of a simulation the steps will always be zero //The starting square will be white //The ant will face north to begin currentSteps = 0; antCurrentSpotColor = charList[0]; antCurrentDirection = NORTH; //Allocate an array of char pointers for the double pointer member variable //The number is equal to the number of rows the user desired antBoard = new char*[boardRows]; //For each of the pointers in this array, allocate an array of chars //The number is equal to the number of columns the user desired for (int i = 0; i < boardRows; i++) { //The [] dereferences the double pointer giving a single pointer //This single pointer can then be givin the address of an array to point at antBoard[i] = new char[boardColumns]; } //Use a nested for loop to set each char in the 2D array to the //space character which represents the white square for (int i = 0; i < boardRows; i++) { for (int j = 0; j < boardColumns; j++) { //the [][] dereferences the double pointer giving the memory //location of a char which can be set using the list of chars //member variable antBoard[i][j] = charList[0]; } } //Whatever location the user picked for the ant (or if it was random), these //values are used to place the '@' at the appropriate location antBoard[antCurrentRow][antCurrentColumn] = charList[2]; } //The Ant class deconstructor is responsible for deallocating the memory used //by the constructor. This will prevent memory leaks in the program. Ant::~Ant() { //Deallocate the memory taken by the char arrays for each //of the single pointers for (int i = 0; i < boardRows; i++) { delete[] antBoard[i]; } //Deallocate the memory taken by the array of char pointers delete[] antBoard; } //The following four functions are all very similar and might be able to be combined //into one function if a better algorithm could be developed. These "sub functions" //were created to make the takeStep() function less "crowded". Each function takes no //parameters and has no return type. Based upon the direction they represent, the function //sets the direction accordingly and updates the ant's position. Here array bound checking //occurs and the ant is "wrapped around" to the other side of the board if it would ever attempt //to step out. void Ant::moveNorth() { //Set enum accordingly antCurrentDirection = NORTH; //If the ant needs to move north but its current row index is 0, //this means it will attempt to step out of bounds if (antCurrentRow == 0) { //boardRows - 1 will equal the highest valid index for the rows of the board //The spot color the ant is about to move into is recorded antCurrentSpotColor = antBoard[boardRows - 1][antCurrentColumn]; //The '@' character is set in the appropriate location antBoard[boardRows - 1][antCurrentColumn] = charList[2]; //The new position for the ant (in this case the rows, is recorded) antCurrentRow = boardRows - 1; } else { //The else condition will run if the ant is not about to step out of //bounds. The concept is the same but instead the new row for the ant //will just be its current row - 1 antCurrentSpotColor = antBoard[antCurrentRow - 1][antCurrentColumn]; antBoard[antCurrentRow - 1][antCurrentColumn] = charList[2]; antCurrentRow -= 1; } } void Ant::moveEast() { antCurrentDirection = EAST; //If the ant is in a column where the index + 1 is equal to or greater than //the max number of columns, than the ant will try to step out of bounds to the right. //To wrap the ant around to the other side, the column is set to 0 index which will be the //leftmost point on the board if (antCurrentColumn + 1 >= boardColumns) { antCurrentSpotColor = antBoard[antCurrentRow][0]; antBoard[antCurrentRow][0] = charList[2]; antCurrentColumn = 0; } else { antCurrentSpotColor = antBoard[antCurrentRow][antCurrentColumn + 1]; antBoard[antCurrentRow][antCurrentColumn + 1] = charList[2]; antCurrentColumn += 1; } } void Ant::moveSouth() { antCurrentDirection = SOUTH; //If the ant is in a row where the index + 1 is equal to or greater than //the max number of row, than the ant will try to step out of bounds through the bottom. //To wrap the ant around to the other side, the row is set to 0 index which will be the //top point on the board if (antCurrentRow + 1 >= boardRows) { antCurrentSpotColor = antBoard[0][antCurrentColumn]; antBoard[0][antCurrentColumn] = charList[2]; antCurrentRow = 0; } else { antCurrentSpotColor = antBoard[antCurrentRow + 1][antCurrentColumn]; antBoard[antCurrentRow + 1][antCurrentColumn] = charList[2]; antCurrentRow += 1; } } void Ant::moveWest() { antCurrentDirection = WEST; //If the ant is in the leftmost column and is trying to move west, //the new column index must be the total board columns - 1 if (antCurrentColumn == 0) { antCurrentSpotColor = antBoard[antCurrentRow][boardColumns - 1]; antBoard[antCurrentRow][boardColumns - 1] = charList[2]; antCurrentColumn = boardColumns - 1; } else { antCurrentSpotColor = antBoard[antCurrentRow][antCurrentColumn - 1]; antBoard[antCurrentRow][antCurrentColumn - 1] = charList[2]; antCurrentColumn -= 1; } } //This function is the main function that runs the simulation. It relies on the //other move functions once it determines which is appropriate for the given //situation. The function takes no parameters but returns a boolean if a step was completed bool Ant::takeStep() { //If the number of steps that have already been completed is //greater than or equal to the number of steps the user //requested then the step should not be carried out if (currentSteps >= maxSteps) { return false; } //Display to the user which step is being shown std::cout << "Step " << currentSteps + 1 << ":" << std::endl; //Use a switch statement that checks which direction the ant is facing switch (antCurrentDirection) { //For each direction the ant is facing, check if the ant is on a //white or black square. Based upon these results set the color of //that square accordingly and call the appropriate move function case NORTH: //For example, tf the ant is on a white square and facing north if (antCurrentSpotColor == charList[0]) { //Change that square to black antBoard[antCurrentRow][antCurrentColumn] = charList[1]; //Move the ant east moveEast(); } else if (antCurrentSpotColor == charList[1]) { antBoard[antCurrentRow][antCurrentColumn] = charList[0]; moveWest(); } break; case EAST: if (antCurrentSpotColor == charList[0]) { antBoard[antCurrentRow][antCurrentColumn] = charList[1]; moveSouth(); } else if (antCurrentSpotColor == charList[1]) { antBoard[antCurrentRow][antCurrentColumn] = charList[0]; moveNorth(); } break; case SOUTH: if (antCurrentSpotColor == charList[0]) { antBoard[antCurrentRow][antCurrentColumn] = charList[1]; moveWest(); } else if (antCurrentSpotColor == charList[1]) { antBoard[antCurrentRow][antCurrentColumn] = charList[0]; moveEast(); } break; case WEST: if (antCurrentSpotColor == charList[0]) { antBoard[antCurrentRow][antCurrentColumn] = charList[1]; moveNorth(); } else if (antCurrentSpotColor == charList[1]) { antBoard[antCurrentRow][antCurrentColumn] = charList[0]; moveSouth(); } break; default: break; } //Increment the number of steps before returning true currentSteps += 1; return true; } //Printing out the board uses its own function that takes no parameters //and returns nothing. It uses a nested for loop to dereference each pointer //in the array and print out the character at that index void Ant::printAntBoard() { for (int i = 0; i < boardRows; i++) { for (int j = 0; j < boardColumns; j++) { std::cout << antBoard[i][j]; } std::cout << std::endl; } } <file_sep>/**************************************************************************** ** Program name: User Input Validation ** Author: <NAME> ** Date: 3/26/17 ---- Updated: 4/6/17 ** Description: This file contains the function implementations for separate ** functions designed to get and validate user input for ints. ** doubles, chars, and strings. Both functions take a prompt that ** is displayed to the user, which has a default value. ** ** One allows for a value to be returned from ** the function (note it will not exit until the user enters ** an appropriate value), and another version that modifies a ** reference variable and returns a boolean to indicate success ** or failure. Two versions for now since I'm not sure what is ** better necessarily. Functions will likely continue to be ** updated. *****************************************************************************/ #include "UserInputValidation.hpp" #include <iostream> #include <sstream> //For using a stringstream object int getInt(std::string promptForUser) { //Declare an int that will hold the user's integer choice after //validation. This will be returned by the function. int userInt; //Boolean for loop control. Keeps track of whether or not the user //has succesfully entered an integer bool userEnteredInteger = true; //String variable to hold the user's raw input std::string userInt_Str; //Declare two integer varaibles for use with the string.substr() function. //This will be used to trim white space from the beginning and end of the string int startPos; int length; //Creates a string stream object that will give the userInt variable the //modified user input std::stringstream convertedUserInput; //Start a do while loop since this action will need to be completed at least once do { //Must set the boolean to true at the start everytime (note this is redundant for the first loop //since the bool is already true) userEnteredInteger = true; //Displays the prompt given to the function and puts a space after it std::cout << promptForUser << " "; //Gets the user input and stores it as a string std::getline(std::cin, userInt_Str); //Using two string functions the first non-whitespace character of the input, //and the last non-whitespace character is found. startPos = userInt_Str.find_first_not_of(' '); //The number of characters from the starting point is determined //by subtracting the index of the first non-whitespace character found //from the index of the last non-whitespace character found and adding 1 length = userInt_Str.find_last_not_of(' ') - startPos + 1; //If the character is not found for either of the previous formula, the //"npos" constant will be returned (equal to -1). To prevent an error (out of bounds), //1 must be added to the startPos so it will be zero and the program will not crash. //Note that if the character is not found, length will already be greater than 0 so there is no //reason to increment this value as well if (startPos == std::string::npos ) { startPos++; } //Returns the "sub string" that starts at index startPos and takes in "length" //number of characters (including the character at the start position). The user's //input string is set as this substring. At this point the user's input has been "trimmed" //of leading and trailing whitespace userInt_Str = userInt_Str.substr(startPos, length); //The "trimmed" string is set as the contents to the "convertedUserInput" string stream object convertedUserInput.str(userInt_Str); //String stream object is streamed to the userInt variable convertedUserInput >> userInt; //Check if the extraction failed or the extraction succeeded but there //are ASCII characters left in the stream if (convertedUserInput.fail() || convertedUserInput.get() >= 0) { //Sets the control bool to false userEnteredInteger = false; //Clear any potential errors with the clear() function convertedUserInput.clear(); } } while (!userEnteredInteger); //Loop will run if the user's input was not successfully validated //Returns validated integer return userInt; } bool getInt(int &userInt, std::string promptForUser) { //String variable to hold the user's raw input std::string userInt_Str; //Declare two integer varaibles for use with the string.substr() function. //This will be used to trim white space from the beginning and end of the string int startPos; int length; //Creates a string stream object that will give the userInt variable the //modified user input std::stringstream convertedUserInput; //Displays the prompt given to the function and puts a space after it std::cout << promptForUser << " "; //Gets the user input and stores it as a string std::getline(std::cin, userInt_Str); //Using two string functions the first non-whitespace character of the input, //and the last non-whitespace character is found. startPos = userInt_Str.find_first_not_of(' '); //The number of characters from the starting point is determined //by subtracting the index of the first non-whitespace character found //from the index of the last non-whitespace character found and adding 1 length = userInt_Str.find_last_not_of(' ') - startPos + 1; //If the character is not found for either of the previous formula, the //"npos" constant will be returned (equal to -1). To prevent an error (out of bounds), //1 must be added to the startPos so it will be zero and the program will not crash. //Note that if the character is not found, length will already be greater than 0 so there is no //reason to increment this value as well if (startPos == std::string::npos) { startPos++; } //Returns the "sub string" that starts at index startPos and takes in "length" //number of characters (including the character at the start position). The user's //input string is set as this substring. At this point the user's input has been "trimmed" //of leading and trailing whitespace userInt_Str = userInt_Str.substr(startPos, length); //The "trimmed" string is set as the contents to the "convertedUserInput" string stream object convertedUserInput.str(userInt_Str); //String stream object is streamed to the userInt variable convertedUserInput >> userInt; //Check if the extraction failed or the extraction succeeded but there //are ASCII characters left in the stream if (convertedUserInput.fail() || convertedUserInput.get() >= 0) { //Tell the caller that the user did not enter an int //and let the caller decide what to do return false; } //If this line is reached then the user entered a valid int return true; } <file_sep> #Makefile for Project 1 - 4/7/17 #Assembled with the help of the following references: #http://mrbook.org/blog/tutorials/make/ (Course material found in Canvas) and "makefile1" TA example provided in Canvas ClementeProject1: LangtonsAnt.cpp LangtonsAnt.hpp LangtonsAntMain.cpp Menu.cpp Menu.hpp UserInputValidation.cpp UserInputValidation.hpp g++ -g -std=c++0x LangtonsAntMain.cpp LangtonsAnt.cpp Menu.cpp UserInputValidation.cpp -o ClementeProject1 clean: rm *o<file_sep>/**************************************************************************** ** Program name: Menu ** Author: <NAME> ** Date: 3/26/17 ** Description: This file contains the implementation of the Menu class. ** Functions are all relatively simple, and rely on functions from ** the vector class that this class uses. *****************************************************************************/ #include "Menu.hpp" #include <iostream> Menu::Menu() { //The default contructor does nothing. //If creating an object this way the addOption() //function will be used to add items to the menu } Menu::Menu(std::vector<std::string> menuOptions) { //Sets the class's vector to the vector passed as an argument this->menuOptions = menuOptions; } void Menu::addOption(std::string option) { //Uses the vector push_back function to add //an option to the menu menuOptions.push_back(option); } void Menu::removeOption(int option) { //Removes the menu option specified by the argument //Note it takes the option and subtracts 1 to find the right index in the vector menuOptions.erase(menuOptions.begin() + (option - 1)); } void Menu::printMenu() { //Sets up a for loop for (unsigned int currentIndex = 0; currentIndex < menuOptions.size(); currentIndex++) { //For each element in the vector, prints out a number for the position (this will be the index plus 1), //and prints out the menu option at the current index std::cout << currentIndex + 1 << ". " << menuOptions.at(currentIndex) << std::endl; } std::cout << std::endl; } bool Menu::validUserChoice(int userChoice) { //User's choice can not be less than 1 (since menus will start at 1) //Choice can also not be greater than the total number of elements in the vector //which is givin by the size function if (userChoice < 1 || userChoice > menuOptions.size()) { //Return false to the caller if the choice is not valid return false; } //If the previous if statement does not run, then the choice was in a valid range return true; }
2ce79a4ab0583c25dccfe4dfffec58e5e57ddd4a
[ "Makefile", "C++" ]
8
C++
ttnguyen128/LangtonsAntSimulator
9f38566139fe432daea4a1c4c263b0e7ccb64d1b
fe5bc621a17c24c35507926e2c78c53b7a77fb8a
refs/heads/main
<repo_name>nam-hle/sole-and-ankle-revisited<file_sep>/src/components/Header/Header.js import React from 'react'; import styled from 'styled-components/macro'; import { BREAKPOINTS, WEIGHTS } from '../../constants'; import Logo from '../Logo'; import SuperHeader from '../SuperHeader'; import MobileMenu from '../MobileMenu'; import Icon from '../Icon'; const Header = () => { const [showMobileMenu, setShowMobileMenu] = React.useState(false); return ( <HeaderWrapper> <SuperHeader /> <MainHeader> <Side> <Logo /> </Side> <Nav> <NavLink href="/sale">Sale Sale Sale</NavLink> <NavLink href="/new">New&nbsp;Releases</NavLink> <NavLink href="/men">Men</NavLink> <NavLink href="/women">Beauty Women</NavLink> <NavLink href="/kids">Children</NavLink> <NavLink href="/collections">Collections</NavLink> </Nav> <Side /> </MainHeader> <MobileButtonGroup> <Icon id="shopping-bag" strokeWidth={2} size={20} /> <Icon id="search" strokeWidth={2} size={20} /> <HamburgerButton onClick={() => setShowMobileMenu(true)}> <Icon id="menu" strokeWidth={2} size={20} /> </HamburgerButton> </MobileButtonGroup> <MobileMenu isOpen={showMobileMenu} onDismiss={() => setShowMobileMenu(false)} /> </HeaderWrapper> ); }; const HamburgerButton = styled.button` background-color: var(--color-white); border: none; `; const MobileButtonGroup = styled.div` display: none; @media ${BREAKPOINTS.TABLET_AND_DOWN} { display: flex; gap: 24px; align-items: center; padding-right: 32px; } `; const HeaderWrapper = styled.header` @media ${BREAKPOINTS.TABLET_AND_DOWN} { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--color-gray-300); border-top: 4px solid var(--color-gray-900); } `; const MainHeader = styled.div` display: flex; align-items: baseline; padding: 18px 32px; height: 72px; border-bottom: 1px solid var(--color-gray-300); @media ${BREAKPOINTS.TABLET_AND_DOWN} { border: none; } `; const Nav = styled.nav` display: flex; gap: min(3rem, 11.7vw - 6.5rem); margin: 0 48px; overflow: scroll; @media ${BREAKPOINTS.TABLET_AND_DOWN} { display: none; } `; const Side = styled.div` flex: 1; `; const NavLink = styled.a` font-size: 1.125rem; text-transform: uppercase; text-decoration: none; color: var(--color-gray-900); font-weight: ${WEIGHTS.medium}; display: block; min-width: max-content; &:first-of-type { color: var(--color-secondary); } `; export default Header;
9cc11bfd98dd7dc52a312b89e1edc7c21c7b5633
[ "JavaScript" ]
1
JavaScript
nam-hle/sole-and-ankle-revisited
5c52d22ea208bdbb98d680cc165c6c9fc60f0957
4d97fa5859893f8ea655b3eeed1a816962405862
refs/heads/master
<file_sep>// // HomePageViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/11. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import SPPermissions let HomePageCell = "HomePageTableViewCell" class HomePageViewController: BaseTableViewController { var currentIndex = 0 var isCurrentPlayerPause = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = .black self.tableView.backgroundColor = .black self.tableView.rowHeight = self.view.bounds.height self.tableView.register(HomePageTableViewCell.classForCoder(), forCellReuseIdentifier: HomePageCell) self.tableView.showsVerticalScrollIndicator = false self.tableView.contentInsetAdjustmentBehavior = .never self.requestTableData() NotificationCenter.default.addObserver(self, selector: #selector(applicationBecomeActive), name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: true) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.tableView.layer.removeAllAnimations() let cells = self.tableView.visibleCells as! [HomePageTableViewCell] for cell in cells { cell.playerView.cancelLoading() } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.tableView.snp.remakeConstraints { (make) in make.edges.equalTo(self.view) } } override func requestTableData() { self.requestCourseList() } @objc func applicationEnterBackground() { let cell: HomePageTableViewCell = self.tableView.cellForRow(at: NSIndexPath.init(row: self.currentIndex, section: 0) as IndexPath) as! HomePageTableViewCell self.isCurrentPlayerPause = cell.rate == 0 ? true : false cell.pause() } @objc func applicationBecomeActive() { if self.isCurrentPlayerPause == false { let cell: HomePageTableViewCell = self.tableView.cellForRow(at: NSIndexPath.init(row: self.currentIndex, section: 0) as IndexPath) as! HomePageTableViewCell cell.play() } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "currentIndex" { self.isCurrentPlayerPause = false weak var cell = self.tableView.cellForRow(at: NSIndexPath.init(row: self.currentIndex, section: 0) as IndexPath) as? HomePageTableViewCell if cell?.isPlayerReady == false { cell?.replay() } else { AVPlayerManager.shared().pauseAll() cell?.onPlayerReady = { [weak self] in if let indexPath = self?.tableView.indexPath(for: cell!) { if self?.isCurrentPlayerPause == true && indexPath.row == self?.currentIndex { cell?.play() } } } } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } } extension HomePageViewController { func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: HomePageCell) as! HomePageTableViewCell cell.initWithData(data: self.tableDataArray[indexPath.row] as! Course) return cell } } // MARK: - 网络请求 extension HomePageViewController { func requestCourseList() { HomePageRequest.requestCourseList(page: self.pageNumber, size: self.pageSize, success: { (data) in if let response = data as? HomePageCourseListResponse { let courseList = response.data self.requestTableDataSuccess(array: courseList?.content ?? [Course](), dataTotal: courseList?.totalElements ?? 0) if self.pageNumber == 0 && self.tableDataArray.count > 0 { if self.isViewLoaded && (self.view!.window != nil) { self.currentIndex = 0 let indexPath = NSIndexPath.init(row: 0, section: 0) self.tableView.scrollToRow(at: indexPath as IndexPath, at: .middle, animated: false) } } } /// 网络加载框结束后提示权限 self.showSPPermissionsAlert() }) { (error) in self.requestNetDataFailed() /// 网络加载框结束后提示权限 self.showSPPermissionsAlert() } } } // MARK: - UIScrollViewDelegate extension HomePageViewController { func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if self.tableView.visibleCells.count == 0 { return } DispatchQueue.main.async { let translatePoint = scrollView.panGestureRecognizer.translation(in: scrollView) scrollView.panGestureRecognizer.isEnabled = false if translatePoint.y < -50 && self.currentIndex < (self.tableDataArray.count - 1) { self.currentIndex += 1 } if translatePoint.y > 50 && self.currentIndex > 0 { self.currentIndex -= 1 } UIView.animate(withDuration: 0.15, animations: { self.tableView.scrollToRow(at: NSIndexPath.init(row: self.currentIndex, section: 0) as IndexPath, at: .top, animated: false) }) { (finished) in scrollView.panGestureRecognizer.isEnabled = true } } } } extension HomePageViewController: SPPermissionsDelegate, SPPermissionsDataSource { func configure(_ cell: SPPermissionTableViewCell, for permission: SPPermission) -> SPPermissionTableViewCell { switch permission { case .camera: cell.permissionTitleLabel.text = "相机" cell.permissionDescriptionLabel.text = "请允许使用摄像头拍照或录像" case .photoLibrary: cell.permissionTitleLabel.text = "相册" cell.permissionDescriptionLabel.text = "请允许使用相册" case .microphone: cell.permissionTitleLabel.text = "麦克风" cell.permissionDescriptionLabel.text = "请允许使用麦克风录制音频" default: break } cell.button.allowTitle = "允许" cell.button.allowedTitle = "已允许" return cell } func showSPPermissionsAlert() { let permissions = [SPPermission.camera, .photoLibrary, .microphone].filter { !$0.isAuthorized } if !permissions.isEmpty { let controller = SPPermissions.dialog(permissions) controller.titleText = "权限列表" controller.headerText = "小书客在正常使用中需要用到以下系统权限,请允许使用" controller.footerText = "小书客" controller.delegate = self controller.dataSource = self controller.present(on: self) } } } <file_sep>// // HomePageRequest.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/13. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class HomePageRequest: BaseRequest { var page:Int? var size:Int? static func requestCourseList(page: Int, size: Int, success: @escaping HttpSuccess, failure: @escaping HttpFailure) { let request = HomePageRequest() request.page = page request.size = size NetWorkManager.get(url: isLogin ? URLForHomePageLearner : URLForHomePageOpen, request: request, showHUD: true, success: { (data) in if let response = HomePageCourseListResponse.deserialize(from: data as? [String: Any]) { success(response) } }) { (error) in failure(error) } } } <file_sep>// // UserGroup.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/16. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class UserGroup: BaseModel { var parentId: Double? var id: Double? var code: String? var type: String? var childCount: Double? var name: String? var namePath: String? } <file_sep>// // WebCacheManager.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/12. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import CommonCrypto /// 缓存清除完毕后回调 typealias WebCacheClearCompletedBlock = (_ cacheSize: String) -> Void /// 缓存查询完毕后回调 typealias WebCacheQueryCompletedBlock = (_ data: Any?, _ hasCache: Bool) -> Void /// 下载进度回调 typealias WebDownloaderProgressBlock = (_ receivedSize: Int64, _ expectedSize: Int64) -> Void /// 下载完毕回调 typealias WebDownloaderCompletedBlock = (_ data: Data?, _ error: Error?, _ finished: Bool) -> Void /// 下载取消回调 typealias WebDownloaderCancelBlock = () -> Void class WebCacheManager: NSObject { var memCache: NSCache<NSString, AnyObject>? var fileManager: FileManager = FileManager.default var diskCacheDirectoryURL: URL? var ioQueue: DispatchQueue? private static let instance = { () -> WebCacheManager in return WebCacheManager.init() }() class func shared() -> WebCacheManager { return instance } private override init() { super.init() self.memCache = NSCache() self.memCache?.name = "webCache" let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let path = paths.last let diskCachePath = path! + "/webCache" var isDirectory: ObjCBool = false let isExisted = fileManager.fileExists(atPath: diskCachePath, isDirectory: &isDirectory) // 判断是否存在缓存文件夹 if !isDirectory.boolValue || !isExisted { do { try fileManager.createDirectory(atPath: diskCachePath, withIntermediateDirectories: true, attributes: nil) } catch { print("创建缓存路径失败" + error.localizedDescription) } } diskCacheDirectoryURL = URL(fileURLWithPath: diskCachePath) ioQueue = DispatchQueue(label: "com.start.webcache") } // MARK: - 查询数据 /// 从内存和磁盘中查询数据 /// - Parameters: /// - key: key 值 /// - cacheQueryCompletedBlock: 查询完毕后回调 func queryDataFromMemory(key: String, cacheQueryCompletedBlock: @escaping WebCacheQueryCompletedBlock) -> Operation { return queryDataFromMemory(key: key, cacheQueryCompletedBlock: cacheQueryCompletedBlock, exten: nil) } /// 从内存和磁盘中查询数据 /// - Parameters: /// - key: key 值 /// - cacheQueryCompletedBlock: 查询完毕后回调 /// - exten: 扩展名 func queryDataFromMemory(key: String, cacheQueryCompletedBlock: @escaping WebCacheQueryCompletedBlock, exten: String?) -> Operation { let operation = Operation() ioQueue?.sync { if operation.isCancelled { return } /// 分别从内存或磁盘获取数据 if let data = self.dataFromMemoryCache(key: key) { cacheQueryCompletedBlock(data, true) } else if let data = self.dataFromDiskCache(key: key, exten: exten) { storeDataToMemoryCache(data: data, key: key) cacheQueryCompletedBlock(data, true) } else { cacheQueryCompletedBlock(nil, false) } } return operation } /// 根据URL查询缓存数据 /// - Parameters: /// - key: key 值 /// - cacheQueryCompletedBlock: 查询完毕后回调 func queryURLFromDiskMemory(key: String, cacheQueryCompletedBlock: @escaping WebCacheQueryCompletedBlock) -> Operation { return queryURLFromDiskMemory(key: key, cacheQueryCompletedBlock: cacheQueryCompletedBlock, exten: nil) } /// 根据URL查询缓存数据 /// - Parameters: /// - key: key 值 /// - cacheQueryCompletedBlock: 查询完毕后回调 /// - exten: 扩展名 func queryURLFromDiskMemory(key: String, cacheQueryCompletedBlock: @escaping WebCacheQueryCompletedBlock, exten: String?) -> Operation { let operation = Operation() ioQueue?.sync { if operation.isCancelled { return; } let path = diskCachePathForKey(key: key, exten: exten) ?? "" if fileManager.fileExists(atPath: path) { cacheQueryCompletedBlock(path, true) } else { cacheQueryCompletedBlock(path, false) } } return operation } // MARK: - 存储数据 func storeDataCache(data: Data?, key: String) { ioQueue?.async { self.storeDataToMemoryCache(data: data, key: key) self.storeDataToDiskCache(data: data, key: key) } } /// 存储数据到内存 /// - Parameters: /// - data: 数据 /// - key: key 值 func storeDataToMemoryCache(data: Data?, key: String) { memCache?.setObject(data as AnyObject, forKey: key as NSString) } /// 存储数据到磁盘 /// - Parameters: func storeDataToDiskCache(data: Data?, key: String) { self.storeDataToDiskCache(data: data, key: key, exten: nil) } /// 存储数据到磁盘 /// - Parameters: /// - data: 数据 /// - key: key 值 /// - exten: 扩展名 func storeDataToDiskCache(data: Data?, key: String, exten: String?) { if let diskPath = diskCachePathForKey(key: key, exten: exten) { fileManager.createFile(atPath: diskPath, contents: data, attributes: nil) } } // MARK: - 获取内存缓存 /// 根据 key 从内存中查询缓存 /// - Parameter key: key 值 func dataFromMemoryCache(key: String) -> Data? { return memCache?.object(forKey: key as NSString) as? Data } // MARK: - 获取磁盘缓存 /// 根据 key 获取本地磁盘缓存数据 /// - Parameter key: key 值 func dataFromDiskCache(key: String) -> Data? { return dataFromDiskCache(key: key, exten: nil) } /// 根据 key 获取本地磁盘缓存数据 /// - Parameters: /// - key: key 值 /// - exten: 扩展名 func dataFromDiskCache(key: String, exten: String?) -> Data? { if let cachePathForKey = diskCachePathForKey(key: key, exten: exten) { do { let data = try Data(contentsOf: URL(fileURLWithPath: cachePathForKey)) return data } catch {} } return nil } // MARK: - 获取文件路径 /// 获取 key 值对应的磁盘缓存路径 (包含扩展名) /// - Parameters: /// - key: key 值 /// - exten: 扩展名 func diskCachePathForKey(key: String, exten: String?) -> String? { let fileName = key.sha256() var cachePathForKey = diskCacheDirectoryURL?.appendingPathComponent(fileName).path if exten != nil { cachePathForKey = cachePathForKey! + "." + exten! } return cachePathForKey } // MARK: - 清除缓存 /// 清理缓存 func clearCache(cacheClearCompletedBlock: @escaping WebCacheClearCompletedBlock) { ioQueue?.async { self.clearMemoryCache() let cacheSize = self.clearDiskCache() DispatchQueue.main.async { cacheClearCompletedBlock(cacheSize) } } } /// 清除内存中的缓存 func clearMemoryCache() { memCache?.removeAllObjects() } /// 清理磁盘缓存 func clearDiskCache() -> String { do { let contents = try fileManager.contentsOfDirectory(atPath: (diskCacheDirectoryURL?.path)!) var folderSize: Float = 0 for fileName in contents { let filePath = (diskCacheDirectoryURL?.path)! + "/" + fileName let fileDict = try fileManager.attributesOfItem(atPath: filePath) folderSize += fileDict[FileAttributeKey.size] as! Float try fileManager.removeItem(atPath: filePath) } return String.format(decimal: folderSize / 1024.0 / 1024.0) ?? "0" } catch { print("清理磁盘错误" + error.localizedDescription) } return "0" } } <file_sep>// // PersonalRequest.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/18. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class PersonalRequest: BaseRequest { var page:Int? var size:Int? var id: String? var displayName: String? var image: UIImage? var file: String? static func reqeustCourseList(url: String, page: Int , size: Int, showHUD: Bool, success: @escaping HttpSuccess, failure: @escaping HttpFailure) { let request = PersonalRequest() request.page = page request.size = size NetWorkManager.get(url: url, request: request, showHUD: showHUD, success: { (data) in if let response = PersonalResponse.deserialize(from: data as? [String: Any]) { success(response) } }) { (error) in failure(error) } } static func updateUserInfo(name: String, userID: String, success: @escaping HttpSuccess, failure: @escaping HttpFailure) { let request = PersonalRequest() request.id = userID request.displayName = name NetWorkManager.post(url: URLForUpdateUserInfo, request: request, showHUD: true, success: { (data) in success(data) }) { (error) in failure(error) } } static func uploadUserIcon(image: UIImage, userId: String, success: @escaping HttpSuccess, failure: @escaping HttpFailure) { let request = PersonalRequest() request.id = userId request.file = "userAvatar.jpg" let url = URLForUploadUserAvatar + userId let imageData = image.jpegData(compressionQuality: 0.5) NetWorkManager.postData(url: url, contentType: .JPG, request: request, showHUD: true, fileData: imageData, success: { (data) in success(data) }) { (error) in failure(error) } } } <file_sep>// // VideoAddNewViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/27. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class VideoAddNewViewController: BaseViewController { let shootBtn = UIButton(type: .custom) let photoBtn = UIButton(type: .custom) var selectedModel: PhotoModel? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "选取视频" let rightItem = UIBarButtonItem(title: "下一步", style: .plain, target: self, action: #selector(nextAction)) rightItem.tintColor = .white self.navigationItem.rightBarButtonItem = rightItem initBottomBtn() clickedPhotosBtn() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) } @objc func nextAction() { if self.selectedModel == nil { WMHUD.textHUD(text: "请选择或者拍摄一个视频", delay: 1) } else { } } func initBottomBtn() { var btnH = 44 if UIDevice.current.isiPhoneXMore() { btnH = 64 } self.shootBtn.backgroundColor = .white self.shootBtn.setTitle("拍摄", for: .normal) self.shootBtn.setTitleColor(.darkGray, for: .normal) self.shootBtn.setTitleColor(ColorTheme, for: .selected) self.shootBtn.addTarget(self, action: #selector(clickedShootBtn), for: .touchUpInside) self.view.addSubview(self.shootBtn) self.shootBtn.snp.makeConstraints { (make) in make.left.bottom.equalTo(0) make.height.equalTo(btnH) make.right.equalTo(self.view.snp.centerX) } self.photoBtn.backgroundColor = .white self.photoBtn.setTitle("手机相册", for: .normal) self.photoBtn.setTitleColor(.darkGray, for: .normal) self.photoBtn.setTitleColor(ColorTheme, for: .selected) self.photoBtn.addTarget(self, action: #selector(clickedPhotosBtn), for: .touchUpInside) self.view.addSubview(self.photoBtn) self.photoBtn.snp.makeConstraints { (make) in make.left.equalTo(self.shootBtn.snp.right) make.height.width.bottom.equalTo(self.shootBtn) } } @objc func clickedShootBtn() { PhotoAssetTool.shared().recoredMovie(controller: self, maxTime: 10) { (videoURL, success) in if success { } else { WMHUD.errorHUD(text: nil, subText: "拍摄视频失败,请重试", delay: 1) } } } @objc func clickedPhotosBtn() { if self.photoBtn.isSelected {return} self.photoBtn.isSelected = true self.shootBtn.isSelected = false self.assetLibraryVC.view.isHidden = false } func shootVideoFinish(videoURL: String) { } func fetchAVURLAssetToFile() { } lazy var assetLibraryVC = { () -> VideoAssetLibraryViewController in let controller = VideoAssetLibraryViewController() self.addChild(controller) self.view.addSubview(controller.view) controller.selectedVideoBlock = { (model) in } controller.view.snp.makeConstraints { (make) in make.width.centerX.equalTo(self.view) make.top.equalTo(self.view.snp.top) make.bottom.equalTo(self.shootBtn.snp.top) } return controller }() } extension VideoAddNewViewController: UIVideoEditorControllerDelegate, UINavigationControllerDelegate { } <file_sep>// // BaseCollectionViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/17. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import MJRefresh import SnapKit import LYEmptyView class BaseCollectionViewController: BaseViewController { /// 没有下拉刷新 var noRefresh = false /// 没有加载更多 var noLoadMore = false /// 数据源 var collectionDataArray = Array<Any>() /// 页码 var pageNumber: Int = 0 /// 每页数据个数 var pageSize: Int = 10 /// 数据总个数 var dataTotal: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } lazy var collectionView = { () -> (UICollectionView) in let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) collectionView.delegate = self collectionView.dataSource = self collectionView.alwaysBounceVertical = true collectionView.contentInsetAdjustmentBehavior = .automatic collectionView.backgroundColor = ColorThemeBackground if !self.noRefresh { collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { self.refreshAction() }) collectionView.mj_header?.addObserver(self, forKeyPath: "state", options: .new, context: nil) } if !self.noLoadMore { collectionView.mj_footer = MJRefreshBackFooter.init(refreshingBlock: { self.loadMoreAction() }) collectionView.mj_footer?.addObserver(self, forKeyPath: "state", options: .new, context: nil) } self.view.addSubview(collectionView) collectionView.snp.makeConstraints { (make) in make.edges.equalTo(self.view) } return collectionView }() override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if self.collectionView.mj_header?.state == MJRefreshState.pulling { self.feedbackGenerator() } else if self.collectionView.mj_footer?.state == MJRefreshState.pulling { self.feedbackGenerator() } } func requestCollectionData() { } @objc func refreshAction() { self.pageNumber = 0 self.dataTotal = 0 self.collectionView.mj_header?.endRefreshing() self.collectionView.mj_footer?.endRefreshing() self.collectionDataArray.removeAll() self.collectionView.reloadData() self.requestCollectionData() } @objc func loadMoreAction() { if self.dataTotal <= self.collectionDataArray.count { self.collectionView.mj_footer?.endRefreshingWithNoMoreData() return } self.collectionView.mj_footer?.endRefreshing() self.pageNumber += 1 self.requestCollectionData() } func requestCollectionDataSuccess(array: Array<Any>, dataTotal: Double) { self.dataTotal = Int(dataTotal) self.collectionDataArray.append(array) self.collectionView.reloadData() if self.collectionDataArray.count == 0 { self.collectionView.ly_emptyView = LYEmptyView.emptyActionView(with: UIImage(named: "NoDataTipImage"), titleStr: "无数据", detailStr: "请稍后再试", btnTitleStr: "重新加载", btnClick: { self.requestCollectionData() }) } } func requestNetDataFailed() { if self.collectionDataArray.count == 0 { self.collectionView.ly_emptyView = LYEmptyView.emptyActionView(with: UIImage(named: "NoDataTipImage"), titleStr: "网络请求失败", detailStr: "请稍后再试", btnTitleStr: "重新加载", btnClick: { self.requestCollectionData() }) } } func feedbackGenerator() { let generator = UIImpactFeedbackGenerator(style: .medium) generator.prepare() generator.impactOccurred() } } extension BaseCollectionViewController: UICollectionViewDelegate { } extension BaseCollectionViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = UICollectionViewCell() return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.collectionDataArray.count } } extension BaseCollectionViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let itemW = (collectionView.bounds.size.width - 30) / 2 return CGSize(width: itemW, height: (itemW * 0.6 + 70)) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 10 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 10) } } <file_sep>// // PersonalViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/17. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import JXPagingView import JXSegmentedView let NotificationUserLikesChange = "NotificationUserLikesChange" class PersonalViewController: BaseViewController { var pagingView: JXPagingView! var dataSoure: JXSegmentedTitleDataSource = JXSegmentedTitleDataSource() var segmentedView: JXSegmentedView! var titles = [String]() var tableHeaderViewHeight: Int = 200 var headerInSectionHeight: Int = 50 var urlArray = [String]() var isMySelf = true override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. dataSoure.titles = titles dataSoure.titleSelectedColor = .white dataSoure.titleNormalColor = .darkText dataSoure.isTitleColorGradientEnabled = false dataSoure.isTitleZoomEnabled = true segmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: CGFloat(headerInSectionHeight))) segmentedView.backgroundColor = .clear segmentedView.delegate = self segmentedView.isContentScrollViewClickTransitionAnimationEnabled = false segmentedView.dataSource = dataSoure let line = JXSegmentedIndicatorLineView() line.indicatorColor = ColorTheme line.indicatorWidth = 50 segmentedView.indicators = [line] pagingView = preferredPagingView() pagingView.mainTableView.gestureDelegate = self pagingView.listContainerView.collectionView.gestureDelegate = self pagingView.pinSectionHeaderVerticalOffset = headerInSectionHeight self.view.addSubview(pagingView) pagingView.snp.makeConstraints { (make) in make.left.top.right.equalTo(0) if (self.parent?.isKind(of: MainTabBarViewController.classForCoder()))! { let offset = UIDevice.current.isiPhoneXMore() ? -50 : 0 make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(offset) } else { make.bottom.equalTo(self.view.snp.bottom) } } segmentedView.contentScrollView = pagingView.listContainerView.collectionView setupSubVCURL() // 延迟请求其他列表,因为第一次进来会请求第一个子列表的数据 DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.requestSubVCTotal(index: self.urlArray.count - 1) } NotificationCenter.default.addObserver(self, selector: #selector(updateUserLikeListTotal), name: NSNotification.Name(rawValue: NotificationUserLikesChange), object: nil) } func preferredPagingView() -> JXPagingView { return JXPagingListRefreshView(delegate: self) } func refreshAction() { self.headerView.setupUser(user: user!) self.segmentedView.reloadData() } lazy var headerView = { () -> (PersonalHeaderView) in let height = UIDevice.current.isiPhoneXMore() ? 180 : 160 let view = PersonalHeaderView(frame: CGRect(x: 0, y: 0, width: Int(self.view.bounds.size.width), height: height)) view.editUserIconBlock = { [weak self] () in self?.showImageAlert() } view.editUserNameBlock = { [weak self] () in self?.showEditNameAlert() } view.settingAppBlock = { [weak self] () in let settingVC = SettingViewController() self?.navigationController?.pushViewController(settingVC, animated: true) } view.goBackBlock = { [weak self] () in } return view }() // MARK: - 渐变背景色 lazy var headBackgroundView = { () -> (UIView) in let view = UIView() self.view.layoutIfNeeded() view.frame = CGRect(x: 0, y: 0, width: self.pagingView.frame.size.width, height: self.headerView.frame.size.height + 50) let gradient = CAGradientLayer() gradient.frame = view.bounds gradient.colors = [RGBA(r: 254, g: 134, b: 46, a: 1).cgColor, RGBA(r: 255, g: 147, b: 67, a: 1).cgColor] view.layer.addSublayer(gradient) return view }() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: true) self.pagingView.mainTableView.addSubview(self.headBackgroundView) self.pagingView.mainTableView.sendSubviewToBack(self.headBackgroundView) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.headBackgroundView.removeFromSuperview() } } // MARK: - 设置和更新segmentTitles extension PersonalViewController { func setupSubVCURL() { if isMySelf { self.urlArray = [URLForMineCourse, URLForMineCourseNotAudited, URLForMineCourseLike] } else { self.urlArray = [URLForMineCourse, URLForMineCourseLike] } } func requestSubVCTotal(index: Int) { PersonalRequest.reqeustCourseList(url: self.urlArray[index], page: 0, size: 0, showHUD: false, success: { (data) in let response = data as? PersonalResponse let totalElement = response?.data?.totalElements self.dataSoure.titles[index] = "\(self.titles[index])\(String(describing: totalElement))" self.segmentedView.reloadDataWithoutListContainer() if index > 1 { self.requestSubVCTotal(index: index - 1) } }) { (error) in } } @objc func updateUserLikeListTotal() { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self.requestSubVCTotal(index: self.titles.count - 1) } } } // MARK: - 修改用户信息 extension PersonalViewController { func showEditNameAlert() { let alertVC = UIAlertController(title: "", message: nil, preferredStyle: .alert) alertVC.addTextField { (textField) in textField.placeholder = "请输入新的名称" } let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) let confirAction = UIAlertAction(title: "确认", style: .default) { (action) in self.updateUserDisplayName(name: alertVC.textFields?.first?.text ?? "") } alertVC.addAction(cancelAction) alertVC.addAction(confirAction) self.present(alertVC, animated: true, completion: nil) } func updateUserDisplayName(name: String) { if name.count == 0 { WMHUD.textHUD(text: "不能使用空白用户名", delay: 1) return } PersonalRequest.updateUserInfo(name: name, userID: "\(String(describing: user?.id))", success: { (data) in user?.displayName = name self.headerView.nameLabel.text = name }) { (error) in } } } // MARK: - 修改头像 extension PersonalViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func showImageAlert() { PhotoAssetTool.shared().showImageSheet(controller: self, photos: { (image, finished) in self.uploadUserIcon(image: image) }) { (image, finished) in self.uploadUserIcon(image: image) } } func uploadUserIcon(image: UIImage?) { guard let newIcon = image else { WMHUD.errorHUD(text: nil, subText: "选取头像错误", delay: 1) return } PersonalRequest.uploadUserIcon(image: newIcon, userId: "\(String(describing: user?.id))", success: { (data) in let response = data as? [String: Any] let imageUrl = response?["avatar"] user?.avatar = imageUrl as? String }) { (error) in } } } // MARK: - JXSegmentedViewDelegate extension PersonalViewController: JXSegmentedViewDelegate { func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) { } func segmentedView(_ segmentedView: JXSegmentedView, didClickSelectedItemAt index: Int) { self.pagingView.listContainerView.collectionView.scrollToItem(at: NSIndexPath(row: index, section: 0) as IndexPath, at: .centeredHorizontally, animated: false) } } // MARK: - JXPagingViewDelegate extension PersonalViewController: JXPagingViewDelegate { func tableHeaderViewHeight(in pagingView: JXPagingView) -> Int { return tableHeaderViewHeight } func tableHeaderView(in pagingView: JXPagingView) -> UIView { return self.headerView } func heightForPinSectionHeader(in pagingView: JXPagingView) -> Int { return headerInSectionHeight } func viewForPinSectionHeader(in pagingView: JXPagingView) -> UIView { return segmentedView } func numberOfLists(in pagingView: JXPagingView) -> Int { return titles.count } func pagingView(_ pagingView: JXPagingView, initListAtIndex index: Int) -> JXPagingViewListViewDelegate { let collectionVC = PersonalCollectionViewController() if index == 0 { collectionVC.listType = .mine } else if index == 1 { collectionVC.listType = .likes } else { collectionVC.listType = .notAudited } return collectionVC } } extension PersonalViewController: JXPagingMainTableViewGestureDelegate { func mainTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { //禁止segmentedView左右滑动的时候,上下和左右都可以滚动 if otherGestureRecognizer == segmentedView?.collectionView.panGestureRecognizer { return false } return gestureRecognizer.isKind(of: UIPanGestureRecognizer.classForCoder()) && otherGestureRecognizer.isKind(of: UIPanGestureRecognizer.classForCoder()) } } extension PersonalViewController: JXPagingListContainerCollectionViewGestureDelegate { func pagingListContainerCollectionView(_ collectionView: JXPagingListContainerCollectionView, gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } } <file_sep>// // AVPlayerView.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/12. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import AVKit import MobileCoreServices /// 播放进度,播放状态 回调 protocol AVPlayerViewDelegate: NSObjectProtocol { /// 播放进度回调 /// - Parameters: /// - current: 当前播放时间 /// - total: 总时长 func onProgressUpdate(current: CGFloat, total: CGFloat) /// 播放状态回调 /// - Parameter status: 播放器状态 func onPlayItemStatusUpdate(status: AVPlayerItem.Status) } class AVPlayerView: UIView { /// 代理 var delegate: AVPlayerViewDelegate? /// 视频播放地址 var sourceURL: URL? /// 视频路径scheme var sourceScheme: String? /// 视频资源 var urlAsset: AVURLAsset? /// playerItem var playerItem: AVPlayerItem? /// 播放器 var player: AVPlayer? /// 播放器图层 var playerLayer: AVPlayerLayer = AVPlayerLayer() /// 播放器观察者 var timeObserver: Any? /// 缓冲数据 var data: Data? /// 视频下载的ssession var session: URLSession? /// 视频下载 task var task: URLSessionTask? /// 视频下载请求响应 var response: HTTPURLResponse? /// AVAssetResourceLoadingRequest 的数组 var pendingRequests = [AVAssetResourceLoadingRequest]() /// 缓存的 key 值 var cacheFilekey: String? /// 查找本地缓存的 operation var queryCacheOperation: Operation? /// 取消所有队列 var cancelLoadingQueue: DispatchQueue? init() { super.init(frame: .zero) initSubview() } override init(frame: CGRect) { super.init(frame: frame) initSubview() } func initSubview() { session = URLSession(configuration: .default, delegate: self, delegateQueue: .main) playerLayer = AVPlayerLayer(player: player) self.layer.addSublayer(self.playerLayer) addProgressObserver() cancelLoadingQueue = DispatchQueue(label: "com.start.cancelLoadingqueue") } override func layoutSubviews() { super.layoutSubviews() CATransaction.begin() CATransaction.setDisableActions(true) playerLayer.frame = self.layer.bounds CATransaction.commit() } func setPlayerVideoGravity(videoGravity: AVLayerVideoGravity) { playerLayer.videoGravity = videoGravity; } /// 数据源 /// - Parameter url: 视频地址 func setPlayerSourceUrl(url: String?) { // 过滤中文和特殊字符 let sourceurl = url?.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "`#%^{}\"[]|\\<> ").inverted) sourceURL = URL(string: sourceurl ?? "") let components = URLComponents(url: sourceURL!, resolvingAgainstBaseURL: false) sourceScheme = components?.scheme cacheFilekey = sourceURL?.absoluteString // 开启缓存线程 queryCacheOperation = WebCacheManager.shared().queryURLFromDiskMemory(key: cacheFilekey ?? "", cacheQueryCompletedBlock: { [weak self] (data, hasCache) in DispatchQueue.main.async { [weak self] in // 判断是否有缓存,创建数据源地址 if hasCache { self?.sourceURL = URL(fileURLWithPath: data as? String ?? "") } else { self?.sourceURL = self?.sourceURL?.absoluteString.urlScheme(scheme: "streaming") } // 创建播放器 if let url = self?.sourceURL { self?.urlAsset = AVURLAsset(url: url, options: nil) self?.urlAsset?.resourceLoader.setDelegate(self, queue: DispatchQueue.main) if let asset = self?.urlAsset { self?.playerItem = AVPlayerItem(asset: asset) self?.playerItem?.addObserver(self!, forKeyPath: "status", options: [.initial, .new], context: nil) self?.player = AVPlayer(playerItem: self?.playerItem) self?.playerLayer.player = self?.player self?.addProgressObserver() } } } }, exten: "mp4") } /// 取消加载 func cancelLoading() { CATransaction.begin() CATransaction.setDisableActions(true) playerLayer.isHidden = true CATransaction.commit() queryCacheOperation?.cancel() removeObserver() pause() player = nil playerItem = nil playerLayer.player = nil cancelLoadingQueue?.async { [weak self] in self?.task?.cancel() self?.task = nil self?.data = nil self?.response = nil for loadingRequest in self?.pendingRequests ?? [] { if !loadingRequest.isFinished { loadingRequest.finishLoading() } } self?.pendingRequests.removeAll() } } func play() { AVPlayerManager.shared().play(player: player!) } func pause() { AVPlayerManager.shared().pause(player: player!) } func replay() { AVPlayerManager.shared().replay(player: player!) } deinit { removeObserver() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 观察者 extension AVPlayerView { /// 监听播放器的状态 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "status" { if playerItem?.status == .readyToPlay { CATransaction.begin() CATransaction.setDisableActions(true) playerLayer.isHidden = false CATransaction.commit() } delegate?.onPlayItemStatusUpdate(status: playerItem?.status ?? AVPlayerItem.Status.unknown) } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } /// 监听播放进度 func addProgressObserver() { timeObserver = player?.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 1), queue: .main, using: { (time) in let current = CMTimeGetSeconds(time) let total = CMTimeGetSeconds(self.playerItem?.duration ?? CMTime.init()) if total == current { // 重新播放 self.replay() } self.delegate?.onProgressUpdate(current: CGFloat(current), total: CGFloat(total)) }) } /// 移除观察者 func removeObserver() { playerItem?.removeObserver(self, forKeyPath: "status") if let observer = timeObserver { player?.removeTimeObserver(observer) } } } // MARK: - sesstion 代理回调 视频下载缓存 extension AVPlayerView: URLSessionDelegate, URLSessionDataDelegate { /// 资源请求获取响应 func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { let httpResponse = dataTask.response as! HTTPURLResponse let code = httpResponse.statusCode if code == 200 { completionHandler(URLSession.ResponseDisposition.allow) self.data = Data() self.response = httpResponse self.progressPendingRequest() } else { completionHandler(URLSession.ResponseDisposition.cancel) } } /// 接收下载数据 func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { self.data?.append(data) self.progressPendingRequest() } /// 下载完成 func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if error == nil { WebCacheManager.shared().storeDataToDiskCache(data: self.data, key: self.cacheFilekey ?? "", exten: "mp4") } else { print("下载失败" + error.debugDescription) } } /// 获取网络缓存的数据 func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) { let cachedResponse = proposedResponse // 判断同一个下载地址及缓存方式是否本地 if dataTask.currentRequest?.cachePolicy == NSURLRequest.CachePolicy.reloadIgnoringLocalCacheData || dataTask.currentRequest?.url?.absoluteString == self.task?.currentRequest?.url?.absoluteString { completionHandler(nil) } else { completionHandler(cachedResponse) } } /// 下载进行中处理 request (处理下载数据等等) func progressPendingRequest() { var requestsCompleted = [AVAssetResourceLoadingRequest]() for loadingRequest in self.pendingRequests { let didRespondCompletely = respondWithDataForRequest(loadingRequest: loadingRequest) if didRespondCompletely { requestsCompleted.append(loadingRequest) loadingRequest.finishLoading() } } for completedRequest in requestsCompleted { if let index = pendingRequests.firstIndex(of: completedRequest) { pendingRequests.remove(at: index) } } } /// 拼接数据 func respondWithDataForRequest(loadingRequest: AVAssetResourceLoadingRequest) -> Bool { let mimeType = self.response?.mimeType ?? "" let contentType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType as CFString, nil) loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true loadingRequest.contentInformationRequest?.contentType = contentType?.takeRetainedValue() as String? loadingRequest.contentInformationRequest?.contentLength = (self.response?.expectedContentLength)! var startOffset: Int64 = loadingRequest.dataRequest?.requestedOffset ?? 0 if loadingRequest.dataRequest?.currentOffset != 0 { startOffset = loadingRequest.dataRequest?.currentOffset ?? 0 } if Int64(data?.count ?? 0) < startOffset { return false } let unreadBytes: Int64 = Int64(data?.count ?? 0) - startOffset let numberOfBytesToRespondWidth: Int64 = min(Int64(loadingRequest.dataRequest?.requestedLength ?? 0), unreadBytes) if let subdata = (data?.subdata(in: Int(startOffset)..<Int(startOffset + numberOfBytesToRespondWidth))) { loadingRequest.dataRequest?.respond(with: subdata) let endOffset: Int64 = startOffset + Int64(loadingRequest.dataRequest?.requestedLength ?? 0) return Int64(data?.count ?? 0) >= endOffset } return false } } // MARK: - AVAssetResourceLoaderDelegate(边下边播缓存代理回调) extension AVPlayerView: AVAssetResourceLoaderDelegate { func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { if task == nil { if let url = loadingRequest.request.url?.absoluteString.urlScheme(scheme: sourceScheme ?? "http") { let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60) task = session?.dataTask(with: request) task?.resume() } } pendingRequests.append(loadingRequest) return true } func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) { if let index = pendingRequests.firstIndex(of: loadingRequest) { pendingRequests.remove(at: index) } } } <file_sep>// // User.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/16. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class User: BaseModel { var id: Double? var userAvatar: UserAvatar? var lastName: String? var firstName: String? var isSystemUser: Bool? var sex: String? var startDate: Double? var status: String? var userGroup: UserGroup? var endDate: Double? var avatar: String? var language: String? var signatureInfo: String? var site: Site? var username: String? var defaultRole: String? var email: String? var displayName: String? var phoneNumber: String? } <file_sep>// // BaseRequest.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/13. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class BaseRequest: BaseModel { } <file_sep>// // VideoAssetLibraryCollectionViewCell.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/27. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class VideoAssetLibraryCollectionViewCell: UICollectionViewCell { let imageView = UIImageView() let durationLabel = UILabel() let selectionTip = UIImageView() override init(frame: CGRect) { super.init(frame: frame) self.imageView.frame = self.bounds self.imageView.contentMode = .scaleAspectFill self.imageView.clipsToBounds = true self.addSubview(self.imageView) self.selectionTip.frame = CGRect(x: 5, y: self.imageView.frame.height - 25, width: 20, height: 20) self.selectionTip.image = UIImage(named: "btn_circle") self.imageView.addSubview(self.selectionTip) self.durationLabel.frame = CGRect(x: 0, y: self.frame.height - 20, width: self.frame.width - 5, height: 20) self.durationLabel.textColor = .white self.durationLabel.textAlignment = .right self.addSubview(self.durationLabel) } override var isSelected: Bool { didSet { self.selectionTip.image = isSelected ? UIImage(named: "btn_selected") : UIImage(named: "btn_circle") } } func updateCellModel(model: PhotoModel) { if model.thumbnailImage != nil { self.imageView.image = model.thumbnailImage } else { PhotoAssetTool.shared().fetchThumbnailImage(asset: model.photoAsset!, size: self.bounds.size) { [weak self] (image) in self?.imageView.image = image model.thumbnailImage = image } } self.durationLabel.text = model.videoDuration } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>// // PersonalCollectionViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/17. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import JXPagingView enum PersonalListType { case mine case likes case notAudited } let personalCollectionCell = "PersonalCollectionViewCell" class PersonalCollectionViewController: BaseCollectionViewController { var listViewDidScrollCallBackBlock: ((UIScrollView) -> Void)? var listType = PersonalListType.mine override func viewDidLoad() { super.viewDidLoad() self.collectionView.register(PersonalCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: personalCollectionCell) self.requestCollectionData() } override func requestCollectionData() { var url = URLForMineCourse if self.listType == .likes { url = URLForMineCourseLike } else if self.listType == .notAudited { url = URLForMineCourseNotAudited } PersonalRequest.reqeustCourseList(url: url, page: self.pageNumber, size: self.pageSize, showHUD: true, success: { (data) in let response = data as? PersonalResponse let courseList = response?.data self.requestCollectionDataSuccess(array: courseList?.content ?? [Course](), dataTotal: courseList?.totalElements ?? 0) }) { (error) in self.requestNetDataFailed() } } deinit { listViewDidScrollCallBackBlock = nil } } extension PersonalCollectionViewController { override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let itemW: CGFloat = (collectionView.bounds.size.width - 8) / 4 return CGSize(width: itemW, height: itemW / 0.75) } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 2, left: 0, bottom: 2, right: 0) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 2 } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 2 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: personalCollectionCell, for: indexPath) as? PersonalCollectionViewCell cell?.setupCourse(course: self.collectionDataArray[indexPath.row] as! Course) return cell! } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } } extension PersonalCollectionViewController: JXPagingViewListViewDelegate { func listView() -> UIView { self.view } func listScrollView() -> UIScrollView { self.collectionView } func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) { self.listViewDidScrollCallBackBlock = callback } } <file_sep>// // Constants.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/11. // Copyright © 2019 dongjiawang. All rights reserved. // import Foundation import UIKit // MARK: - 请求地址 let BaseUrl: String = "http://ugcdev.qimooc.net/" /// 公共上传接口 let URLForUpload = "api/upload/file" /// 登录接口 let URLForLogin = "api/login" /// 首页登录后的列表 let URLForHomePageLearner = "api/learner/ugc/courses" /// 未登录 let URLForHomePageOpen = "api/open/ugc/courses" // MARK: - 个人中心接口 /// 我的作品 let URLForMineCourse = "/api/learner/ugc/courses/mine" /// 我喜欢的 let URLForMineCourseLike = "/api/learner/ugc/courses/mine/likes" /// 待审核 let URLForMineCourseNotAudited = "/api/learner/ugc/courses/mine/not-audited" /// 上传用户头像,需要后面拼接用户 id let URLForUploadUserAvatar = "/api/learner/user/avatar/" /// 更新用户信息 let URLForUpdateUserInfo = "/api/learner/user/info" // MARK: - 颜色 func RGBA(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) -> UIColor { return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a); } /// app主题色 let ColorTheme: UIColor = RGBA(r: 246, g: 124, b: 30, a: 1) /// 默认背景色 let ColorThemeBackground: UIColor = RGBA(r: 243, g: 245, b: 242, a: 1) <file_sep>// // MainPopMenuViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/17. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit typealias selectedAddType = (_ tag: Int) -> Void class MainPopMenuViewController: UIViewController { var butonArray = [UIButton]() let closeBtn = UIButton(type: .custom) var selectedAddTypeBlock: selectedAddType? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = .white self.initMenuBtns() DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.popMenuBtnAnimation(btnIndex: 0) } self.closeBtn.setImage(UIImage(named: "透明关闭"), for: .normal) self.closeBtn.addTarget(self, action: #selector(clickedCloseBtn), for: .touchUpInside) self.view.addSubview(self.closeBtn) self.closeBtn.snp.makeConstraints { (make) in make.centerX.equalTo(self.view) make.size.equalTo(CGSize(width: 44, height: 44)) make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(-44) } } func initMenuBtns() { let btnInfoArray = [["image": "AudioCourse", "title" : "音频"], // ["image": "ImageTextCourse", "title": "图文"], ["image": "VideoCourse", "title": "视频"]] let btnW: CGFloat = 100.0 let btnY: CGFloat = self.view.bounds.size.height - 230 let margin: CGFloat = (self.view.bounds.size.width - btnW * CGFloat(btnInfoArray.count)) / CGFloat(btnInfoArray.count + 1) var btnX = margin for i in 0..<btnInfoArray.count { let info = btnInfoArray[i] let btn = UIButton(type: .custom) btn.setTitle(info["title"], for: .normal) btn.setTitleColor(.darkText, for: .normal) btn.setImage(UIImage(named: info["image"]!), for: .normal) btn.frame = CGRect(x: btnX, y: btnY, width: btnW, height: btnW) btn.transform = CGAffineTransform.init(translationX: 0, y: self.view.bounds.size.height) btn.tag = 10000+i btn.addTarget(self, action: #selector(clickedMenuBtn(btn:)), for: .touchUpInside) self.setupBtnImageAndTitle(spacing: 5, btn: btn) self.butonArray.append(btn) self.view.addSubview(btn) btnX += (margin + btnW) } } @objc func clickedMenuBtn(btn: UIButton) { self.dismissSelf(animated: false) if selectedAddTypeBlock != nil { self.selectedAddTypeBlock!(btn.tag - 10000) } } func setupBtnImageAndTitle(spacing: CGFloat, btn: UIButton) { let imageSize = btn.imageView?.frame.size var titleSize = btn.titleLabel?.frame.size let string = btn.titleLabel?.text ?? "" let textSize = string.boundingRect(with: .zero, options: .usesFontLeading, attributes: [NSAttributedString.Key.font: btn.titleLabel?.font as Any], context: nil) let frameSize = CGSize.init(width: CGFloat(ceilf(Float(textSize.width))), height: CGFloat(ceilf(Float(textSize.height)))) if (titleSize!.width + 0.5 < frameSize.width) { titleSize?.width = frameSize.width } let totalHeight = ((imageSize?.height ?? 0) + (titleSize?.height ?? 0) + spacing) btn.imageEdgeInsets = UIEdgeInsets(top: -(totalHeight - (imageSize?.height ?? 0)), left: 0, bottom: 0, right: -(titleSize?.width ?? 0)) btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: -(imageSize?.width ?? 0), bottom: -(totalHeight - (titleSize?.height ?? 0)), right: 0) } func popMenuBtnAnimation(btnIndex: Int) { UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseIn, animations: { let btn = self.butonArray[btnIndex] btn.transform = CGAffineTransform.identity }) { (finished) in if (btnIndex < (self.butonArray.count - 1)) { self.popMenuBtnAnimation(btnIndex: btnIndex + 1) } } } @objc func clickedCloseBtn() { self.dismissSelf(animated: true) } func dismissSelf(animated: Bool) { if animated { UIView.animate(withDuration: 0.3) { self.closeBtn.transform = CGAffineTransform.init(rotationAngle: CGFloat(-Double.pi / 4)) } } else { self.closeBtn.transform = CGAffineTransform.init(rotationAngle: CGFloat(-Double.pi / 4)) } self.dismissMenuBtnAnimation(animated: animated) } func dismissMenuBtnAnimation(animated: Bool) { if animated { UIView.animate(withDuration: 0.3, animations: { for menuBtn in self.butonArray { menuBtn.transform = CGAffineTransform.init(translationX: 0, y: self.view.bounds.size.height) } }) { (finished) in self.dismiss(animated: true, completion: nil) } } else { for menuBtn in self.butonArray { menuBtn.transform = CGAffineTransform.init(translationX: 0, y: self.view.bounds.size.height) } self.dismiss(animated: true, completion: nil) } } } <file_sep>// // UserAvatar.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/16. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class UserAvatar: BaseModel { var id: Double? var owner: Double? var fileName: String? var contentType: String? var avatarType: String? var isSystemAvatar: Bool? } <file_sep>// // BaseModel.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/13. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import HandyJSON class BaseModel: NSObject, HandyJSON { required override init() { } } <file_sep>// // HomePageTableViewCell.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/16. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import AVKit import Kingfisher typealias OnPlayerReady = () -> Void class HomePageTableViewCell: UITableViewCell { var playerView: AVPlayerView = AVPlayerView() var coverImageView: UIImageView = UIImageView() var pauseIcon: UIImageView = UIImageView() var userIcon: UIButton = UIButton(type: .custom) var likeBtn: UIButton = UIButton(type: .custom) var likesCountLabel: UILabel = UILabel() var messageBtn: UIButton = UIButton(type: .custom) var messageCountLabel: UILabel = UILabel() var playerStatusBar: UIView = UIView() var titleLabel: UILabel = UILabel() var introlLabel: UILabel = UILabel() var isPlayerReady = false var _rate: CGFloat? var onPlayerReady: OnPlayerReady? var courseModel: Course? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none self.backgroundColor = .clear self.contentView.addSubview(self.coverImageView) self.coverImageView.snp.makeConstraints { (make) in make.edges.equalTo(self.contentView) } self.playerView.delegate = self self.playerView.backgroundColor = .clear self.contentView.addSubview(self.playerView) self.playerView.snp.makeConstraints { (make) in make.edges.equalTo(self.contentView) } self.pauseIcon.image = UIImage(named: "Homepage_play_pause") self.pauseIcon.contentMode = .center self.pauseIcon.layer.zPosition = 3 self.pauseIcon.isHidden = true self.contentView.addSubview(self.pauseIcon) self.pauseIcon.snp.makeConstraints { (make) in make.center.equalTo(self.contentView) make.size.equalTo(CGSize(width: 100, height: 100)) } self.messageBtn.setImage(UIImage(named: "HomePageMessage"), for: .normal) self.messageBtn.addTarget(self, action: #selector(clickedMessageBtn), for: .touchUpInside) self.contentView.addSubview(self.messageBtn) self.messageBtn.snp.makeConstraints { (make) in make.size.equalTo(CGSize(width: 44, height: 44)) make.right.equalTo(-10) make.bottom.equalTo(-120) } self.messageCountLabel.textAlignment = .center self.messageCountLabel.font = UIFont.systemFont(ofSize: 12) self.messageCountLabel.textColor = .white self.contentView.addSubview(self.messageCountLabel) self.messageCountLabel.snp.makeConstraints { (make) in make.top.equalTo(self.messageBtn.snp.bottom) make.height.equalTo(20) make.centerX.equalTo(self.messageBtn) } self.likeBtn.setImage(UIImage(named: "HomePageLike_normal"), for: .normal) self.likeBtn.setImage(UIImage(named: "HomePageLike_selected"), for: .selected) self.likeBtn.addTarget(self, action: #selector(clickedLikeBtn), for: .touchUpInside) self.contentView.addSubview(self.likeBtn) self.likeBtn.snp.makeConstraints { (make) in make.size.right.equalTo(self.messageBtn) make.bottom.equalTo(self.messageBtn.snp.top).offset(-20) } self.likesCountLabel.textAlignment = .center self.likesCountLabel.font = UIFont.systemFont(ofSize: 12) self.likesCountLabel.textColor = .white self.contentView.addSubview(self.likesCountLabel) self.likesCountLabel.snp.makeConstraints { (make) in make.top.equalTo(self.likeBtn.snp.bottom) make.height.equalTo(20) make.centerX.equalTo(self.likeBtn) } self.userIcon.setImage(UIImage(named: "userIcon"), for: .normal) self.userIcon.clipsToBounds = true self.userIcon.layer.cornerRadius = 22 self.userIcon.addTarget(self, action: #selector(clickedUserIcon), for: .touchUpInside) self.contentView.addSubview(self.userIcon) self.userIcon.snp.makeConstraints { (make) in make.size.right.equalTo(self.messageBtn) make.bottom.equalTo(self.likeBtn.snp.top).offset(-20) } self.playerStatusBar.backgroundColor = .white self.playerStatusBar.isHidden = true self.contentView.addSubview(self.playerStatusBar) self.playerStatusBar.snp.makeConstraints { (make) in make.centerX.equalTo(self.contentView) make.bottom.equalTo(self.contentView).offset(-0.5) make.width.equalTo(self.contentView) make.height.equalTo(0.5) } self.introlLabel.textColor = .white self.introlLabel.font = UIFont.systemFont(ofSize: 12) self.introlLabel.numberOfLines = 3 self.contentView.addSubview(self.introlLabel) self.introlLabel.snp.makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(-100) make.bottom.equalTo(self.messageCountLabel).offset(-5) make.height.greaterThanOrEqualTo(30) } self.titleLabel.textColor = .white self.titleLabel.font = UIFont.boldSystemFont(ofSize: 16) self.contentView.addSubview(self.titleLabel) self.titleLabel.snp.makeConstraints { (make) in make.left.right.equalTo(self.introlLabel) make.bottom.equalTo(self.introlLabel.snp.top).offset(-5) make.height.greaterThanOrEqualTo(20) } } func initWithData(data: Course) { self.courseModel = data self.introlLabel.text = data.intro self.titleLabel.text = data.user?.displayName self.coverImageView.kf.setImage(with: data.imageUrl?.splicingRequestURL()) self.playerView.setPlayerSourceUrl(url: data.chapter?.startingUrl?.splicingRequestURLString()) let array = data.chapter?.videoRatio?.components(separatedBy: "*") guard let width = Int(array?.first ?? "0"), let height = Int(array?.last ?? "0") else { self.playerView.setPlayerVideoGravity(videoGravity: .resizeAspectFill) return } if (width > height) { //error here self.playerView.setPlayerVideoGravity(videoGravity: .resizeAspect) } else { self.playerView.setPlayerVideoGravity(videoGravity: .resizeAspectFill) } self.userIcon.kf.setImage(with: data.user?.avatar?.splicingRequestURL(), for: .normal, placeholder: UIImage(named: "userIcon")) self.likeBtn.isSelected = data.isLiked ?? false self.likesCountLabel.text = data.likeCountString self.messageCountLabel.text = "\(data.commentCount ?? 0)" self.pauseIcon.isHidden = true self.startLoadingPlayItemAnimation(isStart: true) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepareForReuse() { super.prepareForReuse() self.playerView.cancelLoading() } } // MARK: - 播放器 extension HomePageTableViewCell { func play() { self.playerView.play() } func pause() { self.playerView.pause() } func replay() { self.playerView.replay() } var rate: CGFloat? { get { return _rate } set { _rate = newValue } } } // MARK: - 按钮点击 extension HomePageTableViewCell { @objc func clickedMessageBtn() { } @objc func clickedLikeBtn() { } @objc func clickedUserIcon() { } /// 暂停按钮的动画 func showPauseViewAnimation(rate: CGFloat) { if rate == 0 { UIView.animate(withDuration: 0.25, animations: { self.pauseIcon.alpha = 0 }) { (finished) in self.pauseIcon.isHidden = true } } else { self.pauseIcon.isHidden = false self.pauseIcon.transform = CGAffineTransform(scaleX: 1.8, y: 1.8) self.pauseIcon.alpha = 1 UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseIn, animations: { self.pauseIcon.transform = CGAffineTransform(scaleX: 1, y: 1) }) { (finished) in } } } /// 加载视频动画 func startLoadingPlayItemAnimation(isStart: Bool) { if isStart { self.playerStatusBar.backgroundColor = .white self.playerStatusBar.isHidden = false self.playerStatusBar.layer.removeAllAnimations() let animationGroup = CAAnimationGroup() animationGroup.duration = 0.8 animationGroup.beginTime = CACurrentMediaTime() + 0.5 animationGroup.repeatCount = MAXFLOAT animationGroup.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) let scaleAnimation = CABasicAnimation() scaleAnimation.keyPath = "transform.scale.x" scaleAnimation.fromValue = 1.0 scaleAnimation.toValue = 1.0 * self.bounds.size.width let alphaAnimation = CABasicAnimation() alphaAnimation.keyPath = "opacity" alphaAnimation.fromValue = 1.0 alphaAnimation.toValue = 0.5 animationGroup.animations = [scaleAnimation, alphaAnimation] self.playerStatusBar.layer.add(animationGroup, forKey: nil) } else { self.playerStatusBar.layer.removeAllAnimations() self.playerStatusBar.isHidden = true } } } extension HomePageTableViewCell: AVPlayerViewDelegate { func onProgressUpdate(current: CGFloat, total: CGFloat) { } func onPlayItemStatusUpdate(status: AVPlayerItem.Status) { switch status { case .unknown: self.startLoadingPlayItemAnimation(isStart: true) case .readyToPlay: self.startLoadingPlayItemAnimation(isStart: false) self.isPlayerReady = true onPlayerReady?() case .failed: self.startLoadingPlayItemAnimation(isStart: false) WMHUD.textHUD(text: "加载失败", delay: 1) default: break } } } <file_sep>// // LoginView.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/17. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit typealias beginLogin = (_ name: String, _ pwd: String) -> Void class LoginView: UIView { var userImage = UIImageView() var nameTextField = UITextField() var pwdTextField = UITextField() var loginBtn = UIButton(type: .custom) var forgotBtn = UIButton(type: .custom) var beginLoginBlock: beginLogin? override init(frame: CGRect) { super.init(frame: frame) self.userImage.clipsToBounds = true self.userImage.layer.cornerRadius = 10 self.userImage.image = UIImage(named: "userIcon") self.addSubview(self.userImage) self.userImage.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.size.equalTo(CGSize(width: 70, height: 70)) make.top.equalTo(150) } let tip = UILabel() tip.text = "使用移动学习账号登录" tip.font = UIFont.systemFont(ofSize: 14) tip.textAlignment = .center self.addSubview(tip) tip.snp.makeConstraints { (make) in make.top.equalTo(self.userImage.snp.bottom).offset(30) make.left.right.equalTo(0) make.height.equalTo(30) } self.nameTextField.backgroundColor = .white self.nameTextField.delegate = self self.nameTextField.font = UIFont.systemFont(ofSize: 14) self.nameTextField.placeholder = "请输入用户名" self.nameTextField.textColor = .darkText self.nameTextField.returnKeyType = .done self.nameTextField.textAlignment = .center self.nameTextField.autocorrectionType = .no self.nameTextField.autocapitalizationType = .none self.nameTextField.addTarget(self, action: #selector(nameTextFieldChanged), for: .editingChanged) self.addSubview(self.nameTextField) self.nameTextField.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.top.equalTo(self.userImage.snp.bottom).offset(120) make.left.equalTo(30) make.right.equalTo(-30) make.height.equalTo(44) } self.pwdTextField.backgroundColor = .white self.pwdTextField.delegate = self self.pwdTextField.font = UIFont.systemFont(ofSize: 14) self.pwdTextField.placeholder = "请输入用户密码" self.pwdTextField.textColor = .darkText self.pwdTextField.returnKeyType = .done self.pwdTextField.isSecureTextEntry = true self.pwdTextField.textAlignment = .center self.addSubview(self.pwdTextField) self.pwdTextField.snp.makeConstraints { (make) in make.left.right.centerX.height.equalTo(self.nameTextField) make.top.equalTo(self.nameTextField.snp.bottom).offset(1) } self.loginBtn.setTitle("登 录", for: .normal) self.loginBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16) self.loginBtn.setTitleColor(.white, for: .normal) self.loginBtn.backgroundColor = ColorTheme self.loginBtn.clipsToBounds = true self.loginBtn.layer.cornerRadius = 5 self.loginBtn.addTarget(self, action: #selector(clickedLoginBtn), for: .touchUpInside) self.addSubview(self.loginBtn) self.loginBtn.snp.makeConstraints { (make) in make.left.right.equalTo(self.pwdTextField) make.top.equalTo(self.pwdTextField.snp.bottom).offset(50) make.height.equalTo(44) } self.forgotBtn.setTitle("忘记密码", for: .normal) self.forgotBtn.setTitleColor(.lightGray, for: .normal) self.forgotBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16) self.forgotBtn.contentHorizontalAlignment = .right self.forgotBtn.addTarget(self, action: #selector(clickedForgetBtn), for: .touchUpInside) self.addSubview(self.forgotBtn) self.forgotBtn.snp.makeConstraints { (make) in make.right.equalTo(self.loginBtn) make.top.equalTo(self.loginBtn.snp.bottom) make.size.equalTo(CGSize(width: 100, height: 30)) } } @objc func clickedLoginBtn() { self.endEditing(true) let name = self.nameTextField.text?.replacingOccurrences(of: " ", with: "") ?? "" let pwd = self.pwdTextField.text?.replacingOccurrences(of: " ", with: "") ?? "" if name.count == 0 { WMHUD.textHUD(text: "请输入用户名", delay: 1) return } if pwd.count == 0 { WMHUD.textHUD(text: "请输入用户密码", delay: 1) return } if beginLoginBlock != nil { beginLoginBlock!(name, pwd) } } @objc func clickedForgetBtn() { } @objc func nameTextFieldChanged() { self.pwdTextField.text = "" } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension LoginView: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.clickedLoginBtn() return true } } <file_sep>// // UIDevice+.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/18. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import WebKit import Kingfisher extension UIDevice { func isiPhoneXMore() -> Bool { var isMore = false isMore = UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0.0 > CGFloat(0) return isMore } func clearCookie() { URLCache.shared.removeAllCachedResponses() WKWebsiteDataStore.default().removeData(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(), modifiedSince: Date.init(timeIntervalSince1970: 0)) { } } func clearImageCache() { ImageCache.default.clearDiskCache() ImageCache.default.clearMemoryCache() } func getAudioCachePath() -> String { let documentPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first return (documentPath?.appending("AudioCache"))! } func clearTmpDirectory() { let tmpDirectoryArray = try! FileManager.default.contentsOfDirectory(atPath: NSTemporaryDirectory()) for file in tmpDirectoryArray { let removePath = "\(NSTemporaryDirectory())\(file)" try! FileManager.default.removeItem(atPath: removePath) } } func folderSizeAtPath(folderPath: String) -> Double { var folderSize: Double = 0 let manager = FileManager.default if manager.fileExists(atPath: folderPath) == false {return 0} guard let childFilesEnumerator = manager.subpaths(atPath: folderPath)?.enumerated() else { return 0 } for fileName in childFilesEnumerator { let fileAbsolutePath = folderPath.appending("/\(fileName)") folderSize += UIDevice.current.fileSizeAtPath(filePath: fileAbsolutePath) } return folderSize } func fileSizeAtPath(filePath: String) -> Double { let manager = FileManager.default if manager.fileExists(atPath: filePath) { return try! manager.attributesOfItem(atPath: filePath)[FileAttributeKey.size] as! Double } return 0 } } <file_sep>// // UIImage+.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/12. // Copyright © 2019 dongjiawang. All rights reserved. // import Foundation import UIKit extension UIImage { func fixOrientation() -> UIImage? { guard self.imageOrientation == .up else { return self } let transForm = CGAffineTransform.identity switch self.imageOrientation { case .down, .downMirrored: transForm.translatedBy(x: self.size.width, y: self.size.height) transForm.rotated(by: CGFloat(Double.pi)) case .left, .leftMirrored: transForm.translatedBy(x: self.size.width, y: 0) transForm.rotated(by: CGFloat(Double.pi / 2)) case .right, .rightMirrored: transForm.translatedBy(x: 0, y: self.size.height) transForm.rotated(by: CGFloat(-Double.pi / 2)) default: break } switch self.imageOrientation { case .upMirrored, .downMirrored: transForm.translatedBy(x: self.size.width, y: 0) transForm.scaledBy(x: -1, y: 1) case .leftMirrored, .rightMirrored: transForm.translatedBy(x: self.size.height, y: 0) transForm.scaledBy(x: -1, y: 1) default: break } let content = CGContext.init(data: nil, width: Int(self.size.width), height: Int(self.size.height), bitsPerComponent: 0, bytesPerRow: 0, space: (self.cgImage?.colorSpace!)!, bitmapInfo: (self.cgImage?.bitmapInfo)!.rawValue) content?.concatenate(transForm) switch self.imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: content?.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: self.size.height, height: self.size.width)) default: content?.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)) } let cgImage = content?.makeImage()! content?.flush() return UIImage(cgImage: cgImage!) } } <file_sep>// // VideoCutViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2020/1/3. // Copyright © 2020 dongjiawang. All rights reserved. // import UIKit import AVKit class VideoCutViewController: UIVideoEditorController { var stopFindMovieScrubberView = false var stopFindOverlayView = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. startRelayoutOverLayView() startRelayoutMovieView() } func startRelayoutOverLayView() { if stopFindOverlayView {return} hiddenOverlayView(view: self.view) DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: UInt64(0.01))) { self.startRelayoutOverLayView() } } func startRelayoutMovieView() { if stopFindMovieScrubberView {return} relayoutCollectionView(view: self.view) DispatchQueue.main.asyncAfter(deadline: DispatchTime.init(uptimeNanoseconds: UInt64(0.01))) { self.startRelayoutMovieView() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationBar.isTranslucent = false self.navigationBar.barTintColor = ColorTheme self.navigationBar.tintColor = .white self.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white] changeBottomToolBarColor(view: self.view) } func relayoutCollectionView(view: UIView) { if stopFindMovieScrubberView {return} for subView in view.subviews { if subView.isKind(of: NSClassFromString("UIMovieScrubber")!) { stopFindMovieScrubberView = true subView.superview?.snp.makeConstraints({ (make) in make.bottom.equalTo(-100) make.size.equalTo((subView.superview?.snp.size)!) make.height.equalTo(subView.superview!.snp.height) }) return } relayoutCollectionView(view: subView) } } func hiddenOverlayView(view: UIView) { if stopFindOverlayView {return} for subView in view.subviews { if subView.isKind(of: NSClassFromString("PLVideoEditingOverlayView")!) { stopFindOverlayView = true subView.snp.makeConstraints { (make) in make.top.equalTo(self.navigationBar.snp.bottom).offset(20) make.centerX.equalTo(0) make.size.equalTo(subView.snp.size) } return } hiddenOverlayView(view: subView) } } func changeBottomToolBarColor(view: UIView) { for subView in view.subviews { if subView.isKind(of: NSClassFromString("UIToolbar")!) { let toolbar = subView as! UIToolbar toolbar.barTintColor = ColorTheme toolbar.tintColor = .white } changeBottomToolBarColor(view: subView) } } } <file_sep>// // SettingViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/24. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class SettingViewController: BaseTableViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "设置" self.noRefresh = true self.noLoadMore = true let quitBtn = UIButton(type: .custom) quitBtn.setTitle("退出", for: .normal) quitBtn.backgroundColor = ColorTheme quitBtn.setTitleColor(.white, for: .normal) quitBtn.clipsToBounds = true quitBtn.layer.cornerRadius = 4 quitBtn.addTarget(self, action: #selector(clickedQuiBtn), for: .touchUpInside) self.view.addSubview(quitBtn) quitBtn.snp.makeConstraints { (make) in make.bottom.equalTo(self.view.safeAreaLayoutGuide).offset(-50) make.width.equalTo(300) make.height.equalTo(44) make.centerX.equalTo(self.view) } self.tableView.isScrollEnabled = false self.tableView.separatorStyle = .singleLine self.tableView.tableFooterView = UIView() self.tableView.snp.remakeConstraints { (make) in make.top.equalTo(self.view.safeAreaLayoutGuide) make.left.right.equalToSuperview() make.bottom.equalTo(quitBtn.snp.top).offset(-50) } } @objc func clickedQuiBtn() { let alertVC = UIAlertController(title: "提示", message: "确定退出账号?", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) let confirAction = UIAlertAction(title: "确定", style: .default) { (action) in UIDevice.current.clearCookie() user = nil isLogin = false let rootVC = self.navigationController?.viewControllers.first as! MainTabBarViewController rootVC.resetMainTabVC() self.navigationController?.popToRootViewController(animated: true) } alertVC.addAction(cancelAction) alertVC.addAction(confirAction) self.present(alertVC, animated: true, completion: nil) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cacheCell = UITableViewCell(style: .value1, reuseIdentifier: "cache") cacheCell.textLabel?.text = "清除缓存" cacheCell.selectionStyle = .none var cacheSize: Double = UIDevice.current.folderSizeAtPath(folderPath: UIDevice.current.getAudioCachePath()) cacheSize += UIDevice.current.folderSizeAtPath(folderPath: NSTemporaryDirectory()) var resultSize = cacheSize / 1024 // 小数位最少位数 if resultSize < 1024 { cacheCell.detailTextLabel?.text = String(format: "%.1i KB", resultSize) } else { resultSize = resultSize / 1024 cacheCell.detailTextLabel?.text = String(format: "%.1i MB", resultSize) } return cacheCell } let versionCell = UITableViewCell(style: .value1, reuseIdentifier: "version") versionCell.textLabel?.text = "关于小书客" versionCell.selectionStyle = .none let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String versionCell.detailTextLabel?.text = "V\(String(describing: version))" return versionCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 0 { UIDevice.current.clearImageCache() UIDevice.current.clearTmpDirectory() WMHUD.progressHUD(text: nil, subText: "清除缓存中") DispatchQueue.main.asyncAfter(deadline: .now() + 1) { WMHUD.hideHUD() tableView.reloadData() } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) } } <file_sep>// // PhotoModel.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/25. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import Photos class PhotoModel: NSObject { var videoAsset: AVAsset? var videoUrlAsset: AVURLAsset? var isSelected = false var unAble = false var localIdentifiter: String? var videoDuration: String? var thumbnailImage: UIImage? var originalImage: UIImage? var photoAsset: PHAsset? { willSet { if newValue!.mediaType == .video { self.videoDuration = self.calculateVideoTime(duration: newValue!.duration) } } } func calculateVideoTime(duration: TimeInterval) -> String { let hours = Int(duration / 3600) let minutes = Int((duration.truncatingRemainder(dividingBy: 3600)) / 60) let seconds = Int(duration.truncatingRemainder(dividingBy: 60)) if hours > 0 { return String(format: "%i:%02i:%02i", hours, minutes, seconds) } else { return String(format: "%02i:%02i", minutes, seconds) } } } <file_sep>// // Site.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/16. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class Site: BaseModel { var loginBanner: String? var shortName: String? var id: Double? var anonymousAccess: Bool? var loginWithCurrentSite: String? var siteDescripation: String? var name: String? var logo: String? } <file_sep>// // UIColor+.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/12. // Copyright © 2019 dongjiawang. All rights reserved. // import Foundation import UIKit extension UIColor { func drawToImage(size: CGSize) -> UIImage? { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) var image: UIImage? = nil UIGraphicsBeginImageContextWithOptions(size, false, 1) guard let content = UIGraphicsGetCurrentContext() else { return image } content.setFillColor(self.cgColor) content.fill(rect) image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } public convenience init?(hex: String) { let r, g, b, a: CGFloat if hex.hasPrefix("#") { let start = hex.index(hex.startIndex, offsetBy: 1) let hexColor = String(hex[start...]) if hexColor.count == 8 { let scanner = Scanner(string: hexColor) var hexNumber: UInt64 = 0 if scanner.scanHexInt64(&hexNumber) { r = CGFloat((hexNumber & 0xff000000) >> 24) / 255 g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 a = CGFloat(hexNumber & 0x000000ff) / 255 self.init(red: r, green: g, blue: b, alpha: a) return } } } return nil } } <file_sep>// // WebCombineOperation.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/12. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class WebCombineOperation: NSObject { /// 取消下载后回调 var cancelBlock: WebDownloaderCancelBlock? /// 查询缓存任务 var cacheOperation: Operation? /// 下载任务 var downloadOperation: WebDownloadOperation? func cancel() { if cacheOperation != nil { cacheOperation?.cancel() cacheOperation = nil } if downloadOperation != nil { downloadOperation?.cancel() downloadOperation = nil } if cancelBlock != nil { cancelBlock?() cancelBlock = nil } } } <file_sep>// // TemplateBuildViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/27. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class TemplateBuildViewController: BaseViewController { let templateBuildView = TemplateBuildView() var templateColorCollectionView: UICollectionView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "选择讲稿模板" let leftItem = UIBarButtonItem(title: "上一步", style: .plain, target: self, action: #selector(back)) leftItem.tintColor = .white self.navigationItem.leftBarButtonItem = leftItem let rightItem = UIBarButtonItem(title: "保存", style: .done, target: self, action: #selector(navigationRightItemClicked)) rightItem.tintColor = .white self.navigationItem.rightBarButtonItem = rightItem self.templateBuildView.contentImageView.image = UIImage(named: "1") self.view.addSubview(self.templateBuildView) self.templateBuildView.snp.makeConstraints { (make) in make.width.centerX.equalTo(self.view) make.top.equalTo(self.view.safeAreaLayoutGuide) make.height.equalTo(self.view.snp.height).multipliedBy(0.5).offset(-32) } let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: 44, height: 44) layout.minimumLineSpacing = 20 layout.minimumInteritemSpacing = 5 layout.sectionInset = UIEdgeInsets(top: 20, left: 15, bottom: 20, right: 15) layout.scrollDirection = .horizontal self.templateColorCollectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) self.templateColorCollectionView?.backgroundColor = .clear self.templateColorCollectionView?.delegate = self self.templateColorCollectionView?.dataSource = self self.templateColorCollectionView?.register(TemplateCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "TemplateCollectionViewCell") self.view.addSubview(self.templateColorCollectionView!) self.templateColorCollectionView!.snp.makeConstraints { (make) in make.width.centerX.equalTo(self.view) make.top.equalTo(self.templateBuildView.snp.bottom).offset(10) make.height.equalTo(50) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.templateBuildView.textView.becomeFirstResponder() } typealias finishInitTemplate = (_ photoModel: PhotoModel) -> Void var finishInitTemplateBlock: finishInitTemplate? @objc func navigationRightItemClicked() { self.templateBuildView.finishedTemplateBuild { [weak self] (model) in if self!.finishInitTemplateBlock != nil { self!.finishInitTemplateBlock!(model) } } } } extension TemplateBuildViewController: UICollectionViewDelegate, UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 20 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TemplateCollectionViewCell", for: indexPath) as! TemplateCollectionViewCell cell.imageView.image = UIImage(named: "\(indexPath.row + 1)") return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! TemplateCollectionViewCell self.templateBuildView.contentImageView.image = cell.imageView.image self.templateBuildView.endEditing(true) } } // MARK: - CollectionViewCell class TemplateCollectionViewCell: UICollectionViewCell { let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .clear self.imageView.frame = self.bounds imageView.contentMode = .scaleAspectFit self.addSubview(imageView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>// // AVPlayerManager.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/13. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import AVKit class AVPlayerManager: NSObject { var playerArray = [AVPlayer]() private static let instance = {() -> AVPlayerManager in return AVPlayerManager.init() }() private override init() { super.init() } class func shared() -> AVPlayerManager { return instance } static func setAudioMode() { do { try! AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback) try AVAudioSession.sharedInstance().setActive(true) } catch { print("设置音频模式错误:" + error.localizedDescription) } } func play(player: AVPlayer) { for object in playerArray { object.pause() } if !playerArray.contains(player) { playerArray.append(player) } player.play() } func pause(player: AVPlayer) { if playerArray.contains(player) { player.pause() } } func pauseAll() { for object in playerArray { object.pause() } } func replay(player: AVPlayer) { for object in playerArray { object.pause() } if playerArray.contains(player) { player.seek(to: .zero) play(player: player) } else { play(player: player) } } } <file_sep>// // CourseContentModel.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/16. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class Course: BaseModel { var id: Double? var likeCount: Double = 0 // var likeCountString: String? var intro: String? var lastModifiedDate: Double? var chapter: Chapter? var createdDate: Double? var imageUrl: String? var isPublic: Bool? var viewCount: Double? var commentAgentId: Double? var commentCount: Double? var isLiked: Bool? var hotNum: Double? var user: User? var name: String? var likeCountString: String { get { if self.likeCount > 10000 { return "\((self.likeCount) / 10000)w" } else { return "\(self.likeCount)" } } } } <file_sep>// // WebDoanloader.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/12. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class WebDoanloader: NSObject { var downloadQueue: OperationQueue? private static let instance = { () -> WebDoanloader in return WebDoanloader.init() }() class func shared() -> WebDoanloader { return instance } /// 下载资源数据 func download(url: URL, progress: @escaping WebDownloaderProgressBlock, completed: @escaping WebDownloaderCompletedBlock, cancel: @escaping WebDownloaderCancelBlock) -> WebCombineOperation { // 创建数据请求 var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15) request.httpShouldUsePipelining = true // 使用url做数据到key 值 let key = url.absoluteString // 创建下载进程 let operation = WebCombineOperation.init() // 先获取是否本地缓存 operation.cacheOperation = WebCacheManager.shared().queryDataFromMemory(key: key, cacheQueryCompletedBlock: { [weak self] (data, hasCache) in if hasCache { completed(data as? Data, nil, true) } else { // 没有本地缓存,开启下载进程 let downloadOperation = WebDownloadOperation.init(request: request, progress: progress, compeleted: { (data, error, finished) in if finished && error == nil { // 下载完成,保存数据 WebCacheManager.shared().storeDataCache(data: data, key: key) completed(data, nil, true) } else { completed(data, error, false) } }, cancel: { cancel() }) operation.downloadOperation = downloadOperation self?.downloadQueue?.addOperation(downloadOperation) } }) return operation } } <file_sep>// // BaseViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/11. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class BaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = ColorThemeBackground // 防止返回手势失效 self.navigationController?.interactivePopGestureRecognizer?.delegate = self as? UIGestureRecognizerDelegate initNavigationBarTransparent() } func initNavigationBarTransparent() { setNavigationBarTitleColor(color: UIColor.white) setNavigationBarTintColor(color: UIColor.white) setNavigationBarBarTintColor(color: ColorTheme) initLeftBarButton() setBackgroundColor(color: ColorThemeBackground) self.navigationController?.navigationBar.isTranslucent = false } func initLeftBarButton() { let leftItem = UIBarButtonItem(image: UIImage(systemName: "chevron.left"), style: .plain, target: self, action: #selector(back)) self.navigationItem.leftBarButtonItem = leftItem } func setBackgroundColor(color: UIColor) { self.view.backgroundColor = color } func setNavigationBarTitleColor(color: UIColor) { self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: color] } func setNavigationBarBarTintColor(color: UIColor) { self.navigationController?.navigationBar.barTintColor = color } func setNavigationBarTintColor(color: UIColor) { self.navigationController?.navigationBar.tintColor = color } func setNavigationBarBackgroundColor(color: UIColor) { self.navigationController?.navigationBar.backgroundColor = color } func setNavigationBarBaclgroundImage(image: UIImage) { self.navigationController?.navigationBar.setBackgroundImage(image, for: .default) } func setNavigationBarShadowImage(image: UIImage) { self.navigationController?.navigationBar.shadowImage = image } @objc func back() { self.navigationController?.popViewController(animated: true) if (self.navigationController != nil && (self.navigationController?.children.count)! > 1) { self.navigationController?.popViewController(animated: true) } else { self .dismiss(animated: true, completion: nil) } } func navigationBarHeight() -> CGFloat { return self.navigationController?.navigationBar.frame.size.height ?? 0 } func setLeftButton(imageName: String) { let leftItem = UIBarButtonItem(image: UIImage(named: imageName), style: .plain, target: self, action: #selector(back)) leftItem.tintColor = UIColor.white self.navigationItem.leftBarButtonItem = leftItem } } <file_sep>// // PersonalCollectionViewCell.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/18. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class PersonalCollectionViewCell: UICollectionViewCell { var imageView: UIImageView! var likeTip: UIImageView! var likesLabel: UILabel! var lockImage: UIImageView! override init(frame: CGRect) { super.init(frame: frame) self.imageView = UIImageView(frame: self.bounds) self.imageView.contentMode = .scaleAspectFill self.imageView.clipsToBounds = true self.contentView.addSubview(self.imageView) self.likeTip = UIImageView(frame: CGRect(x: 5, y: frame.size.height - 20, width: 15, height: 15)) self.likeTip.image = UIImage(named: "HomePageLike_normal") self.contentView.addSubview(self.likeTip) self.likesLabel = UILabel(frame: CGRect(x: self.likeTip.frame.origin.x + 20, y: self.likeTip.frame.origin.y - 2.5, width: frame.size.width - 35, height: 20)) self.likesLabel.textColor = .white self.likesLabel.font = UIFont.systemFont(ofSize: 14) self.contentView.addSubview(self.likesLabel) self.lockImage = UIImageView(frame: CGRect(x: frame.size.width - 20, y: frame.size.height - 20, width: 15, height: 15)) self.lockImage.isHidden = true self.lockImage.image = UIImage(named: "icon_not_public") self.contentView.addSubview(self.lockImage) } func setupCourse(course: Course) { self.imageView.kf.setImage(with: course.imageUrl?.splicingRequestURL(), placeholder: UIImage(named: "courseDefaultListStand")) self.likesLabel.text = course.likeCountString self.lockImage.isHidden = course.isPublic ?? true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>// // Chapter.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/16. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class Chapter: BaseModel { var id: Double? var intro: String? var fileName: String? var digest: String? var lastModifiedDate: String? var fileSize: Double? var zipFileName: String? var createData: Double? var imageUrl: String? var title: String? var type: String? var enterFileName: String? var originFieldName: String? var duration: String? var childSeq: String? var startingUrl: String? var videoRatio: String? } <file_sep>// // VideoEditViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2020/1/3. // Copyright © 2020 dongjiawang. All rights reserved. // import UIKit class VideoEditViewController: UIViewController { var videoURL: String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } } <file_sep>source 'https://mirrors.tuna.tsinghua.edu.cn/git/CocoaPods/Specs.git' # Uncomment the next line to define a global platform for your project platform :ios, '13.0' target 'WorkMarker-swift' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! # 忽略引入库的所有警告 inhibit_all_warnings! # Pods for WorkMarker-swift pod 'SwiftyUserDefaults' pod 'HandyJSON' pod 'Kingfisher' pod 'ReachabilitySwift' pod 'SnapKit' pod 'PKHUD' pod 'WCDB.swift' pod 'Alamofire' pod 'MJRefresh' pod 'LYEmptyView' pod 'JXPagingView/Paging' pod 'JXSegmentedView' pod 'SPPermissions/Camera' pod 'SPPermissions/PhotoLibrary' pod 'SPPermissions/Microphone' end <file_sep>// // CourseList.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/16. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class CourseList: BaseModel { var number: Double? var numberOfElements: Double? var content: Array<Course>? var totalPages: Double? var size: Double? var last: Bool? var totalElements: Double? var first: Bool? } <file_sep>// // VideoAssetLibraryViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/27. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import Photos typealias selectedVideo = (_ model: PhotoModel) -> Void class VideoAssetLibraryViewController: BaseCollectionViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.noRefresh = true self.noLoadMore = true PHPhotoLibrary.requestAuthorization { [weak self] (status) in if status == .authorized { DispatchQueue.main.async { self?.collectionDataArray = PhotoAssetTool.shared().fetchAllVideo() self?.collectionView.register(VideoAssetLibraryCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "VideoAssetLibraryCollectionViewCell") self?.collectionView.reloadData() } } else { self?.settingAuthorization() } } } func settingAuthorization() { let alertVC = UIAlertController(title: "提示", message: "没有相册权限,现在去打开?", preferredStyle: .alert) let confirAction = UIAlertAction(title: "确定", style: .default) { (action) in let url = URL(string: UIApplication.openSettingsURLString) UIApplication.shared.open(url!, options: [:], completionHandler: nil) } alertVC.addAction(confirAction) self.present(alertVC, animated: true, completion: nil) } override func refreshAction() { super.refreshAction() self.collectionDataArray = PhotoAssetTool.shared().fetchAllVideo() self.collectionView.reloadData() } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let itemW = (collectionView.bounds.size.width - 50) / 4 return CGSize(width: itemW, height: itemW / 0.75) } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.collectionDataArray.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoAssetLibraryCollectionViewCell", for: indexPath) as! VideoAssetLibraryCollectionViewCell let model = self.collectionDataArray[indexPath.row] as! PhotoModel cell.updateCellModel(model: model) return cell } var selectedVideoBlock: selectedVideo? func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if selectedVideoBlock != nil { selectedVideoBlock!(self.collectionDataArray[indexPath.row] as! PhotoModel) } } } <file_sep>// // MainTabBarViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/11. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class MainTabBarViewController: UITabBarController, UITabBarControllerDelegate { var plusBtn: UIButton = UIButton(type: .custom) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.tabBar.tintColor = ColorTheme self.tabBar.barTintColor = UIColor.clear self.tabBar.backgroundImage = UIImage() self.tabBar.shadowImage = UIImage() self.delegate = self self.addChildViewControllers() self.addPlusBtn(image: UIImage(named: "WorkCourseBtn")!, selectedImage: UIImage(named: "WorkCourseBtn")!) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: false) } func resetMainTabVC() { /// 刷新首页 let homeVC = self.viewControllers?.first as? HomePageViewController homeVC?.refreshAction() self.selectedIndex = 0 self.tabBar.barTintColor = UIColor.clear self.tabBar.backgroundImage = UIImage() } func addChildViewControllers() { let home = HomePageViewController() self.addTabItem(controller: home, normalImage: UIImage(named: "MainTabarHomeBtn_normal")!, selectedImage: UIImage(named: "MainTabarHomeBtn_selected")!, title: "首页") let plus = HomePageViewController() self.addTabItem(controller: plus, normalImage: UIImage(systemName: "plus")!.withTintColor(ColorTheme, renderingMode: .alwaysOriginal), selectedImage: UIImage(systemName: "plus")!.withTintColor(ColorTheme, renderingMode: .alwaysOriginal), title: "") let personal = PersonalViewController() personal.titles = ["作品", "待审核", "喜欢的"] self.addTabItem(controller: personal, normalImage: UIImage(named: "MainTabarMineBtn_normal")!, selectedImage: UIImage(named: "MainTabarMineBtn_selected")!, title: "个人") } func addPlusBtn(image: UIImage, selectedImage: UIImage) { self.plusBtn.clipsToBounds = true self.plusBtn.layer.cornerRadius = 30 self.plusBtn.addTarget(self, action: #selector(clickedPlusBtn), for: .touchUpInside) self.plusBtn.setImage(image, for: .normal) self.plusBtn.setImage(selectedImage, for: .selected) self.view.addSubview(self.plusBtn) self.plusBtn.snp.makeConstraints { (make) in make.centerX.equalTo(self.tabBar) make.size.equalTo(CGSize(width: 60, height: 60)) make.bottom.equalTo(self.tabBar.snp.top).offset(40) } } func addTabItem(controller: UIViewController, normalImage: UIImage, selectedImage: UIImage, title: String) { controller.navigationItem.title = title controller.title = title controller.tabBarItem.image = normalImage controller.tabBarItem.selectedImage = selectedImage self.addChild(controller) } func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { if tabBarController.viewControllers?[1] == viewController { return false } return true } func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { if self.selectedIndex == 1 {return} if self.selectedIndex == 0 { self.tabBar.barTintColor = UIColor.clear self.tabBar.backgroundImage = UIImage() } else { self.tabBar.barTintColor = UIColor.white self.tabBar.backgroundImage = UIColor.white.drawToImage(size: CGSize(width: 100, height: 50)) } } @objc func clickedPlusBtn() { isLogin = true if isLogin { let popMenuVC = MainPopMenuViewController() popMenuVC.modalPresentationStyle = .fullScreen self.navigationController?.present(popMenuVC, animated: true, completion: nil) popMenuVC.selectedAddTypeBlock = {tag in switch tag { case 0: print("添加音频") case 1: let videoVC = VideoAddNewViewController() let rootNav = UIApplication.shared.windows.first?.rootViewController as! UINavigationController rootNav.pushViewController(videoVC, animated: true) default: break } } } else { let loginVC = LoginViewController() loginVC.modalPresentationStyle = .fullScreen self.navigationController?.present(loginVC, animated: true, completion: nil) loginVC.loginSucessBlock = { [weak self] in self!.loginSucess() } } } func loginSucess() { NetWorkManager.cancelAllOperations() /// 刷新首页 let homeVC = self.viewControllers?.first as? HomePageViewController homeVC?.refreshAction() /// 刷新个人中心 let personalVC = self.viewControllers?.last as? PersonalViewController personalVC?.refreshAction() } } <file_sep>// // PersonalHeaderView.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/18. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class PersonalHeaderView: UIView { var settingBtn = UIButton(type: .custom) var userImage = UIButton() var nameLabel = UILabel() var editBtn = UIButton() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = .clear self.settingBtn.setImage(UIImage(named: "settingBtn"), for: .normal) self.settingBtn.addTarget(self, action: #selector(clickedSettingBtn), for: .touchUpInside) self.addSubview(self.settingBtn) self.settingBtn.snp.makeConstraints { (make) in make.size.equalTo(CGSize(width: 44, height: 44)) make.right.equalTo(-10) let top = UIDevice.current.isiPhoneXMore() ? 40 : 20 make.top.equalTo(top) } self.userImage.clipsToBounds = true self.userImage.layer.cornerRadius = 40 self.userImage.setImage(UIImage(named: "userIcon"), for: .normal) self.userImage.addTarget(self, action: #selector(clickedUserImage), for: .touchUpInside) self.addSubview(self.userImage) self.userImage.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.size.equalTo(CGSize(width: 80, height: 80)) make.bottom.equalTo(-40) } self.nameLabel.font = UIFont.systemFont(ofSize: 14) self.nameLabel.textColor = .white self.nameLabel.textAlignment = .center self.addSubview(self.nameLabel) self.nameLabel.snp.makeConstraints { (make) in make.top.equalTo(self.userImage.snp.bottom).offset(5) make.centerX.equalTo(self) make.height.equalTo(20) make.width.greaterThanOrEqualTo(self.userImage.snp.width) } self.editBtn.setImage(UIImage(named: "个人中心_编辑"), for: .normal) self.editBtn.imageEdgeInsets = UIEdgeInsets(top: 7, left: 7, bottom: 7, right: 7) self.editBtn.addTarget(self, action: #selector(clickedEditBtn), for: .touchUpInside) self.addSubview(self.editBtn) self.editBtn.snp.makeConstraints { (make) in make.centerY.equalTo(self.nameLabel) make.size.equalTo(CGSize(width: 30, height: 30)) make.left.equalTo(self.nameLabel.snp.right) } } var editUserNameBlock: (() -> Void)? var editUserIconBlock: (() -> Void)? var settingAppBlock: (() -> Void)? var goBackBlock: (() -> Void)? func setupUser(user: User) { self.userImage.kf.setImage(with: user.avatar?.splicingRequestURL(), for: .normal) self.nameLabel.text = user.displayName } @objc func clickedUserImage() { if editUserIconBlock != nil { editUserIconBlock!() } } @objc func clickedEditBtn() { if editUserNameBlock != nil { editUserNameBlock!() } } @objc func clickedSettingBtn() { if settingAppBlock != nil { settingAppBlock!() } } @objc func clickedBackBtn() { if goBackBlock != nil { goBackBlock!() } } lazy var backBtn = { () -> (UIButton) in let btn = UIButton(type: .custom) btn.setImage(UIImage(systemName: "chevron.left"), for: .normal) btn.addTarget(self, action: #selector(clickedBackBtn), for: .touchUpInside) self.addSubview(btn) btn.snp.makeConstraints { (make) in make.size.equalTo(CGSize(width: 44, height: 44)) make.left.equalTo(20) make.top.equalTo(self.settingBtn) } return btn }() required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>// // WMHUD.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/24. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import PKHUD class WMHUD: NSObject { class func textHUD(text: String?, delay: TimeInterval) { HUD.flash(.label(text), delay: delay) } class func errorHUD(text: String?, subText: String?, delay: TimeInterval) { HUD.flash(.labeledError(title: text, subtitle: subText), delay: delay) } class func progressHUD(text: String?, subText: String?) { HUD.show(.labeledProgress(title: text, subtitle: subText)) } class func activityHUD() { HUD.show(.systemActivity) } class func hideHUD() { HUD.hide() } } <file_sep>// // PhotoAssetActionPreview.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/27. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class PhotoAssetActionPreview: UIImageView { let label = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.label.text = "点击编辑文字" self.label.textAlignment = .center self.label.textColor = .lightGray self.label.font = UIFont.systemFont(ofSize: 20) self.label.layer.borderColor = UIColor.lightGray.cgColor self.label.layer.borderWidth = 0.5 self.addSubview(self.label) self.label.snp.makeConstraints { (make) in make.top.left.equalTo(5) make.bottom.right.equalTo(-5) } self.backgroundColor = .white self.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(beginEditText)) self.label.addGestureRecognizer(tap) } typealias beginEdit = () -> Void var beginEditBlock: beginEdit? @objc func beginEditText() { if beginEditBlock != nil { beginEditBlock!() } } var preImage: UIImage? { set { self.image = newValue if newValue == nil { self.label.isHidden = true self.backgroundColor = .white } else { self.label.isHidden = false self.backgroundColor = .black } } get { return self.image } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>// // NetWorkManager.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/13. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import Alamofire let NetworkStatesChangeNotification = "NetworkStatesChangeNotification" /// 网络请求数据类型 enum NetworkRequestContentType { case NONE case JSON case TEXT case ZIP case MP4 case JPG } /// 请求方式 enum NetworkMethod { case GET case POST case PUT case DELETE } typealias HttpSuccess = (_ data: Any) -> Void typealias HttpFailure = (_ error: Error) -> Void typealias UploadProgress = (_ percent: CGFloat) -> Void class NetWorkManager: NSObject { private static let reachiabilityManager = { () -> NetworkReachabilityManager in let manager = NetworkReachabilityManager() return manager! }() private static let sessionManager = { () -> SessionManager in let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.timeoutIntervalForRequest = 10 // 超时 10s sessionConfiguration.requestCachePolicy = .reloadIgnoringLocalCacheData // 关闭缓存 let manager = SessionManager(configuration: sessionConfiguration) /// https 证书验证 manager.delegate.sessionDidReceiveChallenge = { session, challenge in var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { disposition = URLSession.AuthChallengeDisposition.useCredential credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) } else { credential = manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) if credential != nil { disposition = .useCredential } } return (disposition, credential) } return manager }() } // MARK: - 对外使用的方式,更简洁的使用 extension NetWorkManager { /// get 请求 static func get(url: String, request: BaseRequest, showHUD: Bool, success: @escaping HttpSuccess, failure: @escaping HttpFailure) { startRequest(url: url, request: request, method: .get, contentType: .NONE, showHUD: showHUD, success: success, failure: failure) } /// post 请求 static func post(url: String, request: BaseRequest, showHUD: Bool, success: @escaping HttpSuccess, failure: @escaping HttpFailure) { startRequest(url: url, request: request, method: .post, contentType: .NONE, showHUD: showHUD, success: success, failure: failure) } /// delete 请求 static func delete(url: String, request: BaseRequest, showHUD: Bool, success: @escaping HttpSuccess, failure: @escaping HttpFailure) { startRequest(url: url, request: request, method: .delete, contentType: .NONE, showHUD: showHUD, success: success, failure: failure) } /// 上传文件方法 /// /// 这个方法比较特殊,所以 manager 都是重新创建的,跟常用的请求分开 static func postData(url: String, contentType: NetworkRequestContentType, request: BaseRequest, showHUD: Bool, fileData: Any?, success: @escaping HttpSuccess, failure: @escaping HttpFailure) { let sessionConfiguration = URLSessionConfiguration.default sessionConfiguration.timeoutIntervalForRequest = 600 // 超时 10分钟 sessionConfiguration.requestCachePolicy = .reloadIgnoringLocalCacheData // 关闭缓存 let manager = SessionManager(configuration: sessionConfiguration) let headers = requestHeader() let parameters = request.toJSON() var content: [String] if contentType == .ZIP { content = ["application/zip; charset=utf-8", "application/json"] } else if contentType == .MP4 { content = ["application/json", "multipart/form-data"] } else if contentType == .JPG { content = ["text/plain", ""] } else { content = ["text/plain", "application/zip; charset=utf-8"] } if showHUD { WMHUD.progressHUD(text: "文件上传中", subText: nil) } let sessionRequest = manager.request(url.splicingRequestURL(), method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers) sessionRequest.validate(contentType: content) sessionRequest.responseJSON { (response) in WMHUD.hideHUD() requestComplete(response: response, success: success, failure: failure) } } /// 取消请求 static func cancelAllOperations() { sessionManager.session.invalidateAndCancel() } } // MARK: - 封装的基础网络请求 extension NetWorkManager { /// 开始一个请求 /// - Parameters: /// - url: 请求地址 /// - request: 请求类型 /// - method: 请求方式 /// - contentType: contentType /// - showHUD: 是否显示 HUD /// - success: 成功回调 /// - failure: 失败回调 static func startRequest(url: String, request: BaseRequest, method: HTTPMethod, contentType: NetworkRequestContentType, showHUD: Bool, success: @escaping HttpSuccess, failure: @escaping HttpFailure) { let parameters = request.toJSON() let requestContentType = switchRequestContentType(contentType: contentType) let headers = requestHeader() if showHUD { WMHUD.progressHUD(text: nil, subText: "网络请求中") } let sessionRequest = sessionManager.request(url.splicingRequestURL(), method: method, parameters: parameters, encoding: URLEncoding.default, headers: headers) sessionRequest.validate(contentType: requestContentType) sessionRequest.responseJSON { (response) in WMHUD.hideHUD() requestComplete(response: response, success: success, failure: failure) } } /// 请求完毕回调,处理成功或者失败 static func requestComplete(response: DataResponse<Any>, success: @escaping HttpSuccess, failure: @escaping HttpFailure) { switch response.result { case .success: let data:[String: Any] = response.result.value as! [String : Any] success(data) break case .failure(let error): let err: NSError = error as NSError if reachiabilityManager.networkReachabilityStatus == .notReachable { failure(err) return } var message: String = err.localizedDescription if message == "No message available" { message = "" } if err.code == 401 { message = "重新登录" } else if err.code == 502 { message = "服务器停止运行" } else if err.code == 500 { if message.count > 30 { message = "网络连接错误!" } } else { if message.count == 0 { if response.request?.url?.absoluteString == nil && err.localizedDescription.contains("timed out") { message = "请求超时,请稍后重试!" } else { message = ("接口异常,接口名称:" + (response.request?.url!.relativePath)! + "错误码:\(err.code)") } } } if message.count > 1 { WMHUD.errorHUD(text: nil, subText: message, delay: 2) } failure(err) break } } /// 判断contentType static func switchRequestContentType(contentType: NetworkRequestContentType) -> [String] { switch contentType { case .NONE, .TEXT, .ZIP: return ["application/x-www-form-urlencoded;charset=utf-8"] case .JSON: return ["application/json"] default: return ["application/x-www-form-urlencoded;charset=utf-8"] } } } // MARK: - header参数部分 extension NetWorkManager { static func requestHeader() -> HTTPHeaders { let headers = ["X-Requested-With" : "XMLHttpRequest", "Referer" : BaseUrl, "User-Agent" : userAgent()] return headers; } static func userAgent() -> String { let appVersion: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String let systemVersion: String = UIDevice.current.systemVersion return "Mozilla/5.0 (iPhone; CPU iPhone OS" + systemVersion + " like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Mobile/14F89 CourseMaker/" + appVersion } } // MARK: - Reachiability extension NetWorkManager { /// 开始监控网络状态 static func startMonitoring() { reachiabilityManager.startListening() reachiabilityManager.listener = { status in NotificationCenter.default.post(name: NSNotification.Name(rawValue: NetworkStatesChangeNotification), object: status) } } /// 网络状态 static func networkStatus() -> NetworkReachabilityManager.NetworkReachabilityStatus { return reachiabilityManager.networkReachabilityStatus; } /// 是否正常联网 static func isNotReachableStatus(status : Any?) -> Bool { let netStatus = status as! NetworkReachabilityManager.NetworkReachabilityStatus return netStatus == .notReachable } } <file_sep>// // TemplateBuildView.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/27. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import Photos class TemplateBuildView: UIView { var contentImageView = UIImageView() var textView = UITextView() var textViewFont: CGFloat = 34 var plachholderLabel = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(self.contentImageView) self.contentImageView.snp.makeConstraints({ (make) in make.edges.equalTo(self) }) self.textView.backgroundColor = .clear self.textView.textAlignment = .center self.textView.textColor = .white self.textView.font = UIFont.systemFont(ofSize: self.textViewFont) self.textView.delegate = self self.addSubview(self.textView) self.textView.snp.makeConstraints({ (make) in make.left.top.equalTo(5) make.right.bottom.equalTo(-5) }) self.plachholderLabel.textColor = .lightGray self.plachholderLabel.font = UIFont.systemFont(ofSize: 20) self.plachholderLabel.textAlignment = .center self.plachholderLabel.text = "点击编辑文字" self.addSubview(self.plachholderLabel) self.plachholderLabel.snp.makeConstraints { (make) in make.center.width.equalTo(self.textView) make.height.equalTo(40) } } typealias finishTemplateBuild = (_ photoModel: PhotoModel) -> Void /// 完成模板制作 /// - Parameter finishBlock: 成功回调,包含数据模型 func finishedTemplateBuild(finishBlock: @escaping finishTemplateBuild) { self.textView.layer.borderColor = UIColor.clear.cgColor self.textView.layer.borderWidth = 0 self.textView.resignFirstResponder() UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0) self.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.backgroundColor = .white var imageIds = [String]() PHPhotoLibrary.shared().performChanges({ let request = PHAssetChangeRequest.creationRequestForAsset(from: image!) imageIds.append(request.placeholderForCreatedAsset!.localIdentifier) }) { (success, error) in if success { let result = PHAsset.fetchAssets(withLocalIdentifiers: imageIds, options: nil) result.enumerateObjects { (obj, index, stop) in let model = PhotoModel() model.photoAsset = obj model.localIdentifiter = obj.localIdentifier model.isSelected = true model.originalImage = image DispatchQueue.main.async { finishBlock(model) } } } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TemplateBuildView: UITextViewDelegate { func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { self.plachholderLabel.isHidden = true return true } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { self.plachholderLabel.isHidden = textView.hasText return true } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if self.textViewFont <= 14 { WMHUD.textHUD(text: "输入的文字太长了", delay: 1) return false } return true } func contentSizeToFit(textView: UITextView) { if textView.hasText { textView.textContainerInset = .zero var contentSize = textView.contentSize var offset = UIEdgeInsets.zero if contentSize.height <= textView.frame.height { offset.top = (textView.frame.height - contentSize.height) / 2 } else { while (contentSize.height > textView.frame.height) { self.textViewFont -= 1 textView.font = UIFont.systemFont(ofSize: self.textViewFont) contentSize = textView.contentSize } } textView.contentInset = offset } } } <file_sep>// // PhotoAssetTool.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/25. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import Photos import MobileCoreServices import AssetsLibrary /// 相机回调 typealias cameraHandler = (_ image: UIImage?, _ finished: Bool) -> () /// 相册回调 typealias photoHandler = (_ image: UIImage?, _ finished: Bool) -> Void /// 录制视频回调 typealias recordMovieHandler = (_ url: URL?, _ finished: Bool) -> () class PhotoAssetTool: NSObject { /// 弹出的根控制器 var sheetController: UIViewController? var cameraBlock: cameraHandler? var photosBlock: photoHandler? var recordBlock: recordMovieHandler? private static let instance = { () -> PhotoAssetTool in return PhotoAssetTool.init() }() class func shared() -> PhotoAssetTool { return instance } /// 获取所有图片 /// - Parameter hasCustomPhoto: 是否插入自定义图片模型 func fetchAllPhotos(hasCustomPhoto: Bool) -> [PhotoModel] { var array = [PhotoModel]() let option = PHFetchOptions() //ascending 为YES时,按照照片的创建时间升序排列;为NO时,则降序排列 option.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let result = PHAsset.fetchAssets(with: .image, options: option) result.enumerateObjects { (asset, index, stop) in if asset.mediaType == .image { let model = PhotoModel() model.photoAsset = asset model.localIdentifiter = asset.localIdentifier model.unAble = false array.append(model) } } if hasCustomPhoto == true { let model = PhotoModel() array.append(model) } return array } /// 获取所有视频 func fetchAllVideo() -> [PhotoModel] { var array = [PhotoModel]() let option = PHFetchOptions() //ascending 为YES时,按照照片的创建时间升序排列;为NO时,则降序排列 option.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let result = PHAsset.fetchAssets(with: .video, options: option) result.enumerateObjects { (asset, index, stop) in if asset.mediaType == .video { let model = PhotoModel() model.photoAsset = asset model.localIdentifiter = asset.localIdentifier model.unAble = false array.append(model) } } return array } typealias fetchURLVideoSucess = (_ model: PhotoModel) -> Void /// 获取指定URL的视频 /// - Parameters: /// - videoURL: 视频地址 /// - success: 成功回调 func fetchVideoModel(videoURL: URL, success: @escaping fetchURLVideoSucess) { let option = PHFetchOptions() //ascending 为YES时,按照照片的创建时间升序排列;为NO时,则降序排列 option.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] let result = PHAsset.fetchAssets(with: .video, options: option) let model = PhotoModel() result.enumerateObjects { (asset, index, stop) in if asset.mediaType == .video { model.photoAsset = asset model.localIdentifiter = asset.localIdentifier model.unAble = false stop.pointee = true } } success(model) } typealias fetchVideoItemSucess = (_ item: AVPlayerItem?) -> Void /// 获取视频播放的item /// - Parameters: /// - asset: 视频资源 /// - success: 成功回调 func fetchVideoItem(asset: PHAsset, success: @escaping fetchVideoItemSucess) { let option = PHVideoRequestOptions() option.isNetworkAccessAllowed = true PHImageManager.default().requestPlayerItem(forVideo: asset, options: option) { (item, info) in success(item ?? nil) } } typealias fetchVideoDataSuccess = (_ data: Data?) -> Void /// 获取视频二进制数据 /// - Parameters: /// - asset: 视频资源 /// - success: 成功回调 func fetchVideoData(asset: PHAsset, success: @escaping fetchVideoDataSuccess) { let option = PHImageRequestOptions() option.isNetworkAccessAllowed = true PHImageManager.default().requestImageDataAndOrientation(for: asset, options: option) { (data, dataUTI, orientation, info) in let cancel = info?[PHImageCancelledKey] as! Bool let error = info?[PHImageErrorKey] as? Error if ((error == nil) && !cancel) { success(data) } } } typealias fetchVideoAssetSuccess = (_ asset: AVAsset?) -> Void /// 获取视频的avasset /// - Parameters: /// - asset: 视频资源 /// - success: 成功回调 func fetchVideoAsset(asset: PHAsset, success: @escaping fetchVideoAssetSuccess) { let option = PHVideoRequestOptions() option.version = .current option.deliveryMode = .automatic PHImageManager.default().requestAVAsset(forVideo: asset, options: option) { (avasset, audioMix, info) in success(avasset) } } typealias fetchOriginlImageSuccess = (_ image: UIImage?) -> Void /// 获取原图 /// - Parameters: /// - asset: 图片资源 /// - success: 成功回调 func fetchOriginalImage(asset: PHAsset, success: @escaping fetchOriginlImageSuccess) { let option = PHImageRequestOptions() option.resizeMode = .none option.isNetworkAccessAllowed = true PHCachingImageManager.default().requestImageDataAndOrientation(for: asset, options: option) { (data, dataUTI, orientation, info) in let cancel = info?[PHImageCancelledKey] as! Bool let error = info?[PHImageErrorKey] as? Error if error == nil && !cancel { if data != nil { success(UIImage(data: data!)) } } } } typealias fetchThumbnailImageSuccess = (_ image: UIImage?) -> Void /// 获取缩略图 /// - Parameters: /// - asset: 图像资源 /// - size: 获取大小 /// - success: 成功回调 func fetchThumbnailImage(asset: PHAsset, size: CGSize, success: @escaping fetchThumbnailImageSuccess) { let option = PHImageRequestOptions() option.resizeMode = .none option.isNetworkAccessAllowed = true PHCachingImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFit, options: option) { (image, info) in let error = info?[PHImageErrorKey] as? Error if error == nil { success(image) } } } /// 获取沙盒图片 /// - Parameter path: 沙盒路径 func fetchSandboxImage(path: String) -> UIImage? { let data = try! Data(contentsOf: URL(fileURLWithPath: path)) return UIImage(data: data) ?? nil } } // MARK: - 拍照和选择照片功能 extension PhotoAssetTool: UINavigationControllerDelegate, UIImagePickerControllerDelegate { /// 判断是否打开相机权限 func judgeIsHasCameraAuthority() -> Bool { let status = AVCaptureDevice.authorizationStatus(for: .video) if status == .restricted || status == .denied { return false } return true } /// 弹出选择图片方式的弹窗 /// - Parameters: /// - controller: 弹出的控制器 /// - photos: 相册回调 /// - camera: 相机回调 func showImageSheet(controller: UIViewController, photos: @escaping photoHandler, camera: @escaping cameraHandler) { self.sheetController = controller self.photosBlock = photos self.cameraBlock = camera self.showSheetAlert() } func showSheetAlert() { let alertVC = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil) let cameraAction = UIAlertAction(title: "拍照", style: .default) { (action) in self.showCameraAction() } let photosAction = UIAlertAction(title: "从相册选取", style: .default) { (action) in self.showPhotoLibraryAction() } alertVC.addAction(cancelAction) alertVC.addAction(cameraAction) alertVC.addAction(photosAction) self.sheetController?.present(alertVC, animated: true, completion: nil) } /// 使用相机拍照 func showCameraAction() { if self.judgeIsHasCameraAuthority() { if self.cameraBlock != nil { self.cameraBlock!(nil, false) } } else { if UIImagePickerController.isSourceTypeAvailable(.camera) { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = false picker.videoQuality = .typeHigh picker.sourceType = .camera self.sheetController?.present(picker, animated: true, completion: nil) } } } /// 显示图片浏览器 func showPhotoLibraryAction() { if self.photosBlock != nil { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = false picker.sourceType = .photoLibrary self.sheetController?.present(picker, animated: true, completion: nil) } } /// 开始录制视频 /// - Parameters: /// - controller: 弹出的控制器 /// - maxTime: 最大录制时间 /// - recordCompeletion: 录制回调 func recoredMovie(controller: UIViewController, maxTime: TimeInterval, recordCompeletion: @escaping recordMovieHandler) { self.recordBlock = recordCompeletion let picker = UIImagePickerController() picker.videoQuality = .typeHigh picker.sourceType = .camera picker.cameraDevice = .rear picker.mediaTypes = [(kUTTypeMovie as String)] if maxTime > 0 { picker.videoMaximumDuration = maxTime } picker.delegate = self picker.allowsEditing = true controller.present(picker, animated: true, completion: nil) } // MARK: - picker回调 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { picker.dismiss(animated: true) { if picker.sourceType == .camera { if self.recordBlock != nil { let url = info[.mediaURL] as! URL self.recordBlock!(url, true) } else if self.cameraBlock != nil { let image = info[.originalImage] as! UIImage UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.didFinishSaving(image:error:)), nil) } } else { if self.photosBlock != nil { let image = info[.originalImage] as! UIImage self.photosBlock!(image, true) } } } } /// 保存图片到相册 /// - Parameters: /// - image: 图片 /// - error: 错误结果 @objc func didFinishSaving(image: UIImage, error: Error?) { guard let block = self.cameraBlock else { return } if error != nil { block(nil, false) } else { block(image, true) } } } <file_sep>// // PhotoAssetActionCollectionView.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/26. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit typealias selectedPhotoChanged = () -> Void typealias initTemplateImage = () -> Void let PHOTOASSETACTIONCOLLECTIONVIEWCELL = "PhotoAssetActionCollectionViewCell" class PhotoAssetActionCollectionView: UIView { var collectionArray = [PhotoModel]() var selectedArray = [PhotoModel]() var selectedPhotoChangedBlock: selectedPhotoChanged? var initImageBlock: initTemplateImage? var maxSelectedCount = 10 override init(frame: CGRect) { super.init(frame: frame) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func reloadCollectionView(photoArray: [PhotoModel]) { self.collectionArray = photoArray self.photoCollectionView.reloadData() } var allowsMultipleSelection: Bool? { didSet { self.photoCollectionView.allowsMultipleSelection = allowsMultipleSelection ?? false } } lazy var photoCollectionView = { () -> UICollectionView in let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 5 layout.minimumInteritemSpacing = 5 layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) let itemW = (self.bounds.size.width - 50) / 4 layout.itemSize = CGSize(width: itemW, height: itemW / 0.75) let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = .white collectionView.allowsSelection = true collectionView.register(PhotoAssetCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: PHOTOASSETACTIONCOLLECTIONVIEWCELL) self.addSubview(collectionView) collectionView.snp.makeConstraints { (make) in make.edges.equalTo(self) } return collectionView }() } extension PhotoAssetActionCollectionView: UICollectionViewDelegate, UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.collectionArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PHOTOASSETACTIONCOLLECTIONVIEWCELL, for: indexPath) as! PhotoAssetCollectionViewCell let cellModel = self.collectionArray[indexPath.row] for model in self.selectedArray { if model.localIdentifiter == cellModel.localIdentifiter { cellModel.unAble = true cell.selectedLabel.text = "\(self.selectedArray.firstIndex(of: model)! + 1)" } } cell.setupModel(model: cellModel) if cellModel.photoAsset == nil && indexPath.row == 0 { cell.imageView.contentMode = .center let label = UILabel(frame: CGRect(x: 0, y: (cell.frame.height - 20) / 2 + 30, width: cell.frame.width, height: 20)) label.text = "制作模版" label.font = UIFont.systemFont(ofSize: 14) label.textAlignment = .center cell.addSubview(label) } else { cell.imageView.contentMode = .scaleAspectFill } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cellModel = self.collectionArray[indexPath.row] if cellModel.photoAsset == nil && indexPath.row == 0 { if self.initImageBlock != nil { self.initImageBlock!() } } else { if self.selectedArray.contains(cellModel) { cellModel.isSelected = false let index = self.selectedArray.firstIndex(of: cellModel) ?? 0 self.selectedArray.remove(at: index) } else { cellModel.isSelected = true if cellModel.originalImage == nil { PhotoAssetTool.shared().fetchOriginalImage(asset: cellModel.photoAsset!) { (image) in cellModel.originalImage = image } self.selectedArray.append(cellModel) } } if self.selectedPhotoChangedBlock != nil { self.selectedPhotoChangedBlock!() } } collectionView.reloadData() } func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { let cellModel = self.collectionArray[indexPath.row] cellModel.isSelected = false let index = self.selectedArray.firstIndex(of: cellModel) ?? 0 self.selectedArray.remove(at: index) if self.selectedPhotoChangedBlock != nil { self.selectedPhotoChangedBlock!() } collectionView.reloadData() } // 即将选中的时候,如果是单选,就把已选中的状态更改,并清除已选数组,这样就能添加下一个被选中的图片 func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { if collectionView.allowsMultipleSelection { if self.selectedArray.count >= self.maxSelectedCount { WMHUD.textHUD(text: "最多选取\(self.maxSelectedCount)张图片", delay: 1) return false } } else { if self.selectedArray.count > 0 { let model = self.selectedArray[0] model.isSelected = false self.selectedArray.removeAll() } } return true } } <file_sep>// // BaseTableViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/16. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import MJRefresh import SnapKit import LYEmptyView class BaseTableViewController: BaseViewController { /// 没有下拉刷新 var noRefresh = false /// 没有加载更多 var noLoadMore = false /// 数据源 var tableDataArray = Array<Any>() /// 页码 var pageNumber: Int = 0 /// 每页数据个数 var pageSize: Int = 10 /// 数据总个数 var dataTotal: Int = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } lazy var tableView = { () -> (UITableView) in let tableView = UITableView() tableView.delegate = self tableView.dataSource = self tableView.separatorStyle = .none tableView.backgroundColor = ColorThemeBackground tableView.keyboardDismissMode = .onDrag tableView.contentInsetAdjustmentBehavior = .automatic tableView.insetsContentViewsToSafeArea = true tableView.cellLayoutMarginsFollowReadableWidth = true if !self.noRefresh { tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { self.refreshAction() }) tableView.mj_header?.addObserver(self, forKeyPath: "state", options: .new, context: nil) } if !self.noLoadMore { tableView.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: { self.loadMoreAction() }) tableView.mj_footer?.addObserver(self, forKeyPath: "state", options: .new, context: nil) } self.view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.top.equalTo(self.view.safeAreaLayoutGuide) make.left.right.bottom.equalToSuperview() } return tableView }() override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if self.tableView.mj_header?.state == MJRefreshState.pulling { self.feedbackGenerator() } else if self.tableView.mj_footer?.state == MJRefreshState.pulling { self.feedbackGenerator() } } func requestTableData() { } @objc func refreshAction() { self.pageNumber = 0 self.dataTotal = 0 self.tableView.mj_header?.endRefreshing() self.tableView.mj_footer?.endRefreshing() self.tableDataArray.removeAll() self.tableView.reloadData() self.requestTableData() } @objc func loadMoreAction() { if self.dataTotal <= self.tableDataArray.count { self.tableView.mj_footer?.endRefreshingWithNoMoreData() return } self.tableView.mj_footer?.endRefreshing() self.pageNumber += 1 self.requestTableData() } func requestTableDataSuccess(array: Array<Any>, dataTotal: Double) { self.dataTotal = Int(dataTotal) self.tableDataArray.append(array) self.tableView.reloadData() if self.tableDataArray.count == 0 { self.tableView.ly_emptyView = LYEmptyView.emptyActionView(with: UIImage(named: "NoDataTipImage"), titleStr: "无数据", detailStr: "请稍后再试", btnTitleStr: "重新加载", btnClick: { self.requestTableData() }) } } func requestNetDataFailed() { if self.tableDataArray.count == 0 { self.tableView.ly_emptyView = LYEmptyView.emptyActionView(with: UIImage(named: "NoDataTipImage"), titleStr: "网络请求失败", detailStr: "请稍后再试", btnTitleStr: "重新加载", btnClick: { self.requestTableData() }) } } func feedbackGenerator() { let generator = UIImpactFeedbackGenerator(style: .medium) generator.prepare() generator.impactOccurred() } } extension BaseTableViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { self.view.endEditing(true) return indexPath } } extension BaseTableViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tableDataArray.count } } <file_sep>// // LoginResponse.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/17. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class LoginResponse: BaseResponse { var user: User? var userToken: String? } <file_sep>// // HomePageCourseListResponse.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/16. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class HomePageCourseListResponse: BaseResponse { var data: CourseList? } <file_sep>// // BaseResponse.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/16. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class BaseResponse: BaseModel { var code: Int? var message: String? } <file_sep>// // LoginRequest.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/17. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class LoginRequest: BaseRequest { var name: String? var pwd: String? var siteId: String? static func login(name: String, pwd: String, siteId: String, success: @escaping HttpSuccess, failure: @escaping HttpFailure) { let request = LoginRequest() request.name = name request.pwd = pwd request.siteId = siteId NetWorkManager.post(url: URLForLogin, request: request, showHUD: true, success: { (data) in if let response = LoginResponse.deserialize(from: data as? [String: Any]) { user = response.user userToken = response.userToken isLogin = true success(response) } }) { (error) in failure(error) } } } <file_sep>// // String+.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/12. // Copyright © 2019 dongjiawang. All rights reserved. // import Foundation extension String { /// 文件大小转字符串 static func format(decimal: Float, _ maximumDigits: Int = 1, _ minimumDigits: Int = 1) -> String? { let number = NSNumber(value: decimal) let numberFormatter = NumberFormatter() numberFormatter.maximumIntegerDigits = maximumDigits numberFormatter.minimumIntegerDigits = minimumDigits return numberFormatter.string(from: number) } /// 对 key 值进行 sha256 签名 func sha256() -> String { if let strData = self.data(using: String.Encoding.utf8) { var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) let bytesPointer = UnsafeMutableRawPointer.allocate(byteCount: 4, alignment: 4) CC_SHA256(bytesPointer, UInt32(strData.count), &digest) var sha256String = "" for byte in digest { sha256String += String(format: "%02x", UInt8(byte)) } if sha256String.uppercased() == "E8721A6EBEA3B23768D943D075035C7819662B581E487456FDB1A7129C769188" { print("Matching sha256 hash: E8721A6EBEA3B23768D943D075035C7819662B581E487456FDB1A7129C769188") } else { print("sha256 hash does not match: \(sha256String)") } } return "" } /* /// 对 key 值进行 md5 签名 /// - Parameter key: <#key description#> func md5(key: String) -> String { let cStrl = key.cString(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: 16) CC_MD5(cStrl, CC_LONG(strlen(cStrl!)), buffer) var md5String = "" for idx in 0...15 { let obcStrl = String(format: "%02x", buffer[idx]) md5String.append(obcStrl) } free(buffer) return md5String } */ /// 添加 scheme /// - Parameter scheme: scheme func urlScheme(scheme: String) -> URL? { if let url = URL(string: self) { var components = URLComponents(url: url, resolvingAgainstBaseURL: false) components?.scheme = scheme return components?.url } return nil } /// 拼接网络请求地址 func splicingRequestURL() -> URL { return URL(string: self.splicingRequestURLString())! } /// 拼接网络请求地址的字符串 func splicingRequestURLString() -> String { var resultString: String if self.hasPrefix("http://") || self.hasPrefix("https://") || self.hasPrefix("www") { resultString = self } else { resultString = BaseUrl + self } return resultString.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: "`#%^{}\"[]|\\<> ").inverted)! } } <file_sep>// // VideoEditTool.swift // WorkMarker-swift // // Created by dongjiawang on 2020/1/3. // Copyright © 2020 dongjiawang. All rights reserved. // import UIKit import Photos class VideoEditTool: NSObject { typealias exportResult = (_ url: URL) -> Void var saveResultBlock: exportResult? func getVideoSavePath() -> String { let path = NSTemporaryDirectory() let formatter = DateFormatter() formatter.dateFormat = "yyyyMMddHHmmss" let nowTimeString = formatter.string(from: Date.init(timeIntervalSinceNow: 0)) let fileName = path + "/\(nowTimeString).mp4" return fileName } func getVideoMergeFilePath() -> String { let path = NSTemporaryDirectory() let formatter = DateFormatter() formatter.dateFormat = "yyyyMMddHHmmss" let nowTimeString = formatter.string(from: Date.init(timeIntervalSinceNow: 0)) let fileName = path + "/\(nowTimeString).mp4" return fileName } func getVideoOriginalVideoAsset(videoAsset: AVAsset, videoTrack: AVMutableCompositionTrack, composition: AVMutableComposition) -> AVMutableCompositionTrack { let originalAudioAssetTrack = videoAsset.tracks(withMediaType: .audio).first let originalAudioCompositionTrack = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid) try! originalAudioCompositionTrack?.insertTimeRange(CMTimeRange(start: CMTime.zero, duration: videoTrack.timeRange.duration), of: originalAudioAssetTrack!, at: CMTime.zero) return originalAudioCompositionTrack! } func exportVideo(exportSession: AVAssetExportSession, exportResult: exportResult?) { exportSession.outputFileType = .mp4 exportSession.outputURL = URL(fileURLWithPath: getVideoMergeFilePath()) exportSession.shouldOptimizeForNetworkUse = true exportSession.exportAsynchronously { switch exportSession.status { case .failed: WMHUD.textHUD(text: "导出视频失败:\(String(describing: exportSession.error?.localizedDescription))", delay: 1) case .completed: DispatchQueue.main.async { self.saveVideoToLibrary(videoURL: exportSession.outputURL!, result: exportResult) } default: break } } } func saveVideoToLibrary(videoURL: URL, result: exportResult?) { if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(videoURL.path) { PHPhotoLibrary.shared().performChanges({ _ = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoURL) if result != nil { result!(videoURL) } }) { (finish, error) in if error != nil { WMHUD.textHUD(text: "视频保存相册失败,请设置软件读取相册权限", delay: 1) } } } } } <file_sep>// // PhotoAssetCollectionViewCell.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/26. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class PhotoAssetCollectionViewCell: UICollectionViewCell { var imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) self.imageView.frame = self.bounds self.imageView.contentMode = .scaleAspectFill self.imageView.clipsToBounds = true self.addSubview(self.imageView) } lazy var unSelectedTip = { () -> UIImageView in let tipImage = UIImageView(frame: CGRect(x: self.imageView.frame.size.width - 25, y: 5, width: 20, height: 20)) tipImage.image = UIImage(named: "btn_circle") tipImage.clipsToBounds = true tipImage.layer.cornerRadius = 10 self.addSubview(tipImage) return tipImage }() lazy var selectedLabel = { () -> UILabel in let label = UILabel(frame: CGRect(x: self.imageView.frame.width, y: 5, width: 20, height: 20)) label.backgroundColor = .blue label.textColor = .white label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 10) label.clipsToBounds = true label.layer.cornerRadius = 10 label.layer.borderColor = UIColor.white.cgColor label.layer.borderWidth = 1 self.addSubview(label) return label }() func setupModel(model: PhotoModel) { guard let asset = model.photoAsset else { self.imageView.image = UIImage(named: "drawingImage") self.unSelectedTip.isHidden = true self.selectedLabel.isHidden = true return } if model.unAble { self.unSelectedTip.isHidden = true self.selectedLabel.isHidden = false self.selectedLabel.backgroundColor = UIColor.init(hex: "#2b2b2b") } else if model.isSelected { self.selectedLabel.isHidden = false self.selectedLabel.backgroundColor = UIColor.init(hex: "#3c85f9") self.unSelectedTip.isHidden = true } else { self.selectedLabel.isHidden = true self.unSelectedTip.isHidden = false } if (model.thumbnailImage != nil) { self.imageView.image = model.thumbnailImage } else { PhotoAssetTool.shared().fetchThumbnailImage(asset: asset, size: CGSize(width: self.frame.width * 3, height: self.frame.height * 3)) { (image) in self.imageView.image = image model.thumbnailImage = image } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>// // PhotoAssetActionViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/27. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit import Photos typealias finishPhotoAction = ([PhotoModel]) -> Void typealias navigationGoBack = () -> Void class PhotoAssetActionViewController: BaseViewController { var finishPhotoActionBlock: finishPhotoAction? var navigationGoBackBlock: navigationGoBack? var hasPreview = false var allowsMultipleSelection = false var maxSelectedCount = 10 var showPhotoArray = [PhotoModel]() var preview: PhotoAssetActionPreview? var dragView: UIImageView? var photoCollectionView: PhotoAssetActionCollectionView? var touchingDragView = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. PHPhotoLibrary.requestAuthorization { (status) in if status == .authorized { self.initPreview() self.updatePhotoCollectionViewDataSource() } else { self.settingAuthorization() } } } func settingAuthorization() { let alertVC = UIAlertController(title: "提示", message: "没有相册权限,现在去打开?", preferredStyle: .alert) let confirAction = UIAlertAction(title: "确定", style: .default) { (action) in let url = URL(string: UIApplication.openSettingsURLString) UIApplication.shared.open(url!, options: [:], completionHandler: nil) } let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (action) in self.dismiss(animated: true, completion: nil) } alertVC.addAction(confirAction) alertVC.addAction(cancelAction) self.present(alertVC, animated: true, completion: nil) } @objc override func back() { super.back() if navigationGoBackBlock != nil { navigationGoBackBlock!() } } } // MARK: - 导航栏 extension PhotoAssetActionViewController { func setupNavigationBar() { self.title = "所有照片" self.navigationController?.navigationBar.isTranslucent = false let leftItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(back)) leftItem.tintColor = .white self.navigationItem.leftBarButtonItem = leftItem let rightItem = UIBarButtonItem(title: "下一步", style: .plain, target: self, action: #selector(navigationNext)) rightItem.tintColor = .white self.navigationItem.rightBarButtonItem = rightItem self.navigationController?.navigationBar.barStyle = .black self.navigationController?.navigationBar.barTintColor = ColorTheme } @objc func navigationNext() { if self.photoCollectionView?.selectedArray.count == 0 { WMHUD.textHUD(text: "至少选择一张图片", delay: 1) } else { if finishPhotoActionBlock != nil { finishPhotoActionBlock!(self.photoCollectionView!.selectedArray) } } super.back() } } // MARK: - collectionView extension PhotoAssetActionViewController { func setupPhotoListView() { var photoViewY: CGFloat = 0 if hasPreview { self.initPreview() photoViewY = self.dragView!.frame.origin.y + self.dragView!.frame.height } self.photoCollectionView = PhotoAssetActionCollectionView.init(frame: CGRect(x: 0, y: photoViewY, width: self.view.frame.width, height: self.view.frame.height - photoViewY)) self.photoCollectionView?.allowsMultipleSelection = self.allowsMultipleSelection self.view.addSubview(self.photoCollectionView!) self.photoCollectionView?.selectedPhotoChangedBlock = { [weak self] () in self?.changedPreviewImage() } self.photoCollectionView?.initImageBlock = { [weak self] () in self?.initTemplate(animation: true) } } func initPreview() { self.preview = PhotoAssetActionPreview(frame: .zero) self.view.addSubview(self.preview!) self.preview!.snp.makeConstraints { (make) in make.width.centerX.equalTo(self.view) make.top.equalTo(self.view.safeAreaLayoutGuide) make.height.equalTo(self.view.snp.height).multipliedBy(0.4) } self.preview?.beginEditBlock = { () in } self.view.layoutIfNeeded() self.dragView = UIImageView(frame: CGRect(x: 0, y: self.preview!.frame.height + self.preview!.frame.origin.y, width: self.preview!.frame.width, height: 20)) self.dragView?.backgroundColor = .lightText self.dragView?.contentMode = .scaleAspectFit self.dragView?.isUserInteractionEnabled = true self.dragView?.image = UIImage(named: "photoCollectionDrag") self.view.addSubview(self.dragView!) } func updatePhotoCollectionViewDataSource() { if self.showPhotoArray.count > 0 { self.photoCollectionView?.selectedArray = self.showPhotoArray } self.photoCollectionView?.reloadCollectionView(photoArray: PhotoAssetTool.shared().fetchAllPhotos(hasCustomPhoto: self.hasPreview)) } func changedPreviewImage() { let model = self.photoCollectionView?.selectedArray.last if model == nil { self.preview?.preImage = nil return } if model?.photoAsset == nil { self.preview?.preImage = nil return } self.preview?.preImage = model?.thumbnailImage } func initTemplate(animation: Bool) { let templateVC = TemplateBuildViewController() self.navigationController?.pushViewController(templateVC, animated: animation) templateVC.finishInitTemplateBlock = { [weak self] (photoModel) in self?.addNewTemplateView(model: photoModel) } } func addNewTemplateView(model: PhotoModel) { self.showPhotoArray.insert(model, at: 1) self.photoCollectionView?.selectedArray.append(model) self.photoCollectionView?.reloadCollectionView(photoArray: PhotoAssetTool.shared().fetchAllPhotos(hasCustomPhoto: self.hasPreview)) self.preview?.preImage = model.originalImage } } // MARK: - 拖动手势 extension PhotoAssetActionViewController { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if self.hasPreview == false {return} let touch = touches.first if touch?.view == self.dragView { touchingDragView = true self.photoCollectionView?.frame = CGRect(x: 0, y: self.dragView!.frame.origin.y + self.dragView!.frame.height, width: self.photoCollectionView!.frame.width, height: self.view.frame.height - (self.navigationController!.navigationBar.frame.origin.y + self.navigationController!.navigationBar.frame.height)) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if self.hasPreview == false {return} if touchingDragView { let bottom = self.preview!.frame.origin.y + self.preview!.frame.height let touch = touches.first! let moveY = touch.previousLocation(in: self.view).y - touch.location(in: self.view).y if moveY > bottom {return} let dragTop = (self.dragView!.frame.origin.y - moveY) > bottom ? bottom : (self.dragView!.frame.origin.y - moveY) if dragTop < (self.navigationController!.navigationBar.frame.origin.y + self.navigationController!.navigationBar.frame.height) {return} self.dragView?.frame = CGRect(x: 0, y: dragTop, width: self.dragView!.frame.width, height: self.dragView!.frame.height) self.photoCollectionView?.frame = CGRect(x: 0, y: dragTop + self.dragView!.frame.height, width: self.photoCollectionView!.frame.width, height: self.photoCollectionView!.frame.height) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if self.hasPreview == false {return} if touchingDragView { let touch = touches.first! let pointY = touch.previousLocation(in: self.view).y UIView.animate(withDuration: 0.3) { let bottom = self.preview!.frame.origin.y + self.preview!.frame.height if pointY > self.preview!.center.y { self.dragView?.frame = CGRect(x: 0, y: bottom, width: self.dragView!.frame.width, height: self.dragView!.frame.height) } else { self.dragView?.frame = CGRect(x: 0, y: (self.navigationController!.navigationBar.frame.origin.y + self.navigationController!.navigationBar.frame.height), width: self.dragView!.frame.width, height: self.dragView!.frame.height) } let dragViewBottom = self.dragView!.frame.origin.y + self.dragView!.frame.height self.photoCollectionView?.frame = CGRect(x: 0, y: dragViewBottom, width: self.photoCollectionView!.frame.width, height: self.view.frame.height - dragViewBottom) } } touchingDragView = false } } <file_sep>// // UploadRequest.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/13. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit class UploadRequest: BaseRequest { var parameterName: String? var data: Data? var fileName: String? var mimeType: String? } <file_sep>// // LoginViewController.swift // WorkMarker-swift // // Created by dongjiawang on 2019/12/17. // Copyright © 2019 dongjiawang. All rights reserved. // import UIKit typealias loginSucess = () -> Void class LoginViewController: BaseViewController { var loginSucessBlock: loginSucess? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let loginView = LoginView(frame: self.view.bounds) self.view.addSubview(loginView) loginView.beginLoginBlock = {name, pwd in } let closeBtn = UIButton(type: .custom) closeBtn.setImage(UIImage(named: "透明关闭"), for: .normal) closeBtn.addTarget(self, action: #selector(clickedCloseBtn), for: .touchUpInside) self.view.addSubview(closeBtn) closeBtn.snp.makeConstraints { (make) in make.left.equalTo(20) make.top.equalTo(self.view.safeAreaLayoutGuide).offset(30) make.size.equalTo(CGSize(width: 30, height: 30)) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setToolbarHidden(true, animated: false) } @objc func clickedCloseBtn() { self.dismiss(animated: true, completion: nil) } func login(name: String, pwd: String, siteId: String) { LoginRequest.login(name: name, pwd: pwd, siteId: "1", success: { (data) in if self.loginSucessBlock != nil { self.loginSucessBlock!() } self.clickedCloseBtn() }) { (error) in } } }
0a26fa6bf132ca2082f1597525327bfeb9bd0b31
[ "Swift", "Ruby" ]
57
Swift
dongjiawang/WorkMarker-swift
59c95e336fed1ce482c00a314906e5443e9723e2
aa8a368ac7c0d9ff1ec85212c8df69bdc3ccbfbf
refs/heads/master
<repo_name>uk-gov-mirror/ministryofjustice.doorkeeper<file_sep>/app/controllers/doorkeeper/application_controller.rb module Doorkeeper class ApplicationController < ActionController::Base include Helpers::Controller if ::Rails.version.to_i < 4 protect_from_forgery Doorkeeper.configuration.protect_from_forgery_options else protect_from_forgery( {with: :exception}.merge(Doorkeeper.configuration.protect_from_forgery_options) ) end helper 'doorkeeper/dashboard' end end
43647d3e54ce2d796d48dba91172fec19c445068
[ "Ruby" ]
1
Ruby
uk-gov-mirror/ministryofjustice.doorkeeper
ecdf42a83f3dca7da690f6d6a585c885e14c28e7
2e1611b25f77624ed28e545b4603e52de5726e15
refs/heads/master
<file_sep># ERNI Community MQTT Client MQTT Client with pluggable publish and subscribe topic objects ## Dependencies - Arduino MQTT Client (https://github.com/256dpi/arduino-mqtt, Arduino Library Mgr: *MQTT*) - ESP8266WiFi (ESP8266) or WiFi (ESP32) - Spin Timer (3.0.0) (https://github.com/dniklaus/spin-timer, Arduino Library Mgr: *spin-timer*) - Debug Trace (1.1.0) (https://github.com/ERNICommunity/dbg-trace, Arduino Library Mgr: *dbg-trace*) - Debug CLI (1.3.0) (https://github.com/ERNICommunity/debug-cli, Arduino Library Mgr: *debug-cli*) ## Architecture tbd ## Integration ### Arduino Framework The following example shows the integration of this component into an Arduino Framework based application. #### Dependencies Here are the additional dependencies the example sketch needs to be installed: - SerialCommand (https://github.com/kroimon/Arduino-SerialCommand, Arduino Library Mgr: import ZIP) - App Debug (2.0.1) (https://github.com/dniklaus/wiring-app-debug, Arduino Library Mgr: import ZIP) - RamUtils (2.1.0) (https://github.com/dniklaus/arduino-utils-mem, Arduino Library Mgr: import ZIP) #### Example Sketch ```C++ #include <Arduino.h> #ifdef ESP8266 #include <ESP8266WiFi.h> #elif defined(ESP32) #include <WiFi.h> // see https://github.com/espressif/arduino-esp32/issues/1960#issuecomment-429546528 #endif #include <SerialCommand.h> #include <SpinTimer.h> #include <AppDebug.h> #include <DbgCliNode.h> #include <DbgCliTopic.h> #include <DbgCliCommand.h> #include <DbgTracePort.h> #include <DbgTraceLevel.h> #include <ECMqttClient.h> // ERNI Community MQTT client wrapper library #include <MqttTopic.h> #define MQTT_SERVER "test.mosquitto.org" SerialCommand* sCmd = 0; //----------------------------------------------------------------------------- // ESP8266 / ESP32 WiFi Client //----------------------------------------------------------------------------- #if defined(ESP8266) || defined(ESP32) WiFiClient wifiClient; #endif //----------------------------------------------------------------------------- void setBuiltInLed(bool state) { #if defined(ESP8266) digitalWrite(LED_BUILTIN, !state); // LED state is inverted on ESP8266 #else digitalWrite(LED_BUILTIN, state); #endif } //----------------------------------------------------------------------------- // WiFi Commands //----------------------------------------------------------------------------- class DbgCli_Cmd_WifiMac : public DbgCli_Command { public: DbgCli_Cmd_WifiMac(DbgCli_Topic* wifiTopic) : DbgCli_Command(wifiTopic, "mac", "Print MAC Address.") { } void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { Serial.println(); Serial.print("Wifi MAC: "); Serial.println(WiFi.macAddress().c_str()); Serial.println(); } }; //----------------------------------------------------------------------------- class DbgCli_Cmd_WifiNets : public DbgCli_Command { public: DbgCli_Cmd_WifiNets(DbgCli_Topic* wifiTopic) : DbgCli_Command(wifiTopic, "nets", "Print nearby networks.") { } void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { bool bailOut = false; // scan for nearby networks: Serial.println(); Serial.println("** Scan Networks **"); int numSsid = WiFi.scanNetworks(); if (numSsid == -1) { Serial.println("Couldn't get a wifi connection"); bailOut = true; } if (!bailOut) { // print the list of networks seen: Serial.print("number of available networks:"); Serial.println(numSsid); // print the network number and name for each network found: for (int thisNet = 0; thisNet < numSsid; thisNet++) { Serial.print(thisNet); Serial.print(") "); Serial.print(WiFi.SSID(thisNet)); Serial.print(" - Signal: "); Serial.print(WiFi.RSSI(thisNet)); Serial.print(" dBm"); Serial.print(" - Encryption: "); printEncryptionType(WiFi.encryptionType(thisNet)); } } Serial.println(); } private: void printEncryptionType(int thisType) { // read the encryption type and print out the name: switch (thisType) { #if ! defined(ESP32) // TODO: solve this for ESP32! case ENC_TYPE_WEP: Serial.println("WEP"); break; case ENC_TYPE_TKIP: Serial.println("WPA"); break; case ENC_TYPE_CCMP: Serial.println("WPA2"); break; case ENC_TYPE_NONE: Serial.println("None"); break; case ENC_TYPE_AUTO: Serial.println("Auto"); break; #endif default: Serial.println("Unknown"); break; } } }; //----------------------------------------------------------------------------- class DbgCli_Cmd_WifiStat : public DbgCli_Command { public: DbgCli_Cmd_WifiStat(DbgCli_Topic* wifiTopic) : DbgCli_Command(wifiTopic, "stat", "Show WiFi connection status.") { } void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { wl_status_t wlStatus = WiFi.status(); Serial.println(); Serial.println(wlStatus == WL_NO_SHIELD ? "NO_SHIELD " : wlStatus == WL_IDLE_STATUS ? "IDLE_STATUS " : wlStatus == WL_NO_SSID_AVAIL ? "NO_SSID_AVAIL " : wlStatus == WL_SCAN_COMPLETED ? "SCAN_COMPLETED " : wlStatus == WL_CONNECTED ? "CONNECTED " : wlStatus == WL_CONNECT_FAILED ? "CONNECT_FAILED " : wlStatus == WL_CONNECTION_LOST ? "CONNECTION_LOST" : wlStatus == WL_DISCONNECTED ? "DISCONNECTED " : "UNKNOWN"); Serial.println(); WiFi.printDiag(Serial); Serial.println(); } }; //----------------------------------------------------------------------------- class DbgCli_Cmd_WifiDis : public DbgCli_Command { public: DbgCli_Cmd_WifiDis(DbgCli_Topic* wifiTopic) : DbgCli_Command(wifiTopic, "dis", "Disconnect WiFi.") { } void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { Serial.println(); if (argc - idxToFirstArgToHandle > 0) { printUsage(); } else { const bool DO_NOT_SET_wifioff = false; WiFi.disconnect(DO_NOT_SET_wifioff); Serial.println("WiFi is disconnected now."); } Serial.println(); } void printUsage() { Serial.println(getHelpText()); Serial.println("Usage: dbg wifi dis"); } }; //----------------------------------------------------------------------------- class DbgCli_Cmd_WifiCon : public DbgCli_Command { public: DbgCli_Cmd_WifiCon(DbgCli_Topic* wifiTopic) : DbgCli_Command(wifiTopic, "con", "Connect to WiFi.") { } void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { Serial.println(); if (argc - idxToFirstArgToHandle != 2) { printUsage(); } else { const char* ssid = args[idxToFirstArgToHandle]; const char* pass = args[idxToFirstArgToHandle+1]; Serial.print("SSID: "); Serial.print(ssid); Serial.print(", pass: "); Serial.println(pass); WiFi.begin(ssid, pass); Serial.println("WiFi is connecting now."); } Serial.println(); } void printUsage() { Serial.println(getHelpText()); Serial.println("Usage: dbg wifi con <SSID> <passwd>"); } }; //----------------------------------------------------------------------------- class TestLedMqttSubscriber : public MqttTopicSubscriber { public: TestLedMqttSubscriber() : MqttTopicSubscriber("test/led") { } virtual ~TestLedMqttSubscriber() { } bool processMessage(MqttRxMsg* rxMsg) { bool msgHasBeenHandled = false; if (0 != rxMsg) { // this subscriber object takes the responsibility bool state = atoi(rxMsg->getRxMsgString()); setBuiltInLed(state); // ... and marks the received message as handled (chain of responsibilities) msgHasBeenHandled = true; } return msgHasBeenHandled; } }; void setup() { pinMode(LED_BUILTIN, OUTPUT); setBuiltInLed(false); Serial.begin(9600); setupDebugEnv(); //----------------------------------------------------------------------------- // WiFi Commands //----------------------------------------------------------------------------- #if defined(ESP8266) || defined(ESP32) DbgCli_Topic* wifiTopic = new DbgCli_Topic(DbgCli_Node::RootNode(), "wifi", "WiFi debug commands"); new DbgCli_Cmd_WifiMac(wifiTopic); new DbgCli_Cmd_WifiNets(wifiTopic); new DbgCli_Cmd_WifiStat(wifiTopic); new DbgCli_Cmd_WifiDis(wifiTopic); new DbgCli_Cmd_WifiCon(wifiTopic); #endif //----------------------------------------------------------------------------- // ESP8266 / ESP32 WiFi Client //----------------------------------------------------------------------------- WiFi.mode(WIFI_STA); //----------------------------------------------------------------------------- // MQTT Client //----------------------------------------------------------------------------- ECMqttClient.begin(MQTT_SERVER, ECMqttClientClass::defaultMqttPort, wifiClient, WiFi.macAddress().c_str()); new TestLedMqttSubscriber(); } void loop() { if (0 != sCmd) { sCmd->readSerial(); // process serial commands } ECMqttClient.loop(); // process MQTT Client scheduleTimers(); // process Timers } ``` <file_sep>/* * MqttClientController.cpp * * Created on: 13.10.2016 * Author: nid */ #include <string.h> #include <stdio.h> #include <Client.h> #include <DbgCliNode.h> #include <DbgCliTopic.h> #include <DbgCliCommand.h> #include <DbgTraceContext.h> #include <DbgTracePort.h> #include <DbgTraceLevel.h> #include <DbgPrintConsole.h> #include <DbgTraceOut.h> #include <MqttTopic.h> #include <ConnectionMonitor.h> #include <MqttClientWrapper.h> #include <MqttClientDbgCommand.h> #include <MqttClientController.h> //----------------------------------------------------------------------------- class MyConnMonAdapter : public ConnMonAdapter { private: MqttClientController* m_mqttClientCtrl; public: MyConnMonAdapter(MqttClientController* mqttClientCtrl) : ConnMonAdapter() , m_mqttClientCtrl(mqttClientCtrl) { } bool appProtocolConnectedRaw() { bool isMqttConnected = false; if (0 != m_mqttClientCtrl) { isMqttConnected = m_mqttClientCtrl->mqttClientWrapper()->connected(); TR_PRINTF(trPort(), DbgTrace_Level::debug, "MQTT client is %s", isMqttConnected ? "connected" : "disconnected"); } return isMqttConnected; } bool shallAppProtocolConnect() { bool shallMqttConnect = false; if (0 != m_mqttClientCtrl) { shallMqttConnect = m_mqttClientCtrl->getShallConnect(); TR_PRINTF(trPort(), DbgTrace_Level::debug, "MQTT client shall %s", shallMqttConnect ? "connect" : "not connect"); } return shallMqttConnect; } void actionConnectAppProtocol() { bool isConnected = false; if (0 != m_mqttClientCtrl) { TR_PRINTF(trPort(), DbgTrace_Level::error, "actionConnectAppProtocol(), connect with id: %s", m_mqttClientCtrl->id()); isConnected = m_mqttClientCtrl->connect(); TR_PRINTF(trPort(), DbgTrace_Level::error, "actionConnectAppProtocol() done - MQTT client %s; %s", isConnected ? "connected" : "NOT connected", m_mqttClientCtrl->mqttClientWrapper()->connected() ? "connected" : "NOT connected"); } } void notifyLanConnected(bool isLanConnected) { if (isLanConnected) { TR_PRINT_STR(trPort(), DbgTrace_Level::debug, "LAN Connection: ON"); } else { TR_PRINT_STR(trPort(), DbgTrace_Level::debug, "LAN Connection: OFF"); } } void notifyAppProtocolConnected(bool isMqttConnected) { if (isMqttConnected) { TR_PRINT_STR(trPort(), DbgTrace_Level::info, "MQTT Connection: ON"); // subscribe to topics MqttTopicSubscriber* subscriberChain = m_mqttClientCtrl->mqttSubscriberChain(); if (0 != subscriberChain) { TR_PRINTF(trPort(), DbgTrace_Level::debug, "notifyAppProtocolConnected(), subscriberChain->subscribe()"); subscriberChain->subscribe(); TR_PRINTF(trPort(), DbgTrace_Level::info, "notifyAppProtocolConnected(), subscriberChain->subscribe() done"); } // publish the auto publisher topics MqttTopicPublisher* publisherChain = m_mqttClientCtrl->mqttPublisherChain(); if (0 != publisherChain) { TR_PRINTF(trPort(), DbgTrace_Level::debug, "notifyAppProtocolConnected(), publisherChain->publishAll()"); publisherChain->publishAll(); TR_PRINTF(trPort(), DbgTrace_Level::info, "notifyAppProtocolConnected(), publisherChain->publishAll() done"); } } else { TR_PRINT_STR(trPort(), DbgTrace_Level::info, "MQTT Connection: OFF"); } } }; //----------------------------------------------------------------------------- MqttClientController* MqttClientController::s_instance = 0; IMqttClientWrapper* MqttClientController::s_mqttClientWrapper = 0; const unsigned int MqttClientController::s_maxIdSize = sizeof("AB:CD:EF:01:23:45"); MqttClientController* MqttClientController::Instance() { if (0 == s_instance) { s_instance = new MqttClientController(); } return s_instance; } MqttClientController::MqttClientController() : m_shallConnect(false) , m_trPortMqttctrl(new DbgTrace_Port("mqttctrl", DbgTrace_Level::info)) , m_connMon(new ConnMon(new MyConnMonAdapter(this))) , m_mqttSubscriberChain(0) , m_mqttPublisherChain(0) , m_id(new char[s_maxIdSize+1]) { DbgCli_Topic* mqttClientTopic = new DbgCli_Topic(DbgCli_Node::RootNode(), "mqtt", "MQTT Client debug commands"); new DbgCli_Cmd_MqttClientCon(mqttClientTopic, this); new DbgCli_Cmd_MqttClientDis(mqttClientTopic, this); new DbgCli_Cmd_MqttClientPub(mqttClientTopic, this); new DbgCli_Cmd_MqttClientSub(mqttClientTopic, this); new DbgCli_Cmd_MqttClientUnsub(mqttClientTopic, this); new DbgCli_Cmd_MqttClientShow(mqttClientTopic, this); assignMqttClientWrapper(new MqttClientWrapper(), new MqttClientCallbackAdapter()); setShallConnect(true); } MqttClientController::~MqttClientController() { delete [] m_id; m_id = 0; delete m_connMon->adapter(); delete m_connMon; m_connMon = 0; setShallConnect(false); } void MqttClientController::assignMqttClientWrapper(IMqttClientWrapper* mqttClientWrapper, IMqttClientCallbackAdapter* mqttClientCallbackAdapter) { s_mqttClientWrapper = mqttClientWrapper; if (0 != s_mqttClientWrapper) { s_mqttClientWrapper->setCallbackAdapter(mqttClientCallbackAdapter); } } IMqttClientWrapper* MqttClientController::mqttClientWrapper() { return s_mqttClientWrapper; } void MqttClientController::begin(const char* domain, uint16_t port, Client& client, const char* id) { memset(m_id, 0, s_maxIdSize+1); strncpy(m_id, id, s_maxIdSize); if (0 != s_mqttClientWrapper) { s_mqttClientWrapper->begin(domain, port, client); } } void MqttClientController::setShallConnect(bool shallConnect) { m_shallConnect = shallConnect; if (!shallConnect) { if (0 != s_mqttClientWrapper) { s_mqttClientWrapper->disconnect(); } } } bool MqttClientController::getShallConnect() { return m_shallConnect; } bool MqttClientController::connect() { bool isConnected = false; if (0 != s_mqttClientWrapper) { isConnected = s_mqttClientWrapper->connect(m_id); } return isConnected; } ConnMon* MqttClientController::connMon() { return m_connMon; } DbgTrace_Port* MqttClientController::trPort() { return m_trPortMqttctrl; } const char* MqttClientController::id() { return m_id; } void MqttClientController::loop() { if (0 != m_connMon) { if (m_connMon->isAppProtocolConnected()) { if (0 != s_mqttClientWrapper) { TR_PRINTF(trPort(), DbgTrace_Level::debug, "MqttClientController::loop(), s_mqttClientWrapper->loop()"); s_mqttClientWrapper->loop(); TR_PRINTF(trPort(), DbgTrace_Level::debug, "MqttClientController::loop(), s_mqttClientWrapper->loop() done"); } } } } int MqttClientController::publish(const char* topic, const char* data) { int ret = 0; if (0 != s_mqttClientWrapper) { TR_PRINTF(m_trPortMqttctrl, DbgTrace_Level::debug, "publish(%s, %s)\n", topic, data); ret = s_mqttClientWrapper->publish(topic, data); } return ret; } int MqttClientController::subscribe(const char* topic) { int ret = 0; if (0 != s_mqttClientWrapper) { ret = s_mqttClientWrapper->subscribe(topic); } return ret; } int MqttClientController::unsubscribe(const char* topic) { int ret = 0; if (0 != s_mqttClientWrapper) { ret = s_mqttClientWrapper->unsubscribe(topic); } return ret; } MqttTopicSubscriber* MqttClientController::mqttSubscriberChain() { return m_mqttSubscriberChain; } MqttTopicPublisher* MqttClientController::mqttPublisherChain() { return m_mqttPublisherChain; } void MqttClientController::addMqttSubscriber(MqttTopicSubscriber* mqttSubscriber) { if (0 == m_mqttSubscriberChain) { m_mqttSubscriberChain = mqttSubscriber; TR_PRINTF(m_trPortMqttctrl, DbgTrace_Level::info, "Added first MQTT Subscriber: %s", mqttSubscriber->getTopicString()); } else { MqttTopicSubscriber* next = m_mqttSubscriberChain; while (next->next() != 0) { next = next->next(); } next->setNext(mqttSubscriber); TR_PRINTF(m_trPortMqttctrl, DbgTrace_Level::info, "Added MQTT Subscriber: %s", mqttSubscriber->getTopicString()); } } void MqttClientController::addMqttPublisher(MqttTopicPublisher* mqttPublisher) { if (0 == m_mqttPublisherChain) { m_mqttPublisherChain = mqttPublisher; TR_PRINTF(m_trPortMqttctrl, DbgTrace_Level::info, "Added first MQTT Publisher: %s", mqttPublisher->getTopicString()); } else { MqttTopicPublisher* next = m_mqttPublisherChain; while (next->next() != 0) { next = next->next(); } next->setNext(mqttPublisher); TR_PRINTF(m_trPortMqttctrl, DbgTrace_Level::info, "Added MQTT Publisher: %s", mqttPublisher->getTopicString()); } } MqttTopicSubscriber* MqttClientController::findSubscriberByTopic(const char* topic) { MqttTopicSubscriber* subscriber = m_mqttSubscriberChain; bool found = false; while ((0 != subscriber) && (!found)) { found = (strncmp(subscriber->getTopicString(), topic, strlen(topic)) == 0); if (!found) { subscriber = subscriber->next(); } } return subscriber; } MqttTopicPublisher* MqttClientController::findPublisherByTopic(const char* topic) { MqttTopicPublisher* publisher = m_mqttPublisherChain; bool found = false; while ((0 != publisher) && (!found)) { found = (strncmp(publisher->getTopicString(), topic, strlen(topic)) == 0); if (!found) { publisher = publisher->next(); } } return publisher; } void MqttClientController::deleteSubscriber(MqttTopicSubscriber* subscriberToDelete) { if (m_mqttSubscriberChain == subscriberToDelete) { m_mqttSubscriberChain = subscriberToDelete->next(); } else { MqttTopicSubscriber* next = m_mqttSubscriberChain; while ((next != 0) && (next->next() != subscriberToDelete)) { next = next->next(); } if (next != 0) { next->setNext(subscriberToDelete->next()); } } } void MqttClientController::deletePublisher(MqttTopicPublisher* publisherToDelete) { if (m_mqttPublisherChain == publisherToDelete) { m_mqttPublisherChain = publisherToDelete->next(); } else { MqttTopicPublisher* next = m_mqttPublisherChain; while ((next != 0) && (next->next() != publisherToDelete)) { next = next->next(); } if (next != 0) { next->setNext(publisherToDelete->next()); } } } <file_sep>/* * MqttTopic.h * * Created on: 16.12.2016 * Author: nid */ #ifndef LIB_MQTT_CLIENT_MQTTTOPIC_H_ #define LIB_MQTT_CLIENT_MQTTTOPIC_H_ class DbgTrace_Port; class TopicLevel { public: TopicLevel(const char* level, unsigned int idx); virtual ~TopicLevel(); TopicLevel* next(); const char* level() const; unsigned int idx() const; void append(TopicLevel* level); enum WildcardType { eTWC_None = 0, eTWC_Single = 1, eTWC_Multi = 2 }; WildcardType getWildcardType(); private: const unsigned int m_idx; const unsigned int m_levelSize; char* m_level; WildcardType m_wcType; TopicLevel* m_next; private: // forbidden default functions TopicLevel(); // default constructor TopicLevel& operator = (const TopicLevel& src); // assignment operator TopicLevel(const TopicLevel& src); // copy constructor }; //----------------------------------------------------------------------------- class MqttTopic { public: MqttTopic(const char* topic); virtual ~MqttTopic(); const char* getTopicString() const; TopicLevel* getLevelList() const; bool hasWildcards() const; protected: void appendLevel(TopicLevel* level); private: char* m_topic; unsigned int m_topicLevelCount; static const unsigned int s_maxNumOfTopicLevels; TopicLevel* m_levelList; bool m_hasWildcards; private: // forbidden default functions MqttTopic(); // default constructor MqttTopic& operator = (const MqttTopic& src); // assignment operator MqttTopic(const MqttTopic& src); // copy constructor }; //----------------------------------------------------------------------------- class MqttTopicPublisher : public MqttTopic { public: MqttTopicPublisher(const char* topic, const char* data, bool isAutoPublishOnConnectEnabled = DONT_AUTO_PUBLISH); virtual ~MqttTopicPublisher(); void setData(const char* data); void publish(const char* data); void publish(); const char* getData() const; void setNext(MqttTopicPublisher* mqttPublisher); MqttTopicPublisher* next(); void publishAll(); private: MqttTopicPublisher* m_next; char* m_data; bool m_isAutoPublish; static const unsigned int s_maxDataSize; public: static const bool DO_AUTO_PUBLISH; static const bool DONT_AUTO_PUBLISH; private: // forbidden default functions MqttTopicPublisher(); // default constructor MqttTopicPublisher& operator = (const MqttTopicPublisher& src); // assignment operator MqttTopicPublisher(const MqttTopicPublisher& src); // copy constructor }; //----------------------------------------------------------------------------- class MqttRxMsg { public: MqttRxMsg(); virtual ~MqttRxMsg(); void prepare(const char* topic, const char* payload, unsigned int length); MqttTopic* getRxTopic() const; const char* getRxMsgString() const; const unsigned int getRxMsgSize() const; private: MqttTopic* m_rxTopic; char* m_rxMsg; unsigned int m_rxMsgSize; public: static const unsigned int s_maxRxMsgSize; private: // forbidden default functions MqttRxMsg& operator = (const MqttRxMsg& src); // assignment operator MqttRxMsg(const MqttRxMsg& src); // copy constructor }; //----------------------------------------------------------------------------- /** * Abstract handler for received MQTT messages from subscribed topics. * This is an implementation according the GOF Chain-of-responsibility pattern Pattern */ class MqttTopicSubscriber : public MqttTopic { public: MqttTopicSubscriber(const char* topic); virtual ~MqttTopicSubscriber(); void handleMessage(MqttRxMsg* rxMsg, DbgTrace_Port* trPortMqttRx = 0); virtual bool processMessage(MqttRxMsg* rxMsg) = 0; bool isMyTopic(MqttRxMsg* rxMsg) const; void subscribe(); void setNext(MqttTopicSubscriber* mqttSubscriber); MqttTopicSubscriber* next(); private: MqttTopicSubscriber* m_next; private: // forbidden default functions MqttTopicSubscriber(); // default constructor MqttTopicSubscriber& operator = (const MqttTopicSubscriber& src); // assignment operator MqttTopicSubscriber(const MqttTopicSubscriber& src); // copy constructor }; //----------------------------------------------------------------------------- /** * Default implementation of an MQTT Topic Subscriber. */ class DefaultMqttSubscriber : public MqttTopicSubscriber { public: DefaultMqttSubscriber(const char* topic); virtual bool processMessage(MqttRxMsg* rxMsg); private: DbgTrace_Port* m_trPort; private: // forbidden default functions DefaultMqttSubscriber(); // default constructor DefaultMqttSubscriber& operator = (const DefaultMqttSubscriber& src); // assignment operator DefaultMqttSubscriber(const DefaultMqttSubscriber& src); // copy constructor }; //----------------------------------------------------------------------------- /** * Default implementation of an MQTT Topic Publisher. */ class DefaultMqttPublisher : public MqttTopicPublisher { public: DefaultMqttPublisher(const char* topic, const char* data); void publish(const char* data); private: DbgTrace_Port* m_trPort; private: // forbidden default functions DefaultMqttPublisher(); // default constructor DefaultMqttPublisher& operator = (const DefaultMqttPublisher& src); // assignment operator DefaultMqttPublisher(const DefaultMqttPublisher& src); // copy constructor }; #endif /* LIB_MQTT_CLIENT_MQTTTOPIC_H_ */ <file_sep>/* * IMqttClientWrapper.h * * Created on: 18.10.2016 * Author: nid */ #ifndef LIB_MQTT_CLIENT_IMQTTCLIENTWRAPPER_H_ #define LIB_MQTT_CLIENT_IMQTTCLIENTWRAPPER_H_ class Client; class IMqttClientCallbackAdapter { protected: IMqttClientCallbackAdapter() { } public: virtual ~IMqttClientCallbackAdapter() { } virtual void messageReceived(const char* topic, const char* payload, unsigned int length) = 0; }; class IMqttClientWrapper { protected: IMqttClientWrapper() { } public: virtual ~IMqttClientWrapper() { } /** * Set callback adapter. * @param IMqttClientCallbackAdapter Pointer to an object implementing the interface to the MQTT Client Callback Adapter. */ virtual void setCallbackAdapter(IMqttClientCallbackAdapter* callbackAdapter) = 0; virtual IMqttClientCallbackAdapter* callbackAdapter() = 0; virtual void begin(const char* domain, uint16_t port, Client& client) = 0; /** * Process MQTT messages. * To be called in the Arduino loop() function. * @return Connect status, true: connected, false: disconnected */ virtual bool loop() = 0; virtual bool connect(const char* id) = 0; virtual void disconnect() = 0; virtual bool connected() = 0; /** * Publish data in a message to the mentioned MQTT Topic. * @param topic The MQTT topic to publish to * @param data The data to be published * @return */ virtual unsigned char publish(const char* topic, const char* data) = 0; /** * Subscribe the mentioned MQTT Topic. * @param topic The MQTT topic to subscribe from */ virtual unsigned char subscribe(const char* topic) = 0; /** * Unsubscribe the mentioned MQTT Topic. * @param topic The MQTT topic to unsubscribe */ virtual unsigned char unsubscribe(const char* topic) = 0; typedef enum { eIMqttCS_Connected = 0, eIMqttCS_ConnectBadProtocol = 1, eIMqttCS_ConnectBadClientId = 2, eIMqttCS_ConnectUnavailable = 3, eIMqttCS_ConnectBadCredentials = 4, eIMqttCS_ConnectUnauthorized = 5, eIMqttCS_ConnectionTimeout = 12, eIMqttCS_ConnectionLost = 13, eIMqttCS_ConnectFailed = 14, eIMqttCS_Disconnected = 15 } eIMqttClientState; virtual eIMqttClientState state() = 0; virtual const char* stateStr() { eIMqttClientState st = state(); return ( (eIMqttCS_Connected == st) ? "MqttCS_Connected" : (eIMqttCS_ConnectBadProtocol == st) ? "MqttCS_ConnectBadProtocol" : (eIMqttCS_ConnectBadClientId == st) ? "MqttCS_ConnectBadClientId" : (eIMqttCS_ConnectUnavailable == st) ? "MqttCS_ConnectUnavailable" : (eIMqttCS_ConnectBadCredentials == st) ? "MqttCS_ConnectBadCredentials" : (eIMqttCS_ConnectUnauthorized == st) ? "MqttCS_ConnectUnauthorized" : (eIMqttCS_ConnectionTimeout == st) ? "MqttCS_ConnectionTimeout" : (eIMqttCS_ConnectionLost == st) ? "MqttCS_ConnectionLost" : (eIMqttCS_ConnectFailed == st) ? "MqttCS_ConnectFailed" : (eIMqttCS_Disconnected == st) ? "MqttCS_Disconnected" : "MqttCS_UNKNOWN"); } private: // forbidden default functions IMqttClientWrapper& operator = (const IMqttClientWrapper& src); // assignment operator IMqttClientWrapper(const IMqttClientWrapper& src); // copy constructor }; #endif /* LIB_MQTT_CLIENT_IMQTTCLIENTWRAPPER_H_ */ <file_sep>/* * MqttClientDbgCommand.h * * Created on: 18.10.2016 * Author: nid */ #ifndef LIB_MQTT_CLIENT_MQTTCLIENTDBGCOMMAND_H_ #define LIB_MQTT_CLIENT_MQTTCLIENTDBGCOMMAND_H_ #include <DbgCliCommand.h> class DbgCli_Topic; class MqttClientController; //----------------------------------------------------------------------------- class DbgCli_Cmd_MqttClientCon : public DbgCli_Command { private: MqttClientController* m_mqttClient; public: DbgCli_Cmd_MqttClientCon(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient); void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle); void printUsage(); }; //----------------------------------------------------------------------------- class DbgCli_Cmd_MqttClientDis : public DbgCli_Command { private: MqttClientController* m_mqttClient; public: DbgCli_Cmd_MqttClientDis(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient); void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle); void printUsage(); }; //----------------------------------------------------------------------------- class DbgCli_Cmd_MqttClientPub : public DbgCli_Command { private: MqttClientController* m_mqttClient; public: DbgCli_Cmd_MqttClientPub(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient); void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle); void printUsage(); }; //----------------------------------------------------------------------------- class DbgCli_Cmd_MqttClientSub : public DbgCli_Command { private: MqttClientController* m_mqttClient; public: DbgCli_Cmd_MqttClientSub(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient); void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle); void printUsage(); }; //----------------------------------------------------------------------------- class DbgCli_Cmd_MqttClientUnsub : public DbgCli_Command { private: MqttClientController* m_mqttClient; public: DbgCli_Cmd_MqttClientUnsub(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient); void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle); void printUsage(); }; //----------------------------------------------------------------------------- class DbgCli_Cmd_MqttClientShow : public DbgCli_Command { private: MqttClientController* m_mqttClient; public: DbgCli_Cmd_MqttClientShow(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient); void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle); void printUsage(); }; //----------------------------------------------------------------------------- #endif /* LIB_MQTT_CLIENT_MQTTCLIENTDBGCOMMAND_H_ */ <file_sep>/* * MqttTopic.cpp * * Created on: 16.12.2016 * Author: nid */ #include <string.h> #include <stdio.h> #include <DbgTracePort.h> #include <DbgTraceLevel.h> #include <MqttClientController.h> #include <MqttTopic.h> //----------------------------------------------------------------------------- TopicLevel::TopicLevel(const char* level, unsigned int idx) : m_idx(idx) , m_levelSize(strlen(level)+1) , m_level(new char[m_levelSize]) , m_wcType(eTWC_None) , m_next(0) { strncpy(m_level, level, m_levelSize); if (strncmp(m_level, "+", m_levelSize) == 0) { m_wcType = eTWC_Single; } else if (strncmp(level, "#", m_levelSize) == 0) { m_wcType = eTWC_Multi; } } TopicLevel::~TopicLevel() { delete m_next; m_next = 0; delete [] m_level; m_level = 0; } void TopicLevel::append(TopicLevel* level) { if (0 == m_next) { m_next = level; } else { m_next->append(level); } } TopicLevel* TopicLevel::next() { return m_next; } const char* TopicLevel::level() const { return m_level; } unsigned int TopicLevel::idx() const { return m_idx; } TopicLevel::WildcardType TopicLevel::getWildcardType() { return m_wcType; } //----------------------------------------------------------------------------- const unsigned int MqttTopic::s_maxNumOfTopicLevels = 25; MqttTopic::MqttTopic(const char* topic) : m_topic(new char[strlen(topic)+1]) , m_topicLevelCount(0) , m_levelList(0) , m_hasWildcards(false) { memset(m_topic, 0, strlen(topic)+1); strncpy(m_topic, topic, strlen(topic)); char tmpTopic[strlen(topic)+1]; memset(tmpTopic, 0, strlen(topic)+1); strncpy(tmpTopic, topic, strlen(topic)); unsigned int i = 0; TopicLevel* levelObj = 0; char* level = strtok(tmpTopic, "/"); while (level != 0) { levelObj = new TopicLevel(level, i); m_hasWildcards |= TopicLevel::eTWC_None != levelObj->getWildcardType(); appendLevel(levelObj); level = strtok(0, "/"); i++; } m_topicLevelCount = i; // Serial.print("Topic: "); // Serial.print(m_topic); // Serial.print(", #levels: "); // Serial.print(m_topicLevelCount); // Serial.print(", has "); // Serial.print(!hasWildcards() ? "no " : ""); // Serial.println("Wildcards"); // levelObj = getLevelList(); // while(0 != levelObj) // { // Serial.print("["); // Serial.print(levelObj->idx()); // Serial.print("] - "); // Serial.println(levelObj->level()); // levelObj = levelObj->next(); // } } MqttTopic::~MqttTopic() { delete m_levelList; m_levelList = 0; delete [] m_topic; m_topic = 0; } const char* MqttTopic::getTopicString() const { return m_topic; } bool MqttTopic::hasWildcards() const { return m_hasWildcards; } void MqttTopic::appendLevel(TopicLevel* level) { if (0 == m_levelList) { m_levelList = level; } else { m_levelList->append(level); } } TopicLevel* MqttTopic::getLevelList() const { return m_levelList; } //----------------------------------------------------------------------------- const unsigned int MqttTopicPublisher::s_maxDataSize = 500; const bool MqttTopicPublisher::DO_AUTO_PUBLISH = true; const bool MqttTopicPublisher::DONT_AUTO_PUBLISH = false; MqttTopicPublisher::MqttTopicPublisher(const char* topic, const char* data, bool isAutoPublish) : MqttTopic(topic) , m_next(0) , m_data(new char[s_maxDataSize+1]) , m_isAutoPublish(isAutoPublish) { memset(m_data, 0, s_maxDataSize+1); strncpy(m_data, data, s_maxDataSize); MqttClientController::Instance()->addMqttPublisher(this); if (m_isAutoPublish) { int r = MqttClientController::Instance()->publish(getTopicString(), m_data); if (0 == r) { TR_PRINTF(MqttClientController::Instance()->trPort(), DbgTrace_Level::error, "ERROR! - publish failed"); } } } MqttTopicPublisher::~MqttTopicPublisher() { MqttClientController::Instance()->deletePublisher(this); delete [] m_data; m_data = 0; } void MqttTopicPublisher::setData(const char* data) { memset(m_data, 0, s_maxDataSize+1); strncpy(m_data, data, s_maxDataSize); } const char* MqttTopicPublisher::getData() const { return m_data; } void MqttTopicPublisher::publish(const char* data) { int r = MqttClientController::Instance()->publish(getTopicString(), data); if (0 == r) { TR_PRINTF(MqttClientController::Instance()->trPort(), DbgTrace_Level::error, "ERROR! - publish failed"); } } void MqttTopicPublisher::publish() { int r = MqttClientController::Instance()->publish(getTopicString(), m_data); if (0 == r) { TR_PRINTF(MqttClientController::Instance()->trPort(), DbgTrace_Level::error, "ERROR! - publish failed"); } } void MqttTopicPublisher::publishAll() { if (m_isAutoPublish) { int r = MqttClientController::Instance()->publish(getTopicString(), m_data); if (0 == r) { TR_PRINTF(MqttClientController::Instance()->trPort(), DbgTrace_Level::error, "ERROR! - publish failed"); } } if (0 != next()) { next()->publishAll(); } } void MqttTopicPublisher::setNext(MqttTopicPublisher* mqttPublisher) { m_next = mqttPublisher; } MqttTopicPublisher* MqttTopicPublisher::next() { return m_next; } //----------------------------------------------------------------------------- const unsigned int MqttRxMsg::s_maxRxMsgSize = 500; MqttRxMsg::MqttRxMsg() : m_rxTopic(0) , m_rxMsg(new char[s_maxRxMsgSize+1]) , m_rxMsgSize(0) { memset(m_rxMsg, 0, s_maxRxMsgSize+1); } MqttRxMsg::~MqttRxMsg() { delete [] m_rxMsg; m_rxMsg = 0; delete m_rxTopic; m_rxTopic = 0; } void MqttRxMsg::prepare(const char* topic, const char* payload, unsigned int length) { if (length > s_maxRxMsgSize) { m_rxMsgSize = s_maxRxMsgSize; } else { m_rxMsgSize = length; } memcpy(m_rxMsg, payload, length); m_rxMsg[m_rxMsgSize] = 0; delete m_rxTopic; m_rxTopic = new MqttTopic(topic); } MqttTopic* MqttRxMsg::getRxTopic() const { return m_rxTopic; } const char* MqttRxMsg::getRxMsgString() const { return m_rxMsg; } const unsigned int MqttRxMsg::getRxMsgSize() const { return m_rxMsgSize; } //----------------------------------------------------------------------------- MqttTopicSubscriber::MqttTopicSubscriber(const char* topic) : MqttTopic(topic) , m_next(0) { MqttClientController::Instance()->addMqttSubscriber(this); MqttClientController::Instance()->subscribe(topic); } MqttTopicSubscriber::~MqttTopicSubscriber() { MqttClientController::Instance()->unsubscribe(getTopicString()); MqttClientController::Instance()->deleteSubscriber(this); } void MqttTopicSubscriber::setNext(MqttTopicSubscriber* mqttSubscriber) { m_next = mqttSubscriber; } bool MqttTopicSubscriber::isMyTopic(MqttRxMsg* rxMsg) const { bool ismytopic = false; if ((0 != rxMsg) && (0 != rxMsg->getRxTopic())) { if (hasWildcards()) { // handle smart compare bool stillMatch = true; TopicLevel* subscriberTopicLevel = getLevelList(); TopicLevel* rxTopicLevel = rxMsg->getRxTopic()->getLevelList(); while(stillMatch && (0 != subscriberTopicLevel) && (0 != rxTopicLevel)) { if (TopicLevel::eTWC_None == subscriberTopicLevel->getWildcardType()) { stillMatch &= (strcmp(subscriberTopicLevel->level(), rxTopicLevel->level()) == 0); } subscriberTopicLevel = subscriberTopicLevel->next(); rxTopicLevel = rxTopicLevel->next(); } ismytopic = stillMatch; } else { if (strcmp(getTopicString(), rxMsg->getRxTopic()->getTopicString()) == 0) { ismytopic = true; } } } return ismytopic; } void MqttTopicSubscriber::handleMessage(MqttRxMsg* rxMsg, DbgTrace_Port* trPortMqttRx) { if ((0 != trPortMqttRx) && (0 != rxMsg) && (0 != rxMsg->getRxTopic())) { TR_PRINTF(trPortMqttRx, DbgTrace_Level::debug, "MqttTopicSubscriber::handleMessage(), topic: %s, rx topic: %s, rx msg: %s", getTopicString(), rxMsg->getRxTopic()->getTopicString(), rxMsg->getRxMsgString()); } bool msgHasBeenHandled = false; if (isMyTopic(rxMsg)) { // take responsibility msgHasBeenHandled = processMessage(rxMsg); } if (!msgHasBeenHandled) { if (0 != next()) { next()->handleMessage(rxMsg, trPortMqttRx); } } } void MqttTopicSubscriber::subscribe() { MqttClientController::Instance()->subscribe(getTopicString()); if (0 != next()) { next()->subscribe(); } } MqttTopicSubscriber* MqttTopicSubscriber::next() { return m_next; } //----------------------------------------------------------------------------- DefaultMqttSubscriber::DefaultMqttSubscriber(const char* topic) : MqttTopicSubscriber(topic) , m_trPort(new DbgTrace_Port("mqttdfltsub", DbgTrace_Level::debug)) { } bool DefaultMqttSubscriber::processMessage(MqttRxMsg* rxMsg) { bool msgHasBeenHandled = false; if (0 != rxMsg) { msgHasBeenHandled = true; TR_PRINTF(m_trPort, DbgTrace_Level::debug, "DefaultMqttSubscriber (%s), rx: [%s] %s", getTopicString(), rxMsg->getRxTopic()->getTopicString(), rxMsg->getRxMsgString()); } return msgHasBeenHandled; } //----------------------------------------------------------------------------- DefaultMqttPublisher::DefaultMqttPublisher(const char* topic, const char* data) : MqttTopicPublisher(topic, data) , m_trPort(new DbgTrace_Port("mqttdfltpub", DbgTrace_Level::debug)) { } void DefaultMqttPublisher::publish(const char* data) { TR_PRINTF(m_trPort, DbgTrace_Level::debug, "DefaultMqttPublisher (%s), tx: %s", getTopicString(), data); MqttTopicPublisher::publish(data); } <file_sep>#include <Arduino.h> #ifdef ESP8266 #include <ESP8266WiFi.h> #elif defined(ESP32) #include <WiFi.h> // see https://github.com/espressif/arduino-esp32/issues/1960#issuecomment-429546528 #endif #include <SerialCommand.h> #include <SpinTimer.h> #include <AppDebug.h> #include <DbgCliNode.h> #include <DbgCliTopic.h> #include <DbgCliCommand.h> #include <DbgTracePort.h> #include <DbgTraceLevel.h> #include <ECMqttClient.h> // ERNI Community MQTT client wrapper library #include <MqttTopic.h> #define MQTT_SERVER "test.mosquitto.org" SerialCommand* sCmd = 0; //----------------------------------------------------------------------------- // ESP8266 / ESP32 WiFi Client //----------------------------------------------------------------------------- #if defined(ESP8266) || defined(ESP32) WiFiClient wifiClient; #endif //----------------------------------------------------------------------------- void setBuiltInLed(bool state) { #if defined(ESP8266) digitalWrite(LED_BUILTIN, !state); // LED state is inverted on ESP8266 #else digitalWrite(LED_BUILTIN, state); #endif } //----------------------------------------------------------------------------- // WiFi Commands //----------------------------------------------------------------------------- class DbgCli_Cmd_WifiMac : public DbgCli_Command { public: DbgCli_Cmd_WifiMac(DbgCli_Topic* wifiTopic) : DbgCli_Command(wifiTopic, "mac", "Print MAC Address.") { } void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { Serial.println(); Serial.print("Wifi MAC: "); Serial.println(WiFi.macAddress().c_str()); Serial.println(); } }; class DbgCli_Cmd_WifiNets : public DbgCli_Command { public: DbgCli_Cmd_WifiNets(DbgCli_Topic* wifiTopic) : DbgCli_Command(wifiTopic, "nets", "Print nearby networks.") { } void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { bool bailOut = false; // scan for nearby networks: Serial.println(); Serial.println("** Scan Networks **"); int numSsid = WiFi.scanNetworks(); if (numSsid == -1) { Serial.println("Couldn't get a wifi connection"); bailOut = true; } if (!bailOut) { // print the list of networks seen: Serial.print("number of available networks:"); Serial.println(numSsid); // print the network number and name for each network found: for (int thisNet = 0; thisNet < numSsid; thisNet++) { Serial.print(thisNet); Serial.print(") "); Serial.print(WiFi.SSID(thisNet)); Serial.print(" - Signal: "); Serial.print(WiFi.RSSI(thisNet)); Serial.print(" dBm"); Serial.print(" - Encryption: "); printEncryptionType(WiFi.encryptionType(thisNet)); } } Serial.println(); } private: void printEncryptionType(int thisType) { // read the encryption type and print out the name: switch (thisType) { #if ! defined(ESP32) // TODO: solve this for ESP32! case ENC_TYPE_WEP: Serial.println("WEP"); break; case ENC_TYPE_TKIP: Serial.println("WPA"); break; case ENC_TYPE_CCMP: Serial.println("WPA2"); break; case ENC_TYPE_NONE: Serial.println("None"); break; case ENC_TYPE_AUTO: Serial.println("Auto"); break; #endif default: Serial.println("Unknown"); break; } } }; class DbgCli_Cmd_WifiStat : public DbgCli_Command { public: DbgCli_Cmd_WifiStat(DbgCli_Topic* wifiTopic) : DbgCli_Command(wifiTopic, "stat", "Show WiFi connection status.") { } void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { wl_status_t wlStatus = WiFi.status(); Serial.println(); Serial.println(wlStatus == WL_NO_SHIELD ? "NO_SHIELD " : wlStatus == WL_IDLE_STATUS ? "IDLE_STATUS " : wlStatus == WL_NO_SSID_AVAIL ? "NO_SSID_AVAIL " : wlStatus == WL_SCAN_COMPLETED ? "SCAN_COMPLETED " : wlStatus == WL_CONNECTED ? "CONNECTED " : wlStatus == WL_CONNECT_FAILED ? "CONNECT_FAILED " : wlStatus == WL_CONNECTION_LOST ? "CONNECTION_LOST" : wlStatus == WL_DISCONNECTED ? "DISCONNECTED " : "UNKNOWN"); Serial.println(); WiFi.printDiag(Serial); Serial.println(); } }; class DbgCli_Cmd_WifiDis : public DbgCli_Command { public: DbgCli_Cmd_WifiDis(DbgCli_Topic* wifiTopic) : DbgCli_Command(wifiTopic, "dis", "Disconnect WiFi.") { } void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { Serial.println(); if (argc - idxToFirstArgToHandle > 0) { printUsage(); } else { const bool DO_NOT_SET_wifioff = false; WiFi.disconnect(DO_NOT_SET_wifioff); Serial.println("WiFi is disconnected now."); } Serial.println(); } void printUsage() { Serial.println(getHelpText()); Serial.println("Usage: dbg wifi dis"); } }; //----------------------------------------------------------------------------- class DbgCli_Cmd_WifiCon : public DbgCli_Command { public: DbgCli_Cmd_WifiCon(DbgCli_Topic* wifiTopic) : DbgCli_Command(wifiTopic, "con", "Connect to WiFi.") { } void execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { Serial.println(); if (argc - idxToFirstArgToHandle != 2) { printUsage(); } else { const char* ssid = args[idxToFirstArgToHandle]; const char* pass = args[idxToFirstArgToHandle+1]; Serial.print("SSID: "); Serial.print(ssid); Serial.print(", pass: "); Serial.println(pass); WiFi.begin(ssid, pass); Serial.println("WiFi is connecting now."); } Serial.println(); } void printUsage() { Serial.println(getHelpText()); Serial.println("Usage: dbg wifi con <SSID> <passwd>"); } }; //----------------------------------------------------------------------------- class TestLedMqttSubscriber : public MqttTopicSubscriber { public: TestLedMqttSubscriber() : MqttTopicSubscriber("test/led") { } virtual ~TestLedMqttSubscriber() { } bool processMessage(MqttRxMsg* rxMsg) { bool msgHasBeenHandled = false; if (0 != rxMsg) { // this subscriber object takes the responsibility bool state = atoi(rxMsg->getRxMsgString()); setBuiltInLed(state); // ... and marks the received message as handled (chain of responsibilities) msgHasBeenHandled = true; } return msgHasBeenHandled; } }; void setup() { pinMode(LED_BUILTIN, OUTPUT); setBuiltInLed(false); Serial.begin(9600); setupDebugEnv(); //----------------------------------------------------------------------------- // WiFi Commands //----------------------------------------------------------------------------- #if defined(ESP8266) || defined(ESP32) DbgCli_Topic* wifiTopic = new DbgCli_Topic(DbgCli_Node::RootNode(), "wifi", "WiFi debug commands"); new DbgCli_Cmd_WifiMac(wifiTopic); new DbgCli_Cmd_WifiNets(wifiTopic); new DbgCli_Cmd_WifiStat(wifiTopic); new DbgCli_Cmd_WifiDis(wifiTopic); new DbgCli_Cmd_WifiCon(wifiTopic); #endif //----------------------------------------------------------------------------- // ESP8266 / ESP32 WiFi Client //----------------------------------------------------------------------------- WiFi.mode(WIFI_STA); //----------------------------------------------------------------------------- // MQTT Client //----------------------------------------------------------------------------- ECMqttClient.begin(MQTT_SERVER, ECMqttClientClass::defaultMqttPort, wifiClient, WiFi.macAddress().c_str()); new TestLedMqttSubscriber(); } void loop() { if (0 != sCmd) { sCmd->readSerial(); // process serial commands } ECMqttClient.loop(); // process MQTT Client scheduleTimers(); // process Timers } <file_sep>/* * ECMqttClient.cpp * * Created on: 23.06.2017 * Author: nid */ #include <Client.h> #include <MqttClientController.h> #include <ECMqttClient.h> const unsigned short int ECMqttClientClass::defaultMqttPort = 1883; const unsigned short int ECMqttClientClass::defaultSecureMqttPort = 8883; void ECMqttClientClass::begin(const char* address, unsigned short int port, Client& client, const char* id) { MqttClientController::Instance()->begin(address, port, client, id); } void ECMqttClientClass::loop() { MqttClientController::Instance()->loop(); } ECMqttClientClass ECMqttClient; <file_sep>/* * mqttClientWrapper.h * * Created on: 22.06.2018 * Author: nid */ #ifndef LIB_MQTT_CLIENT_MQTTCLIENTWRAPPER_H_ #define LIB_MQTT_CLIENT_MQTTCLIENTWRAPPER_H_ #include <IMqttClientWrapper.h> #include <MqttClientController.h> class MQTTClient; class DbgTrace_Port; class MqttRxMsg; class MqttClientWrapper: public IMqttClientWrapper { public: MqttClientWrapper(); virtual ~MqttClientWrapper(); void setCallbackAdapter(IMqttClientCallbackAdapter* callbackAdapter); IMqttClientCallbackAdapter* callbackAdapter(); void begin(const char* domain, uint16_t port, Client& client); bool loop(); bool connect(const char* id); void disconnect(); bool connected(); unsigned char publish(const char* topic, const char* data); unsigned char subscribe(const char* topic); unsigned char unsubscribe(const char* topic); eIMqttClientState state(); public: static IMqttClientWrapper* s_mqttClientWrapper; static void (*callback)(char*, uint8_t*, unsigned int); private: MQTTClient* m_mqttClient; IMqttClientCallbackAdapter* m_callbackAdapter; private: // forbidden default functions MqttClientWrapper& operator = (const MqttClientWrapper& src); // assignment operator MqttClientWrapper(const MqttClientWrapper& src); // copy constructor }; //----------------------------------------------------------------------------- class MqttClientCallbackAdapter : public IMqttClientCallbackAdapter { private: DbgTrace_Port* m_trPortMqttRx; MqttRxMsg* m_rxMsg; public: MqttClientCallbackAdapter(); virtual ~MqttClientCallbackAdapter(); void messageReceived(const char* topic, const char* payload, unsigned int length); private: // forbidden default functions MqttClientCallbackAdapter& operator = (const MqttClientCallbackAdapter& src); // assignment operator MqttClientCallbackAdapter(const MqttClientCallbackAdapter& src); // copy constructor }; #endif /* LIB_MQTT_CLIENT_MQTTCLIENTWRAPPER_H_ */ <file_sep>/* * MqttClientDbgCommand.cpp * * Created on: 18.10.2016 * Author: nid */ #include <DbgCliNode.h> #include <DbgCliTopic.h> #include <DbgTraceContext.h> #include <DbgTracePort.h> #include <DbgTraceLevel.h> #include <DbgPrintConsole.h> #include <DbgTraceOut.h> #include <IMqttClientWrapper.h> #include <MqttClientController.h> #include <MqttClientDbgCommand.h> #include <ConnectionMonitor.h> #include <MqttTopic.h> //----------------------------------------------------------------------------- DbgCli_Cmd_MqttClientCon::DbgCli_Cmd_MqttClientCon(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient) : DbgCli_Command(mqttClientTopic, "con", "Connect MQTT client to broker.") , m_mqttClient(mqttClient) { } void DbgCli_Cmd_MqttClientCon::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { if (argc - idxToFirstArgToHandle > 0) { printUsage(); } else { if (0 != m_mqttClient) { if (m_mqttClient->mqttClientWrapper()->connected()) { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "MQTT client is already connected to broker."); } else { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "MQTT client connecting to broker now."); m_mqttClient->setShallConnect(true); } } } } void DbgCli_Cmd_MqttClientCon::printUsage() { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "%s", getHelpText()); TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "Usage: %s %s %s", RootNode()->getNodeName(), getParentNode()->getNodeName(), getNodeName()); } //----------------------------------------------------------------------------- DbgCli_Cmd_MqttClientDis::DbgCli_Cmd_MqttClientDis(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient) : DbgCli_Command(mqttClientTopic, "dis", "Disconnect MQTT client from broker.") , m_mqttClient(mqttClient) { } void DbgCli_Cmd_MqttClientDis::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { if (argc - idxToFirstArgToHandle > 0) { printUsage(); } else { if (0 != m_mqttClient) { m_mqttClient->setShallConnect(false); TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "MQTT client disconnecting from broker now."); } } } void DbgCli_Cmd_MqttClientDis::printUsage() { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "%s", getHelpText()); TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "Usage: %s %s %s", RootNode()->getNodeName(), getParentNode()->getNodeName(), getNodeName()); } //----------------------------------------------------------------------------- DbgCli_Cmd_MqttClientPub::DbgCli_Cmd_MqttClientPub(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient) : DbgCli_Command(mqttClientTopic, "pub", "Publish a value to a topic using MQTT client.") , m_mqttClient(mqttClient) { } void DbgCli_Cmd_MqttClientPub::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { if (argc - idxToFirstArgToHandle != 2) { printUsage(); } else { if (0 != m_mqttClient) { MqttTopicPublisher* publisher = m_mqttClient->findPublisherByTopic(args[idxToFirstArgToHandle]); if (0 == publisher) { publisher = new MqttTopicPublisher(args[idxToFirstArgToHandle], args[idxToFirstArgToHandle+1], MqttTopicPublisher::DO_AUTO_PUBLISH); } else { publisher->setData(args[idxToFirstArgToHandle+1]); publisher->publish(); } TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "MQTT client, published to %s", publisher->getTopicString(), publisher->getData()); } } } void DbgCli_Cmd_MqttClientPub::printUsage() { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "%s", getHelpText()); TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "Usage: %s %s %s <topic> <value>", RootNode()->getNodeName(), getParentNode()->getNodeName(), getNodeName()); } //----------------------------------------------------------------------------- DbgCli_Cmd_MqttClientSub::DbgCli_Cmd_MqttClientSub(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient) : DbgCli_Command(mqttClientTopic, "sub", "Subscribe to a topic using MQTT client.") , m_mqttClient(mqttClient) { } void DbgCli_Cmd_MqttClientSub::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { if (argc - idxToFirstArgToHandle != 1) { printUsage(); } else { if (0 != m_mqttClient) { MqttTopicSubscriber* subscriber = m_mqttClient->findSubscriberByTopic(args[idxToFirstArgToHandle]); if (0 == subscriber) { subscriber = new DefaultMqttSubscriber(args[idxToFirstArgToHandle]); TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "MQTT client, subscribed to %s", subscriber->getTopicString()); } else { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "MQTT client, already subscribed to %s", subscriber->getTopicString()); } } } } void DbgCli_Cmd_MqttClientSub::printUsage() { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "%s", getHelpText()); TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "Usage: %s %s %s <topic>", RootNode()->getNodeName(), getParentNode()->getNodeName(), getNodeName()); } //----------------------------------------------------------------------------- DbgCli_Cmd_MqttClientUnsub::DbgCli_Cmd_MqttClientUnsub(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient) : DbgCli_Command(mqttClientTopic, "unsub", "Unsubscribe a topic using MQTT client.") , m_mqttClient(mqttClient) { } void DbgCli_Cmd_MqttClientUnsub::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { if (argc - idxToFirstArgToHandle != 1) { printUsage(); } else { if (0 != m_mqttClient) { MqttTopicSubscriber* subscriber = m_mqttClient->findSubscriberByTopic(args[idxToFirstArgToHandle]); if (0 != subscriber) { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "MQTT client, unsubscribing from %s", subscriber->getTopicString()); delete subscriber; subscriber = 0; } else { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "MQTT client, unsubscribe not possible, topic %s was not subscribed.", args[idxToFirstArgToHandle]); } } } } void DbgCli_Cmd_MqttClientUnsub::printUsage() { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "%s", getHelpText()); TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "Usage: %s %s %s <topic>", RootNode()->getNodeName(), getParentNode()->getNodeName(), getNodeName()); } //----------------------------------------------------------------------------- DbgCli_Cmd_MqttClientShow::DbgCli_Cmd_MqttClientShow(DbgCli_Topic* mqttClientTopic, MqttClientController* mqttClient) : DbgCli_Command(mqttClientTopic, "show", "Show info from the MQTT client.") , m_mqttClient(mqttClient) { } void DbgCli_Cmd_MqttClientShow::execute(unsigned int argc, const char** args, unsigned int idxToFirstArgToHandle) { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "Subscriber Topics:"); MqttTopicSubscriber* subscriber = m_mqttClient->mqttSubscriberChain(); if (0 == subscriber) { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "=x= no subscribers in the list."); } while (0 != subscriber) { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "- %s", subscriber->getTopicString()); subscriber = subscriber->next(); } TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "Publisher Topics:"); MqttTopicPublisher* publisher = m_mqttClient->mqttPublisherChain(); if (0 == publisher) { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "=x= no publishers in the list."); } while (0 != publisher) { TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "- %s", publisher->getTopicString()); publisher = publisher->next(); } TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "MQTT Client Status: Shall %s connect", m_mqttClient->getShallConnect() ? "" : "not "); TR_PRINTF(m_mqttClient->trPort(), DbgTrace_Level::alert, "Connection Monitor State: %s", m_mqttClient->connMon()->state()->toString()); m_mqttClient->loop(); } //----------------------------------------------------------------------------- <file_sep>/* * ECMqttClient.h * * Created on: 23.06.2017 * Author: nid */ #ifndef LIB_MQTT_CLIENT_MODEL_ERNICOMMUNITYMQTTCLIENT_H_ #define LIB_MQTT_CLIENT_MODEL_ERNICOMMUNITYMQTTCLIENT_H_ class Client; class ECMqttClientClass { public: static const unsigned short int defaultMqttPort; static const unsigned short int defaultSecureMqttPort; ECMqttClientClass() { } virtual ~ECMqttClientClass() { } void begin(const char* address, unsigned short int port, Client& client, const char* id); void loop(); private: // forbidden default functions ECMqttClientClass& operator = (const ECMqttClientClass& src); // assignment operator ECMqttClientClass(const ECMqttClientClass& src); // copy constructor }; extern ECMqttClientClass ECMqttClient; #endif /* LIB_MQTT_CLIENT_MODEL_ERNICOMMUNITYMQTTCLIENT_H_ */ <file_sep>/* * LanConnectionMonitor.h * * Created on: 26.10.2016 * Author: dini */ #ifndef LIB_MQTT_CLIENT_CONNECTIONMONITOR_H_ #define LIB_MQTT_CLIENT_CONNECTIONMONITOR_H_ class SpinTimer; class ConnMonState; class DbgTrace_Port; class ConnMonAdapter { public: ConnMonAdapter(); virtual ~ConnMonAdapter(); virtual bool lanConnectedRaw(); virtual bool appProtocolConnectedRaw(); virtual bool shallAppProtocolConnect(); virtual void actionConnectAppProtocol() { } virtual void notifyLanConnected(bool isLanConnected) { } virtual void notifyAppProtocolConnected(bool isMqttConnected) { } DbgTrace_Port* trPort(); private: DbgTrace_Port* m_trPort; private: // forbidden default functions ConnMonAdapter& operator =(const ConnMonAdapter& src); // assignment operator ConnMonAdapter(const ConnMonAdapter& src); // copy constructor }; class ConnMon { public: ConnMon(ConnMonAdapter* adapter = 0); virtual ~ConnMon(); ConnMonAdapter* adapter(); bool isLanDeviceConnected(); bool isAppProtocolLibConnected(); bool shallAppProtocolConnect(); bool isLanConnected(); bool isAppProtocolConnected(); void evaluateState(); void changeState(ConnMonState* newState); ConnMonState* state(); ConnMonState* prevState(); void startStableLanConnCheckTimer(); private: SpinTimer* m_statusPollTimer; SpinTimer* m_stableConnCheckTimer; ConnMonAdapter* m_adapter; ConnMonState* m_state; ConnMonState* m_prevState; private: // forbidden default functions ConnMon& operator =(const ConnMon& src); // assignment operator ConnMon(const ConnMon& src); // copy constructor }; //----------------------------------------------------------------------------- class ConnMonState { protected: ConnMonState() { } public: virtual ~ConnMonState() { } virtual void evaluateState(ConnMon* monitor) = 0; // virtual void evaluateState(ConnMon* monitor, bool mqttState) { } virtual void timeExpired(ConnMon* monitor) { } virtual void entry(ConnMon* monitor); virtual const char* toString() = 0; }; //----------------------------------------------------------------------------- class ConnMonState_Unconnected : public ConnMonState { private: ConnMonState_Unconnected() { } public: static ConnMonState* Instance(); virtual ~ConnMonState_Unconnected() { } void evaluateState(ConnMon* monitor); void entry(ConnMon* monitor); const char* toString(); private: static ConnMonState* s_instance; }; //----------------------------------------------------------------------------- class ConnMonState_LanConnected : public ConnMonState { private: ConnMonState_LanConnected() { } public: static ConnMonState* Instance(); virtual ~ConnMonState_LanConnected() { } void evaluateState(ConnMon* monitor); void timeExpired(ConnMon* monitor); void entry(ConnMon* monitor); const char* toString(); private: static ConnMonState* s_instance; }; //----------------------------------------------------------------------------- class ConnMonState_StableLanConnection : public ConnMonState { private: ConnMonState_StableLanConnection() { } public: static ConnMonState* Instance(); virtual ~ConnMonState_StableLanConnection() { } void evaluateState(ConnMon* monitor); // void evaluateState(ConnMon* monitor, bool mqttState); void entry(ConnMon* monitor); const char* toString(); private: static ConnMonState* s_instance; }; //----------------------------------------------------------------------------- class ConnMonState_AppProtocolConnected : public ConnMonState { private: ConnMonState_AppProtocolConnected() { } public: static ConnMonState* Instance(); virtual ~ConnMonState_AppProtocolConnected() { } void evaluateState(ConnMon* monitor); // void evaluateState(ConnMon* monitor, bool mqttState); void entry(ConnMon* monitor); const char* toString(); private: static ConnMonState* s_instance; }; //----------------------------------------------------------------------------- #endif /* LIB_MQTT_CLIENT_CONNECTIONMONITOR_H_ */ <file_sep>/* * LanConnectionMonitor.cpp * * Created on: 26.10.2016 * Author: dini */ #ifdef ESP8266 #include <ESP8266WiFi.h> #elif defined(ESP32) #include <WiFi.h> #endif #include <SpinTimer.h> #include <DbgTracePort.h> #include <DbgTraceLevel.h> #include <ConnectionMonitor.h> class StatusPollTimerAction : public SpinTimerAction { private: ConnMon* m_monitor; public: StatusPollTimerAction(ConnMon* monitor) : m_monitor(monitor) { } void timeExpired() { if (0 != m_monitor) { // Serial.println("conMon.StatusPollTimerAction::timeExpired(): calling m_monitor->evaluateState()"); m_monitor->evaluateState(); // Serial.println("conMon.StatusPollTimerAction::timeExpired(): returned from m_monitor->evaluateState()"); } } }; class StableCheckPollTimerAction : public SpinTimerAction { private: ConnMon* m_monitor; public: StableCheckPollTimerAction(ConnMon* monitor) : m_monitor(monitor) { } void timeExpired() { if ((0 != m_monitor) && (0 != m_monitor->state())) { m_monitor->state()->timeExpired(m_monitor); } } }; //----------------------------------------------------------------------------- ConnMonAdapter::ConnMonAdapter() : m_trPort(new DbgTrace_Port("conmon", DbgTrace_Level::info)) { } ConnMonAdapter::~ConnMonAdapter() { delete m_trPort; m_trPort = 0; } DbgTrace_Port* ConnMonAdapter::trPort() { return m_trPort; } bool ConnMonAdapter::lanConnectedRaw() { bool isLanConnected = false; #if (defined(ESP8266) || defined(ESP32)) isLanConnected = WiFi.isConnected(); #endif TR_PRINTF(trPort(), DbgTrace_Level::debug, "WiFi device is %sconnected", (isLanConnected ? "" : "dis")); return isLanConnected; } bool ConnMonAdapter::appProtocolConnectedRaw() { return false; } bool ConnMonAdapter::shallAppProtocolConnect() { return false; } //----------------------------------------------------------------------------- const unsigned long cStatusPollIntervalMillis = 2000; const unsigned long cStableCheckIntervalMillis = 3000; ConnMon::ConnMon(ConnMonAdapter* adapter) : m_statusPollTimer(new SpinTimer(cStatusPollIntervalMillis, new StatusPollTimerAction(this), SpinTimer::IS_RECURRING, SpinTimer::IS_AUTOSTART)) , m_stableConnCheckTimer(new SpinTimer(cStableCheckIntervalMillis, new StableCheckPollTimerAction(this), SpinTimer::IS_NON_RECURRING, SpinTimer::IS_NON_AUTOSTART)) , m_adapter(adapter) , m_state(ConnMonState_Unconnected::Instance()) , m_prevState(ConnMonState_Unconnected::Instance()) { if (0 == m_adapter) { new ConnMonAdapter(); } } ConnMon::~ConnMon() { delete m_adapter; m_adapter = 0; delete m_statusPollTimer->action(); m_statusPollTimer->attachAction(0); delete m_statusPollTimer; m_statusPollTimer = 0; delete m_stableConnCheckTimer->action(); m_stableConnCheckTimer->attachAction(0); delete m_stableConnCheckTimer; m_stableConnCheckTimer = 0; } ConnMonAdapter* ConnMon::adapter() { return m_adapter; } bool ConnMon::isLanDeviceConnected() { bool isConn = false; if (0 != m_adapter) { isConn = m_adapter->lanConnectedRaw(); } return isConn; } bool ConnMon::isAppProtocolLibConnected() { bool isConn = false; if (0 != m_adapter) { isConn = m_adapter->appProtocolConnectedRaw(); } return isConn; } bool ConnMon::shallAppProtocolConnect() { bool shallConn = false; if (0 != m_adapter) { shallConn = m_adapter->shallAppProtocolConnect(); } return shallConn; } bool ConnMon::isLanConnected() { return (ConnMonState_StableLanConnection::Instance() == state()); } bool ConnMon::isAppProtocolConnected() { return (ConnMonState_AppProtocolConnected::Instance() == state()); } void ConnMon::evaluateState() { if (0 != m_state) { m_state->evaluateState(this); } } void ConnMon::startStableLanConnCheckTimer() { m_stableConnCheckTimer->start(cStableCheckIntervalMillis); } void ConnMon::changeState(ConnMonState* newState) { m_prevState = m_state; m_state = newState; if (0 != newState) { newState->entry(this); } } ConnMonState* ConnMon::state() { return m_state; } ConnMonState* ConnMon::prevState() { return m_prevState; } //----------------------------------------------------------------------------- void ConnMonState::entry(ConnMon* monitor) { TR_PRINTF(monitor->adapter()->trPort(), DbgTrace_Level::info, "FSM, entering state %s [from %s]", monitor->state()->toString(), monitor->prevState()->toString()); } //----------------------------------------------------------------------------- ConnMonState* ConnMonState_Unconnected::s_instance = 0; ConnMonState* ConnMonState_Unconnected::Instance() { if (0 == s_instance) { s_instance = new ConnMonState_Unconnected(); } return s_instance; } void ConnMonState_Unconnected::evaluateState(ConnMon* monitor) { if (monitor->isLanDeviceConnected()) { monitor->changeState(ConnMonState_LanConnected::Instance()); } } void ConnMonState_Unconnected::entry(ConnMon* monitor) { ConnMonState::entry(monitor); monitor->adapter()->notifyLanConnected(false); monitor->adapter()->notifyAppProtocolConnected(false); } const char* ConnMonState_Unconnected::toString() { return "Unconnected"; } //----------------------------------------------------------------------------- ConnMonState* ConnMonState_LanConnected::s_instance = 0; ConnMonState* ConnMonState_LanConnected::Instance() { if (0 == s_instance) { s_instance = new ConnMonState_LanConnected(); } return s_instance; } void ConnMonState_LanConnected::evaluateState(ConnMon* monitor) { if (!monitor->isLanDeviceConnected()) { monitor->changeState(ConnMonState_Unconnected::Instance()); } } void ConnMonState_LanConnected::timeExpired(ConnMon* monitor) { if (monitor->isLanDeviceConnected()) { monitor->changeState(ConnMonState_StableLanConnection::Instance()); } else { monitor->changeState(ConnMonState_Unconnected::Instance()); } } void ConnMonState_LanConnected::entry(ConnMon* monitor) { ConnMonState::entry(monitor); monitor->startStableLanConnCheckTimer(); } const char* ConnMonState_LanConnected::toString() { return "LanConnected"; } //----------------------------------------------------------------------------- ConnMonState* ConnMonState_StableLanConnection::s_instance = 0; ConnMonState* ConnMonState_StableLanConnection::Instance() { if (0 == s_instance) { s_instance = new ConnMonState_StableLanConnection(); } return s_instance; } void ConnMonState_StableLanConnection::evaluateState(ConnMon* monitor) { if (monitor->isLanDeviceConnected()) { if (monitor->isAppProtocolLibConnected()) { monitor->changeState(ConnMonState_AppProtocolConnected::Instance()); } else { if (monitor->shallAppProtocolConnect()) { monitor->adapter()->actionConnectAppProtocol(); } } } else { monitor->changeState(ConnMonState_Unconnected::Instance()); } } void ConnMonState_StableLanConnection::entry(ConnMon* monitor) { ConnMonState::entry(monitor); monitor->adapter()->notifyLanConnected(true); } const char* ConnMonState_StableLanConnection::toString() { return "StableLanConnection"; } //----------------------------------------------------------------------------- ConnMonState* ConnMonState_AppProtocolConnected::s_instance = 0; ConnMonState* ConnMonState_AppProtocolConnected::Instance() { if (0 == s_instance) { s_instance = new ConnMonState_AppProtocolConnected(); } return s_instance; } void ConnMonState_AppProtocolConnected::evaluateState(ConnMon* monitor) { if (monitor->isLanDeviceConnected()) { if (!monitor->isAppProtocolLibConnected()) { monitor->changeState(ConnMonState_StableLanConnection::Instance()); monitor->adapter()->notifyAppProtocolConnected(false); } } else { monitor->changeState(ConnMonState_Unconnected::Instance()); } } void ConnMonState_AppProtocolConnected::entry(ConnMon* monitor) { ConnMonState::entry(monitor); monitor->adapter()->notifyAppProtocolConnected(true); } const char* ConnMonState_AppProtocolConnected::toString() { return "AppProtocolConnected"; } <file_sep>/* * MqttClientController.h * * Created on: 13.10.2016 * Author: nid */ #ifndef SRC_MQTTCLIENTCONTROLLER_H_ #define SRC_MQTTCLIENTCONTROLLER_H_ class Client; class IMqttClientWrapper; class IMqttClientCallbackAdapter; class Timer; class ConnMon; class DbgTrace_Port; class MqttTopicSubscriber; class MqttTopicPublisher; class MqttClientController { friend class MqttClientCtrlReconnectTimerAdapter; friend class MqttTopicPublisher; friend class MqttTopicSubscriber; private: MqttClientController(); public: static MqttClientController* Instance(); virtual ~MqttClientController(); static void assignMqttClientWrapper(IMqttClientWrapper* mqttClientWrapper, IMqttClientCallbackAdapter* mqttClientCallbackAdapter); static IMqttClientWrapper* mqttClientWrapper(); void begin(const char* domain, unsigned short int port, Client& client, const char* id); void setShallConnect(bool shallConnect); bool getShallConnect(); void loop(); protected: int publish(const char* topic, const char* data); int subscribe(const char* topic); int unsubscribe(const char* topic); public: bool connect(); ConnMon* connMon(); DbgTrace_Port* trPort(); const char* id(); MqttTopicSubscriber* mqttSubscriberChain(); MqttTopicPublisher* mqttPublisherChain(); MqttTopicSubscriber* findSubscriberByTopic(const char* topic); MqttTopicPublisher* findPublisherByTopic(const char* topic); protected: void deleteSubscriber(MqttTopicSubscriber* subscriberToDelete); void deletePublisher(MqttTopicPublisher* publisherToDelete); void addMqttSubscriber(MqttTopicSubscriber* mqttSubscriber); void addMqttPublisher(MqttTopicPublisher* mqttPublisher); private: static MqttClientController* s_instance; static IMqttClientWrapper* s_mqttClientWrapper; static const unsigned int s_maxIdSize; bool m_shallConnect; DbgTrace_Port* m_trPortMqttctrl; ConnMon* m_connMon; MqttTopicSubscriber* m_mqttSubscriberChain; MqttTopicPublisher* m_mqttPublisherChain; char* m_id; private: // forbidden default functions MqttClientController& operator = (const MqttClientController& src); // assignment operator MqttClientController(const MqttClientController& src); // copy constructor }; #endif /* SRC_MQTTCLIENTCONTROLLER_H_ */ <file_sep>/* * MqttClientWrapper.cpp * * Created on: 22.06.2018 * Author: nid */ #include <DbgTracePort.h> #include <DbgTraceLevel.h> #include <MQTT.h> #include <MqttTopic.h> #include <MqttClientController.h> #include <MqttClientWrapper.h> IMqttClientWrapper* MqttClientWrapper::s_mqttClientWrapper = 0; MqttClientWrapper::MqttClientWrapper() : m_mqttClient(new MQTTClient(512)) , m_callbackAdapter(0) { s_mqttClientWrapper = this; } MqttClientWrapper::~MqttClientWrapper() { } void mqttClientCallback(String& topic, String& payload) { IMqttClientWrapper* mqttWrapper = MqttClientWrapper::s_mqttClientWrapper; if (0 != mqttWrapper) { IMqttClientCallbackAdapter* callbackAdapter = mqttWrapper->callbackAdapter(); if (0 != callbackAdapter) { callbackAdapter->messageReceived(topic.c_str(), payload.c_str(), payload.length()); } } } void MqttClientWrapper::setCallbackAdapter(IMqttClientCallbackAdapter* callbackAdapter) { m_callbackAdapter = callbackAdapter; if (0 != m_mqttClient) { m_mqttClient->onMessage(mqttClientCallback); } } IMqttClientCallbackAdapter* MqttClientWrapper::callbackAdapter() { return m_callbackAdapter; } void MqttClientWrapper::begin(const char* domain, uint16_t port, Client& client) { if (0 != m_mqttClient) { m_mqttClient->begin(domain, port, client); } } bool MqttClientWrapper::connect(const char* id) { bool isConnected = false; if (0 != m_mqttClient) { isConnected = m_mqttClient->connect(id); } return isConnected; } void MqttClientWrapper::disconnect() { if (0 != m_mqttClient) { m_mqttClient->disconnect(); } } bool MqttClientWrapper::connected() { bool isConnected = false; if (0 != m_mqttClient) { isConnected = m_mqttClient->connected(); } return isConnected; } bool MqttClientWrapper::loop() { bool isConnected = false; if (0 != m_mqttClient) { isConnected = m_mqttClient->loop(); } return isConnected; } unsigned char MqttClientWrapper::publish(const char* topic, const char* data) { unsigned char ret = 0; if (0 != m_mqttClient) { ret = m_mqttClient->publish(topic, data); } return ret; } unsigned char MqttClientWrapper::subscribe(const char* topic) { unsigned char ret = 0; if (0 != m_mqttClient) { ret = m_mqttClient->subscribe(topic); } return ret; } unsigned char MqttClientWrapper::unsubscribe(const char* topic) { unsigned char ret = 0; if (0 != m_mqttClient) { ret = m_mqttClient->unsubscribe(topic); } return ret; } IMqttClientWrapper::eIMqttClientState MqttClientWrapper::state() { // TODO eIMqttClientState iMqttClientState = eIMqttCS_ConnectUnavailable; return iMqttClientState; }; //----------------------------------------------------------------------------- MqttClientCallbackAdapter::MqttClientCallbackAdapter() : m_trPortMqttRx(new DbgTrace_Port("mqttrx", DbgTrace_Level::info)) , m_rxMsg(new MqttRxMsg()) { } MqttClientCallbackAdapter::~MqttClientCallbackAdapter() { delete m_rxMsg; m_rxMsg = 0; delete m_trPortMqttRx; m_trPortMqttRx = 0; } void MqttClientCallbackAdapter::messageReceived(const char* topic, const char* payload, unsigned int length) { char msg[length+1]; memcpy(msg, payload, length); msg[length] = 0; TR_PRINTF(m_trPortMqttRx, DbgTrace_Level::info, "Message arrived, topic: %s - msg: %s (len: %d)", topic, msg, length); if (0 != m_rxMsg) { m_rxMsg->prepare(topic, payload, length); } MqttTopicSubscriber* mqttSubscriberChain = MqttClientController::Instance()->mqttSubscriberChain(); if (0 != mqttSubscriberChain) { mqttSubscriberChain->handleMessage(m_rxMsg, m_trPortMqttRx); } }
657016fad4bc0e370a4882e0f34fbe2b64e973be
[ "Markdown", "C++" ]
15
Markdown
ERNICommunity/mqtt-client
8f7915b39d221c7ba93dbf6a17c8c27f4f94c629
b5839c9bc71ef0513472130ed8c03386e6937c83
refs/heads/master
<repo_name>peterchenhdu/cp-music-player<file_sep>/app/src/main/java/io/github/ryanhoo/music/data/model/Task.java package io.github.ryanhoo.music.data.model; import android.os.Parcel; import android.os.Parcelable; import com.litesuits.orm.db.annotation.Column; import com.litesuits.orm.db.annotation.MapCollection; import com.litesuits.orm.db.annotation.Mapping; import com.litesuits.orm.db.annotation.PrimaryKey; import com.litesuits.orm.db.annotation.Table; import com.litesuits.orm.db.annotation.Unique; import com.litesuits.orm.db.enums.AssignType; import com.litesuits.orm.db.enums.Relation; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created with Android Studio. * User: PiChen * Date: 2021/05/12 * Time: 11:51 * */ @Table("task") public class Task implements Parcelable { @PrimaryKey(AssignType.AUTO_INCREMENT) private int id; @Unique private String path; private int level; private Date createdAt; public Task() { // Empty } public Task(Parcel in) { readFromParcel(in); } public int getId() { return id; } public void setId(int id) { this.id = id; } public Task(String path, int level) { this.path = path; this.level = level; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.id); dest.writeString(this.path); dest.writeInt(this.level); dest.writeLong(this.createdAt != null ? this.createdAt.getTime() : -1); } private void readFromParcel(Parcel in) { this.id = in.readInt(); this.path = in.readString(); this.level = in.readInt(); long tmpCreatedAt = in.readLong(); this.createdAt = tmpCreatedAt == -1 ? null : new Date(tmpCreatedAt); } public static final Creator<Task> CREATOR = new Creator<Task>() { @Override public Task createFromParcel(Parcel source) { return new Task(source); } @Override public Task[] newArray(int size) { return new Task[size]; } }; } <file_sep>/app/src/main/java/io/github/ryanhoo/music/data/source/AppContract.java package io.github.ryanhoo.music.data.source; import io.github.ryanhoo.music.data.model.Folder; import io.github.ryanhoo.music.data.model.PlayList; import io.github.ryanhoo.music.data.model.Song; import io.github.ryanhoo.music.data.model.Task; import rx.Observable; import java.util.List; /** * Created with Android Studio. * User: <EMAIL> * Date: 9/10/16 * Time: 4:52 PM * Desc: AppContract */ /* package */ interface AppContract { // Play List Observable<List<PlayList>> playLists(); List<PlayList> cachedPlayLists(); Observable<PlayList> create(PlayList playList); Observable<PlayList> update(PlayList playList); Observable<PlayList> delete(PlayList playList); // Folder Observable<List<Folder>> folders(); Observable<Folder> create(Folder folder); Observable<List<Folder>> create(List<Folder> folders); Observable<Folder> update(Folder folder); Observable<Folder> delete(Folder folder); // Song Observable<List<Song>> insert(List<Song> songs); Observable<Song> update(Song song); Observable<Song> setSongAsFavorite(Song song, boolean favorite); void doTask(Task task); // Task /** * 查询任务列表 * * @return 任务列表 */ Observable<List<Task>> tasks(); /** * 创建任务 * * @param task 任务 * @return 任务 */ Observable<Task> create(Task task); /** * 删除任务 * * @param task 任务 * @return Task */ Task delete(Task task); } <file_sep>/README.md # cp-music-player
656c7e29225f7e724aabb189d9c82c36f395a5f6
[ "Markdown", "Java" ]
3
Java
peterchenhdu/cp-music-player
3d1be574a430c82aa70dec2964d6d0b01ea317e1
eda96fc8e1661108bd57327b5ee5fef4fca14d9d
refs/heads/master
<file_sep>package com.iotend.gql.repository; import com.iotend.gql.model.Post; import org.springframework.data.mongodb.repository.MongoRepository; public interface PostRepository extends MongoRepository<Post,String> { } <file_sep>## 测试 - 启动应用 - 访问 [http://localhost:8083/graphiql](http://localhost:8080/graphiql) #### 查询 - 查询列表 ```graphql { posts { id title content createDate } } ``` ```json { "data": { "posts": [ { "id": "5c50245b7ed65eacb3372aba", "title": "Post one", "content": "Content of Post one", "createDate": "Tue Jan 29 18:00:59 CST 2019" }, { "id": "5c50245b7ed65eacb3372abb", "title": "Post two", "content": "Content of Post two", "createDate": "Tue Jan 29 18:00:59 CST 2019" } ] } } ``` - 查询指定 id ```graphql { post(id: "5c50245b7ed65eacb3372aba") { id title content createDate } } ``` ```json { "data": { "post": { "id": "5c50245b7ed65eacb3372aba", "title": "Post one", "content": "Content of Post one", "createDate": "Tue Jan 29 18:00:59 CST 2019" } } } ``` #### 修改 - 新增 ```graphql mutation { createPost(post: {title: "New Posts", content: "New Post Content"}) { id title content createDate } } ``` ```json { "data": { "createPost": { "id": "5c5027197ed65eaf47a0854d", "title": "New Posts", "content": "New Post Content", "createDate": "Tue Jan 29 18:12:41 CST 2019" } } } ``` - 修改 ```graphql mutation { updatePost(id: "5c5027197ed65eaf47a0854d", post: {title: "Update Posts", content: "Update Post Content"}) { id title content createDate } } ``` ```json { "data": { "updatePost": { "id": "5c5027197ed65eaf47a0854d", "title": "Update Posts", "content": "Update Post Content", "createDate": "Tue Jan 29 18:12:41 CST 2019" } } } ``` - 删除 ```graphql mutation { deletePost(id: "5c5027197ed65eaf47a0854d") } ``` ```json { "data": { "deletePost": "5c5027197ed65eaf47a0854d" } } ``` --- ### 参考文章 - [GraphQL](http://graphql.cn/) - [Spring Boot + GraphQL + MongoDB](https://medium.com/oril/spring-boot-graphql-mongodb-8733002b728a) - [graphql-spring-boot](https://github.com/graphql-java-kickstart/graphql-spring-boot) - [learn-graphql](https://github.com/zhouyuexie/learn-graphql) - [graphql-mongodb-server](https://github.com/leonardomso/graphql-mongodb-server)<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>iotend</artifactId> <groupId>com.iotend</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>iotend-graphql</artifactId> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <!-- graphql --> <dependency> <groupId>com.graphql-java</groupId> <artifactId>graphql-spring-boot-starter</artifactId> <version>5.0.2</version> </dependency> <dependency> <groupId>com.graphql-java</groupId> <artifactId>graphql-java-tools</artifactId> <version>5.2.4</version> </dependency> <dependency> <groupId>com.graphql-java</groupId> <artifactId>graphiql-spring-boot-starter</artifactId> <version>5.0.2</version> </dependency> <!-- MongoDB --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>${springboot.version}</version> </dependency> </dependencies> </project><file_sep>package com.iotend.mg.controller; import com.iotend.mg.db.PositionRepository; import com.iotend.mg.model.Position; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletResponse; @Controller @RequestMapping("/position") public class PositionController { @Autowired PositionRepository positionRepository; @RequestMapping("add") @ResponseBody public String insert(HttpServletResponse httpServletResponse){ Position position = new Position(); position.setLat(12.34); position.setLng(34.12); positionRepository.save(position); return "finish!"; } } <file_sep># iotend ## 开源物联网数据采集服务,包含SaaS平台 ###QQ:8150772 #####感谢支持 ![支付宝](doc/images/支付宝收款.jpg)<file_sep>package com.iotend.gql.resolver; import com.coxautodev.graphql.tools.GraphQLMutationResolver; import com.iotend.gql.model.Post; import com.iotend.gql.repository.PostRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class PostMutation implements GraphQLMutationResolver { @Autowired private PostRepository postRepository; /** * Create Post * * @param post The create Post entity * @return The created Post entity */ public Post createPost(Post post) { Post newPost = Post.builder() .title(post.getTitle()) .content(post.getContent()) .build(); //return postRepository.save(newPost); return newPost; } /** * Update Post * * @param id The update post id * @param post The update post entity * @return Had updated post entity * @throws Exception Throw exception when the entity is not found by the given id */ public Post updatePost(String id, Post post) throws Exception { Post currentPost = postRepository.findById(id) .orElseThrow(() -> new IllegalArgumentException("Post " + id + " Not Exist")); currentPost.setTitle(post.getTitle()); currentPost.setContent(post.getContent()); return postRepository.save(currentPost); } /** * Delete Post * * @param id The delete Post id * @return The deleted Post's id * @throws Exception Throw exception when the entity is not found by the given id */ public String deletePost(String id) throws Exception { postRepository.findById(id) .orElseThrow(() -> new IllegalArgumentException("Post " + id + " Not Exist")); postRepository.deleteById(id); return id; } } <file_sep>package com.iotend.my.api; import com.iotend.my.model.MedInsDetails; public interface MedInsDetailsService { int add(MedInsDetails medInsDetails); } <file_sep>package com.iotend.my.api.impl; import com.iotend.my.api.MedInsService; import com.iotend.my.mapper.MedInsMapper; import com.iotend.my.model.MedIns; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class MedInsServiceImpl implements MedInsService { @Autowired MedInsMapper medInsMapper; @Override public int add(MedIns medIns) { return medInsMapper.add(medIns); } @Override public List<MedIns> findAll() { return medInsMapper.findAll(); } @Override public List<MedIns> findById(int id) { return medInsMapper.findById(id); } } <file_sep>package com.iotend.mg.db; import com.iotend.mg.model.Position; import org.springframework.data.mongodb.repository.MongoRepository; public interface PositionRepository extends MongoRepository<Position,String> { @Override Position insert(Position position); } <file_sep>package com.iotend.gql.resolver; import com.coxautodev.graphql.tools.GraphQLQueryResolver; import com.iotend.gql.model.Post; import com.iotend.gql.repository.PostRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.Optional; @Component public class PostQuery implements GraphQLQueryResolver { @Autowired private PostRepository postRepository; public List<Post> posts() { return postRepository.findAll(); } public Optional<Post> post(String id) { return postRepository.findById(id); } }
a4cb53ee9215b19db738891da0077e8865352e68
[ "Markdown", "Java", "Maven POM" ]
10
Java
huanggreat/iotend
46e0043355d6c4075117ff4074fe298a71a55682
e817e5f7eca45887859d18ea05b8ec8422134366
refs/heads/master
<file_sep>require 'formula' class Drake < Formula homepage 'https://github.com/Factual/drake' head 'https://github.com/Factual/drake', :using => :git, :branch => :develop depends_on 'leiningen' def install libexec.install Dir['*'] bin.write_exec_script Dir["#{libexec}/bin/*"] Dir.chdir(libexec) do system 'lein', 'uberjar' end end end
229b895656329f1b408704bf6b9ff54ef8fa90b5
[ "Ruby" ]
1
Ruby
agate/homebrew
1e44ea52dcc54291733e07a86546d0685d93c70b
f7e364c9c08b9bff9501a16a5a3b1bc6ea65e90e
refs/heads/master
<repo_name>kbrito/d3-coordinated-viz<file_sep>/js/main.js // The most javascript of them all //First line of main.js...wrap everything in a self-executing anonymous function to move to local scope (function(){ //pseudo-global variables var csvArray = [0,1,2,3]; //list of attributes var expressed = csvArray[0,1,2,3,4]; var pop = 0; //begin script when window loads window.onload = setMap(); //set up choropleth map function setMap(){ //map frame dimensions var width = 960, height = 460; //create new svg container for the map var map = d3.select("body") .append("svg") .attr("class", "map") .attr("width", width) .attr("height", height); //create Albers equal area conic projection centered on France var projection = d3.geo.albers() .rotate([108, 0]) .center([-3.64, 34.0]) .parallels([29.5, 45.5]) .scale(3000) .translate([width / 2, height / 2]) .precision(.1); var path = d3.geo.path() .projection(projection); //use queue.js to parallelize asynchronous data loading d3_queue.queue() .defer(d3.csv, "data/Arizona_shp/AZAge2014.csv") //load attributes from csv .defer(d3.json, "data/Arizona_shp/AZcountydata.topojson") //load background spatial data .await(callback); function callback(error, csvData, arizona){ //translate europe TopoJSON var arizonaCounties = topojson.feature(arizona, arizona.objects.AZcountydata).features; function setEnumerationUnits(arizonaCounties, map, path, colorScale){ var counties = map.selectAll(".COUNTY") .data(arizonaCounties) .enter() .append("path") .attr("class", function(d){ return "COUNTY " + d.properties.OBJECTID; }) .attr("d", path) .style("fill", function(d){ return choropleth(d.properties[pop], colorScale); }); }; //function to test for data value and return color function choropleth(props, colorScale){ //make sure attribute value is a number var val = parseFloat(props); //if attribute value exists, assign a color; otherwise assign gray if (val && val != NaN){ return colorScale(val); } else { return "#CCC"; }; }; //examine the results console.log(arizonaCounties); console.log(csvData[0]); //build large array of all values for later for (var i=0; i<arizonaCounties.length; i++){ csvArray[i] = csvData[i]; }; console.log(csvArray); //create the color scale var colorScale = makeColorScale(csvData); console.log(colorScale); setEnumerationUnits(arizonaCounties, map, path, colorScale); }; //function to create color scale generator function makeColorScale(data){ var colorClasses = [ "#f7de9c", "#e1bf61", "#b59334", "#7c5f10", "#56420c" ]; //create color scale generator var colorScale = d3.scale.quantile() .range(colorClasses); console.log(data.length); //build array of all values of the expressed attribute var domainArray = data[expressed]; console.log(csvArray); for (var j=0; j<csvArray.length; j++) { } //assign array of expressed values as scale domain colorScale.domain(csvArray); console.log(colorScale.quantiles()); return colorScale; }; }; })(); //last line of main.js
223c594d676a9fbcb063b112b3d9e40020cfc825
[ "JavaScript" ]
1
JavaScript
kbrito/d3-coordinated-viz
0d7b8978c226b912386e27e786417879ea43629f
7d77df882e726d6e381313751d948f18cf853936
refs/heads/master
<repo_name>jaykar/hw4_robotics<file_sep>/src/README.txt README.txt Group 7 Robotics HW4 Team Leader: <NAME> <NAME>, <NAME>, <NAME> as4313, jan2150, jmd2228 We implemented our code in Python 2.7.4. Before running our program please ensure you run the following: brew tap homebrew/science brew install opencv pip install numpy To run our program, type: python hw4.py The input files for the world should be in a txt file in input_files called Press any key to quit out of the final image. We implemented our own convex hull and dijkstra's function but we used numpy for matrix multiplications and OpenCV to draw images. The output of this program is as follows: == images and GIF == There are four images saved: (1) just the obstacles and start and end (2) add grown obstacles (3) add all possible paths (4) highlights shortest path We also provided a GIF that shows this process--to open this GIF just drag it to a Chrome tab. == text file with shortest path == text file that we feed into our MATLAB program that has the shortest path and positions of the vertices ============== color key =============== start: red circle goal: green circle original obstacles: yellow lines grown convex hulls: green lines all valid paths form start to goal: dark blue shortest path as given by Djikstra: light blue <file_sep>/src/hw4.py # -*- coding: utf-8 -*- import numpy as np import cv2 from math import sqrt import numpy as np import cv2 import math def find_convex_hull(pts_array): num_pts = len(pts_array); # find the rightmost, lowest point, label it P0 sorted_pts = sorted(pts_array, key=lambda element: (element[0], -element[1])) P0 = sorted_pts.pop() P0_x = P0[0] P0_y = P0[1] # sort all points angularly about P0 # Break ties in favor of closeness to P0 # label the sorted points P1....PN-1 sort_array = []; for i in range(num_pts-1): x = pts_array[i][0] y = pts_array[i][1] angle = 0 x_diff = x - P0_x y_diff = y - P0_y angle = math.degrees(math.atan2(y_diff, x_diff)) if angle < 0: angle = angle * (-1) + 180 dist = math.degrees(math.sqrt(x_diff**2 + y_diff**2)); pt_info = (round(angle, 3), round(dist,3), pts_array[i]) sort_array.append(pt_info) sorted_pts = sorted(sort_array, key=lambda element: (element[0], element[1])) # Push the points labeled PN−1 and P0 onto a stack. T # these points are guaranteed to be on the Convex Hull pt_stack = [] pt_stack.append(sorted_pts[num_pts - 2][2]) pt_stack.append(P0) # Set i = 1 # While i < N do # If Pi is strictly left of the line formed by top 2 stack entries (Ptop, Ptop−1), # then Push Pi onto the stack and increment i; else Pop the stack (remove Ptop). i = 1 while i < num_pts - 1: P_i = sorted_pts[i][2] c = pt_stack.pop() d = pt_stack.pop() pt_stack.append(d) pt_stack.append(c) # find the line formed by these two points and see if the point Pi is # strictly to the left of this line is_to_the_left = False position = (d[0] - c[0]) * (P_i[1] - c[1]) - (d[1] - c[1]) * (P_i[0] - c[0]) if position < 0: is_to_the_left = True if (is_to_the_left): pt_stack.append(P_i) i += 1; else: pt_stack.pop() return pt_stack[:-1] # #pts = [[0.0, 1.0], [1.0, 5.0], [2.0, 3.0], [2.0, 3.0], [3.0, 5.0], [3.0, 2.0], [4.0, 2.0], [6.0, 3.0]]; # #pts = [[-0.111, -1.374], [-0.111, -2.174], [-0.911, -1.374], [-0.911, -2.174], [-0.111, -1.843], [-0.111, -2.643], [-0.911, -1.843], [-0.911, -2.643], [0.699, -1.843], [0.699, -2.643], [-0.101, -1.843], [-0.101, -2.643], [0.699, -1.374], [0.699, -2.174], [-0.101, -1.374], [-0.101, -2.174]] # pts = [[1.588, -1.373], [1.588, -2.173], [0.788, -1.373], [0.788, -2.173], [1.588, -1.843], [1.588, -2.643], [0.788, -1.843], [0.788, -2.643], [1.118, -1.843], [1.118, -2.643], [0.318, -1.843], [0.318, -2.643], [1.118, -1.373], [1.118, -2.173], [0.318, -1.373], [0.318, -2.173]] # hull = find_convex_hull(pts); # print(hull) class Line(object): def __init__(self, start, end): self.x0 = start[0] self.y0 = start[1] self.x1 = end[0] self.y1 = end[1] self.constant, self.m = self.gradient() self.b = self.y_intercept() self.A = self.y1 - self.y0 self.B = self.x0 - self.x1 self.C = self.A*self.x0 + self.B*self.y0 def line_intersection(self,line): det = self.A * line.B - line.A * self.B xpts = [line.x0, line.x1] ypts = [line.y0, line.y1] min_x, min_y = min(xpts), min(ypts) max_x, max_y = max(xpts), max(ypts) min_x = round(min_x, 3) max_x = round(max_x, 3) min_y = round(min_y, 3) max_y = round(max_y, 3) xpts = [self.x0, self.x1] ypts = [self.y0, self.y1] min_x_p, min_y_p = min(xpts), min(ypts) max_x_p, max_y_p = max(xpts), max(ypts) min_pt_x = round(min_x_p, 3) max_pt_x = round(max_x_p, 3) min_pt_y = round(min_y_p, 3) max_pt_y = round(max_y_p, 3) if det == 0: return False else: x = round((line.B * self.C - self.B * line.C)/det, 3) y = round((self.A * line.C - line.A * self.C)/det, 3) #print max_y - y #print "intersection x, y", x, y #print "self", (self.x0, self.y0), (self.x1, self.y1) #print "line", (line.x0, line.y0), (line.x1, line.y1) #print "min_x, max_x", min_x, max_x #print "min_y, max_y", min_y, max_y a = (x > min_x and x < max_x) b = (y > min_y and y < max_y) c = (x <= max_pt_x and x >= min_pt_x) d = (y <= max_pt_y and y >= min_pt_y) #print "conditional", a, b if (a or b) and (c and d): return True else: return False def gradient(self): y_p = self.y1 - self.y0 x_p = self.x1 - self.x0 if x_p == 0: return self.y1, 'inf' elif y_p == 0: return self.x1, 0 else: return None, y_p/x_p def y_intercept(self): if self.constant: if self.m == 'inf': return None if self.m == 0: return self.x1 else: return self.y1 - self.m * self.x1 def compare(self, line): return (self.m == line.m and self.b == line.b and \ self.constant == line.constant) def intersect(self, all_lines): for line in all_lines: intersect_in_range = self.line_intersection(line) if intersect_in_range: return True return False def __str__(self): if self.constant: if self.m == 'inf': return "x = " + str(self.constant) else: return "y = " + str(self.constant) else: return "y = " + str(self.m) + "x + " + str(self.b) class Obstacle(object): def __init__(self, xy, grow=True): self.coords = self._format(xy) if grow: self.coords_grown = self._grow() self.lines = self.obstacle_lines(self.coords_grown) self.lines.extend(self.obstacle_lines(self.coords)) else: self.coords_grown = self.coords[:] self.lines = self.obstacle_lines(self.coords_grown) def obstacle_lines(self, A): lines = [] for i in range(len(A)-1): curr_x, curr_y = A[i] next_x, next_y = A[i+1] lines.append(Line([curr_x, curr_y], [next_x, next_y])) curr_x, curr_y = A[-1] next_x, next_y = A[0] lines.append(Line([curr_x, curr_y], [next_x, next_y])) return lines def __repr__(self): print self.coords def _format(self, xy): coords = [] for i in range(len(xy)): coords.append(map(float, xy[i])) return coords def _grow(self, square=0.4): coords = [] for x,y in self.coords: coords.append([x+square, y+square]) coords.append([x+square, y-square]) coords.append([x-square, y+square]) coords.append([x-square, y-square]) coords_round = [] for coord in coords: x, y = coord coords_round.append([round(x, 3), round(y,3)]) coords = coords_round #print "obstacle", coords coords = find_convex_hull(coords_round) #coords = np.array(coords) #hull = ConvexHull(coords) #x = coords[hull.vertices,0] # y = coords[hull.vertices,1] # coords = [] # for (a, b) in zip(x,y): # coords.append([a,b]) return coords def draw(self, grown=False, size=(600, 900, 3), thickness=1, color =(0, 0, 255)): def pixel_location(curr_o, next_o): curr_obs = np.array(curr_o) * -500/11.0 + np.array([275, 575]) next_obs = np.array(next_o) * -500/11.0 + np.array([275, 575]) x0, y0 = map(int, curr_obs) x1, y1 = map(int, next_obs) return ((y0, x0), (y1, x1)) coords = [] if grown: coords = self.coords_grown else: coords = self.coords img = np.zeros(size) for i in range(len(coords)-1): pt1, pt2 = pixel_location(coords[i], coords[i+1]) cv2.line(img, pt1, pt2, color, thickness) pt1, pt2 = pixel_location(coords[0], coords[-1]) cv2.line(img, pt1, pt2, color, thickness) return img def __str__(self): return str(self.coords) class Graph(): def __init__(self): self.nodes = {} def node_exists(self, a): return a in self.nodes def add_node(self, a): if not self.node_exists(a): self.nodes[a] = {} def add_edge(self, a, b, weight): if not self.node_exists(a): self.add_node(a) if not self.node_exists(b): self.add_node(b) self.nodes[a][b] = weight self.nodes[b][a] = weight def shortest_path(self): s = 'start' e = 'end' ans = self.djikstra(self.nodes, s, e) if len(ans) != 0: return ans else: return "no path" def djikstra(self, nodes, S, G): #nodes = graph.nodes unvisited = set(nodes.keys()) unvisited.remove(S) # initialize distance dictionary dist = {} predecessors = {} dist[S] = 0; predecessors[S] = S S_neighbors = set(nodes[S].keys()); for n in unvisited: if n in S_neighbors: dist[n] = nodes[S][n] predecessors[n] = S else: dist[n] = float('Inf'); while len(unvisited) > 0: # find the closest unvisited node keys = unvisited.intersection(set(dist.keys())) dist_of_unvisited = {k:dist[k] for k in keys} V = min(dist_of_unvisited, key = dist_of_unvisited.get); unvisited.remove(V); V_neighbors = set(nodes[V].keys()) for W in V_neighbors: if ((dist[V] + nodes[V][W]) < dist[W]): dist[W] = dist[V] + nodes[V][W] predecessors[W] = V path = [] end = G; while end != S: path.append(end) end = predecessors[end] path.reverse() return path class World(object): def __init__(self, obstacle_txt, goal_txt): self.obstacles = [] self.goals = [] self.populate_obstacles(obstacle_txt) self.populate_goal(goal_txt) self.info, self.graph, self.all_lines = self.intialize_graph() self.make_edges() self.path = ['start'] self.path.extend(self.graph.shortest_path()) self.get_matlab_instructions('1') def position_nodes(self, coord): x, y = coord a = np.eye(4) theta = np.arctan2(y, x) rot = np.array([ [np.cos(theta) , np.sin(theta), 0.0] ,\ [-np.sin(theta), np.cos(theta), 0.0] ,\ [0.0 , 0.0 , 1.0] ,\ ]) a[:3, :3] = rot a[0, 3] = x a[1, 3] = y return a def get_matlab_instructions(self, text_file): # x,y = self.info[self.path[0]] # prev = np.eye(4) # prev[0, 3] = x # prev[1, 3] = y prev_angle = 0 for i in range(len(self.path) - 1): curr = self.info[ self.path[i] ] x0, y0 = curr next = self.info[ self.path[i+1] ] x1, y1 = next theta = np.arctan2(y1 - y0, x1 - x0) #- prev_angle prev_angle = theta print "rotate", 90 - (theta - (np.pi/2))*180/np.pi print "move", np.sqrt((y1 - y0)**2 + (x1 - x0)**2 ) def intialize_graph(self): count = 0 graph = Graph() info = {} lines = [] graph.add_node('start') info['start'] = self.goals[0] for j,obs in enumerate(self.obstacles[1:]): #for j,obs in enumerate(self.obstacles): for i in range(len(obs.coords_grown)): key = str(j) + "_" +str(i) graph.add_node(key) info[key] = obs.coords_grown[i] lines.extend(obs.lines) graph.add_node('end') info['end'] = self.goals[1] lines.extend(self.obstacles[0].lines) return info, graph, lines def make_edges(self): nodes = list(self.graph.nodes.keys()) n_nodes = len(nodes) for i in range(n_nodes - 1): curr_node = nodes[i] for j in range(i + 1, n_nodes): next_node = nodes[j] #print str(curr_node) + " -> " + str(next_node) curr_line = Line(self.info[curr_node], self.info[next_node]) obs_n = next_node[0] obs_l = curr_node[0] ret = curr_line.intersect(self.all_lines) #print ret #print "" if not ret: x0, y0 = self.info[curr_node] x1, y1 = self.info[next_node] weight = np.sqrt( (x0-x1)**2 + (y0 - y1)**2 ) self.graph.add_edge(curr_node, next_node, weight) def populate_obstacles(self, txt_file): with open(txt_file, 'r') as input_file: n_lines = int(next(input_file)) for i in range(n_lines): n_vertex = int(next(input_file)) coords = [] for j in range(n_vertex): coords.append(next(input_file).replace(' \r\n', '').split(' ')) if i==0: self.obstacles.append(Obstacle(coords, grow=False)) else: self.obstacles.append(Obstacle(coords, grow=True)) def populate_goal(self, goal_txt): f = open(goal_txt, 'r') coords = f.read().split('\n') start = map(float, coords[0].split(' ')) end = map(float, coords[1].split(' ')) self.goals.append(start) self.goals.append(end) def draw(self,grown=False, size=(600, 900, 3)): def pixel_location(curr_o): curr_obs = np.array(curr_o) * -500/11.0 + np.array([275, 575]) x0, y0 = map(int, curr_obs) return (y0, x0) img = np.zeros(size) thickness = 2 for i, obstacle in enumerate(self.obstacles): if i > 0: thickness = 1 img += obstacle.draw(False, size,thickness, color=(0, 255, 0)) img += obstacle.draw(False, size,thickness) start = pixel_location(self.goals[0]) end = pixel_location(self.goals[1]) cv2.circle(img, start, radius = 5, color=(0,0,255)) cv2.circle(img, end, radius = 5, color=(0,255,0)) cv2.imwrite("map.png", img) #cv2.imshow('world', img) #cv2.waitKey(0) for i, obstacle in enumerate(self.obstacles): if i > 0: thickness = 1 img += obstacle.draw(True, size,thickness, color=(0, 255, 0)) img += obstacle.draw(False, size,thickness) cv2.imwrite("map_grown_obstacle.png", img) for key in self.graph.nodes: curr = self.info[key] start = pixel_location(curr) for key2 in self.graph.nodes[key]: next = self.info[key2] end = pixel_location(next) cv2.line(img, start, end, color=(255,0,0), thickness=1) #cv2.imshow('world', img) #cv2.waitKey(0) cv2.imwrite("map_all_path.png", img) path = self.path for i in range(len(path) -1): key, key2 = path[i], path[i+1] curr = self.info[key] start = pixel_location(curr) next = self.info[key2] end = pixel_location(next) cv2.line(img, start, end, color=(255,255,0), thickness=1) cv2.imwrite("map_valid_path.png", img) cv2.imshow('world', img) cv2.waitKey(0) def output_path(self, output_file): f = open(output_file, 'w') for node in self.path: coord = self.info[node] x, y = coord #position = "X pos: " + str(x) + " Y pos: " + str(y) + "\n" f.write(str(x) + ' '+ str(y) + '\n') f.close() if __name__ == '__main__': W = World('hw4_world_and_obstacles_convex.txt', 'hw4_start_goal.txt') #W = World('../input_files/small_world.txt', '../input_files/hw4_start_goal.txt') W.draw(grown=True) W.output_path('output.txt') print W.path
6378c749999ef8e13467d6e9536b8f3d30345b33
[ "Python", "Text" ]
2
Text
jaykar/hw4_robotics
a396aa980e42fd50303a8aa94b8d40151eba6af9
2529bd6b26f07ddf99bcbe89ac83a442142f7d4f
refs/heads/master
<file_sep>module Model # Searches title and content for any matching text # # @param [Hash] params form data # @option params [String] search_terms # # @return [Array] containing the data of all matching articles def find_articles(params) # ... # ... # ... end # Inserts a new row in the articles table # # @param [Hash] params form data # @option params [String] title The title of the article # @option params [String] content The content of the article # # @return [Hash] # * :error [Boolean] whether an error occured # * :message [String] the error message def create_article(params) # ... # ... # ... end # Finds an article # # @param [Hash] params form data # @option params [Integer] id The ID of the article # # @return [Hash] # * :id [Integer] The ID of the article # * :title [String] The title of the article # * :content [String] The content of the article # @return [nil] if not found def get_article(params) # ... # ... # ... end # Finds an article # # @param [Hash] params form data # @option params [String] username The username # @option params [String] password The password # # @return [Integer] The ID of the user # @return [false] if credentials do not match a user def login(params) # ... # ... # ... end end<file_sep># YARDoc Tutorial [Generated Site](https://itggot.github.io/yardoc-sinatra-guide/docs/top-level-namespace.html) ## Installation `gem install yard yard-sinatra` ## Usage `yardoc --plugin yard-sinatra app.rb path/to/model.rb` The above command creates a doc-directory containing the generated documentation site ## Documenting routes ```ruby require_relative 'model' require 'sinatra' require 'slim' enable :sessions include Model # Display Landing Page # get('/') do slim(:index) end # Displays search result based on search parameters # # @see Model#find_articles get('/articles/search') do result = find_articles(params) slim(:search_result, locals:{articles:result}) end # Displays a single Article # # @see Model#get_article get('/articles/:id') do article = get_article(params) slim(:article, locals:{article:article}) end # Creates a new article and redirects to '/articles' # # @see Model#create_article post('/articles') do success = create_article(params) if success redirect('/articles') else session[:error_msg] = "Article creation failed" redirect('/error') end end # Attempts login and updates the session # # @see Model#login post('/login') do user_id = login(params) if user_id session[:user_id] = user_id redirect('/') else sessino[:error_msg] = "Invalid Credentials" redirect('/error') end end # Displays an error message # get('/error') do error_msg = session[:error_msg].dup session[:error_msg] = nil slim(:error, locals:{message:error_msg}) end ``` ```ruby module Model # Searches title and content for any matching text # # @param [Hash] params form data # @option params [String] search_terms # # @return [Array] containing the data of all matching articles def find_articles(params) # ... # ... # ... end # Inserts a new row in the articles table # # @param [Hash] params form data # @option params [String] title The title of the article # @option params [String] content The content of the article # # @return [Hash] # * :error [Boolean] whether an error occured # * :message [String] the error message def create_article(params) # ... # ... # ... end # Finds an article # # @param [Hash] params form data # @option params [Integer] id The ID of the article # # @return [Hash] # * :id [Integer] The ID of the article # * :title [String] The title of the article # * :content [String] The content of the article # @return [nil] if not found def get_article(params) # ... # ... # ... end # Finds an article # # @param [Hash] params form data # @option params [String] username The username # @option params [String] password The <PASSWORD> # # @return [Integer] The ID of the user # @return [false] if credentials do not match a user def login(params) # ... # ... # ... end end ``` <file_sep>require_relative 'model' require 'sinatra' require 'slim' enable :sessions include Model # Wat dis? # Display Landing Page # get('/') do slim(:index) end # Displays search result based on search parameters # # @see Model#find_articles get('/articles/search') do result = find_articles(params) slim(:search_result, locals:{articles:result}) end # Displays a single Article # # @see Model#get_article get('/articles/:id') do article = get_article(params) slim(:article, locals:{article:article}) end # Creates a new article and redirects to '/articles' # # @see Model#create_article post('/articles') do success = create_article(params) if success redirect('/articles') else session[:error_msg] = "Article creation failed" redirect('/error') end end # Attempts login and updates the session # # @see Model#login post('/login') do user_id = login(params) if user_id session[:user_id] = user_id redirect('/') else sessino[:error_msg] = "Invalid Credentials" redirect('/error') end end # Displays an error message # get('/error') do error_msg = session[:error_msg].dup session[:error_msg] = nil slim(:error, locals:{message:error_msg}) end
d2a58c10224de93f8a2d1bb032251d7183b7f867
[ "Markdown", "Ruby" ]
3
Ruby
itggot-david-lundholm/yardoc-sinatra-guide
7449890f333d6fc8fc110ab9622e5c786c7c5cb1
546e1829ae45e990e8c05fcfb389635360c77d68
refs/heads/master
<repo_name>ijabir28/DS<file_sep>/app/src/main/java/com/example/administrator/highscore/MainActivity.java package com.example.administrator.highscore; import android.content.Context; import android.content.SharedPreferences; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.File; public class MainActivity extends AppCompatActivity { EditText input; TextView score; protected final static int DEFAULT = 0; int temp = DEFAULT, inputs = DEFAULT ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); input = (EditText)findViewById(R.id.input); score = (TextView)findViewById(R.id.hs); SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE); temp = sharedPreferences.getInt("highScore",DEFAULT); if (temp==DEFAULT){ Toast.makeText(this, "Database Empty\n", Toast.LENGTH_LONG).show(); } else{ //dfgdfg Toast.makeText(this,"Loading Successfull",Toast.LENGTH_LONG).show(); score.setText("Till now the High Score is\n" + temp); } } public void button(View view) { if (input.getText().toString().trim().length()==0){ showMessage("Error", "Please Enter a number"); return; } else{ inputs = Integer.parseInt(input.getText().toString()); if(inputs>temp){ temp = inputs; } SharedPreferences sharedPreferences = getSharedPreferences("MyData",Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("highScore", temp); editor.commit(); input.setText(""); score.setText("High Score Till Now is\n"+temp); } } public void showMessage(String title,String message) { AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setCancelable(true); builder.setTitle(title); builder.setMessage(message); builder.show(); } public void reset(View view) { SharedPreferences sharedPreferences = getSharedPreferences("MyData",Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear().commit(); temp = DEFAULT; score.setText("Database Empty\n"); } }
2f3bcfe6af61a51978ef7323f7ea79785085cb81
[ "Java" ]
1
Java
ijabir28/DS
8157b737640b42c83b101f4748fd2c48e23e1c04
c8db8969e30e44a96236e64e75ffde62a3313e00
refs/heads/master
<repo_name>MarwaSalim/araperso<file_sep>/SaveResult.py def classifaction_report_csv(report,confusionMatrix,Path): import pandas as pd report_data = [] lines = report.split('\n') i=0 for line in lines[2:-3]: row = {} row_data = line.split(' ') row['class'] = row_data[1] row['precision'] = float(row_data[2]) row['recall'] = float(row_data[3]) row['f1_score'] = float(row_data[4]) row['support'] = float(row_data[5]) row['0'] = confusionMatrix[i][0] row['1'] = confusionMatrix[i][1] report_data.append(row) i+=1 row = {} row_data = lines[-2].split(' ') row['class'] = row_data[0] row['precision'] = float(row_data[1]) row['recall'] = float(row_data[2]) row['f1_score'] = float(row_data[3]) row['support'] = float(row_data[4]) report_data.append(row) dataframe = pd.DataFrame.from_dict(report_data) dataframe.to_csv(Path+".csv", index = False)<file_sep>/PreprocessingStage.py # -*- coding: utf-8 -*- def BeginStemmer(text): result="" if text != "": import EgyptionStemmer stemmer = EgyptionStemmer.EgyptionStemmer() #print text for t in text.split(): r=stemmer.stemming(t) result+= r+" " return result def textNormalizeRemain(text): print("Normalize text begin") import re """patternArabWords= r'\w+' match = re.search(patternArabWords,text,flags=re.UNICODE) if not match: return "" """ # replace hamza patternLink1 = r'\xd8\xa4|\xd8\xa6' match = re.search(patternLink1, text) if match: text = re.sub(patternLink1, "\xd8\xa1", text) print("hamza replaced") # replace alf patternLink1 = r'\xd8\xa3|\xd8\xa5|\xd8\xa2' match = re.search(patternLink1, text) if match: text = re.sub(patternLink1, "\xd8\xa7", text) print("alf replaced") #replace lam alf ﻷ patternLink1 = r'\xef\xbb\xb7' match = re.search(patternLink1, text) if match: text = re.sub(patternLink1, "\xd9\x84\xd8\xa7", text) print("lam alf replaced") # replace heh patternLink1 = r'\xd8\xa9' match = re.search(patternLink1, text) if match: text = re.sub(patternLink1, "\xd9\x87", text) print("heh replaced") # replace yah patternLink1 = r'\xd9\x89' match = re.search(patternLink1, text) if match: text = re.sub(patternLink1, "\xd9\x8a", text) print("yah replaced") import pyarabic.araby as araby text=araby.strip_tashkeel(text) text = strip_tashkeel(text) text=araby.strip_harakat(text) text=araby.strip_lastharaka(text) text=araby.strip_shadda(text) print("tashkeel removed") """text=strip_tatweel(text) print("tatweel removed")""" text = removeNoArabicWords(text) print("no arabic removed") return text def removeNoArabicWords(text): print("no arabic removed begin") texts = text.split() result = "" import pyarabic.araby as araby for w in texts: try: w = araby.strip_tatweel(w.decode("utf8")) if araby.is_arabicword(w): result = result + w + " " except: print("Error") return result def strip_tashkeel(text): import re pattern = r'\xd9\x92' match = re.search(pattern, text) if match: text = re.sub(pattern, "", text) pattern = r'\xd9\x8d' match = re.search(pattern, text) if match: text = re.sub(pattern, "", text) pattern = r'\xd9\x90' match = re.search(pattern, text) if match: text = re.sub(pattern, "", text) pattern = r'\xd9\x8e' match = re.search(pattern, text) if match: text = re.sub(pattern, "", text) pattern = r'\xd9\x8b' match = re.search(pattern, text) if match: text = re.sub(pattern, "", text) pattern = r'\xd9\x8f' match = re.search(pattern, text) if match: text = re.sub(pattern, "", text) pattern = r'\xd9\x8c' match = re.search(pattern, text) if match: text = re.sub(pattern, "", text) pattern = r'\xd9\x91' match = re.search(pattern, text) if match: text = re.sub(pattern, "", text) return text """def strip_tatweel(text): import re pattern=r'\xd9\x80' match = re.search(pattern,text) if match: text = re.sub(pattern,"",text) return text """ def removeRedundantChar(text): #text = text.encode('utf8') texts = text.split() newText = " " for w in texts: word = "" x = 0 while (x < len(w)): count = reduncdanceCount(w[x:x + 2], x, w) # print(count) if (count == 2): # print(2) word += w[x:x + 2] + w[x:x + 2] x += 4 elif (count == 1): # print(1) word += w[x:x + 2] x += 2 else: # print(count) word += w[x:x + 2] x += (count * 2) newText += word + " " return newText def reduncdanceCount(ch, index, text): count = 0 x = index while (x < len(text)): if (text[x:x + 2] == ch): count += 1 x += 2 else: return count return count def removeStopWords(text): import FileManging File=FileManging.FileManger("C:\\Users\\Marwa\\PycharmProjects\\LoadDS","127StopWords.txt") StopWords = File.readFile() result=" " try: text=text.encode('utf_8') except: text = text for t in text.split(): if t not in StopWords.split(): result+=t+" " return result <file_sep>/Organize.py import os import FileManging from PreprocessingStage import removeStopWords,BeginStemmer,removeRedundantChar,textNormalizeRemain from CleaningStage import textCleaning def makeThisOptions(options,path): for filename in os.listdir(path): print(filename) IPath=path Opath=path IF = FileManging.FileManger(IPath, filename) text = IF.readFile() if options[0]==1: text=removeStopWords(text) Opath += "_StopWords" if options[1]==1: text=BeginStemmer(text) Opath += "_Stem" OF = FileManging.FileManger(Opath, filename) try: OF.writeFile(text) except: os.mkdir(Opath) OF.writeFile(text) def makeDefaultOptions(Path): for filename in os.listdir(Path): Output_Path = Path+"_Clean" IF = FileManging.FileManger(Path, filename) text=IF.readFile() text = textCleaning(text) OF = FileManging.FileManger(Output_Path, filename) try: OF.writeFile(text) except: os.mkdir(Output_Path) OF.writeFile(text) text = textNormalizeRemain(OF.readFile()) Output_Path += "_Normalize" OF = FileManging.FileManger(Output_Path, filename) try: OF.writeFile(text) except: os.mkdir(Output_Path) OF.writeFile(text) text = removeRedundantChar(OF.readFile()) Output_Path += "_Redundant" OF = FileManging.FileManger(Output_Path, filename) try: OF.writeFile(text) except: os.mkdir(Output_Path) OF.writeFile(text) print "cleaning Normalize Redundacy end"<file_sep>/README.md # araperso implementation of araPersonality project test123<file_sep>/CleaningStage.py # -*- coding: utf-8 -*- # clean text from noise take text and return cleaning text def textCleaning(text): print("cleaning text begin") import re # to remove any email from tweet pattern = r"([\w\.-_]+)@([\w\.-]+)(\.[\w\.]+)" match = re.search(pattern, text) if match: text = re.sub(pattern, " ", text) print("emails removed") # to remove any url from tweet pattern = r'https?:(\/){2}\S+' match = re.search(pattern, text) if match: text = re.sub(pattern, " ", text) print("url removed") # to remove @username pattern = r'@\S+' match = re.search(pattern, text) if match: text = re.sub(pattern, " ", text) print("@username removed") # to remove any digits pattern = r'[0-9]+' match = re.search(pattern, text) if match: text = re.sub(pattern, " ", text) print("English digit removed") # remove noise Marks pattern = r"[<,>\.\?/;:\'\"\{\[\]\}|\\~`!@#%$^&*\(\)_=\+-]" match = re.search(pattern, text) if match: text = re.sub(pattern, " ", text) print("noise marks removed") # replace arabic marks text = removeArabicMarks(text) print("Arabic marks removed") text=removeEmotions(text) print("emotions removed removed") # get english words pattern = r"[A-Za-z][A-Za-z\s]*" match = re.search(pattern, text) if match: english = re.findall(pattern, text) # translate english to arabic from textblob import TextBlob for engWords in english: # modifyFile("E:\\master\\GOGOGO\\train Stem","arabic.txt",engWords+'\n') try: blob = TextBlob(engWords) arabWord = blob.translate(to="ar") """totalWord = " " for w1 in arabWord.words: print w1 totalWord = totalWord + w1 + ' ' """ # modifyFile("E:\\master\\GOGOGO\\train Stem","arabic.txt",totalWord+'\n') text = text.replace(engWords, str(arabWord)+" ") except: text = text.replace(engWords, ' ') print("English words translated") text=removeNoArabicWords(text) print("Text cleaned") return text def removeArabicMarks(text): import re patternLPoint=[r'\xe2\x80\xa6',r'\xd8\x9f',r'\xd8\x8c',r'\xe2\x80\x99',r'\xe2\x80\x98',r'\xd8\x9b',r'\xc3\xb7',r'\xc3\x97'] for x in patternLPoint: match = re.search(x, text) if match: text = re.sub(x, " ", text) return text def removeEmotions(text): import re patternLPoint = [r'\xf0\x9f\x98\x82',r'\xf0\x9f\x90\xb8', r'\xe2\x9c\x8b', r'\xf0\x9f\x98\x8c', r'\xf0\x9f\x98\x8e',r'\xf0\x9f\x92\x99', r'\xf0\x9f\x98\x8b',r'\xf0\x9f\x92\x94',r'\xf0\x9f\x92\x9e', r'\xe2\x80\x94',r'\xf0\x9f\x92\x9c', r'\xf0\x9f\x8c\xb7', r'\xf0\x9f\x8e\x8b',r'\xf0\x9f\x91\x8a', r'\xf0\x9f\x91\x8d',r'\xf0\x9f\xa4\x94', r'\xf0\x9f\x98\x94',r'\xf0\x9f\x92\x83',r'\xf0\x9f\x92\x96',r'\xf0\x9f\xa4\xa6',r'\xe2\x81\xa6', r'\xe2\x81\xa9',r'\xe2\x9d\xa4',r'\xf0\x9f\x98\x8d',r'\xc2\xab',r'\xc2\xbb',r'\xf0\x9f\x8c\xbb', r'\xf0\x9f\x98\xad',r'\xf0\x9f\x8c\x9a',r'\xf0\x9f\xa4\x97',r'\xf0\x9f\xa4\xb8',r'\xf0\x9f\x8f\xbb', r'\xe2\x80\x8d',r'\xe2\x99\x80',r'\xef\xb8\x8f',r'\xf0\x9f\x92\x95',r'\xf0\x9f\x92\x86', r'\xf0\x9f\x8c\x9e', r'\xf0\x9f\xa6\x89',r'\xf0\x9f\x92\x98',r'\xf0\x9f\x99\x88', r'\xf0\x9f\x8c\xba',r'\xf0\x9f\x98\x8f', r'\xf0\x9f\x92\xab', r'\xe2\x9c\x8a', r'\xf0\x9f\x98\xa2', r'\xf0\x9f\x8c\xbc', r'\xf0\x9f\x99\x84', r'\xf0\x9f\xa4\xb7',r'\xf0\x9f\x9a\xb6', r'\xf0\x9f\x99\x82', r'\xf0\x9f\x98\x84', r'\xf0\x9f\x8e\x88', r'\xf0\x9f\x92\x9a', r'\xf0\x9f\xa4\x90', r'\xf0\x9f\x8c\xb8',r'\xf0\x9f\x8e\xb6', r'\xf0\x9f\x8e\x89', r'\xef\xb8\x8f', r'\xf0\x9f\x8f\x83', r'\xf0\x9f\x8c\x99', r'\xf0\x9f\xa4\xb0', r'\xf0\x9f\x9a\xac',r'\xf0\x9f\x91\xa9', r'\xf0\x9f\x8d\xb3', r'\xf0\x9f\x98\x8a', r'\xf0\x9f\x92\xb0',r'\xf0\x9f\x8c\xb9',r'\xf0\x9f\x98\x87', r'\xf0\x9f\x98\xb6', r'\xf0\x9f\x92\x85', r'\xe2\x98\x94', r'\xf0\x9f\x90\xa0',r'\xf0\x9f\x93\xa2', r'\xf0\x9f\x98\x81',r'\xef\xb7\xba',r'\xef\xb4\xbf', r'\xf0\x9f\x91\x90', r'\xf0\x9f\x92\x93',r'\xf0\x9f\x92\xaa', r'\xe2\x99\x89',r'\xf0\x9f\x99\x87', r'\xf0\x9f\x99\x8c', r'\xf0\x9f\x99\x8b',r'\xe2\x9c\x94', r'\xf0\x9f\x91\xbb', r'\xf0\x9f\x91\xbb',r'\xf0\x9f\x91\x8c',r'\xf0\x9f\x92\x81', r'\xf0\x9f\x98\x9e',r'\xf0\x9f\x91\x89',r'\xf0\x9f\x91\x88',r'\xf0\x9f\x99\x86', r'\xf0\x9f\x98\x98',r'\xf0\x9f\x98\x89',r'\xf0\x9f\x98\x85',r'\xf0\x9f\x95\xba', r'\xf0\x9f\x8f\xbd' ] for x in patternLPoint: match = re.search(x, text) if match: text = re.sub(x, " ", text) return text def removeNoArabicWords(text): print("no arabic removed begin") texts = text.split() result = "" import pyarabic.araby as araby for w in texts: try: w = araby.strip_tatweel(w.decode("utf8")) if araby.is_arabicword(w): result = result + w + " " except: print("Error") return result <file_sep>/MNB_UnderSampling.py import os from imblearn.under_sampling import ClusterCentroids from imblearn.pipeline import Pipeline as imbPipeline from customerTransformation import ExtractTextTransform,ColumnExtractorTransformtion from sklearn.preprocessing import (Imputer, StandardScaler) from sklearn.model_selection import train_test_split,GridSearchCV from sklearn.pipeline import (Pipeline, FeatureUnion) from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report from sklearn.externals import joblib from sklearn.metrics import confusion_matrix from SaveResult import classifaction_report_csv import pandas as pd def Begin (df,LabelOfTarget): trainSamples=df TrainTargets = trainSamples[LabelOfTarget] TextFeaturesOnly=[ ("extractTextUsed", ExtractTextTransform(ColumnO='AUX', ColumnI='ID')), ("tfidf", TfidfVectorizer(stop_words=None)), ] NumericalFeaturesOnly=[ ("extract", ColumnExtractorTransformtion()), ("Imputer", Imputer()), ("Scalar", StandardScaler()) ] # Features_Union = FeatureUnion( # transformer_list=[ # ("text_Features",Pipeline(TextFeaturesOnly)), # ("Numerical_Features",Pipeline(NumericalFeaturesOnly)) # ]) tuned_parametersNumericalOnlyMNB=[ { 'clf__alpha': [0.2,0.4,0.6,0.8,1], 'extract__cols': [["NumOfFollowers"], ["NumOfFollowing"], ["NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing"],["NumOfFollowers", "NumOfTweetsPerDay"],[ "NumOfFollowing", "NumOfTweetsPerDay"], ["NumOfFollowing", "NumOfFollowing", "NumOfTweetsPerDay"]], }, ] tuned_parametersTextOnlyMNB=[ { 'tfidf__ngram_range': [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)], 'clf__alpha': [0.2,0.4,0.6,0.8,1], 'extractTextUsed__Path': [ "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_Stem", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords_Stem", ], }, ] tuned_parametersUnionMNB= [ { 'Features__text_Features__tfidf__ngram_range': [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)], 'clf__alpha': [0.2,0.4,0.6,0.8,1], 'Features__text_Features__extractTextUsed__Path': [ "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_Stem", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords_Stem", ], 'Features__Numerical_Features__extract__cols': [["NumOfFollowers"], ["NumOfFollowing"], ["NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing"],["NumOfFollowers", "NumOfTweetsPerDay"],[ "NumOfFollowing", "NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing", "NumOfTweetsPerDay"]], }, ] pipeTN = imbPipeline([("Features", FeatureUnion( transformer_list=[ ("text_Features", Pipeline(TextFeaturesOnly)), ("Numerical_Features", Pipeline(NumericalFeaturesOnly))])), ('oversample', ClusterCentroids(random_state=20)), ('clf', MultinomialNB()) ]) pipeT = imbPipeline([ ("extractTextUsed", ExtractTextTransform(ColumnO='AUX', ColumnI='ID')), ("tfidf", TfidfVectorizer(stop_words=None)), ('oversample', ClusterCentroids(random_state=20)), ('clf', MultinomialNB()) ]) pipeN = imbPipeline([ ("extract", ColumnExtractorTransformtion()), ("Imputer", Imputer()), ("Scalar", StandardScaler()), ('oversample', ClusterCentroids(random_state=20)), ('clf', MultinomialNB()) ]) gridSearchT = GridSearchCV( pipeT, param_grid=tuned_parametersTextOnlyMNB, cv=5, n_jobs=-1, scoring="f1") gridSearchN = GridSearchCV( pipeN, param_grid=tuned_parametersNumericalOnlyMNB, cv=5, n_jobs=-1, scoring="f1") gridSearchTN = GridSearchCV( pipeTN, param_grid=tuned_parametersUnionMNB, cv=5, n_jobs=-1, scoring="f1") #gridSearchN.fit(trainSamples,TrainTargets) gridSearchT.fit(trainSamples,TrainTargets) #gridSearchTN.fit(trainSamples,TrainTargets) os.chdir("C:\\Users\Marwa\\PycharmProjects\FinalISA\\") #pd.DataFrame(gridSearchN.cv_results_).sort_values(by='rank_test_score').to_csv('Results_GridSearch_Numerical_MNB_Under_'+LabelOfTarget+'.csv') pd.DataFrame(gridSearchT.cv_results_).sort_values(by='rank_test_score').to_csv('Results_GridSearch_Text_MNB_Under_'+LabelOfTarget+'.csv') #pd.DataFrame(gridSearchTN.cv_results_).sort_values(by='rank_test_score').to_csv('Results_GridSearch_BothFeatures_MNB_Under_'+LabelOfTarget+'.csv') #joblib.dump(gridSearchN.best_estimator_,'MNBN_Under_'+LabelOfTarget+'.pkl') joblib.dump(gridSearchT.best_estimator_,'MNBT_Under_'+LabelOfTarget+'.pkl') #joblib.dump(gridSearchTN.best_estimator_,'MNBTN_Under_'+LabelOfTarget+'.pkl') #clf=joblib.load('MNBN_Under_'+LabelOfTarget+'.pkl') #clf=joblib.load('MNBT_Under_'+LabelOfTarget+'.pkl') #clf=joblib.load('MNBTN_Under_'+LabelOfTarget+'.pkl') <file_sep>/FileManging.py # -*- coding: utf-8 -*- class FileManger: def __init__(self, directory, name): self.directory=directory self.name=name #read data from file take directory and file name and return data readed def readFile(self): import os os.chdir(self.directory) fileNeed=open(self.name,"r") self.text=fileNeed.read() fileNeed.close() #print("file " + name + " readed") return self.text #write data in file take directory and file name def writeFile(self,text): import os os.chdir(self.directory) fileNeed = open(self.name,"w") try: fileNeed.write(text.encode("utf8")) except: fileNeed.write(text) fileNeed.close() #print("data writen in " + name) #modify data in file take directory and file name def modifyFile(self,text): fileNeed = open(self.name,"a") fileNeed.write(text) fileNeed.close() #print("data updated in " + name) #clear file from any data def clearFile(self): fileNeed = open(self.name,"w").close() #print("file " + name+" cleared") <file_sep>/DT_UnderSampling.py import os from imblearn.under_sampling import ClusterCentroids from customerTransformation import ExtractTextTransform,ColumnExtractorTransformtion from sklearn.preprocessing import (Imputer, StandardScaler) from sklearn.model_selection import GridSearchCV from sklearn.pipeline import (Pipeline, FeatureUnion) from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.tree import DecisionTreeClassifier from sklearn.externals import joblib from imblearn.pipeline import Pipeline as imbPipeline import pandas as pd def Begin (df,LabelOfTarget): trainSamples=df TrainTargets = trainSamples[LabelOfTarget] TextFeaturesOnly=[ ("extractTextUsed", ExtractTextTransform(ColumnO='AUX', ColumnI='ID')), ("tfidf", TfidfVectorizer(stop_words=None)), ] NumericalFeaturesOnly=[ ("extract", ColumnExtractorTransformtion()), ("Imputer", Imputer()), ("Scalar", StandardScaler()) ] # Features_Union = FeatureUnion( # transformer_list=[ # ("text_Features",Pipeline(TextFeaturesOnly)), # ("Numerical_Features",Pipeline(NumericalFeaturesOnly)) # ]) tuned_parametersNumericalOnlyDT=[ { 'extract__cols': [["NumOfFollowers"], ["NumOfFollowing"], ["NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing"],["NumOfFollowers", "NumOfTweetsPerDay"],[ "NumOfFollowing", "NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing", "NumOfTweetsPerDay"]], }, ] tuned_parametersTextOnlyDT=[ { 'tfidf__ngram_range': [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)], 'extractTextUsed__Path': [ "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_Stem", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords_Stem", ], }, ] tuned_parametersUnionDT= [ { 'Features__text_Features__tfidf__ngram_range': [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)], 'Features__text_Features__extractTextUsed__Path': [ "C:\\Users\Marwa\\PycharmProjects\\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant", "C:\\Users\Marwa\\PycharmProjects\\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_Stem", "C:\\Users\Marwa\\PycharmProjects\\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords", "C:\\Users\Marwa\\PycharmProjects\\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords_Stem", ], 'Features__Numerical_Features__extract__cols': [["NumOfFollowers"], ["NumOfFollowing"], ["NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing"],["NumOfFollowers", "NumOfTweetsPerDay"],[ "NumOfFollowing", "NumOfTweetsPerDay"], ["NumOfFollowing", "NumOfFollowing", "NumOfTweetsPerDay"]], }, ] pipeTN = imbPipeline([("Features", FeatureUnion( transformer_list=[ ("text_Features", Pipeline(TextFeaturesOnly)), ("Numerical_Features", Pipeline(NumericalFeaturesOnly))])), ('oversample', ClusterCentroids(random_state=20)), ('clf', DecisionTreeClassifier()) ]) pipeT = imbPipeline([ ("extractTextUsed", ExtractTextTransform(ColumnO='AUX', ColumnI='ID')), ("tfidf", TfidfVectorizer(stop_words=None)), ('oversample', ClusterCentroids(random_state=20)), ('clf', DecisionTreeClassifier()) ]) pipeN = imbPipeline([ ("extract", ColumnExtractorTransformtion()), ("Imputer", Imputer()), ("Scalar", StandardScaler()), ('oversample', ClusterCentroids(random_state=20)), ('clf', DecisionTreeClassifier()) ]) gridSearchT = GridSearchCV( pipeT, param_grid=tuned_parametersTextOnlyDT, cv=5, n_jobs=-1, scoring="f1") gridSearchN = GridSearchCV( pipeN, param_grid=tuned_parametersNumericalOnlyDT, cv=5, n_jobs=-1, scoring="f1") gridSearchTN = GridSearchCV( pipeTN, param_grid=tuned_parametersUnionDT, cv=5, n_jobs=-1, scoring="f1") gridSearchT.fit(trainSamples,TrainTargets) #gridSearchN.fit(trainSamples,TrainTargets) #gridSearchTN.fit(trainSamples,TrainTargets) os.chdir("C:\\Users\Marwa\\PycharmProjects\FinalISA\\") #pd.DataFrame(gridSearchN.cv_results_).sort_values(by='rank_test_score').to_csv( # 'Results_GridSearch_Numerical_DT_Under_' + LabelOfTarget + '.csv') #joblib.dump(gridSearchN.best_estimator_, './DTN_Under_'+LabelOfTarget+'.pkl') pd.DataFrame(gridSearchT.cv_results_).sort_values(by='rank_test_score').to_csv( 'Results_GridSearch_Text_DT_Under_' + LabelOfTarget + '.csv') joblib.dump(gridSearchT.best_estimator_, './DTT_Under_'+LabelOfTarget+'.pkl') #pd.DataFrame(gridSearchTN.cv_results_).sort_values(by='rank_test_score').to_csv('Results_GridSearch_BothFeatures_DT_Under_'+LabelOfTarget+'.csv') #joblib.dump(gridSearchTN.best_estimator_,'./DTTN_Under_'+LabelOfTarget+'.pkl') # with open('DTT.pkl', 'wb') as f: # pickl/e.dump(gridSearchT.best_estimator_, f) # feature_names = gridSearchT.best_estimator_.named_steps['text_Features'].named_steps['tfidf'].get_feature_names() # for f in feature_names: # print f # clf=joblib.load('./DTN_Under_'+LabelOfTarget+'.pkl') # clf=joblib.load('./DTT_Under_'+LabelOfTarget+'.pkl') # clf=joblib.load('./DTTN_Under_'+LabelOfTarget+'.pkl') <file_sep>/MLP_OverSampling.py import os from imblearn.over_sampling import SMOTE from imblearn.pipeline import Pipeline as imbPipeline from customerTransformation import ExtractTextTransform,ColumnExtractorTransformtion from sklearn.preprocessing import (Imputer, StandardScaler) from sklearn.model_selection import train_test_split,GridSearchCV from sklearn.pipeline import (Pipeline, FeatureUnion) from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.neural_network import MLPClassifier from sklearn.metrics import classification_report from sklearn.externals import joblib from SaveResult import classifaction_report_csv import pandas as pd def Begin (Path,LabelOfTarget): df = pd.read_csv(Path) trainSamples, testSamples = train_test_split(df,test_size=0.34) TrainTargets = trainSamples[LabelOfTarget] TestTargets=testSamples[LabelOfTarget] TextFeaturesOnly=[ ("extractTextUsed", ExtractTextTransform(ColumnO='AUX', ColumnI='ID')), ("tfidf", TfidfVectorizer(stop_words=None)), ] NumericalFeaturesOnly=[ ("extract", ColumnExtractorTransformtion()), ("Imputer", Imputer()), ("Scalar", StandardScaler()) ] # Features_Union = FeatureUnion( # transformer_list=[ # ("text_Features",Pipeline(TextFeaturesOnly)), # ("Numerical_Features",Pipeline(NumericalFeaturesOnly)) # ]) tuned_parametersNumericalOnlyDT=[ { 'clf__hidden_layer_sizes':[(30,20,10),(60,50,40),(70,80,90)], 'extract__cols': [["NumOfFollowers"], ["NumOfFollowing"], ["NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing"],["NumOfFollowers", "NumOfTweetsPerDay"],[ "NumOfFollowing", "NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing", "NumOfTweetsPerDay"]], }, ] tuned_parametersTextOnlyDT=[ { 'clf__hidden_layer_sizes': [(30, 20, 10), (60, 50, 40), (70, 80, 90)], 'tfidf__ngram_range': [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)], 'extractTextUsed__Path': [ "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_Stem", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords_Stem", ], }, ] tuned_parametersUnionDT= [ { 'clf__hidden_layer_sizes': [(30, 20, 10), (60, 50, 40), (70, 80, 90)], 'Features__text_Features__tfidf__ngram_range': [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)], 'Features__text_Features__extractTextUsed__Path': [ "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_Stem", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords_Stem", ], 'Features__Numerical_Features__extract__cols': [["NumOfFollowers"], ["NumOfFollowing"], ["NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing"],["NumOfFollowers", "NumOfTweetsPerDay"],[ "NumOfFollowing", "NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing", "NumOfTweetsPerDay"]], }, ] pipeTN = imbPipeline([("Features", FeatureUnion( transformer_list=[ ("text_Features", Pipeline(TextFeaturesOnly)), ("Numerical_Features", Pipeline(NumericalFeaturesOnly))])), ('oversample', SMOTE(random_state=20)), ('clf', MLPClassifier()) ]) pipeT = imbPipeline([ ("extractTextUsed", ExtractTextTransform(ColumnO='AUX', ColumnI='ID')), ("tfidf", TfidfVectorizer(stop_words=None)), ('oversample', SMOTE(random_state=20)), ('clf', MLPClassifier()) ]) pipeN = imbPipeline([ ("extract", ColumnExtractorTransformtion()), ("Imputer", Imputer()), ("Scalar", StandardScaler()), ('oversample', SMOTE(random_state=20)), ('clf', MLPClassifier()) ]) gridSearchT = GridSearchCV( pipeT, param_grid=tuned_parametersTextOnlyDT, cv=5, n_jobs=-1, scoring="f1") gridSearchN = GridSearchCV( pipeN, param_grid=tuned_parametersNumericalOnlyDT, cv=5, n_jobs=-1, scoring="f1") gridSearchTN = GridSearchCV( pipeTN, param_grid=tuned_parametersUnionDT, cv=5, n_jobs=-1, scoring="f1") gridSearchN.fit(trainSamples, TrainTargets) gridSearchT.fit(trainSamples,TrainTargets) gridSearchTN.fit(trainSamples,TrainTargets) os.chdir("C:\\Users\Marwa\\PycharmProjects\FinalISA\\") #pd.DataFrame(gridSearchN.cv_results_).sort_values(by='rank_test_score').to_csv('Results_GridSearch_Numerical_MLP_'+LabelOfTarget+'.csv') pd.DataFrame(gridSearchT.cv_results_).sort_values(by='rank_test_score').to_csv('Results_GridSearch_Text_MLP_'+LabelOfTarget+'.csv') #pd.DataFrame(gridSearchTN.cv_results_).sort_values(by='rank_test_score').to_csv('Results_GridSearch_BothFeatures_MLP_'+LabelOfTarget+'.csv') #joblib.dump(gridSearchN.best_estimator_,'MLPN_'+LabelOfTarget+'.pkl') joblib.dump(gridSearchT.best_estimator_,'MLPT_'+LabelOfTarget+'.pkl') #joblib.dump(gridSearchTN.best_estimator_,'MLPTN_'+LabelOfTarget+'.pkl') # clf=joblib.load('MLPN_'+LabelOfTarget+'.pkl') clf=joblib.load('MLPT_'+LabelOfTarget+'.pkl') # clf=joblib.load('MLPTN_'+LabelOfTarget+'.pkl') predictions = gridSearchT.predict(testSamples) print classification_report(TestTargets, predictions) Begin("DataSet_11_Nov_Tweets_csv1.csv","O") Begin("DataSet_11_Nov_Tweets_csv1.csv","C") Begin("DataSet_11_Nov_Tweets_csv1.csv","E") Begin("DataSet_11_Nov_Tweets_csv1.csv","A") Begin("DataSet_11_Nov_Tweets_csv1.csv","N")<file_sep>/CorrelationCalculation.py import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("DataSet_11_Nov_Tweets_csv1.csv") new_df=df.drop(['ProfilePic','ID'], axis=1).corr(method='spearman') new_df.to_csv('CorrelationSpearman11Nov.csv') new_df=df.drop(['ProfilePic','ID'], axis=1).corr(method='pearson') new_df.to_csv('CorrelationPearson11Nov.csv') new_df=df.drop(['ProfilePic','ID'], axis=1).corr(method='kendall') new_df.to_csv('Correlationkendall11Nov.csv') # plt.rcParams['figure.figsize'] = (50,50) # # fig, ax = plt.subplots(nrows=1, ncols=1) # # #ax=ax.flatten() # cols = [ # 'NumOfFollowers','NumOfFollowing','NumOfTweetsPerDay', # #'O','C','E','A','N', # ] # colors=['#415952', '#f35134', '#243AB5', '#243AB5','#415952', '#f35134', '#243AB5', '#243AB5'] # # bx=['O_Sc','C','E','A','N'] # j=0 # x=0 # index=0 # #for i in ax: # if j%1 ==0: # x=j/1 # index=0 # ax.set_ylabel(bx[x]) # ax.scatter(df[cols[index]], # df[bx[x]], # alpha=0.5, # color=colors[index]) # ax.set_xlabel(cols[index]) # ax.set_title('Pearson: %s'%df.corr().loc[cols[index]][bx[x]].round(2)+' Spearman: %s'%df.corr(method='spearman').loc[cols[index]][bx[x]].round(2)) # j+=1 # index+=1 # # plt.show()<file_sep>/RUN_All.py import pandas as pd import MNB import MNB_OverSampling import MNB_UnderSampling import SVM import SVM_OverSampling import SVM_UnderSampling import DT import DT_OverSampling import DT_UnderSampling import KNN import KNN_OverSampling import KNN_UnderSampling # from sklearn.model_selection import train_test_split # df = pd.read_csv("DataSet_11_Nov_Tweets_csv1.csv") # trainSamples, testSamples = train_test_split(df, test_size=0.34) # testSamples.to_csv("TestSampling.csv") # trainSamples.to_csv("TrainSampling.csv") # df=trainSamples # import matplotlib.pyplot as plt # fig, ax = plt.subplots(nrows=1, ncols=1) # #UNBALANCE # df.O.value_counts().plot(kind='bar', title='Count (O)') # print "O" # print df.O.value_counts() # plt.show() # df.C.value_counts().plot(kind='bar', title='Count (C)') # print "C" # print df.C.value_counts() # plt.show() # df.E.value_counts().plot(kind='bar', title='Count (E)') # print "E" # print df.E.value_counts() # plt.show() # #UNBALANCE # df.A.value_counts().plot(kind='bar', title='Count (A)') # print "A" # print df.A.value_counts() # plt.show() # df.N.value_counts().plot(kind='bar', title='Count (N)') # print "N" # print df.N.value_counts() # plt.show() trainSamples = pd.read_csv("DataSet_11_Nov_Tweets_csv1.csv") # MNB.Begin(trainSamples,"O") # MNB.Begin(trainSamples,"C") # MNB.Begin(trainSamples,"E") # MNB.Begin(trainSamples,"A") # MNB.Begin(trainSamples,"N") # MNB_OverSampling.Begin(trainSamples,"O") #ValueError: Expected n_neighbors <= n_samples, but n_samples = 5, n_neighbors = 6 MNB_OverSampling.Begin(trainSamples,"A") # MNB_UnderSampling.Begin(trainSamples,"O") # MNB_UnderSampling.Begin(trainSamples,"A") # # SVM.Begin(trainSamples,"O") # SVM.Begin(trainSamples,"C") # SVM.Begin(trainSamples,"E") # SVM.Begin(trainSamples,"A") # SVM.Begin(trainSamples,"N") SVM_UnderSampling.Begin(trainSamples,"O") SVM_UnderSampling.Begin(trainSamples,"A") SVM_OverSampling.Begin(trainSamples,"O") SVM_OverSampling.Begin(trainSamples,"A") # DT.Begin(trainSamples,"O") # DT.Begin(trainSamples,"C") # DT.Begin(trainSamples,"E") # DT.Begin(trainSamples,"A") # DT.Begin(trainSamples,"N") # DT_UnderSampling.Begin(trainSamples,"O") # DT_UnderSampling.Begin(trainSamples,"A") # DT_OverSampling.Begin(trainSamples,"O") #ValueError: Expected n_neighbors <= n_samples, but n_samples = 5, n_neighbors = 6 DT_OverSampling.Begin(trainSamples,"A") # KNN.Begin(trainSamples,"O") # KNN.Begin(trainSamples,"C") # KNN.Begin(trainSamples,"E") # KNN.Begin(trainSamples,"A") # KNN.Begin(trainSamples,"N") # KNN_UnderSampling.Begin(trainSamples,"O") # KNN_UnderSampling.Begin(trainSamples,"A") # KNN_OverSampling.Begin(trainSamples,"O") KNN_OverSampling.Begin(trainSamples,"A")<file_sep>/MNB.py import os from customerTransformation import ExtractTextTransform,ColumnExtractorTransformtion from sklearn.preprocessing import (Imputer, StandardScaler) from sklearn.model_selection import train_test_split,GridSearchCV from sklearn.pipeline import (Pipeline, FeatureUnion) from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import classification_report from sklearn.externals import joblib from sklearn.metrics import confusion_matrix from SaveResult import classifaction_report_csv import pandas as pd def Begin (df,LabelOfTarget): trainSamples=df TrainTargets = trainSamples[LabelOfTarget] TextFeaturesOnly=[ ("extractTextUsed", ExtractTextTransform(ColumnO='AUX', ColumnI='ID')), ("tfidf", TfidfVectorizer(stop_words=None)), ] NumericalFeaturesOnly=[ ("extract", ColumnExtractorTransformtion()), ("Imputer", Imputer()), ("Scalar", StandardScaler()) ] Features_Union = FeatureUnion( transformer_list=[ ("text_Features",Pipeline(TextFeaturesOnly)), ("Numerical_Features",Pipeline(NumericalFeaturesOnly)) ]) tuned_parametersNumericalOnlyMNB=[ { 'clf__alpha': [0.2,0.4,0.6,0.8,1], 'Numerical_Features__extract__cols': [["NumOfFollowers"], ["NumOfFollowing"], ["NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing"],["NumOfFollowers", "NumOfTweetsPerDay"],[ "NumOfFollowing", "NumOfTweetsPerDay"], ["NumOfFollowing", "NumOfFollowing", "NumOfTweetsPerDay"]], }, ] tuned_parametersTextOnlyMNB=[ { 'text_Features__tfidf__ngram_range': [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)], 'clf__alpha': [0.2,0.4,0.6,0.8,1], 'text_Features__extractTextUsed__Path': [ "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_Stem", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords_Stem", ], }, ] tuned_parametersUnionMNB= [ { 'Features__text_Features__tfidf__ngram_range': [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)], 'clf__alpha': [0.2,0.4,0.6,0.8,1], 'Features__text_Features__extractTextUsed__Path': [ "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_Stem", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords", "C:\\Users\Marwa\\PycharmProjects\FinalISA\\DataSet_10_Nov_Clean_Normalize_Redundant_StopWords_Stem", ], 'Features__Numerical_Features__extract__cols': [["NumOfFollowers"], ["NumOfFollowing"], ["NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing"],["NumOfFollowers", "NumOfTweetsPerDay"],[ "NumOfFollowing", "NumOfTweetsPerDay"], ["NumOfFollowers", "NumOfFollowing", "NumOfTweetsPerDay"]], }, ] gridSearchT = GridSearchCV( estimator=Pipeline(steps=[ ("text_Features",Pipeline(TextFeaturesOnly)), ("clf", MultinomialNB()), ]), param_grid=tuned_parametersTextOnlyMNB, cv=10, n_jobs=-1, scoring="f1") gridSearchN = GridSearchCV( estimator=Pipeline(steps=[ ('Numerical_Features', Pipeline(NumericalFeaturesOnly)), ("clf", MultinomialNB()) ]), param_grid=tuned_parametersNumericalOnlyMNB, cv=10, n_jobs=-1, scoring="f1") gridSearchTN = GridSearchCV( estimator=Pipeline(steps=[ ('Features', Features_Union), ("clf", MultinomialNB()) ]), param_grid=tuned_parametersUnionMNB, cv=10, n_jobs=-1, scoring="f1") #gridSearchN.fit(trainSamples,TrainTargets) gridSearchT.fit(trainSamples,TrainTargets) #gridSearchTN.fit(trainSamples,TrainTargets) os.chdir("C:\\Users\Marwa\\PycharmProjects\FinalISA\\") #pd.DataFrame(gridSearchN.cv_results_).sort_values(by='rank_test_score').to_csv('Results_GridSearch_Numerical_MNB_Under_'+LabelOfTarget+'.csv') pd.DataFrame(gridSearchT.cv_results_).sort_values(by='rank_test_score').to_csv('Results_GridSearch_Text_MNB_'+LabelOfTarget+'.csv') #pd.DataFrame(gridSearchTN.cv_results_).sort_values(by='rank_test_score').to_csv('Results_GridSearch_BothFeatures_MNB_Under_'+LabelOfTarget+'.csv') #joblib.dump(gridSearchN.best_estimator_,'MNBN_Under_'+LabelOfTarget+'.pkl') joblib.dump(gridSearchT.best_estimator_,'MNBT_'+LabelOfTarget+'.pkl') #joblib.dump(gridSearchTN.best_estimator_,'MNBTN_Under_'+LabelOfTarget+'.pkl') #clf=joblib.load('MNBN_Under_'+LabelOfTarget+'.pkl') #clf=joblib.load('MNBT_Under_'+LabelOfTarget+'.pkl') #clf=joblib.load('MNBTN_Under_'+LabelOfTarget+'.pkl') #predictions = gridSearchT.predict(testSamples) #report= classification_report(TestTargets, predictions) #conf=confusion_matrix(TestTargets,predictions,labels=[0,1]) # try: # classifaction_report_csv(report,conf,"MNBT_BestEstimatorTesting_"+LabelOfTarget) # except: # print report # print conf <file_sep>/customerTransformation.py from sklearn.base import TransformerMixin,BaseEstimator from CleaningStage import textCleaning import FileManging import PreprocessingStage class ExtractTextTransform(BaseEstimator,TransformerMixin): def __init__(self,ColumnI,ColumnO, Path="C:\\Users\Marwa\\PycharmProjects\LoadDS\\DataSet_10_Nov_Clean_Normalize_Redundant"): self.I = ColumnI self.O = ColumnO self.Path = Path def transform(self,X, **kwargs): X[self.O]=X.apply(lambda row: (FileManging.FileManger(self.Path,str(long(row[self.I]))+'.txt').readFile()), axis=1) return X[self.O] def fit(self,X, y=None, **kwargs): return self def get_params(self,**kwargs): return {'Path':self.Path,'ColumnI':self.I,'ColumnO':self.O} class ColumnExtractorTransformtion(BaseEstimator,TransformerMixin): def __init__(self, cols=[]): self.cols = cols def fit(self, x, y=None): return self def transform(self, x): Xcols = x[self.cols] return Xcols def get_params(self, **kwargs): return {'cols': self.cols}
2356af1aaea8127de0eafea2a9502c864b5c4b6f
[ "Markdown", "Python" ]
13
Python
MarwaSalim/araperso
74cfab8b668200c95fa48de28e7ebfaafd65bad6
c36961f0e8bb9688c3ac648cfba8896fb07bc706
refs/heads/master
<file_sep>'use strict'; const sinon = require('sinon'); class SinonMocker { constructor() { this._stubs = new Set(); this._sandbox = sinon.createSandbox(); } } <file_sep>'use strict'; const { RedisMocker } = require('../utils'); const { expect } = require('chai'); const redisClient = require('./../../src/redis-client'); const redisMocker = new RedisMocker(); describe("test resdis-get-async-mock", () => { beforeEach(() => { }); afterEach(() => { redisMocker.reset(); }); it('test one', async () => { // GIVE redisMocker.mockGetOnFirstCall(true); redisMocker.mockGetOnSecondCall(false); // WHEN const client = new redisClient(); const response1 = await client.getDocById(1); const response2 = await client.getDocById(2); // THEN expect(response1).to.eql(true); expect(response2).to.eql(false); }); }); <file_sep> const { createSandbox } = require('sinon'); const { FakeRedis } = require('../fake'); const redis = require('redis'); class RedisMocker { constructor() { this._sandbox = createSandbox(); this._redis = new FakeRedis(); this._sandbox.stub(redis, 'createClient').returns(this._redis); this.generateStubs(); } generateStubs() { this.getStub = this._sandbox.stub(this._redis, 'get'); } mockGetOnFirstCall(value) { this.getStub.onFirstCall().yields(null, value); } mockGetOnSecondCall(value) { this.getStub.onSecondCall().yields(null, value); } reset() { this._sandbox.restore(); } } module.exports = RedisMocker; <file_sep>'use strict'; const redis = require('redis'); const { promisify } = require("util"); // const bluebird = require('bluebird'); class RedisClient { constructor() { ['REDIS_HOST', 'REDIS_PORT', 'REDIS_PASS'].forEach(envName => { const variable = process.env[envName]; if (!variable) throw Error(`the environment variable ${ envName } must be defined`); }); // bluebird.promisifyAll(redis.RedisClient.prototype); this._client = redis.createClient({ host: process.env.REDIS_HOST, port: process.env.REDIS_PORT, password: <PASSWORD> }).on('error', err => { console.error('error when establishing connection with redis'); throw err; }); this.getAsync = promisify(this._client.get).bind(this._client); this._expirationTime = process.env.TTL || 86400; } async getDocById(id) { try { return JSON.parse(await this.getAsync(id)); } catch (err) { console.error(`Oops! There's been a mistake: ${ JSON.stringify(err, null, 2) }`); throw err; } } /* getAsync(key) { return new Promise((resolve, reject) => { this._client.get(key, (err, reply) => { if (err) reject(err); resolve(reply); }); }); }*/ } module.exports = RedisClient;
13fd7291b01b6692c07ade24a3f2d65a5a22724f
[ "JavaScript" ]
4
JavaScript
eze1214/redis-mocker
d331045a2971f764d9251036e2b14af5d806d561
cb167eef07c82a1c47c5817ba24dc96fe5444efc
refs/heads/master
<file_sep>const chalk = require ('chalk'); console.log(chalk.blue.bgYellow.bold('Melanie')); console.log(chalk.magentaBright.bgWhite.bold('Violette')); console.log(chalk.green.bgRed.bold('Maxence')); console.log(chalk.yellow.bgCyan.bold('Baptiste'));
b17fa1fedd1049243c3db6fa8c9940db7a7c8032
[ "JavaScript" ]
1
JavaScript
BarbierAlexis/Wilders
55db633c9bb7fd6c5e47ccee5e269fabe0ee56ff
8743b2ca5b5691d828652d587b036cfc18caf18e
refs/heads/master
<repo_name>isk4/consulta-afp<file_sep>/app/controllers/requests_controller.rb class RequestsController < ApplicationController include ActionController::MimeResponds def show respond_to do |format| format.html { render status: :forbidden } format.json { render json: Request.where(client: params[:name]).count } end end end<file_sep>/app/controllers/ufs_controller.rb class UfsController < ApplicationController include ActionController::MimeResponds def show respond_to do |format| format.html { render status: :forbidden } format.json do begin @date = Date.parse(params[:date]) if @date.month < 3 @uf = Uf.find_by(month: @date.month, day: @date.day) Request.create(client: request.headers['X-CLIENTE']) render json: @uf.value else render json: "Fecha inválida" end rescue ArgumentError render json: "Fecha inválida" end end end end end<file_sep>/config/routes.rb Rails.application.routes.draw do get 'uf/:date', to: 'ufs#show' get 'client/:name', to: 'requests#show' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end<file_sep>/README.md # Desafío - Consultando el valor de la UF<file_sep>/db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require 'csv' file_path = Rails.root.join("public", "UF_2019.csv") file = File.read(file_path.to_s) file = file.gsub(".", "").gsub(",", ".").gsub(";", ",") parsed_file = CSV.parse(file) parsed_file = parsed_file[1..parsed_file.length] for i in 0..parsed_file.length parsed_file[i] = parsed_file[i].drop(1) unless parsed_file[i].nil? end for i in 0...parsed_file.length for j in 0...parsed_file[i].length Uf.create(month: j + 1, day: i + 1, value: parsed_file[i][j]) unless parsed_file[i][j].nil? end end
228c107d3de67f82c2a9be4f4578ec7a9b862832
[ "Markdown", "Ruby" ]
5
Ruby
isk4/consulta-afp
ad196726cf74ceddffbf4f15f527ae9cd23e6ad8
214eeed6365b0ac087c9241442c59eaea25bea0e
refs/heads/master
<repo_name>JoyGromi/hw6<file_sep>/src/app/pipes/filter.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import { IHotel } from '../intesfaces/IHotel'; @Pipe({ name: 'filter' }) export class FilterPipe implements PipeTransform { transform(hotels: IHotel[], searchHotel: string): any { if (!searchHotel) { return hotels; } return hotels.filter((hotel: IHotel) => { return `${hotel.title.toLowerCase()}${hotel.description.toLowerCase()}` .includes(searchHotel.toLowerCase()); }); } } <file_sep>/src/app/hotels/hotels.component.ts import { Component, OnInit } from '@angular/core'; import { PageEvent } from '@angular/material'; import { Observable, of } from 'rxjs'; import { HotelsService } from '../services/hotels.service'; import { IHotel } from '../intesfaces/IHotel'; @Component({ selector: 'app-hotels', templateUrl: './hotels.component.html', styleUrls: ['./hotels.component.css'] }) export class HotelsComponent implements OnInit { // public page: PageEvent = { // pageIndex: 1, // pageSize: 2, // length: 2 // }; // public isLoading$: Observable<boolean> = of(true); // public hotels$: Observable<IHotel[]>; // public currentHotel: IHotel; // public searchHotel: string; // public hotel: IHotel; public constructor( // private hotelService: HotelsService, ) { } public ngOnInit(): void { // this.getHotels(this.page); // setTimeout(() => { // this.isLoading$ = of(false); // }, 1500 ); // this.hotels$.subscribe( (hotel: IHotel[]) => { // this.currentHotel = hotel[0]; // }); } // public getHotels(event: PageEvent): void { // this.hotels$ = this.hotelService.getHotels(event); // // this.hotels$.subscribe( (hotel: IHotel[]) => { // // this.currentHotel = hotel[0]; // // }); // } // public setHotel(hotel: IHotel): void { // this.currentHotel = hotel; // } // public search(event: Event): void { // this.searchHotel = (event.target as HTMLInputElement).value; // } // public changeHotel(event: PageEvent): void { // this.page = event; // this.getHotels(event); // } }<file_sep>/src/app/hotels/hotels.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { HotelsComponent } from './hotels.component'; import { DetailComponent } from './detail/detail.component'; import { HotelsService } from '../services/hotels.service'; import { ListComponent } from './list/list.component'; import { MatCardModule, MatPaginatorModule, MatBadgeModule, MatIconModule, MatListModule, MatButtonModule } from '@angular/material'; import { FavoriteComponent } from './favorite/favorite.component'; import { WeatherComponent } from './weather/weather.component'; import { ProfileComponent } from './profile/profile.component'; import { FilterPipe } from '../pipes/filter.pipe'; import { FlexLayoutModule } from '@angular/flex-layout'; const routes: Routes = [ { path: '', component: HotelsComponent, children: [ { path: '', component: ListComponent }, { path: 'detail/:hotelId', component: DetailComponent } ] } ] @NgModule({ declarations: [ FilterPipe, HotelsComponent, FavoriteComponent, DetailComponent, ListComponent, WeatherComponent, ProfileComponent, ], imports: [ CommonModule, MatCardModule, MatPaginatorModule, MatBadgeModule, MatButtonModule, MatIconModule, MatListModule, FlexLayoutModule, RouterModule.forChild(routes) ], providers: [ HotelsService ] }) export class HotelsModule { } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; // import { FilterPipe } from './pipes/filter.pipe'; import { AppComponent } from './app.component'; import { FooterComponent } from './footer/footer.component'; import { HeaderComponent } from './header/header.component'; import { NavComponent } from './nav/nav.component'; // import { HotelListComponent } from './hotel-list/hotel-list.component'; // import { HotelsComponent } from './hotels/hotels.component'; // import { ListComponent } from './hotels/list/list.component'; // import { WeatherComponent } from './hotels/weather/weather.component'; // import { ProfileComponent } from './hotels/profile/profile.component'; // import { FavoriteComponent } from './hotels/favorite/favorite.component'; import { MatListModule } from '@angular/material/list'; import { MatCardModule } from '@angular/material/card'; import { FlexLayoutModule } from '@angular/flex-layout/'; import { MatIconModule } from '@angular/material/icon'; import { MatButtonModule, MatInputModule } from '@angular/material'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatBadgeModule } from '@angular/material/badge'; import { MatPaginatorModule } from '@angular/material/paginator'; // import { UsersComponent } from './users/users.component'; import { AboutComponent } from './about/about.component'; import { ContactsComponent } from './contacts/contacts.component'; import { RouterModule } from '@angular/router'; import { MatToolbarModule } from '@angular/material/toolbar'; import { routes } from './config.routes'; // import { DetailComponent } from './hotels/detail/detail.component'; import { CommentsComponent } from './hotels/detail/comments/comments.component'; @NgModule({ declarations: [ AppComponent, FooterComponent, HeaderComponent, NavComponent, // HotelListComponent, // HotelsComponent, // ListComponent, // WeatherComponent, // ProfileComponent, // FilterPipe, // FavoriteComponent, // UsersComponent, AboutComponent, ContactsComponent, // DetailComponent, CommentsComponent ], imports: [ BrowserModule, HttpClientModule, // MaterialModule.forRoot, BrowserAnimationsModule, MatToolbarModule, MatListModule, MatCardModule, MatInputModule, MatButtonModule, MatIconModule, MatBadgeModule, MatPaginatorModule, FlexLayoutModule, RouterModule.forRoot(routes) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/services/favorite.service.ts import { Injectable } from '@angular/core'; import { IHotel, IFavorite } from '../intesfaces/IHotel'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class FavoriteService { private favorite: IFavorite[] = []; public addToFavorite(hotel: IHotel) { const index: number = this.favorite.findIndex((item: IFavorite) => item.id === hotel.id); if (index !== -1) { const item: IFavorite = this.favorite[index]; item.amountInFavt = item.amountInFavt + 1; return; } this.favorite.push({...hotel, amountInFavt: 1 }); } // constructor() { } public getFavorite(): IFavorite[] { return this.favorite; } public removeFavorite(id: number): void { const index: number = this.favorite.findIndex((item: IFavorite) => item.id === id); this.favorite.splice(index, 1); } // public updateFavorite(): } <file_sep>/src/app/config.routes.ts import { Routes } from '@angular/router'; // import { HotelsComponent } from './hotels/hotels.component'; import { AboutComponent } from './about/about.component'; // import { UsersComponent } from './users/users.component'; import { ContactsComponent } from './contacts/contacts.component'; export const routes: Routes = [ // Redirect // { // path: '', redirect: hotels, pathMach: 'full', // }, { path: 'hotels', //component: HotelsComponent, loadChildren: './hotels/hotels.module#HotelsModule' }, { path: 'about', component: AboutComponent, }, { path: 'users', //component: UsersComponent, loadChildren: './users/users.module#UsersModule' }, { path: 'contacts', component: ContactsComponent, }, ]<file_sep>/src/app/hotels/favorite/favorite.component.ts import { Component, OnInit } from '@angular/core'; import { IFavorite } from 'src/app/intesfaces/IHotel'; import { FavoriteService } from './../../services/favorite.service'; @Component({ selector: 'app-favorite', templateUrl: './favorite.component.html', styleUrls: ['./favorite.component.css'] }) export class FavoriteComponent implements OnInit { public favorite: IFavorite[] = []; constructor( private favoriteService: FavoriteService ) { } ngOnInit() { this.favorite = this.favoriteService.getFavorite(); } public removeFavorite(id: number): void { this.favoriteService.removeFavorite(id); } } <file_sep>/src/app/hotels/detail/detail.component.ts import { Component, OnInit } from '@angular/core'; import { HotelsService } from 'src/app/services/hotels.service'; import { Observable } from 'rxjs'; import { switchMap } from 'rxjs/operators'; import { IHotel } from 'src/app/intesfaces/IHotel'; import { ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-detail', templateUrl: './detail.component.html', styleUrls: ['./detail.component.css'] }) export class DetailComponent implements OnInit { hotel$: Observable<IHotel>; constructor( private activatedRoute: ActivatedRoute, private hotelService: HotelsService ) { } ngOnInit( ) { this.hotel$ = this.activatedRoute.paramMap.pipe( switchMap((param: ParamMap) => this.hotelService.getHotel(param.get('hotelId'))) ); } } <file_sep>/src/app/services/hotels.service.ts import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { PageEvent } from '@angular/material'; import { environment } from 'src/environments/environment'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { IHotel } from '../intesfaces/IHotel'; @Injectable({ providedIn: 'root' }) export class HotelsService { constructor( private http: HttpClient ) { } public getHotels (event: PageEvent): Observable<IHotel[]> { // console.log(event); const headers: HttpHeaders = new HttpHeaders(); headers.append('Content-Type', 'application/json'); headers.append('Authorization', 'token from local storage'); const params: HttpParams = new HttpParams( { fromObject: { _limit: String(event.pageSize), _page: String(event.pageIndex), } } ); return this.http.get<IHotel[]>(`${environment.apiUrl}/hotels`, {params, headers}); } public getHotel(hotelId: string): Observable<IHotel>{ return this.http.get<IHotel>(`${environment.apiUrl}/hotels/${hotelId}`); } public addHotel(hotel: IHotel): Observable<IHotel> { return this.http.post<IHotel>(`${environment.apiUrl}/hotels`, hotel); } public updateHotel(hotel: IHotel): Observable<IHotel> { return this.http.patch<IHotel>(`${environment.apiUrl}/hotels/${hotel.id}`, hotel); } public deleteHotel(id: number): Observable<IHotel> { return this.http.delete<IHotel>(`${environment.apiUrl}/hotels/${id}`); } }
fed1bf84204b4e25ccae2ebb792fd81d59f94798
[ "TypeScript" ]
9
TypeScript
JoyGromi/hw6
83391c4a11bb39b8bdd599713fcf4c0e310558b7
894fadf0ab8804e67f9b019c862a5578d01448fb
refs/heads/master
<repo_name>vajrala2001/react-chat-app<file_sep>/src/components/Chat/Chat.js import React , {useState,useEffect} from 'react' import queryString from 'query-string' import io from 'socket.io-client' import TextContainer from '../TextContainer/TextContainer'; import InfoBar from '../InfoBar/InfoBar' import Input from '../Input/Input' import Messages from '../Messages/Messages' import './Chat.css' let socket const Chat = ({location}) => { const [name,setName] = useState('') const [room,setRoom] = useState('') const [users, setUsers] = useState(''); const [message,setMessage] = useState('') const [messages,setMessages] = useState([]) const ENDPOINT = 'https://chat-app-react-nodejs.herokuapp.com/' useEffect(() => { const {name,room} = queryString.parse(location.search) socket = io(ENDPOINT) setName(name) setRoom(room) socket.emit('join',{name,room},(error) => { if(error) return error }) },[ENDPOINT,location.search]) useEffect(() => { socket.on('message',(message) => { setMessages([...messages,message]) }) },[messages]) useEffect(() => { socket.on("roomData", ({ users }) => { setUsers(users); }); }, []); //function for sending messages const sendMessage = (event) => { event.preventDefault() if(message){ socket.emit('sendMessage',message,() => setMessage('')) } } return( <div className="outerContainer"> <div className="container"> <InfoBar room={room}/> <Messages messages = {messages} name = {name}/> <Input message = {message} setMessage = {setMessage} sendMessage = {sendMessage}/> </div> <TextContainer users={users}/> </div> ) } export default Chat;
c39e61d3a6717e5b5e3aca6718e893e3347b4d20
[ "JavaScript" ]
1
JavaScript
vajrala2001/react-chat-app
cd42f66488abb11f24cf07ad4391686fea2b208d
a864215a9ad1975fd42b11b35242ab0cf7592dc9
refs/heads/main
<repo_name>rajaKumaranraja/startingProjects<file_sep>/README.md # zuprojects <file_sep>/redux-learn/index.js const redux = require("redux"); const createStore = redux.createStore; const combineReducers = redux.combineReducers; const BUY_CAKE = "BUY_CAKE"; const BUY_ICE = "BUY_ICECREAMS"; const BUY_JUICE = "BUY_JUICES"; function buyCake() { return { type: BUY_CAKE, info: "first redux action" } } function buyIceCreams() { return { type: BUY_ICE } } function buyJuices() { return { type: BUY_JUICE } } const initialState = { numOfCakes: 10, numOfIceCreams: 50 } const stateForJuice = { numOfJuices: 10 } const reducer = (state = initialState, action) => { switch (action.type) { case BUY_CAKE: return { ... state, numOfCakes: state.numOfCakes - 1 } case BUY_ICE: return { ...state, numOfIceCreams: state.numOfIceCreams - 1 } default: return state } } const juiceReducer = (state = stateForJuice, action) => { switch (action.type) { case BUY_JUICE: return { ... state, numOfJuices: state.numOfJuices - 1 } default: return state } } const rootReducer = combineReducers({ cakeIce: reducer, juice: juiceReducer }) const store = createStore(rootReducer); const unSubscribe = store.subscribe(() => { console.log(store.getState()); }); store.dispatch(buyIceCreams()); store.dispatch(buyCake()); store.dispatch(buyJuices()); unSubscribe();
996f4d7e612fd2fc358539b9068f9e53642f3257
[ "Markdown", "JavaScript" ]
2
Markdown
rajaKumaranraja/startingProjects
c202522bbfb8f460d0763e09b1d9d3f91b95d679
9a0889b6eef710c46835675ef45cda8da3fbb347
refs/heads/master
<file_sep># Resin.io layer for VIA arm boards ## Description This repository enables building resin.io for VIA arm machines. ## Supported machines * vab820-quad <file_sep># # VIA vab820 quad # IMAGE_FSTYPES_append_vab820-quad = " resinos-img" # Customize resinos-img RESIN_IMAGE_BOOTLOADER_vab820-quad = "u-boot-vab820" RESIN_BOOT_PARTITION_FILES_vab820-quad = " \ uImage-vab820-quad.bin:/uImage \ uImage-imx6q-vab820.dtb:/imx6q-vab820.dtb \ " IMAGE_CMD_resinos-img_append_vab820-quad () { # vab820-quad needs uboot written at a specific location dd if=${DEPLOY_DIR_IMAGE}/u-boot-${MACHINE}.imx of=${RESIN_RAW_IMG} conv=notrunc seek=2 bs=512 }
eb533da88d4bdfe283951e0ce704c0e2d8e38a96
[ "Markdown", "PHP" ]
2
Markdown
resin-os/resin-via-arm
cf7a740cbe9861edb035a1379113d3f02f7cf64e
14d9da695f2b3cae0766908690708a752ad44ee3
refs/heads/master
<repo_name>serafettingunes/LoginEkraniYeni<file_sep>/loginEkrani/veriGuncelle.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace loginEkrani { public partial class veriGuncelle : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int x = Convert.ToInt32( Request.QueryString["ID"]); DataSet1TableAdapters.TBLADMINTableAdapter DS = new DataSet1TableAdapters.TBLADMINTableAdapter(); TxtID.Text = x.ToString(); TxtID.Enabled = false; if (Page.IsPostBack==false) { TxtKULLANICI.Text = DS.VeriGetir(Convert.ToInt32(TxtID.Text))[0].KULLANICI; TxtSIFRE.Text = DS.VeriGetir(Convert.ToInt32(TxtID.Text))[0].SIFRE; } } protected void BtnGUNCELLE_Click(object sender, EventArgs e) { DataSet1TableAdapters.TBLADMINTableAdapter ds = new DataSet1TableAdapters.TBLADMINTableAdapter(); ds.GUNCELLEADMIN(TxtKULLANICI.Text,TxtSIFRE.Text, Convert.ToInt32(TxtID.Text)); Response.Redirect("Veriler.aspx"); } } }<file_sep>/loginEkrani/LoginEkrani.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace loginEkrani { public partial class LoginEkrani : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnGiris_Click(object sender, EventArgs e) { SqlConnection cn = new SqlConnection(@"Data Source=DESKTOP-8RHPADE;Initial Catalog=Prıje5ADMIN;Integrated Security=True;"); cn.Open(); SqlCommand cmd = new SqlCommand("select*from TBLADMIN where KULLANICI=@KULADI and SIFRE=@SIFRE ",cn); cmd.Parameters.AddWithValue("@KULADI",txtKulAdi.Text); cmd.Parameters.AddWithValue("@SIFRE",txtSifre.Text); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { Response.Redirect("Veriler.aspx"); } else { Response.Write("Yanlış"); } cn.Close(); } } }<file_sep>/loginEkrani/Veriler.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace loginEkrani { public partial class Veriler : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { DataSet1TableAdapters.TBLADMINTableAdapter A = new DataSet1TableAdapters.TBLADMINTableAdapter(); Repeater1.DataSource = A.adminListele(); Repeater1.DataBind(); } } }
1857f58ca8763bb805403b136f4de222239aa892
[ "C#" ]
3
C#
serafettingunes/LoginEkraniYeni
af3687ac4f9d4fc6cef3764736870f9c3762cd09
a6a61c550f28fe85dfa348db2a52153996a1c886
refs/heads/master
<file_sep><?php define ('TITLE', 'Add Organization | Tracker') ?> <?php require 'includes/header.php' ?> <!-- page header --> <div class="orgContainer py-3 mb-5"> <h3 class="pt-1">Add Organization</h3> </div> <!-- /page header --> <div class="container"> <div class="row"> <div class="col-lg-8 mx-auto"> <!-- add org form --> <form class="" action="#" method="post"> <div class="row"> <!-- first column of form items --> <div class="col"> <input type="text" class="form-control mt-2" placeholder="Organization Name"> <input type="text" class="form-control mt-2" placeholder="Organization Address Line 1"> <input type="text" class="form-control mt-2" placeholder="Organization Address Line 2"> <input type="text" class="form-control mt-2" placeholder="Organization City"> <input type="text" class="form-control mt-2" placeholder="Organization State"> <input type="text" class="form-control mt-2" placeholder="Organization Zip Code"> </div> <!-- /first column of form items --> <!-- second column of form items --> <div class="col"> <input type="text" class="form-control mt-2" placeholder="Phone 1"> <input type="text" class="form-control mt-2" placeholder="Phone 2"> <input type="text" class="form-control mt-2" placeholder="Phone 3"> <input type="text" class="form-control mt-2" placeholder="Email 1"> <input type="text" class="form-control mt-2" placeholder="Email 1"> <input type="text" class="form-control mt-2" placeholder="Email 1"> </div> <!-- /second column of form items --> </div> <!-- org notes field --> <textarea name="orgNotes" class="form-control mt-4" rows="4" placeholder="Organization Notes..."></textarea> <!-- /org notes field --> <!-- submit button --> <button type="button" name="submit" class="btn btn-primary mt-2">Submit</button> <!-- /submit button --> </form> <!-- /add org form --> </div> </div> </div> <!-- add org form --> <?php require 'includes/footer.php' ?><file_sep><!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Font Awesome CDN --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Bootstrap CSS/CDN --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Custom CSS --> <link rel="stylesheet" href="css/styles.css"> <title><?php echo TITLE ?></title> </head> <body> <!-- NAVBAR --> <nav class="navbar navbar-expand-lg navbar-light fixed-top bg-light"> <a class="navbar-brand" href="index.php"><img src="" alt="Logo" class="navbarIcon"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarDefault" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav mr-auto"> <?php require 'includes/nav.php' ?> </ul> <!-- Logout button --> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a href="#" class="nav-link">Button Thing</a> </li> </ul><!-- end logout button --> </div><!-- /#nvbarCollapse This is for the navbar collaps-ability on smaller screens / devices--> </nav><!-- end navbar --> <main role="main"> <file_sep> <!-- Footer --> <footer id="footer-main"> <div class="container"> <div class="row"><!-- This div contains all 12 columns. I can break these up as I need --> <div class="col-sm-3"><!-- This is the first section of the 12 column layout. I am using 3 columns (or 1/4 of the container) --> <p>&copy; <?php echo date('Y'); ?>&nbsp;<NAME>.</p> </div> <!-- end section 1 --> <div class="col-sm-3"><!-- This is the second section of the 12 column layout. I am using 3 columns (or 1/4 of the container) --> <ul class="list-unstyled"> <li><a href="#">Home</a></li> <li><a href="index.php">Organizations</a></li> <li><a href="#">Users</a></li> <li><a href="#">Link 4<a></li> <li><a href="#">Link 5</a></li> </ul> </div> <!-- end section 2 --> <div class="col-sm-3"><!-- This is the third section of the 12 column layout. I am using 3 columns (or 1/4 of the container) --> <ul class="list-unstyled"> <li><a href="">facebook</a></li> <li><a href="">twitter</a></li> <li><a href="">youtube</a></li> <li><a href="">linkedin</a></li> </ul> </div> <!-- end section 3 --> <div class="col-sm-3"><!-- This is the fourth section of the 12 column layout. I am using 3 columns (or 1/4 of the container) --> <h6>A tiny header.</h6> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi incidunt necessitatibus quidem! Ad, aspernatur autem doloribus eius explicabo illum incidunt itaque odio optio porro, provident quae, quas quos rerum sunt.</p> </div> <!-- end section 4 --> </div> </div> </footer> <!-- end footer --> </main><!-- /role main --> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html> <file_sep><?php define ('TITLE', 'Home | Tracker') ?> <?php require 'includes/header.php' ?> <!-- page header --> <div class="orgContainer py-3 mb-5"> <h3 class="pt-1">Organizations</h3> </div> <!-- /page header --> <div class="container"> <div class="row"> <div class="col-lg-10 mx-auto"> <!-- add org button --> <div class="addButtoncontainer"> <a class="btn btn-primary my-2 px-5" href="addOrg.php" role="button">Add</a> </div> <!-- /add org button --> <!-- table for organizations --> <table class="table table-striped table-hover"> <thead class="thead-dark"> <th>Organization</th> <th>Location</th> </thead> <?php // Create connection $conn = new mysqli('localhost', 'root' ,'', 'tracker'); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT ID, orgName, city, state FROM org Order by orgName"; $result = $conn->query($sql); //start while loop to fill table while ($dataRows = $result->fetch_array()) { $id = $dataRows['ID']; $orgName = $dataRows['orgName']; $city = $dataRows['city']; $state = $dataRows['state']; ?> <tbody> <tr> <td><a href="users.php?id=<?php echo htmlentities($id); ?>" class="tableLinks"><?php echo htmlentities($orgName); ?></td> <td><?php echo htmlentities($city).', '.htmlentities($state); ?></td> </tr> </tbody> <?php //end while loop } //close database commection mysqli_close($conn); ?> </table> <!-- /table for organizations --> </div> </div> </div> <?php require 'includes/footer.php' ?>
a0a0ca162477fec0b7f1bfc99a9275afd80991b3
[ "PHP" ]
4
PHP
jegan22280/tracker
aa8b8cdbebd1ad4a773578fc0c3d491e607e5a0b
83d3150d1d90873da48bb31cebdde2ccc356aac3
refs/heads/master
<repo_name>janforys/Miscellaneous<file_sep>/cnc programming/Heidenhain/JF/_INNE/FAZ.H 0 BEGIN PGM FAZ MM 1 BLK FORM 0.1 Z X-10 Y-10 Z-10 2 BLK FORM 0.2 X+10 Y+10 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 R0 FMAX / 7 TOOL CALL 30 Z / 8 TOOL DEF 9 9 ; 10 ; 11 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 12 CYCL DEF 7.0 PUNKT BAZOWY 13 CYCL DEF 7.1 X-70 14 ;--------------------------------------------- 15 ; 16 * - fazy 1x45 (faz-90st) 17 TOOL CALL 27 Z S8000 F500 / 18 STOP 19 TOOL DEF 30 20 L M3 M8 21 ; 22 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-4 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+9.97 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=-1 ;RODZAJ FREZOWANIA 23 ; 24 CALL LBL 1 25 M5 M9 26 ; 27 ;--------------------------------------------- 28 L Z+0 R0 FMAX M91 / 29 L X+260 Y+535 R0 FMAX M91 30 L X+100 Y+365 R0 FMAX 31 L M30 32 * - ----------------------------------------- 33 * - LBL1 FAZA 34 LBL 1 35 M3 36 L X+0 Y+0 R0 FMAX M99 37 LBL 0 38 END PGM FAZ MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/TLOCZYSKO/10,2.h 0 BEGIN PGM 10,2 MM 1 BLK FORM 0.1 Z X-42.5 Y-42.5 Z-5 2 BLK FORM 0.2 X+42.5 Y+42.5 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 * - NAW 8 STOP 9 TOOL CALL 8 Z S600 F30 10 TOOL DEF 16 11 M8 12 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 13 CALL LBL 1 14 M5 M9 15 ; 16 * - W 6.6 HSS 17 TOOL CALL 16 Z S600 F30 / 18 STOP 19 TOOL DEF 12 20 M8 21 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-23.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 22 CALL LBL 1 23 M5 M9 24 ; 25 * - FP 8 ZGR 26 TOOL CALL 12 Z S1800 F150 / 27 STOP 28 TOOL DEF 11 29 M8 30 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-23.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+10.1 ;SREDNICA NOMINALNA ~ Q342=+10 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 31 CALL LBL 1 32 M5 M9 33 ; 34 * - FP 8 WYK 35 TOOL CALL 11 Z S1800 F200 DR-0.045 / 36 STOP 37 TOOL DEF 26 38 M8 39 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-23.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+10.2 ;SREDNICA NOMINALNA ~ Q342=+10 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 40 CALL LBL 1 41 M5 M9 42 ; 43 * - FAZA 44 TOOL CALL 26 Z S600 F30 / 45 STOP 46 TOOL DEF 30 47 M8 48 CYCL DEF 200 WIERCENIE ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-5.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5.1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. <NAME> ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 49 CALL LBL 1 50 M5 M9 51 ; 52 ;--------------------------------------------- 53 L Z-5 R0 FMAX M91 54 L X+260 Y+535 R0 FMAX M91 55 L M30 56 * - ----------------------------------------- 57 * - LBL1 10.2+0.1 58 LBL 1 59 M3 60 L X+0 Y+0 R0 FMAX M99 61 LBL 0 62 END PGM 10,2 MM <file_sep>/cnc programming/Heidenhain/JF/DP/N060.00/OTW1.H 0 BEGIN PGM OTW1 MM 1 BLK FORM 0.1 Z X-100 Y-100 Z-35 2 BLK FORM 0.2 X+100 Y+100 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; / 7 STOP 8 TOOL CALL 3 Z S650 F30 9 TOOL DEF 7 10 M8 M3 11 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 12 CALL LBL 1 13 M5 M9 14 ; 15 TOOL CALL 7 Z S675 F30 16 TOOL DEF 24 17 M8 M3 18 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-21 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 19 CALL LBL 1 20 M5 M9 21 ; 22 TOOL CALL 24 Z S2222 F160 23 TOOL DEF 26 24 M8 M3 25 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-6.55 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.6 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.05 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 26 CALL LBL 1 27 M5 M9 28 ; 29 TOOL CALL 26 Z S675 F30 30 TOOL DEF 25 31 M8 M3 32 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-4.45 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 33 CALL LBL 1 34 M5 M9 35 ; 36 ;--------------------------------------------- 37 L Z-5 R0 FMAX M91 38 L X+260 Y+535 R0 FMAX M91 / 39 L M30 40 CALL LBL 99 41 * - ----------------------------------------- 42 * - LBL1 43 LBL 1 44 M3 45 L X+0 Y+0 R0 FMAX M99 46 L X-86 Y+0 R0 FMAX M99 47 L X+86 Y+0 R0 FMAX M99 48 LBL 0 49 ; 50 LBL 99 51 END PGM OTW1 MM <file_sep>/cnc programming/Heidenhain/JF/KR/N091.00/PODWIERCENIE-6F8.H 0 BEGIN PGM PODWIERCENIE-6F8 MM 1 BLK FORM 0.1 Z X-35 Y-35 Z-15 2 BLK FORM 0.2 X+35 Y+35 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 * - NAW-STAL 8 TOOL CALL 3 Z S650 F30 9 TOOL DEF 14 10 M8 11 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 12 CALL LBL 1 13 M5 M9 14 ; 15 * - W 5.8 HSS 16 TOOL CALL 14 Z S700 F30 17 TOOL DEF 2 18 M8 19 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 CALL LBL 1 21 M5 M9 22 ; 23 ;--------------------------------------------- 24 L Z-5 R0 FMAX M91 25 L X+260 Y+535 R0 FMAX M91 / 26 L M30 27 CALL LBL 99 28 * - ----------------------------------------- 29 * - LBL1 6F8 30 LBL 1 31 M3 32 L X+0 Y-17 R0 FMAX M99 33 LBL 0 34 LBL 99 35 END PGM PODWIERCENIE-6F8 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/M8X075.H 0 BEGIN PGM M8X075 MM 1 BLK FORM 0.1 Z X-60 Y-34 Z-119 2 BLK FORM 0.2 X+60 Y+0 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 TOOL CALL 30 Z S50 6 TOOL DEF 9 7 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+75 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-30 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 8 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 9 CYCL DEF 7.0 PUNKT BAZOWY 10 CYCL DEF 7.1 IZ+0 11 ;--------------------------------------------- 12 ; 13 ; 14 * - NAW 15 TOOL CALL 9 Z S1111 F111 16 TOOL DEF 8 17 M8 18 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 19 CALL LBL 1 20 M5 M9 21 ; 22 * - W 6 23 TOOL CALL 8 Z S1300 F111 24 TOOL DEF 23 25 M8 26 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-44 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 27 CALL LBL 1 28 M5 M9 29 ; 30 * - FI 10 31 TOOL CALL 23 Z S7000 F500 32 TOOL DEF 1 33 M8 34 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.4 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+10 ;SREDNICA NOMINALNA ~ Q342=+6 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 35 CALL LBL 1 36 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.2 ;GLEBOKOSC DOSUWU ~ Q203=-1 ;WSPOLRZEDNE POWIERZ. ~ Q204=+60 ;2-GA BEZPIECZNA WYS. ~ Q335=+7.2 ;SREDNICA NOMINALNA ~ Q342=+6 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 37 CALL LBL 1 38 M5 M9 39 ; 40 * - GW M8X075 41 TOOL CALL 1 Z S150 42 TOOL DEF 30 43 M8 44 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-13 ;GLEBOKOSC GWINTU ~ Q239=+0.75 ;SKOK GWINTU ~ Q203=-1 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 45 CALL LBL 1 46 M5 M9 47 ; 48 ; 49 ;--------------------------------------------- 50 L Z-5 R0 FMAX M91 51 L X+260 Y+535 R0 FMAX M91 52 L M30 53 * - ----------------------------------------- 54 * - LBL1 O 55 LBL 1 56 M3 57 L X+0 Y+0 R0 FMAX M99 58 LBL 0 59 END PGM M8X075 MM <file_sep>/cnc programming/Heidenhain/CHWYT-125.h 1 BEGIN PGM CHWYT-125 MM 1 ; 2 ; 3 Q60 = 185 ; DLUGOSC WALKA 4 ; 5 ; 6 ;-------------------------- 7 ;-------------------------- 8 Q70 = Q60 + 50 ; jazda w X+ 9 Q71 = Q60 / 2 ; polowa dlgsc 10 ;-------------------------- 11 ;-------------------------- 12 BLK FORM 0.1 Z X-100 Y-100 Z-44.5 13 BLK FORM 0.2 X+350 Y+100 Z+1 14 CALL PGM TNC:\REF 15 CALL PGM TNC:\Z19 16 PLANE RESET TURN F3000 17 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO / 18 * - SONDA / 19 TOOL CALL 1 Z S50 20 ; 21 ; X 22 ; / 23 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+0 ;1.PKT POMIAROW 1.OSI ~ Q264=+0 ;1.PKT 2.OSI ~ Q261=-10 ;WYSOKOSC POMIARU ~ Q320=+20 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q272=+1 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=-2 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 24 ; 25 ; Y 26 ; / 27 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+Q71 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+90 ;SZEROKOSC MOSTKA ~ Q272=+2 ;OS POMIAROWA ~ Q261=-20 ;WYSOKOSC POMIARU ~ Q320=+5 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+1 ;PROBKOW. NA OSI TS ~ Q382=+Q71 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 28 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 29 ; 30 * - GL-80 31 TOOL CALL 42 Z S4000 F3000 32 PLANE SPATIAL SPA-90 SPB+0 SPC+90 TURN F5555 SEQ- TABLE ROT 33 Q10 = 1 34 CALL LBL 30 35 M5 36 M9 37 CALL PGM TNC:\Z19 38 CALL PGM TNC:\REF 39 PLANE RESET TURN F5555 40 ; 41 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 42 CYCL DEF 7.0 PUNKT BAZOWY 43 CYCL DEF 7.1 IZ-68.5 44 ; 45 ; 46 * - FP-8 47 TOOL CALL 8 Z S8000 F2500 48 Q50 = 49.22 ; (85.8) 49 CALL LBL 10 50 Q50 = 44.22 ; (93.8) 51 CALL LBL 20 52 M5 53 M9 / 54 STOP / 55 CALL PGM PODWIERTY-125 / 56 STOP 57 ; 58 ; PRESET 4 !!! 59 ; 60 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+4 ;NR PKT BAZOWEGO 61 PLANE RESET TURN F4444 62 TOOL CALL 60 Z S50 63 L X-22 Y+0 R0 FMAX 64 L Z+50 FMAX 65 L Z-20 F2000 66 * - ********** / 67 CALL PGM TNC:\REF 68 CALL PGM TNC:\Z19 69 ; /// 70 CALL LBL 99 71 ; /// 72 M30 73 * - ********** 74 * - LBL 10 - KANALEK 49.22 / 85.8 75 LBL 10 76 L X-10 Y+60 R0 FMAX 77 L Z+100 FMAX 78 L Z+Q50 R0 F4000 M3 M8 79 L Y+42.9 RL F AUTO 80 L X+Q70 81 L Y-42.9 F5000 82 L X-10 F AUTO 83 L Z+100 R0 FMAX 84 LBL 0 85 * - LBL 20 - KANALEK 44.22 / 93.8 86 LBL 20 87 L X-10 Y+60 R0 FMAX 88 L Z+100 FMAX 89 L Z+Q50 R0 F4000 M3 M8 90 L Y+46.9 RL F AUTO 91 L X+Q70 92 L Y-46.9 F5000 93 L X-10 F AUTO 94 L Z+100 R0 FMAX 95 LBL 0 96 ; 97 * - LBL 30 - CZOLO-PLAN 98 LBL 30 99 L X-115 Y+35 R0 FMAX 100 L Z+20 R0 FMAX 101 L Z+Q10 R0 F2000 M3 M8 102 L X+115 R0 F AUTO 103 L Z+20 R0 FMAX 104 LBL 0 105 ; /// 106 LBL 99 107 ; /// 108 END PGM CHWYT-125 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/KS-N100-02-1.h 0 BEGIN PGM KS-N100-02-1 MM 1 BLK FORM 0.1 Z X-55 Y-55 Z-51.5 2 BLK FORM 0.2 X+55 Y+55 Z+1 3 ; 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT ODNIESIENIA 5 ; 6 * - W 5H7 / 7 STOP 8 TOOL CALL 12 Z S6360 F890 9 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-11 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+11 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 10 M8 11 CALL LBL 1 12 M5 M9 13 ; 14 * - W 6 15 TOOL CALL 13 Z S5300 F450 / 16 STOP 17 M8 / 18 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-21 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+21 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE / 19 CALL LBL 6 20 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-34 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+12 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 21 CALL LBL 4 22 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-34 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+12 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 23 CALL LBL 5 24 M5 M9 25 ; 26 * - NAW 8 27 TOOL CALL 10 Z S1200 F120 / 28 STOP 29 M8 30 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 31 CALL LBL 1 32 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 33 CALL LBL 3 34 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.9 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 35 CALL LBL 4 36 M5 M9 37 ; 38 * - W 3.2 39 TOOL CALL 26 Z S2500 F100 40 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 41 M8 42 CALL LBL 3 43 M5 M9 44 ; 45 * - 7.2 pod M8x0.75 46 TOOL CALL 28 Z S1000 F90 47 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-14 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 48 M8 49 CALL LBL 5 50 M5 M9 51 ; 52 * - FAZ 16 53 TOOL CALL 16 Z S1200 F100 54 M8 55 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-4 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 56 CALL LBL 5 57 M5 M9 58 ; 59 * - M8x0.75 60 TOOL CALL 27 Z S150 61 CYCL DEF 207 GWINTOWANIE GS-NOWE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC GWINTU ~ Q239=+0.75 ;SKOK ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 62 M8 63 CALL LBL 5 64 M5 M9 65 ; 66 * - ********** 67 CALL PGM TNC:\REF 68 CALL PGM TNC:\Z19 69 CALL LBL 999 / 70 M30 71 * - ********** 72 * - LBL1 5H7 73 LBL 1 74 M3 75 L X-42.5 Y+0 R0 FMAX M99 76 LBL 0 77 ; 78 * - LBL3 3.2 79 LBL 3 80 M3 81 L X+14.8 Y-2.8 R0 FMAX M99 82 LBL 0 83 ; 84 * - LBL4 6 85 LBL 4 86 M3 87 L X+26 Y-11.5 R0 FMAX M99 88 LBL 0 89 ; 90 * - LBL5 M8X0.75 91 LBL 5 92 M3 93 L X+26 Y+9 R0 FMAX M99 94 LBL 0 95 ; 96 * - LBL6 6 SRODEK 97 LBL 6 98 M3 99 L X+0 Y+0 R0 FMAX M99 100 LBL 0 101 ; 102 LBL 999 103 END PGM KS-N100-02-1 MM <file_sep>/cnc programming/Heidenhain/JF/SP/5580/12/OP2.h 0 BEGIN PGM OP2 MM 1 BLK FORM 0.1 Z X-33 Y-45.3 Z-12 2 BLK FORM 0.2 X+33 Y+0 Z+6 3 ; 4 ; -- BAZA Y NA SZTYWNEJ SZCZECE -- 5 ; -- BAZA X NA SRODKU -- 6 ; -- BAZA Z NA PODKLADZIE (-5.6mm) -- 7 ; 8 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 9 CYCL DEF 7.0 PUNKT BAZOWY 10 CYCL DEF 7.1 IZ+0 11 L X+0 Y+0 FMAX 12 ; 13 * - SONDA / 14 STOP 15 TOOL CALL 30 Z S50 16 TOOL DEF 10 17 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=-27 ;SRODEK W 2-SZEJ OSI ~ Q311=+68 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=+3.5 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 18 ; 19 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 20 ; 21 * - PLAN 5.6 -ZGR 22 TOOL CALL 10 Z S600 F240 23 TOOL DEF 10 24 L Z+300 R0 FMAX M3 M8 25 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+0 ;STRATEGIA ~ Q225=-33 ;PKT.STARTU 1SZEJ OSI ~ Q226=+5 ;PKT.STARTU 2GIEJ OSI ~ Q227=+5.5 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+66 ;DLUG. 1-SZEJ STRONY ~ Q219=-60 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+7 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 26 CYCL CALL 27 L Z+300 R0 FMAX 28 ; 29 * - ZANIZENIE 1.3 -ZGR 30 TOOL CALL 10 Z S600 F240 DL+0 31 TOOL DEF 18 32 L Z+300 R0 FMAX M3 M8 33 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+85 ;DLUG. 1-SZEJ STRONY ~ Q219=+41.7 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0.01 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1.2 ;GLEBOKOSC ~ Q202=+0.6 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.4 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. / 34 L X+0 Y-24.65 R0 FMAX M99 35 L X+0 Y-25.65 R0 FMAX M99 36 L Z+300 R0 FMAX 37 M5 M9 38 ; 39 * - PLAN 5.6 -WYK 40 TOOL CALL 18 Z S2000 F200 41 TOOL DEF 18 42 L Z+300 R0 FMAX M3 M8 43 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-33 ;PKT.STARTU 1SZEJ OSI ~ Q226=+0 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+66 ;DLUG. 1-SZEJ STRONY ~ Q219=-6 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.2 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 44 L X+0 Y+0 R0 FMAX M99 45 L Z+300 R0 FMAX 46 ; 47 * - ZANIZENIE 1.3 -WYK 48 TOOL CALL 18 Z S2000 F180 DL+0.03 DR-0.05 49 TOOL DEF 30 50 L Z+300 R0 FMAX M3 M8 51 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+85 ;DLUG. 1-SZEJ STRONY ~ Q219=+41.7 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0.01 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1.3 ;GLEBOKOSC ~ Q202=+1.3 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.4 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 52 L X+0 Y-25.55 R0 FMAX M99 53 L Z+300 R0 FMAX 54 M5 M9 55 ; 56 ; 57 L Z-5 R0 FMAX M91 58 L X+260 Y+535 R0 FMAX M91 59 M30 60 ; 61 END PGM OP2 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/OTW-WALCOWA.H 0 BEGIN PGM OTW-WALCOWA MM 1 BLK FORM 0.1 Z X-60 Y-34 Z-119 2 BLK FORM 0.2 X+60 Y+0 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 * - FI 11 FP8 8 TOOL CALL 27 Z S9987 F500 9 TOOL DEF 21 10 M8 11 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.6 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+11 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 12 CALL LBL 1 13 M5 M9 14 ; 15 * - W 8 VHM 16 TOOL CALL 21 Z S3975 F795 17 TOOL DEF 27 18 M7 19 CYCL DEF 200 WIERCENIE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-42 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+21 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 CALL LBL 1 21 M5 M9 22 ; 23 * - FI 9 FP8 24 TOOL CALL 27 Z S9987 F500 25 TOOL DEF 5 26 M8 27 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.6 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+9 ;SREDNICA NOMINALNA ~ Q342=+8 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 28 CALL LBL 1 29 M5 M9 30 ; 31 * - GW M10X1 32 TOOL CALL 5 Z S200 33 TOOL DEF 27 34 M8 35 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-14.5 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 36 CALL LBL 1 37 M5 M9 38 ; 39 L A+180 FMAX 40 ; 41 * - FI 11 FP8 42 TOOL CALL 27 Z S9987 F500 43 TOOL DEF 21 44 M8 45 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.6 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+11 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 46 CALL LBL 1 47 M5 M9 48 ; 49 * - W 8 VHM 50 TOOL CALL 21 Z S3975 F795 51 TOOL DEF 27 52 M7 53 CYCL DEF 200 WIERCENIE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-57 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+21 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 54 CALL LBL 1 55 M5 M9 56 ; 57 * - FI 9 FP8 58 TOOL CALL 27 Z S9987 F500 59 TOOL DEF 5 60 M8 61 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.6 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+9 ;SREDNICA NOMINALNA ~ Q342=+8 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 62 CALL LBL 1 63 M5 M9 64 ; 65 * - GW M10X1 66 TOOL CALL 5 Z S200 67 TOOL DEF 27 68 M8 69 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-14.5 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 70 CALL LBL 1 71 M5 M9 72 ; 73 L A+0 FMAX 74 TOOL CALL 0 75 ; 76 ;--------------------------------------------- 77 L Z-5 R0 FMAX M91 78 L X+260 Y+535 R0 FMAX M91 79 L M30 80 * - ----------------------------------------- 81 * - LBL1 O 82 LBL 1 83 M3 84 L X+0 Y+0 R0 FMAX M99 85 LBL 0 86 END PGM OTW-WALCOWA MM <file_sep>/cnc programming/Heidenhain/JF/ZAMEK/ZAMEK-W-PODZIELNICY.h 0 BEGIN PGM ZAMEK-W-PODZIELNICY MM 1 BLK FORM 0.1 Z X+0 Y+0 Z+0 2 BLK FORM 0.2 X+0 Y+0 Z+0 3 ;--------------------------------------------- 4 ; 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 ; 7 * - UWAGA!!! 8 * - BAZA "Z" NA SREDNICY ZEWNETRZNEJ! 9 * - UWAGA!!! 10 ; 11 ;--------------------------------------------- 12 ; / 13 STOP 14 * - FP 5 STAL SPLASZCZENIE POD NAWIERTAK 15 TOOL CALL 20 Z S2600 F40 16 TOOL DEF 14 17 M8 18 L A+38.5 R0 FMAX 19 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 CALL LBL 1 21 ; 22 L A+81.5 R0 FMAX 23 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 24 CALL LBL 1 25 ; 26 L A+158.5 R0 FMAX 27 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 28 CALL LBL 1 29 ; 30 L A+201.5 R0 FMAX 31 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 32 CALL LBL 1 33 ; 34 L A+278.5 R0 FMAX 35 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 36 CALL LBL 1 37 ; 38 L A+321.5 R0 FMAX 39 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 40 CALL LBL 1 41 M5 M9 42 ; 43 * - NAWIERTAK TRASOWANIE 44 TOOL CALL 14 Z S600 F30 45 TOOL DEF 14 46 M8 47 L A+60 R0 FMAX 48 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 49 CALL LBL 2 50 ; 51 L A+180 R0 FMAX 52 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 53 CALL LBL 2 54 ; 55 L A+300 R0 FMAX 56 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 57 CALL LBL 2 58 M5 M9 59 ; 60 * - NAW POD GWINTY 61 TOOL CALL 14 Z S600 F30 62 TOOL DEF 2 63 M8 64 L A+38.5 R0 FMAX 65 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 66 CALL LBL 1 67 ; 68 L A+81.5 R0 FMAX 69 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 70 CALL LBL 1 71 ; 72 L A+158.5 R0 FMAX 73 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 74 CALL LBL 1 75 ; 76 L A+201.5 R0 FMAX 77 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 78 CALL LBL 1 79 ; 80 L A+278.5 R0 FMAX 81 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 82 CALL LBL 1 83 ; 84 L A+321.5 R0 FMAX 85 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 86 CALL LBL 1 87 M5 M9 88 ; 89 * - W 5 HSS 90 TOOL CALL 2 Z S760 F30 91 TOOL DEF 8 92 M8 93 L A+38.5 R0 FMAX 94 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 95 CALL LBL 1 96 ; 97 L A+81.5 R0 FMAX 98 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 99 CALL LBL 1 100 ; 101 L A+158.5 R0 FMAX 102 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 103 CALL LBL 1 104 ; 105 L A+201.5 R0 FMAX 106 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 107 CALL LBL 1 108 ; 109 L A+278.5 R0 FMAX 110 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 111 CALL LBL 1 112 ; 113 L A+321.5 R0 FMAX 114 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 115 CALL LBL 1 116 M5 M9 117 ; 118 * - GW M6 119 TOOL CALL 8 Z S120 120 TOOL DEF 20 121 M8 122 L A+38.5 R0 FMAX 123 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 124 CALL LBL 1 125 ; 126 L A+81.5 R0 FMAX 127 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 128 CALL LBL 1 129 ; 130 L A+158.5 R0 FMAX 131 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 132 CALL LBL 1 133 ; 134 L A+201.5 R0 FMAX 135 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 136 CALL LBL 1 137 ; 138 L A+278.5 R0 FMAX 139 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 140 CALL LBL 1 141 ; 142 L A+321.5 R0 FMAX 143 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 144 CALL LBL 1 145 M5 M9 146 ; 147 ;--------------------------------------------- 148 L Z-5 R0 FMAX M91 149 L X+260 Y+535 R0 FMAX M91 150 ; 151 * - OS "A" WRACA DO USAWIENIA 152 L A+0 R0 FMAX 153 ; 154 L M30 155 * - ----------------------------------------- 156 * - LBL1 M6 157 LBL 1 158 M3 159 L X+7.5 Y+0 R0 FMAX M99 160 LBL 0 161 * - LBL2 TRASOWANIE 162 LBL 2 163 M3 164 L X+4 Y+0 R0 FMAX M99 165 L X+7.5 Y+0 R0 FMAX M99 166 L X+11 Y+0 R0 FMAX M99 167 LBL 0 168 END PGM ZAMEK-W-PODZIELNICY MM <file_sep>/cnc programming/Heidenhain/JF/PODZIALY/przyrz.h 0 BEGIN PGM przyrz MM 1 BLK FORM 0.1 Z X-50 Y+0 Z-6 2 BLK FORM 0.2 X+50 Y+50 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 STOP 7 TOOL CALL 3 Z S700 F30 8 STOP 9 M8 10 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 11 CALL LBL 1 12 CALL LBL 2 13 M5 M9 14 ; 15 * - w-5.8 16 TOOL CALL 14 Z S650 F25 17 STOP 18 M8 19 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-14 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 CALL LBL 1 21 M5 M9 22 ; 23 * - w-6.6 24 TOOL CALL 7 Z S600 F25 25 STOP 26 M8 27 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-34 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 28 CALL LBL 2 29 M5 M9 30 ; 31 * - R 6H7 32 TOOL CALL 24 Z S150 F30 33 STOP 34 M8 35 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-11 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+90 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 36 CALL LBL 1 37 M5 M9 38 ; 39 ; 40 ;--------------------------------------------- 41 L Z-5 R0 FMAX M91 42 L X+260 Y+535 R0 FMAX M91 43 L M30 44 * - ----------------------------------------- 45 * - LBL1 6H7 46 LBL 1 47 M3 48 L X-26.5 Y-26 R0 FMAX M99 49 L X+26.5 Y-26 R0 FMAX M99 50 L X-26.5 Y+26 R0 FMAX M99 51 L X+26.5 Y+26 R0 FMAX M99 52 LBL 0 53 * - LBL2 6.6 54 LBL 2 55 M3 56 L X-34 Y-15 R0 FMAX M99 57 L X+34 Y-15 R0 FMAX M99 58 L X-34 Y+15 R0 FMAX M99 59 L X+34 Y+15 R0 FMAX M99 60 LBL 0 61 END PGM przyrz MM <file_sep>/cnc programming/Heidenhain/JF/AD/PLYTKA-GRN-SUR/GABARYT.H 0 BEGIN PGM GABARYT MM 1 BLK FORM 0.1 Z X-45 Y-25 Z-15 2 BLK FORM 0.2 X+45 Y+25 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 STOP 7 L X+0 Y+0 R0 FMAX 8 ; 9 TOOL CALL 30 Z 10 TOOL DEF 7 11 ; 12 TCH PROBE 411 PKT.BAZ.PROST.ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q323=+90 ;DLUG. 1-SZEJ STRONY ~ Q324=+50 ;DLUG. 2-GIEJ STRONY ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+1 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 13 ; 14 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 15 ; 16 ;--------------------------------------------- 17 ; 18 * - PLANOWANIE-ZGR 19 TOOL CALL 7 Z S1600 F1000 20 TOOL DEF 11 21 M7 M3 22 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+1 ;STRATEGIA ~ Q225=-45 ;PKT.STARTU 1SZEJ OSI ~ Q226=-20 ;PKT.STARTU 2GIEJ OSI ~ Q227=+1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+95 ;DLUG. 1-SZEJ STRONY ~ Q219=+52 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1.2 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 23 CALL LBL 1 24 M5 M9 25 ; 26 * - PLANOWANIE-WYK 27 TOOL CALL 11 Z S3000 F600 28 TOOL DEF 7 29 M8 M3 30 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-45 ;PKT.STARTU 1SZEJ OSI ~ Q226=-20 ;PKT.STARTU 2GIEJ OSI ~ Q227=+1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+95 ;DLUG. 1-SZEJ STRONY ~ Q219=+52 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 31 CALL LBL 1 32 M5 M9 33 ; 34 * - GABARYT-ZGR Z NADDATKIEM 35 TOOL CALL 7 Z S1600 F1000 36 TOOL DEF 1 37 M8 M3 38 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+80.6 ;DLUG. 1-SZEJ STRONY ~ Q424=+87 ;WYMIAR POLWYROBU 1 ~ Q219=+40.6 ;DLUG. 2-GIEJ STRONY ~ Q425=+49 ;WYMIAR POLWYROBU 2 ~ Q220=+0.15 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-11.5 ;GLEBOKOSC ~ Q202=+0.8 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 39 CALL LBL 1 40 M5 M9 41 ; 42 * - GABARYT-WYK Z NADDATKIEM 43 TOOL CALL 1 Z S2700 F600 DR-0.04 44 TOOL DEF 9 45 M7 M3 46 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+80.6 ;DLUG. 1-SZEJ STRONY ~ Q424=+81 ;WYMIAR POLWYROBU 1 ~ Q219=+40.6 ;DLUG. 2-GIEJ STRONY ~ Q425=+41 ;WYMIAR POLWYROBU 2 ~ Q220=+0.15 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-11.5 ;GLEBOKOSC ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 47 CALL LBL 1 48 M5 M9 49 ; 50 * - FAZA CZOP 51 TOOL CALL 9 Z S4000 F200 DR-3 52 TOOL DEF 3 53 M7 M3 54 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+80.6 ;DLUG. 1-SZEJ STRONY ~ Q424=+80.7 ;WYMIAR POLWYROBU 1 ~ Q219=+40.6 ;DLUG. 2-GIEJ STRONY ~ Q425=+40.7 ;WYMIAR POLWYROBU 2 ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-0.8 ;GLEBOKOSC ~ Q202=+2.5 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 55 CALL LBL 1 56 M5 M9 57 ; 58 ;--------------------------------------------- 59 L Z-5 R0 FMAX M91 60 L X+260 Y+535 R0 FMAX M91 61 L M30 62 * - ----------------------------------------- 63 * - LBL1 64 LBL 1 65 M3 66 L X+0 Y+0 R0 FMAX M99 67 LBL 0 68 ; 69 END PGM GABARYT MM <file_sep>/cnc programming/Heidenhain/JF/PODZIALY/WKL-NOZ-ZAN.H 0 BEGIN PGM WKL-NOZ-ZAN MM 1 BLK FORM 0.1 Z X-60 Y-4.5 Z-60 2 BLK FORM 0.2 X+60 Y+4.5 Z+1 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO / 4 STOP 5 TOOL CALL 30 Z 6 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=-3.5 ;SRODEK W 2-SZEJ OSI ~ Q311=+6 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-31 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 7 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 8 CYCL DEF 7.0 PUNKT BAZOWY 9 CYCL DEF 7.1 X+41.6 10 CYCL DEF 7.2 Y+4 11 ; 12 * - PODZIAL NA GOTOWO / 13 STOP 14 TOOL CALL 1 Z S1200 F200 DL-0.04 15 L Z+200 R0 FMAX M3 16 L X-70 Y+0 R0 FMAX 17 L Z+25 R0 FMAX M8 18 L Z+2.5 R0 F AUTO 19 LBL 3 20 L IZ-0.25 21 L X-25 F AUTO 22 L X+25 FMAX 23 L X+70 F AUTO 24 ; 25 L IZ-0.25 26 L X+25 F AUTO 27 L X-25 FMAX 28 L X-70 F AUTO 29 LBL 0 30 CALL LBL 3 REP4 31 L Z+25 R0 FMAX 32 ; 33 * - ZNIZENIA ZGR 34 TOOL CALL 1 Z S1200 F200 DL+0.2 / 35 STOP 36 L Z+200 R0 FMAX M3 37 L X-60.5 Y-13 R0 FMAX 38 L Z+25 R0 FMAX M8 39 L Z+1 R0 F1000 40 LBL 1 41 L IZ-0.5 42 L Y+13 43 L IZ-0.5 44 L Y-13 45 LBL 0 46 CALL LBL 1 REP10 47 L Z+25 R0 FMAX 48 ; 49 TOOL CALL 1 Z S1200 F200 DL+0.2 / 50 STOP 51 L Z+200 R0 FMAX M3 52 L X+60.5 Y-13 R0 FMAX 53 L Z+25 R0 FMAX M8 54 L Z+1 R0 F1000 55 LBL 2 56 L IZ-0.5 57 L Y+13 58 L IZ-0.5 59 L Y-13 60 LBL 0 61 CALL LBL 2 REP10 62 L Z+25 R0 FMAX 63 ; 64 M9 M5 65 ; 66 * - ZNIZENIA WYK FP8 67 TOOL CALL 11 Z S1800 F120 DL+0.1 / 68 STOP 69 L Z+200 R0 FMAX M3 70 L X-58.45 Y-13 R0 FMAX 71 L Z+25 R0 FMAX M8 72 L Z-10 R0 F1000 73 L Y+13 F AUTO 74 L Z+25 R0 FMAX 75 ; 76 L X+58.45 Y-13 R0 FMAX 77 L Z+25 R0 FMAX M8 78 L Z-10 R0 F1000 79 L Y+13 F AUTO 80 L Z+25 R0 FMAX 81 ; 82 M9 M5 83 ; 84 * - ZNIZENIA NA GOTOWO FP8 / 85 STOP 86 TOOL CALL 11 Z S1800 F120 DL+0.045 87 L Z+200 R0 FMAX M3 88 L X-58.45 Y-13 R0 FMAX 89 L Z+25 R0 FMAX M8 90 L Z-10 R0 F1000 91 L Y+13 F AUTO 92 L Z+25 R0 FMAX 93 ; 94 L X+58.45 Y-13 R0 FMAX 95 L Z+25 R0 FMAX M8 96 L Z-10 R0 F1000 97 L Y+13 F AUTO 98 L Z+25 R0 FMAX 99 ; 100 M9 M5 101 ; 102 L Z-5 R0 FMAX M91 103 L X+260 Y+535 R0 FMAX M91 104 M30 105 END PGM WKL-NOZ-ZAN MM <file_sep>/cnc programming/Heidenhain/JF/AD/N021.00/OTW.H 0 BEGIN PGM OTW MM 1 BLK FORM 0.1 Z X-30 Y-25 Z-11 2 BLK FORM 0.2 X+30 Y+25 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IY-11.75 7 ;--------------------------------------------- 8 ; 9 * - NAW 10 TOOL CALL 3 Z S650 F30 11 TOOL DEF 3 12 M8 M3 13 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 14 CALL LBL 1 15 CALL LBL 2 16 M5 M9 17 ; 18 * - 6.4 19 TOOL CALL 22 Z S650 F30 20 TOOL DEF 25 21 M8 M3 22 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 23 CALL LBL 2 24 M5 M9 25 ; 26 * - 5.8 27 TOOL CALL 25 Z S700 F30 28 TOOL DEF 26 29 M8 M3 30 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 31 CALL LBL 1 32 M5 M9 33 ; 34 * - FAZO 35 TOOL CALL 26 Z S700 F30 DL+0.1 36 TOOL DEF 17 37 M8 M3 38 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.05 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.05 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 39 CALL LBL 1 40 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 41 CALL LBL 2 42 M5 M9 43 ; 44 * - R6 45 TOOL CALL 17 Z S150 F30 46 TOOL DEF 30 47 M8 M3 48 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+70 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 49 CALL LBL 1 50 M5 M9 51 ; 52 ; 53 ;--------------------------------------------- 54 L Z-5 R0 FMAX M91 55 L X+260 Y+535 R0 FMAX M91 56 CALL LBL 99 / 57 L M30 58 * - ----------------------------------------- 59 * - LBL1 - 6H7 60 LBL 1 61 M3 M8 62 L X-13 Y+5.5 R0 FMAX M99 63 L X+13 Y+5.5 R0 FMAX M99 64 LBL 0 65 * - LBL2 - 6.4 66 LBL 2 67 M3 M8 68 L X-13 Y+18 R0 FMAX M99 69 L X+13 Y+18 R0 FMAX M99 70 LBL 0 71 ; 72 LBL 99 73 LBL 0 74 ; 75 END PGM OTW MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/PLAN-2.H 0 BEGIN PGM PLAN-2 MM 1 BLK FORM 0.1 Z X-90 Y-50 Z-24 2 BLK FORM 0.2 X+90 Y+50 Z+0 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 CYCL DEF 7.0 PUNKT BAZOWY 5 CYCL DEF 7.1 IZ+0 6 TOOL CALL 27 Z S8000 F2500 7 L Z+300 R0 FMAX M3 M8 8 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-96 ;PKT.STARTU 1SZEJ OSI ~ Q226=-56 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.2 ;PKT.STARTU 3CIEJ OSI ~ Q386=-0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+190 ;DLUG. 1-SZEJ STRONY ~ Q219=+110 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.3 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+3 ;BEZPIECZNA WYSOKOSC ~ Q357=+2 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 9 CYCL CALL 10 L Z+300 R0 FMAX 11 L Y+535 R0 FMAX 12 M30 13 END PGM PLAN-2 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/SPLASZCZENIE-WALEK.H 0 BEGIN PGM SPLASZCZENIE-WALEK MM 1 BLK FORM 0.1 Z X-49.5 Y-100 Z-36 2 BLK FORM 0.2 X+49.5 Y+100 Z+36 3 ;------------------------------------------- 4 ; 5 ;------------------------------------------- 6 ; USTAW BAZE W OSI Y DOKLADNIE PO SRODKU SPLASZCZENIA ( SRODEK MOSTKA ) 7 ; USTAW "Z" W OSI DETALU 8 ; USTAW BAZE W OSI X NA SRODKU DETALU 9 ; WYSUNIECIE NARZEDZIA - 82mm 10 ;------------------------------------------- / 11 STOP 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 L X+0 Y+0 R0 FMAX 14 * - SONDA / 15 STOP 16 TOOL CALL 30 Z S50 17 TOOL DEF 19 18 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=-52 ;SRODEK W 2-SZEJ OSI ~ Q311=+95 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=+15 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+75 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 19 ; 20 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 21 ;------------------------------------------- / 22 STOP 23 ; WPISZ PONIZEJ SZEROKOSC MOSTKA W MIEJSCU SPLASZCZENIA ( W OSI Y ) JAKO~ WARTOSC Q1, ZAOKRAGLAJAC DO DWOCH MIEJSC PO PRZECINKU 24 ; 25 FN 0: Q1 =+94.11 26 ; / 27 STOP 28 * - GLOWICA-20-ALU 29 TOOL CALL 19 Z S15000 F1800 30 TOOL DEF 30 31 M3 M8 32 L X-50 Y+0 FMAX 33 L Z+60 FMAX 34 L Z+30 F1800 35 ; 36 FN 2: Q1 =+Q1 - +1 37 FN 4: Q2 =+Q1 DIV +2 38 FN 2: Q3 =+Q2 - +10 39 ; 40 LBL 1 41 L IZ-1 42 L Y-Q3 FMAX 43 L X-30 Y-Q3 44 RND R4 45 L X-30 Y+Q3 46 RND R4 47 L X-50 48 LBL 0 49 ; 50 CALL LBL 1 REP61 51 ; 52 L Z+60 FMAX 53 L X+50 Y+0 FMAX 54 L Z+30 F1800 55 ; 56 LBL 2 57 L IZ-1 58 L Y-Q3 FMAX 59 L X+30 Y-Q3 60 RND R4 61 L X+30 Y+Q3 62 RND R4 63 L X+50 64 LBL 0 65 ; 66 CALL LBL 2 REP61 67 M5 M9 68 ; 69 ;-------------------------------------- 70 L Z+0 R0 FMAX M91 71 L X+260 Y+535 R0 FMAX M91 72 L M30 73 * - ----------------------------------- 74 END PGM SPLASZCZENIE-WALEK MM <file_sep>/cnc programming/Heidenhain/JF/KR/N091.00/KOLEK-MOC-STR2.H 0 BEGIN PGM KOLEK-MOC-STR2 MM 1 BLK FORM 0.1 Z X-35 Y-35 Z-15 2 BLK FORM 0.2 X+35 Y+35 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IY+17 7 ;--------------------------------------------- 8 ; 9 * - FP-8 10 TOOL CALL 24 Z S2222 F160 11 TOOL DEF 26 12 M8 13 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-10.05 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=-25 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+15.05 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 14 CALL LBL 1 15 M5 M9 16 ; 17 * - FAZO-16 18 TOOL CALL 26 Z S777 F30 19 TOOL DEF 9 20 M8 21 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-31.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 22 CALL LBL 1 23 M5 M9 24 ; 25 * - NAW-8 / 26 TOOL CALL 9 Z S1111 F30 DL+0.05 / 27 TOOL DEF 30 / 28 M8 / 29 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-27 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. / 30 CALL LBL 2 / 31 M5 M9 32 ; 33 ;--------------------------------------------- 34 L Z-5 R0 FMAX M91 35 L X+260 Y+535 R0 FMAX M91 / 36 L M30 37 CALL LBL 99 38 * - ----------------------------------------- 39 * - LBL1 9/15 40 LBL 1 41 M3 42 L X+0 Y+22.5 R0 FMAX M99 43 L X+22.2 Y-3.9 R0 FMAX M99 44 L X-22.2 Y-3.9 R0 FMAX M99 45 LBL 0 46 * - LBL2 6H7 47 LBL 2 48 M3 49 L X-13.23 Y+18.2 R0 FMAX M99 50 LBL 0 51 LBL 99 52 END PGM KOLEK-MOC-STR2 MM <file_sep>/cnc programming/Heidenhain/JF/AD/N031.01/STR-2.H 0 BEGIN PGM STR-2 MM 1 BLK FORM 0.1 Z X-40 Y+0 Z-32 2 BLK FORM 0.2 X+40 Y+22 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IY+0 7 ; 8 STOP 9 L X+0 Y+0 R0 FMAX 10 ; 11 TOOL CALL 30 Z 12 TOOL DEF 24 13 ; 14 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+11 ;SRODEK W 2-SZEJ OSI ~ Q311=+80 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+20 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 15 ; 16 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 17 ;--------------------------------------------- 18 ; 19 * - PLANOWANIE 20 TOOL CALL 24 Z S2222 F160 21 STOP 22 TOOL DEF 18 23 M3 M8 24 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-40 ;PKT.STARTU 1SZEJ OSI ~ Q226=+0 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.15 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+80 ;DLUG. 1-SZEJ STRONY ~ Q219=+22 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.2 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 25 CYCL CALL 26 M5 M9 27 ; 28 * - FI11 29 TOOL CALL 18 Z S2222 F160 30 STOP 31 TOOL DEF 30 32 M3 M8 33 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 34 CALL LBL 1 35 M5 M9 36 ; 37 * - FAZA 38 TOOL CALL 9 Z S2000 F300 DR-3 39 STOP 40 TOOL DEF 26 41 M3 M8 42 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+80 ;DLUG. 1-SZEJ STRONY ~ Q424=+80.1 ;WYMIAR POLWYROBU 1 ~ Q219=+22 ;DLUG. 2-GIEJ STRONY ~ Q425=+22.1 ;WYMIAR POLWYROBU 2 ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1.3 ;GLEBOKOSC ~ Q202=+2.3 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 43 CALL LBL 3 44 M5 M9 45 ; 46 * - FAZO 47 TOOL CALL 26 Z S650 F30 DL+0.1 48 TOOL DEF 30 49 M3 M8 50 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-4.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 51 CALL LBL 1 52 M5 M9 53 ; 54 ;--------------------------------------------- 55 L Z-5 R0 FMAX M91 56 L X+260 Y+535 R0 FMAX M91 57 L M30 58 * - ----------------------------------------- 59 * - LBL1 11/6.4 60 LBL 1 61 M3 62 L X-32.5 Y+6 R0 FMAX M99 63 L X+32.5 Y+6 R0 FMAX M99 64 LBL 0 65 * - LBL3 FAZKA 66 LBL 3 67 M3 68 L X+0 Y+11 R0 FMAX M99 69 LBL 0 70 END PGM STR-2 MM <file_sep>/cnc programming/Heidenhain/JF/ALS/N020.04/POGLEBIENIA-2STR.H 0 BEGIN PGM POGLEBIENIA-2STR MM 1 BLK FORM 0.1 Z X-30.1 Y-0.2 Z-13.8 2 BLK FORM 0.2 X+30.1 Y+26.2 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; / 6 STOP 7 L X+0 Y+0 R0 FMAX 8 TOOL CALL 30 Z 9 TOOL DEF 1 10 ; 11 TCH PROBE 401 OBROT 2 WIERCENIE ~ Q268=+0 ;1.SRODEK 1.OSI ~ Q269=+0 ;1.SRODEK 2.OSI ~ Q270=+25 ;2.SRODEK 1.OSI ~ Q271=+0 ;2.SRODEK 2.OSI ~ Q261=+2 ;WYSOKOSC POMIARU ~ Q260=+35 ;BEZPIECZNA WYSOKOSC ~ Q307=+0 ;USTAW.WST. KATA OBR. ~ Q305=+1 ;NR W TABELI ~ Q402=+0 ;KOMPENSACJA ~ Q337=+0 ;USTAWIC ZERO 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 ; 14 TCH PROBE 412 PKT.BAZ.OKRAG WEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+11 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=+2 ;WYSOKOSC POMIARU ~ Q320=+0 ;BEZPIECZNA WYSOKOSC ~ Q260=+35 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 15 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 16 ;--------------------------------------------- 17 ; 18 * - POGL 17 FP-12 19 TOOL CALL 1 Z S1700 F200 / 20 STOP 21 TOOL DEF 6 22 M8 23 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+8 ;BEZPIECZNA WYSOKOSC ~ Q201=-7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.7 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+17 ;SREDNICA NOMINALNA ~ Q342=+11 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 24 CALL LBL 1 25 M5 M9 26 ; / 27 * - FAZA FAZ-10 VHM / 28 TOOL CALL 6 Z S5500 F400 DR-4 / 29 STOP / 30 TOOL DEF 30 / 31 M8 / 32 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+17.05 ;SREDNICA NOMINALNA ~ Q342=+17 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> / 33 CALL LBL 1 / 34 M5 M9 35 ; / 36 * - FAZY INTERPOLACJA / 37 * - UWAGA! FAZOWNIK MUSI MIEC R=2 W TABE<NAME>! / 38 TOOL CALL 9 Z S1600 F150 / 39 STOP / 40 TOOL DEF 30 / 41 M8 / 42 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+3.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+17 ;SREDNICA NOMINALNA ~ Q342=+15 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> / 43 CALL LBL 1 / 44 M5 M9 45 ; 46 ;--------------------------------------------- 47 L Z-5 R0 FMAX M91 48 L X+260 Y+535 R0 FMAX M91 49 L M30 50 * - ----------------------------------------- 51 * - LBL1 POGLEBIENIA 17X7 52 LBL 1 53 M3 54 L X+0 Y+0 R0 FMAX M99 55 L X+25 Y+0 R0 FMAX M99 56 LBL 0 57 END PGM POGLEBIENIA-2STR MM <file_sep>/cnc programming/Heidenhain/JF/KR/N091.00/KOLEK-MOC-STR1.H 0 BEGIN PGM KOLEK-MOC-STR1 MM 1 BLK FORM 0.1 Z X-35 Y-35 Z-15 2 BLK FORM 0.2 X+35 Y+35 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO / 5 L X+0 Y+0 R0 FMAX / 6 STOP / 7 TOOL CALL 30 Z / 8 TOOL DEF 9 / 9 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+68 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q301=+1 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+1 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=-10 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 10 ; 11 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 12 ;--------------------------------------------- 13 ; 14 ; 15 * - NAW-STAL 16 TOOL CALL 3 Z S650 F30 17 TOOL DEF 14 18 M8 19 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 CALL LBL 2 21 M5 M9 22 ; 23 * - W 5.8 HSS 24 TOOL CALL 14 Z S700 F30 25 TOOL DEF 17 26 M8 27 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 28 CALL LBL 2 29 M5 M9 30 ; 31 * - W 9 VHM 32 TOOL CALL 17 Z S883 F88 33 TOOL DEF 26 34 M7 35 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-14.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+7.25 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 36 CALL LBL 1 37 M5 M9 38 ; 39 * - FAZO-16 40 TOOL CALL 26 Z S777 F30 41 STOP 42 TOOL DEF 6 43 M8 44 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-3.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 45 CALL LBL 1 46 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 47 CALL LBL 2 48 M5 M9 49 ; 50 * - R-6 51 TOOL CALL 6 Z S150 F30 52 TOOL DEF 30 53 M8 54 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-16.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+60 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 55 CALL LBL 2 56 M5 M9 57 ; 58 ;--------------------------------------------- 59 L Z-5 R0 FMAX M91 60 L X+260 Y+535 R0 FMAX M91 / 61 L M30 62 CALL LBL 99 63 * - ----------------------------------------- 64 * - LBL1 9 65 LBL 1 66 M3 67 L X+0 Y+22.5 R0 FMAX M99 68 L X+22.2 Y-3.9 R0 FMAX M99 69 L X-22.2 Y-3.9 R0 FMAX M99 70 LBL 0 71 * - LBL2 6H7 72 LBL 2 73 M3 74 L X+13.23 Y+18.2 R0 FMAX M99 75 LBL 0 76 LBL 99 77 END PGM KOLEK-MOC-STR1 MM <file_sep>/pointers.cpp #include<iostream> using namespace std; int main() { int variable = 8, second = 4; int *pointer; pointer = &variable; cout << "variable = " << variable << "\n read by a pointer = " << *pointer << endl; variable = 10; cout << "variable = "<< variable << "\n read by a pointer = " << *pointer << endl; *pointer = 200; cout << "variable = " << variable << "\n read by a pointer = " << *pointer << endl; pointer = &second; cout << "variable = "<< variable << "\n read by a pointer = " << *pointer << endl; system("pause"); } <file_sep>/cnc programming/Heidenhain/JF/_INNE/KS-WAL-DYS-I-1STR.h 0 BEGIN PGM KS-WAL-DYS-I-1STR MM 1 BLK FORM 0.1 Z X-49.5 Y-49.5 Z-70 2 BLK FORM 0.2 X+49.5 Y+49.5 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 R0 FMAX 7 TOOL CALL 30 Z 8 TOOL DEF 9 9 ; 10 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+99 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-12 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 11 ; 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 ;--------------------------------------------- 14 ; 15 * - NAW 8 16 TOOL CALL 9 Z S1200 F120 17 TOOL DEF 19 18 M8 19 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 CALL LBL 1 21 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.7 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 22 CALL LBL 2 23 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-4 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 24 CALL LBL 3 25 M5 M9 26 ; 27 * - W-3 28 TOOL CALL 19 Z S2650 F100 29 TOOL DEF 25 30 M8 31 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-8.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 32 CALL LBL 1 33 M5 M9 34 ; 35 * - W-6.6 36 TOOL CALL 25 Z S1350 F120 37 TOOL DEF 22 38 M8 39 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 40 CALL LBL 2 41 M5 M9 42 ; 43 * - W-8 44 TOOL CALL 22 Z S1000 F100 45 TOOL DEF 30 46 M8 47 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-128 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 48 CALL LBL 3 49 M5 M9 50 ; 51 ;--------------------------------------------- 52 L Z+0 R0 FMAX M91 / 53 L X+260 Y+535 R0 FMAX M91 54 L X+100 Y+365 R0 FMAX 55 L M30 56 * - ----------------------------------------- 57 * - LBL1 3 58 LBL 1 59 M3 60 L X+20 Y+0 R0 FMAX M99 61 LBL 0 62 * - LBL2 6.6 63 LBL 2 64 M3 65 L X-13.1 Y+40.4 R0 FMAX M99 66 L X+34.4 Y+25 R0 FMAX M99 67 L X+34.4 Y-25 R0 FMAX M99 68 L X-13.1 Y-40.4 R0 FMAX M99 69 L X-42.5 Y+0 R0 FMAX M99 70 LBL 0 71 * - LBL3 8 72 LBL 3 73 M3 74 L X+0 Y+11 R0 FMAX M99 75 L X+0 Y-11 R0 FMAX M99 76 LBL 0 77 END PGM KS-WAL-DYS-I-1STR MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/RPi4B/plan-2.h 0 BEGIN PGM plan-2 MM 1 BLK FORM 0.1 Z X-32.5 Y-15 Z-18 2 BLK FORM 0.2 X+32.5 Y+15 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 STOP 7 ; 8 * - TOR -PLAN 9 TOOL CALL 13 Z S2000 F800 10 STOP 11 M8 12 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+1 ;STRATEGIA ~ Q225=-85 ;PKT.STARTU 1SZEJ OSI ~ Q226=-85 ;PKT.STARTU 2GIEJ OSI ~ Q227=+6 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+75 ;DLUG. 1-SZEJ STRONY ~ Q219=+35 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 13 CALL LBL 2 14 M5 M9 15 ; 16 * - FP-12 -PLAN 17 TOOL CALL 27 Z S9987 F800 18 STOP 19 M8 20 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-35 ;PKT.STARTU 1SZEJ OSI ~ Q226=-16 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+75 ;DLUG. 1-SZEJ STRONY ~ Q219=+35 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 21 CALL LBL 2 22 M5 M9 23 ; 24 * - NAW -FAZA GAB 25 TOOL CALL 9 Z S5000 F700 DL-0.6 DR-3 26 STOP 27 ; POPRAW BAZE 28 M8 29 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+65 ;DLUG. 1-SZEJ STRONY ~ Q424=+65.1 ;WYMIAR POLWYROBU 1 ~ Q219=+30 ;DLUG. 2-GIEJ STRONY ~ Q425=+30.1 ;WYMIAR POLWYROBU 2 ~ Q220=+3.5 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-0.4 ;GLEBOKOSC ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 30 CALL LBL 2 31 M5 M9 32 ; 33 ;--------------------------------------------- 34 L Z-5 R0 FMAX M91 35 L X+260 Y+535 R0 FMAX M91 36 L M30 37 * - ----------------------------------------- 38 * - LBL1 GW/OTW 39 LBL 1 40 M3 41 L X-29 Y+11.5 R0 FMAX M99 42 L X+29 Y+11.5 R0 FMAX M99 43 L X-29 Y-11.5 R0 FMAX M99 44 L X+29 Y-11.5 R0 FMAX M99 45 LBL 0 46 * - LBL2 SRODEK 47 LBL 2 48 M3 49 L X+0 Y+0 R0 FMAX M99 50 LBL 0 51 END PGM plan-2 MM <file_sep>/cnc programming/Heidenhain/JF/KR/N091.00/SONDA-6H7.H 0 BEGIN PGM SONDA-6H7 MM 1 BLK FORM 0.1 Z X-35 Y-35 Z-15 2 BLK FORM 0.2 X+35 Y+35 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IY+17 7 L X+0 Y+0 R0 FMAX 8 TOOL CALL 30 Z 9 TOOL DEF 9 10 TCH PROBE 412 PKT.BAZ.OKRAG WEWN. ~ Q321=-13.23 ;SRODEK W 1-SZEJ OSI ~ Q322=+18.2 ;SRODEK W 2-SZEJ OSI ~ Q262=+6 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-29 ;WYSOKOSC POMIARU ~ Q320=+5 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+2 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 11 ; 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+2 ;NR PKT BAZOWEGO 13 ;--------------------------------------------- 14 ; / 15 STOP 16 CALL PGM TNC:\5646-KR\N091.00\6H7-FAZA.H 17 ; 18 ;--------------------------------------------- 19 L Z-5 R0 FMAX M91 20 L X+260 Y+535 R0 FMAX M91 / 21 L M30 22 * - ----------------------------------------- 23 END PGM SONDA-6H7 MM <file_sep>/cnc programming/Heidenhain/JF/KS/KS-N100.02/KS-N100-02-2.H 0 BEGIN PGM KS-N100-02-2 MM 1 BLK FORM 0.1 Z X-60 Y-60 Z-60 2 BLK FORM 0.2 X+60 Y+60 Z+1 3 ; 4 ;=================================== 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 L X+0 Y+0 FMAX 7 ; 8 TOOL CALL 30 Z S50 9 TOOL DEF 26 10 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+109 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-10 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 11 ; 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 ;=================================== 14 ; 15 * - FAZ-16 16 TOOL CALL 26 Z S1200 F100 17 TOOL DEF 1 18 M8 M3 19 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 CALL LBL 1 21 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-4.65 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 22 CALL LBL 2 23 M5 M9 24 ; 25 * - W-6.3 26 TOOL CALL 1 Z S1300 F120 27 TOOL DEF 14 28 M3 M8 29 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-20 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.<NAME> ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 30 CALL LBL 1 31 M5 M9 32 ; 33 * - W-3.3 34 TOOL CALL 14 Z S2450 F120 35 TOOL DEF 29 36 M3 M8 37 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-19 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 38 CALL LBL 2 39 M5 M9 40 ; 41 * - FP-8 42 TOOL CALL 29 Z S5000 F350 43 TOOL DEF 27 44 M8 M3 45 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.8 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.05 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 46 CALL LBL 3 47 M5 M9 48 ; 49 * - GW EG-M6 50 TOOL CALL 27 Z S150 51 TOOL DEF 28 52 M13 53 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-16.5 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 54 CALL LBL 1 55 ; 56 * - GW M4 57 TOOL CALL 28 Z S100 58 TOOL DEF 26 59 M13 60 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC GWINTU ~ Q239=+0.7 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 61 CALL LBL 2 62 ; 63 * - FAZY NA fi11 64 TOOL CALL 26 Z S1200 F120 65 TOOL DEF 30 66 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-5.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+6 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 67 CALL LBL 3 68 M8 69 M5 M9 70 ; 71 * - -------------------- 72 ; 73 L Z+0 R0 FMAX M91 74 L X+460 Y+535 R0 FMAX M91 75 CALL LBL 999 76 L M30 77 ; 78 * - -------------------- 79 ; 80 * - LBL1 HC-M6 81 LBL 1 82 M3 83 L X+0 Y+36 FMAX M99 84 L X+0 Y-36 FMAX M99 85 LBL 0 86 ; 87 * - LBL2 M4 88 LBL 2 89 M3 90 L X+28.5 Y+0 FMAX M99 91 LBL 0 92 ; 93 * - LBL3 6.6/11 94 LBL 3 95 M3 96 L X+34.4 Y+25 R0 FMAX M99 97 L X-13.1 Y+40.4 R0 FMAX M99 98 L X-42.5 Y+0 R0 FMAX M99 99 L X-13.1 Y-40.4 R0 FMAX M99 100 L X+34.4 Y-25 R0 FMAX M99 101 LBL 0 102 LBL 999 103 END PGM KS-N100-02-2 MM <file_sep>/cnc programming/Heidenhain/JF/SP/5580/12/op1.h 0 BEGIN PGM op1 MM 1 BLK FORM 0.1 Z X-30 Y-24 Z-12 2 BLK FORM 0.2 X+30 Y+24 Z+1 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 CYCL DEF 7.0 PUNKT BAZOWY 5 CYCL DEF 7.1 IZ+0 6 ;plan / 7 STOP 8 TOOL CALL 18 Z S2000 F200 9 L Z+300 R0 FMAX M3 M8 10 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-33 ;PKT.STARTU 1SZEJ OSI ~ Q226=+24 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.2 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+65 ;DLUG. 1-SZEJ STRONY ~ Q219=-50 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q357=+2 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 11 CYCL CALL 12 L Z+300 R0 FMAX 13 ;gab-WYK / 14 STOP 15 TOOL CALL 18 Z S2000 F200 DR-0.02 16 L Z+300 R0 FMAX M3 M8 17 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+58.6 ;DLUG. 1-SZEJ STRONY ~ Q424=+66 ;WYMIAR POLWYROBU 1 ~ Q219=+45.2 ;DLUG. 2-GIEJ STRONY ~ Q425=+52 ;WYMIAR POLWYROBU 2 ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-6.5 ;GLEBOKOSC ~ Q202=+3.5 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 18 L X+0 Y+0 R0 FMAX M99 19 L Z+300 R0 FMAX / 20 STOP 21 TOOL CALL 18 Z S2000 F180 22 L Z+300 R0 FMAX M3 M8 23 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;<NAME> ~ Q218=+67 ;DLUG. 1-SZEJ STRONY ~ Q219=+11.4 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0.01 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1.6 ;GLEBOKOSC ~ Q202=+0.5 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.4 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 24 L X+0 Y+22.6 R0 FMAX M99 25 L Z+300 R0 FMAX 26 M5 M9 / 27 L Z+300 R0 FMAX / 28 L Y+280 X+0 R0 FMAX 29 L Z-5 R0 FMAX M91 30 L X+260 Y+535 R0 FMAX M91 31 M30 32 END PGM op1 MM <file_sep>/cnc programming/Heidenhain/KR_N10103-1STR.h 0 BEGIN PGM KR_N10103-1STR MM 1 BLK FORM 0.1 Z X-50 Y-50 Z-47.2 2 BLK FORM 0.2 X+50 Y+50 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; / 6 STOP 7 L X+0 Y+0 R0 FMAX 8 TOOL CALL 30 Z 9 TOOL DEF 9 10 ; 11 TCH PROBE 412 PKT.BAZ.OKRAG WEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+68 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-2 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+10 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 12 ; 13 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 14 ;--------------------------------------------- 15 ; / 16 STOP 17 * - NAW 8 18 TOOL CALL 9 Z S1200 F120 19 TOOL DEF 17 20 M8 21 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3.1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-9.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 22 CALL LBL 1 23 CALL LBL 2 24 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 25 CALL LBL 3 26 M5 M9 27 ; 28 * - W 5.8 29 TOOL CALL 17 Z S1300 F100 / 30 STOP 31 TOOL DEF 21 32 M8 33 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-9.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 34 CALL LBL 1 35 M5 M9 36 ; 37 * - W 6.8 38 TOOL CALL 21 Z S1300 F100 / 39 STOP 40 TOOL DEF 25 41 M8 42 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-21 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-9.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 43 CALL LBL 2 44 M5 M9 45 ; 46 * - W 6.6 UWAGA NA PODKLADY 47 TOOL CALL 25 Z S1200 F100 / 48 STOP 49 TOOL DEF 20 50 M8 51 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-34 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 52 CALL LBL 3 53 M5 M9 54 ; 55 * - W 8 VHM WSTEPNIE POD 11.8 56 TOOL CALL 20 Z S3975 F795 / 57 STOP 58 TOOL DEF 29 59 M8 60 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-25 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+25 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 61 CALL LBL 4 62 M5 M9 63 ; 64 * - FP 8 65 TOOL CALL 29 Z S9987 F600 / 66 STOP 67 TOOL DEF 26 68 M8 69 ; POGLEBIENIA 70 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.8 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+13.05 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;RODZAJ FREZOWANIA 71 CALL LBL 3 72 ; 73 ; 11.8 74 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.8 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.85 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 75 CALL LBL 4 76 M5 M9 77 ; 78 * - NAW 16 FAZY 79 TOOL CALL 26 Z S1200 F120 / 80 STOP 81 TOOL DEF 12 82 M8 83 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-4.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+4.1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. <NAME> ~ Q203=-9.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 84 CALL LBL 2 85 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-6.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+6.6 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 86 CALL LBL 3 87 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-6.7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+6.7 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 88 CALL LBL 4 89 M5 M9 90 ; 91 * - R 6H7 92 TOOL CALL 12 Z S150 F30 / 93 STOP 94 TOOL DEF 27 95 M8 96 CYCL DEF 201 ROZWIERCANIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+90 ;POSUW RUCHU POWROTN. ~ Q203=-9.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 97 CALL LBL 1 98 M5 M9 99 ; 100 * - GW M8 101 TOOL CALL 27 Z S150 / 102 STOP 103 TOOL DEF 3 104 M8 105 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-19 ;GLEBOKOSC GWINTU ~ Q239=+1.25 ;SKOK GWINTU ~ Q203=-9.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 106 CALL LBL 2 107 M5 M9 108 ; 109 * - GW 1/4 110 TOOL CALL 3 Z S120 / 111 STOP 112 TOOL DEF 30 113 M8 114 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1.337 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 115 CALL LBL 4 116 M5 M9 117 ; 118 ;--------------------------------------------- 119 L Z-5 R0 FMAX M91 120 L X+460 Y+535 R0 FMAX M91 121 L M30 122 * - ----------------------------------------- 123 * - LBL1 6H7 124 LBL 1 125 M3 126 L X-13.23 Y+18.2 R0 FMAX M99 127 LBL 0 128 * - LBL2 GW M8 129 LBL 2 130 M3 131 L X+0 Y+22.5 R0 FMAX M99 132 L X+22.2 Y-3.9 R0 FMAX M99 133 L X-22.2 Y-3.9 R0 FMAX M99 134 LBL 0 135 * - LBL3 6.6/13 136 LBL 3 137 M3 138 L X+0 Y-50 R0 FMAX M99 139 L X-47.6 Y-15.5 R0 FMAX M99 140 L X-29.4 Y+40.5 R0 FMAX M99 141 L X+29.4 Y+40.5 R0 FMAX M99 142 L X+47.6 Y-15.5 R0 FMAX M99 143 LBL 0 144 * - LBL4 GW 1/4 145 LBL 4 146 M3 147 L X-37.5 Y-35 R0 FMAX M99 148 L X-43.3 Y+25 R0 FMAX M99 149 L X+43.3 Y+25 R0 FMAX M99 150 L X+37.5 Y-35 R0 FMAX M99 151 LBL 0 152 END PGM KR_N10103-1STR MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/WALEK-OBROTY-MAHO.H 0 BEGIN PGM WALEK-OBROTY-MAHO MM 1 BLK FORM 0.1 Z X-50 Y-50 Z-70 2 BLK FORM 0.2 X+50 Y+50 Z+0 3 CALL PGM TNC:\Z19 4 CALL PGM TNC:\REF 5 ; 6 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 7 PLANE RESET TURN F2500 8 CYCL DEF 19.0 PLASZCZ.ROBOCZA 9 CYCL DEF 19.1 A+90 B+0 C-90 10 L B+Q121 C+Q122 R0 FMAX M126 11 STOP 12 ;--------------------------------- 13 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 14 ;--------------------------------- 15 ; 16 * - W 6.6 VHM 17 TOOL CALL 29 Z S4818 F829 18 M8 M3 19 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+16 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 20 CALL LBL 3 21 M5 M9 22 ; 23 * - W 5H7 VHM 24 TOOL CALL 5 Z S6360 F890 25 M8 M3 26 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+8 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 27 CALL LBL 4 28 M5 M9 29 ; 30 * - NAW 31 TOOL CALL 10 Z S1200 F120 32 M8 M3 33 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.8 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 34 CALL LBL 1 35 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 36 CALL LBL 2 37 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.4 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3.4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 38 CALL LBL 3 39 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.6 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 40 CALL LBL 4 41 M5 M9 42 ; 43 * - W 3.2 44 TOOL CALL 23 Z S2500 F100 45 M8 M3 46 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 47 CALL LBL 2 48 M5 M9 49 ; 50 * - W 6 51 TOOL CALL 26 Z S1400 F110 52 M8 M3 53 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-75 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 54 CALL LBL 1 55 M5 M9 56 ; 57 ;--------------------------------- 58 CALL PGM TNC:\REF 59 CALL PGM TNC:\Z19 60 CALL LBL 99 61 L M30 62 * - ------------------------------ 63 * - LBL1 6 64 LBL 1 65 M3 66 L X+26.1 Y-11.5 R0 FMAX M99 67 LBL 0 68 * - LBL2 3.2 69 LBL 2 70 M3 71 L X+14.8 Y-2.8 R0 FMAX M99 72 LBL 0 73 * - LBL3 6.6 74 LBL 3 75 M3 76 L X-13.1 Y-40.4 R0 FMAX M99 77 L X-42.5 Y+0 R0 FMAX M99 78 L X-13.1 Y+40.4 R0 FMAX M99 79 L X+34.4 Y+25 R0 FMAX M99 80 L X+34.4 Y-25 R0 FMAX M99 81 LBL 0 82 * - LBL4 5H7 83 LBL 4 84 M3 85 L X+0 Y-42.5 R0 FMAX M99 86 LBL 0 87 LBL 99 88 END PGM WALEK-OBROTY-MAHO MM <file_sep>/cnc programming/Heidenhain/JF/SD/DYSTANS/SD-N10203A-DYST-1.H 0 BEGIN PGM SD-N10203A-DYST-1 MM 1 BLK FORM 0.1 Z X-60 Y-60 Z-34 2 BLK FORM 0.2 X+60 Y+60 Z+0 3 ; 4 ;--------------------------------------------- 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 ; 7 L X+0 Y+0 FMAX 8 STOP 9 TOOL CALL 30 Z S50 10 TOOL DEF 20 11 ; 12 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+56 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 13 ; 14 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 15 ;--------------------------------------------- 16 ; 17 * - FI8 18 TOOL CALL 17 Z S3975 F795 19 STOP 20 TOOL DEF 9 21 M13 22 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-24 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+24 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 23 CALL LBL 2 24 M5 M9 25 ; 26 * - FAZY (NAW MAX 10) 27 TOOL CALL 9 Z S1200 F120 28 STOP 29 TOOL DEF 17 30 M8 31 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-9 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 32 CALL LBL 1 33 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3.3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-9 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 34 CALL LBL 3 35 M5 M9 36 ; 37 * - 6.6 38 TOOL CALL 25 Z S987 F97 39 STOP 40 TOOL DEF 14 41 M13 42 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-24 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-9 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 43 CALL LBL 3 44 M5 M9 45 ; 46 * - 4.8 47 TOOL CALL 17 Z S1600 F120 48 STOP 49 TOOL DEF 6 50 M8 51 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-9.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-9 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 52 CALL LBL 1 53 M5 M9 54 ; 55 * - R 5H7 ANOD 56 TOOL CALL 6 Z S250 F50 57 STOP 58 TOOL DEF 30 59 M8 60 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+150 ;POSUW RUCHU POWROTN. ~ Q203=-9 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 61 CALL LBL 1 62 M5 M9 63 ; 64 ;--------------------------------------------- 65 L Z-5 R0 FMAX M91 66 L X+260 Y+535 R0 FMAX M91 67 L M30 68 * - ----------------------------------------- 69 ; 70 * - LBL1 5H7 71 LBL 1 72 L M3 73 L X+35 Y+0 FMAX M99 74 LBL 0 75 ; 76 * - LBL2 FI8 77 LBL 2 78 L M3 79 L X-14.1 Y+14.1 FMAX M99 80 L X+14.1 Y+14.1 FMAX M99 81 LBL 0 82 ; 83 * - LBL3 6.6 84 LBL 3 85 L M3 86 L X-12 Y+32.9 FMAX M99 87 L X+32.9 Y+12 FMAX M99 88 L X+12 Y-32.9 FMAX M99 89 L X-32.9 Y-12 FMAX M99 90 LBL 0 91 ; 92 END PGM SD-N10203A-DYST-1 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/RPi/RPI-BASE.H 0 BEGIN PGM RPI-BASE MM 1 BLK FORM 0.1 Z X-32.5 Y-15 Z-18 2 BLK FORM 0.2 X+32.5 Y+15 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 STOP 7 ; 8 * - FP-8 -PLAN 9 TOOL CALL 28 Z S9987 F700 10 STOP 11 M8 12 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-35 ;PKT.STARTU 1SZEJ OSI ~ Q226=-16 ;PKT.STARTU 2GIEJ OSI ~ Q227=+1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+75 ;DLUG. 1-SZEJ STRONY ~ Q219=+35 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;<NAME> ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 13 CALL LBL 2 14 M5 M9 15 ; 16 * - FP-12 -GAB 17 TOOL CALL 28 Z S9987 F650 18 STOP 19 M8 20 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+65 ;DLUG. 1-SZEJ STRONY ~ Q424=+70 ;WYMIAR POLWYROBU 1 ~ Q219=+30 ;DLUG. 2-GIEJ STRONY ~ Q425=+37 ;WYMIAR POLWYROBU 2 ~ Q220=+3.5 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-14.4 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 21 CALL LBL 2 22 M5 M9 23 ; 24 * - FP-12 -GAB WYK 25 TOOL CALL 28 Z S9987 F700 DR-0.02 26 STOP 27 M8 28 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+65 ;DLUG. 1-SZEJ STRONY ~ Q424=+70 ;WYMIAR POLWYROBU 1 ~ Q219=+30 ;DLUG. 2-GIEJ STRONY ~ Q425=+37 ;WYMIAR POLWYROBU 2 ~ Q220=+3.5 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-14.4 ;GLEBOKOSC ~ Q202=+14.4 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 29 CALL LBL 2 30 M5 M9 31 ; 32 * - NAW 33 TOOL CALL 9 Z S1111 F111 34 STOP 35 M8 36 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 37 CALL LBL 1 38 M5 M9 39 ; 40 * - W2.5 41 TOOL CALL 3 Z S2800 F100 42 STOP 43 TOOL DEF 23 44 M8 45 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-23 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 46 CALL LBL 1 47 M5 M9 48 ; 49 * - M3 50 TOOL CALL 5 Z S100 51 STOP 52 TOOL DEF 23 53 M8 54 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+3 ;BEZPIECZNA WYSOKOSC ~ Q201=-6 ;GLEBOKOSC GWINTU ~ Q239=+0.5 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 55 CALL LBL 1 56 M5 M9 57 ; 58 * - FP-12 -WYSPY 59 TOOL CALL 28 Z S9987 F400 DL+0.2 60 STOP 61 M8 62 CYCL DEF 257 CZOP OKRAGLY ~ Q223=+6 ;SRED.WYBR.OBR.NA GOT ~ Q222=+7 ;SREDNICA WST.OBR.WYB ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-4 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q206=+250 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q376=-1 ;KAT POCZATKOWY 63 CALL LBL 1 64 M5 M9 65 ; 66 * - FP-12 -WYBRANIE 67 TOOL CALL 28 Z S9987 F600 DL+0.2 68 STOP 69 M8 70 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;<NAME> ~ Q218=+45 ;DLUG. 1-SZEJ STRONY ~ Q219=+45 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-4 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+250 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 71 CALL LBL 2 72 M5 M9 73 ; 74 * - FP-12 -WYSPY 75 TOOL CALL 28 Z S9987 F400 DL-0.05 76 STOP 77 M8 78 CYCL DEF 257 CZOP OKRAGLY ~ Q223=+6 ;SRED.WYBR.OBR.NA GOT ~ Q222=+7 ;SREDNICA WST.OBR.WYB ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;<NAME>IA ~ Q201=-4 ;GLEBOKOSC ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q206=+250 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q376=-1 ;KAT POCZATKOWY 79 CALL LBL 1 80 M5 M9 81 ; 82 * - FP-12 -WYBRANIE 83 TOOL CALL 28 Z S9987 F600 DL-0.05 84 STOP 85 M8 86 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;<NAME> ~ Q218=+45 ;DLUG. 1-SZEJ STRONY ~ Q219=+45 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-4 ;GLEBOKOSC ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+250 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 87 CALL LBL 2 88 M5 M9 89 ; 90 * - FAZY 91 TOOL CALL 9 Z S5000 F400 DL-0.5 DR-3 92 STOP 93 M8 M3 94 L X-29 Y+11.5 R0 FMAX 95 CYCL DEF 257 CZOP OKRAGLY ~ Q223=+6 ;SRED.WYBR.OBR.NA GOT ~ Q222=+6.1 ;SREDNICA WST.OBR.WYB ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-0.4 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q376=-1 ;KAT POCZATKOWY 96 CYCL CALL 97 L X+29 Y+11.5 R0 FMAX 98 CYCL CALL 99 L X-29 Y-11.5 R0 FMAX 100 CYCL CALL 101 L X+29 Y-11.5 R0 FMAX 102 CYCL CALL 103 M5 M9 104 ; 105 * - KULA 1 DLA WIERZCHOLKA 106 TOOL CALL 2 Z S9987 F50 DL-0.05 107 STOP 108 M3 M8 109 L X-10.5 Y-2 R0 FMAX 110 CYCL DEF 225 GRAWEROWANIE ~ QS500="RPi-Zero" ;TEKST GRAWER. ~ Q513=+4.3 ;WYSOK.ZNAKU ~ Q514=+0.7 ;WSPOL.ODSTEPU ~ Q515=+0 ;FONT ~ Q516=+0 ;UKLAD TEKSTU ~ Q374=+0 ;KAT OBROTU ~ Q517=+50 ;PROMIEN OKREGU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q201=-0.06 ;GLEBOKOSC ~ Q206=+20 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=-4 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 111 CYCL CALL 112 M5 M9 113 ; 114 ;--------------------------------------------- 115 L Z-5 R0 FMAX M91 116 L X+260 Y+535 R0 FMAX M91 117 L M30 118 * - ----------------------------------------- 119 * - LBL1 GW/OTW 120 LBL 1 121 M3 122 L X-29 Y+11.5 R0 FMAX M99 123 L X+29 Y+11.5 R0 FMAX M99 124 L X-29 Y-11.5 R0 FMAX M99 125 L X+29 Y-11.5 R0 FMAX M99 126 LBL 0 127 * - LBL2 SRODEK 128 LBL 2 129 M3 130 L X+0 Y+0 R0 FMAX M99 131 LBL 0 132 END PGM RPI-BASE MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/M10.H 0 BEGIN PGM M10 MM 1 BLK FORM 0.1 Z X-60 Y-34 Z-119 2 BLK FORM 0.2 X+60 Y+0 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IZ+57 7 ;--------------------------------------------- 8 ; 9 L A+45 FMAX 10 CALL LBL 2 11 ; 12 L A+135 FMAX 13 CALL LBL 2 14 ; 15 TOOL CALL 9 16 L X-15 Y+6.5 FMAX 17 L A+0 FMAX 18 M30 19 ; 20 LBL 2 21 * - NAW 22 TOOL CALL 9 Z S1111 F111 23 TOOL DEF 21 24 M8 25 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 26 CALL LBL 1 27 M5 M9 28 ; 29 * - W 8 30 TOOL CALL 21 Z S1111 F111 31 TOOL DEF 27 32 M8 33 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-43 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 34 CALL LBL 1 35 M5 M9 36 ; 37 * - FI 11 FP8 38 TOOL CALL 27 Z S9987 F500 39 TOOL DEF 9 40 M8 41 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-4 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.95 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;RODZAJ FREZOWANIA 42 CALL LBL 1 / 43 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.2 ;GLEBOKOSC DOSUWU ~ Q203=-4 ;WSPOLRZEDNE POWIERZ. ~ Q204=+60 ;2-GA BEZPIECZNA WYS. ~ Q335=+9 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> / 44 CALL LBL 1 45 M5 M9 46 LBL 0 47 ; / 48 * - GW M10X1 / 49 TOOL CALL 13 Z S200 / 50 TOOL DEF 27 / 51 M8 / 52 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-11.5 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=-4 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. / 53 CALL LBL 1 / 54 M5 M9 55 ; 56 ; 57 ;--------------------------------------------- 58 L Z-5 R0 FMAX M91 59 L X+260 Y+535 R0 FMAX M91 60 L M30 61 * - ----------------------------------------- 62 * - LBL1 O 63 LBL 1 64 M3 65 L X+0 Y+0 R0 FMAX M99 66 LBL 0 67 END PGM M10 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/SCIECIA.H 0 BEGIN PGM SCIECIA MM 1 BLK FORM 0.1 Z X-60 Y+0 Z-60 2 BLK FORM 0.2 X+60 Y+26 Z+1 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 CYCL DEF 7.0 PUNKT BAZOWY 5 CYCL DEF 7.1 IZ+35 6 ; 7 STOP 8 TOOL CALL 30 Z S50 9 TOOL DEF 27 10 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+4.5 ;SRODEK W 2-SZEJ OSI ~ Q311=+100 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=+30 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+100 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 11 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 12 CYCL DEF 7.0 PUNKT BAZOWY 13 CYCL DEF 7.1 IZ+35 14 ; 15 TOOL CALL 27 Z S9999 F600 DL+0.057 16 TOOL DEF 30 17 L Z+300 R0 FMAX M3 18 ; 19 L X-58.5 Y-10 FMAX 20 L Z+20 FMAX 21 ; 22 ; 23 LBL 1 24 L IZ-0.5 F AUTO 25 L Y+20 26 L IZ-0.5 27 L Y-10 28 LBL 0 29 ; 30 ; 31 CALL LBL 1 REP29 32 L Z+100 FMAX 33 ; 34 L X+58.5 Y-10 FMAX 35 L Z+20 FMAX 36 ; 37 LBL 2 38 L IZ-0.5 F AUTO 39 L Y+20 40 L IZ-0.5 41 L Y-10 42 LBL 0 43 ; 44 CALL LBL 2 REP29 45 ; 46 L Z+100 FMAX 47 M5 M9 48 ; 49 ; 50 L Z+0 R0 FMAX M91 51 L X+260 Y+535 R0 FMAX M91 52 L M30 53 ; 54 M30 55 END PGM SCIECIA MM <file_sep>/cnc programming/Heidenhain/JF/AD/N030.02/fi104.H 0 BEGIN PGM fi104 MM 1 BLK FORM 0.1 Z X-140 Y-100 Z-18 2 BLK FORM 0.2 X+140 Y+100 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IX-60 7 ; 8 L X+0 Y+0 R0 FMAX 9 ;--------------------------------------------- 10 ; 11 ; 12 * - TOR-25 13 TOOL CALL 13 Z S1400 F700 14 L X+0 Y+0 R0 FMAX 15 M8 M3 16 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-5.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.3 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+104.5 ;SREDNICA NOMINALNA ~ Q342=+90 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;RODZAJ FREZOWANIA 17 CYCL CALL 18 ; 19 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 20 CYCL DEF 7.0 PUNKT BAZOWY 21 CYCL DEF 7.1 IX+60 22 ; 23 * - TOR-25 24 TOOL CALL 13 Z S1400 F700 25 L X+0 Y+0 R0 FMAX 26 M8 M3 27 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-5.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.3 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+104.5 ;SREDNICA NOMINALNA ~ Q342=+90 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 28 CYCL CALL 29 ; 30 M5 M9 31 ; 32 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 33 ; 34 ;--------------------------------------------- 35 L Z+0 R0 FMAX M91 36 L X+260 Y+535 R0 FMAX M91 / 37 L M30 38 * - ----------------------------------------- 39 END PGM fi104 MM <file_sep>/cnc programming/Heidenhain/JF/WALEK-DYST-SUR-PROG/PLAN2.H 0 BEGIN PGM PLAN2 MM 1 BLK FORM 0.1 Z X-50 Y-50 Z-51.7 2 BLK FORM 0.2 X+50 Y+50 Z+8.5 3 CALL PGM TNC:\Z19 4 CALL PGM TNC:\REF 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 PLANE RESET TURN F2500 7 ; 8 CYCL DEF 7.0 PUNKT BAZOWY 9 CYCL DEF 7.1 IZ+0.025 10 ; 11 TOOL CALL 24 Z S15000 F4500 12 M3 M8 13 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+1 ;STRATEGIA ~ Q225=-60 ;PKT.STARTU 1SZEJ OSI ~ Q226=-60 ;PKT.STARTU 2GIEJ OSI ~ Q227=+4.5 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.15 ;PUNKT KONCOWY 3. OSI ~ Q218=+125 ;DLUG. 1-SZEJ STRONY ~ Q219=+125 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 14 CYCL CALL 15 M5 M9 16 ; 17 TOOL CALL 3 Z S16987 F3000 18 M3 M8 19 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-60 ;PKT.STARTU 1SZEJ OSI ~ Q226=-60 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.15 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+125 ;DLUG. 1-SZEJ STRONY ~ Q219=+125 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1.2 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 20 CYCL CALL 21 M5 M9 22 ; 23 CALL PGM TNC:\Z19 24 CALL PGM TNC:\REF 25 ; 26 STOP 27 CALL PGM 2-STRONA 28 ; 29 M30 30 END PGM PLAN2 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/OBROTY-ZAMEK-5OS.H 0 BEGIN PGM OBROTY-ZAMEK-5OS MM 1 CALL PGM TNC:\Z19 2 CALL PGM TNC:\REF 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 L B+0 C+0 R0 FMAX M94 5 ;(999999 ) 6 ;( NAME ) 7 BLK FORM 0.1 Z X+0 Y+0 Z+0 8 BLK FORM 0.2 X+0 Y+0 Z+0 9 CYCL DEF 19.0 PLASZCZ.ROBOCZA 10 CYCL DEF 19.1 A+0 B+0 C+0 11 CYCL DEF 19.0 PLASZCZ.ROBOCZA 12 CYCL DEF 19.1 13 ; TOOL DEF 21 L+30. D+4. R+0. 14 ; TOOL DEF 22 L+40. D+4. R+0. 15 ; TOOL DEF 1 L+20. D+1. R+0. 16 L Z-5 FMAX M91 17 L X-500 FMAX M91 18 L Y-5 R0 FMAX M91 / 19 L Z-5 FMAX M91 / 20 L X-500 FMAX M91 / 21 L Y-5 R0 FMAX M91 22 ; 23 ; 24 * - NAW STAL 25 STOP 26 TOOL CALL 21 Z S650 ; 27 CYCL DEF 32.0 TOLERANCJA 28 CYCL DEF 32.1 T0.01 29 L B+0 C+0 F2500 M94 30 CYCL DEF 19.0 PLASZCZ.ROBOCZA 31 CYCL DEF 19.1 A+90 B+0 C+21.5 32 L B+Q121 C+Q122 R0 FMAX M126 33 L X+0 Y-7.5 R0 FMAX M3 34 M8 35 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 36 CYCL CALL / 37 M140 MB MAX / 38 L Z-5 FMAX M91 / 39 L X-500 FMAX M91 / 40 L Y-5 R0 FMAX M91 41 CYCL DEF 19.0 PLASZCZ.ROBOCZA 42 CYCL DEF 19.1 A+0 B+0 C+0 43 CYCL DEF 19.0 PLASZCZ.ROBOCZA 44 CYCL DEF 19.1 45 ; 46 ; 47 ; 48 CYCL DEF 19.0 PLASZCZ.ROBOCZA 49 CYCL DEF 19.1 A+90 B+0 C+98.5 50 L B+Q121 C+Q122 R0 FMAX M126 51 ; 52 L X+0 Y-7.5 R0 FMAX M3 53 M8 54 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 55 CYCL CALL / 56 M140 MB MAX / 57 L Z-5 FMAX M91 / 58 L X-500 FMAX M91 / 59 L Y-5 R0 FMAX M91 60 ; 61 ; 62 ; 63 CYCL DEF 19.0 PLASZCZ.ROBOCZA 64 CYCL DEF 19.1 A+90 B+0 C+141.5 65 L B+Q121 C+Q122 R0 FMAX M126 66 ; 67 L X+0 Y-7.5 R0 FMAX M3 68 M8 69 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 70 CYCL CALL 71 ; 72 ; 73 CYCL DEF 19.0 PLASZCZ.ROBOCZA 74 CYCL DEF 19.1 A+90 B+0 C+218.5 75 L B+Q121 C+Q122 R0 FMAX M126 76 ; 77 L X+0 Y-7.5 R0 FMAX M3 78 M8 79 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 80 CYCL CALL 81 ; 82 ; 83 CYCL DEF 19.0 PLASZCZ.ROBOCZA 84 CYCL DEF 19.1 A+90 B+0 C+261.5 85 L B+Q121 C+Q122 R0 FMAX M126 86 ; 87 L X+0 Y-7.5 R0 FMAX M3 88 M8 89 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 90 CYCL CALL 91 ; 92 ; 93 CYCL DEF 19.0 PLASZCZ.ROBOCZA 94 CYCL DEF 19.1 A+90 B+0 C+338.5 95 L B+Q121 C+Q122 R0 FMAX M126 96 ; 97 L X+0 Y-7.5 R0 FMAX M3 98 M8 99 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 100 CYCL CALL 101 M9 M5 102 ; 103 ; 104 * - W-5 105 STOP 106 TOOL CALL 28 Z S800 ; 107 CYCL DEF 32.0 TOLERANCJA 108 CYCL DEF 32.1 T0.01 109 L B+0 C+0 F2500 M94 110 CYCL DEF 19.0 PLASZCZ.ROBOCZA 111 CYCL DEF 19.1 A+90 B+0 C+21.5 112 L B+Q121 C+Q122 R0 FMAX M126 113 L X+0 Y-7.5 R0 FMAX M3 114 M8 115 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 116 CYCL CALL / 117 M140 MB MAX / 118 L Z-5 FMAX M91 / 119 L X-500 FMAX M91 / 120 L Y-5 R0 FMAX M91 121 CYCL DEF 19.0 PLASZCZ.ROBOCZA 122 CYCL DEF 19.1 A+0 B+0 C+0 123 CYCL DEF 19.0 PLASZCZ.ROBOCZA 124 CYCL DEF 19.1 125 ; 126 ; 127 ; 128 CYCL DEF 19.0 PLASZCZ.ROBOCZA 129 CYCL DEF 19.1 A+90 B+0 C+98.5 130 L B+Q121 C+Q122 R0 FMAX M126 131 ; 132 L X+0 Y-7.5 R0 FMAX M3 133 M8 134 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 135 CYCL CALL / 136 M140 MB MAX / 137 L Z-5 FMAX M91 / 138 L X-500 FMAX M91 / 139 L Y-5 R0 FMAX M91 140 ; 141 ; 142 ; 143 CYCL DEF 19.0 PLASZCZ.ROBOCZA 144 CYCL DEF 19.1 A+90 B+0 C+141.5 145 L B+Q121 C+Q122 R0 FMAX M126 146 ; 147 L X+0 Y-7.5 R0 FMAX M3 148 M8 149 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 150 CYCL CALL 151 ; 152 ; 153 CYCL DEF 19.0 PLASZCZ.ROBOCZA 154 CYCL DEF 19.1 A+90 B+0 C+218.5 155 L B+Q121 C+Q122 R0 FMAX M126 156 ; 157 L X+0 Y-7.5 R0 FMAX M3 158 M8 159 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 160 CYCL CALL 161 ; 162 ; 163 CYCL DEF 19.0 PLASZCZ.ROBOCZA 164 CYCL DEF 19.1 A+90 B+0 C+261.5 165 L B+Q121 C+Q122 R0 FMAX M126 166 ; 167 L X+0 Y-7.5 R0 FMAX M3 168 M8 169 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 170 CYCL CALL 171 ; 172 ; 173 CYCL DEF 19.0 PLASZCZ.ROBOCZA 174 CYCL DEF 19.1 A+90 B+0 C+338.5 175 L B+Q121 C+Q122 R0 FMAX M126 176 ; 177 L X+0 Y-7.5 R0 FMAX M3 178 M8 179 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 180 CYCL CALL 181 M9 M5 182 ; 183 * - NAW 184 STOP 185 TOOL CALL 10 Z S650 ; 186 CYCL DEF 32.0 TOLERANCJA 187 CYCL DEF 32.1 T0.01 188 L B+0 C+0 F2500 M94 189 CYCL DEF 19.0 PLASZCZ.ROBOCZA 190 CYCL DEF 19.1 A+90 B+0 C+21.5 191 L B+Q121 C+Q122 R0 FMAX M126 192 L X+0 Y-7.5 R0 FMAX M3 193 M8 194 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 195 CYCL CALL / 196 M140 MB MAX / 197 L Z-5 FMAX M91 / 198 L X-500 FMAX M91 / 199 L Y-5 R0 FMAX M91 200 CYCL DEF 19.0 PLASZCZ.ROBOCZA 201 CYCL DEF 19.1 A+0 B+0 C+0 202 CYCL DEF 19.0 PLASZCZ.ROBOCZA 203 CYCL DEF 19.1 204 ; 205 ; 206 ; 207 CYCL DEF 19.0 PLASZCZ.ROBOCZA 208 CYCL DEF 19.1 A+90 B+0 C+98.5 209 L B+Q121 C+Q122 R0 FMAX M126 210 ; 211 L X+0 Y-7.5 R0 FMAX M3 212 M8 213 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 214 CYCL CALL / 215 M140 MB MAX / 216 L Z-5 FMAX M91 / 217 L X-500 FMAX M91 / 218 L Y-5 R0 FMAX M91 219 ; 220 ; 221 ; 222 CYCL DEF 19.0 PLASZCZ.ROBOCZA 223 CYCL DEF 19.1 A+90 B+0 C+141.5 224 L B+Q121 C+Q122 R0 FMAX M126 225 ; 226 L X+0 Y-7.5 R0 FMAX M3 227 M8 228 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 229 CYCL CALL 230 ; 231 ; 232 CYCL DEF 19.0 PLASZCZ.ROBOCZA 233 CYCL DEF 19.1 A+90 B+0 C+218.5 234 L B+Q121 C+Q122 R0 FMAX M126 235 ; 236 L X+0 Y-7.5 R0 FMAX M3 237 M8 238 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 239 CYCL CALL 240 ; 241 ; 242 CYCL DEF 19.0 PLASZCZ.ROBOCZA 243 CYCL DEF 19.1 A+90 B+0 C+261.5 244 L B+Q121 C+Q122 R0 FMAX M126 245 ; 246 L X+0 Y-7.5 R0 FMAX M3 247 M8 248 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 249 CYCL CALL 250 ; 251 ; 252 CYCL DEF 19.0 PLASZCZ.ROBOCZA 253 CYCL DEF 19.1 A+90 B+0 C+338.5 254 L B+Q121 C+Q122 R0 FMAX M126 255 ; 256 L X+0 Y-7.5 R0 FMAX M3 257 M8 258 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206=+30 ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 259 CYCL CALL 260 M9 M5 261 ; 262 ; 263 * - GW-M6 264 STOP 265 TOOL CALL 7 Z S120 ; 266 CYCL DEF 32.0 TOLERANCJA 267 CYCL DEF 32.1 T0.01 268 L B+0 C+0 F2500 M94 269 CYCL DEF 19.0 PLASZCZ.ROBOCZA 270 CYCL DEF 19.1 A+90 B+0 C+21.5 271 L B+Q121 C+Q122 R0 FMAX M126 272 L X+0 Y-7.5 R0 FMAX M3 273 M8 274 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. 275 CYCL CALL / 276 M140 MB MAX / 277 L Z-5 FMAX M91 / 278 L X-500 FMAX M91 / 279 L Y-5 R0 FMAX M91 280 CYCL DEF 19.0 PLASZCZ.ROBOCZA 281 CYCL DEF 19.1 A+0 B+0 C+0 282 CYCL DEF 19.0 PLASZCZ.ROBOCZA 283 CYCL DEF 19.1 284 ; 285 ; 286 ; 287 CYCL DEF 19.0 PLASZCZ.ROBOCZA 288 CYCL DEF 19.1 A+90 B+0 C+98.5 289 L B+Q121 C+Q122 R0 FMAX M126 290 ; 291 L X+0 Y-7.5 R0 FMAX M3 292 M8 293 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. 294 CYCL CALL / 295 M140 MB MAX / 296 L Z-5 FMAX M91 / 297 L X-500 FMAX M91 / 298 L Y-5 R0 FMAX M91 299 ; 300 ; 301 ; 302 CYCL DEF 19.0 PLASZCZ.ROBOCZA 303 CYCL DEF 19.1 A+90 B+0 C+141.5 304 L B+Q121 C+Q122 R0 FMAX M126 305 ; 306 L X+0 Y-7.5 R0 FMAX M3 307 M8 308 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. 309 CYCL CALL 310 ; 311 ; 312 CYCL DEF 19.0 PLASZCZ.ROBOCZA 313 CYCL DEF 19.1 A+90 B+0 C+218.5 314 L B+Q121 C+Q122 R0 FMAX M126 315 ; 316 L X+0 Y-7.5 R0 FMAX M3 317 M8 318 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. 319 CYCL CALL 320 ; 321 ; 322 CYCL DEF 19.0 PLASZCZ.ROBOCZA 323 CYCL DEF 19.1 A+90 B+0 C+261.5 324 L B+Q121 C+Q122 R0 FMAX M126 325 ; 326 L X+0 Y-7.5 R0 FMAX M3 327 M8 328 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. 329 CYCL CALL 330 ; 331 ; 332 CYCL DEF 19.0 PLASZCZ.ROBOCZA 333 CYCL DEF 19.1 A+90 B+0 C+338.5 334 L B+Q121 C+Q122 R0 FMAX M126 335 ; 336 L X+0 Y-7.5 R0 FMAX M3 337 M8 338 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+62.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+70 ;2-GA BEZPIECZNA WYS. 339 CYCL CALL 340 M9 M5 341 ; 342 ; 343 ; 344 STOP 345 L Z-5 FMAX M91 346 L X-500 FMAX M91 347 L Y-5 R0 FMAX M91 348 ; 349 CYCL DEF 19.0 PLASZCZ.ROBOCZA 350 CYCL DEF 19.1 A+0 B+0 C+0 351 CYCL DEF 19.0 PLASZCZ.ROBOCZA 352 CYCL DEF 19.1 353 L C+0 B+0 R0 FMAX M94 354 M30 355 END PGM OBROTY-ZAMEK-5OS MM <file_sep>/cnc programming/Heidenhain/JF/SP/N100.00/WIERCENIE-fi10.H 0 BEGIN PGM WIERCENIE-fi10 MM 1 BLK FORM 0.1 Z X-75 Y-75 Z-50 2 BLK FORM 0.2 X+75 Y+75 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 TOOL CALL 23 Z S1000 F100 8 M8 M3 9 L X+0 Y+0 FMAX 10 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+120 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 11 CYCL CALL 12 M5 M9 13 ; 14 ; 15 TOOL CALL 25 Z S1000 F100 16 STOP 17 M8 M3 18 L X+0 Y+0 FMAX 19 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+120 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 CYCL CALL 21 M5 M9 22 ; 23 TOOL CALL 28 Z S1000 F100 24 STOP 25 M8 M3 26 L X+0 Y+0 FMAX 27 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-10 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2 ;WSPOLRZEDNE POWIERZ. ~ Q204=+120 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 28 CYCL CALL 29 M5 M9 30 ; 31 ; 32 ;--------------------------------------------- 33 L Z+0 R0 FMAX M91 34 L X+260 Y+535 R0 FMAX M91 35 L M30 36 * - ----------------------------------------- 37 * - LBL1 8.4 38 LBL 1 39 M3 40 L X-29.5 Y+61 R0 FMAX M99 41 L X+29.5 Y+61 R0 FMAX M99 42 L X-62.5 Y+27 R0 FMAX M99 43 L X+62.5 Y+27 R0 FMAX M99 44 LBL 0 45 * - LBL2 TRASA 46 LBL 2 47 M3 48 L X-70 Y+0 R0 FMAX M99 49 L X-65 Y+0 R0 FMAX M99 50 L X+65 Y+0 R0 FMAX M99 51 L X+70 Y+0 R0 FMAX M99 52 LBL 0 53 * - LBL3 8H7 54 LBL 3 55 M3 56 L X-47.5 Y+48 R0 FMAX M99 57 L X+47.5 Y+48 R0 FMAX M99 58 LBL 0 59 END PGM WIERCENIE-fi10 MM <file_sep>/cnc programming/Heidenhain/kieszen.h 0 BEGIN PGM KIESZEN MM 1 BLK FORM 0.1 Z X-170 Y+0 Z-53 2 BLK FORM 0.2 X+170 Y+80 Z+1 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 ; 5 STOP 6 TOOL CALL 16 Z S5000 F1000 DR+0 7 L Z+300 R0 FMAX M3 M8 8 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+322 ;DLUG. 1-SZEJ STRONY ~ Q219=+92 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0.01 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-3.45 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.4 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 9 L X+0 Y+40 R0 FMAX M99 10 L Z+300 R0 FMAX 11 L Y+280 X+0 R0 FMAX 12 TOOL CALL 29 Z S9990 F2000 DR-0.02 13 L Z+300 R0 FMAX M3 M8 14 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+324 ;DLUG. 1-SZEJ STRONY ~ Q219=+92 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0.01 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-3.65 ;GLEBOKOSC ~ Q202=+3.65 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.4 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 15 L X+0 Y+40 R0 FMAX M99 16 L Z+300 R0 FMAX 17 L Y+280 X+0 R0 FMAX 18 M30 19 END PGM KIESZEN MM <file_sep>/cnc programming/Heidenhain/JF/ALS/N020.04/ZAMEK-OTW-ALS_N020_02-2.H 0 BEGIN PGM ZAMEK-OTW-ALS_N020_02-2 MM 1 BLK FORM 0.1 Z X-30.1 Y-0.2 Z-13.8 2 BLK FORM 0.2 X+30.1 Y+26.2 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 R0 FMAX / 7 STOP 8 TOOL CALL 30 Z 9 TOOL DEF 3 10 ; 11 TCH PROBE 411 PKT.BAZ.PROST.ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q323=+70 ;DLUG. 1-SZEJ STRONY ~ Q324=+47 ;DLUG. 2-GIEJ STRONY ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+20 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+1 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 12 ; 13 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 14 ;--------------------------------------------- 15 ; 16 * - PLANOWANIE ZGR TOR 17 TOOL CALL 3 Z S1600 F800 / 18 STOP 19 TOOL DEF 12 20 M8 M3 21 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-35 ;PKT.STARTU 1SZEJ OSI ~ Q226=-25 ;PKT.STARTU 2GIEJ OSI ~ Q227=+1.5 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+70 ;DLUG. 1-SZEJ STRONY ~ Q219=+50 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.5 ;MAX. <NAME>UWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 22 CYCL CALL 23 M5 M9 24 ; 25 * - PLANOWANIE WYK 26 TOOL CALL 11 Z S3000 F600 / 27 STOP 28 TOOL DEF 8 29 M7 M3 30 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-35 ;PKT.STARTU 1SZEJ OSI ~ Q226=-24 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+70 ;DLUG. 1-SZEJ STRONY ~ Q219=+50 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 31 CYCL CALL 32 M5 M9 33 ; 34 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 35 ; 36 CYCL DEF 7.0 PUNKT BAZOWY 37 CYCL DEF 7.1 IY-13.45 38 ; 39 * - NAW 40 TOOL CALL 8 Z S600 F30 / 41 STOP 42 TOOL DEF 21 43 M8 44 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.45 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 45 CALL LBL 1 46 M5 M9 47 ; 48 * - W 4.8 HSS 49 TOOL CALL 21 Z S600 F30 / 50 STOP 51 TOOL DEF 28 52 M8 53 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-10 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 54 CALL LBL 1 55 M5 M9 56 ; 57 * - W 10 VHM 58 TOOL CALL 28 Z S795 F87 / 59 STOP 60 TOOL DEF 26 61 M8 62 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-28 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+15 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 63 CALL LBL 2 64 M5 M9 65 ; 66 * - FAZY 67 TOOL CALL 26 Z S600 F30 DL-0.1 / 68 STOP 69 TOOL DEF 25 70 M8 71 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-3.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 72 CALL LBL 2 73 M5 M9 74 ; 75 * - W 11 HSS 76 TOOL CALL 25 Z S300 F30 / 77 STOP 78 TOOL DEF 20 79 M8 80 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-31 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 81 CALL LBL 2 82 M5 M9 83 ; 84 * - R 5H7 85 TOOL CALL 20 Z S150 F30 / 86 STOP 87 TOOL DEF 30 88 M8 89 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-8.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+90 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 90 CALL LBL 1 91 M5 M9 92 ; 93 ;--------------------------------------------- 94 L Z-5 R0 FMAX M91 95 L X+260 Y+535 R0 FMAX M91 96 L X+150 R0 FMAX 97 L M30 98 * - ----------------------------------------- 99 * - LBL1 5H7 100 LBL 1 101 M3 102 L X-24 Y+6 R0 FMAX M99 103 L X+24 Y+6 R0 FMAX M99 104 LBL 0 105 * - LBL2 11 106 LBL 2 107 M3 108 L X-12.5 Y+11 R0 FMAX M99 109 L X+12.5 Y+11 R0 FMAX M99 110 LBL 0 111 END PGM ZAMEK-OTW-ALS_N020_02-2 MM <file_sep>/cnc programming/Heidenhain/JF/WALEK-DYST-SUR-PROG/2-STRONA.H 0 BEGIN PGM 2-STRONA MM 1 BLK FORM 0.1 Z X-62 Y-62 Z-36 2 BLK FORM 0.2 X+62 Y+62 Z+0 3 CALL PGM TNC:\Z19 4 CALL PGM TNC:\REF 5 ; 6 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 7 PLANE RESET TURN F2500 8 ;--------------------------------- 9 ; 10 * - CZOP POD SONDE / 11 STOP 12 TOOL CALL 3 Z S12000 F3500 13 M3 M8 14 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+6 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+125 ;SREDNICA WST.OBR.WYB ~ Q223=+118.9 ;SRED.WYBR.OBR.NA GOT 15 CALL LBL 1 16 M5 M9 17 ; 18 * - POMIAR SONDA / 19 STOP 20 TOOL CALL 1 Z S50 21 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+119 ;SREDNICA NOMINALNA ~ Q325=+15 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-7.5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 22 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 23 ; 24 * - 85g6 ZGR 25 TOOL CALL 3 Z S15000 F2000 DL+0.1 DR-0.005 / 26 STOP 27 M3 M8 28 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16.9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+16.9 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+119 ;SREDNICA WST.OBR.WYB ~ Q223=+111 ;SRED.WYBR.OBR.NA GOT 29 CALL LBL 1 30 Q222 = 111 31 Q223 = 103 32 CALL LBL 1 33 Q222 = 103 34 Q223 = 95 35 CALL LBL 1 36 Q222 = 95 37 Q223 = 87 38 CALL LBL 1 39 Q222 = 87 40 Q223 = 85 41 CALL LBL 1 42 M5 M9 43 ; 44 * - 85g6 WYK 45 TOOL CALL 3 Z S15000 F2000 DL+0.06 DR-0.014 / 46 STOP 47 M3 M8 48 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16.9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+16.9 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+119 ;SREDNICA WST.OBR.WYB ~ Q223=+111 ;SRED.WYBR.OBR.NA GOT 49 CALL LBL 1 50 Q222 = 111 51 Q223 = 103 52 CALL LBL 1 53 Q222 = 103 54 Q223 = 95 55 CALL LBL 1 56 Q222 = 95 57 Q223 = 87 58 CALL LBL 1 59 Q222 = 87 60 Q223 = 85 61 CALL LBL 1 62 M5 M9 63 ; 64 * - FAZA 85g6 65 TOOL CALL 30 Z S12000 F2000 DR-1 / 66 STOP 67 M3 M8 68 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+85.1 ;SREDNICA WST.OBR.WYB ~ Q223=+85 ;SRED.WYBR.OBR.NA GOT 69 CALL LBL 1 70 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+85.1 ;SREDNICA WST.OBR.WYB ~ Q223=+85 ;SRED.WYBR.OBR.NA GOT 71 CALL LBL 1 72 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-4.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+85.1 ;SREDNICA WST.OBR.WYB ~ Q223=+85 ;SRED.WYBR.OBR.NA GOT 73 CALL LBL 1 74 M5 M9 75 ; 76 * - FAZA 119 77 TOOL CALL 30 Z S12000 F2000 DR-1 / 78 STOP 79 M3 M8 80 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=-16.9 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+120 ;SREDNICA WST.OBR.WYB ~ Q223=+119 ;SRED.WYBR.OBR.NA GOT 81 CALL LBL 1 82 M5 M9 83 ; 84 * - W-3.2-VHM 85 TOOL CALL 26 Z S9938 F1034 / 86 STOP 87 M3 M8 88 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+8 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 89 CALL LBL 2 90 M5 M9 91 ; 92 ;--------------------------------- 93 CALL PGM TNC:\REF 94 CALL PGM TNC:\Z19 95 L M30 96 * - ------------------------------ 97 ; 98 * - LBL1 SRODEK 99 LBL 1 100 L M3 M8 101 L X+0 Y+0 FMAX M99 102 LBL 0 103 ; 104 * - LBL2 3.2 105 LBL 2 106 L M3 M8 107 L X+24 Y+20 FMAX M99 108 LBL 0 109 ; 110 END PGM 2-STRONA MM <file_sep>/cnc programming/Heidenhain/JF/PODZIALY/PODZIAL-POLP-GRN.H 0 BEGIN PGM PODZIAL-POLP-GRN MM 1 BLK FORM 0.1 Z X-50 Y-50 Z+0 2 BLK FORM 0.2 X+50 Y+50 Z+11 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 L X+0 Y+0 FMAX 6 ; 7 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 8 CYCL DEF 7.0 PUNKT BAZOWY 9 CYCL DEF 7.1 IZ-6 10 ;--------------------------------------------- 11 ; / 12 STOP 13 * - FP-12-ZGR 14 TOOL CALL 1 Z S1400 F80 DR-0.01 15 TOOL DEF 24 16 M8 M3 17 L X-60 Y-7 FMAX 18 L Z-1 FMAX 19 ; 20 L Y+0 RR F AUTO 21 L X+60 F AUTO 22 L Z+50 R0 FMAX 23 ; 24 M5 M9 25 ; 26 * - FP-8-WYK 27 TOOL CALL 11 Z S2700 F150 DR-0.035 / 28 STOP 29 TOOL DEF 11 30 M3 M8 31 L X-60 Y-7 FMAX 32 L Z-1 FMAX 33 ; 34 L Y+0 RR F AUTO 35 L X+60 F AUTO 36 L Z+50 FMAX 37 M5 M9 38 ; 39 ;--------------------------------------------- 40 L Z-5 R0 FMAX M91 41 L X+360 Y+535 R0 FMAX M91 42 L M30 43 * - ----------------------------------------- 44 ; 45 END PGM PODZIAL-POLP-GRN MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/KS-N100-02-2.H 0 BEGIN PGM KS-N100-02-2 MM 1 BLK FORM 0.1 Z X-55 Y-55 Z-53 2 BLK FORM 0.2 X+55 Y+55 Z+1 3 ;============================= 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT ODNIESIENIA / 5 STOP 6 ;============================= 7 * - FP-8 -POD SONDE 8 TOOL CALL 3 Z S9987 F3333 9 L X+0 Y+0 R0 FMAX 10 M8 M3 11 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+111 ;SREDNICA WST.OBR.WYB ~ Q223=+109.2 ;SRED.WYBR.OBR.NA GOT 12 CYCL CALL 13 M5 M9 14 ; 15 * - SONDA 16 TOOL CALL 1 Z S50 17 STOP 18 TCH PROBE 413 USTAW SRODEK KOLA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+109 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-7 ;POMIAR WYSOKOSCI ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD BEZPIECZNY ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 19 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT ODNIESIENIA 20 ; 21 * - FP-8 -PLANOWANIE 22 TOOL CALL 3 Z S9987 F3333 DL+4.12 23 L X+0 Y+0 R0 FMAX 24 M8 M3 25 CYCL DEF 252 WYBRANIE KOLOWE ~ Q215=+0 ;RODZ<NAME> ~ Q223=+115 ;SREDNICA OKREGU ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-4 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0.1 ;NADDATEK NA DNIE ~ Q206=+555 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;POSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 26 CYCL CALL 27 M5 M9 28 ; 29 * - FP-8 -WYBRANIA 30 TOOL CALL 3 Z S9987 F3333 DL+0.2 DR-0.03 31 L X+0 Y+0 R0 FMAX 32 M8 M3 33 CYCL DEF 252 WYBRANIE KOLOWE ~ Q215=+0 ;<NAME> ~ Q223=+47 ;SREDNICA OKREGU ~ Q368=+0.1 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-15.9 ;GLEBOKOSC ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+555 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;POSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 34 CYCL CALL 35 CYCL DEF 252 WYBRANIE KOLOWE ~ Q215=+0 ;<NAME> ~ Q223=+47 ;SREDNICA OKREGU ~ Q368=+0.1 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-16 ;GLEBOKOSC ~ Q202=+16 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+1000 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;POSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 36 CYCL CALL 37 CYCL DEF 252 WYBRANIE KOLOWE ~ Q215=+0 ;RODZAJ OBROBKI ~ Q223=+53.1 ;SREDNICA OKREGU ~ Q368=+0.1 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-3.2 ;GLEBOKOSC ~ Q202=+3.2 ;GLEBOKOSC DOSUWU ~ Q369=+0.1 ;NADDATEK NA DNIE ~ Q206=+555 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;POSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 38 CYCL CALL 39 M5 M9 40 ; 41 * - FAZO16 42 TOOL CALL 16 Z S1200 F100 43 M8 M3 44 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395 = 0 45 CALL LBL 1 46 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-4.2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395 = 0 47 CALL LBL 2 48 M5 M9 49 ; 50 * - W-6.3 51 TOOL CALL 23 Z S7950 F950 52 ;NAJPIERW W4 POTEM FP6, BO BRAKOWALO OPRAWEK 53 ;W4-VHM 54 M3 M8 55 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-20 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+12 ;GLEBOKOSC DOSUWU ~ Q210=+0.5 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 56 CALL LBL 1 57 M5 M9 58 TOOL CALL 4 Z S6666 F222 59 ;FP-6-KAN 60 M3 M8 61 CYCL DEF 208 FREZOWANIE OTOWROW ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-20 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.2 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+6.35 ;SREDNICA NOMINALNA ~ Q342=+4 ;ZADANA SREDNICA ~ Q351=+1 ;RODZAJ FREZOWANIA 62 CALL LBL 1 63 M5 M9 64 ; 65 * - W-3.3 66 TOOL CALL 25 Z S2450 F120 67 M3 M8 68 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-19 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395 = 0 69 CALL LBL 2 70 M5 M9 71 ; 72 * - FP-8 73 TOOL CALL 3 Z S9987 F1111 74 M8 M3 75 CYCL DEF 208 FREZOWANIE OTOWROW ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.8 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.05 ;SREDNICA NOMINALNA ~ Q342=+0 ;ZADANA SREDNICA ~ Q351=+1 ;<NAME> 76 CALL LBL 3 77 M5 M9 78 ; 79 * - GW EG-M6 80 TOOL CALL 11 Z S250 81 M8 82 CYCL DEF 207 GWINTOWANIE GS-NOWE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 83 CALL LBL 1 84 ; 85 * - GW M4 86 TOOL CALL 7 Z S200 87 M8 88 CYCL DEF 207 GWINTOWANIE GS-NOWE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC GWINTU ~ Q239=+0.7 ;SKOK ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 89 CALL LBL 2 90 ; 91 * - 92 * - FAZY - 93 * - FAZO10 -fi47H7 94 TOOL CALL 30 Z S10000 F2500 DL-3.4 DR+2 95 L X+0 Y+0 R0 FMAX 96 M8 M3 97 CYCL DEF 208 FREZOWANIE OTOWROW ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-4.2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+47 ;SREDNICA NOMINALNA ~ Q342=+46.8 ;ZADANA SREDNICA ~ Q351=+1 ;<NAME> 98 CYCL CALL / 99 M5 M9 100 ; 101 * - FAZO10 -fi109 102 TOOL CALL 30 Z S10000 F2500 DL+0 DR-1 103 L X+0 Y+0 R0 FMAX 104 M8 M3 105 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+109.1 ;SREDNICA WST.OBR.WYB ~ Q223=+109 ;SRED.WYBR.OBR.NA GOT 106 CYCL CALL 107 M5 M9 108 ; 109 * - FAZO16 -fi11 110 TOOL CALL 16 Z S1200 F120 111 M8 112 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-4.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395 = 0 113 CALL LBL 3 114 M5 M9 115 * - 116 * - WALCOWA - 117 * - FP-8 118 TOOL CALL 17 Z S9987 F1500 119 PLANE SPATIAL SPA+90 SPB+0 SPC-110 TURN FMAX 120 L X+0 Y-36 R0 FMAX 121 M3 M8 122 CYCL DEF 208 FREZOWANIE OTOWROW ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206=+666 ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+54.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+10 ;SREDNICA NOMINALNA ~ Q342=+0 ;ZADANA SREDNICA ~ Q351=+1 ;<NAME> 123 CYCL CALL 124 CALL PGM TNC:\REF 125 CALL PGM TNC:\Z19 126 PLANE SPATIAL SPA+90 SPB+0 SPC+0 TURN FMAX 127 L X-28 Y-20 R0 FMAX 128 M3 M8 129 CYCL DEF 208 FREZOWANIE OTOWROW ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+54.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+15 ;SREDNICA NOMINALNA ~ Q342=+0 ;ZADANA SREDNICA ~ Q351=+1 ;<NAME> 130 CYCL CALL 131 CYCL DEF 208 FREZOWANIE OTOWROW ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+54.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+20 ;SREDNICA NOMINALNA ~ Q342=+15 ;ZADANA SREDNICA ~ Q351=+1 ;<NAME> 132 CYCL CALL 133 CALL PGM TNC:\REF 134 CALL PGM TNC:\Z19 135 PLANE SPATIAL SPA+90 SPB+0 SPC+180 TURN FMAX 136 L X+28 Y-20 R0 FMAX 137 M3 M8 138 CYCL DEF 208 FREZOWANIE OTOWROW ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+54.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+15 ;SREDNICA NOMINALNA ~ Q342=+0 ;ZADANA SREDNICA ~ Q351=+1 ;<NAME> 139 CYCL CALL 140 CYCL DEF 208 FREZOWANIE OTOWROW ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+54.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+20 ;SREDNICA NOMINALNA ~ Q342=+15 ;ZADANA SREDNICA ~ Q351=+1 ;<NAME> 141 CYCL CALL 142 CALL PGM TNC:\REF 143 CALL PGM TNC:\Z19 144 M5 M9 145 ; 146 * - W-9 147 TOOL CALL 5 Z S3533 F777 148 PLANE SPATIAL SPA+90 SPB+0 SPC+0 TURN FMAX 149 L X-28 Y-20 R0 FMAX 150 M3 M8 151 CYCL DEF 200 WIERCENIE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-20 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+20 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+39 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 152 CYCL CALL 153 CALL PGM TNC:\REF 154 CALL PGM TNC:\Z19 155 PLANE SPATIAL SPA+90 SPB+0 SPC+180 TURN FMAX 156 L X+28 Y-20 R0 FMAX 157 M3 M8 158 CYCL DEF 200 WIERCENIE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-20 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+20 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+39 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 159 CYCL CALL 160 CALL PGM TNC:\REF 161 CALL PGM TNC:\Z19 162 M5 M9 163 ; 164 * - W-6.6-VHM 165 TOOL CALL 8 Z S4818 F829 166 PLANE SPATIAL SPA+90 SPB+0 SPC+0 TURN FMAX 167 L X-28 Y-20 R0 FMAX 168 M3 M8 169 CYCL DEF 200 WIERCENIE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+15 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+19 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 170 CYCL CALL 171 CALL PGM TNC:\REF 172 CALL PGM TNC:\Z19 173 PLANE SPATIAL SPA+90 SPB+0 SPC+180 TURN FMAX 174 L X+28 Y-20 R0 FMAX 175 M3 M8 176 CYCL DEF 200 WIERCENIE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-14 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+20 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+19 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 177 CYCL CALL 178 CALL PGM TNC:\REF 179 CALL PGM TNC:\Z19 180 M5 M9 181 ; 182 * - NAW-8 183 TOOL CALL 10 Z S1111 F120 184 PLANE SPATIAL SPA+90 SPB+0 SPC-110 TURN FMAX 185 L X+0 Y-36 R0 FMAX 186 M3 M8 187 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-4 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+54.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 188 CYCL CALL 189 CALL PGM TNC:\REF 190 CALL PGM TNC:\Z19 191 M5 M9 192 ; 193 * - W-7.2-VHM 194 TOOL CALL 20 Z S4417 F817 195 PLANE SPATIAL SPA+90 SPB+0 SPC-110 TURN FMAX 196 L X+0 Y-36 R0 FMAX 197 M3 M8 198 CYCL DEF 200 WIERCENIE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-40 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+20 ;GLEBOKOSC DOSUWU ~ Q210=+1 ;PRZER. CZAS.NA GORZE ~ Q203=+54.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+60 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 199 CYCL CALL 200 CALL PGM TNC:\REF 201 CALL PGM TNC:\Z19 202 M5 M9 203 ; 204 * - W-7.2-HSS -DOWIERCANIE 205 TOOL CALL 28 Z S1111 F120 206 PLANE SPATIAL SPA+90 SPB+0 SPC-110 TURN FMAX 207 L X+0 Y-36 R0 FMAX 208 M3 M8 209 CYCL DEF 200 WIERCENIE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q210=+0.5 ;PRZER. CZAS.NA GORZE ~ Q203=+14.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+60 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 210 CYCL CALL 211 CALL PGM TNC:\REF 212 CALL PGM TNC:\Z19 213 M5 M9 214 ; 215 * - GW-M8X075 216 TOOL CALL 27 Z S200 217 PLANE SPATIAL SPA+90 SPB+0 SPC-110 TURN FMAX 218 L X+0 Y-36 R0 FMAX 219 M3 M8 220 CYCL DEF 207 GWINTOWANIE GS-NOWE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-13 ;GLEBOKOSC GWINTU ~ Q239=+0.75 ;SKOK ~ Q203=+54.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+60 ;2-GA BEZPIECZNA WYS. 221 CYCL CALL 222 CALL PGM TNC:\REF 223 CALL PGM TNC:\Z19 224 M5 M9 225 ; 226 * - FP-8 -POD GWINT 1,4 227 TOOL CALL 17 Z S9987 F999 228 PLANE SPATIAL SPA+90 SPB+0 SPC+0 TURN FMAX 229 L X-28 Y-20 R0 FMAX 230 M3 M8 231 CYCL DEF 208 FREZOWANIE OTOWROW ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-20.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+39 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.85 ;SREDNICA NOMINALNA ~ Q342=+0 ;<NAME> ~ Q351=+1 ;<NAME> 232 CYCL CALL 233 CALL PGM TNC:\REF 234 CALL PGM TNC:\Z19 235 PLANE SPATIAL SPA+90 SPB+0 SPC+180 TURN FMAX 236 L X+28 Y-20 R0 FMAX 237 M3 M8 238 CYCL DEF 208 FREZOWANIE OTOWROW ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-20.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+39 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.85 ;SREDNICA NOMINALNA ~ Q342=+0 ;ZADANA SREDNICA ~ Q351=+1 ;<NAME> 239 CYCL CALL 240 CALL PGM TNC:\REF 241 CALL PGM TNC:\Z19 242 M5 M9 243 ; 244 * - GW 1,4 245 TOOL CALL 22 Z S150 246 PLANE SPATIAL SPA+90 SPB+0 SPC+0 TURN FMAX 247 L X-28 Y-20 R0 FMAX 248 M3 M8 249 CYCL DEF 207 GWINTOWANIE GS-NOWE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-19.6 ;GLEBOKOSC GWINTU ~ Q239=+1.337 ;SKOK ~ Q203=+39 ;WSPOLRZEDNE POWIERZ. ~ Q204=+60 ;2-GA BEZPIECZNA WYS. 250 CYCL CALL 251 CALL PGM TNC:\REF 252 CALL PGM TNC:\Z19 253 PLANE SPATIAL SPA+90 SPB+0 SPC+180 TURN FMAX 254 L X+28 Y-20 R0 FMAX 255 M3 M8 256 CYCL DEF 207 GWINTOWANIE GS-NOWE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-19.6 ;GLEBOKOSC GWINTU ~ Q239=+1.337 ;SKOK ~ Q203=+39 ;WSPOLRZEDNE POWIERZ. ~ Q204=+60 ;2-GA BEZPIECZNA WYS. 257 CYCL CALL 258 CALL PGM TNC:\REF 259 CALL PGM TNC:\Z19 260 M5 M9 261 ; 262 PLANE RESET TURN F2500 263 ; 264 * - -------------------- 265 CALL PGM TNC:\REF 266 CALL PGM TNC:\Z19 / 267 STOP 268 CALL PGM GRAWERKA 269 L M30 270 * - -------------------- 271 * - LBL1 HC-M6 272 LBL 1 273 M3 274 L X+0 Y+36 FMAX M99 275 L X+0 Y-36 FMAX M99 276 LBL 0 277 ; 278 * - LBL2 M4 279 LBL 2 280 M3 281 L X+28.5 Y+0 FMAX M99 282 LBL 0 283 ; 284 * - LBL3 6.6/11 285 LBL 3 286 M3 287 L X+34.4 Y+25 R0 FMAX M99 288 L X-13.1 Y+40.4 R0 FMAX M99 289 L X-42.5 Y+0 R0 FMAX M99 290 L X-13.1 Y-40.4 R0 FMAX M99 291 L X+34.4 Y-25 R0 FMAX M99 292 LBL 0 293 END PGM KS-N100-02-2 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/POPRAWA2.H 0 BEGIN PGM POPRAWA2 MM 1 BLK FORM 0.1 Z X-34 Y-34 Z-15 2 BLK FORM 0.2 X+34 Y+34 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO / 5 STOP 6 L Z-5 R0 FMAX M91 7 L X+260 Y+535 R0 FMAX M91 8 ; / 9 STOP 10 TOOL CALL 30 Z S50 11 ; 12 TCH PROBE 412 PKT.BAZ.OKRAG WEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+87 ;SREDNICA NOMINALNA ~ Q325=+45 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-8 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+1 ;PROBKOW. NA OSI TS ~ Q382=+51 ;1.WSPOL. DLA OSI TS ~ Q383=+9 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 13 ; 14 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 15 ;--------------------------------------------- 16 ; / 17 STOP 18 L Z-5 R0 FMAX M91 19 L X+260 Y+535 R0 FMAX M91 / 20 STOP 21 ; 22 TOOL CALL 1 Z S2600 F700 DL+0.02 DR-3 23 L X+0 Y+0 R0 FMAX 24 M3 25 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.01 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.3 ;GLEBOKOSC DOSUWU ~ Q203=-49.34 ;WSPOLRZEDNE POWIERZ. ~ Q204=+85 ;2-GA BEZPIECZNA WYS. ~ Q335=+63.1 ;SREDNICA NOMINALNA ~ Q342=+62.8 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME>ZOWANIA 26 CYCL CALL 27 M5 M9 28 ; 29 ; 30 ;--------------------------------------------- 31 L Z-5 R0 FMAX M91 32 L X+260 Y+535 R0 FMAX M91 33 L M30 34 * - ----------------------------------------- 35 * - LBL1 36 LBL 1 37 M3 38 L X+0 Y+0 R0 FMAX M99 39 LBL 0 40 END PGM POPRAWA2 MM <file_sep>/cnc programming/Heidenhain/JF/SD/DYSTANS/M12X1-18H7.h 0 BEGIN PGM M12X1-18H7 MM 1 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 2 PLANE RESET TURN F2500 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 BLK FORM 0.1 Z X-59 Y-59 Z-33 5 BLK FORM 0.2 X+59 Y+59 Z+1 6 ; 7 * - NAW / 8 STOP / 9 TOOL CALL 9 Z S1500 F120 / 10 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE / 11 CALL LBL 1 / 12 M5 / 13 M9 14 ; 15 * - W -10.5-WSTEPNIE POD GWINT 16 TOOL CALL 28 Z S3180 F763 / 17 STOP 18 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-29 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+20 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 19 CALL LBL 1 20 M5 21 M9 22 ; 23 ; 24 * - FP-8-FI-11 POD GWINT 25 TOOL CALL 27 Z S9000 F800 / 26 STOP 27 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-6.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.7 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+12 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 28 CALL LBL 1 29 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-29 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.7 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.03 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 30 CALL LBL 1 31 M5 32 M9 33 ; 34 * - 18 H7 ZGRUBNIE 35 TOOL CALL 27 Z S9000 F800 DL+0.1 / 36 STOP 37 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-6.9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.8 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+17.85 ;SREDNICA NOMINALNA ~ Q342=+17 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 38 CALL LBL 1 39 M5 40 M9 41 ; 42 * - FAZ 16 43 TOOL CALL 26 Z S1500 F120 / 44 STOP 45 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-5.9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7 ;WSPOLRZEDNE POWIERZ. ~ Q204=+30 ;2-GA BEZPIECZNA WYS. ~ Q211=+0.5 ;PRZERWA CZAS. DNIE 46 CALL LBL 1 47 M5 48 M9 49 ; 50 * - GW M12X1 51 TOOL CALL 18 Z S150 / 52 STOP 53 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-21 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=-7 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 54 CALL LBL 1 55 M5 56 M9 57 ; 58 * - 18 H7 WYKONCZENIE 59 TOOL CALL 27 Z S8000 F600 DL+0.02 DR+0.017 / 60 STOP 61 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.8 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+17.99 ;SREDNICA NOMINALNA ~ Q342=+17 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 62 CALL LBL 1 63 M5 64 M9 65 ; / 66 STOP 67 * - FAZA / 68 STOP 69 TOOL CALL 9 Z S4000 F1000 DL+0 DR-2 70 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+18 ;SREDNICA NOMINALNA ~ Q342=+17 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 71 CALL LBL 1 72 M5 73 M9 74 ; 75 * - ********** 76 L Z-5 R0 FMAX M91 77 L X+260 Y+535 R0 FMAX M91 / 78 M30 79 * - ********** 80 * - LBL 1 - SRODEK 81 LBL 1 82 L X+0 Y+0 R0 FMAX M99 M13 83 LBL 0 84 END PGM M12X1-18H7 MM <file_sep>/inheritance.cpp #include <iostream> #include <math.h> using namespace std; class Point { float x,y; string name; public: void display() { cout<<name<<"("<<x<<","<<y<<")"<<endl; } Point(string n="S", float a=0, float b=0) { name = n; x = a; y = b; } }; class Circle : public Point //public inheritance from 'Point' class { float r; string name; public: void display() { cout<<"Circle name: "<<name<< endl; cout<<"Center of the circle: "; Point::display(); cout<<"Radius: "<<r<< endl; cout<<"Circle surface: "<<M_PI*r*r<<endl; } Circle(string nk="Circle_0", string np="S", float a=0, float b=0, float pr=1) : Point(np,a,b) { name = nk; r = pr; } }; int main() { Circle k1; k1.display(); return 0; } <file_sep>/cnc programming/Heidenhain/JF/SD/WYCIECIA-AVIA.H 0 BEGIN PGM WYCIECIA-AVIA MM 1 ;MASTERCAM - X9 2 ;MCX FILE -~ \\NCNCSERV\NCNC\00NZL\SD\SDN10102\MCX\DYSTANS_SD_N101_02_AVIA_POD~ GWINTOWNIK.MCX-9 3 ;POST - MPPOSTABILITY_AVIA_VMC_800_4X.PST 4 ;PROGRAM - SDN10102A.h 5 ;DATE - 2017.09.20 6 ;TIME - 1:44 PM 7 ;1 - 20. FLAT ENDMILL - D20.000mm 8 ;2 - NAWIERTAK 6 - D4.000mm 9 ;3 - 11.7 DRILL - D11.700mm 10 ;5 - 10 / 45 CHAMFER MILL - D10.000mm 11 ;6 - G1/4" TAP RH - D13.158mm 12 BLK FORM 0.1 Z X-69.5 Y-103.5 Z+0 13 BLK FORM 0.2 X+69.5 Y+35.5 Z+34 14 M129 15 ; 16 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 17 ; 18 L X+0 Y+0 R0 FMAX M91 19 PLANE RESET TURN FMAX 20 ; 21 * - 20. FLAT ENDMILL 22 STOP 23 TOOL CALL 8 Z S6000 24 TOOL DEF 0 25 ; 20. FLAT ENDMILL TOOL - 1 DIA. OFF. - 1 LEN. - 1 DIA. - 20. 26 ;HOLDER - DEFAULT HOLDER 27 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 28 CYCL DEF 32.0 TOLERANCJA 29 CYCL DEF 32.1 T0.003 30 CYCL DEF 32.2 HSC-MODE:0 31 M3 32 L X-51.05 Y-45.884 FMAX M8 33 L Z+96.6 FMAX 34 L Z+76.6 FMAX 35 L Z+63.337 F600 36 L Y+10 37 L Z+93.338 FMAX 38 L X-44.05 Y-45.884 FMAX 39 L Z+76.6 FMAX 40 L Z+63.337 F600 41 L Y+10 42 L Z+93.338 FMAX 43 L X-37.05 Y-45.884 FMAX 44 L Z+76.6 FMAX 45 L Z+63.337 F600 46 L Y+10 47 L Z+93.338 FMAX 48 L X-30.05 Y-45.884 FMAX 49 L Z+76.6 FMAX 50 L Z+63.337 F600 51 L Y+10 52 L Z+93.338 FMAX 53 L X-51.05 Y-45.884 FMAX 54 L Z+73.338 FMAX 55 L Z+60.075 F600 56 L Y+10 57 L Z+90.075 FMAX 58 L X-44.05 Y-45.884 FMAX 59 L Z+73.338 FMAX 60 L Z+60.075 F600 61 L Y+10 62 L Z+90.075 FMAX 63 L X-37.05 Y-45.884 FMAX 64 L Z+73.338 FMAX 65 L Z+60.075 F600 66 L Y+10 67 L Z+90.075 FMAX 68 L X-30.05 Y-45.884 FMAX 69 L Z+73.338 FMAX 70 L Z+60.075 F600 71 L Y+10 72 L Z+90.075 FMAX 73 L X-51.05 Y-45.884 FMAX 74 L Z+70.075 FMAX 75 L Z+56.813 F600 76 L Y+10 77 L Z+86.813 FMAX 78 L X-44.05 Y-45.884 FMAX 79 L Z+70.075 FMAX 80 L Z+56.813 F600 81 L Y+10 82 L Z+86.813 FMAX 83 L X-37.05 Y-45.884 FMAX 84 L Z+70.075 FMAX 85 L Z+56.813 F600 86 L Y+10 87 L Z+86.813 FMAX 88 L X-30.05 Y-45.884 FMAX 89 L Z+70.075 FMAX 90 L Z+56.813 F600 91 L Y+10 92 L Z+86.813 FMAX 93 L X-51.05 Y-45.884 FMAX 94 L Z+66.813 FMAX 95 L Z+53.55 F600 96 L Y+10 97 L Z+83.55 FMAX 98 L X-44.05 Y-45.884 FMAX 99 L Z+66.813 FMAX 100 L Z+53.55 F600 101 L Y+10 102 L Z+83.55 FMAX 103 L X-37.05 Y-45.884 FMAX 104 L Z+66.813 FMAX 105 L Z+53.55 F600 106 L Y+10 107 L Z+83.55 FMAX 108 L X-30.05 Y-45.884 FMAX 109 L Z+66.813 FMAX 110 L Z+53.55 F600 111 L Y+10 112 L Z+83.55 FMAX 113 L X-51.05 Y-45.884 FMAX 114 L Z+63.55 FMAX 115 L Z+53.5 F600 116 L Y+10 117 L Z+83.5 FMAX 118 L X-44.05 Y-45.884 FMAX 119 L Z+63.55 FMAX 120 L Z+53.5 F600 121 L Y+10 122 L Z+83.5 FMAX 123 L X-37.05 Y-45.884 FMAX 124 L Z+63.55 FMAX 125 L Z+53.5 F600 126 L Y+10 127 L Z+83.5 FMAX 128 L X-30.05 Y-45.884 FMAX 129 L Z+63.55 FMAX 130 L Z+53.5 F600 131 L Y+10 132 L Z+83.5 FMAX 133 L X-30 Y-45.884 FMAX 134 L Z+63.55 FMAX 135 L Z+53.5 F600 136 L Y+10 137 L Z+96.6 FMAX 138 L X+51.05 Y+13.884 FMAX 139 L Z+76.6 FMAX 140 L Z+63.337 F600 141 L Y-42 142 L Z+93.338 FMAX 143 L X+44.05 Y+13.884 FMAX 144 L Z+76.6 FMAX 145 L Z+63.337 F600 146 L Y-42 147 L Z+93.338 FMAX 148 L X+37.05 Y+13.884 FMAX 149 L Z+76.6 FMAX 150 L Z+63.337 F600 151 L Y-42 152 L Z+93.338 FMAX 153 L X+30.05 Y+13.884 FMAX 154 L Z+76.6 FMAX 155 L Z+63.337 F600 156 L Y-42 157 L Z+93.338 FMAX 158 L X+51.05 Y+13.884 FMAX 159 L Z+73.338 FMAX 160 L Z+60.075 F600 161 L Y-42 162 L Z+90.075 FMAX 163 L X+44.05 Y+13.884 FMAX 164 L Z+73.338 FMAX 165 L Z+60.075 F600 166 L Y-42 167 L Z+90.075 FMAX 168 L X+37.05 Y+13.884 FMAX 169 L Z+73.338 FMAX 170 L Z+60.075 F600 171 L Y-42 172 L Z+90.075 FMAX 173 L X+30.05 Y+13.884 FMAX 174 L Z+73.338 FMAX 175 L Z+60.075 F600 176 L Y-42 177 L Z+90.075 FMAX 178 L X+51.05 Y+13.884 FMAX 179 L Z+70.075 FMAX 180 L Z+56.813 F600 181 L Y-42 182 L Z+86.813 FMAX 183 L X+44.05 Y+13.884 FMAX 184 L Z+70.075 FMAX 185 L Z+56.813 F600 186 L Y-42 187 L Z+86.813 FMAX 188 L X+37.05 Y+13.884 FMAX 189 L Z+70.075 FMAX 190 L Z+56.813 F600 191 L Y-42 192 L Z+86.813 FMAX 193 L X+30.05 Y+13.884 FMAX 194 L Z+70.075 FMAX 195 L Z+56.813 F600 196 L Y-42 197 L Z+86.813 FMAX 198 L X+51.05 Y+13.884 FMAX 199 L Z+66.813 FMAX 200 L Z+53.55 F600 201 L Y-42 202 L Z+83.55 FMAX 203 L X+44.05 Y+13.884 FMAX 204 L Z+66.813 FMAX 205 L Z+53.55 F600 206 L Y-42 207 L Z+83.55 FMAX 208 L X+37.05 Y+13.884 FMAX 209 L Z+66.813 FMAX 210 L Z+53.55 F600 211 L Y-42 212 L Z+83.55 FMAX 213 L X+30.05 Y+13.884 FMAX 214 L Z+66.813 FMAX 215 L Z+53.55 F600 216 L Y-42 217 L Z+83.55 FMAX 218 L X+51.05 Y+13.884 FMAX 219 L Z+63.55 FMAX 220 L Z+53.5 F600 221 L Y-42 222 L Z+83.5 FMAX 223 L X+44.05 Y+13.884 FMAX 224 L Z+63.55 FMAX 225 L Z+53.5 F600 226 L Y-42 227 L Z+83.5 FMAX 228 L X+37.05 Y+13.884 FMAX 229 L Z+63.55 FMAX 230 L Z+53.5 F600 231 L Y-42 232 L Z+83.5 FMAX 233 L X+30.05 Y+13.884 FMAX 234 L Z+63.55 FMAX 235 L Z+53.5 F600 236 L Y-42 237 L Z+83.5 FMAX 238 L X+30 Y+13.884 FMAX 239 L Z+63.55 FMAX 240 L Z+53.5 F600 241 L Y-42 242 L Z+96.6 FMAX 243 L X-63.55 Y-44.884 Z+74.362 FMAX 244 L Z+54.362 FMAX 245 L Z+40.889 F600 246 L Y+10 247 L Z+70.889 FMAX 248 L Y-44.884 FMAX 249 L Z+50.889 FMAX 250 L Z+37.416 F600 251 L Y+10 252 L Z+67.416 FMAX 253 L Y-44.884 FMAX 254 L Z+47.416 FMAX 255 L Z+33.943 F600 256 L Y+10 257 L Z+63.943 FMAX 258 L Y-44.884 FMAX 259 L Z+43.943 FMAX 260 L Z+30.469 F600 261 L Y+10 262 L Z+60.469 FMAX 263 L Y-44.884 FMAX 264 L Z+40.469 FMAX 265 L Z+26.996 F600 266 L Y+10 267 L Z+56.996 FMAX 268 L Y-44.884 FMAX 269 L Z+36.996 FMAX 270 L Z+23.523 F600 271 L Y+10 272 L Z+53.523 FMAX 273 L Y-44.884 FMAX 274 L Z+33.523 FMAX 275 L Z+20.05 F600 276 L Y+10 277 L Z+50.05 FMAX 278 L Y-44.884 FMAX 279 L Z+30.05 FMAX 280 L Z+20 F600 281 L Y+10 282 L Z+50 FMAX 283 L X-63.5 Y-44.884 FMAX 284 L Z+30.05 FMAX 285 L Z+20 F600 286 L Y+10 287 L Z+74.362 FMAX 288 L X+63.55 Y+13.884 FMAX 289 L Z+54.362 FMAX 290 L Z+40.889 F600 291 L Y-42 292 L Z+70.889 FMAX 293 L X+63.5 Y+13.884 FMAX 294 L Z+54.362 FMAX 295 L Z+40.889 F600 296 L Y-42 297 L Z+70.889 FMAX 298 L X+63.55 Y+13.884 FMAX 299 L Z+50.889 FMAX 300 L Z+37.416 F600 301 L Y-42 302 L Z+67.416 FMAX 303 L X+63.5 Y+13.884 FMAX 304 L Z+50.889 FMAX 305 L Z+37.416 F600 306 L Y-42 307 L Z+67.416 FMAX 308 L X+63.55 Y+13.884 FMAX 309 L Z+47.416 FMAX 310 L Z+33.943 F600 311 L Y-42 312 L Z+63.943 FMAX 313 L X+63.5 Y+13.884 FMAX 314 L Z+47.416 FMAX 315 L Z+33.943 F600 316 L Y-42 317 L Z+63.943 FMAX 318 L X+63.55 Y+13.884 FMAX 319 L Z+43.943 FMAX 320 L Z+30.469 F600 321 L Y-42 322 L Z+60.469 FMAX 323 L X+63.5 Y+13.884 FMAX 324 L Z+43.943 FMAX 325 L Z+30.469 F600 326 L Y-42 327 L Z+60.469 FMAX 328 L X+63.55 Y+13.884 FMAX 329 L Z+40.469 FMAX 330 L Z+26.996 F600 331 L Y-42 332 L Z+56.996 FMAX 333 L X+63.5 Y+13.884 FMAX 334 L Z+40.469 FMAX 335 L Z+26.996 F600 336 L Y-42 337 L Z+56.996 FMAX 338 L X+63.55 Y+13.884 FMAX 339 L Z+36.996 FMAX 340 L Z+23.523 F600 341 L Y-42 342 L Z+53.523 FMAX 343 L X+63.5 Y+13.884 FMAX 344 L Z+36.996 FMAX 345 L Z+23.523 F600 346 L Y-42 347 L Z+53.523 FMAX 348 L X+63.55 Y+13.884 FMAX 349 L Z+33.523 FMAX 350 L Z+20.05 F600 351 L Y-42 352 L Z+50.05 FMAX 353 L X+63.5 Y+13.884 FMAX 354 L Z+33.523 FMAX 355 L Z+20.05 F600 356 L Y-42 357 L Z+50.05 FMAX 358 L X+63.55 Y+13.884 FMAX 359 L Z+30.05 FMAX 360 L Z+20 F600 361 L Y-42 362 L Z+50 FMAX 363 L X+63.5 Y+13.884 FMAX 364 L Z+30.05 FMAX 365 L Z+20 F600 366 L Y-42 367 L Z+74.362 FMAX 368 CYCL DEF 32.0 TOLERANCJA 369 CYCL DEF 32.1 370 M5 M9 371 ; 372 * - NAWIERTAK 373 TOOL CALL 9 Z S1111 374 STOP 375 TOOL DEF 0 376 ;NAWIERTAK 6 TOOL - 2 DIA. OFF. - 2 LEN. - 2 DIA. - 4. 377 ;HOLDER - DEFAULT HOLDER 378 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 379 M3 380 L X-34.5 Y-16 FMAX M8 381 L Z+103.5 FMAX 382 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206=+100 ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0.5 ;PRZER. CZAS.NA GORZE ~ Q203=+53.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 383 L X-34.5 Y-16 FMAX M99 384 L X+34.5 Y-16 FMAX M99 385 M5 M9 386 ; 387 * - 11.7 DRILL 388 TOOL CALL 3 Z S700 389 STOP 390 TOOL DEF 0 391 ;11.7 DRILL TOOL - 3 DIA. OFF. - 3 LEN. - 3 DIA. - 11.7 392 ;HOLDER - DEFAULT HOLDER 393 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 394 M3 395 L X-34.5 Y-16 FMAX M8 396 L Z+103.5 FMAX 397 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-29.515 ;GLEBOKOSC ~ Q206=+120 ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q210=+0.5 ;PRZER. CZAS.NA GORZE ~ Q203=+53.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 398 L X-34.5 Y-16 FMAX M99 399 L X+34.5 Y-16 FMAX M99 400 M5 M9 401 ; 402 * - 10 / 45 CHAMFER MILL 403 TOOL CALL 9 Z S5000 404 STOP 405 TOOL DEF 0 406 * - KOMPENSACJA DLUGOSCI 407 ; 10 / 45 CHAMFER MILL TOOL - 5 DIA. OFF. - 5 LEN. - 5 DIA. - 10. 408 ;HOLDER - DEFAULT HOLDER 409 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 410 CYCL DEF 32.0 TOLERANCJA 411 CYCL DEF 32.1 T0.003 412 CYCL DEF 32.2 HSC-MODE:0 413 M3 414 L X+34.5 Y-10.6 FMAX M8 415 L Z+103.5 FMAX 416 L Z+56.5 FMAX 417 L Z+53.2 F300 418 CC X+34.5 Y-16 419 C X+34.5 Y-10.6 DR+ 420 L Z+103.2 FMAX 421 L Z+103.5 FMAX 422 L X-34.5 FMAX 423 L Z+56.5 FMAX 424 L Z+53.2 F300 425 CC X-34.5 Y-16 426 C X-34.5 Y-10.6 DR+ 427 L Z+103.5 FMAX 428 CYCL DEF 32.0 TOLERANCJA 429 CYCL DEF 32.1 430 M5 M9 431 ; 432 * - G1/4" TAP RH 433 TOOL CALL 2 Z S200 434 STOP 435 TOOL DEF 30 436 ; G1/4" TAP RH TOOL - 6 DIA. OFF. - 6 LEN. - 6 DIA. - 13.158 437 ;HOLDER - DEFAULT HOLDER 438 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 439 M3 440 L X-34.5 Y-16 FMAX M8 441 L Z+106.5 FMAX 442 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1.337 ;SKOK GWINTU ~ Q203=+56.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 443 L X-34.5 Y-16 FMAX M99 444 L X+34.5 Y-16 FMAX M99 445 M5 M9 446 M2 447 END PGM WYCIECIA-AVIA MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/OP2.H 0 BEGIN PGM OP2 MM 1 BLK FORM 0.1 Z X-96 Y-56 Z-24 2 BLK FORM 0.2 X+96 Y+56 Z+1 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 ; 5 TOOL CALL 29 Z S2000 F500 6 L Z+300 R0 FMAX M3 7 ; 8 L X+0 Y+0 FMAX 9 L Z+10 FMAX 10 L X-28.28 Y+28.28 FMAX 11 L X-50 FMAX 12 L Z-1 FMAX 13 ; 14 L X-37 F500 15 L Z+5 FMAX 16 L X+50 FMAX 17 L Z-1 FMAX 18 L X+37 F500 19 L Z+50 FMAX 20 ; 21 L X+0 Y+0 R0 FMAX M99 22 L Z+300 R0 FMAX 23 L Y+535 X+0 R0 FMAX 24 M30 25 END PGM OP2 MM <file_sep>/cnc programming/Heidenhain/JF/AD/N031.01/PLAN-NA-GOTOWO.H 0 BEGIN PGM PLAN-NA-GOTOWO MM 1 BLK FORM 0.1 Z X-45 Y-16 Z-32 2 BLK FORM 0.2 X+45 Y+16 Z+9 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 * - PLAN ZGR 8 STOP 9 TOOL CALL 14 Z S1600 F800 10 TOOL DEF 24 11 M8 M3 12 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+1 ;STRATEGIA ~ Q225=-53 ;PKT.STARTU 1SZEJ OSI ~ Q226=-20 ;PKT.STARTU 2GIEJ OSI ~ Q227=+9 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.15 ;PUNKT KONCOWY 3. OSI ~ Q218=+106 ;DLUG. 1-SZEJ STRONY ~ Q219=+40 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.8 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 13 CYCL CALL 14 M5 M9 15 ; 16 STOP 17 * - STOP! ZDEJMIJ RESZTKI 18 ; 19 * - PLAN WYK 20 TOOL CALL 24 Z S3000 F600 21 TOOL DEF 30 22 M8 M3 23 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-50 ;PKT.STARTU 1SZEJ OSI ~ Q226=-12 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.15 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+100 ;DLUG. 1-SZEJ STRONY ~ Q219=+24 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.3 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 24 CYCL CALL 25 M5 M9 26 ; 27 ;--------------------------------------------- 28 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 29 ; / 30 STOP 31 L X+0 Y+0 R0 FMAX 32 ; 33 TOOL CALL 30 Z 34 TOOL DEF 9 35 ; 36 TCH PROBE 411 PKT.BAZ.PROST.ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q323=+80 ;DLUG. 1-SZEJ STRONY ~ Q324=+22 ;DLUG. 2-GIEJ STRONY ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+20 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+1 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 37 ; 38 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 39 ; 40 ;--------------------------------------------- 41 ; 42 * - GRATOWANIE OBRYS 43 TOOL CALL 9 Z S3000 F200 DR-3 / 44 STOP 45 TOOL DEF 18 46 M8 M3 47 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+80 ;DLUG. 1-SZEJ STRONY ~ Q424=+80.1 ;WYMIAR POLWYROBU 1 ~ Q219=+22 ;DLUG. 2-GIEJ STRONY ~ Q425=+22.1 ;WYMIAR POLWYROBU 2 ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 48 CALL LBL 1 49 M5 M9 50 ; 51 * - FP 8 ZGR POGLEBIENIA 52 TOOL CALL 18 Z S1800 F200 / 53 STOP 54 TOOL DEF 26 55 M8 M3 56 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.4 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.05 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 57 CALL LBL 2 58 M5 M9 59 ; 60 * - FAZY POGLEBIENIA 61 TOOL CALL 26 Z S600 F40 / 62 STOP 63 TOOL DEF 14 64 M8 M3 65 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.6 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-3 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0.3 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 66 CALL LBL 2 67 M5 M9 68 ; 69 ;--------------------------------------------- 70 L Z-5 R0 FMAX M91 71 L X+260 Y+535 R0 FMAX M91 72 L M30 73 * - ----------------------------------------- 74 * - LBL1 SRODEK 75 LBL 1 76 M3 77 L X+0 Y+0 R0 FMAX M99 78 LBL 0 79 * - LBL2 POGLEBIENIA 11 80 LBL 2 81 M3 82 L X-32.5 Y-5 R0 FMAX M99 83 L X+32.5 Y-5 R0 FMAX M99 84 LBL 0 85 ; 86 END PGM PLAN-NA-GOTOWO MM <file_sep>/cnc programming/Heidenhain/JF/AD/N031.01/STR-Z-WYBRANIEM.h 0 BEGIN PGM STR-Z-WYBRANIEM MM 1 BLK FORM 0.1 Z X-40 Y+0 Z-32 2 BLK FORM 0.2 X+40 Y+22 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; / 6 STOP 7 L X+0 Y+0 R0 FMAX 8 ; 9 TOOL CALL 30 Z 10 TOOL DEF 24 11 ; 12 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+80 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+20 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 13 ; 14 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 15 ; 16 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+0 ;1.PKT POMIAROW 1.OSI ~ Q264=+0 ;1.PKT 2.OSI ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+20 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q272=+2 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 17 ; 18 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 19 ;--------------------------------------------- 20 ; 21 * - PLANOWANIE NADDATKU 22 TOOL CALL 24 Z S3000 F400 / 23 STOP 24 TOOL DEF 3 25 M3 M8 26 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-40 ;PKT.STARTU 1SZEJ OSI ~ Q226=+0 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.015 ;PUNKT KONCOWY 3. OSI ~ Q218=+80 ;DLUG. 1-SZEJ STRONY ~ Q219=+22 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 27 CYCL CALL 28 M5 M9 29 ; 30 * - NAW STAL 31 TOOL CALL 3 Z S650 F30 / 32 STOP 33 TOOL DEF 10 34 M8 35 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 36 CALL LBL 1 37 CALL LBL 2 38 M5 M9 39 ; 40 * - W 7.8 HSS 41 TOOL CALL 10 Z S500 F30 / 42 STOP 43 TOOL DEF 22 44 M8 45 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 46 CALL LBL 1 47 M5 M9 48 ; 49 * - W 6.3 HSS 50 TOOL CALL 22 Z S600 F30 / 51 STOP 52 TOOL DEF 26 53 M8 54 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-30 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 55 CALL LBL 2 56 M5 M9 57 ; 58 * - FAZY 59 TOOL CALL 26 Z S650 F30 DL+0.05 / 60 STOP 61 TOOL DEF 4 62 M8 63 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.6 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 64 CALL LBL 1 65 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 66 CALL LBL 2 67 M5 M9 68 ; 69 * - R 8H7 70 TOOL CALL 4 Z S150 F30 / 71 STOP 72 TOOL DEF 9 73 M8 74 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-13 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+100 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 75 CALL LBL 1 76 M5 M9 77 ; 78 * - FAZA 79 TOOL CALL 9 Z S4000 F300 DL+0 DR-2 / 80 STOP 81 TOOL DEF 30 82 M3 M8 83 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+80 ;DLUG. 1-SZEJ STRONY ~ Q424=+80.1 ;WYMIAR POLWYROBU 1 ~ Q219=+22 ;DLUG. 2-GIEJ STRONY ~ Q425=+22.1 ;WYMIAR POLWYROBU 2 ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1.9 ;GLEBOKOSC ~ Q202=+2.3 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 84 CALL LBL 3 85 M5 M9 86 ; 87 ;--------------------------------------------- 88 L Z-5 R0 FMAX M91 89 L X+260 Y+535 R0 FMAX M91 90 ; / 91 STOP 92 CALL PGM TNC:\JF\AD\N031.01\kzadn031.h 93 ; 94 L M30 95 * - ----------------------------------------- 96 * - LBL1 8H7 97 LBL 1 98 M3 99 L X-32.5 Y+16 R0 FMAX M99 100 L X+32.5 Y+16 R0 FMAX M99 101 LBL 0 102 * - LBL2 6.4 103 LBL 2 104 M3 105 L X-32.5 Y+6 R0 FMAX M99 106 L X+32.5 Y+6 R0 FMAX M99 107 LBL 0 108 * - LBL3 FAZKA 109 LBL 3 110 M3 111 L X+0 Y+11 R0 FMAX M99 112 LBL 0 113 END PGM STR-Z-WYBRANIEM MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/TEST-PO-NAPRAWIE-04-2021-OK.H 0 BEGIN PGM TEST-PO-NAPRAWIE-04-2021-OK MM 1 BLK FORM 0.1 Z X-55 Y+25 Z-51 2 BLK FORM 0.2 X+55 Y+25 Z+8 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 CYCL DEF 7.0 PUNKT BAZOWY 5 CYCL DEF 7.1 IZ+50 6 TOOL CALL 26 Z S1111 F111 7 LBL 2 8 L Z-30 R0 FMAX 9 L Z+30 R0 FMAX 10 LBL 0 11 CALL LBL 2 REP600 12 M30 13 END PGM TEST-PO-NAPRAWIE-04-2021-OK MM <file_sep>/calculator.c #include <stdio.h> #include <stdlib.h> void loadValue( int *a, int *b ); int addition( int a, int b ); int subtraction( int a, int b ); int multiplication( int a, int b ); int division( int a, int b ); #define line "---------------------------\n" int main(void) { int a, b = 0; char sign; int result = 0; int choice = 0; // choice loop do { printf("CHOICE MENU \n1. Addition \n2. Subtraction \n3. Multiplication \n4. Division \n"); printf( line ); printf("Your choice: "); scanf("%d", &choice ); loadValue( &a, &b ); switch( choice ) { case 1: result = addition( a, b ); break; case 2: result = subtraction( a, b ); break; case 3: result = multiplication( a, b ); break; case 4: result = division( a, b ); break; default: printf("Choice error!"); } printf("Result: %d\n", result ); printf( line ); printf("\nGo back to main menu? y/n "); scanf("%s", &sign ); // clear screen system("cls"); } while( sign == 't' ); return 0; } void loadValue( int *a, int *b ) { int x, y; printf("Type a: "); scanf("%d", &x ); printf("Type b: "); scanf("%d", &y ); *a = x; *b = y; } int addition( int a, int b ) { return a + b; } int subtraction( int a, int b ) { return a - b; } int multiplication( int a, int b ) { return a * b; } int division( int a, int b ) { return a / b; } <file_sep>/cnc programming/Heidenhain/JF/_INNE/10X1.h 0 BEGIN PGM 10X1 MM 1 BLK FORM 0.1 Z X-60 Y-34 Z-119 2 BLK FORM 0.2 X+60 Y+0 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 STOP 6 L X+0 Y+0 R0 FMAX 7 TOOL CALL 30 Z S50 8 TOOL DEF 27 9 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+85 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-30 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 10 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 11 ;--------------------------------------------- 12 ; 13 ; / 14 * - NAW / 15 TOOL CALL 9 Z S1111 F111 / 16 STOP / 17 TOOL DEF 23 / 18 M8 / 19 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. / 20 CALL LBL 1 / 21 M5 M9 22 ; 23 * - FI 11 FP8 24 TOOL CALL 27 Z S9987 F500 25 TOOL DEF 19 26 M8 27 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.6 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+10 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 28 CALL LBL 1 29 M5 M9 30 ; 31 TOOL CALL 9 Z S1111 F111 32 TOOL DEF 19 33 M8 34 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-1 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 35 CALL LBL 1 36 M5 M9 37 ; / 38 * - W 7.2 / 39 TOOL CALL 19 Z S4417 F813 / 40 STOP / 41 TOOL DEF 5 / 42 M8 / 43 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-20 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+20 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-1 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. / 44 CALL LBL 1 / 45 M5 M9 46 ; 47 * - W 6 48 TOOL CALL 5 Z S1300 F120 / 49 STOP 50 TOOL DEF 13 51 M8 52 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-40 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-1 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 53 CALL LBL 1 54 M5 M9 55 ; 56 * - FI 7.2 FP6 57 TOOL CALL 10 Z S6000 F500 58 TOOL DEF 19 59 M8 60 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.6 ;GLEBOKOSC DOSUWU ~ Q203=-1 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+7.2 ;SREDNICA NOMINALNA ~ Q342=+6 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 61 CALL LBL 1 62 M5 M9 63 ; 64 * - GW M8X0.75 65 TOOL CALL 13 Z S200 66 TOOL DEF 30 67 M8 68 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-12.5 ;GLEBOKOSC GWINTU ~ Q239=+0.75 ;SKOK GWINTU ~ Q203=-1 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 69 CALL LBL 1 70 M5 M9 71 ; 72 ; 73 ;--------------------------------------------- 74 L Z-5 R0 FMAX M91 75 L X+260 Y+535 R0 FMAX M91 76 L M30 77 * - ----------------------------------------- 78 * - LBL1 O 79 LBL 1 80 M3 81 L X+0 Y+0 R0 FMAX M99 82 LBL 0 83 END PGM 10X1 MM <file_sep>/cnc programming/Heidenhain/JF/PODZIALY/SYMULACJA-GRAWERKI.h 0 BEGIN PGM SYMULACJA-GRAWERKI MM 1 BLK FORM 0.1 Z X-50 Y+0 Z-6 2 BLK FORM 0.2 X+50 Y+50 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 * - FI 96 (100 MINUS FAZA) 7 TOOL CALL 19 Z S2000 F200 / 8 STOP 9 M8 10 CYCL DEF 257 CZOP OKRAGLY ~ Q223=+96 ;SRED.WYBR.OBR.NA GOT ~ Q222=+97 ;SREDNICA WST.OBR.WYB ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-6 ;GLEBOKOSC ~ Q202=+6 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q376=-1 ;KAT POCZATKOWY 11 CALL LBL 3 / 12 CYCL DEF 252 WYBRANIE KOLOWE ~ Q215=+0 ;RODZAJ OBROBKI ~ Q223=+36.5 ;SREDNICA OKREGU ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207=+500 ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-20 ;GLEBOKOSC ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+150 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385=+500 ;POSUW OBR.WYKAN. / 13 CALL LBL 3 14 M5 M9 15 ; 16 * - FI 11 17 TOOL CALL 18 Z S2000 F200 / 18 STOP 19 M8 20 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-4.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.4 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q335=+11 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 21 CALL LBL 2 22 M5 M9 23 ; 24 * - R 6H7 25 TOOL CALL 24 Z S150 F30 / 26 STOP 27 M8 28 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+90 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 29 CALL LBL 1 30 M5 M9 31 ; 32 ;--------------------------------------------- 33 ; / 34 STOP 35 * - FK 1 DLA WIERZCHOLKA 36 TOOL CALL 19 Z S9987 F70 37 TOOL DEF 0 38 M3 M8 39 ; / 40 STOP 41 L X+0 Y+0 R0 FMAX 42 CYCL DEF 225 GRAWEROWANIE ~ QS500="250ml" ;TEKST GRAWER. ~ Q513=+3 ;WYSOK.ZNAKU ~ Q514=+0.7 ;WSPOL.ODSTEPU ~ Q515=+0 ;FONT ~ Q516=+1 ;UKLAD TEKSTU ~ Q374=+150 ;KAT OBROTU ~ Q517=+43 ;PROMIEN OKREGU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q201=-0.07 ;GLEBOKOSC ~ Q206=+15 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 43 CYCL CALL 44 L X+0 Y+0 R0 FMAX 45 CYCL DEF 225 GRAWEROWANIE ~ QS500="PRET SQUARE" ;TEKST GRAWER. ~ Q513=+3 ;WYSOK.ZNAKU ~ Q514=+0.7 ;WSPOL.ODSTEPU ~ Q515=+0 ;FONT ~ Q516=+1 ;UKLAD TEKSTU ~ Q374=+114.5 ;KAT OBROTU ~ Q517=+43 ;PROMIEN OKREGU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q201=-0.07 ;GLEBOKOSC ~ Q206=+15 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 46 CYCL CALL 47 L X+0 Y+0 R0 FMAX 48 CYCL DEF 225 GRAWEROWANIE ~ QS500="E2266-B-02" ;TEKST GRAWER. ~ Q513=+3 ;WYSOK.ZNAKU ~ Q514=+0.7 ;WSPOL.ODSTEPU ~ Q515=+0 ;FONT ~ Q516=+1 ;UKLAD TEKSTU ~ Q374=+65 ;KAT OBROTU ~ Q517=+43 ;PROMIEN OKREGU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q201=-0.07 ;GLEBOKOSC ~ Q206=+15 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 49 CYCL CALL 50 L X+0 Y+0 R0 FMAX 51 CYCL DEF 225 GRAWEROWANIE ~ QS500="5625/01" ;TEKST GRAWER. ~ Q513=+3 ;WYSOK.ZNAKU ~ Q514=+0.7 ;WSPOL.ODSTEPU ~ Q515=+0 ;FONT ~ Q516=+1 ;UKLAD TEKSTU ~ Q374=+30 ;KAT OBROTU ~ Q517=+43 ;PROMIEN OKREGU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q201=-0.07 ;GLEBOKOSC ~ Q206=+15 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 52 CYCL CALL 53 ; 54 M5 M9 55 ; 56 ;--------------------------------------------- 57 L Z-5 R0 FMAX M91 58 L X+260 Y+535 R0 FMAX M91 59 L M30 60 * - ----------------------------------------- 61 * - LBL1 6H7 62 LBL 1 63 M3 64 L X-28.285 Y+28.28 R0 FMAX M99 65 L X+28.285 Y+28.28 R0 FMAX M99 66 LBL 0 67 * - LBL2 6.6/11 68 LBL 2 69 M3 70 L X-39.15 Y+8.3 R0 FMAX M99 71 L X+0 Y+40 R0 FMAX M99 72 L X+39.15 Y+8.3 R0 FMAX M99 73 LBL 0 74 * - LBL3 SRODEK 75 LBL 3 76 M3 77 L X+0 Y+0 R0 FMAX M99 78 LBL 0 79 END PGM SYMULACJA-GRAWERKI MM <file_sep>/cnc programming/Heidenhain/JF/PODZIALY/PODZIAL-WKLADKA-GW.H 0 BEGIN PGM PODZIAL-WKLADKA-GW MM 1 BLK FORM 0.1 Z X-50 Y-50 Z+0 2 BLK FORM 0.2 X+50 Y+50 Z+11 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 L X+0 Y+0 FMAX 6 STOP 7 ; 8 TOOL CALL 30 Z S50 9 TOOL DEF 27 10 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+108 ;SREDNICA NOMINALNA ~ Q325=+5 ;KAT POCZATKOWY ~ Q247=+85 ;KATOWY PRZYROST-KROK ~ Q261=+4.5 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+3 ;LICZBA PKT POMIAR. ~ Q365=+1 ;<NAME>ZCZ. 11 ; 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 ;--------------------------------------------- 14 ; / 15 STOP 16 * - FP-8-CIECIE 17 TOOL CALL 27 Z S7000 F3000 18 TOOL DEF 27 19 M8 M3 20 L X-60 Y-6 FMAX 21 L Z+14 FMAX 22 ; 23 LBL 1 24 L IZ-1 FMAX 25 L X+60 26 L IZ-1 FMAX 27 L X-60 28 LBL 0 29 ; 30 CALL LBL 1 REP6 31 L Z+50 FMAX 32 ; 33 M5 M9 34 ; / 35 STOP 36 * - FP-8-ZGR 37 TOOL CALL 27 Z S7000 F140 38 TOOL DEF 14 39 M8 M3 40 L X-60 Y-4.6 FMAX 41 L Z-1 FMAX 42 ; 43 L X+60 44 L Z+50 FMAX 45 ; 46 M5 M9 47 ; / 48 STOP 49 * - FP-8-WYK 50 TOOL CALL 27 Z S7000 F140 DR+0 51 TOOL DEF 30 52 M3 M8 53 L X-60 Y-5 FMAX 54 L Z-1 FMAX 55 ; 56 L Y-0.5 RR 57 L X+60 58 L Z+50 FMAX 59 M5 M9 60 ; 61 ; 62 ;--------------------------------------------- 63 L Z-5 R0 FMAX M91 64 L X+160 Y+535 R0 FMAX M91 65 L M30 66 * - ----------------------------------------- 67 ; 68 END PGM PODZIAL-WKLADKA-GW MM <file_sep>/cnc programming/Heidenhain/JF/PLYTY/PLAN.H 0 BEGIN PGM PLAN MM 1 BLK FORM 0.1 Z X-100 Y-100 Z-35 2 BLK FORM 0.2 X+100 Y+100 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+2 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 TOOL CALL 27 Z S6666 F2000 8 L X+0 Y+0 R0 FMAX 9 M8 M3 10 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=+0 ;PKT.STARTU 1SZEJ OSI ~ Q226=+0 ;PKT.STARTU 2GIEJ OSI ~ Q227=+2 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+111 ;DLUG. 1-SZEJ STRONY ~ Q219=+30 ;DLUG. 2-GIEJ STRONY ~ Q202=+5 ;MAX. GLEB. DOSUWU ~ Q369=+0.15 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q357=+2 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 11 CYCL CALL 12 M5 M9 13 ; 14 ;--------------------------------------------- 15 L Z-5 R0 FMAX M91 16 L X+260 Y+535 R0 FMAX M91 17 L M30 18 * - ----------------------------------------- 19 * - LBL1 20 LBL 1 21 M3 22 L X+0 Y+0 R0 FMAX M99 23 LBL 0 24 ; 25 END PGM PLAN MM <file_sep>/cnc programming/Heidenhain/JF/PODZIALY/PRZ2.h 0 BEGIN PGM PRZ2 MM 1 BLK FORM 0.1 Z X-50 Y+0 Z-6 2 BLK FORM 0.2 X+50 Y+50 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 STOP 7 TOOL CALL 18 Z S2200 F150 8 STOP 9 M8 10 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-6.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.4 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+10.3 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 11 CALL LBL 1 12 M5 M9 13 ; 14 ; 15 ;--------------------------------------------- 16 L Z-5 R0 FMAX M91 17 L X+260 Y+535 R0 FMAX M91 18 L M30 19 * - ----------------------------------------- 20 * - LBL1 POGL FI10 21 LBL 1 22 M3 23 L X-34 Y-15 R0 FMAX M99 24 L X+34 Y-15 R0 FMAX M99 25 L X-34 Y+15 R0 FMAX M99 26 L X+34 Y+15 R0 FMAX M99 27 LBL 0 28 END PGM PRZ2 MM <file_sep>/cnc programming/Heidenhain/JF/PLYTY/POMIR.H 0 BEGIN PGM POMIR MM 1 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 2 ; 3 L Z+300 R0 FMAX 4 L X+0 Y+0 R0 FMAX 5 TOOL CALL 30 Z 6 ; 7 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+780 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+100 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 8 ; 9 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 10 ; 11 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+335 ;SZEROKOSC MOSTKA ~ Q272=+2 ;OS POMIAROWA ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+100 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 12 ; 13 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 14 TOOL CALL 0 Z 15 ;--------------------------------------------- 16 ;--------------------------------------------- 17 L Z+0 R0 FMAX M91 18 L X+260 Y+535 R0 FMAX M91 19 L M30 20 END PGM POMIR MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/K00BKI/001-KUBKI.h 0 BEGIN PGM 001-KUBKI MM 1 ; 2 BLK FORM 0.1 Z X+0 Y-75 Z-75 3 BLK FORM 0.2 X+200 Y+75 Z+1 4 CALL PGM TNC:\REF 5 CALL PGM TNC:\Z19 6 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 7 PLANE RESET TURN F3000 8 ; 9 * - SONDA 10 TOOL CALL 1 Z S10 11 ; 12 ; X 13 ; 14 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+0 ;1.PKT POMIAROW 1.OSI ~ Q264=-54 ;1.PKT 2.OSI ~ Q261=-7 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q272=+1 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 15 ; 16 M140 MB MAX / 17 STOP 18 CALL PGM kubki-sd-sonda / 19 STOP 20 ; 21 M30 22 END PGM 001-KUBKI MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/KS-WAL-DYS-I-2STR.h 0 BEGIN PGM KS-WAL-DYS-I-2STR MM 1 BLK FORM 0.1 Z X-49.5 Y-49.5 Z-101.1 2 BLK FORM 0.2 X+49.5 Y+49.5 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 R0 FMAX 7 STOP 8 TOOL CALL 30 Z 9 TOOL DEF 14 10 ; 11 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+99 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-11 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 12 ; 13 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 14 ;--------------------------------------------- 15 ; 16 * - W 3.6 17 STOP 18 TOOL CALL 14 Z S8833 F989 19 TOOL DEF 8 20 M7 21 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-7.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+7.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 22 CALL LBL 1 23 M5 M9 24 ; 25 * - W 5 26 TOOL CALL 8 Z S6360 F890 27 STOP 28 TOOL DEF 5 29 M7 30 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+16 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.4 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 31 CALL LBL 2 32 M5 M9 33 ; 34 * - W 6 WIDIA 35 TOOL CALL 5 Z S5300 F848 36 STOP 37 TOOL DEF 20 38 M7 39 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-35 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+25 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 40 CALL LBL 3 41 M5 M9 42 ; 43 * - NAW 8 44 TOOL CALL 12 Z S1200 F100 45 STOP 46 TOOL DEF 999 47 M8 48 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.4 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 49 CALL LBL 2 50 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.75 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.75 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 51 CALL LBL 1 52 M5 M9 53 ; 54 * - GW M6 55 TOOL CALL 999 Z S100 56 STOP 57 TOOL DEF 30 58 M8 59 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=-7.4 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 60 CALL LBL 2 61 M5 M9 62 ; 63 ;--------------------------------------------- 64 L Z+0 R0 FMAX M91 / 65 L X+260 Y+535 R0 FMAX M91 66 L X+100 Y+365 R0 FMAX 67 L M30 68 * - ----------------------------------------- 69 * - LBL1 3.6 70 LBL 1 71 M3 72 L X-14.8 Y-2.8 R0 FMAX M99 73 LBL 0 74 * - LBL2 6.6 75 LBL 2 76 M3 77 L X-13.1 Y-40.4 R0 FMAX M99 78 L X+34.4 Y-25 R0 FMAX M99 79 L X+34.4 Y+25 R0 FMAX M99 80 L X-13.1 Y+40.4 R0 FMAX M99 81 L X-42.5 Y+0 R0 FMAX M99 82 LBL 0 83 * - LBL3 6 84 LBL 3 85 M3 86 L X-26.1 Y-11.5 R0 FMAX M99 87 LBL 0 88 END PGM KS-WAL-DYS-I-2STR MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/TLOCZYSKO/ZGRUBNIE.H 0 BEGIN PGM ZGRUBNIE MM 1 BLK FORM 0.1 Z X-25 Y-25 Z-50 2 BLK FORM 0.2 X+25 Y+25 Z+1 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 ;FREZ-8 5 ; 6 STOP 7 TOOL CALL 12 Z S3000 F500 8 L Z+300 R0 FMAX M3 9 L X-30 Y-23.5 R0 FMAX 10 L Z+25 R0 FMAX M7 11 L Z+0 R0 F AUTO 12 LBL 1 13 L IZ-0.5 14 L X+30 15 L IZ-0.5 16 L X-30 17 LBL 0 18 CALL LBL 1 REP14 19 L Z+25 R0 FMAX 20 M9 M5 21 ; 22 TOOL CALL 12 Z S3000 F500 / 23 STOP 24 L Z+300 R0 FMAX M3 25 L X-30 Y+23.5 R0 FMAX 26 L Z+25 R0 FMAX M7 27 L Z+0 R0 F AUTO 28 LBL 2 29 L IZ-0.5 30 L X+30 31 L IZ-0.5 32 L X-30 33 LBL 0 34 CALL LBL 2 REP14 35 L Z+25 R0 FMAX 36 M9 M5 37 ; / 38 STOP 39 TOOL CALL 12 Z S3000 F500 40 L Z+300 R0 FMAX M3 41 L X-33 Y-16 R0 FMAX 42 L Z+25 R0 FMAX M7 43 L Z+0 R0 F AUTO 44 LBL 3 45 L IZ-0.5 46 L X+33 47 L IZ-0.5 48 L X-33 49 LBL 0 50 CALL LBL 3 REP14 51 L Z+25 R0 FMAX 52 M9 M5 53 ; 54 TOOL CALL 12 Z S3000 F500 / 55 STOP 56 L Z+300 R0 FMAX M3 57 L X-33 Y+16 R0 FMAX 58 L Z+25 R0 FMAX M7 59 L Z+0 R0 F AUTO 60 LBL 4 61 L IZ-0.5 62 L X+33 63 L IZ-0.5 64 L X-33 65 LBL 0 66 CALL LBL 4 REP14 67 L Z+25 R0 FMAX 68 M9 M5 69 ; 70 L Z-5 R0 FMAX M91 71 L X+260 Y+535 R0 FMAX M91 72 M30 73 END PGM ZGRUBNIE MM <file_sep>/cnc programming/Heidenhain/JF/PLYTA-SP-n160/GAB4.h 0 BEGIN PGM GAB4 MM 1 BLK FORM 0.1 Z X+0 Y-15 Z-5 2 BLK FORM 0.2 X+208.9 Y+15 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 R0 FMAX 7 ; 8 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 9 CYCL DEF 7.0 PUNKT BAZOWY 10 CYCL DEF 7.1 IZ+0 11 ;--------------------------------------------- 12 ; / 13 STOP 14 * - GLOW-20 15 TOOL CALL 22 Z S6000 F2000 DL+0 16 TOOL DEF 30 17 M8 M3 18 ; 19 ; 20 L X-150 Y-20 FMAX 21 L Z+0 FMAX 22 ; 23 Q22 = - 3 24 LBL 2 25 L Z+Q22 26 L Y+0.05 RL 27 L X-429.9 28 L Y+379.95 29 L X-150 30 ; 31 L Z+5 R0 FMAX 32 L X-150 Y-20 FMAX 33 Q22 = Q22 - 3 34 LBL 0 35 CALL LBL 2 REP14 36 ; 37 M5 M9 38 ; 39 ;--------------------------------------------- 40 L Z-5 R0 FMAX M91 41 L X+260 Y+535 R0 FMAX M91 42 L M30 43 * - ----------------------------------------- 44 * - LBL1 / 45 LBL 1 / 46 M3 / 47 L X+0 Y+0 R0 FMAX M99 / 48 LBL 0 49 END PGM GAB4 MM <file_sep>/cnc programming/Heidenhain/JF/KR/N091.00/KR-KOL-MOC-WCIECIE.H 0 BEGIN PGM KR-KOL-MOC-WCIECIE MM 1 BLK FORM 0.1 Z X-25 Y-25 Z-50 2 BLK FORM 0.2 X+25 Y+25 Z+1 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 ;FREZ-8 5 TOOL CALL 4 Z S3000 F200 DL+0.2 6 L Z+300 R0 FMAX M3 7 L X-20 Y-13 R0 FMAX 8 L Z+25 R0 FMAX M8 9 L Z+0 R0 F AUTO 10 LBL 1 11 L IZ-0.5 12 L X+20 13 L IZ-0.5 14 L X-20 15 LBL 0 16 CALL LBL 1 REP9 / 17 STOP 18 L Y-13.12 19 L X+20 20 M9 M5 21 ; 22 L Z+0 R0 FMAX M91 23 L X+260 Y+535 R0 FMAX M91 24 M30 25 END PGM KR-KOL-MOC-WCIECIE MM <file_sep>/cnc programming/Heidenhain/JF/PLYTA-SP-n160/OTW.h 0 BEGIN PGM OTW MM 1 BLK FORM 0.1 Z X+0 Y-15 Z-5 2 BLK FORM 0.2 X+208.9 Y+15 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 FMAX 7 ; 8 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 9 ;--------------------------------------------- 10 ; / 11 STOP 12 * - W-5-VHM 13 TOOL CALL 27 Z S6360 F890 14 TOOL DEF 30 15 M8 16 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+8 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 17 CALL LBL 1 18 M5 M9 19 ; 20 ;--------------------------------------------- 21 L Z-5 R0 FMAX M91 22 L X+260 Y+535 R0 FMAX M91 23 L M30 24 * - ----------------------------------------- 25 * - LBL1 5 26 LBL 1 27 M3 28 L X+21 Y-155 R0 FMAX M99 29 LBL 0 30 END PGM OTW MM <file_sep>/cnc programming/Heidenhain/JF/PODZIALY/GRAWERKI-ZMIENIAJ-NR.h 0 BEGIN PGM GRAWERKI-ZMIENIAJ-NR MM 1 BLK FORM 0.1 Z X-42.5 Y+0 Z-6 2 BLK FORM 0.2 X+42.5 Y+42.5 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- / 6 STOP 7 * - KULA 2 DLA WIERZCHOLKA 8 TOOL CALL 22 Z S9987 F70 9 TOOL DEF 0 10 M3 M8 11 ; 12 L X-22.65 Y+30 R0 FMAX 13 CYCL DEF 225 GRAWEROWANIE ~ QS500="P2002-B008-06 2.0L" ;TEKST GRAWER. ~ Q513=+4 ;WYSOK.ZNAKU ~ Q514=+0.6 ;WSPOL.ODSTEPU ~ Q515=+0 ;FONT ~ Q516=+0 ;UKLAD TEKSTU ~ Q374=+0 ;KAT OBROTU ~ Q517=+50 ;PROMIEN OKREGU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q201=-0.07 ;GLEBOKOSC ~ Q206=+20 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 14 CYCL CALL 15 ; / 16 STOP 17 L X-35 Y+2.5 R0 FMAX 18 CYCL DEF 225 GRAWEROWANIE ~ QS500="06" ;TEKST GRAWER. ~ Q513=+4 ;WYSOK.ZNAKU ~ Q514=+0.6 ;WSPOL.ODSTEPU ~ Q515=+0 ;FONT ~ Q516=+0 ;UKLAD TEKSTU ~ Q374=+0 ;KAT OBROTU ~ Q517=+50 ;PROMIEN OKREGU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q201=-0.07 ;GLEBOKOSC ~ Q206=+20 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 19 CYCL CALL 20 ; / 21 STOP 22 L X+25.6 Y+2.5 R0 FMAX 23 CYCL DEF 225 GRAWEROWANIE ~ QS500="5608" ;TEKST GRAWER. ~ Q513=+4 ;WYSOK.ZNAKU ~ Q514=+0.6 ;WSPOL.ODSTEPU ~ Q515=+0 ;FONT ~ Q516=+0 ;UKLAD TEKSTU ~ Q374=+0 ;KAT OBROTU ~ Q517=+50 ;PROMIEN OKREGU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q201=-0.07 ;GLEBOKOSC ~ Q206=+20 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 24 CYCL CALL 25 ; 26 M5 M9 27 ; 28 ;--------------------------------------------- 29 L Z-5 R0 FMAX M91 30 L X+260 Y+535 R0 FMAX M91 31 L M30 32 * - ----------------------------------------- 33 END PGM GRAWERKI-ZMIENIAJ-NR MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/G1,4.H 0 BEGIN PGM G1,4 MM 1 BLK FORM 0.1 Z X-60 Y-34 Z-119 2 BLK FORM 0.2 X+60 Y+0 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IZ+0 7 ;--------------------------------------------- 8 ; 9 L X+0 Y+0 FMAX 10 TOOL CALL 30 Z S50 11 TOOL DEF 27 12 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+100 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-30 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 13 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 14 ; 15 * - FI 11 FP8 16 TOOL CALL 27 Z S9987 F800 17 TOOL DEF 21 18 M8 19 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+15 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 20 CALL LBL 1 21 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+20 ;SREDNICA NOMINALNA ~ Q342=+15 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME>IA 22 CALL LBL 1 23 M5 M9 24 ; 25 ; 26 * - W 8 27 TOOL CALL 21 Z S3975 F795 28 TOOL DEF 27 29 M8 30 CYCL DEF 200 WIERCENIE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-40 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+20 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-1.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 31 CALL LBL 1 32 M5 M9 33 ; 34 * - FI 11 FP8 35 TOOL CALL 27 Z S9987 F800 36 TOOL DEF 25 37 M8 38 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-17.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=-1.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.8 ;SREDNICA NOMINALNA ~ Q342=+8 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 39 CALL LBL 1 40 M5 M9 41 ; 42 * - GW 43 TOOL CALL 25 Z S150 44 TOOL DEF 30 45 M8 46 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.5 ;GLEBOKOSC GWINTU ~ Q239=+1.337 ;SKOK GWINTU ~ Q203=-1.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 47 CALL LBL 1 48 M5 M9 49 ; 50 ; 51 ;--------------------------------------------- 52 L Z-5 R0 FMAX M91 53 L X+260 Y+535 R0 FMAX M91 54 L M30 55 * - ----------------------------------------- 56 * - LBL1 O 57 LBL 1 58 M3 59 L X+0 Y+0 R0 FMAX M99 60 LBL 0 61 END PGM G1,4 MM <file_sep>/cnc programming/Heidenhain/PPG-OTW.H 0 BEGIN PGM PPG-OTW MM 1 CALL PGM TNC:\REF 2 CALL PGM TNC:\Z19 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+2 ;NR PKT BAZOWEGO 4 PLANE RESET TURN F4444 5 BLK FORM 0.1 Z X-45 Y-45 Z-6 6 BLK FORM 0.2 X+45 Y+45 Z+0.1 7 STOP 8 * - NAW-8 9 TOOL CALL 8 Z S500 F30 10 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+10 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+1 ;PRZERWA CZAS. DNIE 11 CALL LBL 2 12 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+10 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+1 ;PRZERWA CZAS. DNIE 13 CALL LBL 3 14 M5 M9 15 * - W-5.8 -HSS 16 TOOL CALL 10 Z S655 F30 17 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-10 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 18 CALL LBL 2 19 M5 M9 20 * - FP-8 21 TOOL CALL 44 Z S1600 F120 22 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-4.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.7 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+12 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 23 CALL LBL 1 24 * - FP-5 25 TOOL CALL 54 Z S2800 F80 26 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=-4.3 ;WSPOLRZEDNE POWIERZ. ~ Q204=+55 ;2-GA BEZPIECZNA WYS. ~ Q335=+7 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;RODZAJ FREZOWANIA 27 CALL LBL 1 28 M5 M9 29 * - NAW-16 30 TOOL CALL 12 Z S500 F40 31 CYCL DEF 200 WIERCENIE ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+10 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+1 ;PRZERWA CZAS. DNIE 32 CALL LBL 1 33 CYCL DEF 200 WIERCENIE ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+10 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+1 ;PRZERWA CZAS. DNIE 34 CALL LBL 2 35 M5 M9 36 * - R-6 37 TOOL CALL 36 Z S150 F15 38 CYCL DEF 201 ROZWIERCANIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+150 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 39 CALL LBL 2 40 M5 M9 41 * - ********** 42 CALL PGM TNC:\REF3 43 CALL PGM TNC:\Z19 44 CALL LBL 99 / 45 M30 46 * - ********** 47 * - LBL 1 - FI12 48 LBL 1 49 L X-38.5 Y+19.3 R0 FMAX M99 M13 50 L X-38.5 Y-19.3 R0 FMAX M99 M13 51 L X+38.5 Y+19.3 R0 FMAX M99 M13 52 L X+38.5 Y-19.3 R0 FMAX M99 M13 53 LBL 0 54 * - LBL 2 - 6H7 55 LBL 2 56 L X-27 Y+14.1 R0 FMAX M99 M13 57 L X-27 Y-14.1 R0 FMAX M99 M13 58 L X+27 Y+14.1 R0 FMAX M99 M13 59 L X+27 Y-14.1 R0 FMAX M99 M13 60 LBL 0 61 * - LBL 3 - TRAS 62 LBL 3 63 L X+27 Y+0 R0 FMAX M99 M13 64 L X+30 Y+0 R0 FMAX M99 M13 65 L X-27 Y+0 R0 FMAX M99 M13 66 L X-30 Y+0 R0 FMAX M99 M13 67 LBL 0 68 LBL 99 69 END PGM PPG-OTW MM <file_sep>/cnc programming/Heidenhain/JF/ALS/N030.05/PLAN.H 0 BEGIN PGM PLAN MM 1 BLK FORM 0.1 Z X-55 Y-25 Z-51 2 BLK FORM 0.2 X+55 Y+25 Z+8 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 TOOL CALL 3 Z S2000 F500 5 L Z+300 R0 FMAX M3 M8 6 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-65 ;PKT.STARTU 1SZEJ OSI ~ Q226=+20 ;PKT.STARTU 2GIEJ OSI ~ Q227=+9 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+125 ;DLUG. 1-SZEJ STRONY ~ Q219=-40 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1.2 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q357=+2 ;ODST. BEZP. Z BOKU ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 7 CYCL CALL 8 L Z+300 R0 FMAX 9 ; 10 TOOL CALL 12 Z S2500 F500 11 L Z+300 R0 FMAX M3 M8 12 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-65 ;PKT.STARTU 1SZEJ OSI ~ Q226=+18 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.05 ;PUNKT KONCOWY 3. OSI ~ Q218=+125 ;DLUG. 1-SZEJ STRONY ~ Q219=-36 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q357=+2 ;ODST. BEZP. Z BOKU ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 13 CYCL CALL 14 L Z+300 R0 FMAX 15 L Y+220 R0 FMAX 16 M5 M9 17 STOP 18 CALL PGM TNC:\JF\ALS\N030.05\FAZA.H 19 M30 20 END PGM PLAN MM <file_sep>/cnc programming/Heidenhain/JF/KR/N091.00/6H7-FAZA.H 0 BEGIN PGM 6H7-FAZA MM 1 BLK FORM 0.1 Z X-35 Y-35 Z-15 2 BLK FORM 0.2 X+35 Y+35 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+2 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 * - NAW-8 8 TOOL CALL 9 Z S1111 F30 DL-0.05 9 TOOL DEF 30 10 M8 11 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-27 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 12 CALL LBL 1 13 M5 M9 14 ; 15 ;--------------------------------------------- 16 L Z-5 R0 FMAX M91 17 L X+260 Y+535 R0 FMAX M91 / 18 L M30 19 CALL LBL 99 20 * - ----------------------------------------- 21 * - LBL1 22 LBL 1 23 M3 24 L X+0 Y+0 R0 FMAX M99 25 LBL 0 26 LBL 99 27 END PGM 6H7-FAZA MM <file_sep>/cnc programming/Heidenhain/JF/CHWYTAKI/sd_5458_02_01_B.h 0 BEGIN PGM sd_5458_02_01_B MM 1 ;MASTERCAM - X9 2 ;MCX FILE - D:\0_ZLECENIA\5458_SD\SD_5458.02.01_B.MCX-9 3 ;POST - MPPOSTABILITY_AVIA_VMC_800_4X.PST 4 ;PROGRAM - sd_5458_02_01_B.h 5 ;DATE - 2019.11.05 6 ;TIME - 3:15 PM 7 ;1 - FREZ PLASKI FI 20 R04 - D20.000mm - R0.400mm 8 ;3 - FREZ PLASKI FI 8 - D8.000mm 9 BLK FORM 0.1 Z X+0 Y-24.5 Z-9.8 10 BLK FORM 0.2 X+105.105 Y+0 Z+0 11 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 12 M126 13 M129 14 PLANE RESET TURN FMAX 15 ; 16 * - FREZ PLASKI FI 20 R04 17 TOOL CALL 1 Z S1034 18 TOOL DEF 0 19 * - ZGRUBNIE 20 ;FREZ PLASKI FI 20 R04 TOOL - 1 DIA. OFF. - 1 LEN. - 1 DIA. - 20. 21 ;HOLDER - DEFAULT HOLDER 22 CYCL DEF 32.0 TOLERANCJA 23 CYCL DEF 32.1 T0.003 24 CYCL DEF 32.2 HSC-MODE:0 25 L A+0 FMAX 26 M3 27 L X-8.9 Y+2.5 FMAX M8 28 L Z+16.1 FMAX 29 L Z-7.9 FMAX 30 L Z-15.4 F233 31 L Y+49 32 L Z+9.6 FMAX 33 L X-7.9 Y+2.5 FMAX 34 L Z-7.9 FMAX 35 L Z-15.4 F233 36 L Y+49 37 L Z+9.6 FMAX 38 L X-6.9 Y+2.5 FMAX 39 L Z-7.9 FMAX 40 L Z-15.4 F233 41 L Y+49 42 L Z+9.6 FMAX 43 L X-5.9 Y+2.5 FMAX 44 L Z-7.9 FMAX 45 L Z-15.4 F233 46 L Y+49 47 L Z+9.6 FMAX 48 L X-4.9 Y+2.5 FMAX 49 L Z-7.9 FMAX 50 L Z-15.4 F233 51 L Y+49 52 L Z+9.6 FMAX 53 L X-3.9 Y+2.5 FMAX 54 L Z-7.9 FMAX 55 L Z-15.4 F233 56 L Y+49 57 L Z+9.6 FMAX 58 L X-2.9 Y+2.5 FMAX 59 L Z-7.9 FMAX 60 L Z-15.4 F233 61 L Y+49 62 L Z+9.6 FMAX 63 L X-1.9 Y+2.5 FMAX 64 L Z-7.9 FMAX 65 L Z-15.4 F233 66 L Y+49 67 L Z+9.6 FMAX 68 L X-0.9 Y+2.5 FMAX 69 L Z-7.9 FMAX 70 L Z-15.4 F233 71 L Y+49 72 L Z+9.6 FMAX 73 L X+0.1 Y+2.5 FMAX 74 L Z-7.9 FMAX 75 L Z-15.4 F233 76 L Y+49 77 L Z+9.6 FMAX 78 L X+1.1 Y+2.5 FMAX 79 L Z-7.9 FMAX 80 L Z-15.4 F233 81 L Y+49 82 L Z+9.6 FMAX 83 L X+2.1 Y+2.5 FMAX 84 L Z-7.9 FMAX 85 L Z-15.4 F233 86 L Y+49 87 L Z+9.6 FMAX 88 L X+3.1 Y+2.5 FMAX 89 L Z-7.9 FMAX 90 L Z-15.4 F233 91 L Y+49 92 L Z+9.6 FMAX 93 L X+4.1 Y+2.5 FMAX 94 L Z-7.9 FMAX 95 L Z-15.4 F233 96 L Y+49 97 L Z+9.6 FMAX 98 L X+5.1 Y+2.5 FMAX 99 L Z-7.9 FMAX 100 L Z-15.4 F233 101 L Y+49 102 L Z+9.6 FMAX 103 L X+6.1 Y+2.5 FMAX 104 L Z-7.9 FMAX 105 L Z-15.4 F233 106 L Y+49 107 L Z+9.6 FMAX 108 L X+7.1 Y+2.5 FMAX 109 L Z-7.9 FMAX 110 L Z-15.4 F233 111 L Y+49 112 L Z+9.6 FMAX 113 L X+8.1 Y+2.5 FMAX 114 L Z-7.9 FMAX 115 L Z-15.4 F233 116 L Y+49 117 L Z+9.6 FMAX 118 L X+9.1 Y+2.5 FMAX 119 L Z-7.9 FMAX 120 L Z-15.4 F233 121 L Y+49 122 L Z+9.6 FMAX 123 L X+10.1 Y+2.5 FMAX 124 L Z-7.9 FMAX 125 L Z-15.4 F233 126 L Y+49 127 L Z+9.6 FMAX 128 L X+11.1 Y+2.5 FMAX 129 L Z-7.9 FMAX 130 L Z-15.4 F233 131 L Y+49 132 L Z+9.6 FMAX 133 L X+12.1 Y+2.5 FMAX 134 L Z-7.9 FMAX 135 L Z-15.4 F233 136 L Y+49 137 L Z+9.6 FMAX 138 L X+13.1 Y+2.5 FMAX 139 L Z-7.9 FMAX 140 L Z-15.4 F233 141 L Y+49 142 L Z+9.6 FMAX 143 L X+14.1 Y+2.5 FMAX 144 L Z-7.9 FMAX 145 L Z-15.4 F233 146 L Y+49 147 L Z+9.6 FMAX 148 L X+15.1 Y+2.5 FMAX 149 L Z-7.9 FMAX 150 L Z-15.4 F233 151 L Y+49 152 L Z+9.6 FMAX 153 L X+16.1 Y+2.5 FMAX 154 L Z-7.9 FMAX 155 L Z-15.4 F233 156 L Y+49 157 L Z+9.6 FMAX 158 L X+17.1 Y+2.5 FMAX 159 L Z-7.9 FMAX 160 L Z-15.4 F233 161 L Y+49 162 L Z+9.6 FMAX 163 L X+18.1 Y+2.5 FMAX 164 L Z-7.9 FMAX 165 L Z-15.4 F233 166 L Y+49 167 L Z+9.6 FMAX 168 L X+19.1 Y+2.5 FMAX 169 L Z-7.9 FMAX 170 L Z-15.4 F233 171 L Y+49 172 L Z+9.6 FMAX 173 L X+20.1 Y+2.5 FMAX 174 L Z-7.9 FMAX 175 L Z-15.4 F233 176 L Y+49 177 L Z+9.6 FMAX 178 L X+21.1 Y+2.5 FMAX 179 L Z-7.9 FMAX 180 L Z-15.4 F233 181 L Y+49 182 L Z+9.6 FMAX 183 L X+22.1 Y+2.5 FMAX 184 L Z-7.9 FMAX 185 L Z-15.4 F233 186 L Y+49 187 L Z+9.6 FMAX 188 L X+23.1 Y+2.5 FMAX 189 L Z-7.9 FMAX 190 L Z-15.4 F233 191 L Y+49 192 L Z+9.6 FMAX 193 L X+24.1 Y+2.5 FMAX 194 L Z-7.9 FMAX 195 L Z-15.4 F233 196 L Y+49 197 L Z+9.6 FMAX 198 L X+25.1 Y+2.5 FMAX 199 L Z-7.9 FMAX 200 L Z-15.4 F233 201 L Y+49 202 L Z+9.6 FMAX 203 L X+26.1 Y+2.5 FMAX 204 L Z-7.9 FMAX 205 L Z-15.4 F233 206 L Y+49 207 L Z+9.6 FMAX 208 L X+27.1 Y+2.5 FMAX 209 L Z-7.9 FMAX 210 L Z-15.4 F233 211 L Y+49 212 L Z+9.6 FMAX 213 L X+28.1 Y+2.5 FMAX 214 L Z-7.9 FMAX 215 L Z-15.4 F233 216 L Y+49 217 L Z+9.6 FMAX 218 L X+29.1 Y+2.5 FMAX 219 L Z-7.9 FMAX 220 L Z-15.4 F233 221 L Y+49 222 L Z+9.6 FMAX 223 L X+30.1 Y+2.5 FMAX 224 L Z-7.9 FMAX 225 L Z-15.4 F233 226 L Y+49 227 L Z+9.6 FMAX 228 L X+31.1 Y+2.5 FMAX 229 L Z-7.9 FMAX 230 L Z-15.4 F233 231 L Y+49 232 L Z+9.6 FMAX 233 L X+32.1 Y+2.5 FMAX 234 L Z-7.9 FMAX 235 L Z-15.4 F233 236 L Y+49 237 L Z+9.6 FMAX 238 L X+33.1 Y+2.5 FMAX 239 L Z-7.9 FMAX 240 L Z-15.4 F233 241 L Y+49 242 L Z+9.6 FMAX 243 L X+34.1 Y+2.5 FMAX 244 L Z-7.9 FMAX 245 L Z-15.4 F233 246 L Y+49 247 L Z+9.6 FMAX 248 L X+35.1 Y+2.5 FMAX 249 L Z-7.9 FMAX 250 L Z-15.4 F233 251 L Y+49 252 L Z+9.6 FMAX 253 L X+36.1 Y+2.5 FMAX 254 L Z-7.9 FMAX 255 L Z-15.4 F233 256 L Y+49 257 L Z+9.6 FMAX 258 L X+37.1 Y+2.5 FMAX 259 L Z-7.9 FMAX 260 L Z-15.4 F233 261 L Y+49 262 L Z+9.6 FMAX 263 L X+38.1 Y+2.5 FMAX 264 L Z-7.9 FMAX 265 L Z-15.4 F233 266 L Y+49 267 L Z+9.6 FMAX 268 L X+39.1 Y+2.5 FMAX 269 L Z-7.9 FMAX 270 L Z-15.4 F233 271 L Y+49 272 L Z+9.6 FMAX 273 L X+40.1 Y+2.5 FMAX 274 L Z-7.9 FMAX 275 L Z-15.4 F233 276 L Y+49 277 L Z+9.6 FMAX 278 L X+40.6 Y+2.5 FMAX 279 L Z-7.9 FMAX 280 L Z-15.4 F233 281 L Y+49 282 L Z+16.1 FMAX 283 CYCL DEF 32.0 TOLERANCJA 284 CYCL DEF 32.1 285 M5 286 L Z-15 R0 FMAX M91 M9 287 L X+273 Y+529 R0 FMAX M91 288 M0 289 ; 290 * - FREZ PLASKI FI 20 R04 291 TOOL CALL 1 Z S1034 292 TOOL DEF 0 293 * - KOMPENSACJA WYMIARU 4.5 +/-0.05 294 ;FREZ PLASKI FI 20 R04 TOOL - 1 DIA. OFF. - 1 LEN. - 1 DIA. - 20. 295 ;HOLDER - DEFAULT HOLDER 296 CYCL DEF 32.0 TOLERANCJA 297 CYCL DEF 32.1 T0.003 298 CYCL DEF 32.2 HSC-MODE:0 299 L A+0 FMAX 300 M3 301 L X+10.7 Y+2.5 FMAX M8 302 L Z+16.1 FMAX 303 L Z-7.9 FMAX 304 L Z-15.5 F155 305 L Y+49 306 L Z+9.5 FMAX 307 L X+25.7 Y+2.5 FMAX 308 L Z-7.9 FMAX 309 L Z-15.5 F155 310 L Y+49 311 L Z+9.5 FMAX 312 L X+40.7 Y+2.5 FMAX 313 L Z-7.9 FMAX 314 L Z-15.5 F155 315 L Y+49 316 L Z+16.1 FMAX 317 L X+42.5 Y+2.5 FMAX 318 L Z-7.9 FMAX 319 L Z-12.4 F250 320 L Y+49 F186 321 L Z-10.4 FMAX 322 L Z-7.9 FMAX 323 L X+43.5 Y+2.5 FMAX 324 L Z-12.4 F250 325 L Y+49 F186 326 L Z-10.4 FMAX 327 L Z-7.9 FMAX 328 L X+44.5 Y+2.5 FMAX 329 L Z-12.4 F250 330 L Y+49 F186 331 L Z-10.4 FMAX 332 L Z-7.9 FMAX 333 L X+45.5 Y+2.5 FMAX 334 L Z-12.4 F250 335 L Y+49 F186 336 L Z-10.4 FMAX 337 L Z-7.9 FMAX 338 L X+46.5 Y+2.5 FMAX 339 L Z-12.4 F250 340 L Y+49 F186 341 L Z-10.4 FMAX 342 L Z-7.9 FMAX 343 L X+47.5 Y+2.5 FMAX 344 L Z-12.4 F250 345 L Y+49 F186 346 L Z-10.4 FMAX 347 L Z-7.9 FMAX 348 L X+48.5 Y+2.5 FMAX 349 L Z-12.4 F250 350 L Y+49 F186 351 L Z-10.4 FMAX 352 L Z-7.9 FMAX 353 L X+49.5 Y+2.5 FMAX 354 L Z-12.4 F250 355 L Y+49 F186 356 L Z-10.4 FMAX 357 L Z-7.9 FMAX 358 L X+50.5 Y+2.5 FMAX 359 L Z-12.4 F250 360 L Y+49 F186 361 L Z-10.4 FMAX 362 L Z-7.9 FMAX 363 L X+51.5 Y+2.5 FMAX 364 L Z-12.4 F250 365 L Y+49 F186 366 L Z-10.4 FMAX 367 L Z-7.9 FMAX 368 L X+52.5 Y+2.5 FMAX 369 L Z-12.4 F250 370 L Y+49 F186 371 L Z-10.4 FMAX 372 L Z-7.9 FMAX 373 L X+53.5 Y+2.5 FMAX 374 L Z-12.4 F250 375 L Y+49 F186 376 L Z-10.4 FMAX 377 L Z-7.9 FMAX 378 L X+54.5 Y+2.5 FMAX 379 L Z-12.4 F250 380 L Y+49 F186 381 L Z-10.4 FMAX 382 L Z-7.9 FMAX 383 L X+55.5 Y+2.5 FMAX 384 L Z-12.4 F250 385 L Y+49 F186 386 L Z-10.4 FMAX 387 L Z-7.9 FMAX 388 L X+56.5 Y+2.5 FMAX 389 L Z-12.4 F250 390 L Y+49 F186 391 L Z-10.4 FMAX 392 L Z-7.9 FMAX 393 L X+57.5 Y+2.5 FMAX 394 L Z-12.4 F250 395 L Y+49 F186 396 L Z-10.4 FMAX 397 L Z-7.9 FMAX 398 L X+58.5 Y+2.5 FMAX 399 L Z-12.4 F250 400 L Y+49 F186 401 L Z-10.4 FMAX 402 L Z-7.9 FMAX 403 L X+59.5 Y+2.5 FMAX 404 L Z-12.4 F250 405 L Y+49 F186 406 L Z-10.4 FMAX 407 L Z-7.9 FMAX 408 L X+60.5 Y+2.5 FMAX 409 L Z-12.4 F250 410 L Y+49 F186 411 L Z-10.4 FMAX 412 L Z-7.9 FMAX 413 L X+61.5 Y+2.5 FMAX 414 L Z-12.4 F250 415 L Y+49 F186 416 L Z-10.4 FMAX 417 L Z-7.9 FMAX 418 L X+62.5 Y+2.5 FMAX 419 L Z-12.4 F250 420 L Y+49 F186 421 L Z-10.4 FMAX 422 L Z-7.9 FMAX 423 L X+63.5 Y+2.5 FMAX 424 L Z-12.4 F250 425 L Y+49 F186 426 L Z-10.4 FMAX 427 L Z-7.9 FMAX 428 L X+64.5 Y+2.5 FMAX 429 L Z-12.4 F250 430 L Y+49 F186 431 L Z-10.4 FMAX 432 L Z-7.9 FMAX 433 L X+65.5 Y+2.5 FMAX 434 L Z-12.4 F250 435 L Y+49 F186 436 L Z-10.4 FMAX 437 L Z-7.9 FMAX 438 L X+66.5 Y+2.5 FMAX 439 L Z-12.4 F250 440 L Y+49 F186 441 L Z-10.4 FMAX 442 L Z-7.9 FMAX 443 L X+67.5 Y+2.5 FMAX 444 L Z-12.4 F250 445 L Y+49 F186 446 L Z-10.4 FMAX 447 L Z-7.9 FMAX 448 L X+68.5 Y+2.5 FMAX 449 L Z-12.4 F250 450 L Y+49 F186 451 L Z-10.4 FMAX 452 L Z-7.9 FMAX 453 L X+69.5 Y+2.5 FMAX 454 L Z-12.4 F250 455 L Y+49 F186 456 L Z-10.4 FMAX 457 L Z-7.9 FMAX 458 L X+70.5 Y+2.5 FMAX 459 L Z-12.4 F250 460 L Y+49 F186 461 L Z-10.4 FMAX 462 L Z-7.9 FMAX 463 L X+71.5 Y+2.5 FMAX 464 L Z-12.4 F250 465 L Y+49 F186 466 L Z-10.4 FMAX 467 L Z-7.9 FMAX 468 L X+72.5 Y+2.5 FMAX 469 L Z-12.4 F250 470 L Y+49 F186 471 L Z-10.4 FMAX 472 L Z-7.9 FMAX 473 L X+73.5 Y+2.5 FMAX 474 L Z-12.4 F250 475 L Y+49 F186 476 L Z-10.4 FMAX 477 L Z-7.9 FMAX 478 L X+74.5 Y+2.5 FMAX 479 L Z-12.4 F250 480 L Y+49 F186 481 L Z-10.4 FMAX 482 L Z-7.9 FMAX 483 L X+75.5 Y+2.5 FMAX 484 L Z-12.4 F250 485 L Y+49 F186 486 L Z-10.4 FMAX 487 L Z-7.9 FMAX 488 L X+76.5 Y+2.5 FMAX 489 L Z-12.4 F250 490 L Y+49 F186 491 L Z-10.4 FMAX 492 L Z-7.9 FMAX 493 L X+76.7 Y+2.5 FMAX 494 L Z-12.4 F250 495 L Y+49 F186 496 L Z+16.1 FMAX 497 ;TOOLPATH - FINISHFLOW 498 ;STOCK LEFT ON DRIVE SURFS = +0 499 ;STOCK LEFT ON CHECK SURFS = +.01 500 * - FREZ PLASKI FI 20 R04 - REPEAT 501 TOOL CALL 1 Z S1000 502 TOOL DEF 0 503 M3 504 M9 505 L X+41.7 Y+46 Z+12.2 FMAX 506 L Z-7.8 FMAX 507 L Z-12.8 F180 508 L Y+38 509 L Y+13.5 510 L Y+5.5 511 L Z-13.85 512 L Y+13.5 513 L Y+38 514 L Y+46 515 L Z-14.9 516 L Y+38 517 L Y+13.5 518 L Y+5.5 519 L Y+13.5 520 L Y+38 521 L Y+46 522 L X+41.694 523 L Z-14.987 524 L Y+38 525 L Y+13.5 526 L Y+5.5 527 L X+41.674 528 L Z-15.076 529 L Y+13.5 530 L Y+38 531 L Y+46 532 L X+41.638 533 L Z-15.165 534 L Y+38 535 L Y+13.5 536 L Y+5.5 537 L X+41.588 538 L Z-15.249 539 L Y+13.5 540 L Y+38 541 L Y+46 542 L X+41.524 543 L Z-15.324 544 L Y+38 545 L Y+13.5 546 L Y+5.5 547 L X+41.449 548 L Z-15.388 549 L Y+13.5 550 L Y+38 551 L Y+46 552 L X+41.365 553 L Z-15.438 554 L Y+38 555 L Y+13.5 556 L Y+5.5 557 L X+41.276 558 L Z-15.474 559 L Y+13.5 560 L Y+38 561 L Y+46 562 L X+41.187 563 L Z-15.494 564 L Y+38 565 L Y+13.5 566 L Y+5.5 567 L X+41.1 568 L Z-15.5 569 L Y+13.5 570 L Y+38 571 L Y+46 572 L Z-10.5 FMAX 573 L Z+9.5 FMAX 574 CYCL DEF 32.0 TOLERANCJA 575 CYCL DEF 32.1 576 M5 577 L Z-15 R0 FMAX M91 578 L X+273 Y+529 R0 FMAX M91 579 M0 580 ; 581 * - FREZ PLASKI FI 20 R04 582 TOOL CALL 1 Z S1034 583 TOOL DEF 0 584 * - WYSOKO NA GOTOWO 9.4-0.05 585 ;FREZ PLASKI FI 20 R04 TOOL - 1 DIA. OFF. - 1 LEN. - 1 DIA. - 20. 586 ;HOLDER - DEFAULT HOLDER 587 CYCL DEF 32.0 TOLERANCJA 588 CYCL DEF 32.1 T0.003 589 CYCL DEF 32.2 HSC-MODE:0 590 L A+0 FMAX 591 M3 592 L X+91.7 Y+2.5 FMAX M8 593 L Z+16.1 FMAX 594 L Z-7.9 FMAX 595 L Z-9.375 F233 596 L Y+49 597 L Z+15.625 FMAX 598 L X+101.7 Y+2.5 FMAX 599 L Z-7.9 FMAX 600 L Z-9.375 F233 601 L Y+49 602 L Z+15.625 FMAX 603 L X+91.7 Y+2.5 FMAX 604 L Z-8.375 FMAX 605 L Z-9.425 F233 606 L Y+49 607 L Z+15.575 FMAX 608 L X+101.7 Y+2.5 FMAX 609 L Z-8.375 FMAX 610 L Z-9.425 F233 611 L Y+49 612 L Z+16.1 FMAX 613 CYCL DEF 32.0 TOLERANCJA 614 CYCL DEF 32.1 615 M5 616 L Z-15 R0 FMAX M91 M9 617 L X+273 Y+529 R0 FMAX M91 618 M0 619 ; 620 * - FREZ PLASKI FI 8 621 TOOL CALL 3 Z S2586 622 TOOL DEF 0 623 * - ZGRUBNIE 624 ;FREZ PLASKI FI 8 TOOL - 3 DIA. OFF. - 3 LEN. - 3 DIA. - 8. 625 ;HOLDER - DEFAULT HOLDER 626 CYCL DEF 32.0 TOLERANCJA 627 CYCL DEF 32.1 T0.003 628 CYCL DEF 32.2 HSC-MODE:0 629 L A+0 FMAX 630 M3 631 L X+96.7 Y+43 FMAX M8 632 L Z+16.1 FMAX 633 L Z-7.9 FMAX 634 L Z-9.775 F207 635 L Y+8.5 636 L Y+43 637 L Z-10.65 638 L Y+8.5 639 L Y+43 640 L Z-11.525 641 L Y+8.5 642 L Y+43 643 L Z-12.4 644 L Y+8.5 645 L Z+16.1 FMAX 646 CYCL DEF 32.0 TOLERANCJA 647 CYCL DEF 32.1 648 M5 649 L Z-15 R0 FMAX M91 M9 650 L X+273 Y+529 R0 FMAX M91 651 M0 652 ; 653 * - FREZ PLASKI FI 8 654 TOOL CALL 3 Z S1400 655 TOOL DEF 0 656 * - KOMPENSACJA 657 ;FREZ PLASKI FI 8 TOOL - 3 DIA. OFF. - 3 LEN. - 3 DIA. - 8. 658 ;HOLDER - DEFAULT HOLDER 659 CYCL DEF 32.0 TOLERANCJA 660 CYCL DEF 32.1 T0.003 661 CYCL DEF 32.2 HSC-MODE:0 662 L A+0 FMAX 663 M3 664 L X+97.088 Y+43 FMAX M8 665 L Z+15.6 FMAX 666 L Z-8.4 FMAX 667 L Z-12.4 F160 668 L X+92.688 RL 669 L Y+8.5 670 L X+97.088 R0 671 L Z+15.6 FMAX 672 CYCL DEF 32.0 TOLERANCJA 673 CYCL DEF 32.1 674 M5 675 L Z-15 R0 FMAX M91 M9 676 L X+273 Y+529 R0 FMAX M91 677 M0 678 ; 679 * - FREZ PLASKI FI 8 680 TOOL CALL 3 Z S1400 681 TOOL DEF 0 682 * - KOMPENSACJA 683 ;FREZ PLASKI FI 8 TOOL - 3 DIA. OFF. - 3 LEN. - 3 DIA. - 8. 684 ;HOLDER - DEFAULT HOLDER 685 CYCL DEF 32.0 TOLERANCJA 686 CYCL DEF 32.1 T0.003 687 CYCL DEF 32.2 HSC-MODE:0 688 L A+0 FMAX 689 M3 690 L X+96.312 Y+8.5 FMAX M8 691 L Z+15.6 FMAX 692 L Z-8.4 FMAX 693 L Z-12.4 F160 694 L X+100.712 RL 695 L Y+43 696 L X+96.312 R0 697 L Z+15.6 FMAX 698 CYCL DEF 32.0 TOLERANCJA 699 CYCL DEF 32.1 700 M5 701 L Z-15 R0 FMAX M91 M9 702 L X+273 Y+529 R0 FMAX M91 703 L A+0 FMAX M91 704 M2 705 END PGM sd_5458_02_01_B MM <file_sep>/cnc programming/Heidenhain/FAZ.H 0 BEGIN PGM FAZ MM 1 BLK FORM 0.1 Z X-10 Y-10 Z-10 2 BLK FORM 0.2 X+10 Y+10 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 R0 FMAX 7 TOOL CALL 30 Z 8 TOOL DEF 9 9 ; 10 ; 11 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 12 ;--------------------------------------------- 13 ; 14 * - fazy 1x45 (faz-90st) 15 TOOL CALL 26 Z S4000 F120 / 16 STOP 17 TOOL DEF 30 18 L M3 M8 19 ; 20 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+20 ;SREDNICA NOMINALNA ~ Q342=+19 ;WYW.WSTEP. SREDNICA ~ Q351=-1 ;<NAME> 21 ; 22 CALL LBL 1 23 M5 M9 24 ; 25 ;--------------------------------------------- 26 L Z+0 R0 FMAX M91 / 27 L X+260 Y+535 R0 FMAX M91 28 L X+100 Y+365 R0 FMAX 29 L M30 30 * - ----------------------------------------- 31 * - LBL1 FAZA 32 LBL 1 33 M3 34 L X+0 Y+0 R0 FMAX M99 35 LBL 0 36 END PGM FAZ MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/FAZA-CZOP.H 0 BEGIN PGM FAZA-CZOP MM 1 BLK FORM 0.1 Z X-96 Y-56 Z-24 2 BLK FORM 0.2 X+96 Y+56 Z+1 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 ; 5 TOOL CALL 9 Z S9999 F666 DR-2 6 L Z+300 R0 FMAX M3 M8 7 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+180 ;DLUG. 1-SZEJ STRONY ~ Q424=+180 ;WYMIAR POLWYROBU 1 ~ Q219=+100 ;DLUG. 2-GIEJ STRONY ~ Q425=+100 ;WYMIAR POLWYROBU 2 ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-2.4 ;GLEBOKOSC ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 8 L X+0 Y+0 R0 FMAX M99 9 L Z+300 R0 FMAX 10 L Y+535 X+0 R0 FMAX 11 M30 12 END PGM FAZA-CZOP MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/PRZYRZAD.h 0 BEGIN PGM PRZYRZAD MM 1 BLK FORM 0.1 Z X-54 Y-54 Z-13 2 BLK FORM 0.2 X+54 Y+54 Z+0 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 STOP / 5 TOOL CALL 30 Z / 6 TCH PROBE 412 PKT.BAZ.OKRAG WEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+74 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-3.5 ;WYSOKOSC POMIARU ~ Q320=+5 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+28 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+0 ;RODZAJ PRZEMIESZCZ. 7 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 8 ; 9 * - naw-10-stal 10 TOOL CALL 9 Z S1200 F100 11 TOOL DEF 13 12 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 13 M8 14 CALL LBL 1 15 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 16 M8 17 CALL LBL 2 18 M5 M9 19 ; 20 * - w-3.8 21 TOOL CALL 17 Z S2000 F100 22 TOOL DEF 17 23 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 24 M8 25 CALL LBL 1 26 M5 M9 27 ; 28 * - w-3.3 29 TOOL CALL 21 Z S1800 F100 30 TOOL DEF 27 31 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 32 M8 33 CALL LBL 2 34 M5 M9 35 ; 36 * - r-4 37 TOOL CALL 3 Z S150 F30 38 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+300 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 39 CALL LBL 1 40 M5 M9 41 ; 42 * - GW-M4 43 TOOL CALL 16 Z S120 44 TOOL DEF 27 45 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC GWINTU ~ Q239=+0.7 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 46 M8 47 CALL LBL 2 48 M5 M9 49 ; 50 ; 51 L Z+0 R0 FMAX M91 52 L X+260 Y+535 R0 FMAX M91 53 L M30 54 ; 55 LBL 1 56 M13 57 L X-28.8 Y+49.8 R0 FMAX M99 58 L X+28.8 Y+49.8 R0 FMAX M99 59 LBL 0 60 LBL 2 61 M13 62 L X-46.3 Y+38.9 R0 FMAX M99 63 L X+46.3 Y+38.9 R0 FMAX M99 64 LBL 0 65 END PGM PRZYRZAD MM <file_sep>/cnc programming/Heidenhain/JF/PODZIALY/PODZIAL-ODP.H 0 BEGIN PGM PODZIAL-ODP MM 1 BLK FORM 0.1 Z X-60 Y-60 Z+0 2 BLK FORM 0.2 X+60 Y+60 Z+11 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 L X+0 Y+0 FMAX 6 ; 7 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 8 CYCL DEF 7.0 PUNKT BAZOWY 9 CYCL DEF 7.1 IZ-7 10 ;--------------------------------------------- 11 ; 12 * - FP-4 13 TOOL CALL 23 Z S3500 F150 DR+0 / 14 STOP 15 TOOL DEF 11 16 M3 M8 17 L X-30 Y-7 FMAX 18 L Z-1 FMAX 19 ; 20 L Y-1.5 R0 F AUTO 21 L X-38 F AUTO 22 L Z+50 FMAX / 23 M5 M9 24 ; 25 ; 26 * - FP-4 27 TOOL CALL 23 Z S3500 F150 DR+0 / 28 STOP 29 TOOL DEF 11 30 M3 M8 31 L X-30 Y-7 FMAX 32 L Z-1 FMAX 33 ; 34 L Y-1 R0 F AUTO 35 L X-38 F AUTO 36 L Z+50 FMAX / 37 M5 M9 38 ; 39 ; 40 * - FP-4 41 TOOL CALL 23 Z S3500 F150 DR+0 / 42 STOP 43 TOOL DEF 11 44 M3 M8 45 L X+38 Y-7 FMAX 46 L Z-1 FMAX 47 ; 48 L Y-1.5 R0 F AUTO 49 L X+30 F AUTO 50 L Z+50 FMAX / 51 M5 M9 52 ; 53 ; 54 * - FP-4 55 TOOL CALL 23 Z S3500 F150 DR+0 / 56 STOP 57 TOOL DEF 11 58 M3 M8 59 L X+38 Y-7 FMAX 60 L Z-1 FMAX 61 ; 62 L Y-1 R0 F AUTO 63 L X+30 F AUTO 64 L Z+50 FMAX 65 M5 M9 66 ; 67 ;--------------------------------------------- 68 L Z-5 R0 FMAX M91 69 L X+360 Y+535 R0 FMAX M91 70 L M30 71 * - ----------------------------------------- 72 ; 73 END PGM PODZIAL-ODP MM <file_sep>/cnc programming/Heidenhain/JF/WALEK-DYST-SUR-PROG/1-STRONA.H 0 BEGIN PGM 1-STRONA MM 1 BLK FORM 0.1 Z X-62 Y-62 Z-36 2 BLK FORM 0.2 X+62 Y+62 Z+0 3 CALL PGM TNC:\Z19 4 CALL PGM TNC:\REF 5 ; 6 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 7 PLANE RESET TURN F2500 8 ;--------------------------------- 9 ; 10 * - CZOP ZGR / 11 STOP 12 TOOL CALL 2 Z S5600 F2400 DR+0.2 13 M3 M8 14 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-32 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+32 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+120 ;SREDNICA WST.OBR.WYB ~ Q223=+119 ;SRED.WYBR.OBR.NA GOT 15 CALL LBL 1 16 M5 M9 17 ; 18 * - CZOP WYK 19 TOOL CALL 2 Z S5600 F2400 DR+0 / 20 STOP 21 M3 M8 22 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-32 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+32 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+120 ;SREDNICA WST.OBR.WYB ~ Q223=+119 ;SRED.WYBR.OBR.NA GOT 23 CALL LBL 1 24 M5 M9 25 ; 26 * - 80H7 ZGR 27 TOOL CALL 3 Z S16987 F5000 / 28 STOP 29 M13 30 CYCL DEF 252 WYBRANIE KOLOWE ~ Q215=+0 ;<NAME> ~ Q223=+79.8 ;SREDNICA OKREGU ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-8.8 ;GLEBOKOSC ~ Q202=+8.8 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+1000 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+0.5 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385=+500 ;POSUW OBR.WYKAN. 31 CALL LBL 1 32 M5 M9 33 ; 34 * - GLEBOKOSC NA GOTOWO 35 TOOL CALL 3 Z S16987 F3000 DL+0.025 / 36 STOP 37 M13 38 CYCL DEF 252 WYBRANIE KOLOWE ~ Q215=+0 ;RODZAJ OBROBKI ~ Q223=+79.8 ;SREDNICA OKREGU ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-9 ;GLEBOKOSC ~ Q202=+9 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+1000 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385=+500 ;POSUW OBR.WYKAN. 39 CALL LBL 1 40 M5 M9 41 ; 42 * - 80H7 NA GOTOWO 43 TOOL CALL 3 Z S16987 F1500 DL+0.025 DR-0.002 / 44 STOP 45 M13 46 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+3 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+80 ;SREDNICA NOMINALNA ~ Q342=+79.8 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 47 CALL LBL 1 48 M5 M9 49 ; 50 * - W 6.6 VHM 51 TOOL CALL 25 Z S4818 F829 / 52 STOP 53 M13 54 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-22 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+22 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 55 CALL LBL 2 56 M5 M9 57 ; 58 * - W 8 VHM 59 TOOL CALL 17 Z S3975 F795 / 60 STOP 61 M13 62 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-30 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+30 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-9 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 63 CALL LBL 3 64 M5 M9 65 ; 66 * - W 3.2 67 TOOL CALL 26 Z S9938 F1034 / 68 STOP 69 M13 70 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+8 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-9 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 71 CALL LBL 4 72 M5 M9 73 ; 74 * - FAZY 75 TOOL CALL 30 Z S12000 F200 / 76 STOP 77 M13 78 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 79 CALL LBL 2 80 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-4 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-9 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 81 CALL LBL 3 82 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.6 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-9 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 83 CALL LBL 4 84 M5 M9 85 ; 86 * - FAZA 80H7 87 TOOL CALL 30 Z S12000 F2000 DR-1 / 88 STOP 89 M13 90 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+80 ;SREDNICA NOMINALNA ~ Q342=+79.8 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;RODZAJ FREZOWANIA 91 CALL LBL 1 / 92 M5 M9 93 ; 94 * - FAZA 119 95 TOOL CALL 30 Z S12000 F2000 DR-1 / 96 STOP 97 M3 M8 98 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+120 ;SREDNICA WST.OBR.WYB ~ Q223=+119 ;SRED.WYBR.OBR.NA GOT 99 CALL LBL 1 100 M5 M9 101 ; 102 ;--------------------------------- 103 CALL PGM TNC:\REF 104 CALL PGM TNC:\Z19 105 L M30 106 * - ------------------------------ 107 ; 108 * - LBL1 SRODEK 109 LBL 1 110 L M3 111 L X+0 Y+0 FMAX M99 112 LBL 0 113 ; 114 * - LBL2 6.6 115 LBL 2 116 L M3 117 L X-15 Y-46.1 FMAX M99 118 L X-48.5 Y+0 FMAX M99 119 L X-15 Y+46.1 FMAX M99 120 L X+39.2 Y+28.5 FMAX M99 121 L X+39.2 Y-28.5 FMAX M99 122 LBL 0 123 ; 124 * - LBL3 8 125 LBL 3 126 L M3 127 L X-27.6 Y+11.8 FMAX M99 128 L X-27.6 Y-11.8 FMAX M99 129 LBL 0 130 ; 131 * - LBL4 3.2 132 LBL 4 133 L M3 134 L X-24 Y+20 FMAX M99 135 LBL 0 136 ; 137 END PGM 1-STRONA MM <file_sep>/cnc programming/Heidenhain/SPLASZCZENIE-WALEK-2.H 0 BEGIN PGM SPLASZCZENIE-WALEK-2 MM 1 BLK FORM 0.1 Z X-49.5 Y-100 Z-36 2 BLK FORM 0.2 X+49.5 Y+100 Z+36 3 ;------------------------------------------- 4 ; USTAW BAZE W OSI Y DOKLADNIE PO SRODKU SPLASZCZENIA ( SRODEK MOSTKA ) 5 ; USTAW "Z" W OSI DETALU 6 ; USTAW BAZE W OSI X NA SRODKU DETALU 7 ; WYSUNIECIE NARZEDZIA - 82mm 8 ;------------------------------------------- 9 STOP 10 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 11 L X+0 Y+0 R0 FMAX 12 * - SONDA / 13 TOOL CALL 30 Z S50 / 14 TOOL DEF 16 / 15 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+50 ;SRODEK W 1-SZEJ OSI ~ Q322=+50 ;SRODEK W 2-SZEJ OSI ~ Q311=+15 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=+0 ;WYSOKOSC POMIARU ~ Q320=+0 ;BEZPIECZNA WYSOKOSC ~ Q260=+100 ;BEZPIECZNA WYSOKOSC ~ Q305=+Q2 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 16 ; 17 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 18 ;------------------------------------------- 19 STOP 20 ; WPISZ PONIZEJ SZEROKOSC MOSTKA W MIEJSCU SPLASZCZENIA ( W OSI Y ) JAKO~ WARTOSC Q2, ZAOKRAGLAJAC DO DWOCH MIEJSC PO PRZECINKU 21 ; 22 Q2 = 100 ; DLUGOSC WYBRANIA / 23 Q2 = - 1 ; DLUGOSC WYBRANIA 24 Q3 = Q2 / 2 ; POLOWA DLUGOSCI 25 Q5 = Q3 - 14 ; SCIANKA - LUK 26 ; 27 STOP 28 * - GLOWICA-20-ALU 29 TOOL CALL 16 Z S15000 F1800 30 TOOL DEF 30 31 M3 M8 32 L X-50 Y-Q3 FMAX 33 L Z+60 FMAX 34 L Z+30 F1800 35 ; 36 CALL LBL 10 37 ; 38 ; 39 CALL LBL 10 REP61 40 M5 M9 41 ; 42 ;-------------------------------------- 43 L Z+0 R0 FMAX M91 44 L X+100 Y+535 R0 FMAX 45 L M30 46 * - ----------------------------------- 47 ; 48 ; 49 LBL 10 50 L IZ-1 51 L X-50 Y-Q3 RR F AUTO M3 52 L X-34 53 CC X-34 Y-Q5 54 C X-20 Y-Q5 DR+ 55 L Y+Q5 56 CC X-34 Y+Q5 57 C X-34 Y+Q3 DR+ 58 L X-50 59 L Z+100 R0 FMAX 60 LBL 0 61 L 62 END PGM SPLASZCZENIE-WALEK-2 MM <file_sep>/cnc programming/Heidenhain/JF/AD/N031.01/GAB.H 0 BEGIN PGM GAB MM 1 BLK FORM 0.1 Z X-41 Y-12 Z-40 2 BLK FORM 0.2 X+41 Y+12 Z+0.5 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO / 5 STOP 6 L X+0 Y+0 R0 FMAX 7 ;--------------------------------------------- 8 ; / 9 STOP 10 TOOL CALL 30 Z S50 11 TOOL DEF 6 12 ; 13 TCH PROBE 411 PKT.BAZ.PROST.ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+11 ;SRODEK W 2-SZEJ OSI ~ Q323=+102 ;DLUG. 1-SZEJ STRONY ~ Q324=+28 ;DLUG. 2-GIEJ STRONY ~ Q261=-5 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+1 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 14 ; 15 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 16 ; / 17 STOP 18 * - PLAN-ZGR 19 TOOL CALL 6 Z S2222 F400 20 M3 M7 21 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-55 ;PKT.STARTU 1SZEJ OSI ~ Q226=-11 ;PKT.STARTU 2GIEJ OSI ~ Q227=+4 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.15 ;PUNKT KONCOWY 3. OSI ~ Q218=+104 ;DLUG. 1-SZEJ STRONY ~ Q219=+30 ;DLUG. 2-GIEJ STRONY ~ Q202=+4 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 22 CYCL CALL 23 M5 M9 24 ; 25 * - GAB-ZGR 26 TOOL CALL 14 Z S2000 F700 / 27 STOP 28 M3 M8 29 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+80 ;DLUG. 1-SZEJ STRONY ~ Q424=+101 ;WYMIAR POLWYROBU 1 ~ Q219=+22 ;DLUG. 2-GIEJ STRONY ~ Q425=+27 ;WYMIAR POLWYROBU 2 ~ Q220=+0.1 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-33 ;GLEBOKOSC ~ Q202=+0.6 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.4 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 30 L X+0 Y+0 R0 FMAX M99 31 M5 M9 32 ; 33 * - PLAN-WYK 34 TOOL CALL 24 Z S3000 F400 / 35 STOP 36 M3 M7 37 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-45 ;PKT.STARTU 1SZEJ OSI ~ Q226=-11 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.15 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+85 ;DLUG. 1-SZEJ STRONY ~ Q219=+30 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.05 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 38 CYCL CALL 39 M5 M9 40 ; 41 * - GAB-WYK 42 TOOL CALL 5 Z S3000 F400 DR-0.02 / 43 STOP 44 M3 M7 45 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+80 ;DLUG. 1-SZEJ STRONY ~ Q424=+81 ;WYMIAR POLWYROBU 1 ~ Q219=+22 ;DLUG. 2-GIEJ STRONY ~ Q425=+23 ;WYMIAR POLWYROBU 2 ~ Q220=+0.1 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-33 ;GLEBOKOSC ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.4 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 46 L X+0 Y+0 R0 FMAX M99 47 M5 M9 48 ; 49 L Z-5 R0 FMAX M91 50 L X+200 Y+535 R0 FMAX M91 / 51 STOP 52 CALL PGM TNC:\JF\AD\N031.01\STR-Z-WYBRANIEM.h 53 L M30 54 END PGM GAB MM <file_sep>/cnc programming/Heidenhain/JF/CHWYTAKI/PLANOWANIE.h 0 BEGIN PGM PLANOWANIE MM 1 BLK FORM 0.1 Z X-50 Y-50 Z-13 2 BLK FORM 0.2 X+50 Y+50 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; / 6 STOP 7 TOOL CALL 30 Z S50 8 TOOL DEF 22 9 ; 10 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+0 ;1.PKT POMIAROW 1.OSI ~ Q264=-12 ;1.PKT 2.OSI ~ Q261=-5 ;WYSOKOSC POMIARU ~ Q320=+20 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q272=+1 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 11 ; 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 ; 14 ;--------------------------------------------- 15 ; 16 * - FP8 WYK 17 TOOL CALL 22 Z S3000 F600 / 18 STOP 19 TOOL DEF 29 20 M3 M8 21 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=+0 ;PKT.STARTU 1SZEJ OSI ~ Q226=+2 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.15 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+106 ;DLUG. 1-SZEJ STRONY ~ Q219=-28 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.15 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385=+500 ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 22 CYCL CALL 23 M5 M9 24 ; 25 ;--------------------------------------------- 26 L Z-5 R0 FMAX M91 27 L X+260 Y+535 R0 FMAX M91 28 ; / 29 STOP 30 CALL PGM TNC:\5458-sd\CHWYTAKI\sd_5458_02_01_lewy.h 31 ; / 32 STOP 33 CALL PGM TNC:\5458-sd\CHWYTAKI\M5-CHWYTAKI-PCO.h 34 ; 35 L M30 36 * - ----------------------------------------- 37 END PGM PLANOWANIE MM <file_sep>/cnc programming/Heidenhain/JF/PLYTY/GAB.H 0 BEGIN PGM GAB MM 1 BLK FORM 0.1 Z X-400 Y-150 Z-35 2 BLK FORM 0.2 X+400 Y+150 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IZ+0 7 ;ZGR 8 STOP 9 TOOL CALL 29 Z S9999 F1500 10 M8 M3 11 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+250 ;DLUG. 1-SZEJ STRONY ~ Q424=+256 ;WYMIAR POLWYROBU 1 ~ Q219=+130 ;DLUG. 2-GIEJ STRONY ~ Q425=+136 ;WYMIAR POLWYROBU 2 ~ Q220=+0.1 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-28.4 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+10 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.4 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 12 CALL LBL 1 13 M5 M9 14 ;WYK 15 STOP M0 16 TOOL CALL 29 Z S9999 F1500 DR-0.02 17 M8 M3 18 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+250 ;DLUG. 1-SZEJ STRONY ~ Q424=+251 ;WYMIAR POLWYROBU 1 ~ Q219=+130 ;DLUG. 2-GIEJ STRONY ~ Q425=+131 ;WYMIAR POLWYROBU 2 ~ Q220=+0.1 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-28.4 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+10 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.4 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 19 CALL LBL 1 20 M5 M9 21 L Z-5 R0 FMAX M91 22 L X+260 Y+535 R0 FMAX M91 23 L M30 24 * - ----------------------------------------- 25 * - LBL1 26 LBL 1 27 M3 28 L X+0 Y+0 R0 FMAX M99 29 LBL 0 30 END PGM GAB MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/kula.h 0 BEGIN PGM kula MM 1 BLK FORM 0.1 Z X-25 Y-25 Z-100 2 BLK FORM 0.2 X+25 Y+25 Z+0 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 TOOL CALL 4 Z S9999 F1000 5 M3 M8 6 L Z+300 R0 FMAX 7 L X+0 Y+0 R0 FMAX 8 L Z+5 R0 FMAX 9 L Z+5 R0 F AUTO 10 LBL 1 11 CYCL DEF 10.0 OBROT 12 CYCL DEF 10.1 IROT+1 13 CR X+25 Z-25 R+25 DR+ F AUTO 14 L Z+0 R0 FMAX 15 L X+0 16 LBL 0 17 CALL LBL 1 REP360 18 L Z+300 FMAX 19 L Y+300 R0 FMAX 20 STOP M30 21 END PGM kula MM <file_sep>/cnc programming/Heidenhain/JF/AD/N030.02/P-ZBIORCZY.H 0 BEGIN PGM P-ZBIORCZY MM 1 BLK FORM 0.1 Z X-140 Y-100 Z-18 2 BLK FORM 0.2 X+140 Y+100 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 L X+0 Y+0 R0 FMAX 6 ;--------------------------------------------- 7 * - UWAGA NA SCIEZKE ! 8 ; 9 STOP 10 CALL PGM TNC:\5772-AD\N030.02\90H7-ZGR-60mm.H 11 STOP 12 CALL PGM TNC:\5772-AD\N030.02\90H7-ZGR60mm.H 13 STOP 14 CALL PGM TNC:\5772-AD\N030.02\fi104.H 15 STOP 16 CALL PGM TNC:\5772-AD\N030.02\90H7-WYK-60mm.H 17 STOP 18 CALL PGM TNC:\5772-AD\N030.02\90H7-WYK60mm.H 19 STOP 20 CALL PGM TNC:\5772-AD\N030.02\90H7-WYK.H 21 STOP 22 CALL PGM TNC:\5772-AD\N030.02\WYK-60mm.H 23 STOP 24 CALL PGM TNC:\5772-AD\N030.02\WYK60mm.H 25 ; 26 ;--------------------------------------------- 27 L Z+0 R0 FMAX M91 28 L X+260 Y+535 R0 FMAX M91 29 L M30 30 * - ----------------------------------------- 31 END PGM P-ZBIORCZY MM <file_sep>/cnc programming/Heidenhain/JF/WKLADKA-WYMIENNA/op-1_2.H 0 BEGIN PGM op-1_2 MM 1 BLK FORM 0.1 Z X-13 Y-11.5 Z-14 2 BLK FORM 0.2 X+13 Y+11.5 Z+0 3 STOP 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; / 6 TOOL CALL 30 Z S50 / 7 TOOL DEF 29 / 8 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+20 ;SRODEK W 1-SZEJ OSI ~ Q322=+3.5 ;SRODEK W 2-SZEJ OSI ~ Q311=+55 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-3 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 9 ; 10 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO / 11 STOP 12 ; 13 TOOL CALL 29 Z S7000 F2000 DL-0.2 14 L Z+300 R0 FMAX M3 M8 15 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-28 ;PKT.STARTU 1SZEJ OSI ~ Q226=-13 ;PKT.STARTU 2GIEJ OSI ~ Q227=+3.1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+60 ;DLUG. 1-SZEJ STRONY ~ Q219=+30 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+10 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 16 CYCL CALL 17 ; / 18 STOP 19 ; 20 TOOL CALL 29 Z S7000 F2000 DL-0.2 21 TOOL DEF 6 22 L Z+300 R0 FMAX M3 M8 23 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-28 ;PKT.STARTU 1SZEJ OSI ~ Q226=-13 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+60 ;DLUG. 1-SZEJ STRONY ~ Q219=+30 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+10 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 24 CYCL CALL 25 ; 26 L Z+300 R0 FMAX 27 ; 28 TOOL CALL 6 Z S6000 F999 / 29 STOP 30 ; 31 M3 M8 32 L Z+300 R0 FMAX 33 L X+40 Y-15 R0 FMAX 34 L Z+5 R0 FMAX 35 L Z+0 R0 F AUTO 36 LBL 2 37 L IZ-1 R0 FMAX 38 L Y-10.5 RL 39 L X-21 40 RND R3.5 41 L Y+10.5 42 RND R3.5 43 L X+3 44 L Y-15 45 L X+14 R0 46 L Y+15 47 L X+24 48 L Y-15 49 L X+40 R0 50 LBL 0 51 CALL LBL 2 REP11 52 L Z+300 FMAX 53 ; / 54 STOP 55 ; 56 TOOL CALL 6 Z S6000 F999 DR-0.027 57 TOOL DEF 30 58 M3 M8 59 L Z+300 R0 FMAX 60 L X+40 Y-15 R0 FMAX 61 L Z+5 R0 FMAX 62 L Z+0 R0 F AUTO 63 LBL 3 64 L IZ-2 R0 FMAX 65 L Y-10.5 RL 66 L X-21 67 RND R3.5 68 L Y+10.5 69 RND R3.5 70 L X+3 71 L Y-15 72 L X+40 R0 73 LBL 0 74 CALL LBL 3 REP5 75 L Z+300 FMAX 76 ; / 77 STOP 78 ; 79 TOOL CALL 30 Z S50 80 STOP 81 TOOL DEF 9 82 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=-38 ;1.PKT POMIAROW 1.OSI ~ Q264=+0 ;1.PKT 2.OSI ~ Q261=-3 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q272=+1 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 83 ; 84 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 85 ; 86 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+10 ;1.PKT POMIAROW 1.OSI ~ Q264=-13 ;1.PKT 2.OSI ~ Q261=-3 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q272=+2 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 87 ; 88 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 89 ; 90 * - NAW-8 91 TOOL CALL 9 Z S1000 F100 / 92 STOP 93 TOOL DEF 17 94 M8 95 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 96 CALL LBL 1 97 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.8 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 98 CALL LBL 4 99 M5 M9 100 ; 101 * - W-5.5 102 TOOL CALL 17 Z S1500 F120 / 103 STOP 104 TOOL DEF 19 105 M8 M3 106 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-13 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 107 CALL LBL 4 108 M5 M9 109 ; 110 * - F4-O5H7 111 TOOL CALL 19 Z S5000 F300 DL-0.08 DR-0.029 / 112 STOP 113 TOOL DEF 30 114 M8 115 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-7.05 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.45 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q335=+5 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME>REZOWANIA 116 CALL LBL 1 117 M5 M9 118 ; 119 ;--------------------------------------------- 120 L Z+0 R0 FMAX M91 121 L X+260 Y+535 R0 FMAX M91 122 L M30 123 * - ----------------------------------------- 124 * - LBL1 - 5H7 125 LBL 1 126 M3 127 L X+5 Y+14 R0 FMAX M99 128 LBL 0 129 * - LBL4 - 5.5 130 LBL 4 131 M3 132 L X+15 Y+14 R0 FMAX M99 133 LBL 0 134 END PGM op-1_2 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/OTW-M5.H 0 BEGIN PGM OTW-M5 MM 1 BLK FORM 0.1 Z X-161 Y-36 Z-10 2 BLK FORM 0.2 X+70 Y+80.4 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 * - NAW 8 8 TOOL CALL 3 Z S650 F30 9 TOOL DEF 20 10 M8 11 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 12 CALL LBL 1 13 M5 M9 14 ; 15 * - W 4.2 16 TOOL CALL 20 Z S800 F30 17 TOOL DEF 9 18 M8 19 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 CALL LBL 1 21 M5 M9 22 ; 23 * - NAW 8 24 TOOL CALL 9 Z S600 F50 / 25 STOP 26 TOOL DEF 1 27 M8 28 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 29 CALL LBL 1 30 M5 M9 31 ; 32 * - M-5 33 TOOL CALL 1 Z S120 34 STOP 35 TOOL DEF 30 36 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-13 ;GLEBOKOSC GWINTU ~ Q239=+0.8 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 37 CALL LBL 1 38 M5 M9 39 ; 40 ;--------------------------------------------- 41 L Z+0 R0 FMAX M91 42 L X+260 Y+535 R0 FMAX M91 43 L X+160 R0 FMAX 44 L M30 45 * - ----------------------------------------- 46 * - LBL1 M5 47 LBL 1 48 M3 49 L X-154.8 Y+65.9 R0 FMAX M99 50 L X-134.8 Y+65.9 R0 FMAX M99 51 LBL 0 52 END PGM OTW-M5 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/K00BKI/kubki-sd-sonda.h 0 BEGIN PGM kubki-sd-sonda MM 1 ; 2 BLK FORM 0.1 Z X+0 Y-90 Z-75 3 BLK FORM 0.2 X+241 Y+90 Z+0 4 CALL PGM TNC:\Z19 5 CALL PGM TNC:\REF 6 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 7 PLANE RESET TURN F3000 8 ; 9 * - para 1: ustawianie plaszczyzny (sonda) 10 TOOL CALL 1 Z S50 11 CYCL DEF 7.0 PUNKT BAZOWY 12 CYCL DEF 7.1 X+36.1 13 TCH PROBE 431 POMIAR PLASZCZYZNY ~ Q263=+7 ;1.PKT POMIAROW 1.OSI ~ Q264=-63 ;1.PKT 2.OSI ~ Q294=+0 ;1.PKT 3.OSI ~ Q265=+12 ;2-GI PUNKT W 1. OSI ~ Q266=-63 ;2-GI PUNKT W 2. OSI ~ Q295=+0 ;2-GI PUNKT W 3. OSI ~ Q296=+12 ;3-CI PUNKT W 1. OSI ~ Q297=+63 ;3-CI PUNKT W 2. OSI ~ Q298=+0 ;3-CI PUNKT W 3. OSI ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q281=+1 ;PROTOKOL POMIARU 14 CALL PGM TNC:\REF 15 ; 16 * - para 1: FP-12 17 TOOL CALL 28 Z S6000 F1000 DL-0.02 18 PLANE SPATIAL SPA+Q170 SPB+Q171 SPC+Q172 TURN F3333 19 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+2 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+24 ;SREDNICA NOMINALNA ~ Q342=+5 ;WYW.WSTEP. SREDNICA 20 LBL 1 21 L X+0 Y-78.5 R0 FMAX M99 M13 22 L X+0 Y+78.5 R0 FMAX M99 M13 23 LBL 0 24 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+24.05 ;SREDNICA NOMINALNA ~ Q342=+24 ;WYW.WSTEP. SREDNICA 25 CALL LBL 1 26 M5 27 M9 28 ; 29 M140 MB MAX 30 PLANE RESET TURN F3333 31 ; / 32 STOP 33 * - PRZEDMUCH 34 CYCL DEF 7.0 PUNKT BAZOWY 35 CYCL DEF 7.1 X+117.1 36 TOOL CALL 28 Z S5000 F150 37 M25 M3 38 LBL 60 ;PRZEDMUCH 39 L X-2 Y-67 FMAX M25 40 L Z+15 FMAX 41 L Z+15 F1500 42 L X+2 F AUTO 43 L Y+67 F2222 44 L X-2 F AUTO 45 L Z+50 FMAX 46 LBL 0 47 M5 48 M9 49 ; 50 * - para 2: <NAME> (sonda) 51 ; 52 TOOL CALL 1 Z S50 53 PLANE RESET TURN F3333 54 CYCL DEF 7.0 PUNKT BAZOWY 55 CYCL DEF 7.1 X+117.1 56 TCH PROBE 431 POMIAR PLASZCZYZNY ~ Q263=-9 ;1.PKT POMIAROW 1.OSI ~ Q264=-63 ;1.PKT 2.OSI ~ Q294=+0 ;1.PKT 3.OSI ~ Q265=+8 ;2-GI PUNKT W 1. OSI ~ Q266=-63 ;2-GI PUNKT W 2. OSI ~ Q295=+0 ;2-GI PUNKT W 3. OSI ~ Q296=+8 ;3-CI PUNKT W 1. OSI ~ Q297=+63 ;3-CI PUNKT W 2. OSI ~ Q298=+0 ;3-CI PUNKT W 3. OSI ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q281=+1 ;PROTOKOL POMIARU 57 CALL PGM TNC:\REF 58 ; 59 * - para 2: FP-12 60 TOOL CALL 28 Z S6000 F1000 DL-0.03 61 PLANE SPATIAL SPA+Q170 SPB+Q171 SPC+Q172 TURN F2000 62 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+2 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+24 ;SREDNICA NOMINALNA ~ Q342=+5 ;WYW.WSTEP. SREDNICA 63 CALL LBL 1 64 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+24.05 ;SREDNICA NOMINALNA ~ Q342=+24 ;WYW.WSTEP. SREDNICA 65 CALL LBL 1 66 M5 67 M9 68 M140 MB MAX 69 PLANE RESET TURN F3333 70 ; 71 ; 72 * - PRZEDMUCH 73 CYCL DEF 7.0 PUNKT BAZOWY 74 CYCL DEF 7.1 X+221.1 75 TOOL CALL 28 Z S5000 F150 76 M25 M3 77 CALL LBL 60 78 M5 M9 79 CALL PGM TNC:\Z19 80 CALL PGM TNC:\REF 81 ; 82 * - para 3: ustawianie plaszczyzny (sonda) 83 TOOL CALL 1 Z S50 84 CYCL DEF 7.0 PUNKT BAZOWY 85 CYCL DEF 7.1 X+221.1 86 TCH PROBE 431 POMIAR PLASZCZYZNY ~ Q263=-7 ;1.PKT POMIAROW 1.OSI ~ Q264=-63 ;1.PKT 2.OSI ~ Q294=+0 ;1.PKT 3.OSI ~ Q265=+7 ;2-GI PUNKT W 1. OSI ~ Q266=-63 ;2-GI PUNKT W 2. OSI ~ Q295=+0 ;2-GI PUNKT W 3. OSI ~ Q296=+7 ;3-CI PUNKT W 1. OSI ~ Q297=+63 ;3-CI PUNKT W 2. OSI ~ Q298=+0 ;3-CI PUNKT W 3. OSI ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q281=+1 ;PROTOKOL POMIARU 87 CALL PGM TNC:\REF 88 ; 89 * - para 3: FP-12 90 TOOL CALL 28 Z S6000 F1000 DL-0.05 91 PLANE SPATIAL SPA+Q170 SPB+Q171 SPC+Q172 TURN F2000 92 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+2 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+24.05 ;SREDNICA NOMINALNA ~ Q342=+5 ;WYW.WSTEP. SREDNICA 93 CALL LBL 1 94 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+24.02 ;SREDNICA NOMINALNA ~ Q342=+5 ;WYW.WSTEP. SREDNICA 95 CALL LBL 1 96 M5 97 M9 98 ; 99 CALL PGM TNC:\Z19 100 CALL PGM TNC:\REF3 101 PLANE RESET TURN F3333 102 END PGM kubki-sd-sonda MM <file_sep>/cnc programming/Heidenhain/JF/PLYTY/PLYTA-OTW-TECHN.h 0 BEGIN PGM PLYTA-OTW-TECHN MM 1 BLK FORM 0.1 Z X-350 Y-150 Z-35 2 BLK FORM 0.2 X+350 Y+150 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 * - NAW 8 TOOL CALL 9 Z S1200 F120 9 M8 10 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 11 CALL LBL 1 12 M5 M9 13 ; 14 * - W-12.1 15 TOOL CALL 1 Z S1000 F150 16 M8 17 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-40 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 18 CALL LBL 1 19 M5 M9 20 ; 21 * - FP-8 POGL 22 TOOL CALL 29 Z S9999 F999 23 M8 24 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-14 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+19 ;SREDNICA NOMINALNA ~ Q342=+12 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 25 CALL LBL 1 26 M5 M9 27 ; 28 * - FP-12 O12.5 29 TOOL CALL 13 Z S9999 F200 30 M8 31 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-36 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+12.5 ;SREDNICA NOMINALNA ~ Q342=+12 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 32 CALL LBL 1 33 M5 M9 34 ; 35 ;--------------------------------------------- 36 L Z-5 R0 FMAX M91 37 L X+260 Y+535 R0 FMAX M91 38 L M30 39 * - ----------------------------------------- 40 * - LBL1 OTW 41 LBL 1 42 M3 43 L X-300 Y+0 R0 FMAX M99 44 L X+300 Y+0 R0 FMAX M99 45 LBL 0 46 END PGM PLYTA-OTW-TECHN MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/6H7.H 0 BEGIN PGM 6H7 MM 1 BLK FORM 0.1 Z X-400 Y-150 Z-35 2 BLK FORM 0.2 X+400 Y+150 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 BLK FORM 0.1 Z X-400 Y-150 Z-35 7 BLK FORM 0.2 X+400 Y+150 Z+1 8 ;--------------------------------------------- 9 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 10 CYCL DEF 7.0 PUNKT BAZOWY 11 CYCL DEF 7.1 IX-27 12 CYCL DEF 7.2 IY+17.2 13 ;--------------------------------------------- 14 ; 15 TOOL CALL 3 Z S650 F30 16 M8 M3 17 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 18 CALL LBL 1 19 M5 M9 20 ; 21 TOOL CALL 14 Z S700 F30 22 M8 M3 23 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 24 CALL LBL 1 25 M5 M9 26 ; 27 TOOL CALL 6 Z S150 F30 28 M8 M3 29 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+50 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 30 CALL LBL 1 31 M5 M9 32 ; 33 TOOL CALL 9 Z S700 F30 34 M8 M3 35 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 36 CALL LBL 1 37 M5 M9 38 ; 39 ;--------------------------------------------- 40 L Z-5 R0 FMAX M91 41 L X+260 Y+535 R0 FMAX M91 42 L M30 43 * - ----------------------------------------- 44 * - LBL1 45 LBL 1 46 M3 47 L X+0 Y+0 R0 FMAX M99 48 LBL 0 49 ; 50 END PGM 6H7 MM <file_sep>/cnc programming/Heidenhain/JF/WALEK-DYST-SUR-PROG/PLAN.H 0 BEGIN PGM PLAN MM 1 BLK FORM 0.1 Z X-50 Y-50 Z-51.7 2 BLK FORM 0.2 X+50 Y+50 Z+8.5 3 CALL PGM TNC:\Z19 4 CALL PGM TNC:\REF 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 PLANE RESET TURN F2500 7 ; 8 STOP 9 TOOL CALL 1 Z S50 10 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+120 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-3 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 11 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 12 ; 13 TOOL CALL 3 Z S16987 F5000 14 M3 M8 15 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+0 ;STRATEGIA ~ Q225=-60 ;PKT.STARTU 1SZEJ OSI ~ Q226=-60 ;PKT.STARTU 2GIEJ OSI ~ Q227=+1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.15 ;PUNKT KONCOWY 3. OSI ~ Q218=+120 ;DLUG. 1-SZEJ STRONY ~ Q219=+120 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1.5 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 16 CYCL CALL 17 M5 M9 18 ; 19 TOOL CALL 3 Z S16987 F3000 20 M3 M8 21 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-60 ;PKT.STARTU 1SZEJ OSI ~ Q226=-60 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.15 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+120 ;DLUG. 1-SZEJ STRONY ~ Q219=+120 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1.2 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 22 CYCL CALL 23 M5 M9 24 ; 25 CALL PGM TNC:\Z19 26 CALL PGM TNC:\REF 27 ; / 28 STOP 29 CALL PGM 1-STRONA 30 ; 31 M30 32 END PGM PLAN MM <file_sep>/cnc programming/Heidenhain/JF/PLYTY/PLAN2.H 0 BEGIN PGM PLAN2 MM 1 BLK FORM 0.1 Z X-100 Y-100 Z-35 2 BLK FORM 0.2 X+100 Y+100 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; / 7 STOP 8 TOOL CALL 29 Z S11987 F2000 DL+0.03 9 TOOL DEF 30 10 M8 M3 11 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-130 ;PKT.STARTU 1SZEJ OSI ~ Q226=-70 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.4 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+260 ;DLUG. 1-SZEJ STRONY ~ Q219=+140 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.4 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+15 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 12 CALL LBL 1 13 M5 M9 14 ; / 15 TOOL CALL 29 Z S11987 F3000 DL+0.05 / 16 STOP / 17 TOOL DEF 30 / 18 M8 M3 / 19 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=+0 ;PKT.STARTU 1SZEJ OSI ~ Q226=+0 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.65 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.5 ;PUNKT KONCOWY 3. OSI ~ Q218=+340 ;DLUG. 1-SZEJ STRONY ~ Q219=+230 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.15 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+10 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. / 20 CALL LBL 1 21 ; 22 M5 M9 23 ; 24 ;--------------------------------------------- 25 L Z-5 R0 FMAX M91 26 L X+260 Y+535 R0 FMAX M91 27 L M30 28 * - ----------------------------------------- 29 * - LBL1 30 LBL 1 31 M3 32 L X+0 Y+0 R0 FMAX M99 33 LBL 0 34 ; 35 END PGM PLAN2 MM <file_sep>/cnc programming/Heidenhain/JF/DP/N060.00/POMIAR2.H 0 BEGIN PGM POMIAR2 MM 1 BLK FORM 0.1 Z X-100 Y-100 Z-35 2 BLK FORM 0.2 X+100 Y+100 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; / 7 STOP 8 TOOL CALL 30 Z S50 / 9 M8 M3 10 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+240 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 11 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 12 ; 13 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+15 ;SZEROKOSC MOSTKA ~ Q272=+2 ;OS POMIAROWA ~ Q261=-5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 14 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 15 ; / 16 M5 M9 17 ; 18 ;--------------------------------------------- / 19 L Z-5 R0 FMAX M91 / 20 L X+260 Y+535 R0 FMAX M91 / 21 L M30 22 CALL LBL 99 23 * - ----------------------------------------- 24 * - LBL1 25 LBL 1 26 M3 27 L X+0 Y+0 R0 FMAX M99 28 LBL 0 29 ; 30 LBL 99 31 END PGM POMIAR2 MM <file_sep>/cnc programming/Heidenhain/JF/ALS/N020.04/op3.h 0 BEGIN PGM op3 MM 1 BLK FORM 0.1 Z X-30.1 Y-0.2 Z-13.8 2 BLK FORM 0.2 X+30.1 Y+26.2 Z+0.2 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 ;--------------------------------------------- 5 STOP 6 * - TOROID-25 7 TOOL CALL 3 Z S1200 F1000 8 TOOL DEF 1 9 L Z+300 R0 FMAX M3 M8 10 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+1 ;STRATEGIA ~ Q225=-40 ;PKT.STARTU 1SZEJ OSI ~ Q226=+35 ;PKT.STARTU 2GIEJ OSI ~ Q227=+9 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+80 ;DLUG. 1-SZEJ STRONY ~ Q219=-51 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.8 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 11 CYCL CALL 12 L Z+300 R0 FMAX 13 ; 14 * - FP-12 15 TOOL CALL 1 Z S2222 F400 16 TOOL DEF 26 / 17 STOP 18 L Z+300 R0 FMAX M3 19 L X+0 Y-12 R0 FMAX 20 L Z+5 R0 FMAX M7 21 L Z+0 R0 F AUTO 22 LBL 1 23 L IZ-1 24 L X+12 RL 25 CC X+0 Y-12 26 C X+0 Y+0 DR+ 27 L X-29.75 28 CC X-29.75 Y+0.1 29 C X-29.85 Y+0.1 DR- 30 L Y+19.759 31 CC X-19.85 Y+19.759 32 C X-26.85 Y+26.9 DR- 33 L X+26.85 34 CC X+19.85 Y+19.759 35 C X+29.85 Y+19.759 DR- 36 L Y+0.1 37 CC X+29.75 Y+0.1 38 C X+29.75 Y+0 DR- 39 L X+0 40 CC X+0 Y-12 41 C X-12 Y-12 DR+ 42 L X+0 R0 43 LBL 0 44 CALL LBL 1 REP14 45 L Z+300 R0 FMAX 46 M9 M5 47 M5 48 ; 49 * - FAZO-16 50 TOOL CALL 26 Z S500 F50 DL-0.05 / 51 STOP 52 L Z+300 R0 FMAX M3 53 L X+31 Y-8 R0 FMAX 54 L Z+5 R0 FMAX M8 55 L Z-1 R0 F AUTO 56 LBL 2 57 L IZ-1 58 L Y+35 59 L IZ-1 60 L Y-8 61 LBL 0 62 CALL LBL 2 REP2 63 L Z+300 R0 FMAX 64 ; 65 * - FAZO-16 66 TOOL CALL 26 Z S500 F50 DL-0.05 / 67 STOP 68 L Z+300 R0 FMAX M3 69 L X-31 Y+35 R0 FMAX 70 L Z+5 R0 FMAX M8 71 L Z-1 R0 F AUTO 72 LBL 3 73 L IZ-1 74 L Y-8 75 L IZ-1 76 L Y+35 77 LBL 0 78 CALL LBL 3 REP2 79 L Z+300 R0 FMAX 80 ; 81 * - FAZO-16 82 TOOL CALL 26 Z S500 F50 DL-0.05 / 83 STOP 84 L Z+300 R0 FMAX M3 85 L X-30 Y+28 R0 FMAX 86 L Z+5 R0 FMAX M8 87 L Z-1.8 R0 F AUTO 88 L X+30 89 L Z+300 R0 FMAX 90 ; 91 * - FP-8 92 TOOL CALL 11 Z S3000 F500 DL-0.045 / 93 STOP 94 TOOL DEF 20 95 L Z+300 R0 FMAX M3 M8 96 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-35 ;PKT.STARTU 1SZEJ OSI ~ Q226=+32.5 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.5 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+70 ;DLUG. 1-SZEJ STRONY ~ Q219=-40 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q357=+2 ;ODST. BEZP. Z BOKU ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 97 CYCL CALL 98 L Z+300 R0 FMAX 99 ; 100 * - FP-8 101 TOOL CALL 19 Z S3000 F300 DR-0.04 / 102 STOP 103 L Z+300 R0 FMAX M3 104 L X+0 Y-12 R0 FMAX 105 L Z+5 R0 FMAX M8 106 L Z-15 R0 F AUTO 107 L X+12 RL 108 CC X+0 Y-12 109 C X+0 Y+0 DR+ 110 L X-29.75 111 CC X-29.75 Y+0.1 112 C X-29.85 Y+0.1 DR- 113 L Y+19.759 114 CC X-19.85 Y+19.759 115 C X-26.85 Y+26.9 DR- 116 L X+26.85 117 CC X+19.85 Y+19.759 118 C X+29.85 Y+19.759 DR- 119 L Y+0.1 120 CC X+29.75 Y+0.1 121 C X+29.75 Y+0 DR- 122 L X+0 123 CC X+0 Y-12 124 C X-12 Y-12 DR+ 125 L X+0 R0 126 L Z+300 R0 FMAX 127 L Z-15 R0 FMAX M91 M9 128 L X+300 Y+529 R0 FMAX M91 129 STOP M30 130 END PGM op3 MM <file_sep>/cnc programming/Heidenhain/polp-gorny.h 0 BEGIN PGM polp-gorny MM 1 BLK FORM 0.1 Z X-50 Y-50 Z-15 2 BLK FORM 0.2 X+50 Y+50 Z+1 3 ; 4 * - SONDA 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 TOOL CALL 30 Z S50 7 TCH PROBE 412 PKT.BAZ.OKRAG WEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+35.62 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=+1.5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 8 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 9 ; 10 * - ***************** 11 ; 12 * - NAW 13 TOOL CALL 9 Z S650 F20 14 TOOL DEF 25 15 M8 16 CYCL DEF 200 WIERCENIE ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 17 CALL LBL 1 18 CALL LBL 2 19 CYCL DEF 200 WIERCENIE ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 CALL LBL 3 21 M5 M9 22 ; 23 * - W-6.6 24 TOOL CALL 25 Z S650 F30 25 TOOL DEF 15 26 M8 27 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 28 CALL LBL 2 29 M5 M9 30 ; 31 * - W-5.8 32 TOOL CALL 15 Z S700 F30 33 TOOL DEF 12 34 M8 35 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 36 CALL LBL 1 37 M5 M9 38 ; 39 * - R-6 40 TOOL CALL 12 Z S150 F40 41 TOOL DEF 13 42 M8 43 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208= AUTO ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 44 CALL LBL 1 45 M5 M9 46 ; 47 * - FP-8 48 TOOL CALL 13 Z S2500 F150 49 TOOL DEF 26 50 M8 51 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-4.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.25 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11 ;SREDNICA NOMINALNA ~ Q342=+6.6 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 52 CALL LBL 2 53 M5 M9 54 ; 55 * - FAZ-16 56 TOOL CALL 26 Z S700 F60 57 TOOL DEF 30 58 M8 59 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0.5 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 60 CALL LBL 1 61 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-5.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+6 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0.5 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 62 CALL LBL 2 63 M5 M9 64 ; 65 * - ***************** 66 L Z+0 R0 FMAX M91 67 L X+550 Y+535 R0 FMAX M91 68 L M30 69 ; 70 * - ------------------------- 71 * - LBL 1 - 6H7 72 LBL 1 73 M13 74 L X-28.285 Y+28.28 R0 FMAX M99 75 L X+28.285 Y+28.28 R0 FMAX M99 76 LBL 0 77 * - LBL 2 - 6.6/11 78 LBL 2 79 M13 80 L X-39.15 Y+8.3 R0 FMAX M99 81 L X+39.15 Y+8.3 R0 FMAX M99 82 L X+0 Y+40 R0 FMAX M99 83 LBL 0 84 * - LBL 3 - TRAS 85 LBL 3 86 M13 87 L X-49 Y+0 R0 FMAX M99 88 L X-47 Y+0 R0 FMAX M99 89 L X+47 Y+0 R0 FMAX M99 90 L X+49 Y+0 R0 FMAX M99 91 LBL 0 92 END PGM polp-gorny MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/RPi4B/M6.H 0 BEGIN PGM M6 MM 1 BLK FORM 0.1 Z X-32.5 Y-15 Z-18 2 BLK FORM 0.2 X+32.5 Y+15 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 STOP 7 ; 8 * - NAW 9 TOOL CALL 9 Z S1111 F111 10 TOOL DEF 18 11 M8 12 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3.1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 13 CALL LBL 1 14 M5 M9 15 ; 16 * - W5 17 TOOL CALL 18 Z S1600 F111 18 TOOL DEF 7 19 M8 20 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0.5 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 21 CALL LBL 1 22 M5 M9 23 ; 24 * - M6 25 TOOL CALL 7 Z S200 26 TOOL DEF 23 27 M8 28 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-7.7 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 29 CALL LBL 1 30 M5 M9 31 ; 32 ;--------------------------------------------- 33 L Z-5 R0 FMAX M91 34 L X+260 Y+535 R0 FMAX M91 35 L M30 36 * - ----------------------------------------- 37 * - LBL1 GW 38 LBL 1 39 M3 40 L X+0 Y+0 R0 FMAX M99 41 LBL 0 42 * - LBL2 SRODEK 43 LBL 2 44 M3 45 L X+0 Y+0 R0 FMAX M99 46 LBL 0 47 END PGM M6 MM <file_sep>/cnc programming/Heidenhain/JF/PLYTY/KM-PLYTA-MOC-1STR.h 0 BEGIN PGM KM-PLYTA-MOC-1STR MM 1 BLK FORM 0.1 Z X-258 Y-320 Z-28 2 BLK FORM 0.2 X+258 Y+0 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 STOP 8 * - NAW 8 9 TOOL CALL 9 Z S1200 F120 10 TOOL DEF 14 11 M8 12 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 13 CALL LBL 2 14 CALL LBL 3 15 M5 M9 16 ; 17 * - W 7.8 VHM 18 TOOL CALL 14 Z S4077 F799 / 19 STOP 20 TOOL DEF 18 21 M8 22 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-25 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+25 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 23 CALL LBL 1 24 M5 M9 25 ; 26 * - W 10 HSS 27 TOOL CALL 18 Z S800 F100 / 28 STOP 29 TOOL DEF 25 30 M8 31 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-17.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 32 CALL LBL 2 33 M5 M9 34 ; 35 * - W 6.8 HSS 36 TOOL CALL 25 Z S1200 F100 / 37 STOP 38 TOOL DEF 12 39 M8 40 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-20 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 41 CALL LBL 3 42 M5 M9 43 ; 44 * - W 9 VHM 45 TOOL CALL 12 Z S3533 F777 / 46 STOP 47 TOOL DEF 26 48 M8 49 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-20 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+20 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 50 CALL LBL 4 51 M5 M9 52 ; 53 * - FAZY 54 TOOL CALL 26 Z S1200 F120 / 55 STOP 56 TOOL DEF 7 57 M8 58 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 59 CALL LBL 1 60 CALL LBL 3 61 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.9 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-3 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 62 CALL LBL 2 63 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 64 CALL LBL 4 65 M5 M9 66 ; 67 * - R 8H7 68 TOOL CALL 7 Z S130 F30 / 69 STOP 70 TOOL DEF 23 71 M8 72 CYCL DEF 201 ROZWIERCANIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-21 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+90 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 73 CALL LBL 1 74 M5 M9 75 ; 76 * - GW M8 77 TOOL CALL 23 Z S150 / 78 STOP 79 TOOL DEF 30 80 M8 81 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1.25 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 82 CALL LBL 3 83 M5 M9 84 ; 85 ;--------------------------------------------- 86 L Z-5 R0 FMAX M91 87 L X+260 Y+535 R0 FMAX M91 88 L M30 89 * - ----------------------------------------- 90 * - LBL1 8H7 91 LBL 1 92 M3 93 L X-232 Y-52 R0 FMAX M99 94 L X-128 Y-52 R0 FMAX M99 95 L X-112 Y-52 R0 FMAX M99 96 L X-8 Y-52 R0 FMAX M99 97 ; 98 L X+232 Y-52 R0 FMAX M99 99 L X+128 Y-52 R0 FMAX M99 100 L X+112 Y-52 R0 FMAX M99 101 L X+8 Y-52 R0 FMAX M99 102 ; 103 L X-232 Y-201 R0 FMAX M99 104 L X-128 Y-201 R0 FMAX M99 105 L X-112 Y-201 R0 FMAX M99 106 L X-8 Y-201 R0 FMAX M99 107 ; 108 L X+232 Y-201 R0 FMAX M99 109 L X+128 Y-201 R0 FMAX M99 110 L X+112 Y-201 R0 FMAX M99 111 L X+8 Y-201 R0 FMAX M99 112 ; 113 LBL 0 114 * - LBL2 10 WODA 115 LBL 2 116 M3 117 L X-216 Y-38 R0 FMAX M99 118 L X-194.5 Y-38 R0 FMAX M99 119 L X-165.5 Y-38 R0 FMAX M99 120 L X-144 Y-38 R0 FMAX M99 121 L X-96 Y-38 R0 FMAX M99 122 L X-74.5 Y-38 R0 FMAX M99 123 L X-45.5 Y-38 R0 FMAX M99 124 L X-24 Y-38 R0 FMAX M99 125 ; 126 L X+216 Y-38 R0 FMAX M99 127 L X+194.5 Y-38 R0 FMAX M99 128 L X+165.5 Y-38 R0 FMAX M99 129 L X+144 Y-38 R0 FMAX M99 130 L X+96 Y-38 R0 FMAX M99 131 L X+74.5 Y-38 R0 FMAX M99 132 L X+45.5 Y-38 R0 FMAX M99 133 L X+24 Y-38 R0 FMAX M99 134 LBL 0 135 * - LBL3 GW-M8 136 LBL 3 137 M3 138 L X-160 Y-60 R0 FMAX M99 139 L X+160 Y-60 R0 FMAX M99 140 LBL 0 141 * - LBL4 9 142 LBL 4 143 M3 144 L X-232 Y-7 R0 FMAX M99 145 L X-128 Y-7 R0 FMAX M99 146 L X-112 Y-7 R0 FMAX M99 147 L X-8 Y-7 R0 FMAX M99 148 ; 149 L X+232 Y-7 R0 FMAX M99 150 L X+128 Y-7 R0 FMAX M99 151 L X+112 Y-7 R0 FMAX M99 152 L X+8 Y-7 R0 FMAX M99 153 ; 154 L X-232 Y-87 R0 FMAX M99 155 L X-128 Y-87 R0 FMAX M99 156 L X-112 Y-87 R0 FMAX M99 157 L X-8 Y-87 R0 FMAX M99 158 ; 159 L X+232 Y-87 R0 FMAX M99 160 L X+128 Y-87 R0 FMAX M99 161 L X+112 Y-87 R0 FMAX M99 162 L X+8 Y-87 R0 FMAX M99 163 ; 164 L X-232 Y-167 R0 FMAX M99 165 L X-128 Y-167 R0 FMAX M99 166 L X-112 Y-167 R0 FMAX M99 167 L X-8 Y-167 R0 FMAX M99 168 ; 169 L X+232 Y-167 R0 FMAX M99 170 L X+128 Y-167 R0 FMAX M99 171 L X+112 Y-167 R0 FMAX M99 172 L X+8 Y-167 R0 FMAX M99 173 ; 174 L X-232 Y-247 R0 FMAX M99 175 L X-128 Y-247 R0 FMAX M99 176 L X-112 Y-247 R0 FMAX M99 177 L X-8 Y-247 R0 FMAX M99 178 ; 179 L X+232 Y-247 R0 FMAX M99 180 L X+128 Y-247 R0 FMAX M99 181 L X+112 Y-247 R0 FMAX M99 182 L X+8 Y-247 R0 FMAX M99 183 ; 184 LBL 0 185 END PGM KM-PLYTA-MOC-1STR MM <file_sep>/cnc programming/Heidenhain/PODWIERTY-125.h 0 BEGIN PGM PODWIERTY-125 MM 1 BLK FORM 0.1 Z X-100 Y-100 Z-44.5 2 BLK FORM 0.2 X+100 Y+100 Z+1 3 CALL PGM TNC:\REF 4 CALL PGM TNC:\Z19 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 PLANE RESET TURN F4000 / 7 STOP 8 * - FP-8 9 TOOL CALL 46 Z S4000 F400 10 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-43.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.6 ;GLEBOKOSC DOSUWU ~ Q203=-10 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.1 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA 11 CALL LBL 1 12 M5 13 M9 14 * - ********** 15 CALL PGM TNC:\REF 16 CALL PGM TNC:\Z19 17 ; /// 18 CALL LBL 99 19 ; /// / 20 M30 21 * - ********** 22 * - LBL 1 - PODWIERTY 23 LBL 1 24 L X+35 Y+45 R0 FMAX M99 M13 25 L IX+120 Y-45 R0 FMAX M99 M13 26 LBL 0 27 ; /// 28 LBL 99 29 ; /// 30 END PGM PODWIERTY-125 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/listwa-mocujaca.h 0 BEGIN PGM listwa-mocujaca MM 1 BLK FORM 0.1 Z X-20 Y-13 Z-15 2 BLK FORM 0.2 X+20 Y+13 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IY+0 7 CYCL DEF 7.2 IZ+0 8 ; 9 STOP 10 TOOL CALL 30 Z S50 11 TOOL DEF 11 12 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+40 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 13 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 14 ; 15 ;--------------------------------------------- 16 ; 17 * - PLAN / 18 STOP 19 TOOL CALL 21 Z S2000 F160 20 TOOL DEF 11 21 M8 22 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-20 ;PKT.STARTU 1SZEJ OSI ~ Q226=-13 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.5 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+45 ;DLUG. 1-SZEJ STRONY ~ Q219=+30 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+10 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 23 CALL LBL 1 24 M5 M9 25 ; 26 * - GAB - ZGR 27 STOP 28 TOOL CALL 21 Z S2000 F160 29 TOOL DEF 30 30 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+29 ;DLUG. 1-SZEJ STRONY ~ Q424=+40 ;WYMIAR POLWYROBU 1 ~ Q219=+15 ;DLUG. 2-GIEJ STRONY ~ Q425=+25 ;WYMIAR POLWYROBU 2 ~ Q220=+1.5 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-11 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q206=+750 ;WARTOSC POSUWU WGL. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 31 CALL LBL 1 32 M5 M9 33 ; 34 * - GAB - WYK 35 STOP 36 TOOL CALL 14 Z S2000 F200 DR-0.025 37 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+29 ;DLUG. 1-SZEJ STRONY ~ Q424=+29.1 ;WYMIAR POLWYROBU 1 ~ Q219=+15 ;DLUG. 2-GIEJ STRONY ~ Q425=+15.1 ;WYMIAR POLWYROBU 2 ~ Q220=+1.5 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-11 ;GLEBOKOSC ~ Q202=+11 ;GLEBOKOSC DOSUWU ~ Q206=+750 ;WARTOSC POSUWU WGL. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 38 CALL LBL 1 39 M5 M9 40 ; 41 ; 42 STOP 43 * - SONDA 44 ; 45 TOOL CALL 30 Z S50 46 TOOL DEF 11 47 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+29 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 48 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 49 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+15 ;SZEROKOSC MOSTKA ~ Q272=+2 ;OS POMIAROWA ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 50 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 51 ; 52 * - NAW 53 STOP 54 TOOL CALL 7 Z S650 F30 55 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 56 CALL LBL 2 57 M5 M9 58 ; 59 * - W-6.3 60 STOP 61 TOOL CALL 23 Z S650 F30 62 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-14 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 63 CALL LBL 2 64 M5 M9 65 ; 66 * - 11/7 67 STOP 68 TOOL CALL 14 Z S2000 F160 69 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-7.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.8 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.05 ;SREDNICA NOMINALNA ~ Q342=+6.3 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 70 CALL LBL 2 71 M5 M9 72 ; 73 * - FAZA - OTWORY / 74 STOP / 75 TOOL CALL 26 Z S6000 F300 DR-8 / 76 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11 ;SREDNICA NOMINALNA ~ Q342=+10.7 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> / 77 CALL LBL 2 / 78 M5 M9 79 TOOL CALL 26 Z S650 F30 DR+0 80 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-5.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 81 CALL LBL 2 82 M5 M9 83 ; 84 * - FAZA - GABARYT 85 STOP 86 TOOL CALL 26 Z S6000 F300 DR-7 87 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+29 ;DLUG. 1-SZEJ STRONY ~ Q424=+30 ;WYMIAR POLWYROBU 1 ~ Q219=+15 ;DLUG. 2-GIEJ STRONY ~ Q425=+16 ;WYMIAR POLWYROBU 2 ~ Q220=+1.5 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-0.9 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q206=+750 ;WARTOSC POSUWU WGL. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 88 CALL LBL 1 89 M5 M9 90 ; 91 ;--------------------------------------------- 92 L Z+0 R0 FMAX M91 93 L X+260 Y+535 R0 FMAX M91 94 L M30 95 * - ----------------------------------------- 96 * - LBL1 - SRODEK 97 LBL 1 98 M3 M8 99 L X+0 Y+0 R0 FMAX M99 100 LBL 0 101 * - LBL2 - 11/6.4 102 LBL 2 103 M3 M8 104 L X+8 Y+0 R0 FMAX M99 105 L X-8 Y+0 R0 FMAX M99 106 LBL 0 107 END PGM listwa-mocujaca MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/WZOR-FREZ-SREDNICA.H 0 BEGIN PGM WZOR-FREZ-SREDNICA MM 1 BLK FORM 0.1 Z X-100 Y-100 Z-80 2 BLK FORM 0.2 X+100 Y+100 Z+0.1 3 ;------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;------------------------------- 6 STOP / 7 TOOL CALL 2 Z S5600 F2200 DL+0 DR+0 8 TOOL CALL 27 Z S11111 F3000 DL+0 DR+0 9 L X+0 Y+0 R0 FMAX 10 M8 M3 11 ; 12 * - TU WPROWADZAJ ZMIANY 13 ; (DLA Q1 i Q2 TYLKO LICZBY CALKOWITE!!!) 14 Q1 = 77 ; fi WSTEPNE 15 Q2 = 68 ; fi NA GOTOWO 16 Q3 = 30.6 ; GLEBOKOSC I DOSUW 17 ; <NAME> 18 ; 19 Q1 = Q1 + 1 20 Q4 = Q2 + ( Q1 - Q2 - 0.5 ) 21 Q5 = ( Q1 - Q2 ) * 2 - 1 ;ZBIERA PO 0.5mm 22 Q5 = Q5 - 1 23 ; 24 LBL 2 25 Q1 = Q1 - 0.5 26 Q4 = Q4 - 0.5 27 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-Q3 ;GLEBOKOSC ~ Q206=+2000 ;WARTOSC POSUWU WGL. ~ Q202=+Q3 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+Q1 ;SREDNICA WST.OBR.WYB ~ Q223=+Q4 ;SRED.WYBR.OBR.NA GOT 28 CYCL CALL 29 LBL 0 30 CALL LBL 2 REPQ5 31 ; 32 M5 M9 33 ; 34 * - ********** 35 CALL PGM TNC:\REF 36 CALL PGM TNC:\Z19 37 L M30 38 * - ********** 39 * - LBL1 SRODEK 40 LBL 1 41 M3 42 L X+0 Y+0 R0 FMAX M99 43 LBL 0 44 END PGM WZOR-FREZ-SREDNICA MM <file_sep>/cnc programming/Heidenhain/JF/ZAMEK/ZAMEK-STR1.H 0 BEGIN PGM ZAMEK-STR1 MM 1 BLK FORM 0.1 Z X-61 Y-61 Z-15 2 BLK FORM 0.2 X+61 Y+61 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 L X+0 Y+0 R0 FMAX / 6 STOP 7 TOOL CALL 30 Z 8 TOOL DEF 3 9 TCH PROBE 412 PKT.BAZ.OKRAG WEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+81 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-6.5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 10 ; 11 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 12 ;--------------------------------------------- 13 ; 14 * - NAW STAL / 15 STOP 16 TOOL CALL 3 Z S600 F30 17 TOOL DEF 4 18 M8 19 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.07 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.07 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 ; 21 CYCL DEF 10.0 OBROT 22 CYCL DEF 10.1 ROT+45 23 CALL LBL 3 24 ; 25 CYCL DEF 10.0 OBROT 26 CYCL DEF 10.1 ROT+135 27 CALL LBL 3 28 ; 29 CYCL DEF 10.0 OBROT 30 CYCL DEF 10.1 ROT+225 31 CALL LBL 3 32 ; 33 CYCL DEF 10.0 OBROT 34 CYCL DEF 10.1 ROT+315 35 CALL LBL 3 36 ; 37 CYCL DEF 10.0 OBROT 38 CYCL DEF 10.1 ROT+0 39 ; 40 M5 M9 41 ; 42 * - NAW STAL 43 TOOL CALL 3 Z S600 F30 / 44 STOP 45 TOOL DEF 4 46 M8 47 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 48 CALL LBL 1 49 CALL LBL 2 50 ; 51 CYCL DEF 10.0 OBROT 52 CYCL DEF 10.1 ROT+90 53 CALL LBL 1 54 CALL LBL 2 55 ; 56 CYCL DEF 10.0 OBROT 57 CYCL DEF 10.1 ROT-90 58 CALL LBL 1 59 CALL LBL 2 60 ; 61 CYCL DEF 10.0 OBROT 62 CYCL DEF 10.1 ROT+180 63 CALL LBL 1 64 CALL LBL 2 65 ; 66 CYCL DEF 10.0 OBROT 67 CYCL DEF 10.1 ROT+0 68 ; 69 M5 M9 70 ; 71 * - W 7.8-VHM 72 TOOL CALL 4 Z S1427 F126 / 73 STOP 74 TOOL DEF 20 75 M7 76 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-10 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+6 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 77 CALL LBL 1 78 ; 79 CYCL DEF 10.0 OBROT 80 CYCL DEF 10.1 ROT+90 81 CALL LBL 1 82 ; 83 CYCL DEF 10.0 OBROT 84 CYCL DEF 10.1 ROT-90 85 CALL LBL 1 86 ; 87 CYCL DEF 10.0 OBROT 88 CYCL DEF 10.1 ROT+180 89 CALL LBL 1 90 ; 91 CYCL DEF 10.0 OBROT 92 CYCL DEF 10.1 ROT+0 93 ; 94 M5 M9 95 ; 96 * - W 8.4 97 TOOL CALL 20 Z S480 F30 / 98 STOP 99 TOOL DEF 26 100 M8 101 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-19 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 102 CALL LBL 2 103 ; 104 CYCL DEF 10.0 OBROT 105 CYCL DEF 10.1 ROT+90 106 CALL LBL 2 107 ; 108 CYCL DEF 10.0 OBROT 109 CYCL DEF 10.1 ROT-90 110 CALL LBL 2 111 ; 112 CYCL DEF 10.0 OBROT 113 CYCL DEF 10.1 ROT+180 114 CALL LBL 2 115 ; 116 CYCL DEF 10.0 OBROT 117 CYCL DEF 10.1 ROT+0 118 ; 119 M5 M9 120 ; 121 * - FAZY (FAZOWNIK 90ST) 122 TOOL CALL 26 Z S500 F30 DL+0.05 / 123 STOP 124 TOOL DEF 28 125 M8 126 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-3 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 127 CALL LBL 1 128 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-3.2 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 129 CALL LBL 2 130 ; 131 CYCL DEF 10.0 OBROT 132 CYCL DEF 10.1 ROT+90 133 CALL LBL 1 134 CALL LBL 2 135 ; 136 CYCL DEF 10.0 OBROT 137 CYCL DEF 10.1 ROT-90 138 CALL LBL 1 139 CALL LBL 2 140 ; 141 CYCL DEF 10.0 OBROT 142 CYCL DEF 10.1 ROT+180 143 CALL LBL 1 144 CALL LBL 2 145 ; 146 CYCL DEF 10.0 OBROT 147 CYCL DEF 10.1 ROT+0 148 ; 149 M5 M9 150 ; 151 * - R 8H7 152 TOOL CALL 28 Z S150 F30 / 153 STOP 154 TOOL DEF 30 155 M8 156 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+60 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 157 CALL LBL 1 158 ; 159 CYCL DEF 10.0 OBROT 160 CYCL DEF 10.1 ROT+90 161 CALL LBL 1 162 ; 163 CYCL DEF 10.0 OBROT 164 CYCL DEF 10.1 ROT-90 165 CALL LBL 1 166 ; 167 CYCL DEF 10.0 OBROT 168 CYCL DEF 10.1 ROT+180 169 CALL LBL 1 170 ; 171 CYCL DEF 10.0 OBROT 172 CYCL DEF 10.1 ROT+0 173 ; 174 M5 M9 175 ; 176 ;--------------------------------------------- 177 L Z-5 R0 FMAX M91 178 L X+260 Y+535 R0 FMAX M91 179 L M30 180 * - ----------------------------------------- 181 * - LBL1 8H7 182 LBL 1 183 M3 M8 184 L X-13.5 Y-50 R0 FMAX M99 185 L X+13.5 Y-50 R0 FMAX M99 186 LBL 0 187 * - LBL2 8.4 188 LBL 2 189 M3 M8 190 L X-26 Y-45 R0 FMAX M99 191 L X+0 Y-52 R0 FMAX M99 192 L X+26 Y-45 R0 FMAX M99 193 LBL 0 194 * - LBL3 TRAS 195 LBL 3 196 M3 M8 197 L X+56 Y+0 R0 FMAX M99 198 L X+48 Y+0 R0 FMAX M99 199 LBL 0 200 END PGM ZAMEK-STR1 MM <file_sep>/cnc programming/Heidenhain/JF/DP/N060.00/FAZA.H 0 BEGIN PGM FAZA MM 1 BLK FORM 0.1 Z X-400 Y-150 Z-35 2 BLK FORM 0.2 X+400 Y+150 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IZ+0 7 ; 8 ;--------------------------------------------- 9 ; 10 * - FAZA 11 TOOL CALL 9 Z S5000 F700 DL-0.1 DR-3 12 TOOL DEF 30 13 M8 M3 14 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+240 ;DLUG. 1-SZEJ STRONY ~ Q424=+240.1 ;WYMIAR POLWYROBU 1 ~ Q219=+15 ;DLUG. 2-GIEJ STRONY ~ Q425=+15.1 ;WYMIAR POLWYROBU 2 ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.4 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 15 CALL LBL 1 16 M5 M9 17 ; 18 ;--------------------------------------------- 19 L Z-5 R0 FMAX M91 20 L X+260 Y+535 R0 FMAX M91 / 21 L M30 22 CALL LBL 99 23 * - ----------------------------------------- 24 * - LBL1 25 LBL 1 26 M3 27 L X+0 Y+0 R0 FMAX M99 28 LBL 0 29 LBL 99 30 END PGM FAZA MM <file_sep>/cnc programming/Heidenhain/JF/KR/N091.00/n091f.h 0 BEGIN PGM n091f MM 1 ;MASTERCAM - X9 2 ;MCX FILE -~ Z:\00NZL\KR\KRN09100\MCX\KOEK_MOCUJCY_ZAPFEN_N091_FASOLKA_MIKRON.MCX-9 3 ;POST - MPPOSTABILITY_AVIA_VMC_800_4X.PST 4 ;PROGRAM - n091f.h 5 ;DATE - 2018.02.01 6 ;TIME - 8:57 AM 7 ;2 - NAWIERTAK FI 4 - D4.000mm 8 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 9 M126 10 M129 11 PLANE RESET TURN FMAX 12 ; 13 * - NAWIERTAK FI 4 14 TOOL CALL 8 Z S1000 DL+0.1 15 TOOL DEF 3 16 * - FAZUJE FASOLKE 17 ;NAWIERTAK FI 4 TOOL - 2 DIA. OFF. - 2 LEN. - 2 DIA. - 4. 18 ;HOLDER - DEFAULT HOLDER 19 CYCL DEF 32.0 TOLERANCJA 20 CYCL DEF 32.1 T0.003 21 CYCL DEF 32.2 HSC-MODE:0 / 22 L A+0 FMAX 23 M3 24 L X-1.92 Y-16.5 FMAX M8 25 L Z+15 FMAX 26 L Z+2 FMAX 27 L Z-1.58 F50 28 L Y-17.5 29 CC X+0 Y-17.5 30 C X+1.92 DR+ 31 L Y-16.5 32 CC X+0 Y-16.5 33 C X-1.92 DR+ 34 L Z+15 FMAX 35 CYCL DEF 32.0 TOLERANCJA 36 CYCL DEF 32.1 37 M5 38 L Z-15 R0 FMAX M91 M9 39 L X+273 Y+529 R0 FMAX M91 / 40 L A+0 FMAX M91 / 41 M2 42 END PGM n091f MM <file_sep>/cnc programming/Heidenhain/JF/WKLADKA-WYMIENNA/OP-2_2.H 0 BEGIN PGM OP-2_2 MM 1 BLK FORM 0.1 Z X-13 Y-11.5 Z-14 2 BLK FORM 0.2 X+13 Y+11.5 Z+0 3 STOP 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; / 6 TOOL CALL 30 Z S50 / 7 TOOL DEF 18 / 8 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=-2.7 ;1.PKT POMIAROW 1.OSI ~ Q264=-7 ;1.PKT 2.OSI ~ Q261=+8 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q272=+1 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 9 ; 10 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 11 STOP 12 ; 13 TOOL CALL 18 Z S5000 F2000 DL+0 14 L Z+300 R0 FMAX M3 M8 15 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+0 ;STRATEGIA ~ Q225=+0 ;PKT.STARTU 1SZEJ OSI ~ Q226=-10 ;PKT.STARTU 2GIEJ OSI ~ Q227=+21 ;PKT.STARTU 3CIEJ OSI ~ Q386=+11.6 ;PUNKT KONCOWY 3. OSI ~ Q218=+57 ;DLUG. 1-SZEJ STRONY ~ Q219=+26 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+10 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 16 CYCL CALL 17 ; / 18 STOP 19 ; 20 TOOL CALL 18 Z S5000 F2000 21 TOOL DEF 30 22 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+0 ;STRATEGIA ~ Q225=+0 ;PKT.STARTU 1SZEJ OSI ~ Q226=-10 ;PKT.STARTU 2GIEJ OSI ~ Q227=+11.6 ;PKT.STARTU 3CIEJ OSI ~ Q386=+11.5 ;PUNKT KONCOWY 3. OSI ~ Q218=+57 ;DLUG. 1-SZEJ STRONY ~ Q219=+26 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+10 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 23 L Z+300 R0 FMAX M3 M8 24 CYCL CALL 25 ; 26 L Z+300 R0 FMAX 27 ; 28 TOOL CALL 30 Z S50 / 29 STOP 30 TOOL DEF 26 31 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+2.7 ;1.PKT POMIAROW 1.OSI ~ Q264=+0 ;1.PKT 2.OSI ~ Q261=+4 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q272=+1 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 32 ; 33 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 34 ; 35 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+10 ;1.PKT POMIAROW 1.OSI ~ Q264=+10.5 ;1.PKT 2.OSI ~ Q261=+9 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q272=+2 ;OS POMIAROWA ~ Q267=-1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 36 ; 37 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 38 ; 39 TCH PROBE 417 PKT.BAZOWY TS.-OSI ~ Q263=+5 ;1.PKT POMIAROW 1.OSI ~ Q264=-5 ;1.PKT 2.OSI ~ Q294=+11.5 ;1.PKT 3.OSI ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 40 ; 41 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 42 ; 43 CYCL DEF 7.0 PUNKT BAZOWY 44 CYCL DEF 7.1 IZ-0.5 45 ; 46 * - FAZ-16 47 TOOL CALL 26 Z S1000 F100 / 48 STOP 49 TOOL DEF 28 50 M8 51 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.4 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 52 CALL LBL 1 53 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-5.65 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 54 CALL LBL 4 55 M5 M9 56 ; 57 * - W-4.25 58 TOOL CALL 28 Z S1700 F120 / 59 STOP 60 TOOL DEF 20 61 M8 M3 62 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 63 CALL LBL 1 64 M5 M9 65 ; 66 * - GW-M5 67 TOOL CALL 20 Z S120 / 68 STOP 69 TOOL DEF 30 70 M8 71 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-7.5 ;GLEBOKOSC GWINTU ~ Q239=+0.8 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 72 CALL LBL 1 73 M5 M9 74 ; 75 ;--------------------------------------------- 76 L Z+0 R0 FMAX M91 77 L X+260 Y+535 R0 FMAX M91 78 L M30 79 * - ----------------------------------------- 80 * - LBL1 - M5 81 LBL 1 82 M3 83 L X+5 Y-7 R0 FMAX M99 84 LBL 0 85 * - LBL4 - 5.5 86 LBL 4 87 M3 88 L X+15 Y-7 R0 FMAX M99 89 LBL 0 90 END PGM OP-2_2 MM <file_sep>/cnc programming/Heidenhain/JF/PLYTY/PLAN3.H 0 BEGIN PGM PLAN3 MM 1 BLK FORM 0.1 Z X-400 Y-150 Z-35 2 BLK FORM 0.2 X+400 Y+150 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 BLK FORM 0.1 Z X-400 Y-150 Z-35 7 BLK FORM 0.2 X+400 Y+150 Z+1 8 ;--------------------------------------------- 9 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 10 CYCL DEF 7.0 PUNKT BAZOWY 11 CYCL DEF 7.1 IX-45 12 CYCL DEF 7.2 IY-33 13 ;--------------------------------------------- 14 ; 15 STOP 16 TOOL CALL 27 Z S8000 F2500 17 TOOL DEF 30 18 M8 M3 19 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=+0 ;PKT.STARTU 1SZEJ OSI ~ Q226=+0 ;PKT.STARTU 2GIEJ OSI ~ Q227=+2.5 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+95 ;DLUG. 1-SZEJ STRONY ~ Q219=+35 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 20 CALL LBL 1 21 M5 M9 22 ; 23 TOOL CALL 27 Z S8000 F2500 24 TOOL DEF 30 25 M8 M3 26 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=+0 ;PKT.STARTU 1SZEJ OSI ~ Q226=+0 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+95 ;DLUG. 1-SZEJ STRONY ~ Q219=+35 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 27 CALL LBL 1 28 M5 M9 29 ; 30 ; 31 ;--------------------------------------------- 32 L Z-5 R0 FMAX M91 33 L X+260 Y+535 R0 FMAX M91 34 L M30 35 * - ----------------------------------------- 36 * - LBL1 37 LBL 1 38 M3 39 L X+0 Y+0 R0 FMAX M99 40 LBL 0 41 ; 42 END PGM PLAN3 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/WWW.H 0 BEGIN PGM WWW MM 1 BLK FORM 0.1 Z X+0 Y+0 Z+0 2 BLK FORM 0.2 X+0 Y+0 Z+0 3 ;http://192.168.127.12 4 END PGM WWW MM <file_sep>/cnc programming/Heidenhain/JF/ALS/N030.05/GABARYT.H 0 BEGIN PGM GABARYT MM 1 BLK FORM 0.1 Z X-61 Y-18 Z-20 2 BLK FORM 0.2 X+61 Y+18 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 STOP 7 L X+0 Y+0 R0 FMAX 8 ; 9 TOOL CALL 30 Z 10 TOOL DEF 7 11 ; 12 TCH PROBE 411 PKT.BAZ.PROST.ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q323=+126 ;DLUG. 1-SZEJ STRONY ~ Q324=+41 ;DLUG. 2-GIEJ STRONY ~ Q261=-5 ;WYSOKOSC POMIARU ~ Q320=+20 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+1 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 13 ; 14 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 15 ; 16 ;--------------------------------------------- 17 ; 18 * - TOROID ZGRUBNIE 19 TOOL CALL 3 Z S1300 F800 DR+0.5 / 20 STOP 21 TOOL DEF 17 22 M8 M3 23 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+120 ;DLUG. 1-SZEJ STRONY ~ Q424=+126 ;WYMIAR POLWYROBU 1 ~ Q219=+33 ;DLUG. 2-GIEJ STRONY ~ Q425=+41 ;WYMIAR POLWYROBU 2 ~ Q220=+0.2 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-19.8 ;GLEBOKOSC ~ Q202=+0.8 ;GLEBOKOSC DOSUWU ~ Q206=+3000 ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 24 CALL LBL 1 25 M5 M9 26 ; / 27 STOP 28 ; SPRAWDZ PODKLADY 29 ; 30 * - PLANOWANIE 31 TOOL CALL 12 Z S3000 F600 / 32 STOP 33 TOOL DEF 12 34 M8 M3 35 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-63 ;PKT.STARTU 1SZEJ OSI ~ Q226=-21 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.2 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+126 ;DLUG. 1-SZEJ STRONY ~ Q219=+42 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 36 CYCL CALL 37 M5 M9 38 ; 39 STOP 40 * - FREZ ZGRUBNY ZBIERA PROMIEN PO TOROIDZIE 41 TOOL CALL 1 Z S1300 F600 DR+0.5 42 TOOL DEF 12 43 M8 M3 44 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+120 ;DLUG. 1-SZEJ STRONY ~ Q424=+126 ;WYMIAR POLWYROBU 1 ~ Q219=+33 ;DLUG. 2-GIEJ STRONY ~ Q425=+41 ;WYMIAR POLWYROBU 2 ~ Q220=+0.2 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-5.8 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206=+3000 ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=-14 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 45 CALL LBL 1 46 M5 M9 47 ; 48 * - <NAME> 12 MALY NADDATEK 49 TOOL CALL 1 Z S1300 F600 DR+0.05 / 50 STOP 51 TOOL DEF 17 52 M8 M3 53 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+120 ;DLUG. 1-SZEJ STRONY ~ Q424=+126 ;WYMIAR POLWYROBU 1 ~ Q219=+33 ;DLUG. 2-GIEJ STRONY ~ Q425=+41 ;WYMIAR POLWYROBU 2 ~ Q220=+0.2 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-19.8 ;GLEBOKOSC ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q206=+3000 ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 54 CALL LBL 1 55 M5 M9 56 ; 57 * - FREZ 8 WYKONCZENIOWY 58 TOOL CALL 11 Z S1200 F400 DL+0 DR-0.04 / 59 STOP 60 TOOL DEF 9 61 M8 M3 62 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+120 ;DLUG. 1-SZEJ STRONY ~ Q424=+126 ;WYMIAR POLWYROBU 1 ~ Q219=+33 ;DLUG. 2-GIEJ STRONY ~ Q425=+41 ;WYMIAR POLWYROBU 2 ~ Q220=+0.2 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-19.8 ;GLEBOKOSC ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q206=+3000 ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 63 CALL LBL 1 64 M5 M9 65 ; 66 * - FAZA CZOP 67 TOOL CALL 9 Z S4000 F200 DR-3 / 68 STOP 69 TOOL DEF 24 70 M7 M3 71 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+120 ;DLUG. 1-SZEJ STRONY ~ Q424=+120.1 ;WYMIAR POLWYROBU 1 ~ Q219=+33 ;DLUG. 2-GIEJ STRONY ~ Q425=+33.1 ;<NAME> 2 ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1.5 ;GLEBOKOSC ~ Q202=+2.5 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 72 CALL LBL 1 73 M5 M9 74 ; 75 STOP 76 ;--------------------------------------------- 77 L Z-5 R0 FMAX M91 78 L X+260 Y+535 R0 FMAX M91 / 79 STOP 80 CALL PGM TNC:\JF\ALS\N030.05\n03003z.h / 81 STOP 82 CALL PGM TNC:\JF\ALS\N030.05\n03003w.h 83 L M30 84 * - ----------------------------------------- 85 * - LBL1 86 LBL 1 87 M3 88 L X+0 Y+0 R0 FMAX M99 89 LBL 0 90 ; 91 END PGM GABARYT MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/KS-N060_01-PIERSCIEN-UST.h 0 BEGIN PGM KS-N060_01-PIERSCIEN-UST MM 1 BLK FORM 0.1 Z X-62.5 Y-62.5 Z-15 2 BLK FORM 0.2 X+62.5 Y+62.5 Z+0 3 ; 4 * - UWAGA! SZCZEKI USTAWIC PO SKOSIE, SONDA PORUSZA SIE W SRODKU MIEDZY~ SZCZEKAMI 5 ; 6 ;--------------------------------------------- 7 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 8 ; / 9 STOP 10 L X+0 Y+0 FMAX 11 ; 12 TOOL CALL 30 Z 13 TOOL DEF 9 14 ; 15 TCH PROBE 412 PKT.BAZ.OKRAG WEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+72 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+26 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 16 ; 17 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 18 ;--------------------------------------------- 19 ; 20 * - NAW 21 TOOL CALL 9 Z S1800 F100 / 22 STOP 23 TOOL DEF 13 24 M8 25 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3.6 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 26 CALL LBL 1 27 M5 M9 28 ; 29 * - W 7 30 TOOL CALL 13 Z S1500 F150 / 31 STOP 32 TOOL DEF 27 33 M8 34 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-19.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 35 CALL LBL 1 36 M5 M9 37 ; 38 * - FP-8 39 TOOL CALL 27 Z S5000 F250 / 40 STOP 41 TOOL DEF 9 42 M3 43 L X+64 Y-25 FMAX 44 L Z+10 FMAX 45 L Z-16 F1000 M8 46 L X+58 Y-25 RR F AUTO 47 L Y+25 RR F AUTO 48 L Z+20 R0 FMAX 49 ; 50 L X-64 Y+25 FMAX 51 L Z+10 FMAX 52 L Z-16 F1000 53 L X-58 Y+25 RR F AUTO 54 L Y-25 RR F AUTO 55 L Z+20 R0 FMAX 56 ; 57 M5 M9 58 ; 59 * - NAW 90ST R=0 / KOMPENSACJA FAZY W "DL" 60 TOOL CALL 9 Z S2000 F200 DL-0.1 / 61 STOP 62 TOOL DEF 30 63 M3 64 ; 65 L X+60 Y-25 FMAX 66 L Z+10 FMAX M8 67 L Z-2.75 F500 68 L Y+25 F AUTO 69 L Z+20 R0 FMAX 70 ; 71 L X-60 Y+25 FMAX 72 L Z+10 FMAX 73 L Z-2.75 F500 74 L Y-25 F AUTO 75 L Z+20 R0 FMAX 76 ; 77 M5 M9 78 ; 79 ;--------------------------------------------- 80 L Z+0 R0 FMAX M91 81 L X+260 Y+535 R0 FMAX M91 82 L M30 83 * - ----------------------------------------- 84 * - LBL1 7 85 LBL 1 86 M3 87 L X-42.5 Y+0 R0 FMAX M99 88 L X-13.1 Y+40.4 R0 FMAX M99 89 L X+34.4 Y+25 R0 FMAX M99 90 L X+34.4 Y-25 R0 FMAX M99 91 L X+0 Y-42.5 R0 FMAX M99 92 L X-13.1 Y-40.4 R0 FMAX M99 93 LBL 0 94 END PGM KS-N060_01-PIERSCIEN-UST MM <file_sep>/cnc programming/Heidenhain/JF/AD/N021.00/PLAN.H 0 BEGIN PGM PLAN MM 1 BLK FORM 0.1 Z X-100 Y-100 Z-35 2 BLK FORM 0.2 X+100 Y+100 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 TOOL CALL 6 Z S3000 F600 8 TOOL DEF 24 9 M7 M3 10 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-30 ;PKT.STARTU 1SZEJ OSI ~ Q226=-15 ;PKT.STARTU 2GIEJ OSI ~ Q227=+1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.05 ;PUNKT KONCOWY 3. OSI ~ Q218=+65 ;DLUG. 1-SZEJ STRONY ~ Q219=+35 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 11 CALL LBL 1 12 M5 M9 13 ; 14 TOOL CALL 24 Z S3000 F600 / 15 STOP 16 TOOL DEF 30 17 M7 M3 18 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-30 ;PKT.STARTU 1SZEJ OSI ~ Q226=-15 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.05 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+65 ;DLUG. 1-SZEJ STRONY ~ Q219=+35 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.05 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 19 CALL LBL 1 20 M5 M9 21 ; 22 ; 23 ;--------------------------------------------- 24 L Z-5 R0 FMAX M91 25 L X+260 Y+535 R0 FMAX M91 26 CALL LBL 99 / 27 L M30 28 STOP 29 CALL PGM TNC:\5675-AD\N021.00\GAB.H 30 STOP 31 CALL PGM TNC:\5675-AD\N021.00\adn02100.h 32 STOP 33 CALL PGM TNC:\5675-AD\N021.00\OTW.H 34 * - ----------------------------------------- 35 * - LBL1 36 LBL 1 37 M3 38 L X+0 Y+0 R0 FMAX M99 39 LBL 0 40 LBL 99 41 LBL 0 42 ; 43 END PGM PLAN MM <file_sep>/cnc programming/Heidenhain/JF/PODZIALY/R2.H 0 BEGIN PGM R2 MM 1 BLK FORM 0.1 Z X-42.5 Y-0.01 Z-4.6 2 BLK FORM 0.2 X+42.5 Y+42.5 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 * - PROMIENIE "R" W POLPIERSCIENIACH GORNYCH 8 * - (ZMIENIAC WSP. POCZATKU i KONCA PROMIENIA) 9 * - PRZEPROWADZ SYMULACJE W CELU SPRAWDZENIA 10 ; 11 ;--------------------------------------------- 12 ; 13 * - FP-8 14 TOOL CALL 11 Z S3000 F600 DL+0.1 15 ; 16 STOP 17 ; ZACZYNA Z LEWEJ 18 L X-55 Y-7 FMAX 19 M8 M3 20 L Z-1 FMAX 21 L Y+0 RR F AUTO 22 L X-23.3 ;WSPOLRZEDNA POCZATKU PROMIENIA 23 ; 24 L X-23.3 Y+0 RR F AUTO ;WSP. POCZ. POWTORZONA 25 CT X-20.3 Y+5 ;WSPOLRZEDNE KONCA PROMIENIA 26 L X-10 27 L Z+50 R0 FMAX 28 ; 29 STOP 30 ; ZACZYNA Z PRAWEJ 31 L X+55 Y-7 FMAX 32 L Z-1 FMAX 33 L Y+0 RL F AUTO 34 L X+23.3 ;WSPOLRZEDNA POCZATKU PROMIENIA 35 ; 36 L X+23.3 Y+0 RL F AUTO ;WSP. POCZ. POWTORZONA 37 CT X+20.3 Y+5 ;WSPOLRZEDNE KONCA PROMIENIA 38 L X+10 39 L Z+50 R0 FMAX 40 ; 41 M5 M9 42 ; 43 ; 44 ;--------------------------------------------- 45 L Z-5 R0 FMAX M91 46 L X+260 Y+535 R0 FMAX M91 47 L M30 48 * - ----------------------------------------- 49 * - LBL1 0 50 LBL 1 51 M3 52 L X+0 Y+0 R0 FMAX M99 53 LBL 0 54 END PGM R2 MM <file_sep>/cnc programming/Heidenhain/JF/AD/N030.02/90H7-ZGR60mm.H 0 BEGIN PGM 90H7-ZGR60mm MM 1 BLK FORM 0.1 Z X-140 Y-100 Z-18 2 BLK FORM 0.2 X+140 Y+100 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 L X+0 Y+0 R0 FMAX 6 CYCL DEF 7.0 PUNKT BAZOWY 7 CYCL DEF 7.1 IX+60 8 ; 9 L X+0 Y+0 R0 FMAX 10 ;--------------------------------------------- 11 ; 12 ; 13 * - TOR-25 14 TOOL CALL 13 Z S1300 F700 15 L X+0 Y+0 R0 FMAX 16 M8 M3 17 CYCL DEF 252 WYBRANIE KOLOWE ~ Q215=+0 ;RODZAJ OBROBKI ~ Q223=+89 ;SREDNICA OKREGU ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-23 ;GLEBOKOSC ~ Q202=+0.7 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+300 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 18 CYCL CALL 19 M5 M9 20 ; 21 ; 22 ;--------------------------------------------- 23 L Z+0 R0 FMAX M91 24 L X+260 Y+535 R0 FMAX M91 / 25 L M30 26 * - ----------------------------------------- 27 END PGM 90H7-ZGR60mm MM <file_sep>/cnc programming/Heidenhain/JF/KR/N091.00/POMIAR2.H 0 BEGIN PGM POMIAR2 MM 1 BLK FORM 0.1 Z X-35 Y-35 Z-15 2 BLK FORM 0.2 X+35 Y+35 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 L X+0 Y+0 R0 FMAX 6 TOOL CALL 30 Z 7 TOOL DEF 8 8 TCH PROBE 412 PKT.BAZ.OKRAG WEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+6 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-29 ;WYSOKOSC POMIARU ~ Q320=+5 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+1 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+11 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 9 ; 10 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 11 ;--------------------------------------------- 12 ; / 13 STOP 14 CALL PGM TNC:\5646-KR\N091.00\n091d.h / 15 STOP 16 CALL PGM TNC:\5646-KR\N091.00\KOLEK-MOC-STR2.H / 17 STOP 18 CALL PGM TNC:\5646-KR\N091.00\SONDA-6H7.H 19 ; 20 ;--------------------------------------------- 21 L Z-5 R0 FMAX M91 22 L X+260 Y+535 R0 FMAX M91 23 L M30 24 * - ----------------------------------------- 25 END PGM POMIAR2 MM <file_sep>/cnc programming/Heidenhain/JF/DP/N060.00/GAB-WYK.H 0 BEGIN PGM GAB-WYK MM 1 BLK FORM 0.1 Z X-125 Y-10 Z-20 2 BLK FORM 0.2 X+125 Y+10 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; / 7 STOP 8 TOOL CALL 23 Z S1222 F300 DL-0.05 DR-0.04 9 M8 M3 10 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+240 ;DLUG. 1-SZEJ STRONY ~ Q424=+250 ;WYMIAR POLWYROBU 1 ~ Q219=+15 ;DLUG. 2-GIEJ STRONY ~ Q425=+19 ;WYMIAR POLWYROBU 2 ~ Q220=+0.1 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-18 ;GLEBOKOSC ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 11 CALL LBL 1 12 ; 13 M5 M9 14 ; 15 ;--------------------------------------------- 16 L Z-5 R0 FMAX M91 17 L X+260 Y+535 R0 FMAX M91 / 18 L M30 19 CALL LBL 99 20 * - ----------------------------------------- 21 * - LBL1 22 LBL 1 23 M3 24 L X+0 Y+0 R0 FMAX M99 25 LBL 0 26 ; 27 LBL 99 28 END PGM GAB-WYK MM <file_sep>/cnc programming/Heidenhain/JF/SP/5580/12/GAB.h 0 BEGIN PGM GAB MM 1 BLK FORM 0.1 Z X-40 Y-30 Z-7 2 BLK FORM 0.2 X+40 Y+30 Z+1 3 ; 4 ; -- <NAME> 2 5 ; 6 ;--------------------------------------------- 7 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 8 CYCL DEF 7.0 PUNKT BAZOWY 9 CYCL DEF 7.1 IZ+0 10 ;--------------------------------------------- 11 STOP 12 TOOL CALL 30 Z S50 13 TOOL DEF 10 14 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=-18 ;SRODEK W 2-SZEJ OSI ~ Q311=+68 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-2 ;WYSOKOSC POMIARU ~ Q320=+15 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 15 ; 16 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 17 ;--------------------------------------------- 18 ; 19 * - GLOW-20 -PLANOWANIE / 20 STOP 21 TOOL CALL 10 Z S600 F240 22 TOOL DEF 10 23 M8 24 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-33 ;PKT.STARTU 1SZEJ OSI ~ Q226=-26 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.5 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+70 ;DLUG. 1-SZEJ STRONY ~ Q219=+55 ;DLUG. 2-GIEJ STRONY ~ Q202=+5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 25 CALL LBL 1 26 M5 M9 27 ; 28 * - GLOW-20 -GABARYT Z NADDATKAMI 29 TOOL CALL 10 Z S600 F200 / 30 STOP 31 TOOL DEF 14 32 M8 33 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+58.6 ;DLUG. 1-SZEJ STRONY ~ Q424=+66 ;WYMIAR POLWYROBU 1 ~ Q219=+45.2 ;DLUG. 2-GIEJ STRONY ~ Q425=+53 ;WYMIAR POLWYROBU 2 ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-6.5 ;GLEBOKOSC ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 34 CALL LBL 1 35 M5 M9 36 ; 37 ;--------------------------------------------- 38 L Z-5 R0 FMAX M91 39 L X+260 Y+535 R0 FMAX M91 40 CALL PGM TNC:\5580-SP\12\op1.h 41 L M30 42 * - ----------------------------------------- 43 * - LBL1 O 44 LBL 1 45 M3 46 L X+0 Y+0 R0 FMAX M99 47 LBL 0 48 END PGM GAB MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/MOTOR1.H 0 BEGIN PGM MOTOR1 MM 1 BLK FORM 0.1 Z X-12.5 Y-12.5 Z-160 2 BLK FORM 0.2 X+12.5 Y+12.5 Z+0.1 3 ;--------------------------------------------- 4 ; 5 * - Z WALKA FI25mm, L=100mm 6 ; 7 ;--------------------------------------------- 8 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 9 ;--------------------------------------------- 10 ; 11 * - FP 12 STOP 13 TOOL CALL 27 Z S11987 F1000 14 CYCL DEF 252 WYBRANIE KOLOWE ~ Q215=+0 ;RODZAJ OBROBKI ~ Q223=+26 ;SREDNICA OKREGU ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-60 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+450 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+30 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 15 CALL LBL 1 16 M5 M9 17 ; 18 * - NAW 19 STOP 20 TOOL CALL 3 Z S700 F40 21 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-60 ;WSPOLRZEDNE POWIERZ. ~ Q204=+80 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 22 CALL LBL 1 23 M5 M9 24 ; 25 * - W 20 26 STOP 27 TOOL CALL 29 Z S420 F60 28 CYCL DEF 200 WIERCENIE ~ Q200=+3 ;BEZPIECZNA WYSOKOSC ~ Q201=-95 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-60 ;WSPOLRZEDNE POWIERZ. ~ Q204=+80 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 29 CALL LBL 1 30 M5 M9 31 ; 32 * - NAW -FAZ 33 STOP 34 TOOL CALL 9 Z S2000 F300 DL+0 DR-1 35 CYCL DEF 257 CZOP OKRAGLY ~ Q223=+24.99 ;SRED.WYBR.OBR.NA GOT ~ Q222=+25 ;SREDNICA WST.OBR.WYB ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1.4 ;GLEBOKOSC ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=-60 ;WSPOLRZEDNE POWIERZ. ~ Q204=+80 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q376=-1 ;KAT POCZATKOWY 36 CALL LBL 1 37 M5 M9 38 ; 39 ;--------------------------------------------- 40 L Z-5 R0 FMAX M91 41 L X+260 Y+535 R0 FMAX M91 42 L M30 43 * - ----------------------------------------- 44 * - LBL1 O 45 LBL 1 46 M3 47 L X+0 Y+0 R0 FMAX M99 48 LBL 0 49 END PGM MOTOR1 MM <file_sep>/cnc programming/Heidenhain/JF/CHWYTAKI/sd_5458_01_01LB.H 0 BEGIN PGM sd_5458_01_01LB MM 1 ;MASTERCAM - X9 2 ;MCX FILE - D:\0_ZLECENIA\5458\CHWYTAK_BUTELKI_PRAWY_PROGRAM2_5458.MCX-9 3 ;POST - MPPOSTABILITY_AVIA_VMC_800_4X.PST 4 ;PROGRAM - sd_5458_01_01LB.H 5 ;DATE - 2020.01.28 6 ;TIME - 9:32 AM 7 ;1 - FREZ PLASKI FI 20 R04 - D20.000mm - R0.400mm 8 ;3 - FREZ PLASKI FI 8 - D8.000mm 9 BLK FORM 0.1 Z X+0 Y-12.25 Z-9.2 10 BLK FORM 0.2 X+114 Y+20.084 Z+0 11 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 12 M126 13 M129 14 PLANE RESET TURN FMAX 15 ; 16 * - FREZ PLASKI FI 20 R04 17 TOOL CALL 1 Z S1000 18 TOOL DEF 3 19 * - STREFA 1 20 ;FREZ PLASKI FI 20 R04 TOOL - 1 DIA. OFF. - 1 LEN. - 1 DIA. - 20. 21 ;HOLDER - DEFAULT HOLDER 22 CYCL DEF 32.0 TOLERANCJA 23 CYCL DEF 32.1 T0.01 24 CYCL DEF 32.2 HSC-MODE:0 25 L A+0 FMAX 26 M3 27 L X+105.489 Y+30.875 FMAX M8 28 L Z+150 FMAX 29 L Z+2.5 FMAX 30 L Z-0.155 F250 31 L Y-26.036 F180 32 L Z+50 FMAX 33 L X+95.489 Y+30.875 FMAX 34 L Z+2.5 FMAX 35 L Z-0.155 F250 36 L Y-26.036 F180 37 L Z+50 FMAX 38 L X+105.489 Y+30.875 FMAX 39 L Z+1.845 FMAX 40 L Z-0.81 F250 41 L Y-26.036 F180 42 L Z+50 FMAX 43 L X+95.489 Y+30.875 FMAX 44 L Z+1.845 FMAX 45 L Z-0.81 F250 46 L Y-26.036 F180 47 L Z+50 FMAX 48 L X+105.489 Y+30.875 FMAX 49 L Z+1.19 FMAX 50 L Z-1.465 F250 51 L Y-26.036 F180 52 L Z+50 FMAX 53 L X+95.489 Y+30.875 FMAX 54 L Z+1.19 FMAX 55 L Z-1.465 F250 56 L Y-26.036 F180 57 L Z+50 FMAX 58 L X+105.489 Y+30.875 FMAX 59 L Z+0.535 FMAX 60 L Z-2.12 F250 61 L Y-26.036 F180 62 L Z+50 FMAX 63 L X+95.489 Y+30.875 FMAX 64 L Z+0.535 FMAX 65 L Z-2.12 F250 66 L Y-26.036 F180 67 L Z+50 FMAX 68 L X+105.489 Y+30.875 FMAX 69 L Z-0.12 FMAX 70 L Z-2.775 F250 71 L Y-26.036 F180 72 L Z+50 FMAX 73 L X+95.489 Y+30.875 FMAX 74 L Z-0.12 FMAX 75 L Z-2.775 F250 76 L Y-26.036 F180 77 L Z+50 FMAX 78 L X+105.489 Y+30.875 FMAX 79 L Z-0.775 FMAX 80 L Z-3.43 F250 81 L Y-26.036 F180 82 L Z+50 FMAX 83 L X+95.489 Y+30.875 FMAX 84 L Z-0.775 FMAX 85 L Z-3.43 F250 86 L Y-26.036 F180 87 L Z+50 FMAX 88 L X+105.489 Y+30.875 FMAX 89 L Z-1.43 FMAX 90 L Z-4.085 F250 91 L Y-26.036 F180 92 L Z+50 FMAX 93 L X+95.489 Y+30.875 FMAX 94 L Z-1.43 FMAX 95 L Z-4.085 F250 96 L Y-26.036 F180 97 L Z+50 FMAX 98 L X+105.489 Y+30.875 FMAX 99 L Z-2.085 FMAX 100 L Z-4.74 F250 101 L Y-26.036 F180 102 L Z+50 FMAX 103 L X+95.489 Y+30.875 FMAX 104 L Z-2.085 FMAX 105 L Z-4.74 F250 106 L Y-26.036 F180 107 L Z+50 FMAX 108 L X+105.489 Y+30.875 FMAX 109 L Z-2.74 FMAX 110 L Z-5.395 F250 111 L Y-26.036 F180 112 L Z+50 FMAX 113 L X+95.489 Y+30.875 FMAX 114 L Z-2.74 FMAX 115 L Z-5.395 F250 116 L Y-26.036 F180 117 L Z+50 FMAX 118 L X+105.489 Y+30.875 FMAX 119 L Z-3.395 FMAX 120 L Z-6.05 F250 121 L Y-26.036 F180 122 L Z+50 FMAX 123 L X+95.489 Y+30.875 FMAX 124 L Z-3.395 FMAX 125 L Z-6.05 F250 126 L Y-26.036 F180 127 L Z+50 FMAX 128 L X+105.489 Y+30.875 FMAX 129 L Z-4.05 FMAX 130 L Z-6.1 F250 131 L Y-26.036 F180 132 L Z+50 FMAX 133 L X+95.489 Y+30.875 FMAX 134 L Z-4.05 FMAX 135 L Z-6.1 F250 136 L Y-26.036 F180 137 L Z+150 FMAX 138 CYCL DEF 32.0 TOLERANCJA 139 CYCL DEF 32.1 140 M5 141 L Z-15 R0 FMAX M91 M9 142 L X+273 Y+529 R0 FMAX M91 143 M0 144 ; 145 * - FREZ PLASKI FI 20 R04 146 TOOL CALL 1 Z S1000 147 TOOL DEF 3 148 * - STREFA 2 149 ;FREZ PLASKI FI 20 R04 TOOL - 1 DIA. OFF. - 1 LEN. - 1 DIA. - 20. 150 ;HOLDER - DEFAULT HOLDER 151 CYCL DEF 32.0 TOLERANCJA 152 CYCL DEF 32.1 T0.01 153 CYCL DEF 32.2 HSC-MODE:0 154 L A+0 FMAX 155 M3 156 L X+86 Y+31.026 FMAX M8 157 L Z+150 FMAX 158 L Z+2.5 FMAX 159 L Z-0.155 F250 160 L Y-22.026 F180 161 L Z+50 FMAX 162 L X+76 Y+31.026 FMAX 163 L Z+2.5 FMAX 164 L Z-0.155 F250 165 L Y-22.026 F180 166 L Z+50 FMAX 167 L X+66 Y+31.026 FMAX 168 L Z+2.5 FMAX 169 L Z-0.155 F250 170 L Y-22.026 F180 171 L Z+50 FMAX 172 L X+86 Y+31.026 FMAX 173 L Z+1.845 FMAX 174 L Z-0.81 F250 175 L Y-22.026 F180 176 L Z+50 FMAX 177 L X+76 Y+31.026 FMAX 178 L Z+1.845 FMAX 179 L Z-0.81 F250 180 L Y-22.026 F180 181 L Z+50 FMAX 182 L X+66 Y+31.026 FMAX 183 L Z+1.845 FMAX 184 L Z-0.81 F250 185 L Y-22.026 F180 186 L Z+50 FMAX 187 L X+86 Y+31.026 FMAX 188 L Z+1.19 FMAX 189 L Z-1.465 F250 190 L Y-22.026 F180 191 L Z+50 FMAX 192 L X+76 Y+31.026 FMAX 193 L Z+1.19 FMAX 194 L Z-1.465 F250 195 L Y-22.026 F180 196 L Z+50 FMAX 197 L X+66 Y+31.026 FMAX 198 L Z+1.19 FMAX 199 L Z-1.465 F250 200 L Y-22.026 F180 201 L Z+50 FMAX 202 L X+86 Y+31.026 FMAX 203 L Z+0.535 FMAX 204 L Z-2.12 F250 205 L Y-22.026 F180 206 L Z+50 FMAX 207 L X+76 Y+31.026 FMAX 208 L Z+0.535 FMAX 209 L Z-2.12 F250 210 L Y-22.026 F180 211 L Z+50 FMAX 212 L X+66 Y+31.026 FMAX 213 L Z+0.535 FMAX 214 L Z-2.12 F250 215 L Y-22.026 F180 216 L Z+50 FMAX 217 L X+86 Y+31.026 FMAX 218 L Z-0.12 FMAX 219 L Z-2.775 F250 220 L Y-22.026 F180 221 L Z+50 FMAX 222 L X+76 Y+31.026 FMAX 223 L Z-0.12 FMAX 224 L Z-2.775 F250 225 L Y-22.026 F180 226 L Z+50 FMAX 227 L X+66 Y+31.026 FMAX 228 L Z-0.12 FMAX 229 L Z-2.775 F250 230 L Y-22.026 F180 231 L Z+50 FMAX 232 L X+86 Y+31.026 FMAX 233 L Z-0.775 FMAX 234 L Z-3.43 F250 235 L Y-22.026 F180 236 L Z+50 FMAX 237 L X+76 Y+31.026 FMAX 238 L Z-0.775 FMAX 239 L Z-3.43 F250 240 L Y-22.026 F180 241 L Z+50 FMAX 242 L X+66 Y+31.026 FMAX 243 L Z-0.775 FMAX 244 L Z-3.43 F250 245 L Y-22.026 F180 246 L Z+50 FMAX 247 L X+86 Y+31.026 FMAX 248 L Z-1.43 FMAX 249 L Z-4.085 F250 250 L Y-22.026 F180 251 L Z+50 FMAX 252 L X+76 Y+31.026 FMAX 253 L Z-1.43 FMAX 254 L Z-4.085 F250 255 L Y-22.026 F180 256 L Z+50 FMAX 257 L X+66 Y+31.026 FMAX 258 L Z-1.43 FMAX 259 L Z-4.085 F250 260 L Y-22.026 F180 261 L Z+50 FMAX 262 L X+86 Y+31.026 FMAX 263 L Z-2.085 FMAX 264 L Z-4.74 F250 265 L Y-22.026 F180 266 L Z+50 FMAX 267 L X+76 Y+31.026 FMAX 268 L Z-2.085 FMAX 269 L Z-4.74 F250 270 L Y-22.026 F180 271 L Z+50 FMAX 272 L X+66 Y+31.026 FMAX 273 L Z-2.085 FMAX 274 L Z-4.74 F250 275 L Y-22.026 F180 276 L Z+50 FMAX 277 L X+86 Y+31.026 FMAX 278 L Z-2.74 FMAX 279 L Z-5.395 F250 280 L Y-22.026 F180 281 L Z+50 FMAX 282 L X+76 Y+31.026 FMAX 283 L Z-2.74 FMAX 284 L Z-5.395 F250 285 L Y-22.026 F180 286 L Z+50 FMAX 287 L X+66 Y+31.026 FMAX 288 L Z-2.74 FMAX 289 L Z-5.395 F250 290 L Y-22.026 F180 291 L Z+50 FMAX 292 L X+86 Y+31.026 FMAX 293 L Z-3.395 FMAX 294 L Z-6.05 F250 295 L Y-22.026 F180 296 L Z+50 FMAX 297 L X+76 Y+31.026 FMAX 298 L Z-3.395 FMAX 299 L Z-6.05 F250 300 L Y-22.026 F180 301 L Z+50 FMAX 302 L X+66 Y+31.026 FMAX 303 L Z-3.395 FMAX 304 L Z-6.05 F250 305 L Y-22.026 F180 306 L Z+50 FMAX 307 L X+86 Y+31.026 FMAX 308 L Z-4.05 FMAX 309 L Z-6.1 F250 310 L Y-22.026 F180 311 L Z+50 FMAX 312 L X+76 Y+31.026 FMAX 313 L Z-4.05 FMAX 314 L Z-6.1 F250 315 L Y-22.026 F180 316 L Z+50 FMAX 317 L X+66 Y+31.026 FMAX 318 L Z-4.05 FMAX 319 L Z-6.1 F250 320 L Y-22.026 F180 321 L Z+150 FMAX 322 ;TOOLPATH - FINISHFLOW 323 ;STOCK LEFT ON DRIVE SURFS = +0 324 M9 325 L X+65 Y+23.25 Z+21.6 FMAX 326 L Z+1.6 FMAX 327 L Z-3.4 F180 328 L Y+12.25 329 L Y-12.25 330 L Y-23.25 331 L Z-4.45 332 L Y-12.25 333 L Y+12.25 334 L Y+23.25 335 L Z-5.5 336 L Y+12.25 337 L Y-12.25 338 L Y-23.25 339 L Y-12.25 340 L Y+12.25 341 L Y+23.25 342 L X+65.006 343 L Z-5.587 344 L Y+12.25 345 L Y-12.25 346 L Y-23.25 347 L X+65.026 348 L Z-5.676 349 L Y-12.25 350 L Y+12.25 351 L Y+23.25 352 L X+65.062 353 L Z-5.765 354 L Y+12.25 355 L Y-12.25 356 L Y-23.25 357 L X+65.112 358 L Z-5.849 359 L Y-12.25 360 L Y+12.25 361 L Y+23.25 362 L X+65.176 363 L Z-5.924 364 L Y+12.25 365 L Y-12.25 366 L Y-23.25 367 L X+65.251 368 L Z-5.988 369 L Y-12.25 370 L Y+12.25 371 L Y+23.25 372 L X+65.335 373 L Z-6.038 374 L Y+12.25 375 L Y-12.25 376 L Y-23.25 377 L X+65.424 378 L Z-6.074 379 L Y-12.25 380 L Y+12.25 381 L Y+23.25 382 L X+65.513 383 L Z-6.094 384 L Y+12.25 385 L Y-12.25 386 L Y-23.25 387 L X+65.6 388 L Z-6.1 389 L Y-12.25 390 L Y+12.25 391 L Y+23.25 392 L Z-1.1 FMAX 393 L Z+18.9 FMAX 394 M8 395 L X+50 Y+31.026 Z+150 FMAX 396 L Z+2.5 FMAX 397 L Z-0.19 F250 398 L Y-24.026 F180 399 L Z+50 FMAX 400 L X+40 Y+31.026 FMAX 401 L Z+2.5 FMAX 402 L Z-0.19 F250 403 L Y-24.026 F180 404 L Z+50 FMAX 405 L X+30 Y+31.026 FMAX 406 L Z+2.5 FMAX 407 L Z-0.19 F250 408 L Y-24.026 F180 409 L Z+50 FMAX 410 L X+50 Y+31.026 FMAX 411 L Z+1.81 FMAX 412 L Z-0.88 F250 413 L Y-24.026 F180 414 L Z+50 FMAX 415 L X+40 Y+31.026 FMAX 416 L Z+1.81 FMAX 417 L Z-0.88 F250 418 L Y-24.026 F180 419 L Z+50 FMAX 420 L X+30 Y+31.026 FMAX 421 L Z+1.81 FMAX 422 L Z-0.88 F250 423 L Y-24.026 F180 424 L Z+50 FMAX 425 L X+50 Y+31.026 FMAX 426 L Z+1.12 FMAX 427 L Z-1.57 F250 428 L Y-24.026 F180 429 L Z+50 FMAX 430 L X+40 Y+31.026 FMAX 431 L Z+1.12 FMAX 432 L Z-1.57 F250 433 L Y-24.026 F180 434 L Z+50 FMAX 435 L X+30 Y+31.026 FMAX 436 L Z+1.12 FMAX 437 L Z-1.57 F250 438 L Y-24.026 F180 439 L Z+50 FMAX 440 L X+50 Y+31.026 FMAX 441 L Z+0.43 FMAX 442 L Z-2.26 F250 443 L Y-24.026 F180 444 L Z+50 FMAX 445 L X+40 Y+31.026 FMAX 446 L Z+0.43 FMAX 447 L Z-2.26 F250 448 L Y-24.026 F180 449 L Z+50 FMAX 450 L X+30 Y+31.026 FMAX 451 L Z+0.43 FMAX 452 L Z-2.26 F250 453 L Y-24.026 F180 454 L Z+50 FMAX 455 L X+50 Y+31.026 FMAX 456 L Z-0.26 FMAX 457 L Z-2.95 F250 458 L Y-24.026 F180 459 L Z+50 FMAX 460 L X+40 Y+31.026 FMAX 461 L Z-0.26 FMAX 462 L Z-2.95 F250 463 L Y-24.026 F180 464 L Z+50 FMAX 465 L X+30 Y+31.026 FMAX 466 L Z-0.26 FMAX 467 L Z-2.95 F250 468 L Y-24.026 F180 469 L Z+50 FMAX 470 L X+50 Y+31.026 FMAX 471 L Z-0.95 FMAX 472 L Z-3 F250 473 L Y-24.026 F180 474 L Z+50 FMAX 475 L X+40 Y+31.026 FMAX 476 L Z-0.95 FMAX 477 L Z-3 F250 478 L Y-24.026 F180 479 L Z+50 FMAX 480 L X+30 Y+31.026 FMAX 481 L Z-0.95 FMAX 482 L Z-3 F250 483 L Y-24.026 F180 484 L Z+150 FMAX 485 CYCL DEF 32.0 TOLERANCJA 486 CYCL DEF 32.1 487 M5 488 L Z-15 R0 FMAX M91 M9 489 L X+273 Y+529 R0 FMAX M91 490 M0 491 ; 492 * - FREZ PLASKI FI 20 R04 493 TOOL CALL 1 Z S1000 494 TOOL DEF 3 495 * - STREFA 3 496 ;FREZ PLASKI FI 20 R04 TOOL - 1 DIA. OFF. - 1 LEN. - 1 DIA. - 20. 497 ;HOLDER - DEFAULT HOLDER 498 CYCL DEF 32.0 TOLERANCJA 499 CYCL DEF 32.1 T0.01 500 CYCL DEF 32.2 HSC-MODE:0 501 L A+0 FMAX 502 M3 503 L X+17 Y+29.026 FMAX M8 504 L Z+150 FMAX 505 L Z+2.5 FMAX 506 L Z+0.05 F250 507 L Y-24.026 F180 508 L Z+50 FMAX 509 L X+7 Y+29.026 FMAX 510 L Z+2.5 FMAX 511 L Z+0.05 F250 512 L Y-24.026 F180 513 L Z+50 FMAX 514 L X+17 Y+29.026 FMAX 515 L Z+2.05 FMAX 516 L Z+0 F250 517 L Y-24.026 F180 518 L Z+50 FMAX 519 L X+7 Y+29.026 FMAX 520 L Z+2.05 FMAX 521 L Z+0 F250 522 L Y-24.026 F180 523 L Z+150 FMAX 524 CYCL DEF 32.0 TOLERANCJA 525 CYCL DEF 32.1 526 M5 527 L Z-15 R0 FMAX M91 M9 528 L X+273 Y+529 R0 FMAX M91 529 M0 530 ; 531 * - FREZ PLASKI FI 8 532 TOOL CALL 3 Z S1400 533 TOOL DEF 1 534 ;FREZ PLASKI FI 8 TOOL - 3 DIA. OFF. - 3 LEN. - 3 DIA. - 8. 535 ;HOLDER - DEFAULT HOLDER 536 CYCL DEF 32.0 TOLERANCJA 537 CYCL DEF 32.1 T0.01 538 CYCL DEF 32.2 HSC-MODE:0 539 L A+0 FMAX 540 M3 541 L X+12.27 Y-20.073 FMAX M8 542 L Z+50 FMAX 543 L Z+3 FMAX 544 L Z-0.6 F160 545 L Y-15.727 546 L X+10 Y-13.457 547 L Y+13.457 548 L X+12.27 Y+15.727 549 L Y+16.073 550 L X+7.73 551 L Y+15.727 552 L X+10 Y+13.457 553 L Y-13.457 554 L X+7.73 Y-15.727 555 L Y-20.073 556 L X+12.27 557 L Z-1.2 558 L Y-15.727 559 L X+10 Y-13.457 560 L Y+13.457 561 L X+12.27 Y+15.727 562 L Y+16.073 563 L X+7.73 564 L Y+15.727 565 L X+10 Y+13.457 566 L Y-13.457 567 L X+7.73 Y-15.727 568 L Y-20.073 569 L X+12.27 570 L Z-1.8 571 L Y-15.727 572 L X+10 Y-13.457 573 L Y+13.457 574 L X+12.27 Y+15.727 575 L Y+16.073 576 L X+7.73 577 L Y+15.727 578 L X+10 Y+13.457 579 L Y-13.457 580 L X+7.73 Y-15.727 581 L Y-20.073 582 L X+12.27 583 L Z-2.4 584 L Y-15.727 585 L X+10 Y-13.457 586 L Y+13.457 587 L X+12.27 Y+15.727 588 L Y+16.073 589 L X+7.73 590 L Y+15.727 591 L X+10 Y+13.457 592 L Y-13.457 593 L X+7.73 Y-15.727 594 L Y-20.073 595 L X+12.27 596 L Z-3 597 L Y-15.727 598 L X+10 Y-13.457 599 L Y+13.457 600 L X+12.27 Y+15.727 601 L Y+16.073 602 L X+7.73 603 L Y+15.727 604 L X+10 Y+13.457 605 L Y-13.457 606 L X+7.73 Y-15.727 607 L Y-20.073 608 L Z+50 FMAX 609 CYCL DEF 32.0 TOLERANCJA 610 CYCL DEF 32.1 611 M5 612 L Z-15 R0 FMAX M91 M9 613 L X+273 Y+529 R0 FMAX M91 614 M0 615 ; 616 * - FREZ PLASKI FI 8 617 TOOL CALL 3 Z S1400 618 TOOL DEF 1 619 * - KOMPENSACJA 620 ;FREZ PLASKI FI 8 TOOL - 3 DIA. OFF. - 3 LEN. - 3 DIA. - 8. 621 ;HOLDER - DEFAULT HOLDER 622 CYCL DEF 32.0 TOLERANCJA 623 CYCL DEF 32.1 T0.01 624 CYCL DEF 32.2 HSC-MODE:0 625 L A+0 FMAX 626 M3 627 L X+8.27 Y-20.073 FMAX M8 628 L Z+50 FMAX 629 L Z+3 FMAX 630 L Z-3 F160 631 L X+16.27 RL 632 L Y-14.07 633 L X+14 Y-11.8 634 L Y+11.8 635 L X+16.27 Y+14.07 636 L Y+20.073 637 L X+3.73 638 L Y+14.07 639 L X+6 Y+11.8 640 L Y-11.8 641 L X+3.73 Y-14.07 642 L Y-20.073 643 L X+11.73 R0 644 L Z+50 FMAX 645 CYCL DEF 32.0 TOLERANCJA 646 CYCL DEF 32.1 647 M5 648 L Z-15 R0 FMAX M91 M9 649 L X+273 Y+529 R0 FMAX M91 650 L A+0 FMAX M91 651 M2 652 END PGM sd_5458_01_01LB MM <file_sep>/cnc programming/Heidenhain/JF/PODZIALY/ZAN-PODZIAL-FP2-FI118.H 0 BEGIN PGM ZAN-PODZIAL-FP2-FI118 MM 1 BLK FORM 0.1 Z X-59 Y+0 Z-5 2 BLK FORM 0.2 X+59 Y+59 Z+0 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 ; 5 * - FP 2 LEWA 6 TOOL CALL 22 Z S9999 F500 DL+0 7 M3 M8 8 L Z+300 R0 FMAX 9 L X-61 Y+0 R0 FMAX 10 L Z+5 R0 FMAX 11 L Z+0 R0 F AUTO 12 LBL 1 13 L IZ-0.1 IX+10 R0 F AUTO 14 L IZ-0.1 IX-10 R0 15 LBL 0 16 CALL LBL 1 REP35 17 L Z+300 FMAX 18 ; 19 * - FP 2 PRAWA 20 TOOL CALL 22 Z S9999 F500 DL+0 21 M3 M8 22 L Z+300 R0 FMAX 23 L X+61 Y+0 R0 FMAX 24 L Z+5 R0 FMAX 25 L Z+0 R0 F AUTO 26 LBL 2 27 L IZ-0.1 IX-10 R0 F AUTO 28 L IZ-0.1 IX+10 R0 29 LBL 0 30 CALL LBL 2 REP35 31 L Z+300 FMAX 32 ; 33 M5 M9 34 ; 35 ;--------------------------------------------- 36 L Z-5 R0 FMAX M91 37 L X+360 Y+535 R0 FMAX M91 38 L M30 39 * - ----------------------------------------- 40 ; 41 END PGM ZAN-PODZIAL-FP2-FI118 MM <file_sep>/cnc programming/Heidenhain/zanizenie.h 0 BEGIN PGM zanizenie MM 1 BLK FORM 0.1 Z X-80 Y+0 Z-4 2 BLK FORM 0.2 X+0 Y+40 Z+1 3 ; 4 ;--------------------------------------------- 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 ; / 7 STOP 8 L X+0 Y+0 FMAX 9 ;--------------------------------------------- 10 ; 11 * - GLOW 20 ZGR 12 TOOL CALL 4 Z S1000 F200 13 TOOL DEF 25 14 M3 M7 15 L Z+20 FMAX 16 L X-82.5 Y+0 FMAX 17 L Z-0.45 FMAX 18 L Y+50 19 L X-93 20 L Y+0 21 L X-104 22 L Y+50 23 L Z+20 FMAX 24 ; 25 L X-82.5 Y+0 FMAX 26 L Z-0.9 FMAX 27 L Y+50 28 L X-93 29 L Y+0 30 L X-104 31 L Y+50 32 L Z+20 FMAX 33 ; 34 L Z+50 FMAX 35 M5 M9 36 ; 37 * - FP 8 WYK 38 TOOL CALL 25 Z S6000 F300 DL+0.01 DR-0.05 39 TOOL DEF 4 40 M3 M7 41 L Z+20 FMAX 42 L X-76 Y+0 FMAX 43 L Z-1 FMAX 44 L Y+50 F150 45 L X-80 F300 46 L Y+0 47 L X-84 48 L Y+50 49 L X-88 50 L Y+0 51 L X-92 52 L Y+50 53 L X-96 54 L Y+0 55 L X-100 56 L Y+50 57 L X-104 58 L Y+0 59 L X-108 60 L Y+50 61 L X-112 62 L Y+0 63 L Z+20 FMAX 64 ; 65 L Z+50 FMAX 66 M5 M9 67 ;--------------------------------------------- 68 L Z-5 R0 FMAX M91 69 L X+300 Y+535 R0 FMAX M91 70 L M30 71 END PGM zanizenie MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/PODWIERT.h 0 BEGIN PGM PODWIERT MM 1 BLK FORM 0.1 Z X-300 Y-100 Z+0 2 BLK FORM 0.2 X+0 Y+100 Z+150 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IZ+0 7 ;--------------------------------------------- 8 ; / 9 STOP 10 * - FP-8-PODW 11 TOOL CALL 14 Z S2000 F150 12 TOOL DEF 12 13 M8 14 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=+60 ;WSPOLRZEDNE POWIERZ. ~ Q204=+150 ;2-GA BEZPIECZNA WYS. ~ Q335=+9.05 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 15 CALL LBL 1 16 M5 M9 17 ; 18 * - NAW-STAL 19 TOOL CALL 12 Z S700 F30 / 20 STOP 21 TOOL DEF 28 22 M8 23 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+45 ;WSPOLRZEDNE POWIERZ. ~ Q204=+150 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 24 CALL LBL 1 25 M5 M9 26 ; 27 * - W-9 28 TOOL CALL 28 Z S450 F30 / 29 STOP 30 TOOL DEF 1 31 M8 32 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-25 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+45 ;WSPOLRZEDNE POWIERZ. ~ Q204=+150 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 33 CALL LBL 1 34 M5 M9 35 ; 36 * - FP-8 37 TOOL CALL 1 Z S2500 F70 / 38 STOP 39 TOOL DEF 30 40 M8 41 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-4 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.3 ;GLEBOKOSC DOSUWU ~ Q203=+24 ;WSPOLRZEDNE POWIERZ. ~ Q204=+150 ;2-GA BEZPIECZNA WYS. ~ Q335=+9.05 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 42 CALL LBL 1 43 M5 M9 44 ; 45 ; 46 ;--------------------------------------------- 47 L Z-5 R0 FMAX M91 48 L X+260 Y+535 R0 FMAX M91 49 L M30 50 * - ----------------------------------------- 51 * - LBL1 52 LBL 1 53 M3 54 L X-96 Y-66 R0 FMAX M99 55 L X-96 Y+66 R0 FMAX M99 56 L X-246 Y-66 R0 FMAX M99 57 L X-246 Y+66 R0 FMAX M99 58 LBL 0 59 END PGM PODWIERT MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/ROB.H 0 BEGIN PGM ROB MM 1 BLK FORM 0.1 Z X-100 Y-100 Z-15 2 BLK FORM 0.2 X+100 Y+100 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 L X+0 Y+0 R0 FMAX 6 ;--------------------------------------------- 7 ; 8 TOOL CALL 27 Z S8000 F1000 9 M8 M3 10 ; 11 ; 12 L X-80 Y-80 R0 FMAX 13 L Z+1 FMAX 14 L Z-0.1 F150 15 L Y-30 F AUTO 16 L X-65 17 CR X-65 Y-55 R+15 DR- 18 CC X-75 Y-35 19 L X-75 20 L X-55 Y-80 21 L Z+2 FMAX 22 ; 23 L X-40 Y-65 R0 FMAX 24 L Z+1 FMAX 25 L Z-0.1 F150 26 CR X-10 Y-65 R+15 DR+ F AUTO 27 L Y-45 28 CR X-40 Y-45 R+15 DR+ 29 L X-40 Y-70 30 L Z+2 FMAX 31 ; 32 L X+10 Y-80 R0 FMAX 33 L Z+1 FMAX 34 L Z-0.1 F150 35 L Y-30 F AUTO 36 L X+20 37 CR X+20 Y-55 R+15 DR- 38 L X+10 39 L X+25 40 CR X+25 Y-80 R+20 DR- 41 L X+10 42 L Z+2 FMAX 43 ; 44 ; 45 ; 46 ; 47 ; 48 L Z+50 FMAX 49 ; 50 ;--------------------------------------------- 51 L Z-5 R0 FMAX M91 52 L X+260 Y+535 R0 FMAX M91 53 L M30 54 * - ----------------------------------------- 55 * - LBL1 56 LBL 1 57 M3 58 L X+0 Y+0 R0 FMAX M99 59 LBL 0 60 END PGM ROB MM <file_sep>/cnc programming/Heidenhain/JF/DP/N060.00/PLAN.H 0 BEGIN PGM PLAN MM 1 BLK FORM 0.1 Z X-100 Y-100 Z-35 2 BLK FORM 0.2 X+100 Y+100 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; / 7 STOP 8 TOOL CALL 24 Z S2222 F222 DL-0.1 9 M8 M3 10 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-135 ;PKT.STARTU 1SZEJ OSI ~ Q226=-9 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.4 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+275 ;DLUG. 1-SZEJ STRONY ~ Q219=+22 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.4 ;<NAME> ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+15 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 11 CALL LBL 1 12 ; 13 M5 M9 14 ; 15 ;--------------------------------------------- 16 L Z-5 R0 FMAX M91 17 L X+260 Y+535 R0 FMAX M91 18 STOP 19 CALL PGM TNC:\5622-DP\N060.00\GAB.H 20 STOP 21 CALL PGM TNC:\5622-DP\N060.00\GAB-WYK.H 22 STOP 23 CALL PGM TNC:\5622-DP\N060.00\POMIAR2.H 24 STOP 25 CALL PGM TNC:\5622-DP\N060.00\FAZA.H 26 STOP 27 CALL PGM TNC:\5622-DP\N060.00\OTW1.H 28 STOP 29 CALL PGM TNC:\5622-DP\N060.00\dp_n060.H 30 L M30 31 * - ----------------------------------------- 32 * - LBL1 33 LBL 1 34 M3 35 L X+0 Y+0 R0 FMAX M99 36 LBL 0 37 ; 38 END PGM PLAN MM <file_sep>/cnc programming/Heidenhain/JF/CHWYTAKI/M5-CHWYTAKI-PCO.h 0 BEGIN PGM M5-CHWYTAKI-PCO MM 1 BLK FORM 0.1 Z X+0 Y-24.5 Z-9.8 2 BLK FORM 0.2 X+105.105 Y+0 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; / 7 STOP 8 * - NAW 9 TOOL CALL 23 Z S600 F30 10 TOOL DEF 16 11 M8 12 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.4 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 13 CALL LBL 1 14 M5 M9 15 ; 16 * - W 4.2 17 TOOL CALL 16 Z S950 F30 / 18 STOP 19 TOOL DEF 3 20 M8 21 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-13 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 22 CALL LBL 1 23 M5 M9 24 ; 25 * - GW M5 26 TOOL CALL 3 Z S100 27 STOP 28 ; 29 ; TEREBOR 30 ; 31 TOOL DEF 30 32 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-10 ;GLEBOKOSC GWINTU ~ Q239=+0.8 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 33 CALL LBL 1 34 M5 M9 35 ; 36 ;--------------------------------------------- 37 L Z-5 R0 FMAX M91 38 L X+260 Y+535 R0 FMAX M91 39 L M30 40 * - ----------------------------------------- 41 * - LBL1 42 LBL 1 43 M3 44 ; 45 * - WSPOLRZEDNE DLA BAZY "Y" NA SZTYWNEJ SZCZECE 46 L X+10 Y-8.5 R0 FMAX M99 47 ; / 48 * - WSPOLRZEDNE DLA BAZY "Y" NA RUCHOMEJ SZCZECE / 49 L X+10 Y+8.5 R0 FMAX M99 50 ; 51 LBL 0 52 END PGM M5-CHWYTAKI-PCO MM <file_sep>/cnc programming/Heidenhain/JF/PLYTA-SP-n160/GAB3.h 0 BEGIN PGM GAB3 MM 1 BLK FORM 0.1 Z X+0 Y-15 Z-5 2 BLK FORM 0.2 X+208.9 Y+15 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 R0 FMAX 7 ; 8 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 9 CYCL DEF 7.0 PUNKT BAZOWY 10 CYCL DEF 7.1 IZ+0 11 ;--------------------------------------------- 12 ; / 13 STOP 14 * - GLOW-20 15 TOOL CALL 22 Z S6000 F2000 DL+0 16 TOOL DEF 30 17 M8 M3 18 ; 19 ; 20 L X+0 Y+20 FMAX 21 L Z+0 FMAX 22 ; 23 Q22 = - 3 24 LBL 2 25 L Z+Q22 26 L Y-0.05 RL 27 L X+400 28 L Z+5 R0 FMAX 29 L X+0 Y+20 FMAX 30 Q22 = Q22 - 3 31 LBL 0 32 CALL LBL 2 REP14 33 ; 34 M5 M9 35 ; 36 ;--------------------------------------------- 37 L Z-5 R0 FMAX M91 38 L X+260 Y+535 R0 FMAX M91 39 L M30 40 * - ----------------------------------------- 41 * - LBL1 / 42 LBL 1 / 43 M3 / 44 L X+0 Y+0 R0 FMAX M99 / 45 LBL 0 46 END PGM GAB3 MM <file_sep>/cnc programming/Heidenhain/JF/SD/WYCIECIA-KORYGOWANA-12mm.H 0 BEGIN PGM WYCIECIA-KORYGOWANA-12mm MM 1 ;MASTERCAM - X9 2 ;MCX FILE -~ \\NCNCSERV\NCNC\00NZL\SD\SDN10102\MCX\DYSTANS_SD_N101_02_AVIA_POD~ GWINTOWNIK.MCX-9 3 ;POST - MPPOSTABILITY_AVIA_VMC_800_4X.PST 4 ;PROGRAM - SDN10102A.h 5 ;DATE - 2017.09.20 6 ;TIME - 1:44 PM 7 ;1 - 20. FLAT ENDMILL - D20.000mm 8 ;2 - NAWIERTAK 6 - D4.000mm 9 ;3 - 11.7 DRILL - D11.700mm 10 ;5 - 10 / 45 CHAMFER MILL - D10.000mm 11 ;6 - G1/4" TAP RH - D13.158mm 12 BLK FORM 0.1 Z X-69.5 Y-103.5 Z-69.5 13 BLK FORM 0.2 X+69.5 Y+35.5 Z+69.5 14 M129 15 ; 16 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 17 ; 18 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 19 ; / 20 L Z+300 R0 FMAX 21 L X+0 Y+0 R0 FMAX 22 ; / 23 STOP 24 TOOL CALL 30 Z 25 TOOL DEF 8 26 ; 27 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=-13 ;SRODEK W 2-SZEJ OSI ~ Q311=+120 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=+40 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+100 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 28 ; 29 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 30 TCH PROBE 417 PKT.BAZOWY TS.-OSI ~ Q263=+0 ;1.PKT POMIAROW 1.OSI ~ Q264=-13 ;1.PKT 2.OSI ~ Q294=+69.5 ;1.PKT 3.OSI ~ Q320=+0 ;BEZPIECZNA WYSOKOSC ~ Q260=+100 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q333=+69.5 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 31 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 32 ; 33 * - 20. FLAT ENDMILL / 34 STOP 35 TOOL CALL 22 Z S4000 36 TOOL DEF 9 37 ; 20. FLAT ENDMILL TOOL - 1 DIA. OFF. - 1 LEN. - 1 DIA. - 20. 38 ;HOLDER - DEFAULT HOLDER 39 CYCL DEF 32.0 TOLERANCJA 40 CYCL DEF 32.1 T0.003 41 CYCL DEF 32.2 HSC-MODE:0 42 M3 43 L X-51.05 Y-45.884 FMAX M8 44 L Z+96.6 FMAX 45 L Z+76.6 FMAX 46 L Z+63.337 F600 47 L Y+10 48 L Z+93.338 FMAX 49 L X-44.05 Y-45.884 FMAX 50 L Z+76.6 FMAX 51 L Z+63.337 F600 52 L Y+10 53 L Z+93.338 FMAX 54 L X-37.05 Y-45.884 FMAX 55 L Z+76.6 FMAX 56 L Z+63.337 F600 57 L Y+10 58 L Z+93.338 FMAX 59 L X-30.05 Y-45.884 FMAX 60 L Z+76.6 FMAX 61 L Z+63.337 F600 62 L Y+10 63 L Z+93.338 FMAX 64 L X-51.05 Y-45.884 FMAX 65 L Z+73.338 FMAX 66 L Z+60.075 F600 67 L Y+10 68 L Z+90.075 FMAX 69 L X-44.05 Y-45.884 FMAX 70 L Z+73.338 FMAX 71 L Z+60.075 F600 72 L Y+10 73 L Z+90.075 FMAX 74 L X-37.05 Y-45.884 FMAX 75 L Z+73.338 FMAX 76 L Z+60.075 F600 77 L Y+10 78 L Z+90.075 FMAX 79 L X-30.05 Y-45.884 FMAX 80 L Z+73.338 FMAX 81 L Z+60.075 F600 82 L Y+10 83 L Z+90.075 FMAX 84 L X-51.05 Y-45.884 FMAX 85 L Z+70.075 FMAX 86 L Z+56.813 F600 87 L Y+10 88 L Z+86.813 FMAX 89 L X-44.05 Y-45.884 FMAX 90 L Z+70.075 FMAX 91 L Z+56.813 F600 92 L Y+10 93 L Z+86.813 FMAX 94 L X-37.05 Y-45.884 FMAX 95 L Z+70.075 FMAX 96 L Z+56.813 F600 97 L Y+10 98 L Z+86.813 FMAX 99 L X-30.05 Y-45.884 FMAX 100 L Z+70.075 FMAX 101 L Z+56.813 F600 102 L Y+10 103 L Z+86.813 FMAX 104 L X-51.05 Y-45.884 FMAX 105 L Z+66.813 FMAX 106 L Z+53.55 F600 107 L Y+10 108 L Z+83.55 FMAX 109 L X-44.05 Y-45.884 FMAX 110 L Z+66.813 FMAX 111 L Z+53.55 F600 112 L Y+10 113 L Z+83.55 FMAX 114 L X-37.05 Y-45.884 FMAX 115 L Z+66.813 FMAX 116 L Z+53.55 F600 117 L Y+10 118 L Z+83.55 FMAX 119 L X-30.05 Y-45.884 FMAX 120 L Z+66.813 FMAX 121 L Z+53.55 F600 122 L Y+10 123 L Z+83.55 FMAX 124 L X-51.05 Y-45.884 FMAX 125 L Z+63.55 FMAX 126 L Z+53.5 F600 127 L Y+10 128 L Z+83.5 FMAX 129 L X-44.05 Y-45.884 FMAX 130 L Z+63.55 FMAX 131 L Z+53.5 F600 132 L Y+10 133 L Z+83.5 FMAX 134 L X-37.05 Y-45.884 FMAX 135 L Z+63.55 FMAX 136 L Z+53.5 F600 137 L Y+10 138 L Z+83.5 FMAX 139 L X-30.05 Y-45.884 FMAX 140 L Z+63.55 FMAX 141 L Z+53.5 F600 142 L Y+10 143 L Z+83.5 FMAX 144 L X-30 Y-45.884 FMAX 145 L Z+63.55 FMAX 146 L Z+53.5 F600 147 L Y+10 148 L Z+96.6 FMAX 149 L X+51.05 Y+13.884 FMAX 150 L Z+76.6 FMAX 151 L Z+63.337 F600 152 L Y-42 153 L Z+93.338 FMAX 154 L X+44.05 Y+13.884 FMAX 155 L Z+76.6 FMAX 156 L Z+63.337 F600 157 L Y-42 158 L Z+93.338 FMAX 159 L X+37.05 Y+13.884 FMAX 160 L Z+76.6 FMAX 161 L Z+63.337 F600 162 L Y-42 163 L Z+93.338 FMAX 164 L X+30.05 Y+13.884 FMAX 165 L Z+76.6 FMAX 166 L Z+63.337 F600 167 L Y-42 168 L Z+93.338 FMAX 169 L X+51.05 Y+13.884 FMAX 170 L Z+73.338 FMAX 171 L Z+60.075 F600 172 L Y-42 173 L Z+90.075 FMAX 174 L X+44.05 Y+13.884 FMAX 175 L Z+73.338 FMAX 176 L Z+60.075 F600 177 L Y-42 178 L Z+90.075 FMAX 179 L X+37.05 Y+13.884 FMAX 180 L Z+73.338 FMAX 181 L Z+60.075 F600 182 L Y-42 183 L Z+90.075 FMAX 184 L X+30.05 Y+13.884 FMAX 185 L Z+73.338 FMAX 186 L Z+60.075 F600 187 L Y-42 188 L Z+90.075 FMAX 189 L X+51.05 Y+13.884 FMAX 190 L Z+70.075 FMAX 191 L Z+56.813 F600 192 L Y-42 193 L Z+86.813 FMAX 194 L X+44.05 Y+13.884 FMAX 195 L Z+70.075 FMAX 196 L Z+56.813 F600 197 L Y-42 198 L Z+86.813 FMAX 199 L X+37.05 Y+13.884 FMAX 200 L Z+70.075 FMAX 201 L Z+56.813 F600 202 L Y-42 203 L Z+86.813 FMAX 204 L X+30.05 Y+13.884 FMAX 205 L Z+70.075 FMAX 206 L Z+56.813 F600 207 L Y-42 208 L Z+86.813 FMAX 209 L X+51.05 Y+13.884 FMAX 210 L Z+66.813 FMAX 211 L Z+53.55 F600 212 L Y-42 213 L Z+83.55 FMAX 214 L X+44.05 Y+13.884 FMAX 215 L Z+66.813 FMAX 216 L Z+53.55 F600 217 L Y-42 218 L Z+83.55 FMAX 219 L X+37.05 Y+13.884 FMAX 220 L Z+66.813 FMAX 221 L Z+53.55 F600 222 L Y-42 223 L Z+83.55 FMAX 224 L X+30.05 Y+13.884 FMAX 225 L Z+66.813 FMAX 226 L Z+53.55 F600 227 L Y-42 228 L Z+83.55 FMAX 229 L X+51.05 Y+13.884 FMAX 230 L Z+63.55 FMAX 231 L Z+53.5 F600 232 L Y-42 233 L Z+83.5 FMAX 234 L X+44.05 Y+13.884 FMAX 235 L Z+63.55 FMAX 236 L Z+53.5 F600 237 L Y-42 238 L Z+83.5 FMAX 239 L X+37.05 Y+13.884 FMAX 240 L Z+63.55 FMAX 241 L Z+53.5 F600 242 L Y-42 243 L Z+83.5 FMAX 244 L X+30.05 Y+13.884 FMAX 245 L Z+63.55 FMAX 246 L Z+53.5 F600 247 L Y-42 248 L Z+83.5 FMAX 249 L X+30 Y+13.884 FMAX 250 L Z+63.55 FMAX 251 L Z+53.5 F600 252 L Y-42 253 L Z+96.6 FMAX 254 L X-63.55 Y-44.884 Z+74.362 FMAX 255 L Z+54.362 FMAX 256 L Z+40.889 F600 257 L Y+10 258 L Z+70.889 FMAX 259 L Y-44.884 FMAX 260 L Z+50.889 FMAX 261 L Z+37.416 F600 262 L Y+10 263 L Z+67.416 FMAX 264 L Y-44.884 FMAX 265 L Z+47.416 FMAX 266 L Z+33.943 F600 267 L Y+10 268 L Z+63.943 FMAX 269 L Y-44.884 FMAX 270 L Z+43.943 FMAX 271 L Z+30.469 F600 272 L Y+10 273 L Z+60.469 FMAX 274 L Y-44.884 FMAX 275 L Z+40.469 FMAX 276 L Z+26.996 F600 277 L Y+10 278 L Z+56.996 FMAX 279 L Y-44.884 FMAX 280 L Z+36.996 FMAX 281 L Z+23.523 F600 282 L Y+10 283 L Z+53.523 FMAX 284 L Y-44.884 FMAX 285 L Z+33.523 FMAX 286 L Z+20.05 F600 287 L Y+10 288 L Z+50.05 FMAX 289 L Y-44.884 FMAX 290 L Z+30.05 FMAX 291 L Z+20 F600 292 L Y+10 293 L Z+50 FMAX 294 L X-63.5 Y-44.884 FMAX 295 L Z+30.05 FMAX 296 L Z+20 F600 297 L Y+10 298 L Z+74.362 FMAX 299 L X+63.55 Y+13.884 FMAX 300 L Z+54.362 FMAX 301 L Z+40.889 F600 302 L Y-42 303 L Z+70.889 FMAX 304 L X+63.5 Y+13.884 FMAX 305 L Z+54.362 FMAX 306 L Z+40.889 F600 307 L Y-42 308 L Z+70.889 FMAX 309 L X+63.55 Y+13.884 FMAX 310 L Z+50.889 FMAX 311 L Z+37.416 F600 312 L Y-42 313 L Z+67.416 FMAX 314 L X+63.5 Y+13.884 FMAX 315 L Z+50.889 FMAX 316 L Z+37.416 F600 317 L Y-42 318 L Z+67.416 FMAX 319 L X+63.55 Y+13.884 FMAX 320 L Z+47.416 FMAX 321 L Z+33.943 F600 322 L Y-42 323 L Z+63.943 FMAX 324 L X+63.5 Y+13.884 FMAX 325 L Z+47.416 FMAX 326 L Z+33.943 F600 327 L Y-42 328 L Z+63.943 FMAX 329 L X+63.55 Y+13.884 FMAX 330 L Z+43.943 FMAX 331 L Z+30.469 F600 332 L Y-42 333 L Z+60.469 FMAX 334 L X+63.5 Y+13.884 FMAX 335 L Z+43.943 FMAX 336 L Z+30.469 F600 337 L Y-42 338 L Z+60.469 FMAX 339 L X+63.55 Y+13.884 FMAX 340 L Z+40.469 FMAX 341 L Z+26.996 F600 342 L Y-42 343 L Z+56.996 FMAX 344 L X+63.5 Y+13.884 FMAX 345 L Z+40.469 FMAX 346 L Z+26.996 F600 347 L Y-42 348 L Z+56.996 FMAX 349 L X+63.55 Y+13.884 FMAX 350 L Z+36.996 FMAX 351 L Z+23.523 F600 352 L Y-42 353 L Z+53.523 FMAX 354 L X+63.5 Y+13.884 FMAX 355 L Z+36.996 FMAX 356 L Z+23.523 F600 357 L Y-42 358 L Z+53.523 FMAX 359 L X+63.55 Y+13.884 FMAX 360 L Z+33.523 FMAX 361 L Z+20.05 F600 362 L Y-42 363 L Z+50.05 FMAX 364 L X+63.5 Y+13.884 FMAX 365 L Z+33.523 FMAX 366 L Z+20.05 F600 367 L Y-42 368 L Z+50.05 FMAX 369 L X+63.55 Y+13.884 FMAX 370 L Z+30.05 FMAX 371 L Z+20 F600 372 L Y-42 373 L Z+50 FMAX 374 L X+63.5 Y+13.884 FMAX 375 L Z+30.05 FMAX 376 L Z+20 F600 377 L Y-42 378 L Z+74.362 FMAX 379 CYCL DEF 32.0 TOLERANCJA 380 CYCL DEF 32.1 381 M5 M9 382 ; 383 * - NAWIERTAK 384 TOOL CALL 9 Z S1111 DL-1 / 385 STOP 386 TOOL DEF 29 387 ;NAWIERTAK 6 TOOL - 2 DIA. OFF. - 2 LEN. - 2 DIA. - 4. 388 ;HOLDER - DEFAULT HOLDER 389 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 390 M3 391 L X-34.5 Y-12 FMAX M8 392 L Z+103.5 FMAX 393 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206=+100 ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0.5 ;PRZER. CZAS.NA GORZE ~ Q203=+53.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 394 L X-34.5 Y-12 FMAX M99 395 L X+34.5 Y-12 FMAX M99 396 M5 M9 397 ; 398 * - 11.7 DRILL 399 TOOL CALL 21 Z S650 / 400 STOP 401 TOOL DEF 9 402 ;11.7 DRILL TOOL - 3 DIA. OFF. - 3 LEN. - 3 DIA. - 11.7 403 ;HOLDER - DEFAULT HOLDER 404 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 405 M3 406 L X-34.5 Y-12 FMAX M8 407 L Z+103.5 FMAX 408 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-29.515 ;GLEBOKOSC ~ Q206=+120 ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q210=+0.5 ;PRZER. CZAS.NA GORZE ~ Q203=+53.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 409 L X-34.5 Y-12 FMAX M99 410 L X+34.5 Y-12 FMAX M99 411 M5 M9 412 ; 413 * - 10 / 45 CHAMFER MILL 414 TOOL CALL 9 Z S5000 F200 DL+0 DR-3 415 TOOL DEF 2 / 416 STOP 417 L X-34.5 Y-12 FMAX M3 M8 418 L Z+103.5 FMAX 419 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+2 ;GLEBOKOSC DOSUWU ~ Q203=+53.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.8 ;SREDNICA NOMINALNA ~ Q342=+11 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 420 L X-34.5 Y-12 FMAX M99 421 L X+34.5 Y-12 FMAX M99 422 M5 M9 423 ; 424 * - G1/4" TAP RH 425 TOOL CALL 28 Z S150 / 426 STOP 427 TOOL DEF 30 428 ; G1/4" TAP RH TOOL - 6 DIA. OFF. - 6 LEN. - 6 DIA. - 13.158 429 ;HOLDER - DEFAULT HOLDER 430 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 431 M3 432 L X-34.5 Y-12 FMAX M8 433 L Z+106.5 FMAX 434 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q201=-17 ;GLEBOKOSC GWINTU ~ Q239=+1.337 ;SKOK GWINTU ~ Q203=+56.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 435 L X-34.5 Y-12 FMAX M99 436 L X+34.5 Y-12 FMAX M99 437 M5 M9 438 ; 439 L Z-5 R0 FMAX M91 440 L X+260 Y+535 R0 FMAX M91 441 L M30 442 END PGM WYCIECIA-KORYGOWANA-12mm MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/K00BKI/KUBKI-SONDA-Q.H 0 BEGIN PGM KUBKI-SONDA-Q MM 1 ; 2 Q80 = 156 ; ROZSTAW KUBKOW 3 Q81 = 24 ; SREDNICA KUBKOW 4 Q82 = 15.8 ; GLEBOKOSC KUBKOW 5 Q83 = 38 ; X - DLA 1. PARY 6 Q84 = 119 ; X - DLA 2. PARY 7 Q85 = 223 ; X - DLA 3. PARY 8 Q86 = 0.15 ; DL - DLA 1. PARY 9 Q87 = 0.15 ; DL - DLA 2. PARY 10 Q88 = 0.15 ; DL - DLA 3. PARY 11 ; 12 ;--- 13 Q50 = - 10 ; X1 - 1 PLASZCZYZNA 14 Q51 = - 63 ; Y1 - 1 PLASZCZYZNA 15 Q52 = 10 ; X2/X3 - 1 PLASZCZYZNA 16 Q53 = 63 ; Y2/Y3 - 1 PLASZCZYZNA 17 ; 18 Q60 = - 10 ; X1 - 2 PLASZCZYZNA 19 Q61 = - 63 ; Y1 - 2 PLASZCZYZNA 20 Q62 = 10 ; X2/X3 - 2 PLASZCZYZNA 21 Q63 = 63 ; Y2/Y3 - 2 PLASZCZYZNA 22 ; 23 Q70 = - 10 ; X1 - 3 PLASZCZYZNA 24 Q71 = - 63 ; Y1 - 3 PLASZCZYZNA 25 Q72 = 10 ; X2/X3 - 3 PLASZCZYZNA 26 Q73 = 63 ; Y2/Y3 - 3 PLASZCZYZNA 27 ;----------------------------------- 28 ;----------------------------------- 29 ;----------------------------------- 30 Q90 = Q80 / 2 ; rozstaw / 2 31 Q91 = Q81 - 0.2 ; srednica zgrubnie 32 Q92 = Q81 + 0.05 ; srednica wyk. 33 Q93 = Q82 - 0.1 ; glebokosc zgrubnie 34 ;----------------------------------- 35 ;----------------------------------- 36 ;----------------------------------- 37 BLK FORM 0.1 Z X+0 Y-90 Z-75 38 BLK FORM 0.2 X+241 Y+90 Z+0 39 CALL PGM TNC:\Z19 40 CALL PGM TNC:\REF 41 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 42 PLANE RESET TURN F4000 43 ; 44 STOP 45 * - SONDA 46 TOOL CALL "SONDA" Z S10 47 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+0 ;1.PKT POMIAROW 1.OSI ~ Q264=-56 ;1.PKT 2.OSI ~ Q261=-5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q272=+1 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 48 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 49 TCH PROBE 427 POMIAR WSPOLRZEDNA ~ Q263=+0 ;1.PKT POMIAROW 1.OSI ~ Q264=-56 ;1.PKT 2.OSI ~ Q261=-5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q272=+1 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q281=+1 ;PROTOKOL POMIARU ~ Q288=+0.004 ;MAKSYMALNY WYMIAR ~ Q289=-0.004 ;MINIMALNY WYMIAR ~ Q309=+1 ;PGM-STOP JESLI BLAD ~ Q330=+0 ;NARZEDZIE 50 M140 MB MAX 51 ; 52 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 53 PLANE RESET TURN F4000 54 ; 55 * - para 1: ustawianie plaszczyzny (sonda) 56 TOOL CALL 1 Z S50 57 CYCL DEF 7.0 PUNKT BAZOWY 58 CYCL DEF 7.1 X+Q83 59 TCH PROBE 431 POMIAR PLASZCZYZNY ~ Q263=+Q50 ;1.PKT POMIAROW 1.OSI ~ Q264=+Q51 ;1.PKT 2.OSI ~ Q294=+0 ;1.PKT 3.OSI ~ Q265=+Q52 ;2-GI PUNKT W 1. OSI ~ Q266=-Q53 ;2-GI PUNKT W 2. OSI ~ Q295=+0 ;2-GI PUNKT W 3. OSI ~ Q296=+Q52 ;3-CI PUNKT W 1. OSI ~ Q297=+Q53 ;3-CI PUNKT W 2. OSI ~ Q298=+0 ;3-CI PUNKT W 3. OSI ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q281=+1 ;PROTOKOL POMIARU 60 M140 MB MAX 61 ; 62 * - para 1: FP-14 63 TOOL CALL 7 Z S5000 F1200 DL+Q86 64 PLANE SPATIAL SPA+Q170 SPB+Q171 SPC+Q172 TURN F4000 / 65 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-Q93 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+2 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+Q91 ;SREDNICA NOMINALNA ~ Q342=+5 ;WYW.WSTEP. SREDNICA 66 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+28 ;DLUGOSC ROWKA ~ Q219=+24 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-Q93 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+666 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 67 LBL 1 68 L X+0 Y-Q90 R0 FMAX M99 M13 69 L X+0 Y+Q90 R0 FMAX M99 M13 70 LBL 0 / 71 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-Q82 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+Q92 ;SREDNICA NOMINALNA ~ Q342=+Q91 ;WYW.WSTEP. SREDNICA 72 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+28 ;DLUGOSC ROWKA ~ Q219=+24 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-Q82 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+666 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 73 CALL LBL 1 74 M5 75 M9 76 M140 MB MAX 77 PLANE RESET TURN F4000 78 ; 79 * - PRZEDMUCH 80 CYCL DEF 7.0 PUNKT BAZOWY 81 CYCL DEF 7.1 X+Q84 82 TOOL CALL 7 Z S5000 F150 83 M3 84 M25 85 LBL 60 ;PRZEDMUCH 86 L X-2 Y-67 FMAX 87 L Z+15 FMAX 88 L Z+5 F1500 89 L X+2 F AUTO 90 L Y+67 F5000 91 L X-2 F AUTO 92 L Z+50 FMAX 93 LBL 0 94 M5 95 M9 96 M140 MB MAX 97 PLANE RESET TURN F4000 98 ; 99 * - para 2: ustawianie plaszczyzny (sonda) 100 ; 101 TOOL CALL 1 Z S50 102 PLANE RESET TURN F4000 103 CYCL DEF 7.0 PUNKT BAZOWY 104 CYCL DEF 7.1 X+Q84 105 TCH PROBE 431 POMIAR PLASZCZYZNY ~ Q263=+Q60 ;1.PKT POMIAROW 1.OSI ~ Q264=+Q61 ;1.PKT 2.OSI ~ Q294=+0 ;1.PKT 3.OSI ~ Q265=+Q62 ;2-GI PUNKT W 1. OSI ~ Q266=-Q63 ;2-GI PUNKT W 2. OSI ~ Q295=+0 ;2-GI PUNKT W 3. OSI ~ Q296=+Q62 ;3-CI PUNKT W 1. OSI ~ Q297=+Q63 ;3-CI PUNKT W 2. OSI ~ Q298=+0 ;3-CI PUNKT W 3. OSI ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q281=+1 ;PROTOKOL POMIARU 106 M140 MB MAX 107 ; 108 * - para 2: FP-14 109 TOOL CALL 7 Z S5000 F1200 DL+Q87 110 PLANE SPATIAL SPA+Q170 SPB+Q171 SPC+Q172 TURN F4000 / 111 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-Q93 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+2 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+Q91 ;SREDNICA NOMINALNA ~ Q342=+5 ;WYW.WSTEP. SREDNICA 112 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+28 ;DLUGOSC ROWKA ~ Q219=+24 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-Q93 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+666 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 113 CALL LBL 1 / 114 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-Q82 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+Q92 ;SREDNICA NOMINALNA ~ Q342=+Q91 ;WYW.WSTEP. SREDNICA 115 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+28 ;DLUGOSC ROWKA ~ Q219=+24 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-Q82 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+666 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 116 CALL LBL 1 117 M5 118 M9 119 M140 MB MAX 120 PLANE RESET TURN F4000 121 ; 122 * - PRZEDMUCH 123 ; 124 CYCL DEF 7.0 PUNKT BAZOWY 125 CYCL DEF 7.1 X+Q85 126 TOOL CALL 7 Z S5000 F150 127 M3 128 M25 129 CALL LBL 60 130 M5 131 M9 132 M140 MB MAX 133 PLANE RESET TURN F4000 134 ; 135 * - para 3: ustawianie plaszczyzny (sonda) 136 TOOL CALL 1 Z S50 137 CYCL DEF 7.0 PUNKT BAZOWY 138 CYCL DEF 7.1 X+Q85 139 TCH PROBE 431 POMIAR PLASZCZYZNY ~ Q263=+Q70 ;1.PKT POMIAROW 1.OSI ~ Q264=+Q71 ;1.PKT 2.OSI ~ Q294=+0 ;1.PKT 3.OSI ~ Q265=+Q72 ;2-GI PUNKT W 1. OSI ~ Q266=-Q73 ;2-GI PUNKT W 2. OSI ~ Q295=+0 ;2-GI PUNKT W 3. OSI ~ Q296=+Q72 ;3-CI PUNKT W 1. OSI ~ Q297=+Q73 ;3-CI PUNKT W 2. OSI ~ Q298=+0 ;3-CI PUNKT W 3. OSI ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q281=+1 ;PROTOKOL POMIARU 140 M140 MB MAX 141 ; 142 * - para 3: FP-14 143 TOOL CALL 7 Z S5000 F1200 DL+Q88 144 PLANE SPATIAL SPA+Q170 SPB+Q171 SPC+Q172 TURN F4000 / 145 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-Q93 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+2 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+Q91 ;SREDNICA NOMINALNA ~ Q342=+5 ;WYW.WSTEP. SREDNICA 146 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+28 ;DLUGOSC ROWKA ~ Q219=+24 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-Q93 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+666 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 147 CALL LBL 1 / 148 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-Q82 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+Q92 ;SREDNICA NOMINALNA ~ Q342=+Q91 ;WYW.WSTEP. SREDNICA 149 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+28 ;DLUGOSC ROWKA ~ Q219=+24 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-Q82 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+666 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 150 CALL LBL 1 151 M5 152 M9 153 ; 154 CALL PGM TNC:\Z19 155 CALL PGM TNC:\REF 156 PLANE RESET TURN F4000 157 CALL PGM TNC:\FIN 158 M30 159 END PGM KUBKI-SONDA-Q MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/RPi4B/RPI-BASE.H 0 BEGIN PGM RPI-BASE MM 1 BLK FORM 0.1 Z X-60 Y-60 Z-22 2 BLK FORM 0.2 X+60 Y+60 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 STOP 7 ; 8 * - FP-12 -PLAN 9 TOOL CALL 17 Z S9987 F1111 10 STOP 11 M8 12 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+1 ;STRATEGIA ~ Q225=-60 ;PKT.STARTU 1SZEJ OSI ~ Q226=-60 ;PKT.STARTU 2GIEJ OSI ~ Q227=+1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+120 ;DLUG. 1-SZEJ STRONY ~ Q219=+120 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 13 CALL LBL 2 14 M5 M9 15 ; 16 * - FP-12 -GAB/TOR 17 TOOL CALL 13 Z S6000 F3000 18 STOP 19 M8 20 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+85 ;DLUG. 1-SZEJ STRONY ~ Q424=+118 ;WYMIAR POLWYROBU 1 ~ Q219=+85 ;DLUG. 2-GIEJ STRONY ~ Q425=+107 ;WYMIAR POLWYROBU 2 ~ Q220=+3 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-14.4 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 21 CALL LBL 2 22 M5 M9 23 ; 24 * - FP-12 -GAB WYK 25 TOOL CALL 17 Z S9987 F700 DR+0 26 STOP 27 M8 28 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+85 ;DLUG. 1-SZEJ STRONY ~ Q424=+87 ;WYMIAR POLWYROBU 1 ~ Q219=+85 ;DLUG. 2-GIEJ STRONY ~ Q425=+87 ;WYMIAR POLWYROBU 2 ~ Q220=+3 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-14.4 ;GLEBOKOSC ~ Q202=+14.4 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 29 CALL LBL 2 30 M5 M9 31 ; 32 * - FP-12 -GAB WYK 33 TOOL CALL 17 Z S9987 F700 DR-0.02 34 STOP 35 M8 36 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+85 ;DLUG. 1-SZEJ STRONY ~ Q424=+86 ;WYMIAR POLWYROBU 1 ~ Q219=+85 ;DLUG. 2-GIEJ STRONY ~ Q425=+86 ;WYMIAR POLWYROBU 2 ~ Q220=+3 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-14.4 ;GLEBOKOSC ~ Q202=+14.4 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 37 CALL LBL 2 38 M5 M9 39 ; 40 * - NAW 41 TOOL CALL 9 Z S1111 F111 42 STOP 43 M8 44 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 45 CALL LBL 1 46 CALL LBL 3 47 M5 M9 48 ; 49 * - W4.2 50 TOOL CALL 22 Z S1900 F100 51 STOP 52 TOOL DEF 23 53 M8 54 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-30 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 55 CALL LBL 3 56 M5 M9 57 ; 58 * - W2.5 59 TOOL CALL 18 Z S2800 F80 60 STOP 61 TOOL DEF 23 62 M8 63 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-23 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 64 CALL LBL 1 65 M5 M9 66 ; 67 * - M3 68 TOOL CALL 15 Z S60 69 STOP 70 TOOL DEF 23 71 M8 72 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC GWINTU ~ Q239=+0.5 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 73 CALL LBL 1 74 M5 M9 75 ; 76 * - FP-12 -WYSPY 77 TOOL CALL 17 Z S9987 F1200 DL+0.2 78 STOP 79 M8 80 CYCL DEF 257 CZOP OKRAGLY ~ Q223=+6 ;SRED.WYBR.OBR.NA GOT ~ Q222=+20 ;SREDNICA WST.OBR.WYB ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-3.5 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206=+500 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q376=-1 ;KAT POCZATKOWY 81 CALL LBL 1 82 M5 M9 83 ; 84 * - FP-12 -WYBRANIE 85 TOOL CALL 17 Z S9987 F1200 DL+0.2 86 STOP 87 M8 88 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;<NAME> ~ Q218=+100 ;DLUG. 1-SZEJ STRONY ~ Q219=+40 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-3.5 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+500 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 89 CALL LBL 2 90 M5 M9 91 ; 92 CYCL DEF 7.0 PUNKT BAZOWY 93 CYCL DEF 7.1 X-10 94 ; 95 * - FP-12 -WYBRANIE 96 TOOL CALL 17 Z S9987 F1200 DL+0.2 97 STOP 98 M8 99 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+50 ;DLUG. 1-SZEJ STRONY ~ Q219=+100 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-3.5 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+500 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 100 CALL LBL 2 101 M5 M9 102 ; 103 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 104 ; 105 ; 106 CYCL DEF 7.0 PUNKT BAZOWY 107 CYCL DEF 7.1 X+35 108 ; 109 * - FP-12 -WYBRANIE 110 TOOL CALL 17 Z S9987 F1200 DL+0.2 111 STOP 112 M8 113 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;<NAME> ~ Q218=+20 ;DLUG. 1-SZEJ STRONY ~ Q219=+120 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-3.5 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+500 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 114 CALL LBL 2 115 M5 M9 116 ; 117 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 118 ; 119 * - FP-12 -WYSPY 120 TOOL CALL 17 Z S9987 F1200 DL-0.05 121 STOP 122 M8 123 CYCL DEF 257 CZOP OKRAGLY ~ Q223=+6 ;SRED.WYBR.OBR.NA GOT ~ Q222=+20 ;SREDNICA WST.OBR.WYB ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-3.5 ;GLEBOKOSC ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q206=+500 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q376=-1 ;KAT POCZATKOWY 124 CALL LBL 1 125 M5 M9 126 ; 127 * - FP-12 -WYBRANIE 128 TOOL CALL 17 Z S9987 F1200 DL-0.05 129 STOP 130 M8 131 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+100 ;DLUG. 1-SZEJ STRONY ~ Q219=+40 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-3.5 ;GLEBOKOSC ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+500 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 132 CALL LBL 2 133 M5 M9 134 ; 135 CYCL DEF 7.0 PUNKT BAZOWY 136 CYCL DEF 7.1 X-10 137 ; 138 * - FP-12 -WYBRANIE 139 TOOL CALL 17 Z S9987 F1200 DL-0.05 140 STOP 141 M8 142 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;<NAME> ~ Q218=+50 ;DLUG. 1-SZEJ STRONY ~ Q219=+100 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-3.5 ;GLEBOKOSC ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+500 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 143 CALL LBL 2 144 M5 M9 145 ; 146 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 147 ; 148 ; 149 CYCL DEF 7.0 PUNKT BAZOWY 150 CYCL DEF 7.1 X+35 151 ; 152 * - FP-12 -WYBRANIE 153 TOOL CALL 17 Z S9987 F1200 DL-0.05 154 STOP 155 M8 156 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;<NAME> ~ Q218=+20 ;DLUG. 1-SZEJ STRONY ~ Q219=+120 ;DLUG. 2-GIEJ STRONY ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-3.5 ;GLEBOKOSC ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+500 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 157 CALL LBL 2 158 M5 M9 159 ; 160 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 161 ; 162 * - FAZY 163 TOOL CALL 9 Z S5000 F400 DL-0.5 DR-3 164 STOP 165 M8 M3 166 L X-39 Y+24.5 R0 FMAX 167 CYCL DEF 257 CZOP OKRAGLY ~ Q223=+6 ;SRED.WYBR.OBR.NA GOT ~ Q222=+6.1 ;SREDNICA WST.OBR.WYB ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-0.4 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q376=-1 ;KAT POCZATKOWY 168 CYCL CALL 169 L X-39 Y-24.5 R0 FMAX 170 CYCL CALL 171 L X+19 Y+24.5 R0 FMAX 172 CYCL CALL 173 L X+19 Y-24.5 R0 FMAX 174 CYCL CALL 175 M5 M9 176 ; 177 * - FAZA-GAB 178 TOOL CALL 9 Z S5000 F400 DL-2.5 DR-0.5 179 STOP 180 M8 M3 181 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+85 ;DLUG. 1-SZEJ STRONY ~ Q424=+85.1 ;WYMIAR POLWYROBU 1 ~ Q219=+85 ;DLUG. 2-GIEJ STRONY ~ Q425=+85.1 ;WYMIAR POLWYROBU 2 ~ Q220=+3 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-0.1 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q206= MAX ;WARTOSC POSUWU WGL. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 182 CALL LBL 2 183 M5 M9 184 ; 185 * - KULA 1 DLA WIERZCHOLKA 186 TOOL CALL 2 Z S9987 F70 DL-0.05 187 STOP 188 M3 M8 189 L X-22 Y-1 R0 FMAX 190 CYCL DEF 225 GRAWEROWANIE ~ QS500="Raspberry Pi 4B" ;TEKST GRAWER. ~ Q513=+4.3 ;WYSOK.ZNAKU ~ Q514=+0.75 ;WSPOL.ODSTEPU ~ Q515=+0 ;FONT ~ Q516=+0 ;UKLAD TEKSTU ~ Q374=+0 ;KAT OBROTU ~ Q517=+50 ;PROMIEN OKREGU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q201=-0.07 ;GLEBOKOSC ~ Q206=+20 ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=-3.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 191 CYCL CALL 192 M5 M9 193 ; 194 ;--------------------------------------------- 195 L Z-5 R0 FMAX M91 196 L X+260 Y+535 R0 FMAX M91 197 L M30 198 * - ----------------------------------------- 199 * - LBL1 GW/OTW 200 LBL 1 201 M3 202 L X-39 Y+24.5 R0 FMAX M99 203 L X-39 Y-24.5 R0 FMAX M99 204 L X+19 Y+24.5 R0 FMAX M99 205 L X+19 Y-24.5 R0 FMAX M99 206 LBL 0 207 * - LBL2 SRODEK 208 LBL 2 209 M3 210 L X+0 Y+0 R0 FMAX M99 211 LBL 0 212 * - LBL3 OTW 213 LBL 3 214 M3 215 L X-37.5 Y+37.5 R0 FMAX M99 216 L X+37.5 Y+37.5 R0 FMAX M99 217 L X-37.5 Y-37.5 R0 FMAX M99 218 L X+37.5 Y-37.5 R0 FMAX M99 219 LBL 0 220 END PGM RPI-BASE MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/TLOCZYSKO/TLOCZYSKO.H 0 BEGIN PGM TLOCZYSKO MM 1 BLK FORM 0.1 Z X-26 Y-26 Z-23 2 BLK FORM 0.2 X+26 Y+26 Z+0 3 ; 4 ;--------------------------------------------- 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 ;--------------------------------------------- 7 ; 8 * - FP 8 ZGR 9 STOP 10 TOOL CALL 12 Z S3000 F500 DR+0.2 11 TOOL DEF 11 12 M7 M3 13 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+49.98 ;DLUG. 1-SZEJ STRONY ~ Q424=+54 ;WYMIAR POLWYROBU 1 ~ Q219=+13.6 ;DLUG. 2-GIEJ STRONY ~ Q425=+24 ;WYMIAR POLWYROBU 2 ~ Q220=+0.2 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-22 ;GLEBOKOSC ~ Q202=+0.5 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.99 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 14 CALL LBL 1 15 M5 M9 16 ; 17 * - FP 8 WYK 18 STOP 19 TOOL CALL 11 Z S3000 F200 DR+0.1 20 TOOL DEF 11 21 M7 M3 22 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+49.98 ;DLUG. 1-SZEJ STRONY ~ Q424=+52 ;WYMIAR POLWYROBU 1 ~ Q219=+13.6 ;DLUG. 2-GIEJ STRONY ~ Q425=+16 ;WYMIAR POLWYROBU 2 ~ Q220=+0.2 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-22 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.99 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 23 CALL LBL 1 24 M5 M9 25 ; 26 * - FP 8 WYK / 27 STOP 28 TOOL CALL 11 Z S3000 F200 DR-0.02 29 TOOL DEF 30 30 M7 M3 31 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+49.98 ;DLUG. 1-SZEJ STRONY ~ Q424=+52 ;WYMIAR POLWYROBU 1 ~ Q219=+13.6 ;DLUG. 2-GIEJ STRONY ~ Q425=+16 ;WYMIAR POLWYROBU 2 ~ Q220=+0.2 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-22 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1.99 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 32 CALL LBL 1 33 M5 M9 34 ; 35 ;--------------------------------------------- 36 L Z-5 R0 FMAX M91 37 L X+260 Y+535 R0 FMAX M91 38 L M30 39 * - ----------------------------------------- 40 * - LBL1 41 LBL 1 42 M3 43 L X+0 Y+0 R0 FMAX M99 44 LBL 0 45 END PGM TLOCZYSKO MM <file_sep>/cnc programming/Heidenhain/JF/AD/N030.02/90H7-WYK60mm.H 0 BEGIN PGM 90H7-WYK60mm MM 1 ;MASTERCAM - X9 2 ;MCX FILE - \\NCNCSERV\NCNC\00NZL\AD\ADN03001\MCX\ZAMEK_AD_N030_01.MCX-9 3 ;POST - MPPOSTABILITY_AVIA_VMC_800_4X.PST 4 ;PROGRAM - PZ2.h 5 ;DATE - 2018.07.11 6 ;TIME - 2:54 PM 7 ;2 - FP14 - D16.000mm 8 BLK FORM 0.1 Z X-140 Y-100 Z-18 9 BLK FORM 0.2 X+140 Y+100 Z+0.1 10 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 11 CYCL DEF 7.0 PUNKT BAZOWY 12 CYCL DEF 7.1 IX+60 13 M126 14 M129 15 PLANE RESET TURN FMAX 16 ; 17 * - FP14 18 TOOL CALL 24 Z S1000 DL-1 DR-0.05 19 TOOL DEF 0 20 * - KOMPENSACJA 21 ;FP14 TOOL - 2 DIA. OFF. - 2 LEN. - 2 DIA. - 16. 22 ;HOLDER - DEFAULT HOLDER 23 CYCL DEF 32.0 TOLERANCJA 24 CYCL DEF 32.1 T0.003 25 CYCL DEF 32.2 HSC-MODE:0 / 26 L A+0 FMAX 27 M3 28 L X-22.6 Y+11.2 FMAX M8 29 L Z+15 FMAX 30 L Z+2 FMAX 31 L Z-8.3 F160 32 L X-33.8 RL 33 CC X-33.8 Y+0 34 C X-45 Y+0 DR+ 35 CC X+0 Y+0 36 C X-45 Y+0 DR+ 37 CC X-33.8 Y+0 38 C X-33.8 Y-11.2 DR+ 39 L X-22.6 R0 40 L Z+15 FMAX 41 L Y+11.2 FMAX 42 L Z+2 FMAX 43 L Z-11.6 F160 44 L X-33.8 RL 45 CC X-33.8 Y+0 46 C X-45 Y+0 DR+ 47 CC X+0 Y+0 48 C X-45 Y+0 DR+ 49 CC X-33.8 Y+0 50 C X-33.8 Y-11.2 DR+ 51 L X-22.6 R0 52 L Z+15 FMAX 53 L Y+11.2 FMAX 54 L Z+2 FMAX 55 L Z-14.9 F160 56 L X-33.8 RL 57 CC X-33.8 Y+0 58 C X-45 Y+0 DR+ 59 CC X+0 Y+0 60 C X-45 Y+0 DR+ 61 CC X-33.8 Y+0 62 C X-33.8 Y-11.2 DR+ 63 L X-22.6 R0 64 L Z+15 FMAX 65 L Y+11.2 FMAX 66 L Z+2 FMAX 67 L Z-18.2 F160 68 L X-33.8 RL 69 CC X-33.8 Y+0 70 C X-45 Y+0 DR+ 71 CC X+0 Y+0 72 C X-45 Y+0 DR+ 73 CC X-33.8 Y+0 74 C X-33.8 Y-11.2 DR+ 75 L X-22.6 R0 76 L Z+15 FMAX 77 CYCL DEF 32.0 TOLERANCJA 78 CYCL DEF 32.1 79 M5 80 L Z-15 R0 FMAX M91 M9 81 L X+273 Y+529 R0 FMAX M91 / 82 L A+0 FMAX M91 / 83 M2 84 END PGM 90H7-WYK60mm MM <file_sep>/cnc programming/Heidenhain/JF/PLYTA-SP-n160/plan-os-y-rot-2.h 0 BEGIN PGM plan-os-y-rot-2 MM 1 BLK FORM 0.1 Z X+0 Y-380 Z+0 2 BLK FORM 0.2 X+812 Y+0 Z+10 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IX+20 7 ;--------------------------------------------- 8 ; 9 * - GLOW 80 NM 10 STOP 11 TOOL CALL 44 Z S5000 F1500 DL+0.17 12 M8 13 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=+0 ;PKT.STARTU 1SZEJ OSI ~ Q226=+20 ;PKT.STARTU 2GIEJ OSI ~ Q227=+3 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=-375 ;DLUG. 1-SZEJ STRONY ~ Q219=-40 ;DLUG. 2-GIEJ STRONY ~ Q202=+1.5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1.85 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253=+3000 ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 14 ; 15 CYCL DEF 10.0 OBROT 16 CYCL DEF 10.1 ROT+90 17 ; 18 CALL LBL 1 19 ; 20 M5 M9 21 ; 22 CYCL DEF 10.0 OBROT 23 CYCL DEF 10.1 ROT+0 24 ; 25 ; 26 ;--------------------------------------------- 27 L Z-5 R0 FMAX M91 28 L X+260 Y+535 R0 FMAX M91 29 L M30 30 * - ----------------------------------------- 31 * - LBL1 32 LBL 1 33 M3 34 L X+0 Y+0 R0 FMAX M99 35 LBL 0 36 END PGM plan-os-y-rot-2 MM <file_sep>/cnc programming/Heidenhain/JF/WKLADKA-WYMIENNA/OP2.H 0 BEGIN PGM OP2 MM 1 BLK FORM 0.1 Z X-5 Y-10 Z-16 2 BLK FORM 0.2 X+30 Y+10 Z+1 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 TOOL CALL 29 Z S9999 F2000 5 L Z+300 R0 FMAX M3 M8 6 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-5 ;PKT.STARTU 1SZEJ OSI ~ Q226=+8 ;PKT.STARTU 2GIEJ OSI ~ Q227=+13.2 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.2 ;PUNKT KONCOWY 3. OSI ~ Q218=+35 ;DLUG. 1-SZEJ STRONY ~ Q219=-16 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 7 CYCL CALL 8 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-5 ;PKT.STARTU 1SZEJ OSI ~ Q226=+10 ;PKT.STARTU 2GIEJ OSI ~ Q227=+1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+35 ;DLUG. 1-SZEJ STRONY ~ Q219=-20 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 9 CYCL CALL 10 L Z+300 R0 FMAX 11 ; UWAGA 12 STOP M0 13 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 14 ; 15 L Z+300 R0 FMAX 16 L X+0 Y+0 R0 FMAX 17 TOOL CALL 30 Z 18 ; 19 ; 20 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+0 ;1.PKT POMIAROW 1.OSI ~ Q264=+0 ;1.PKT 2.OSI ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+20 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q272=+1 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 21 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 22 ;--------------------------------------------- 23 * - NAW-16 24 TOOL CALL 26 Z S500 F50 25 TOOL DEF 4 26 M8 M3 27 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 28 L X+15 Y+0 R0 FMAX M99 29 M5 M9 30 ; 31 L Z+0 R0 FMAX M91 32 L X+260 Y+535 R0 FMAX M91 33 L M30 34 END PGM OP2 MM <file_sep>/cnc programming/Heidenhain/JF/SD/POLPIERSCIEN-ZAMKA-Z-POGL.H 0 BEGIN PGM POLPIERSCIEN-ZAMKA-Z-POGL MM 1 BLK FORM 0.1 Z X-75 Y-75 Z-25 2 BLK FORM 0.2 X+75 Y+75 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 STOP 7 L X+0 Y+0 R0 FMAX 8 * - SONDA 9 TOOL CALL 30 Z 10 TOOL DEF 1 11 ; 12 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+150 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 13 ; 14 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 15 ;--------------------------------------------- 16 ; 17 ; 18 STOP 19 CALL LBL 3 20 ; 21 STOP 22 CYCL DEF 10.0 OBROT 23 CYCL DEF 10.1 ROT+120 24 CALL LBL 3 25 ; 26 STOP 27 CYCL DEF 10.0 OBROT 28 CYCL DEF 10.1 ROT-120 29 CALL LBL 3 30 ; 31 CYCL DEF 10.0 OBROT 32 CYCL DEF 10.1 ROT+0 33 ; 34 L Z+0 R0 FMAX M91 35 L X+260 Y+535 R0 FMAX M91 36 L M30 37 ; 38 ; 39 * - LBL 3 40 LBL 3 41 ; 42 * - W 6.6 VHM 43 TOOL CALL 1 Z S1205 F92 / 44 STOP 45 TOOL DEF 3 46 M7 47 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-28 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+15 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 48 CALL LBL 1 49 ; 50 * - NAW-STAL -TRASA 51 TOOL CALL 3 Z S700 F30 / 52 STOP 53 TOOL DEF 24 54 M8 55 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.08 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+0.1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 56 CALL LBL 2 57 ; 58 * - FP-8 -FASOLKI 59 TOOL CALL 24 Z S2600 F300 / 60 STOP 61 TOOL DEF 9 62 M8 M3 63 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+25 ;DLUGOSC ROWKA ~ Q219=+11 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=-60 ;KAT OBROTU ~ Q367=+2 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-8 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+2 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q439=+3 ;BAZA POSUWU 64 L X+34.8 Y-60.2 R0 FMAX M99 65 Q367 = 3 66 Q374 = 60 67 L X-34.8 Y-60.2 R0 FMAX M99 68 ; 69 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+25 ;DLUGOSC ROWKA ~ Q219=+11 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=-40 ;KAT OBROTU ~ Q367=+2 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-8 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+2 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q439=+3 ;BAZA POSUWU 70 L X+53.2 Y-44.7 R0 FMAX M99 71 Q367 = 3 72 Q374 = 40 73 L X-53.2 Y-44.7 R0 FMAX M99 74 ; 75 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+25 ;DLUGOSC ROWKA ~ Q219=+11 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=-90 ;KAT OBROTU ~ Q367=+2 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-8 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+2 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q439=+3 ;BAZA POSUWU 76 L X+12.1 Y-68.4 R0 FMAX M99 77 Q367 = 3 78 Q374 = 90 79 L X-12.1 Y-68.4 R0 FMAX M99 80 ; 81 * - NAW-8 -FAZY 82 TOOL CALL 9 Z S4000 F300 DL-0.6 DR-3 / 83 STOP 84 TOOL DEF 22 85 M8 M3 86 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+25 ;DLUGOSC ROWKA ~ Q219=+11 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=-60 ;KAT OBROTU ~ Q367=+2 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-0.5 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+500 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+2 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q439=+3 ;BAZA POSUWU 87 L X+34.8 Y-60.2 R0 FMAX M99 88 Q367 = 3 89 Q374 = 60 90 L X-34.8 Y-60.2 R0 FMAX M99 91 ; 92 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;<NAME> ~ Q218=+25 ;DLUGOSC ROWKA ~ Q219=+11 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=-40 ;KAT OBROTU ~ Q367=+2 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-0.5 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+500 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+2 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q439=+3 ;BAZA POSUWU 93 L X+53.2 Y-44.7 R0 FMAX M99 94 Q367 = 3 95 Q374 = 40 96 L X-53.2 Y-44.7 R0 FMAX M99 97 ; 98 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+25 ;DLUGOSC ROWKA ~ Q219=+11 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=-90 ;KAT OBROTU ~ Q367=+2 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-0.5 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+500 ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+2 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q439=+3 ;BAZA POSUWU 99 L X+12.1 Y-68.4 R0 FMAX M99 100 Q367 = 3 101 Q374 = 90 102 L X-12.1 Y-68.4 R0 FMAX M99 103 ; 104 LBL 0 105 ; 106 ; 107 ;--------------------------------------------- 108 L Z+0 R0 FMAX M91 109 L X+260 Y+535 R0 FMAX M91 110 L M30 111 * - ----------------------------------------- 112 * - LBL1 6.6/11 113 LBL 1 114 M3 115 L X-12.1 Y-68.4 R0 FMAX M99 116 L X-34.8 Y-60.2 R0 FMAX M99 117 L X-53.2 Y-44.7 R0 FMAX M99 118 ; 119 L X+12.1 Y-68.4 R0 FMAX M99 120 L X+34.8 Y-60.2 R0 FMAX M99 121 L X+53.2 Y-44.7 R0 FMAX M99 122 LBL 0 123 ; 124 * - LBL 2 TRAS 125 LBL 2 126 M3 127 L X+0 Y+72 R0 FMAX M99 128 L X+0 Y+69 R0 FMAX M99 129 L X+0 Y+66 R0 FMAX M99 130 LBL 0 131 END PGM POLPIERSCIEN-ZAMKA-Z-POGL MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/OTW-PLYTA-2.H 0 BEGIN PGM OTW-PLYTA-2 MM 1 BLK FORM 0.1 Z X-90 Y-50 Z-24 2 BLK FORM 0.2 X+90 Y+50 Z+2 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 ; 5 * - -------------------- 6 * - NAW 7 TOOL CALL 9 Z S1500 F100 8 TOOL DEF 25 9 M8 10 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.25 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3.25 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 11 CALL LBL 1 12 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 13 CALL LBL 2 14 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.9 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 15 CALL LBL 3 16 M5 M9 17 ; / 18 STOP 19 ; 20 * - w-6.6 21 TOOL CALL 25 Z S1000 F100 22 TOOL DEF 17 23 M8 24 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-27 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+25 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 25 CALL LBL 1 26 M5 M9 27 ; 28 * - w-4.8 29 TOOL CALL 17 Z S1500 F100 30 TOOL DEF 21 31 M8 32 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-11.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 33 CALL LBL 2 34 M5 M9 35 ; 36 ; 37 * - w-6 38 TOOL CALL 0 Z S1000 F100 39 TOOL DEF 29 40 M8 41 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 42 CALL LBL 3 43 M5 M9 44 ; 45 ; 46 * - fp-8 47 TOOL CALL 29 Z S8000 F200 48 TOOL DEF 10 49 M8 50 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.35 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+9.65 ;SREDNICA NOMINALNA ~ Q342=+6 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 51 CALL LBL 3 52 M5 M9 53 ; / 54 STOP 55 * - r-5 56 TOOL CALL 10 Z S200 F30 57 TOOL DEF 8 58 M8 59 CYCL DEF 201 ROZWIERCANIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-9.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+70 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 60 CALL LBL 2 61 M5 M9 62 ; 63 ; 64 * - -------------------- 65 L Z+0 R0 FMAX M91 66 L X+560 Y+535 R0 FMAX M91 67 L M30 68 * - -------------------- 69 LBL 1 70 M13 71 L X-35 Y+28 R0 FMAX M99 72 L X+35 Y+28 R0 FMAX M99 73 L X+35 Y-28 R0 FMAX M99 74 L X-35 Y-28 R0 FMAX M99 75 LBL 0 76 LBL 2 77 M13 78 L X-44.5 Y+0 R0 FMAX M99 79 L X+44.5 Y+0 R0 FMAX M99 80 LBL 0 81 LBL 3 82 M13 83 L X-8 Y+13.3 R0 FMAX M99 84 L X+8 Y+13.3 R0 FMAX M99 85 LBL 0 86 END PGM OTW-PLYTA-2 MM <file_sep>/cnc programming/Heidenhain/JF/SD/DYSTANS/SD-N10203A-DYST-2.h 0 BEGIN PGM SD-N10203A-DYST-2 MM 1 BLK FORM 0.1 Z X-60 Y-60 Z-25 2 BLK FORM 0.2 X+60 Y+60 Z+1 3 ; 4 ;=================================== 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 ; / 7 STOP / 8 L X+0 Y+0 FMAX / 9 TOOL CALL 30 Z / 10 TOOL DEF 18 / 11 ; / 12 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+119 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-3 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. / 13 ; / 14 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 15 ;=================================== 16 ; 17 * - OTWORY WSTEPNE DUZYM WIERTLEM (8-9) / 18 STOP 19 TOOL CALL 28 Z S3180 F763 20 TOOL DEF 27 21 M7 22 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-19 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+19 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 23 CALL LBL 2 24 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+18 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 25 CALL LBL 3 26 M5 M9 27 ; 28 TOOL CALL 27 Z S5987 F800 29 TOOL DEF 27 30 * - POGLEBIENIA FI 11 31 M8 32 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;RODZAJ FREZOWANIA 33 CALL LBL 1 34 * - FI 11.8 POD G1/4 35 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.8 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 36 CALL LBL 2 37 * - FI 12 38 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-16.05 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+12 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 39 CALL LBL 3 40 * - 15H7 ZGRUBNIE 41 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-12.55 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+14.9 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 42 CALL LBL 3 43 ; 44 * - 15H7 WYKONCZENIE (ZMIEN SREDNICE!) 45 TOOL CALL 27 Z S5987 F600 DR+0.017 / 46 STOP 47 TOOL DEF 26 48 M8 49 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-12.55 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+14.99 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 50 CALL LBL 3 51 M5 M9 52 ; 53 TOOL CALL 26 Z S1200 F120 / 54 STOP 55 TOOL DEF 20 56 * - FAZA FI11 57 M8 58 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.55 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.55 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-4 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0.5 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 59 CALL LBL 1 60 * - FAZA G1/4 61 M8 62 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.6 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-4 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0.5 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 63 CALL LBL 2 64 * - FAZA 15H7 65 M8 66 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.55 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.55 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0.5 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 67 CALL LBL 3 68 M5 M9 69 ; 70 * - GWINTOWANIE 1/4 71 TOOL CALL 4 Z S200 / 72 STOP 73 TOOL DEF 30 74 M8 75 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-17.5 ;GLEBOKOSC GWINTU ~ Q239=+1.337 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 76 CALL LBL 2 77 M5 M9 78 ; 79 ;--------------------------------------------- 80 L Z+0 R0 FMAX M91 81 L X+260 Y+535 R0 FMAX M91 / 82 L M30 83 * - ----------------------------------------- 84 ; 85 * - LBL1 POGL FI 11/6.6 86 LBL 1 87 M3 88 L X+0 Y+48.5 R0 FMAX M99 89 L X-46.1 Y+15 R0 FMAX M99 90 L X+46.1 Y+15 R0 FMAX M99 91 L X-28.5 Y-39.2 R0 FMAX M99 92 L X+28.5 Y-39.2 R0 FMAX M99 93 LBL 0 94 ; 95 * - LBL2 G1/4 96 LBL 2 97 M3 98 L X-32 Y+32 R0 FMAX M99 99 L X+32 Y+32 R0 FMAX M99 100 LBL 0 101 ; 102 * - LBL3 15H7 103 LBL 3 104 M3 105 L X+0 Y-48 R0 FMAX M99 106 LBL 0 107 END PGM SD-N10203A-DYST-2 MM <file_sep>/cnc programming/Heidenhain/JF/ALS/N030.05/FAZA.H 0 BEGIN PGM FAZA MM 1 BLK FORM 0.1 Z X-61 Y-18 Z-20 2 BLK FORM 0.2 X+61 Y+18 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 R0 FMAX 7 ; 8 TOOL CALL 30 Z 9 TOOL DEF 7 10 ; 11 TCH PROBE 411 PKT.BAZ.PROST.ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q323=+126 ;DLUG. 1-SZEJ STRONY ~ Q324=+41 ;DLUG. 2-GIEJ STRONY ~ Q261=-4.6 ;WYSOKOSC POMIARU ~ Q320=+20 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+1 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 12 ; 13 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 14 ; 15 ;--------------------------------------------- 16 ; 17 ; 18 * - FAZA CZOP 19 TOOL CALL 9 Z S4000 F200 DL+0.3 DR-3 20 TOOL DEF 24 21 M7 M3 22 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+120 ;DLUG. 1-SZEJ STRONY ~ Q424=+120.1 ;WYMIAR POLWYROBU 1 ~ Q219=+33 ;DLUG. 2-GIEJ STRONY ~ Q425=+33.1 ;WYMIAR POLWYROBU 2 ~ Q220=+0 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1.5 ;GLEBOKOSC ~ Q202=+2.5 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+1 ;POZYCJA NAJAZDU 23 CALL LBL 1 24 M5 M9 25 ; 26 ;--------------------------------------------- 27 L Z-5 R0 FMAX M91 28 L X+260 Y+535 R0 FMAX M91 29 L M30 30 * - ----------------------------------------- 31 * - LBL1 32 LBL 1 33 M3 34 L X+0 Y+0 R0 FMAX M99 35 LBL 0 36 ; 37 END PGM FAZA MM <file_sep>/cnc programming/Heidenhain/JF/PLYTA-SP-n160/GAB.h 0 BEGIN PGM GAB MM 1 BLK FORM 0.1 Z X+0 Y-15 Z-5 2 BLK FORM 0.2 X+208.9 Y+15 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 R0 FMAX 7 ; 8 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 9 CYCL DEF 7.0 PUNKT BAZOWY 10 CYCL DEF 7.1 IZ+0 11 ;--------------------------------------------- 12 ; / 13 STOP 14 * - GLOW-20 15 TOOL CALL 22 Z S6000 F2000 16 TOOL DEF 30 17 M8 M3 18 ; 19 ; 20 L X-210 Y-15 FMAX 21 L Z+0 FMAX 22 ; 23 Q22 = - 3 24 LBL 2 25 L Z+Q22 26 L Y-8 27 L X+8 28 L Y+391.8 29 L X-210 30 L Z+5 FMAX 31 L X-210 Y-15 FMAX 32 Q22 = Q22 - 3 33 LBL 0 34 CALL LBL 2 REP14 35 ; 36 M5 M9 37 ; 38 ;--------------------------------------------- 39 L Z-5 R0 FMAX M91 40 L X+260 Y+535 R0 FMAX M91 41 L M30 42 * - ----------------------------------------- 43 * - LBL1 / 44 LBL 1 / 45 M3 / 46 L X+0 Y+0 R0 FMAX M99 / 47 LBL 0 48 END PGM GAB MM <file_sep>/cnc programming/Heidenhain/JF/ZAMEK/ZAMEK-n020-GAB.H 0 BEGIN PGM ZAMEK-n020-GAB MM 1 BLK FORM 0.1 Z X-30.1 Y-0.2 Z-13.8 2 BLK FORM 0.2 X+30.1 Y+26.2 Z+0.2 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 ;--------------------------------------------- 5 TOOL CALL 14 Z S1500 F300 6 TOOL DEF 20 7 L Z+300 R0 FMAX M3 M8 8 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-40 ;PKT.STARTU 1SZEJ OSI ~ Q226=+35 ;PKT.STARTU 2GIEJ OSI ~ Q227=+3.1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+80 ;DLUG. 1-SZEJ STRONY ~ Q219=-40 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 9 CYCL CALL 10 L Z+300 R0 FMAX 11 ; 12 TOOL CALL 11 Z S2000 F300 13 L Z+300 R0 FMAX M3 14 L X+0 Y-12 R0 FMAX 15 L Z+5 R0 FMAX M8 16 L Z+0 R0 F AUTO 17 LBL 1 18 L IZ-1 19 L X+12 RL 20 CC X+0 Y-12 21 C X+0 Y+0 DR+ 22 L X-29.75 23 CC X-29.75 Y+0.1 24 C X-29.85 Y+0.1 DR- 25 L Y+19.759 26 CC X-19.85 Y+19.759 27 C X-26.85 Y+26.9 DR- 28 L X+26.85 29 CC X+19.85 Y+19.759 30 C X+29.85 Y+19.759 DR- 31 L Y+0.1 32 CC X+29.75 Y+0.1 33 C X+29.75 Y+0 DR- 34 L X+0 35 CC X+0 Y-12 36 C X-12 Y-12 DR+ 37 L X+0 R0 38 LBL 0 39 CALL LBL 1 REP14 40 L Z+300 R0 FMAX 41 M9 M5 42 M5 43 ; 44 TOOL CALL 26 Z S500 F50 45 L Z+300 R0 FMAX M3 46 L X+31 Y-8 R0 FMAX 47 L Z+5 R0 FMAX M8 48 L Z-1 R0 F AUTO 49 LBL 2 50 L IZ-1 51 L Y+35 52 L IZ-1 53 L Y-8 54 LBL 0 55 CALL LBL 2 REP2 56 L Z+300 R0 FMAX 57 ; 58 TOOL CALL 26 Z S500 F50 59 L Z+300 R0 FMAX M3 60 L X-31 Y+35 R0 FMAX 61 L Z+5 R0 FMAX M8 62 L Z-1 R0 F AUTO 63 LBL 3 64 L IZ-1 65 L Y-8 66 L IZ-1 67 L Y+35 68 LBL 0 69 CALL LBL 3 REP2 70 L Z+300 R0 FMAX 71 ; 72 TOOL CALL 26 Z S500 F50 73 L Z+300 R0 FMAX M3 74 L X-30 Y+28 R0 FMAX 75 L Z+5 R0 FMAX M8 76 L Z-1.8 R0 F AUTO 77 L X+30 78 L Z+300 R0 FMAX 79 ; 80 TOOL CALL 29 Z S3000 F500 DL-0.015 81 TOOL DEF 20 82 L Z+300 R0 FMAX M3 M8 83 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-35 ;PKT.STARTU 1SZEJ OSI ~ Q226=+32.5 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.5 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+70 ;DLUG. 1-SZEJ STRONY ~ Q219=-40 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.5 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q357=+2 ;ODST. BEZP. Z BOKU ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 84 CYCL CALL 85 L Z+300 R0 FMAX 86 ; 87 TOOL CALL 29 Z S3000 F300 DR-0.035 88 L Z+300 R0 FMAX M3 89 L X+0 Y-12 R0 FMAX 90 L Z+5 R0 FMAX M8 91 L Z-15 R0 F AUTO 92 L X+12 RL 93 CC X+0 Y-12 94 C X+0 Y+0 DR+ 95 L X-29.75 96 CC X-29.75 Y+0.1 97 C X-29.85 Y+0.1 DR- 98 L Y+19.759 99 CC X-19.85 Y+19.759 100 C X-26.85 Y+26.9 DR- 101 L X+26.85 102 CC X+19.85 Y+19.759 103 C X+29.85 Y+19.759 DR- 104 L Y+0.1 105 CC X+29.75 Y+0.1 106 C X+29.75 Y+0 DR- 107 L X+0 108 CC X+0 Y-12 109 C X-12 Y-12 DR+ 110 L X+0 R0 111 L Z+300 R0 FMAX 112 L Z-15 R0 FMAX M91 M9 113 L X+600 Y+529 R0 FMAX M91 114 STOP M30 115 END PGM ZAMEK-n020-GAB MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/POMIAR.H 0 BEGIN PGM POMIAR MM 1 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 2 ; 3 L X+0 Y+0 R0 FMAX 4 TOOL CALL 30 Z S50 5 ; / 6 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+15 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q311=+27 ;SZEROKOSC MOSTKA ~ Q272=+2 ;OS POMIAROWA ~ Q261=-2.5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 7 ; / 8 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 9 ; 10 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+0 ;1.PKT POMIAROW 1.OSI ~ Q264=+0 ;1.PKT 2.OSI ~ Q261=-2.5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q272=+1 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 11 ; 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 ;--------------------------------------------- 14 ; 15 STOP 16 CALL PGM TNC:\5437-SD\sd5437_01_01B.H 17 ; 18 ;--------------------------------------------- 19 L Z+0 R0 FMAX M91 20 L X+260 Y+535 R0 FMAX M91 21 L M30 22 END PGM POMIAR MM <file_sep>/cnc programming/Heidenhain/JF/ALS/N020.04/ZAMEK-POGL-ALS_N020_02.h 0 BEGIN PGM ZAMEK-POGL-ALS_N020_02 MM 1 BLK FORM 0.1 Z X-30.1 Y-0.2 Z-13.8 2 BLK FORM 0.2 X+30.1 Y+26.2 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 R0 FMAX 7 TOOL CALL 30 Z 8 TOOL DEF 11 9 ; 10 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+14 ;SRODEK W 2-SZEJ OSI ~ Q311=+60.6 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-3 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q305=+1 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 11 ; 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 ;--------------------------------------------- 14 ; 15 * - POGL 17 FP-8 16 TOOL CALL 11 Z S1400 F200 17 TOOL DEF 9 18 M8 19 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+17 ;SREDNICA NOMINALNA ~ Q342=+11 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 20 CALL LBL 1 21 M5 M9 22 ; 23 * - FAZY INTERPOLACJA 24 * - UWAGA! FAZOWNIK MUSI MIEC R=2 W TABELI NARZEDZI! 25 TOOL CALL 9 Z S1600 F150 26 TOOL DEF 30 27 M8 28 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+3.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+17 ;SREDNICA NOMINALNA ~ Q342=+15 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 29 CALL LBL 1 30 M5 M9 31 ; 32 ;--------------------------------------------- 33 L Z+0 R0 FMAX M91 34 L X+700 Y+535 R0 FMAX M91 35 L M30 36 * - ----------------------------------------- 37 * - LBL1 POGLEBIENIA 17X7 38 LBL 1 39 M3 40 L X-12.5 Y+11 R0 FMAX M99 41 L X+12.5 Y+11 R0 FMAX M99 42 LBL 0 43 END PGM ZAMEK-POGL-ALS_N020_02 MM <file_sep>/cnc programming/Heidenhain/fasolka.h 0 BEGIN PGM FASOLKI MM 1 BLK FORM 0.1 Z X-170 Y+0 Z-25 2 BLK FORM 0.2 X+170 Y+80 Z+2 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 ;--------------------------------------------- 7 ; 8 CYCL DEF 7.0 PUNKT BAZOWY 9 CYCL DEF 7.1 IZ+0 10 * - FASOLKI 11 TOOL CALL 29 Z S10000 F1000 / 12 STOP 13 TOOL DEF 30 14 M8 15 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+34 ;DLUGOSC ROWKA ~ Q219=+11.6 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-12 ;GLEBOKOSC ~ Q202=+0.5 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+2 ;DOSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=-3.7 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+0 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q439=+3 ;BAZA POSUWU 16 CALL LBL 2 / 17 STOP 18 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+34.4 ;DLUGOSC ROWKA ~ Q219=+12 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-12 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+2 ;DOSUW - OBR.WYKONCZ. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=-3.7 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+0 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q439=+3 ;BAZA POSUWU 19 CALL LBL 2 20 M5 M9 21 ; 22 ;--------------------------------------------- 23 L Z+0 R0 FMAX M91 24 L X+260 Y+535 R0 FMAX M91 25 L M30 26 * - ----------------------------------------- 27 * - LBL2 KANALKI 28 LBL 2 29 M3 30 L X+0 Y+65 R0 FMAX M99 31 LBL 0 32 END PGM FASOLKI MM <file_sep>/cnc programming/Heidenhain/JF/WKLADKA-WYMIENNA/OP1.H 0 BEGIN PGM OP1 MM 1 BLK FORM 0.1 Z X-5 Y-10 Z-16 2 BLK FORM 0.2 X+30 Y+10 Z+1 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 ; 5 TOOL CALL 29 Z S9999 F2000 6 L Z+300 R0 FMAX M3 M8 7 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-5 ;PKT.STARTU 1SZEJ OSI ~ Q226=+10 ;PKT.STARTU 2GIEJ OSI ~ Q227=+3.1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+35 ;DLUG. 1-SZEJ STRONY ~ Q219=-20 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 8 CYCL CALL 9 L Z+300 R0 FMAX 10 ; 11 TOOL CALL 29 Z S9999 F999 12 M3 M8 13 L Z+300 R0 FMAX 14 L X+40 Y-15 R0 FMAX 15 L Z+5 R0 FMAX 16 L Z+0 R0 F AUTO 17 LBL 2 18 L IZ-1 R0 FMAX 19 L Y-6 RL 20 L X+0 21 RND R3.5 22 L Y+6 23 RND R3.5 24 L X+24 25 L Y-15 26 L X+40 R0 27 LBL 0 28 CALL LBL 2 REP11 29 L Z+300 FMAX 30 ; 31 TOOL CALL 29 Z S9999 F2000 32 L Z+300 R0 FMAX M3 M8 33 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-5 ;PKT.STARTU 1SZEJ OSI ~ Q226=+10 ;PKT.STARTU 2GIEJ OSI ~ Q227=+1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+35 ;DLUG. 1-SZEJ STRONY ~ Q219=-20 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+100 ;2-GA BEZPIECZNA WYS. 34 CYCL CALL 35 L Z+300 R0 FMAX 36 ; 37 TOOL CALL 29 Z S9999 F999 DR-0.02 38 M3 M8 39 L Z+300 R0 FMAX 40 L X+40 Y-15 R0 FMAX 41 L Z+5 R0 FMAX 42 L Z+0 R0 F AUTO 43 LBL 3 44 L IZ-2 R0 FMAX 45 L Y-6 RL 46 L X+0 47 RND R3.5 48 L Y+6 49 RND R3.5 50 L X+24 51 L Y-15 52 L X+40 R0 53 LBL 0 54 CALL LBL 3 REP5 55 L Z+300 FMAX 56 ; 57 * - W -5.5 58 TOOL CALL 19 Z S5782 F867 59 TOOL DEF 4 60 M8 M3 61 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+12 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 62 L X+15 Y+0 R0 FMAX M99 63 M5 M9 64 ; 65 * - NAW 66 TOOL CALL 9 Z S1000 F100 67 TOOL DEF 4 68 M8 69 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 70 CALL LBL 1 71 M5 M9 72 ; 73 * - W -4.25 74 TOOL CALL 24 Z S2000 F100 75 TOOL DEF 4 76 M8 77 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 78 CALL LBL 1 79 M5 M9 80 ; 81 * - FAZY 82 TOOL CALL 9 Z S1000 F100 83 TOOL DEF 10 84 M8 85 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 86 CALL LBL 1 87 M5 M9 88 ; 89 ; 90 * - GW M5 91 TOOL CALL 23 Z S100 92 STOP 93 TOOL DEF 0 94 M8 95 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC GWINTU ~ Q239=+0.8 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 96 CALL LBL 1 97 M5 M9 98 ; 99 * - F4-O5H7 100 TOOL CALL 21 Z S9999 F200 DR-0.015 101 TOOL DEF 4 102 M8 103 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-4 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.25 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+5 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 104 CALL LBL 1 105 M5 M9 106 ; 107 ;--------------------------------------------- 108 L Z+0 R0 FMAX M91 109 L X+260 Y+535 R0 FMAX M91 110 L M30 111 * - ----------------------------------------- 112 * - LBL1 113 LBL 1 114 M3 115 L X+5 Y+0 R0 FMAX M99 116 LBL 0 117 END PGM OP1 MM <file_sep>/cnc programming/Heidenhain/KS-N100-02-1.h 0 BEGIN PGM KS-N100-02-1 MM 1 BLK FORM 0.1 Z X-55 Y-55 Z-51.5 2 BLK FORM 0.2 X+55 Y+55 Z+1 3 ; 4 ;=================================== 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 ; 7 L X+0 Y+0 FMAX 8 ; / 9 STOP 10 TOOL CALL 30 Z S50 11 TOOL DEF 20 12 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+109 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-10 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 13 ; 14 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 15 ;=================================== 16 ; 17 * - NAW-8 18 TOOL CALL 9 Z S1200 F100 19 TOOL DEF 17 20 M8 21 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 22 CALL LBL 1 23 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.7 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 24 CALL LBL 2 25 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.55 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 26 CALL LBL 3 27 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 28 CALL LBL 4 29 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 30 CALL LBL 5 31 M5 M9 32 ; 33 * - W-4.8 34 TOOL CALL 17 Z S1666 F120 35 TOOL DEF 25 36 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-13 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 37 M8 38 CALL LBL 1 39 M5 M9 40 ; 41 * - W-6.6 42 TOOL CALL 25 Z S1212 F120 43 TOOL DEF 10 44 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-47 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 45 M8 46 CALL LBL 2 47 M5 M9 48 ; 49 * - 5H7 50 TOOL CALL 10 Z S120 F30 51 TOOL DEF 14 52 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-11 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+60 ;POSUW RUCHU POWROTN. ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 53 M8 54 CALL LBL 1 55 M5 M9 56 ; 57 * - W-3.2 58 TOOL CALL 14 Z S2500 F120 59 TOOL DEF 21 60 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-9.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 61 M8 62 CALL LBL 3 63 M5 M9 64 ; 65 * - W-6 66 TOOL CALL 1 Z S1340 F120 67 TOOL DEF 26 68 M8 69 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-34 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 70 CALL LBL 4 71 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-34 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 72 CALL LBL 5 73 M5 M9 74 ; 75 * - 7.2 pod M8x0.75 76 TOOL CALL 21 Z S1050 F100 77 TOOL DEF 1 78 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-14 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 79 M8 80 CALL LBL 5 81 M5 M9 82 ; 83 * - FAZ-16 84 TOOL CALL 26 Z S1200 F100 85 TOOL DEF 3 86 M8 87 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-4.2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 88 CALL LBL 5 89 M5 M9 90 ; 91 * - M8x0.75 92 TOOL CALL 3 Z S100 93 TOOL DEF 30 94 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC GWINTU ~ Q239=+0.75 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 95 M8 96 CALL LBL 5 97 M5 M9 98 ; 99 * - ------------------------- 100 ; 101 L Z+0 R0 FMAX M91 102 L X+430 Y+535 R0 FMAX M91 103 L M30 104 ; 105 * - ------------------------- 106 ; 107 * - LBL1 5H7 108 LBL 1 109 M3 110 L X-42.5 Y+0 R0 FMAX M99 111 LBL 0 112 ; 113 * - LBL2 6.6 114 LBL 2 115 M3 116 L X-34.4 Y+25 R0 FMAX M99 117 L X+13.1 Y+40.4 R0 FMAX M99 118 L X+42.5 Y+0 R0 FMAX M99 119 L X+13.1 Y-40.4 R0 FMAX M99 120 L X-34.4 Y-25 R0 FMAX M99 121 LBL 0 122 ; 123 * - LBL3 3.2 124 LBL 3 125 M3 126 L X+14.8 Y-2.8 R0 FMAX M99 127 LBL 0 128 ; 129 * - LBL4 6 130 LBL 4 131 M3 132 L X+26 Y-11.5 R0 FMAX M99 133 LBL 0 134 ; 135 * - LBL5 M8X0.75 136 LBL 5 137 M3 138 L X+26 Y+9 R0 FMAX M99 139 LBL 0 140 ; 141 END PGM KS-N100-02-1 MM <file_sep>/cnc programming/Heidenhain/JF/SD/DYSTANS/OTWORY-6,6.H 0 BEGIN PGM OTWORY-6,6 MM 1 BLK FORM 0.1 Z X-60 Y-60 Z-34 2 BLK FORM 0.2 X+60 Y+60 Z+0 3 ; 4 ;--------------------------------------------- 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 ;--------------------------------------------- 7 ; 8 ; 9 * - 6.6 10 TOOL CALL 1 Z S4818 F829 11 TOOL DEF 14 12 M13 13 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-29 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+17 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 14 CALL LBL 1 15 M5 M9 16 ; 17 ;--------------------------------------------- 18 L Z-5 R0 FMAX M91 19 L X+260 Y+535 R0 FMAX M91 20 L M30 21 * - ----------------------------------------- 22 ; 23 * - LBL1 POGL FI 11/6.6 24 LBL 1 25 M3 26 L X+0 Y+48.5 R0 FMAX M99 27 L X-46.1 Y+15 R0 FMAX M99 28 L X+46.1 Y+15 R0 FMAX M99 29 L X-28.5 Y-39.2 R0 FMAX M99 30 L X+28.5 Y-39.2 R0 FMAX M99 31 LBL 0 32 ; 33 END PGM OTWORY-6,6 MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/FREZ-GWINT.H 0 BEGIN PGM FREZ-GWINT MM 1 CALL PGM TNC:\REF3 2 CALL PGM TNC:\Z19 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 PLANE RESET TURN F2500 5 BLK FORM 0.1 Z X-57 Y-57 Z-38 6 BLK FORM 0.2 X+57 Y+57 Z+0 7 ; 8 * - W5H7 9 TOOL CALL 5 Z S6360 F890 10 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-11.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+11.5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 11 CALL LBL 2 12 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+8 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 13 CALL LBL 1 14 ; 15 * - W 3 VHM 16 TOOL CALL 6 Z S10600 F1060 17 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+8 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+4 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 18 CALL LBL 3 19 M5 M9 20 ; 21 * - FP-4 22 TOOL CALL 26 Z S8000 F500 23 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-11.95 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.7 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+5 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 24 CALL LBL 2 25 M5 M9 26 ; 27 * - FREZ-GWINT 28 TOOL CALL 23 Z S10000 29 CYCL DEF 262 FREZ.WEWN. GWINTU ~ Q335=+6 ;SREDNICA NOMINALNA ~ Q239=+1 ;SKOK GWINTU ~ Q201=-11.6 ;GLEBOKOSC GWINTU ~ Q355=+0 ;PRZEJSCIA DODATKOWE ~ Q253=+1000 ;PREDK. POS. ZAGLEB. ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q207=+750 ;POSUW FREZOWANIA 30 CALL LBL 2 31 M5 M9 32 ; 33 * - ********** 34 CALL PGM TNC:\REF 35 CALL PGM TNC:\Z19 36 ; /// 37 CALL LBL 99 38 ; /// 39 M30 40 * - ********** 41 * - LBL 1 - 5H7 42 LBL 1 43 L X+0 Y-48.5 R0 FMAX M99 M13 44 LBL 0 45 * - LBL 2 - M6 46 LBL 2 47 L X-46.1 Y+15 R0 FMAX M99 M13 48 L X+46.1 Y+15 R0 FMAX M99 M13 49 L X+0 Y+48.5 R0 FMAX M99 M13 50 L X-28.5 Y-39.2 R0 FMAX M99 M13 51 L X+28.5 Y-39.2 R0 FMAX M99 M13 52 LBL 0 53 * - LBL 3 - 3 54 LBL 3 55 L X-21 Y+0 R0 FMAX M99 M13 56 LBL 0 57 ; /// 58 LBL 99 59 ; /// 60 END PGM FREZ-GWINT MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/TULEJA-R10.H 0 BEGIN PGM TULEJA-R10 MM 1 BLK FORM 0.1 Z X-50 Y+0 Z-6 2 BLK FORM 0.2 X+50 Y+50 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IZ+0 7 ;--------------------------------------------- 8 TOOL CALL 27 Z S9987 F1000 DR-0.005 9 M8 M3 10 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;<NAME> ~ Q218=+28 ;DLUGOSC ROWKA ~ Q219=+20 ;SZEROKOSC ROWKA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q374=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-7 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+0 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q366=+2 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q439=+3 ;BAZA POSUWU 11 CALL LBL 1 12 L A+72 FMAX 13 CALL LBL 1 14 L A+144 FMAX 15 CALL LBL 1 16 L A+216 FMAX 17 CALL LBL 1 18 L A+288 FMAX 19 CALL LBL 1 20 M5 M9 21 ; 22 ;--------------------------------------------- 23 L Z-5 R0 FMAX M91 24 L X+260 Y+535 R0 FMAX M91 25 L M30 26 * - ----------------------------------------- 27 * - LBL1 28 LBL 1 29 M3 30 L X+0 Y+0 R0 FMAX M99 31 LBL 0 32 END PGM TULEJA-R10 MM <file_sep>/cnc programming/Heidenhain/JF/SP/PLASZCZ-PRZECIECIA-POLP-DYST.H 0 BEGIN PGM PLASZCZ-PRZECIECIA-POLP-DYST MM 1 BLK FORM 0.1 Z X-76 Y-76 Z-21 2 BLK FORM 0.2 X+76 Y+76 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO / 5 STOP 6 L X+0 Y+0 R0 FMAX 7 TOOL CALL 30 Z 8 TOOL DEF 27 9 ; 10 TCH PROBE 412 PKT.BAZ.OKRAG WEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+120 ;SREDNICA NOMINALNA ~ Q325=+40 ;KAT POCZATKOWY ~ Q247=+50 ;KATOWY PRZYROST-KROK ~ Q261=-4 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+3 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 11 ; 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 CYCL DEF 7.0 PUNKT BAZOWY 14 CYCL DEF 7.1 IZ+0 15 ;--------------------------------------------- 16 ; 17 TOOL CALL 27 Z S9987 F600 18 TOOL DEF 28 19 M8 M3 20 ; 21 CYCL DEF 10.0 OBROT 22 CYCL DEF 10.1 ROT-60 23 ; 24 L X-2 Y+85 RL FMAX 25 L Z+1 FMAX 26 L Z-20.6 F AUTO 27 L X-2 Y+61 RL F AUTO 28 L X-2 Y+60 29 RND R1 F AUTO 30 L X-10 Y+57 31 L Z+30 R0 FMAX 32 ; 33 CYCL DEF 10.0 OBROT 34 CYCL DEF 10.1 ROT+0 35 ; / 36 STOP 37 ; 38 CYCL DEF 10.0 OBROT 39 CYCL DEF 10.1 ROT+60 40 ; 41 L X+2 Y+85 RR FMAX 42 L Z+1 FMAX 43 L Z-20.6 F AUTO 44 L X+2 Y+61 RR F AUTO 45 L X+2 Y+60 46 RND R1 F AUTO 47 L X+10 Y+57 48 L Z+30 R0 FMAX 49 ; 50 CYCL DEF 10.0 OBROT 51 CYCL DEF 10.1 ROT+0 52 ; 53 M5 M9 54 ; 55 ;--------------------------------------------- 56 L Z-5 R0 FMAX M91 57 L X+260 Y+535 R0 FMAX M91 58 L M30 59 * - ----------------------------------------- 60 * - LBL1 TRAS 61 LBL 1 62 M3 63 L X+0 Y+0 R0 FMAX M99 64 LBL 0 65 END PGM PLASZCZ-PRZECIECIA-POLP-DYST MM <file_sep>/cnc programming/Heidenhain/JF/AD/N021.00/GAB.H 0 BEGIN PGM GAB MM 1 BLK FORM 0.1 Z X-30 Y-15 Z-11 2 BLK FORM 0.2 X+30 Y+15 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 * - TOR-ZGR / 8 STOP 9 TOOL CALL 14 Z S1300 F800 10 TOOL DEF 6 11 M7 M3 12 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+50 ;DLUG. 1-SZEJ STRONY ~ Q424=+62 ;WYMIAR POLWYROBU 1 ~ Q219=+23.6 ;DLUG. 2-GIEJ STRONY ~ Q425=+30 ;WYMIAR POLWYROBU 2 ~ Q220=+0.15 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-10.7 ;GLEBOKOSC ~ Q202=+0.8 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 13 CALL LBL 1 14 M5 M9 15 ; 16 * - WYK 17 TOOL CALL 6 Z S3000 F600 DR+0 / 18 STOP 19 TOOL DEF 30 20 M7 M3 21 CYCL DEF 256 CZOP PROSTOKATNY ~ Q218=+50 ;DLUG. 1-SZEJ STRONY ~ Q424=+51 ;WYMIAR POLWYROBU 1 ~ Q219=+23.6 ;DLUG. 2-GIEJ STRONY ~ Q425=+25 ;WYMIAR POLWYROBU 2 ~ Q220=+0.15 ;PROMIEN NAROZA ~ Q368=+0 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE CZOPU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-10.7 ;GLEBOKOSC ~ Q202=+5.35 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q437=+0 ;POZYCJA NAJAZDU 22 CALL LBL 1 23 M5 M9 24 ; 25 ; 26 ;--------------------------------------------- 27 L Z-5 R0 FMAX M91 28 L X+260 Y+535 R0 FMAX M91 29 CALL LBL 99 / 30 L M30 31 * - ----------------------------------------- 32 * - LBL1 33 LBL 1 34 M3 35 L X+0 Y+0 R0 FMAX M99 36 LBL 0 37 LBL 99 38 LBL 0 39 ; 40 END PGM GAB MM <file_sep>/cnc programming/Heidenhain/JF/AD/N030.02/90H7-WYK.H 0 BEGIN PGM 90H7-WYK MM 1 BLK FORM 0.1 Z X-140 Y-100 Z-18 2 BLK FORM 0.2 X+140 Y+100 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IX-60 7 ; 8 L X+0 Y+0 R0 FMAX 9 ;--------------------------------------------- 10 ; 11 ; 12 * - FP-12 13 TOOL CALL 12 Z S1450 F300 DR-0.04 14 L X+0 Y+0 R0 FMAX 15 M8 M3 16 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-21.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+21.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+90 ;SREDNICA NOMINALNA ~ Q342=+89 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;RODZAJ FREZOWANIA 17 CYCL CALL 18 ; 19 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 20 CYCL DEF 7.0 PUNKT BAZOWY 21 CYCL DEF 7.1 IX+60 22 ; 23 * - FP-12 24 TOOL CALL 12 Z S1450 F300 DR-0.04 25 L X+0 Y+0 R0 FMAX 26 M8 M3 27 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-21.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+21.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+90 ;SREDNICA NOMINALNA ~ Q342=+89 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 28 CYCL CALL 29 ; 30 M5 M9 31 ; 32 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 33 ; 34 ;--------------------------------------------- 35 L Z+0 R0 FMAX M91 36 L X+260 Y+535 R0 FMAX M91 / 37 L M30 38 * - ----------------------------------------- 39 END PGM 90H7-WYK MM <file_sep>/cnc programming/Heidenhain/SPLASZCZENIE-WALEK.H 0 BEGIN PGM SPLASZCZENIE-WALEK MM 1 BLK FORM 0.1 Z X-49.5 Y-100 Z-36 2 BLK FORM 0.2 X+49.5 Y+100 Z+36 3 ;------------------------------------------- 4 ; 5 ;------------------------------------------- 6 ; USTAW BAZE W OSI Y DOKLADNIE PO SRODKU SPLASZCZENIA ( SRODEK MOSTKA ) 7 ; USTAW "Z" W OSI DETALU 8 ; USTAW BAZE W OSI X NA SRODKU DETALU 9 ; WYSUNIECIE NARZEDZIA - 82mm 10 ;------------------------------------------- 11 STOP 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 L X+0 Y+0 R0 FMAX 14 * - SONDA / 15 TOOL CALL 30 Z S50 / 16 TOOL DEF 16 / 17 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+50 ;SRODEK W 1-SZEJ OSI ~ Q322=+50 ;SRODEK W 2-SZEJ OSI ~ Q311=+15 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=+0 ;WYSOKOSC POMIARU ~ Q320=+0 ;BEZPIECZNA WYSOKOSC ~ Q260=+100 ;BEZPIECZNA WYSOKOSC ~ Q305=+0 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 18 ; 19 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 20 ;------------------------------------------- 21 STOP 22 ; WPISZ PONIZEJ SZEROKOSC MOSTKA W MIEJSCU SPLASZCZENIA ( W OSI Y ) JAKO~ WARTOSC Q1, ZAOKRAGLAJAC DO DWOCH MIEJSC PO PRZECINKU 23 ; 24 FN 0: Q1 =+78.56 25 ; 26 STOP 27 * - GLOWICA-20-ALU 28 TOOL CALL 16 Z S15000 F1800 29 TOOL DEF 30 30 M3 M8 31 L X-47 Y+0 FMAX 32 L Z+60 FMAX 33 L Z+30 F1800 34 ; 35 FN 2: Q1 =+Q1 - +1 36 FN 4: Q2 =+Q1 DIV +2 37 FN 2: Q3 =+Q2 - +10 38 ; 39 LBL 1 40 L IZ-1 41 L Y-Q3 FMAX 42 L X-20 Y-Q3 43 RND R14 44 L X-20 Y+Q2 45 RND R14 46 L X-47 47 LBL 0 48 ; 49 CALL LBL 1 REP61 50 ; 51 L Z+60 FMAX 52 L X+47 Y+0 FMAX 53 L Z+30 F1800 54 ; 55 LBL 2 56 L IZ-1 57 L Y-Q3 FMAX 58 L X+20 Y-Q3 59 RND R14 60 L X+20 Y+Q2 61 RND R14 62 L X+47 63 LBL 0 64 ; 65 CALL LBL 2 REP61 66 M5 M9 67 ; 68 ;-------------------------------------- 69 L Z+0 R0 FMAX M91 70 L X+100 Y+535 R0 FMAX 71 L M30 72 * - ----------------------------------- 73 END PGM SPLASZCZENIE-WALEK MM <file_sep>/cnc programming/Heidenhain/JF/AD/PLYTKA-GRN-SUR/OTWORY.H 0 BEGIN PGM OTWORY MM 1 BLK FORM 0.1 Z X-43 Y-43 Z-6 2 BLK FORM 0.2 X+43 Y+43 Z+0.1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 STOP / 6 TOOL CALL 30 Z / 7 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+109 ;SREDNICA NOMINALNA ~ Q325=+15 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-1.5 ;WYSOKOSC POMIARU ~ Q320=+5 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+1 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+1 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=-25 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 8 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 9 CYCL DEF 7.0 PUNKT BAZOWY 10 CYCL DEF 7.1 IY-20 11 ;--------------------------------------------- 12 ; 13 * - NAW 14 TOOL CALL 3 Z S600 F30 15 TOOL DEF 4 16 M8 17 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 18 CALL LBL 3 19 CALL LBL 1 20 CALL LBL 2 21 M5 M9 22 ; 23 * - W 6.4 24 TOOL CALL 4 Z S700 F30 / 25 STOP 26 TOOL DEF 24 27 M8 28 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-14 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 29 CALL LBL 2 30 M5 M9 31 ; 32 * - FP-8 33 TOOL CALL 24 Z S2222 F180 34 TOOL DEF 8 35 M8 36 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-5.35 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.05 ;SREDNICA NOMINALNA ~ Q342=+6.3 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;RODZAJ FREZOWANIA 37 CALL LBL 2 38 M5 M9 39 ; 40 * - W 4.8 41 TOOL CALL 8 Z S750 F30 42 TOOL DEF 6 43 M8 44 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-14 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 45 CALL LBL 1 46 M5 M9 47 ; 48 * - W 5 49 TOOL CALL 6 Z S700 F30 50 TOOL DEF 26 51 M8 52 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-14 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 53 CALL LBL 3 54 M5 M9 55 ; 56 * - FAZY (FAZOWNIK 90ST) 57 TOOL CALL 26 Z S600 F30 58 TOOL DEF 12 59 M8 60 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-1.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 61 CALL LBL 1 62 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-4.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 63 CALL LBL 2 64 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 65 CALL LBL 3 66 M5 M9 67 ; 68 * - R 5H7 69 TOOL CALL 12 Z S150 F30 70 TOOL DEF 15 71 M8 72 CYCL DEF 201 ROZWIERCANIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-10 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+60 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 73 CALL LBL 1 74 M5 M9 75 ; 76 * - M6 77 TOOL CALL 15 Z S100 78 TOOL DEF 30 79 M8 80 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-11 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 81 CALL LBL 3 82 M5 M9 83 ; 84 ;--------------------------------------------- 85 L Z-5 R0 FMAX M91 86 L X+260 Y+535 R0 FMAX M91 87 L M30 88 * - ----------------------------------------- 89 * - LBL1 5H7 90 LBL 1 91 M3 92 L X-27 Y+32 R0 FMAX M99 93 L X+27 Y+32 R0 FMAX M99 94 LBL 0 95 * - LBL2 6.4/11 96 LBL 2 97 M3 98 L X-32 Y+23 R0 FMAX M99 99 L X+32 Y+23 R0 FMAX M99 100 LBL 0 101 * - LBL3 M6 102 LBL 3 103 M3 104 L X-19.5 Y+32 R0 FMAX M99 105 L X+19.5 Y+32 R0 FMAX M99 106 LBL 0 107 END PGM OTWORY MM <file_sep>/cnc programming/Heidenhain/JF/PLYTY/FAZA-7X45.H 0 BEGIN PGM FAZA-7X45 MM 1 BLK FORM 0.1 Z X-364 Y-65 Z-28 2 BLK FORM 0.2 X+364 Y+65 Z+0.1 3 ; 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 PLANE RESET TURN F2500 6 ; 7 CYCL DEF 7.0 PUNKT BAZOWY 8 CYCL DEF 7.1 IZ+0 9 ; 10 CYCL DEF 7.0 PUNKT BAZOWY 11 CYCL DEF 7.1 X-364 12 TOOL CALL 29 Z S8000 F800 DR+0 13 M13 14 Q1 = - 10 15 CALL LBL 1 16 Q1 = - 20 17 CALL LBL 1 18 Q1 = - 30 19 CALL LBL 1 20 ; 21 ; 22 * - 2 23 TOOL CALL 29 Z S8000 F800 DR+0 24 M13 25 Q1 = - 10 26 CALL LBL 2 27 Q1 = - 20 28 CALL LBL 2 29 Q1 = - 30 30 CALL LBL 2 31 ; 32 CYCL DEF 7.0 PUNKT BAZOWY 33 CYCL DEF 7.1 X+364 34 ; 35 * - 3 36 TOOL CALL 29 Z S8000 F800 DR+0 37 M13 38 Q1 = - 10 39 CALL LBL 3 40 Q1 = - 20 41 CALL LBL 3 42 Q1 = - 30 43 CALL LBL 3 44 ; 45 ; 46 * - 4 47 TOOL CALL 29 Z S8000 F800 DR+0 48 M13 49 Q1 = - 10 50 CALL LBL 4 51 Q1 = - 20 52 CALL LBL 4 53 Q1 = - 30 54 CALL LBL 4 55 ; 56 ; 57 M5 58 M9 59 * - ******** 60 L Z-5 R0 FMAX M91 61 L X+400 Y+535 R0 FMAX M91 62 M30 63 ; 64 LBL 1 65 L Z+10 FMAX 66 L X+13 Y-70 R0 F2000 67 L Z+Q1 F2000 68 L X+0 Y-57 F AUTO 69 L Z+10 R0 FMAX 70 LBL 0 71 ; 72 LBL 2 73 L Z+10 FMAX 74 L X-5 Y+57 R0 F2000 75 L Z+Q1 F2000 76 L X+8 Y+70 F AUTO 77 L Z+10 R0 FMAX 78 LBL 0 79 ; 80 LBL 3 81 L Z+10 FMAX 82 L X-13 Y+70 R0 F2000 83 L Z+Q1 F2000 84 L X+0 Y+57 F AUTO 85 L Z+10 R0 FMAX 86 LBL 0 87 ; 88 LBL 4 89 L Z+10 FMAX 90 L X+5 Y-57 R0 F2000 91 L Z+Q1 F2000 92 L X-8 Y-70 F AUTO 93 L Z+10 R0 FMAX 94 LBL 0 95 ; 96 END PGM FAZA-7X45 MM <file_sep>/cnc programming/Heidenhain/JF/PLYTY/PLAN-WSTEP.H 0 BEGIN PGM PLAN-WSTEP MM 1 BLK FORM 0.1 Z X-400 Y-150 Z-35 2 BLK FORM 0.2 X+400 Y+150 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 BLK FORM 0.1 Z X-400 Y-150 Z-35 7 BLK FORM 0.2 X+400 Y+150 Z+1 8 ;--------------------------------------------- 9 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 10 ;--------------------------------------------- 11 ; 12 * - GLOW-20 13 STOP 14 TOOL CALL 24 Z S11987 F2500 15 TOOL DEF 30 16 M8 M3 17 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-390 ;PKT.STARTU 1SZEJ OSI ~ Q226=+170 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.5 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.1 ;PUNKT KONCOWY 3. OSI ~ Q218=+780 ;DLUG. 1-SZEJ STRONY ~ Q219=-340 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1.2 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+4 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 18 CALL LBL 1 19 M5 M9 20 ; 21 * - GLOW-20 WYK 22 STOP 23 TOOL CALL 24 Z S11987 F3000 24 TOOL DEF 30 25 M8 M3 26 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-390 ;PKT.STARTU 1SZEJ OSI ~ Q226=+170 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+780 ;DLUG. 1-SZEJ STRONY ~ Q219=-340 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+0.9 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385= AUTO ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+4 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 27 CALL LBL 1 28 M5 M9 29 ; 30 ;--------------------------------------------- 31 L Z-5 R0 FMAX M91 32 L X+260 Y+535 R0 FMAX M91 33 L M30 34 * - ----------------------------------------- 35 * - LBL1 36 LBL 1 37 M3 38 L X+0 Y+0 R0 FMAX M99 39 LBL 0 40 ; 41 END PGM PLAN-WSTEP MM <file_sep>/cnc programming/Heidenhain/JF/PODZIALY/PODZIAL-PRZECIECIE.H 0 BEGIN PGM PODZIAL-PRZECIECIE MM 1 BLK FORM 0.1 Z X-60 Y-60 Z-6 2 BLK FORM 0.2 X+60 Y+60 Z+0.1 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 4 TOOL CALL 11 Z S3000 F2000 DL+0 5 M3 M8 6 L Z+300 R0 FMAX 7 L X-130 Y-5 R0 FMAX 8 L Z+1 R0 FMAX 9 L Z+0 R0 F AUTO 10 LBL 1 11 L IZ-0.075 IX+265 R0 F AUTO 12 L IZ-0.075 IX-265 R0 13 LBL 0 14 CALL LBL 1 REP33 15 STOP 16 M5 M9 17 L Z+300 FMAX 18 L Y+370 R0 FMAX 19 STOP M30 20 END PGM PODZIAL-PRZECIECIE MM <file_sep>/cnc programming/Heidenhain/JF/KR/N091.00/n091d.h 0 BEGIN PGM n091d MM 1 BLK FORM 0.1 Z X-35 Y-35 Z-15 2 BLK FORM 0.2 X+35 Y+35 Z+0.1 3 ;MASTERCAM - X9 4 ;MCX FILE -~ Z:\00NZL\KR\KRN09100\MCX\KOEK_MOCUJCY_ZAPFEN_N091_FASOLKA_MIKRON.MCX-9 5 ;POST - MPPOSTABILITY_AVIA_VMC_800_4X.PST 6 ;PROGRAM - n091d.h 7 ;DATE - 2018.02.01 8 ;TIME - 8:57 AM 9 ;3 - NAWIERTAK FI 6 - D6.000mm 10 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 11 CYCL DEF 7.0 PUNKT BAZOWY 12 CYCL DEF 7.1 IY+17 13 M126 14 M129 15 PLANE RESET TURN FMAX 16 ; 17 * - NAWIERTAK FI 6 18 TOOL CALL 8 Z S1000 DL+0.3 19 TOOL DEF 24 20 * - FAZUJE FASOLKE OD STRONY CZOPA 21 ;NAWIERTAK FI 6 TOOL - 3 DIA. OFF. - 3 LEN. - 3 DIA. - 6. 22 ;HOLDER - DEFAULT HOLDER 23 CYCL DEF 32.0 TOLERANCJA 24 CYCL DEF 32.1 T0.003 25 CYCL DEF 32.2 HSC-MODE:0 / 26 L A+0 FMAX 27 M3 28 L X-0.5 Y-16.5 FMAX M8 29 L Z+15 FMAX 30 L Z-20 FMAX 31 L Z-28 F50 32 L Y-17.5 33 CC X+0 Y-17.5 34 C X+0.5 DR+ 35 L Y-16.5 36 CC X+0 Y-16.5 37 C X-0.5 DR+ 38 L Z+15 FMAX 39 CYCL DEF 32.0 TOLERANCJA 40 CYCL DEF 32.1 41 M5 42 L Z-15 R0 FMAX M91 M9 43 L X+273 Y+529 R0 FMAX M91 / 44 L A+0 FMAX M91 / 45 M2 46 END PGM n091d MM <file_sep>/cnc programming/Heidenhain/JF/PLYTY/KM-PLYTA-MOC-2STR.h 0 BEGIN PGM KM-PLYTA-MOC-2STR MM 1 BLK FORM 0.1 Z X-258 Y-320 Z-28 2 BLK FORM 0.2 X+258 Y+0 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 STOP 8 * - NAW 8 9 TOOL CALL 9 Z S1200 F120 10 TOOL DEF 14 11 M8 12 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 13 CALL LBL 2 14 CALL LBL 3 15 M5 M9 16 ; 17 * - W 7.8 VHM DOWIERCANIE NA WYLOT 18 TOOL CALL 14 Z S4077 F799 19 STOP 20 TOOL DEF 16 21 M8 22 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+6 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 23 CALL LBL 1 24 M5 M9 25 ; 26 * - W 8.4 HSS 27 TOOL CALL 16 Z S800 F100 28 STOP 29 TOOL DEF 29 30 M8 31 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-25 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 32 CALL LBL 2 33 M5 M9 34 ; 35 * - 12H7 ZGR 36 TOOL CALL 29 Z S7987 F600 37 STOP 38 TOOL DEF 29 39 M8 40 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.05 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.8 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q335=+11.9 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 41 CALL LBL 3 42 M5 M9 43 ; 44 * - 12H7 WYK 45 TOOL CALL 29 Z S7987 F600 DR+0.05 46 STOP 47 TOOL DEF 29 48 M8 49 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q335=+12 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 50 CALL LBL 3 51 M5 M9 52 ; 53 * - POGLEBIENIA 14X12 54 TOOL CALL 29 Z S7987 F800 55 STOP 56 TOOL DEF 26 57 M8 58 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+1 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q335=+14 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 59 CALL LBL 4 60 M5 M9 61 ; 62 * - FAZY 63 TOOL CALL 26 Z S1200 F120 64 TOOL DEF 7 65 M8 66 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.05 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2.05 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-2 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 67 CALL LBL 1 68 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 69 CALL LBL 3 70 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.9 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1.9 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-3 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 71 CALL LBL 2 72 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-6 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 73 CALL LBL 4 74 M5 M9 75 ; 76 * - R 8H7 77 TOOL CALL 7 Z S130 F30 78 STOP 79 TOOL DEF 23 80 M8 81 CYCL DEF 201 ROZWIERCANIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-21 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+90 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 82 CALL LBL 1 83 M5 M9 84 ; 85 * - GW HC M8 SPREZYNKI 86 TOOL CALL 23 Z S150 87 STOP 88 TOOL DEF 29 89 M8 90 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-23 ;GLEBOKOSC GWINTU ~ Q239=+1.25 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. 91 CALL LBL 2 92 M5 M9 93 ; 94 * - POGLEBIENIE R7 MALE 95 TOOL CALL 29 Z S9987 F1500 96 STOP 97 TOOL DEF 29 98 M8 99 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+21 ;DLUGOSC ROWKA ~ Q219=+14 ;SZEROKOSC ROWKA ~ Q368=+0.1 ;NADDATEK NA STRONE ~ Q374=+90 ;KAT OBROTU ~ Q367=+2 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-12 ;GLEBOKOSC ~ Q202=+1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+6 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q366=+2 ;ZAGLEBIANIE ~ Q385=+1000 ;POSUW OBR.WYKAN. ~ Q439=+3 ;BAZA POSUWU 100 CALL LBL 5 101 M5 M9 102 ; 103 * - POGLEBIENIE R7 DUZE 104 TOOL CALL 29 Z S9987 F1500 105 STOP 106 TOOL DEF 9 107 M8 108 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+0 ;RODZAJ OBROBKI ~ Q218=+30 ;DLUG. 1-SZEJ STRONY ~ Q219=+21 ;DLUG. 2-GIEJ STRONY ~ Q220=+7 ;PROMIEN NAROZA ~ Q368=+0.1 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-12 ;GLEBOKOSC ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206=+1000 ;WARTOSC POSUWU WGL. ~ Q338=+6 ;DOSUW - OBR.WYKONCZ. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q370=+0.4 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385=+1000 ;POSUW OBR.WYKAN. 109 CALL LBL 6 110 M5 M9 111 ; 112 * - FAZA R7 MALE 113 TOOL CALL 9 Z S6000 F1000 DR-3 114 STOP 115 TOOL DEF 9 116 M8 117 CYCL DEF 253 FREZOWANIE KANALKA ~ Q215=+2 ;<NAME> ~ Q218=+21 ;DLUGOSC ROWKA ~ Q219=+14 ;SZEROKOSC ROWKA ~ Q368=+0.1 ;NADDATEK NA STRONE ~ Q374=+90 ;KAT OBROTU ~ Q367=+2 ;POLOZENIE ROWKA ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1.1 ;GLEBOKOSC ~ Q202=+1.1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+2 ;DOSUW - OBR.WYKONCZ. ~ Q200=+0.5 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q366=+2 ;ZAGLEBIANIE ~ Q385=+1000 ;POSUW OBR.WYKAN. ~ Q439=+3 ;BAZA POSUWU 118 CALL LBL 5 119 M5 M9 120 ; 121 * - FAZA R7 DUZE 122 TOOL CALL 9 Z S6000 F1000 DR-3 123 STOP 124 TOOL DEF 30 125 M8 126 CYCL DEF 251 KIESZEN PROSTOKATNA ~ Q215=+2 ;RODZAJ OBROBKI ~ Q218=+30 ;DLUG. 1-SZEJ STRONY ~ Q219=+21 ;DLUG. 2-GIEJ STRONY ~ Q220=+7 ;PROMIEN NAROZA ~ Q368=+0.1 ;NADDATEK NA STRONE ~ Q224=+0 ;KAT OBROTU ~ Q367=+0 ;POLOZENIE KIESZENI ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-1.1 ;GLEBOKOSC ~ Q202=+1.1 ;GLEBOKOSC DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q338=+2 ;DOSUW - OBR.WYKONCZ. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q366=+1 ;ZAGLEBIANIE ~ Q385= AUTO ;POSUW OBR.WYKAN. 127 CALL LBL 6 128 M5 M9 129 ; 130 ;--------------------------------------------- 131 L Z-5 R0 FMAX M91 132 L X+260 Y+535 R0 FMAX M91 133 L M30 134 * - ----------------------------------------- 135 * - LBL1 7.8 136 LBL 1 137 M3 138 L X-232 Y-52 R0 FMAX M99 139 L X-128 Y-52 R0 FMAX M99 140 L X-112 Y-52 R0 FMAX M99 141 L X-8 Y-52 R0 FMAX M99 142 ; 143 L X+232 Y-52 R0 FMAX M99 144 L X+128 Y-52 R0 FMAX M99 145 L X+112 Y-52 R0 FMAX M99 146 L X+8 Y-52 R0 FMAX M99 147 ; 148 L X-232 Y-201 R0 FMAX M99 149 L X-128 Y-201 R0 FMAX M99 150 L X-112 Y-201 R0 FMAX M99 151 L X-8 Y-201 R0 FMAX M99 152 ; 153 L X+232 Y-201 R0 FMAX M99 154 L X+128 Y-201 R0 FMAX M99 155 L X+112 Y-201 R0 FMAX M99 156 L X+8 Y-201 R0 FMAX M99 157 LBL 0 158 ; 159 * - LBL2 HC M8 SPREZYNKI 160 LBL 2 161 M3 162 L X-195 Y-17 R0 FMAX M99 163 L X-195 Y-207 R0 FMAX M99 164 L X-195 Y-297 R0 FMAX M99 165 ; 166 L X+195 Y-17 R0 FMAX M99 167 L X+195 Y-207 R0 FMAX M99 168 L X+195 Y-297 R0 FMAX M99 169 LBL 0 170 ; 171 * - LBL3 12H7 172 LBL 3 173 M3 174 L X-160 Y-60 R0 FMAX M99 175 L X+160 Y-60 R0 FMAX M99 176 LBL 0 177 ; 178 * - LBL4 9 179 LBL 4 180 M3 181 L X-232 Y-7 R0 FMAX M99 182 L X-128 Y-7 R0 FMAX M99 183 L X-112 Y-7 R0 FMAX M99 184 L X-8 Y-7 R0 FMAX M99 185 ; 186 L X+232 Y-7 R0 FMAX M99 187 L X+128 Y-7 R0 FMAX M99 188 L X+112 Y-7 R0 FMAX M99 189 L X+8 Y-7 R0 FMAX M99 190 ; 191 L X-232 Y-87 R0 FMAX M99 192 L X-128 Y-87 R0 FMAX M99 193 L X-112 Y-87 R0 FMAX M99 194 L X-8 Y-87 R0 FMAX M99 195 ; 196 L X+232 Y-87 R0 FMAX M99 197 L X+128 Y-87 R0 FMAX M99 198 L X+112 Y-87 R0 FMAX M99 199 L X+8 Y-87 R0 FMAX M99 200 ; 201 L X-232 Y-167 R0 FMAX M99 202 L X-128 Y-167 R0 FMAX M99 203 L X-112 Y-167 R0 FMAX M99 204 L X-8 Y-167 R0 FMAX M99 205 ; 206 L X+232 Y-167 R0 FMAX M99 207 L X+128 Y-167 R0 FMAX M99 208 L X+112 Y-167 R0 FMAX M99 209 L X+8 Y-167 R0 FMAX M99 210 ; 211 L X-232 Y-247 R0 FMAX M99 212 L X-128 Y-247 R0 FMAX M99 213 L X-112 Y-247 R0 FMAX M99 214 L X-8 Y-247 R0 FMAX M99 215 ; 216 L X+232 Y-247 R0 FMAX M99 217 L X+128 Y-247 R0 FMAX M99 218 L X+112 Y-247 R0 FMAX M99 219 L X+8 Y-247 R0 FMAX M99 220 LBL 0 221 ; 222 * - LBL5 R7 MALE 223 LBL 5 224 M3 225 L X-323 Y-7 R0 FMAX M99 226 L X+323 Y-7 R0 FMAX M99 227 LBL 0 228 ; 229 * - LBL6 R7 DUZE 230 LBL 6 231 M3 232 L X-120 Y-3.5 R0 FMAX M99 233 L X+0 Y-3.5 R0 FMAX M99 234 L X+120 Y-3.5 R0 FMAX M99 235 LBL 0 236 END PGM KM-PLYTA-MOC-2STR MM <file_sep>/if_else_statement.cpp #include<iostream> using namespace std; int main() { int x,y,age; cout << "Please type numerals only!\n Type '1' to close"; cin >> y; if (y == 1) { goto aa; } else { cout << "Why didn't you close an application?\n Give me value of 'x':"; cin >> x; if ( x > 10 ) { cout << "ARE U CRAZY? You gave me a number greater than 10!?\n So now, try to guess how old my cat is:>"; cin >> age; if (age == 7) { cout << "mIAUUUUU!!"; system("pause"); } else { goto aa; } } } aa: return(0); } <file_sep>/matrix.c #include<conio.h> #include<stdio.h> #include<math.h> #define n 3 #define m 3 void load(int t[][m]); void display(int t[n][m]); int diagonal(int t[n][m]); int main() { int t[n][m]; load(t); display(t); printf("The total sum of matrix's diagonal: %d",diagonal(t)); return 0; } void load(int t[n][m]) { int i,j; printf("Please type matrix components:\n"); for (i=0; i<n; i++) for (j=0; j<m; j++) scanf("%d",&t[i][j]); } void display(int t[n][m]) { printf("Components of your matrix:\n"); int i,j; for (i=0; i<n; i++) for(j=0; j<m; j++) { printf("%d\n",t[i][j]); if (j==m-1) printf(" "); } } int diagonal(int t[n][m]) { int i,j,sum; sum=0; for (i=0; i<n; i++) for (j=0; j<m; j++) if (i==j) sum=sum+t[i][j]; return(sum); } <file_sep>/README.md # Miscellaneous This repository contains my old, simple applications from the beginnings and other. <NAME> 2018 :-) <file_sep>/cnc programming/Heidenhain/JF/_INNE/PODWIERTY-BLOK150-FI9.h 0 BEGIN PGM PODWIERTY-BLOK150-FI9 MM 1 BLK FORM 0.1 Z X+0 Y-75 Z-75 2 BLK FORM 0.2 X+253 Y+75 Z+75 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 CYCL DEF 7.0 PUNKT BAZOWY 6 CYCL DEF 7.1 IZ+75 7 ;--------------------------------------------- 8 ; 9 STOP 10 * - FP-8 11 TOOL CALL 29 Z S7987 F300 12 TOOL DEF 28 13 M8 14 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-20 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=-20 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q335=+9.05 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;RODZAJ FREZOWANIA 15 CALL LBL 1 16 M5 M9 17 ; 18 * - W-9 19 TOOL CALL 28 Z S900 F100 20 TOOL DEF 4 21 M8 22 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-10 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-40 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 23 CALL LBL 1 24 M5 M9 25 ; 26 * - W-9-PLASKIE 27 TOOL CALL 4 Z S800 F50 28 TOOL DEF 30 29 M8 30 CYCL DEF 200 WIERCENIE ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-7 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-50 ;WSPOLRZEDNE POWIERZ. ~ Q204=+100 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 31 CALL LBL 1 32 M5 M9 33 ; 34 ;--------------------------------------------- 35 L Z-5 R0 FMAX M91 36 L X+260 Y+535 R0 FMAX M91 37 L M30 38 * - ----------------------------------------- 39 * - LBL1 40 LBL 1 41 M3 42 L X+96 Y-66.5 R0 FMAX M99 43 L X+96 Y+66.5 R0 FMAX M99 44 L X+201 Y-66.5 R0 FMAX M99 45 L X+201 Y+66.5 R0 FMAX M99 46 LBL 0 47 END PGM PODWIERTY-BLOK150-FI9 MM <file_sep>/switch_instruction.cpp #include <iostream> int main() { std::cout << "Captain, which subassembly need to be checked?\n" << "no. 10 - Engine\nno. 35 - Steer \nno. 30 - Radar\n" << "Give number, captain: "; int which; std::cin >> which; switch(which) //selection menu { case 10: std::cout << "Checking engine...\n"; break; case 30: std::cout << "Checking radar...\n"; break; case 35: std::cout << "Checking steer...\n"; break; default: std::cout << "You gave no. " << which << " - do not know that number ! "; break; } system("pause"); } <file_sep>/cnc programming/Heidenhain/JF/_INNE/PLYTA-DOLNA-BOK-1.h 0 BEGIN PGM PLYTA-DOLNA-BOK-1 MM 1 BLK FORM 0.1 Z X-53 Y+0 Z-340 2 BLK FORM 0.2 X+0 Y+80 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 L X+0 Y+0 FMAX 6 STOP 7 ; / 8 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+10 ;1.PKT POMIAROW 1.OSI ~ Q264=+10 ;1.PKT 2.OSI ~ Q261=-5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q272=+1 ;OS POMIAROWA ~ Q267=-1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 9 ; / 10 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 11 ; / 12 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=-10 ;1.PKT POMIAROW 1.OSI ~ Q264=-10 ;1.PKT 2.OSI ~ Q261=-5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q272=+2 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+1 ;NR W TABELI ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. 13 ; / 14 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 15 ; 16 ;--------------------------------------------- 17 ; 18 * - ODJAZD 19 L Z-5 R0 FMAX M91 20 L X+260 Y+535 R0 FMAX M91 21 ; 22 * - N-8 23 TOOL CALL 9 Z S1200 F120 / 24 STOP 25 TOOL DEF 15 26 M8 27 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 28 CALL LBL 1 29 CALL LBL 2 30 CALL LBL 3 31 M5 M9 32 ; 33 * - ODJAZD 34 L Z-5 R0 FMAX M91 35 L X+260 Y+535 R0 FMAX M91 36 ; 37 * - W-12 38 TOOL CALL 15 Z S666 F90 / 39 STOP 40 TOOL DEF 22 41 M8 42 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-180 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 43 CALL LBL 1 44 M5 M9 45 ; 46 * - ODJAZD 47 L Z-5 R0 FMAX M91 48 L X+260 Y+535 R0 FMAX M91 49 ; 50 * - W 8 HSS 51 TOOL CALL 22 Z S1000 F100 / 52 STOP 53 TOOL DEF 29 54 M8 55 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-175 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 56 CALL LBL 2 57 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-153 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+20 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 58 CALL LBL 3 59 M5 M9 60 ; 61 * - ODJAZD 62 L Z-5 R0 FMAX M91 63 L X+260 Y+535 R0 FMAX M91 64 ; 65 * - FP-8 66 TOOL CALL 29 Z S6500 F350 / 67 STOP 68 TOOL DEF 18 69 M8 70 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-17.05 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+15.25 ;SREDNICA NOMINALNA ~ Q342=+12 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 71 CALL LBL 1 72 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-25.05 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+12 ;SREDNICA NOMINALNA ~ Q342=+8 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 73 CALL LBL 2 74 CALL LBL 3 75 M5 M9 76 ; 77 * - ODJAZD 78 L Z-5 R0 FMAX M91 79 L X+260 Y+535 R0 FMAX M91 80 ; 81 * - W-9-VHM 82 TOOL CALL 18 Z S3533 F777 / 83 STOP 84 TOOL DEF 26 85 M7 86 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-19 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+19 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-25 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 87 CALL LBL 2 88 CALL LBL 3 89 M5 M9 90 ; 91 * - ODJAZD 92 L Z-5 R0 FMAX M91 93 L X+260 Y+535 R0 FMAX M91 94 ; 95 * - FAZ-16 96 TOOL CALL 26 Z S1100 F120 / 97 STOP 98 TOOL DEF 21 99 M8 100 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-8.2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+10 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 101 CALL LBL 1 102 CYCL DEF 200 WIERCENIE ~ Q200=+0 ;BEZPIECZNA WYSOKOSC ~ Q201=-6 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+10 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 103 CALL LBL 2 104 CALL LBL 3 105 M5 M9 106 ; 107 * - ODJAZD 108 L Z-5 R0 FMAX M91 109 L X+260 Y+535 R0 FMAX M91 110 ; 111 * - GW 3/8 112 TOOL CALL 21 Z S150 / 113 STOP 114 TOOL DEF 11 115 M8 116 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-16.5 ;GLEBOKOSC GWINTU ~ Q239=+1.337 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 117 CALL LBL 1 118 M5 M9 119 ; 120 * - ODJAZD 121 L Z-5 R0 FMAX M91 122 L X+260 Y+535 R0 FMAX M91 123 ; 124 * - GW M10x1 125 TOOL CALL 11 Z S150 / 126 STOP 127 TOOL DEF 9 128 M8 129 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-14.5 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=-25 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 130 CALL LBL 2 131 CALL LBL 3 132 M5 M9 133 ; 134 * - ODJAZD 135 L Z-5 R0 FMAX M91 136 L X+260 Y+535 R0 FMAX M91 137 ; 138 ;--------------------------------------------- 139 L Z+0 R0 FMAX M91 140 L X+260 Y+535 R0 FMAX M91 141 L M30 142 * - ----------------------------------------- 143 * - LBL1 - 12 144 LBL 1 145 M3 146 L X-16 Y+42 R0 FMAX M99 147 LBL 0 148 * - LBL2 - 8-PRZELOTOWY 149 LBL 2 150 M3 151 L X-16 Y+13 R0 FMAX M99 152 LBL 0 153 * - LBL3 - 8 154 LBL 3 155 M3 156 L X-34 Y+13 R0 FMAX M99 157 LBL 0 158 END PGM PLYTA-DOLNA-BOK-1 MM <file_sep>/websites/www2/index.html <!DOCTYPE HTML> <html lang="pl"/> <head> <meta charset="utf-8" /> <title>STRONA O MNIE</title> <meta name="description" content="Przed Toba strona o mnie"/> <meta name="keywords" content="cv, omnie, zyciorys"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <meta name="author" content="<NAME>"/> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div id="container"> <div id="logo"> Poznaj mnie :) </div> <div id="menu"> <div class="option">Strona główna</div> <div class="option">Szkoła</div> <div class="option">Distribution</div> <div class="option">Instalacja </div> <div class="option">Mikro </div> <div class="option">O projekcie</div> <div style="clear:both"></div> </div> <div id="topbar"> <div id="topbarL"> <img src="mikro.jpeg"/> </div> <div id="topbarR"> <span class="bigtitle">O projekcie słów kilka...</span> <div style="height: 15px;"></div> Siema siema sieeemaaa !!! </div> <div style="clear:both;"></div> </div> <div id="sidebar"> <div class="optionL">Strona główna</div> <div class="optionL">Szkoła</div> <div class="optionL">Distribution</div> <div class="optionL">Instalacja </div> <div class="optionL">Mikro </div> <div class="optionL">O projekcie</div> </div> <div id="content"> <span class="bigtitle">Coś tam po angielsku...</span> <div class="dottedline"></div> <div style="height: 15px;"></div> "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" </div> <div id="footer"> <NAME> - Strona w sieci od 2015r. &copy; Wszelkie prawa zastrzeżone </div> </div> </body> </html><file_sep>/cnc programming/Heidenhain/JF/AD/N021.00/POMIAR.H 0 BEGIN PGM POMIAR MM 1 BLK FORM 0.1 Z X-100 Y-100 Z-35 2 BLK FORM 0.2 X+100 Y+100 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ;--------------------------------------------- 6 ; 7 TOOL CALL 30 Z S50 8 TCH PROBE 411 PKT.BAZ.PROST.ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q323=+62 ;DLUG. 1-SZEJ STRONY ~ Q324=+30 ;DLUG. 2-GIEJ STRONY ~ Q261=-3.5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+1 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA 9 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 10 ; 11 ;--------------------------------------------- / 12 L Z-5 R0 FMAX M91 / 13 L X+260 Y+535 R0 FMAX M91 / 14 L M30 15 STOP 16 CALL PGM TNC:\5675-AD\N021.00\PLAN.H 17 * - ----------------------------------------- 18 ; 19 END PGM POMIAR MM <file_sep>/cnc programming/Heidenhain/KS-N100-02-2.H 0 BEGIN PGM KS-N100-02-2 MM 1 BLK FORM 0.1 Z X-60 Y-60 Z-60 2 BLK FORM 0.2 X+60 Y+60 Z+0 3 ; 4 ;=================================== 5 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 6 STOP 7 TOOL CALL 30 Z S50 8 TOOL DEF 26 9 ; 10 TCH PROBE 412 PKT.BAZ.OKRAG WEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+47 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-5 ;WYSOKOSC POMIARU ~ Q320=+2 ;BEZPIECZNA WYSOKOSC ~ Q260=+50 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=-36 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 11 ; 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 ;=================================== 14 ; 15 * - NAWIERT 16 TOOL CALL 26 Z S1000 F100 17 TOOL DEF 3 18 M13 19 CYCL DEF 240 NAKIELKOWANIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q343=+0 ;WYBOR SRED./GLEBOK. ~ Q201=-3.3 ;GLEBOKOSC ~ Q344=-10 ;SREDNICA ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 20 CALL LBL 1 21 ; 22 CYCL DEF 240 NAKIELKOWANIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q343=+0 ;WYBOR SRED./GLEBOK. ~ Q201=-4.9 ;GLEBOKOSC ~ Q344=-10 ;SREDNICA ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 23 CALL LBL 2 24 CYCL DEF 240 NAKIELKOWANIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q343=+0 ;WYBOR SRED./GLEBOK. ~ Q201=-5.55 ;GLEBOKOSC ~ Q344=-10 ;SREDNICA ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 25 CALL LBL 3 26 M5 M9 27 ; / 28 STOP 29 * - W6.3 30 TOOL CALL 3 Z S1300 F120 31 TOOL DEF 27 32 M3 M7 33 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-19 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 34 CALL LBL 1 35 M5 M9 36 ; 37 * - EG M6 38 TOOL CALL 27 Z S150 39 TOOL DEF 7 40 M13 41 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-16.5 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 42 CALL LBL 1 43 ; 44 * - W3.3 45 TOOL CALL 7 Z S2450 F120 46 TOOL DEF 22 47 M3 M7 48 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 49 CALL LBL 2 50 M5 M9 51 ; 52 * - M4 53 TOOL CALL 22 Z S100 54 TOOL DEF 23 55 M13 56 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-15 ;GLEBOKOSC GWINTU ~ Q239=+0.7 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 57 CALL LBL 2 58 ; 59 * - FI11 60 TOOL CALL 23 Z S7988 F1500 61 TOOL DEF 30 62 M7 M3 63 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.8 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 64 CALL LBL 3 65 M5 M9 66 ; 67 L Z+0 R0 FMAX M91 68 L X+260 Y+535 R0 FMAX M91 69 ; 70 L M30 71 ; 72 * - LBL1 M6 73 LBL 1 ;M6 74 L X+0 Y+36 FMAX M99 75 L X+0 Y-36 FMAX M99 76 LBL 0 77 ; 78 * - LBL2 M4 79 LBL 2 ;M4 80 L X+28.5 Y+0 FMAX M99 81 LBL 0 82 ; 83 * - LBL3 6.6/11 84 LBL 3 85 M3 86 L X+34.4 Y+25 R0 FMAX M99 87 L X-13.1 Y+40.4 R0 FMAX M99 88 L X-42.5 Y+0 R0 FMAX M99 89 L X-13.1 Y-40.4 R0 FMAX M99 90 L X+34.4 Y-25 R0 FMAX M99 91 LBL 0 92 END PGM KS-N100-02-2 MM <file_sep>/cnc programming/Heidenhain/JF/KS/KS-N100.02/ks_n100_02_obw.h 0 BEGIN PGM ks_n100_02_obw MM 1 ;MASTERCAM - X9 2 ;MCX FILE -~ D:\0_ZLECENIA\KSN10002\MCX\DYSTANS_KS_N100_02_WIERCENIE_OD_WALCOWEJ_AVIA.M~ CX-9 3 ;POST - MPPOSTABILITY_AVIA_VMC_800_4X.PST 4 ;PROGRAM - ks_N100_02_obw.h 5 ;DATE - 2017.09.08 6 ;TIME - 12:06 PM 7 ;1 - FREZ PLASKI 16 - D16.000mm 8 ;2 - FREZ PLASKI 8 - D8.000mm 9 ;3 - NAWIERTAK - D6.000mm 10 ;4 - 6.0 WIERTLO HSS - D6.000mm 11 ;5 - 7.2 WIERTLO VHM - D7.200mm 12 ;6 - 8.00-0.75 GWINTOWNIK - D8.000mm 13 ;7 - G1/4" GWINTOWNIK - D13.158mm 14 BLK FORM 0.1 Z X-54.5 Y-54.5 Z+0 15 BLK FORM 0.2 X+54.5 Y+54.5 Z+50.5 16 M129 17 L Z-15 R0 FMAX M91 18 L X+273 Y+529 R0 FMAX M91 19 PLANE RESET TURN FMAX 20 ; / 21 STOP 22 * - FREZ PLASKI 16 23 TOOL CALL 1 Z S3980 24 TOOL DEF 27 25 ;FREZ PLASKI 16 TOOL - 1 DIA. OFF. - 1 LEN. - 1 DIA. - 16. 26 ;HOLDER - DEFAULT HOLDER 27 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 28 CYCL DEF 32.0 TOLERANCJA 29 CYCL DEF 32.1 T0.003 30 CYCL DEF 32.2 HSC-MODE:0 31 L A+90 FMAX 32 M3 33 L X+31.5 Y-26 Z+100 FMAX M8 34 L Z+53 FMAX 35 L Z+52 F250 36 CC X+31.5 Y-28 37 CP IPA-360 Z+51.341 DR- F800 38 CC X+31.5 Y-28 39 CP IPA-360 Z+50.683 DR- 40 CC X+31.5 Y-28 41 CP IPA-360 Z+50.024 DR- 42 CC X+31.5 Y-28 43 CP IPA-360 Z+49.366 DR- 44 CC X+31.5 Y-28 45 CP IPA-360 Z+48.707 DR- 46 CC X+31.5 Y-28 47 CP IPA-360 Z+48.049 DR- 48 CC X+31.5 Y-28 49 CP IPA-360 Z+47.39 DR- 50 CC X+31.5 Y-28 51 CP IPA-360 Z+46.731 DR- 52 CC X+31.5 Y-28 53 CP IPA-360 Z+46.073 DR- 54 CC X+31.5 Y-28 55 CP IPA-360 Z+45.414 DR- 56 CC X+31.5 Y-28 57 CP IPA-360 Z+44.756 DR- 58 CC X+31.5 Y-28 59 CP IPA-360 Z+44.097 DR- 60 CC X+31.5 Y-28 61 CP IPA-360 Z+43.439 DR- 62 CC X+31.5 Y-28 63 CP IPA-360 Z+42.78 DR- 64 CC X+31.5 Y-28 65 CP IPA-360 Z+42.121 DR- 66 CC X+31.5 Y-28 67 CP IPA-360 Z+41.463 DR- 68 CC X+31.5 Y-28 69 CP IPA-360 Z+40.804 DR- 70 CC X+31.5 Y-28 71 CP IPA-360 Z+40.146 DR- 72 CC X+31.5 Y-28 73 CP IPA-360 Z+39.487 DR- 74 CC X+31.5 Y-28 75 CP IPA-266.245 Z+39 DR- 76 CC X+31.5 Y-28 77 C X+31.5 Y-26 DR- 78 CC X+31.5 Y-28 79 C X+29.504 Y-28.131 DR- 80 L Z+53 F3400 81 L Z+100 FMAX 82 CYCL DEF 32.0 TOLERANCJA 83 CYCL DEF 32.1 84 M9 85 M5 86 L Z-15 R0 FMAX M91 M9 87 L X+273 Y+529 R0 FMAX M91 88 M1 89 ; 90 * - FREZ PLASKI 8 91 TOOL CALL 27 Z S8000 / 92 STOP 93 TOOL DEF 1 94 ;FREZ PLASKI 8 TOOL - 2 DIA. OFF. - 2 LEN. - 2 DIA. - 8. 95 ;HOLDER - DEFAULT HOLDER 96 CYCL DEF 32.0 TOLERANCJA 97 CYCL DEF 32.1 T0.003 98 CYCL DEF 32.2 HSC-MODE:0 99 L A+160 FMAX 100 M3 101 L X+16.5 Y+0 Z+100 FMAX M8 102 L Z+57 FMAX 103 L Z+54 F250 104 CC X+15.5 Y+0 105 C X+16.5 Y+0 DR+ F1920 106 L Z+57 F3400 107 L Z+100 FMAX 108 CYCL DEF 32.0 TOLERANCJA 109 CYCL DEF 32.1 110 M9 111 M5 112 L Z-15 R0 FMAX M91 M9 113 L X+273 Y+529 R0 FMAX M91 114 M1 115 ; 116 * - FREZ PLASKI 16 117 TOOL CALL 1 Z S3980 / 118 STOP 119 TOOL DEF 9 120 ;FREZ PLASKI 16 TOOL - 1 DIA. OFF. - 1 LEN. - 1 DIA. - 16. 121 ;HOLDER - DEFAULT HOLDER 122 CYCL DEF 32.0 TOLERANCJA 123 CYCL DEF 32.1 T0.003 124 CYCL DEF 32.2 HSC-MODE:0 125 L A+270 FMAX 126 M3 127 L X+31.5 Y+26 Z+100 FMAX M8 128 L Z+53 FMAX 129 L Z+52 F250 130 CC X+31.5 Y+28 131 CP IPA-360 Z+51.341 DR- F800 132 CC X+31.5 Y+28 133 CP IPA-360 Z+50.683 DR- 134 CC X+31.5 Y+28 135 CP IPA-360 Z+50.024 DR- 136 CC X+31.5 Y+28 137 CP IPA-360 Z+49.366 DR- 138 CC X+31.5 Y+28 139 CP IPA-360 Z+48.707 DR- 140 CC X+31.5 Y+28 141 CP IPA-360 Z+48.049 DR- 142 CC X+31.5 Y+28 143 CP IPA-360 Z+47.39 DR- 144 CC X+31.5 Y+28 145 CP IPA-360 Z+46.731 DR- 146 CC X+31.5 Y+28 147 CP IPA-360 Z+46.073 DR- 148 CC X+31.5 Y+28 149 CP IPA-360 Z+45.414 DR- 150 CC X+31.5 Y+28 151 CP IPA-360 Z+44.756 DR- 152 CC X+31.5 Y+28 153 CP IPA-360 Z+44.097 DR- 154 CC X+31.5 Y+28 155 CP IPA-360 Z+43.439 DR- 156 CC X+31.5 Y+28 157 CP IPA-360 Z+42.78 DR- 158 CC X+31.5 Y+28 159 CP IPA-360 Z+42.121 DR- 160 CC X+31.5 Y+28 161 CP IPA-360 Z+41.463 DR- 162 CC X+31.5 Y+28 163 CP IPA-360 Z+40.804 DR- 164 CC X+31.5 Y+28 165 CP IPA-360 Z+40.146 DR- 166 CC X+31.5 Y+28 167 CP IPA-360 Z+39.487 DR- 168 CC X+31.5 Y+28 169 CP IPA-266.245 Z+39 DR- 170 CC X+31.5 Y+28 171 C X+31.5 Y+26 DR- 172 CC X+31.5 Y+28 173 C X+33.496 Y+28.131 DR- 174 L Z+53 F3400 175 L Z+100 FMAX 176 CYCL DEF 32.0 TOLERANCJA 177 CYCL DEF 32.1 178 M9 179 M5 180 L Z-15 R0 FMAX M91 M9 181 L X+273 Y+529 R0 FMAX M91 182 M1 183 ; 184 * - NAWIERTAK 185 TOOL CALL 9 Z S1000 / 186 STOP 187 TOOL DEF 19 188 ;NAWIERTAK TOOL - 3 DIA. OFF. - 3 LEN. - 3 DIA. - 6. 189 ;HOLDER - DEFAULT HOLDER 190 L A+90 FMAX 191 M3 192 L X+31.5 Y-26 Z+100 FMAX M8 193 L Z+70 FMAX 194 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206=+100 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+39 ;WSPOLRZEDNE POWIERZ. ~ Q204=+31 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 195 L Y-26 Z+70 FMAX M99 196 L Z+100 FMAX 197 L Z-15 R0 FMAX M91 198 L A+160 FMAX 199 L X+15.5 Y+0 Z+100 FMAX 200 L Z+70 FMAX 201 L Z+57 FMAX 202 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2.5 ;GLEBOKOSC ~ Q206=+100 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+55 ;WSPOLRZEDNE POWIERZ. ~ Q204=+2 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 203 L FMAX M99 204 L Z+70 FMAX 205 L Z+100 FMAX 206 L Z-15 R0 FMAX M91 207 L A+270 FMAX 208 L X+31.5 Y+26 Z+100 FMAX 209 L Z+70 FMAX 210 L Z+70 FMAX 211 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206=+100 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+39 ;WSPOLRZEDNE POWIERZ. ~ Q204=+31 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 212 L Y+26 Z+70 FMAX M99 213 L Z+100 FMAX 214 M9 215 M5 216 L Z-15 R0 FMAX M91 M9 217 L X+273 Y+529 R0 FMAX M91 218 M1 219 ; 220 * - 6.0 WIERTLO HSS 221 TOOL CALL 19 Z S1000 / 222 STOP 223 TOOL DEF 7 224 ;6.0 WIERTLO HSS TOOL - 4 DIA. OFF. - 4 LEN. - 4 DIA. - 6. 225 ;HOLDER - DEFAULT HOLDER 226 L A+90 FMAX 227 M3 228 L X+31.5 Y-26 Z+100 FMAX M8 229 L Z+70 FMAX 230 L Z+70 FMAX 231 CYCL DEF 200 WIERCENIE ~ Q200=+3 ;BEZPIECZNA WYSOKOSC ~ Q201=-35.303 ;GLEBOKOSC ~ Q206=+100 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0.5 ;PRZER. CZAS.NA GORZE ~ Q203=+39 ;WSPOLRZEDNE POWIERZ. ~ Q204=+31 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 232 L Y-26 Z+70 FMAX M99 233 L Z+100 FMAX 234 L Z-15 R0 FMAX M91 235 L A+160 FMAX 236 L X+15.5 Y+0 Z+100 FMAX 237 L Z+70 FMAX 238 L Z+70 FMAX 239 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-56.803 ;GLEBOKOSC ~ Q206=+100 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0.5 ;PRZER. CZAS.NA GORZE ~ Q203=+55 ;WSPOLRZEDNE POWIERZ. ~ Q204=+15 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 240 L FMAX M99 241 L Z+100 FMAX 242 L Z-15 R0 FMAX M91 243 L A+270 FMAX 244 L X+31.5 Y+26 Z+100 FMAX 245 L Z+70 FMAX 246 L Z+70 FMAX 247 CYCL DEF 200 WIERCENIE ~ Q200=+3 ;BEZPIECZNA WYSOKOSC ~ Q201=-32.803 ;GLEBOKOSC ~ Q206=+100 ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0.5 ;PRZER. CZAS.NA GORZE ~ Q203=+39 ;WSPOLRZEDNE POWIERZ. ~ Q204=+31 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 248 L Y+26 Z+70 FMAX M99 249 L Z+100 FMAX 250 M9 251 M5 252 L Z-15 R0 FMAX M91 M9 253 L X+273 Y+529 R0 FMAX M91 254 M1 255 ; 256 * - 7.2 WIERTLO VHM 257 TOOL CALL 7 Z S4417 / 258 STOP 259 TOOL DEF 27 260 ;7.2 WIERTLO VHM TOOL - 5 DIA. OFF. - 5 LEN. - 5 DIA. - 7.2 261 ;HOLDER - DEFAULT HOLDER 262 L A+160 FMAX 263 M3 264 L X+15.5 Y+0 Z+100 FMAX M7 265 L Z+70 FMAX 266 L Z+70 FMAX 267 CYCL DEF 200 WIERCENIE ~ Q200=+3 ;BEZPIECZNA WYSOKOSC ~ Q201=-16.5 ;GLEBOKOSC ~ Q206=+813 ;WARTOSC POSUWU WGL. ~ Q202=+16.5 ;GLEBOKOSC DOSUWU ~ Q210=+0.5 ;PRZER. CZAS.NA GORZE ~ Q203=+54.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+31 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE 268 L FMAX M99 269 L Z+100 FMAX 270 M9 271 M5 272 L Z-15 R0 FMAX M91 M9 273 L X+273 Y+529 R0 FMAX M91 274 M1 275 ; 276 * - FREZ PLASKI 8 277 TOOL CALL 27 Z S8000 / 278 STOP 279 TOOL DEF 20 280 ;FREZ PLASKI 8 TOOL - 2 DIA. OFF. - 2 LEN. - 2 DIA. - 8. 281 ;HOLDER - DEFAULT HOLDER 282 CYCL DEF 32.0 TOLERANCJA 283 CYCL DEF 32.1 T0.003 284 CYCL DEF 32.2 HSC-MODE:0 285 L A+90 FMAX 286 M3 287 L X+33.4 Y-28 Z+100 FMAX M8 288 L Z+42 FMAX 289 L Z+39 F360 290 CC X+31.5 Y-28 291 CP IPA+360 Z+38.374 DR+ F1920 292 CC X+31.5 Y-28 293 CP IPA+360 Z+37.749 DR+ 294 CC X+31.5 Y-28 295 CP IPA+360 Z+37.123 DR+ 296 CC X+31.5 Y-28 297 CP IPA+360 Z+36.497 DR+ 298 CC X+31.5 Y-28 299 CP IPA+360 Z+35.872 DR+ 300 CC X+31.5 Y-28 301 CP IPA+360 Z+35.246 DR+ 302 CC X+31.5 Y-28 303 CP IPA+360 Z+34.62 DR+ 304 CC X+31.5 Y-28 305 CP IPA+360 Z+33.995 DR+ 306 CC X+31.5 Y-28 307 CP IPA+360 Z+33.369 DR+ 308 CC X+31.5 Y-28 309 CP IPA+360 Z+32.744 DR+ 310 CC X+31.5 Y-28 311 CP IPA+360 Z+32.118 DR+ 312 CC X+31.5 Y-28 313 CP IPA+360 Z+31.492 DR+ 314 CC X+31.5 Y-28 315 CP IPA+360 Z+30.867 DR+ 316 CC X+31.5 Y-28 317 CP IPA+360 Z+30.241 DR+ 318 CC X+31.5 Y-28 319 CP IPA+360 Z+29.615 DR+ 320 CC X+31.5 Y-28 321 CP IPA+360 Z+28.99 DR+ 322 CC X+31.5 Y-28 323 CP IPA+360 Z+28.364 DR+ 324 CC X+31.5 Y-28 325 CP IPA+360 Z+27.738 DR+ 326 CC X+31.5 Y-28 327 CP IPA+360 Z+27.113 DR+ 328 CC X+31.5 Y-28 329 CP IPA+360 Z+26.487 DR+ 330 CC X+31.5 Y-28 331 CP IPA+360 Z+25.861 DR+ 332 CC X+31.5 Y-28 333 CP IPA+360 Z+25.236 DR+ 334 CC X+31.5 Y-28 335 CP IPA+360 Z+24.61 DR+ 336 CC X+31.5 Y-28 337 CP IPA+360 Z+23.984 DR+ 338 CC X+31.5 Y-28 339 CP IPA+360 Z+23.359 DR+ 340 CC X+31.5 Y-28 341 CP IPA+360 Z+22.733 DR+ 342 CC X+31.5 Y-28 343 CP IPA+360 Z+22.108 DR+ 344 CC X+31.5 Y-28 345 CP IPA+360 Z+21.482 DR+ 346 CC X+31.5 Y-28 347 CP IPA+360 Z+20.856 DR+ 348 CC X+31.5 Y-28 349 CP IPA+360 Z+20.231 DR+ 350 CC X+31.5 Y-28 351 CP IPA+360 Z+19.605 DR+ 352 CC X+31.5 Y-28 353 CP IPA+360 Z+18.979 DR+ 354 CC X+31.5 Y-28 355 CP IPA+360 Z+18.354 DR+ 356 CC X+31.5 Y-28 357 CP IPA+360 Z+17.728 DR+ 358 CC X+31.5 Y-28 359 CP IPA+131.18 Z+17.5 DR+ 360 CC X+31.5 Y-28 361 C X+33.4 Y-28 DR+ 362 CC X+31.5 Y-28 363 C X+30.249 Y-26.57 DR+ 364 L Z+42 F3400 365 L Z+100 FMAX 366 CYCL DEF 32.0 TOLERANCJA 367 CYCL DEF 32.1 368 L Z-15 R0 FMAX M91 369 CYCL DEF 32.0 TOLERANCJA 370 CYCL DEF 32.1 T0.003 371 CYCL DEF 32.2 HSC-MODE:0 372 L A+270 FMAX 373 L X+31.5 Y+29.9 Z+100 FMAX 374 L Z+42 FMAX 375 L Z+39 F360 376 CC X+31.5 Y+28 377 CP IPA+360 Z+38.374 DR+ F1920 378 CC X+31.5 Y+28 379 CP IPA+360 Z+37.749 DR+ 380 CC X+31.5 Y+28 381 CP IPA+360 Z+37.123 DR+ 382 CC X+31.5 Y+28 383 CP IPA+360 Z+36.497 DR+ 384 CC X+31.5 Y+28 385 CP IPA+360 Z+35.872 DR+ 386 CC X+31.5 Y+28 387 CP IPA+360 Z+35.246 DR+ 388 CC X+31.5 Y+28 389 CP IPA+360 Z+34.62 DR+ 390 CC X+31.5 Y+28 391 CP IPA+360 Z+33.995 DR+ 392 CC X+31.5 Y+28 393 CP IPA+360 Z+33.369 DR+ 394 CC X+31.5 Y+28 395 CP IPA+360 Z+32.744 DR+ 396 CC X+31.5 Y+28 397 CP IPA+360 Z+32.118 DR+ 398 CC X+31.5 Y+28 399 CP IPA+360 Z+31.492 DR+ 400 CC X+31.5 Y+28 401 CP IPA+360 Z+30.867 DR+ 402 CC X+31.5 Y+28 403 CP IPA+360 Z+30.241 DR+ 404 CC X+31.5 Y+28 405 CP IPA+360 Z+29.615 DR+ 406 CC X+31.5 Y+28 407 CP IPA+360 Z+28.99 DR+ 408 CC X+31.5 Y+28 409 CP IPA+360 Z+28.364 DR+ 410 CC X+31.5 Y+28 411 CP IPA+360 Z+27.738 DR+ 412 CC X+31.5 Y+28 413 CP IPA+360 Z+27.113 DR+ 414 CC X+31.5 Y+28 415 CP IPA+360 Z+26.487 DR+ 416 CC X+31.5 Y+28 417 CP IPA+360 Z+25.861 DR+ 418 CC X+31.5 Y+28 419 CP IPA+360 Z+25.236 DR+ 420 CC X+31.5 Y+28 421 CP IPA+360 Z+24.61 DR+ 422 CC X+31.5 Y+28 423 CP IPA+360 Z+23.984 DR+ 424 CC X+31.5 Y+28 425 CP IPA+360 Z+23.359 DR+ 426 CC X+31.5 Y+28 427 CP IPA+360 Z+22.733 DR+ 428 CC X+31.5 Y+28 429 CP IPA+360 Z+22.108 DR+ 430 CC X+31.5 Y+28 431 CP IPA+360 Z+21.482 DR+ 432 CC X+31.5 Y+28 433 CP IPA+360 Z+20.856 DR+ 434 CC X+31.5 Y+28 435 CP IPA+360 Z+20.231 DR+ 436 CC X+31.5 Y+28 437 CP IPA+360 Z+19.605 DR+ 438 CC X+31.5 Y+28 439 CP IPA+360 Z+18.979 DR+ 440 CC X+31.5 Y+28 441 CP IPA+360 Z+18.354 DR+ 442 CC X+31.5 Y+28 443 CP IPA+360 Z+17.728 DR+ 444 CC X+31.5 Y+28 445 CP IPA+131.18 Z+17.5 DR+ 446 CC X+31.5 Y+28 447 C X+31.5 Y+29.9 DR+ 448 CC X+31.5 Y+28 449 C X+30.07 Y+26.749 DR+ 450 L Z+42 F3400 451 L Z+100 FMAX 452 CYCL DEF 32.0 TOLERANCJA 453 CYCL DEF 32.1 454 M9 455 M5 456 L Z-15 R0 FMAX M91 M9 457 L X+273 Y+529 R0 FMAX M91 458 M1 459 ; 460 * - 8.00-0.75 GWINTOWNIK 461 TOOL CALL 20 Z S120 / 462 STOP 463 TOOL DEF 12 464 ;8.00-0.75 GWINTOWNIK TOOL - 6 DIA. OFF. - 6 LEN. - 6 DIA. - 8. 465 ;HOLDER - DEFAULT HOLDER 466 L A+160 FMAX 467 M3 468 L X+15.5 Y+0 Z+100 FMAX M8 469 L Z+70 FMAX 470 L Z+70 FMAX 471 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-14 ;GLEBOKOSC GWINTU ~ Q239=+0.75 ;SKOK GWINTU ~ Q203=+55 ;WSPOLRZEDNE POWIERZ. ~ Q204=+15 ;2-GA BEZPIECZNA WYS. 472 L FMAX M99 473 L Z+100 FMAX 474 M9 475 M5 476 L Z-15 R0 FMAX M91 M9 477 L X+273 Y+529 R0 FMAX M91 478 M1 479 ; 480 * - G1/4" GWINTOWNIK 481 TOOL CALL 12 Z S150 / 482 STOP 483 TOOL DEF 9 484 ;G1/4" GWINTOWNIK TOOL - 7 DIA. OFF. - 7 LEN. - 7 DIA. - 13.158 485 ;HOLDER - DEFAULT HOLDER 486 L A+90 FMAX 487 M3 488 L X+31.5 Y-28 Z+100 FMAX M8 489 L Z+70 FMAX 490 L Z+70 FMAX 491 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+6.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-27.5 ;GLEBOKOSC GWINTU ~ Q239=+1.337 ;SKOK GWINTU ~ Q203=+45.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+24.5 ;2-GA BEZPIECZNA WYS. 492 L Y-28 Z+70 FMAX M99 493 L Z+100 FMAX 494 L Z-15 R0 FMAX M91 495 L A+270 FMAX 496 L X+31.5 Y+28 Z+100 FMAX 497 L Z+70 FMAX 498 L Z+70 FMAX 499 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+6.5 ;BEZPIECZNA WYSOKOSC ~ Q201=-27.5 ;GLEBOKOSC GWINTU ~ Q239=+1.337 ;SKOK GWINTU ~ Q203=+45.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+24.5 ;2-GA BEZPIECZNA WYS. 500 L Y+28 Z+70 FMAX M99 501 L Z+100 FMAX 502 M9 503 M5 / 504 L Z-15 R0 FMAX M91 / 505 L X+500 Y+529 R0 FMAX M91 / 506 L A+0 FMAX M91 507 ; / 508 STOP 509 L Z-15 R0 FMAX M91 510 L X+0 Y+6.5 R0 FMAX 511 L A+0 FMAX 512 ; 513 TOOL CALL 9 Z S50 514 TOOL DEF 1 515 ; 516 M2 517 END PGM ks_n100_02_obw MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/TAKETAM.H 0 BEGIN PGM TAKETAM MM 1 BLK FORM 0.1 Z X-100 Y-100 Z-25 2 BLK FORM 0.2 X+100 Y+100 Z+5 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 L X+0 Y+0 R0 FMAX 6 ;--------------------------------------------- 7 ; 8 ; 9 STOP 10 TOOL CALL 8 Z S6000 F1000 DL+2.5 11 L X+0 Y+0 R0 FMAX 12 M8 M3 13 ; 14 Q1 = 53 15 Q2 = 53.2 16 Q3 = 0.5 17 ; 18 STOP 19 LBL 2 20 Q1 = Q1 - Q3 21 Q2 = Q2 - Q3 22 CYCL DEF 215 WYSEP.KOL.NA GOT. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.01 ;GLEBOKOSC ~ Q206=+3000 ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q216=+0 ;SRODEK W 1-SZEJ OSI ~ Q217=+0 ;SRODEK W 2-SZEJ OSI ~ Q222=+Q2 ;SREDNICA WST.OBR.WYB ~ Q223=+Q1 ;SRED.WYBR.OBR.NA GOT 23 CYCL CALL 24 LBL 0 25 ; 26 CALL LBL 2 REP38 27 ; 28 ; 29 M5 M9 30 ; 31 ;--------------------------------------------- 32 L Z-5 R0 FMAX M91 33 L X+260 Y+535 R0 FMAX M91 34 L M30 35 * - ----------------------------------------- 36 * - LBL1 SRODEK 37 LBL 1 38 M3 39 L X+0 Y+0 R0 FMAX M99 40 LBL 0 41 END PGM TAKETAM MM <file_sep>/cnc programming/Heidenhain/DENKO-OTW-BOKI.H 0 BEGIN PGM DENKO-OTW-BOKI MM 1 CALL PGM TNC:\REF 2 CALL PGM TNC:\Z19 3 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+2 ;NR PKT BAZOWEGO 4 BLK FORM 0.1 Z X-60 Y-60 Z-50 5 BLK FORM 0.2 X+60 Y+60 Z+1 6 STOP 7 TOOL CALL 1 Z S50 8 TCH PROBE 409 PKT BAZ.SR.MOSTKA ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+40 ;SRODEK W 2-SZEJ OSI ~ Q311=+119 ;SZEROKOSC MOSTKA ~ Q272=+1 ;OS POMIAROWA ~ Q261=-45 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+100 ;BEZPIECZNA WYSOKOSC ~ Q305=+2 ;NR W TABELI ~ Q405=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT BAZOWY 9 TCH PROBE 419 PKT.BAZOW.POJED. OSI ~ Q263=+0 ;1.PKT POMIAROW 1.OSI ~ Q264=+0 ;1.PKT 2.OSI ~ Q261=-12 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+100 ;BEZPIECZNA WYSOKOSC ~ Q272=+2 ;OS POMIAROWA ~ Q267=+1 ;KIERUNEK RUCHU ~ Q305=+2 ;NR W TABELI ~ Q333=+0 ;PUNKT BAZOWY ~ Q303=+1 ;PRZEKAZ DANYCH POM. 10 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+2 ;NR PKT BAZOWEGO 11 STOP 12 * - NAW-8 13 TOOL CALL 8 Z S1500 F120 14 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+1 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 15 CALL LBL 1 16 CALL LBL 2 17 M5 M9 18 * - W-5-HSS 19 TOOL CALL 15 Z S1600 F120 20 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 21 CALL LBL 1 22 M5 M9 23 * - W-5.8-HSS 24 TOOL CALL 10 Z S1444 F120 25 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-13.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 26 CALL LBL 2 27 M5 M9 28 * - GW-M6 29 TOOL CALL 16 Z S800 30 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-16 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 31 CALL LBL 1 32 M5 M9 33 * - R-6 34 TOOL CALL 36 Z S150 F40 35 CYCL DEF 201 ROZWIERCANIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-12 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q208=+400 ;POSUW RUCHU POWROTN. ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 36 CALL LBL 2 37 M5 M9 38 CALL PGM TNC:\REF3 39 CALL PGM TNC:\Z19 40 M30 41 * - ************** 42 * - LBL 1 - M6 43 LBL 1 44 L X-13 Y+66.5 R0 FMAX M99 M13 45 L X+13 Y+66.5 R0 FMAX M99 M13 46 LBL 0 47 * - LBL 2 - 6H7 48 LBL 2 49 L X-13 Y+54 R0 FMAX M99 M13 50 L X+13 Y+54 R0 FMAX M99 M13 51 LBL 0 52 * - ************** 53 END PGM DENKO-OTW-BOKI MM <file_sep>/cnc programming/Heidenhain/JF/SD/DYSTANS/GABARYT.h 0 BEGIN PGM GABARYT MM 1 BLK FORM 0.1 Z X-65 Y-65 Z-35 2 BLK FORM 0.2 X+65 Y+65 Z+1 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; / 6 STOP 7 L X+0 Y+0 R0 FMAX 8 TOOL CALL 30 Z 9 TOOL DEF 27 10 ; 11 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+120 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-5 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+30 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 12 ; 13 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 14 ;--------------------------------------------- 15 ; / 16 STOP 17 * - PLAN ZGR 18 TOOL CALL 27 Z S11987 F4000 DL+0 19 TOOL DEF 27 20 M8 21 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+0 ;STRATEGIA ~ Q225=-60 ;PKT.STARTU 1SZEJ OSI ~ Q226=-60 ;PKT.STARTU 2GIEJ OSI ~ Q227=+1 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0.15 ;PUNKT KONCOWY 3. OSI ~ Q218=+120 ;DLUG. 1-SZEJ STRONY ~ Q219=+120 ;DLUG. 2-GIEJ STRONY ~ Q202=+1 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1.5 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385=+500 ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 22 CALL LBL 1 23 M5 M9 24 ; 25 * - PLAN WYK 26 TOOL CALL 27 Z S11987 F2000 DL+0 / 27 STOP 28 TOOL DEF 17 29 M8 30 CYCL DEF 232 FREZOW.PLANOWE ~ Q389=+2 ;STRATEGIA ~ Q225=-60 ;PKT.STARTU 1SZEJ OSI ~ Q226=-60 ;PKT.STARTU 2GIEJ OSI ~ Q227=+0.15 ;PKT.STARTU 3CIEJ OSI ~ Q386=+0 ;PUNKT KONCOWY 3. OSI ~ Q218=+120 ;DLUG. 1-SZEJ STRONY ~ Q219=+120 ;DLUG. 2-GIEJ STRONY ~ Q202=+0.15 ;MAX. GLEB. DOSUWU ~ Q369=+0 ;NADDATEK NA DNIE ~ Q370=+1 ;MAX. NAKLADANIE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q385=+500 ;POSUW OBR.WYKAN. ~ Q253= MAX ;PREDK. POS. ZAGLEB. ~ Q200=+5 ;BEZPIECZNA WYSOKOSC ~ Q357=+5 ;ODST. BEZP. Z BOKU ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 31 CALL LBL 1 32 M5 M9 33 ; / 34 STOP 35 * - FP 12 FI 119 ZGR 36 TOOL CALL 17 Z S5987 F1500 37 TOOL DEF 17 38 M8 39 CYCL DEF 257 CZOP OKRAGLY ~ Q223=+119.4 ;SRED.WYBR.OBR.NA GOT ~ Q222=+120 ;SREDNICA WST.OBR.WYB ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;<NAME> ~ Q201=-30 ;GLEBOKOSC ~ Q202=+10 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q376=-1 ;KAT POCZATKOWY 40 CALL LBL 1 41 M5 M9 42 ; / 43 STOP 44 * - FP 12 FI 119 WYK 45 TOOL CALL 17 Z S6987 F1500 46 TOOL DEF 9 47 M8 48 CYCL DEF 257 CZOP OKRAGLY ~ Q223=+119 ;SRED.WYBR.OBR.NA GOT ~ Q222=+120 ;SREDNICA WST.OBR.WYB ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-30 ;GLEBOKOSC ~ Q202=+6 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q376=-1 ;KAT POCZATKOWY 49 CALL LBL 1 50 M5 M9 51 ; 52 * - FAZA 119 53 TOOL CALL 9 Z S5987 F600 DR-3 / 54 STOP 55 TOOL DEF 0 56 M8 57 CYCL DEF 257 CZOP OKRAGLY ~ Q223=+119 ;SRED.WYBR.OBR.NA GOT ~ Q222=+120 ;SREDNICA WST.OBR.WYB ~ Q368=+0 ;NADDATEK NA STRONE ~ Q207= AUTO ;POSUW FREZOWANIA ~ Q351=+1 ;RODZAJ FREZOWANIA ~ Q201=-2 ;GLEBOKOSC ~ Q202=+5 ;GLEBOKOSC DOSUWU ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q370=+1 ;ZACHODZENIE TOROW ~ Q376=-1 ;KAT POCZATKOWY 58 CALL LBL 1 59 M5 M9 60 ; 61 ;--------------------------------------------- 62 L Z-5 R0 FMAX M91 63 L X+260 Y+535 R0 FMAX M91 64 L M30 65 * - ----------------------------------------- 66 * - LBL1 SRODEK 67 LBL 1 68 M3 69 L X+0 Y+0 R0 FMAX M99 70 LBL 0 71 END PGM GABARYT MM <file_sep>/cnc programming/Heidenhain/WAL-DYS-I-1STR.h 0 BEGIN PGM WAL-DYS-I-1STR MM 1 BLK FORM 0.1 Z X-49.5 Y-49.5 Z-70 2 BLK FORM 0.2 X+49.5 Y+49.5 Z+0 3 ;--------------------------------------------- 4 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 5 ; 6 L X+0 Y+0 R0 FMAX 7 TOOL CALL 30 Z 8 TOOL DEF 9 9 ; 10 TCH PROBE 413 PKT.BAZ.OKRAG ZEWN. ~ Q321=+0 ;SRODEK W 1-SZEJ OSI ~ Q322=+0 ;SRODEK W 2-SZEJ OSI ~ Q262=+99 ;SREDNICA NOMINALNA ~ Q325=+0 ;KAT POCZATKOWY ~ Q247=+90 ;KATOWY PRZYROST-KROK ~ Q261=-12 ;WYSOKOSC POMIARU ~ Q320=+10 ;BEZPIECZNA WYSOKOSC ~ Q260=+20 ;BEZPIECZNA WYSOKOSC ~ Q301=+0 ;ODJAZD NA BEZP.WYS. ~ Q305=+1 ;NR W TABELI ~ Q331=+0 ;PUNKT ODNIESIENIA ~ Q332=+0 ;PUNKT ODNIESIENIA ~ Q303=+1 ;PRZEKAZ DANYCH POM. ~ Q381=+0 ;PROBKOW. NA OSI TS ~ Q382=+0 ;1.WSPOL. DLA OSI TS ~ Q383=+0 ;2.WSPOLRZ.DLA OSI TS ~ Q384=+0 ;3. WSPOL. DLA OSI TS ~ Q333=+0 ;PUNKT ODNIESIENIA ~ Q423=+4 ;LICZBA PKT POMIAR. ~ Q365=+1 ;RODZAJ PRZEMIESZCZ. 11 ; 12 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 13 ;--------------------------------------------- 14 ; 15 * - NAW 8 16 TOOL CALL 9 Z S1200 F100 17 TOOL DEF 24 18 M8 19 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-3.05 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 20 CALL LBL 2 21 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-1.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 22 CALL LBL 1 23 M5 M9 24 ; 25 * - W-3 26 TOOL CALL 24 Z S2650 F100 27 TOOL DEF 2 28 M8 29 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-8 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 30 CALL LBL 1 31 M5 M9 32 ; 33 * - W-5 34 TOOL CALL 2 Z S1600 F120 35 TOOL DEF 28 36 M8 37 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-18 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 38 CALL LBL 2 39 M5 M9 40 ; 41 * - M6 42 TOOL CALL 28 Z S100 43 TOOL DEF 26 44 M8 45 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-19 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=-7.5 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 46 CALL LBL 2 47 M5 M9 48 ; 49 * - FAZ-16 50 TOOL CALL 26 Z S1200 F120 51 TOOL DEF 30 52 M8 53 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-0.1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+4 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=-3.9 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+1 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 54 CALL LBL 3 55 M5 M9 56 ; 57 ;--------------------------------------------- 58 L Z+0 R0 FMAX M91 / 59 L X+260 Y+535 R0 FMAX M91 60 L X+100 Y+365 R0 FMAX 61 L M30 62 * - ----------------------------------------- 63 * - LBL1 3 64 LBL 1 65 M3 66 L X-20 Y+0 R0 FMAX M99 67 LBL 0 68 * - LBL2 M6 69 LBL 2 70 M3 71 L X-34.4 Y+25 R0 FMAX M99 72 L X-34.4 Y-25 R0 FMAX M99 73 L X+42.5 Y+0 R0 FMAX M99 74 L X+13.1 Y-40.4 R0 FMAX M99 75 L X+13.1 Y+40.4 R0 FMAX M99 76 LBL 0 77 * - LBL3 8 78 LBL 3 79 M3 80 L X+0 Y+11 R0 FMAX M99 81 L X+0 Y-11 R0 FMAX M99 82 LBL 0 83 END PGM WAL-DYS-I-1STR MM <file_sep>/cnc programming/Heidenhain/JF/_INNE/DYSTANS-PODZIELNICA.H 0 BEGIN PGM DYSTANS-PODZIELNICA MM 1 BLK FORM 0.1 Z X-60 Y-34 Z-119 2 BLK FORM 0.2 X+60 Y+0 Z+0 3 ;--------------------------------------------- 4 ; 5 ; 6 CYCL DEF 247 USTAWIENIE PKT.BAZ ~ Q339=+1 ;NR PKT BAZOWEGO 7 CYCL DEF 7.0 PUNKT BAZOWY 8 CYCL DEF 7.1 IZ+0 9 ;--------------------------------------------- 10 ; 11 L A-45 FMAX 12 CALL LBL 2 13 ; 14 L A+45 FMAX 15 CALL LBL 3 16 ; 17 TOOL CALL 9 18 L X-44.66 Y+6.5 FMAX 19 L A+0 FMAX 20 M30 21 ; 22 LBL 2 23 * - NAW 24 TOOL CALL 9 Z S1111 F111 25 TOOL DEF 21 26 M8 27 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 28 CALL LBL 1 29 M5 M9 30 ; 31 * - W 8 32 TOOL CALL 17 Z S1111 F111 33 TOOL DEF 27 34 M8 35 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-35 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 36 CALL LBL 1 37 M5 M9 38 ; 39 * - FI 11 FP8 40 TOOL CALL 27 Z S9987 F500 41 TOOL DEF 9 42 M8 43 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 44 CALL LBL 1 45 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.2 ;GLEBOKOSC DOSUWU ~ Q203=-1 ;WSPOLRZEDNE POWIERZ. ~ Q204=+60 ;2-GA BEZPIECZNA WYS. ~ Q335=+9 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 46 CALL LBL 1 47 M5 M9 48 ; 49 * - GW M10X1 50 TOOL CALL 18 Z S200 51 TOOL DEF 27 52 M8 53 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-13.5 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=-1 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 54 CALL LBL 1 55 M5 M9 56 ; 57 LBL 0 58 ; 59 LBL 3 60 * - NAW 61 TOOL CALL 9 Z S1111 F111 62 TOOL DEF 21 63 M8 64 CYCL DEF 200 WIERCENIE ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-2 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+2 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 65 CALL LBL 1 66 M5 M9 67 ; 68 * - W 8 69 TOOL CALL 17 Z S1111 F111 70 TOOL DEF 27 71 M8 72 CYCL DEF 200 WIERCENIE ~ Q200=+2 ;BEZPIECZNA WYSOKOSC ~ Q201=-67 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q202=+3 ;GLEBOKOSC DOSUWU ~ Q210=+0 ;PRZER. CZAS.NA GORZE ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q211=+0 ;PRZERWA CZAS. DNIE ~ Q395=+0 ;REFERENCJA GLEB. 73 CALL LBL 1 74 M5 M9 75 ; 76 * - FI 11 FP8 77 TOOL CALL 27 Z S9987 F500 78 TOOL DEF 9 79 M8 80 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-1 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.5 ;GLEBOKOSC DOSUWU ~ Q203=+0 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. ~ Q335=+11 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 81 CALL LBL 1 82 CYCL DEF 208 SPIRALNE FREZ. OTW. ~ Q200=+1 ;BEZPIECZNA WYSOKOSC ~ Q201=-15.5 ;GLEBOKOSC ~ Q206= AUTO ;WARTOSC POSUWU WGL. ~ Q334=+0.2 ;GLEBOKOSC DOSUWU ~ Q203=-1 ;WSPOLRZEDNE POWIERZ. ~ Q204=+60 ;2-GA BEZPIECZNA WYS. ~ Q335=+9 ;SREDNICA NOMINALNA ~ Q342=+0 ;WYW.WSTEP. SREDNICA ~ Q351=+1 ;<NAME> 83 CALL LBL 1 84 M5 M9 85 ; 86 * - GW M10X1 87 TOOL CALL 18 Z S200 88 TOOL DEF 27 89 M8 90 CYCL DEF 207 GWINTOWANIE GS ~ Q200=+4 ;BEZPIECZNA WYSOKOSC ~ Q201=-13.5 ;GLEBOKOSC GWINTU ~ Q239=+1 ;SKOK GWINTU ~ Q203=-1 ;WSPOLRZEDNE POWIERZ. ~ Q204=+50 ;2-GA BEZPIECZNA WYS. 91 CALL LBL 1 92 M5 M9 93 ; 94 LBL 0 95 ; 96 ;--------------------------------------------- 97 L Z-5 R0 FMAX M91 98 L X+260 Y+535 R0 FMAX M91 99 L M30 100 * - ----------------------------------------- 101 * - LBL1 O 102 LBL 1 103 M3 104 L X+0 Y+0 R0 FMAX M99 105 LBL 0 106 END PGM DYSTANS-PODZIELNICA MM
5c66cd5f93e8a7c6cc9be5e2b29c7a12400fda5d
[ "Markdown", "C", "C++", "HTML" ]
163
C
janforys/Miscellaneous
d2040a8c59bb7d4f8133c1b78146d579b1aaea6c
db93074897dd3440347cdda0ed4dc3cf7ba5bc4a
refs/heads/master
<file_sep>// real-time listener db.collection('recipes').onSnapshot(snapshot => { snapshot.docChanges().forEach(change => { if(change.type === 'added'){ renderRecipe(change.doc.data(), change.doc.id); } if(change.type === 'removed'){ // remove the document data from the web page } }); });<file_sep># PWA-test This is a very basic progressive web application made with: * Vanilla JS * HTML5 * CSS * Materialize * FireBase
639718928d655e092355a82b80184ad048de8d9f
[ "JavaScript", "Markdown" ]
2
JavaScript
Dola29/PWA-test
923df6daf48486ead5ea8c7d5d7d87f7c4102d37
b2cb5b0b24aef6049734dcc05ab2413bf3a9c471
refs/heads/master
<repo_name>ealves-pt/CharCounter<file_sep>/spec/StringerSpec.js describe("The '$_stringer.process' method", function() { describe("when called", function() { it("should accept strings", function() { expect(function() { $_stringer.process('lol'); }).not.toThrow(); }); it("should not accept integers", function() { expect(function() { $_stringer.process(3); }).toThrow(); }); it("should not accept arrays", function() { expect(function() { $_stringer.process([]); }).toThrow(); }); it("should not accept objects", function() { expect(function() { $_stringer.process({}); }).toThrow(); }); }); describe("when called with a string", function() { it("should count lower and upper vowels", function() { var result = $_stringer.process('aAeE'); expect(result.vowels.count).toEqual(4); }); it("should count lower and upper consonants", function() { var result = $_stringer.process('bBfF'); expect(result.consonants.count).toEqual(4); }); it("should count lower and upper chars", function() { var result = $_stringer.process('EbaBfAFe'); expect(result.consonants.count + result.vowels.count).toEqual(8); }); it("it should count lower and upper chars in multiline strings", function() { var result = $_stringer.process('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod quidem iam fit etiam in Academia. Quo invento omnis ab eo quasi capite de summo bono et malo disputatio ducitur. Tu vero, inquam, ducas licet, si sequetur; Tum ille: Ain tandem? Quid de Platone aut de Democrito loquar? Quae diligentissime contra Aristonem dicuntur a Chryippo. Atqui eorum nihil est eius generis, ut sit in fine atque extrerno bonorum.\nDuo Reges: constructio interrete. Nunc omni virtuti vitium contrario nomine opponitur. Cur tantas regiones barbarorum pedibus obiit, tot maria transmisit?'); expect(result.consonants.count + result.vowels.count).toEqual(463); }); it("should calc the top chars", function() { var result = $_stringer.process('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quod quidem iam fit etiam in Academia. Quo invento omnis ab eo quasi capite de summo bono ret malo disputatio ducitur. Tu vero, inquam, ducas licet, si sequetur; Tum ille: Ain tandem? Quid de Platone aut de Democrito loquar? Quae diligentissime contra Aristonem dicuntur a Chryippo. Atqui eorum nihil est eius generis, ut sit in fine atque extrerno bonorum.\nDuo Reges: constructio interrete. Nunc omni virtuti vitium contrario nomine opponitur. Cur tantas regiones barbarorum pedibus obiit, tot maria transmisit?'); expect(result.vowels.top).toEqual([ {chars: 'i', count: 58}, {chars: 'e', count: 45}, {chars: 'o', count: 39} ]); expect(result.consonants.top).toEqual([ {chars: 't', count: 47}, {chars: 'n,r', count: 33}, {chars: 'm,s', count: 25} ]); }); }); }); <file_sep>/README.md # CharCounter A simple char counter in Javascript. Allows to count number of vowels and consonants in a string and gives us the top 3 vowels and consonants used. <file_sep>/js/Stringer.js // String operations (function() { 'use strict'; String.prototype.removeOccurrences = function(pattern) { return this.replace(new RegExp(pattern, 'g'), ''); }; function Stringer() {}; Stringer.prototype = { process: function(text) { var vowelsReport; var consonantsReport; if (typeof text === 'string') { vowelsReport = countVowels(text); text = vowelsReport.resultText; consonantsReport = countConsonants(text); return { vowels: { top: vowelsReport.top, count: vowelsReport.total }, consonants: { top: consonantsReport.top, count: consonantsReport.total } }; } else { throw 'Invalid input type.'; } } }; function countVowels(text) { return countLetter(text, ['a','e','i','o','u']); } function countConsonants(text) { return countLetter(text, ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']); } function countLetter(text, letterList) { var report = { map: [], top: [], total: 0, resultText: '', }; letterList.forEach(function (val) { var size = text.length; var count = 0; text = text.removeOccurrences('['+val+val.toUpperCase()+']'); count = size - text.length; report.total += count; report.map = insertIntoArray({chars: [val], count: count}, report.map); }); report.map = report.map.reverse(); report.top = extractTopLetters(report.map); report.resultText = text; return report; } function insertIntoArray(element, array) { var i = locationOf(element, array); if (typeof array[i] !== 'undefined' && array[i].count === element.count) { array[i].chars = array[i].chars.concat(element.chars); } else { array.splice(i+1, 0, element); } return array; } function locationOf(element, array, start, end) { start = start || 0; end = end || array.length; var pivot = parseInt(start + (end - start) / 2, 10); if (end - start <= 1) { if (typeof array[pivot] === 'undefined') { return pivot; } else { return array[pivot].count > element.count ? pivot - 1 : pivot; } } if (array[pivot].count === element.count) return pivot; if (array[pivot].count < element.count) { return locationOf(element, array, pivot, end); } else { return locationOf(element, array, start, pivot); } } function extractTopLetters(map) { var topThree = map.slice(0, 3); var result = []; topThree.forEach(function(elem) { if (elem.count !== 0) { result.push({ chars: elem.chars.join(','), count: elem.count }); } }); return result; } window.$_stringer = new Stringer(); }).call(); <file_sep>/js/app.js // DOM interactions (function() { 'use strict'; var textarea = $_lightDom.findFirst('#field'); var vowelCount = $_lightDom.findFirst('#vowel-count'); var consonantCount = $_lightDom.findFirst('#consonant-count'); var topVowels = $_lightDom.findFirst('#top-vowels'); var topConsonants = $_lightDom.findFirst('#top-consonants'); $_lightDom.addEvent(textarea, 'keyup', function(e) { var target = e.target || e.srcElement; // IE8 support var report = $_stringer.process(target.value); vowelCount.innerHTML = report.vowels.count; generateTop(topVowels, report.vowels.top); consonantCount.innerHTML = report.consonants.count; generateTop(topConsonants, report.consonants.top); }); function generateTop(target, top) { if (target.childNodes.length) { target.removeChild(target.childNodes[0]); } var ulElem = document.createElement('ul'); top.forEach(function(v, i) { var liElem = document.createElement('li'); liElem.appendChild( document.createTextNode('[' + v.chars + '] (' + v.count + ')') ); ulElem.appendChild(liElem); }); target.appendChild(ulElem); } }).call();
49d6cbe814ee0a3c1ba24219e8552e8ae54ccf24
[ "JavaScript", "Markdown" ]
4
JavaScript
ealves-pt/CharCounter
0f037f670daa2dc7d4c834eb43f066a9879e9274
1079962a344070dc248904c0faebb7bac395efac
refs/heads/master
<repo_name>Skorodumov8091/OOP_labs<file_sep>/Lab_2/Lab_1/Examen.cs using System; namespace Lab_1 { public class Examen { public string name { get; private set; } public int grade; int limit = 3; int count_attempts = 1; public Examen(string name) { this.name = name; } public int Exam(int min, int max) { count_attempts++; Random rnd = new Random(); grade = rnd.Next(min, max + 1); return grade; } public bool Limit() { return limit >= count_attempts; } public bool LastAttempt() { return limit == count_attempts; } } } <file_sep>/Lab_2/Lab_1/Program.cs using System.Collections.Generic; using System; namespace Lab_1 { class Program { static void Main(string[] args) { Student student1 = new Botanist("Петров", "Петр", "Петрович", new List<int> { 5, 4, 4, 3, 5, 2 }); Student student2 = new OrdinaryStudent("Петров", "Петр", "Викторович", new List<int> { 5, 5, 3, 5, 5 }); Student student3 = new StudentCouncilMember("Иванов", "Иван", "Иванович", new List<int> { 5, 3, 4, 2 }); Console.WriteLine(student1); student1.Exam("Math"); Console.WriteLine(student1); student1.Exam("Philosophy"); Console.WriteLine(student1); student2.Exam("Math"); Console.WriteLine(student2); student2.Exam("Philosophy"); Console.WriteLine(student2); student2.Exam("Philosophy"); student2.Exam("Philosophy"); Console.WriteLine(student2); student2.Exam("Philosophy"); Console.WriteLine(student2); student3.Exam("Math"); Console.WriteLine(student3); student3.Exam("Philosophy"); student3.Exam("Philosophy"); Console.WriteLine(student3); student3.Exam("Philosophy"); Console.WriteLine(student3); } } } <file_sep>/Lab_2/Lab_1/Student.cs using System; using System.Collections.Generic; namespace Lab_1 { public abstract class Student { public string surname { get; private set; } public string name { get; private set; } public string middleName { get; private set; } public List<int> grades { get; private set; } List<Examen> examens = new List<Examen>(); public Student(string surname, string name, string middleName, List<int> grades) { this.surname = surname; this.name = name; this.middleName = middleName; this.grades = grades; } public abstract int Exam(string name); public Examen GetOrAddExamen(string name) { foreach (Examen ex in examens) if (ex.name == name) return ex; Examen examen = new Examen(name); examens.Add(examen); return examen; } public override string ToString() { string str = $"{ this.surname} { this.name} { this.middleName} "; for (int i = 0; i < this.grades.Count; ++i) { str += $"{this.grades[i]} "; } if (examens.Count > 0) { str += "\nExamens:\n"; foreach (Examen ex in examens) str += $"{ex.name}: {ex.grade}\n"; } return str; } } public class Botanist : Student { public Botanist(string surname, string name, string middleName, List<int> grades) : base(surname, name, middleName, grades) { } public override int Exam(string name) { Examen examen = GetOrAddExamen(name); return examen.Exam(4, 5); } } public class OrdinaryStudent : Student { public OrdinaryStudent(string surname, string name, string middleName, List<int> grades) : base(surname, name, middleName, grades) { } public override int Exam(string name) { Examen examen = GetOrAddExamen(name); if (examen.Limit()) return examen.Exam(2, 5); else return -1; } } public class StudentCouncilMember : OrdinaryStudent { public StudentCouncilMember(string surname, string name, string middleName, List<int> grades) : base(surname, name, middleName, grades) { } public override int Exam(string name) { Examen examen = GetOrAddExamen(name); if (examen.LastAttempt()) return examen.grade = 3; else return examen.Exam(2, 5); } } } <file_sep>/Lab_1/Lab_1/Student.cs using System; using System.Collections.Generic; using System.Text; namespace Lab_1 { public class Student { public string surname { get; private set; } public string name { get; private set; } public string middleName { get; private set; } public List<int> grades { get; private set; } public Student(string surname, string name, string middleName, List<int> grades) { this.surname = surname; this.name = name; this.middleName = middleName; this.grades = grades; } public override string ToString() { string str = $"{ this.surname} { this.name} { this.middleName} "; for (int i = 0; i < this.grades.Count; ++i) { str += $"{this.grades[i]} "; } return str; } } } <file_sep>/README.md # OOP_labs ## Lab_1 ### Вариант 1 Описать классы Student и StudentGroup, описывающие отношение между студентом и группой. Студент может быть добавлен в группу, может быть удален из нее. В одной группе могут находиться не более N студентов, один студент может находиться в неограниченном количестве групп. Реализовать методы: - для получения студента группы по ФИО; - для получения списка студентов, отсортированного в лексикографическом порядке, по оценкам; - для вывода обоих классов в ostream. Для демонстрации создать несколько групп и заполнить их студентами. Вывести группы в ostream. Продемонстрировать работу всех публичных методов классов (кроме геттеров и сеттеров). ## Lab_2 ### Вариант 1 Продолжение первой лабораторной работы.<br> Класс Student, реализованный в рамках лабораторной работы №1, следует сделать абстрактным, предоставив производным классам определять разные варианты поведения студентов. Произвести от класса Студент производные «Ботаник» (сдает все экзамены с первого раза на 4 и 5), «Обычный студент» (реализует рандомное поведение) и «Член студенческого совета» (является производным «обычного студента», но на последней пересдаче всегда получает 3 балла минимум и, следовательно, никогда не бывает отчислен). <file_sep>/Lab_1/Lab_1/Program.cs using System.Collections.Generic; using System; namespace Lab_1 { class Program { static void Main(string[] args) { // Создание студентов student1-student6 Student student1 = new Student("Петров", "Петр", "Петрович", new List<int> { 5, 4, 4, 3, 5, 2 }); Student student2 = new Student("Петров", "Петр", "Викторович", new List<int> { 5, 5, 3, 5, 5 }); Student student3 = new Student("Иванов", "Иван", "Иванович", new List<int> { 5, 3, 4, 2 }); Student student4 = new Student("Иванов", "Сергей", "Иванович", new List<int> { 4, 4, 4, 4, 2, 4 }); Student student5 = new Student("Дмитриев", "Дмитрий", "Дмитриевич", new List<int> { 5, 5, 5, 5 }); Student student6 = new Student("Павлов", "Павел", "Павлович", new List<int> { 5, 5, 4 }); // Создание группы studentGroup_1 StudentGroup studentGroup1 = new StudentGroup("Группа_1", 2); // Добавление студентов в группу studentGroup_1 if (!studentGroup1.addStudent(student1)) { Console.WriteLine("Больше нет мест в группе."); } if (!studentGroup1.addStudent(student2)) { Console.WriteLine("Больше нет мест в группе."); } // Выведется сообщение, т. к. больше нет мест в группе if (!studentGroup1.addStudent(student3)) { Console.WriteLine("Больше нет мест в группе."); } Console.WriteLine(studentGroup1); // Удаление студента из группы studentGroup1.removeStudent(student1); Console.WriteLine(studentGroup1); // Поиск студента по ФИО (+) if (studentGroup1.searchStudentByFIO("Петров", "Петр", "Викторович") != null) { Console.WriteLine("Студент состоит в группе."); } else { Console.WriteLine("Студент не состоит в группе."); } // Поиск студента по ФИО (-) if (studentGroup1.searchStudentByFIO("Иванов", "Петр", "Иванович") != null) { Console.WriteLine("Студент состоит в группе."); } else { Console.WriteLine("Студент не состоит в группе."); } StudentGroup studentGroup2 = new StudentGroup("Группа_2", 15); // Добавление студентов в группу studentGroup_2 if (!studentGroup2.addStudent(student1)) { Console.WriteLine("Больше нет мест в группе."); } if (!studentGroup2.addStudent(student2)) { Console.WriteLine("Больше нет мест в группе."); } if (!studentGroup2.addStudent(student3)) { Console.WriteLine("Больше нет мест в группе."); } if (!studentGroup2.addStudent(student4)) { Console.WriteLine("Больше нет мест в группе."); } if (!studentGroup2.addStudent(student5)) { Console.WriteLine("Больше нет мест в группе."); } if (!studentGroup2.addStudent(student6)) { Console.WriteLine("Больше нет мест в группе."); } Console.WriteLine(); Console.WriteLine("Сортировка по ФИО: "); studentGroup2.sortStudentGroupFIO(); Console.WriteLine(studentGroup2); Console.WriteLine("Сортировка по оценкам: "); studentGroup2.sortStudentGroupGrades(); Console.WriteLine(studentGroup2); } } } <file_sep>/Lab_2/Lab_1/StudentGroup.cs using System; using System.Collections.Generic; namespace Lab_1 { public class StudentGroup { public string nameGroup { get; private set; } public int numberStudent { get; private set; } public List<Student> students { get; private set; } public StudentGroup(string nameGroup, int numberStudent) { this.nameGroup = nameGroup; this.numberStudent = numberStudent; this.students = new List<Student>(); } public bool addStudent(Student student) { if (students.Count < numberStudent) { students.Add(student); return true; } else { return false; } } public void removeStudent(Student student) { students.Remove(student); } public Student searchStudentByFIO(string surname, string name, string middleName) { if (students.Count != 0) { foreach (Student el in students) { if (el.surname == surname && el.name == name && el.middleName == middleName) { return el; } } } return null; } public void sortStudentGroupFIO() { students.Sort(CompareByFIO); } public static int CompareByFIO(Student student1, Student student2) { if (student1.surname == student2.surname) { if (student1.name == student2.name) { return String.Compare(student1.middleName, student2.middleName); } else { return String.Compare(student1.name, student2.name); } } else { return String.Compare(student1.surname, student2.surname); } } public void sortStudentGroupGrades() { students.Sort(CompareByGrades); } public static int CompareByGrades(Student student1, Student student2) { double srGrades1 = srGrades(student1); double srGrades2 = srGrades(student2); if (srGrades1 < srGrades2) { return 1; } else if (srGrades1 > srGrades2) { return -1; } else { return 0; } } public static double srGrades(Student student) { int size = student.grades.Count; double srGrades = 0; for (int i = 0; i < size; ++i) { srGrades += student.grades[i]; } return srGrades /= size; } public override string ToString() { string str = ""; foreach (Student el in students) { str += $"{ el.surname} { el.name} { el.middleName} "; for (int i = 0; i < el.grades.Count; ++i) { str += $"{el.grades[i]} "; } str += "\n"; } return str; } } }
02046d2c22d7f17076238996cb34d7fd21281815
[ "Markdown", "C#" ]
7
C#
Skorodumov8091/OOP_labs
ba367e8df5993ed08317dea6cc552673ef2ee30d
508485fd9531f7937640a4855895f2cadeb7d3a4
refs/heads/master
<repo_name>DccShield/Lchika1<file_sep>/Lchika1/Lchika1.ino // // D2 port に接続したLEDを1秒周期で点滅を繰り替えす // delay()関数版 // void setup() { pinMode(2, OUTPUT); } void loop() { digitalWrite(2, HIGH); delay(1000); digitalWrite(2, LOW); delay(1000); }
e9c74051d30320c9347c50c237041f1ee19564a4
[ "C++" ]
1
C++
DccShield/Lchika1
fc490826c4650c1893f276f2b31e2613d1785d75
4df007c2a5869eb9823a881049b3c499a82b9a9a
refs/heads/master
<file_sep>Description =========== Install Percona server components, leveraging the Opscode MySQL cookbook as much as possible. Currently, this cookbook requires the use of a modified mysql cookbook (linked below), pending possible acceptance of a pull request. Tested only on Ubuntu 10.04. Not tested on enterprise linux distros. Requirements ============ * [modified mysql cookbook](http://tickets.opscode.com/browse/COOK-1236) * [mysql cookbook bugfix](http://tickets.opscode.com/browse/COOK-1113) Attributes ========== `percona['version']` Which version of Percona to install. Options are `5.0`, `5.1`, `5.5`, or `latest`. Other attributes override the default mysql attributes related to package names. Recipes ======= percona_repo ------------ Installs Apt and Yum repos as required to download Percona packages. client ------ Install Percona client using mysql::client recipe. server ------ Installs Percona server using mysql::server recipe. Usage ===== <file_sep>Bakery-enabled cluster of Drupal sites for Bakery testing using Vagrant and Chef. [![Build Status](https://secure.travis-ci.org/glennpratt/Bakery-Chef.png)](http://travis-ci.org/glennpratt/Bakery-Chef) ## Installation 1. [Download Virtual Box](https://www.virtualbox.org/wiki/Downloads) 1. [Download & install vagrant](http://downloads.vagrantup.com/tags/v1.0.3) 1. `git clone git://github.com/bjeavons/Bakery-Chef.git` 1. `cd Bakery-Chef` 1. `vagrant up` Running `vagrant up` will take awhile because it downloads the VM image. It may fail with message about mysql returning status 1. Just type `vagrant provision` to restart. When it is done you can connect to the vm server using `vagrant ssh`. The vm's apache server will be accessible at 172.22.22.22 and it will create the following sites that you should add to your /etc/hosts file (all at 172.22.22.22): * masterd6.vbox - Drupal 6 master * d6.masterd6.vbox - Drupal 6 slave of Drupal 6 master * d7.masterd6.vbox - Drupal 7 slave of Drupal 6 master * masterd7.vbox - Drupal 7 master * d6.masterd7.vbox - Drupal 6 slave of Drupal 7 master * d7.masterd7.vbox - Drupal 7 slave of Drupal 7 master Drupal sites come pre-installed with latest Bakery 2.x development release. ## Testing Cucumber tests of SSO and basic data synchronization are available in the /tests directory. <file_sep>Vagrant::Config.run do |config| # All Vagrant configuration is done here. For a detailed explanation # and listing of configuration options, please view the documentation # online. # Every Vagrant virtual environment requires a box to build off of. config.vm.box = "ms-ubuntu-11.10" # Download the box automatically from S3. config.vm.box_url = "http://msonnabaum-public.s3.amazonaws.com/ms-ubuntu-11.10.box" config.vm.provision :chef_solo do |chef| chef.cookbooks_path = ["cookbooks"] chef.roles_path = "roles" chef.data_bags_path = "data_bags" chef.add_role("db-server") chef.add_role("bakery") chef.json.merge!({ :www_root => '/var/www', :mysql => { "server_root_password" => "<PASSWORD>", "drupal_user" => "bakery", "drupal_password" => "<PASSWORD>" }, :drupal => { "admin_password" => "<PASSWORD>", "test_name" => "test1", "test_password" => "<PASSWORD>", }, :sites => { "masterd6" => { :alias => "masterd6.vbox", :core => "6", :master => "masterd6.vbox", :subs => ["d6.masterd6.vbox", "d7.masterd6.vbox"] }, "d6subd6" => {:alias => "d6.masterd6.vbox", :core => "6", :master => "masterd6.vbox"}, "d7subd6" => {:alias => "d7.masterd6.vbox", :core => "7", :master => "masterd6.vbox"}, "masterd7" => { :alias => "masterd7.vbox", :core => "7", :master => "masterd7.vbox", :subs => ["d6.masterd7.vbox", "d7.masterd7.vbox"] }, "d6subd7" => {:alias => "d6.masterd7.vbox", :core => "6", :master => "masterd7.vbox"}, "d7subd7" => {:alias => "d7.masterd7.vbox", :core => "7", :master => "masterd7.vbox"} } }) end # Run the host with a host-only IP of 172.22.22.22. config.vm.network :hostonly, "172.22.22.22" config.ssh.max_tries = 1000 # Forward port 22 to localhost:2222. config.vm.forward_port 22, 2222 end <file_sep># Automatically prepare vhosts for drupal sites. require_recipe "hosts" require_recipe "apache2" node[:sites].each do |name, attrs| site = attrs[:alias] # Configure the site vhost web_app site do template "sites.conf.erb" server_name site server_aliases [site] docroot "#{node[:www_root]}/#{name}/htdocs" end end<file_sep>=begin Capybara: Most important things are here: https://github.com/jnicklas/capybara/blob/master/README.md The full documentation is here: http://rubydoc.info/github/jnicklas/capybara/master #Examples #When /^I click (?:on )?["'](.*)['"]$/ do |link| # click_link(link) #end #Then /^there should be a button called ['"](.*)['"]$/ do |button_name| # page.should have_button(button_name) #end =end Given /^I visit "(.*?)"$/ do |site| Capybara.app_host = site visit('/') end Given /^I am visiting the homepage$/ do visit('/') end Then /^I should (not )?see a title containing the word "(.*?)"$/ do |present, text| if present page.should_not have_css('title', :text => text) else page.should have_css('title', :text => text) end end Given /^I search for '(.*)'$/ do |text| fill_in('edit-search-block-form--2', :with => text) find(:css, 'input#edit-submit').click end Then /^I should see (no|a lot of) search results$/ do |amount| if amount == 'a lot of' all('li.search-result').size.should >= 4 else all('li.search-result').size.should == 0 end end Then /^I should see the text "(.*?)"$/ do |text| page.should have_content(text) end Then /^I should see the (.*?) form value "(.*?)"$/ do |name, text| page.has_field?(name, :value => text) end Given /^I log in as user "(.*?)" with password "(.*?)"$/ do |user, pass| visit('/user/login') within('#user-login') do fill_in 'Username', :with => user fill_in 'Password', :with => <PASSWORD> end click_button('Log in') end Given /^I goto my account edit page$/ do visit('/user') click_link 'Edit' end Given /^I change my email to "(.*?)"$/ do |change| within('#user-profile-form') do fill_in 'E-mail address', :with => change end click_button('Save') end Then /^I should see a link containing the text "(.*?)"$/ do |text| find_link(text).visible? end When /^I click "(.*?)"$/ do |text| click_link text end Then /^I should not see a link containing the text "(.*?)"$/ do |text| page.should have_no_content(text) end <file_sep>include_recipe "apt" php_pear "pear" do action :upgrade end package "mcrypt" do action :install end package "php5-mcrypt" do action :install end cookbook_file "/usr/lib/php5/mcrypt.so" do source "mcrypt/mcrypt.so" owner "root" group "root" mode "0644" end cookbook_file "/etc/php5/conf.d/mcrypt.ini" do source "mcrypt/mcrypt.ini" owner "root" group "root" mode "0644" end<file_sep>require_recipe "mysql" require_recipe "drush" require_recipe "drush_make" sql_pass_opt = !node[:mysql][:server_root_password].empty? ? "-p #{node[:mysql][:server_root_password]}" : "" sql_cmd = "/usr/bin/mysql -u root #{sql_pass_opt}" node[:sites].each do |name, attrs| site_dir = "#{node[:www_root]}/#{name}" web_root = "#{site_dir}/htdocs" make = "bakery-d#{attrs[:core]}.make" db_url = "mysqli://#{node[:mysql][:drupal_user]}:#{node[:mysql][:drupal_password]}@localhost/#{name}" cookie_domain = ".#{attrs[:master]}" # Create DB TODO Use Provider execute "add-#{name}-db" do command "#{sql_cmd} -e \"" + "CREATE DATABASE #{name};" + "GRANT ALL PRIVILEGES ON #{name}.* TO '#{node[:mysql][:drupal_user]}'@'localhost' IDENTIFIED BY '#{node[:mysql][:drupal_password]}';\"" action :run ignore_failure true end # Create site dir execute "create-#{name}-site-dir" do command "mkdir -p #{site_dir}" not_if { File.exists?("#{site_dir}/#{make}") } end # Copy makefile cookbook_file "copy-#{name}-makefile" do path "#{site_dir}/#{make}" source make action :create_if_missing end # drush make site execute "make-#{name}-site" do command "cd #{site_dir}; drush make #{make} htdocs" not_if { File.exists?("#{web_root}/index.php") } end # copy settings.php file execute "create-#{name}-settings-file" do command "cp #{web_root}/sites/default/default.settings.php #{web_root}/sites/default/settings.php" not_if { File.exists?("#{web_root}/sites/default/settings.php") } end # chown settings.php file execute "chown-#{name}-settings-file" do command "chown www-data #{web_root}/sites/default/settings.php" not_if { !File.exists?("#{web_root}/sites/default/settings.php") } end # make files dir execute "make-#{name}-files-dir" do command "mkdir #{web_root}/sites/default/files" not_if { File.exists?("#{web_root}/sites/default/files") } end # chown files dir execute "chown-#{name}-files-dir" do command "chown www-data #{web_root}/sites/default/files" not_if { !File.exists?("#{web_root}/sites/default/files") } end # install site if attrs[:core] == "7" execute "install-#{name}" do command "cd #{web_root}; drush si --db-url=#{db_url} --account-pass=#{node[:drupal][:admin_password]} --site-name='#{name}' -y" end else # Copy makefile cookbook_file "copy-#{name}-sql" do path "/tmp/#{name}.sql" source "#{name}.sql" end execute "install-#{name}" do command "#{sql_cmd} #{name} < /tmp/#{name}.sql" end execute "install-#{name}" do command "echo \'$db_url = \"#{db_url}\";\' >> #{web_root}/sites/default/settings.php" end end # setup bakery execute "#{name}-setup-bakery" do if attrs[:master] == attrs[:alias] # This is Bakery master subs = [] attrs[:subs].each do |sub| subs << "'http://#{sub}/'" end subs = subs.join(',') command "cd #{web_root}; drush en -y bakery; drush vset -y bakery_is_master 1; drush vset -y bakery_key 'bakerysecret'; drush vset -y bakery_master 'http://#{attrs[:master]}/'; drush vset -y bakery_domain '#{cookie_domain}'; php -r \"print json_encode(array(#{subs}));\" | drush vset -y --format=json bakery_slaves -; drush cc all;" else # This is Bakery slave command "cd #{web_root}; drush en -y bakery; drush vset -y bakery_is_master 0; drush vset -y bakery_key 'bakerysecret'; drush vset -y bakery_master 'http://#{attrs[:master]}/'; drush vset -y bakery_domain '#{cookie_domain}'; drush cc all;" end end # create test1 accounts on master if attrs[:master] == attrs[:alias] execute "create-#{name}-test-account" do command "cd #{web_root}; drush user-create #{node[:drupal][:test_name]} --mail='#{node[:drupal][:test_name]}@example.com' --password='#{node[:drupal][:test_password]}'" ignore_failure true end end # setup /etc/hosts @todo this isn't working https://github.com/bjeavons/Bakery-Chef/issues/2 #execute "#{name}-setup-hosts" do # command "echo '127.0.0.1 #{name}' >> /etc/hosts" #end end
75453314b8068b647110852bfb8ba4c82c67d6c6
[ "Markdown", "Ruby" ]
7
Markdown
glennpratt/Bakery-Chef
bd2c9b23faf72621d1a193049de2ffea51369919
09778c759d03ba93d151b6583bb67c50706b0c69
refs/heads/master
<file_sep>HBC === HandBrake Cutter (HBC) is a command-line wrapper for HandBrakeCLI that cuts or extracts video clips by human-readable time format. ## Requirements Make sure you have installed the [command line version of HandBrake](https://handbrake.fr/downloads2.php) and place the binary into any "PATH" (e.g. `/usr/local/bin`). ## Usage Time format are `HH:MM:SS` or `MM:SS`, or `SS` (simply seconds): [OUTDIR=output_directory] hbc FILENAME START-TIME STOP-TIME By default, if you don't pass the OUTDIR environment variable, output directory will be `~/.hbc`. ## Example To extract video from 00:34 (0 minute 34 seconds) to (1 minute 57 seconds): $ hbc sample.mp4 00:34 01:57 To extract video from 00:01:10 (0 hour, 1 minute and 10 seconds) to 01:23:14 (1 hour, 23 minutes and 14 seconds): $ hbc sample.mp4 00:01:10 01:23:14 <file_sep>#!/usr/bin/env bash # HandBrake Cutter set -e USAGE='usage: [OUTDIR=output_directory] hbc FILENAME START-TIME STOP-TIME' show_help() { echo "$USAGE" >&2 } # Convert format time (HH:MM:SS) to seconds time2seconds() { echo "$1" | awk -F: '{ if (NF > 3) { print "Invalid time format." > "/dev/stderr" exit 1 } base = 60 res = 0 for (i = 1; i <= NF; i++) { res = res * base + $i } print res }' } autoincr() { f="$1" ext="" # Extract the file extension (if any), with preceeding '.' [[ "$f" == *.* ]] && ext=".${f##*.}" if [[ -e "$f" ]] ; then i=1 f="${f%.*}"; while [[ -e "${f}_${i}${ext}" ]]; do let i++ done f="${f}_${i}${ext}" fi echo "$f" } [ $# -ne 3 ] && { show_help exit 1 } eval OUTDIR="${OUTDIR:-~/.hbc}" mkdir -p "$OUTDIR" FILENAME="$(echo "${1// /_}")" BITRATE="$(ffmpeg -i "$1" |& grep -o 'bitrate.*$' | awk '{ print $2 }')" START_TIME="$(time2seconds "$2")" STOP_TIME="$(time2seconds "$3")" echo "Output directory is $OUTDIR." which HandBrakeCLI &> /dev/null || { echo 'HandBrakeCLI command is not found. Please install it to PATH.' >&2 exit 1 } HandBrakeCLI -i "$1" -o "$(autoincr "$OUTDIR/$(basename "$FILENAME")")" \ -b "$BITRATE" \ --start-at "duration:$START_TIME" \ --stop-at "duration:$(echo "$STOP_TIME - $START_TIME" | bc)"
81eff53c5cd86d0ba76bf804ead59ce62aeff2c5
[ "Markdown", "Shell" ]
2
Markdown
shichao-an/hbc
dd4b5ef7cf1204d88feead47a072cc8f23d92028
36046fe0d6f25d4607bcd3cda2bba339b86d2bfa
refs/heads/master
<file_sep>import pandas as pd from flask import Flask from flask import jsonify from flask import request from flask import json test={'result':'xyz'} image={'path':'','name':''} app = Flask(__name__) @app.route('/popularrecommendation/qwerty',methods=['POST']) def index(): print(json.dumps(request.json)) return jsonify(test) @app.route('/image/qwerty',methods=['POST']) def index(): print(json.dumps(request.json)) return jsonify(test) if __name__ == '__main__': app.run(host= '192.168.0.8') # ============================================================================= # ============================================================================= # frame = pd.read_csv("C:/Users/abcdef/Downloads/Ex_Files_Intro_Python_Rec_Systems/Exercise Files/01_02/rating_final.csv") # cuisine = pd.read_csv("C:/Users/abcdef/Downloads/Ex_Files_Intro_Python_Rec_Systems/Exercise Files/01_02/chefmozcuisine.csv") # rating_count = pd.DataFrame(frame.groupby(['placeID'])['rating'].count()) # rating_Top_Five = rating_count.sort_values('rating',ascending=False).head() # rating_Top_Five.reset_index().head() # rating_Top_Five.drop(['rating'], axis = 1, inplace = True) # summary = pd.DataFrame(rating_Top_Five).reset_index().head() # summary.to_json(orient='records') # print(summary.to_json(orient='records')) # =============================================================================
537a76606184f6324abc00fe7aa7c3071fa9704f
[ "Python" ]
1
Python
hvardhan617/PythonCCOCR
92122e6d38c0b50f0f822ad74edfffb71a9ec7a1
9458d0ced749dfd7d1f5b0b3f53278161a9a0249
refs/heads/master
<repo_name>parthsarthiprasad/restfulapi<file_sep>/api/routes/products.js const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const Product = require('../models/product'); router.get('/', (req, res, next) => { Product.find() .select('name price _id') .exec() .then(doc => { const response = { count: doc.length, products: doc.map(doc => { return { //...docs, name: doc.name, price: doc.price, id: doc._id, request: { type: 'GET', url: 'https://localhost:3000/products/' + doc._id } } }) } res.status(200).json(response); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); // res.status(200).json({ // message: 'handling GET requests to /products' // }); }); router.post('/', (req, res, next) => { // const product ={ // name: req.body.name, // price: req.body.price // }; const product = new Product({ _id: new mongoose.Types.ObjectId(), name: req.body.name, price: req.body.price }); //product.save().exec(); // exec helps to return a promise , else product.save with require a callback //exec is a function of mongoose , not require for save funtion //product.save(err ,result) product .save() .then(result => { console.log(result); res.status(201).json({ message: 'created product sucessfully', createdProduct: { name: result.name, price: result.price, _id: result._id, request: { type: "GET", url: "http://localhost:3000/products/" + result._id } } }) }) .catch(err => { console.log(err) res.status(500).json({ error: err }) }); }); router.get('/:productId', (req, res, next) => { const id = req.params.productId; Product .findById(id) .select('name price _id') .exec() .then(doc => { console.log("from database", doc); if (doc) { res.status(200).json({ name: doc.name, price: doc.price, id: doc._id, request: { type: "GET", url: "http://localhost:3000/products/" + doc._id } }); } else { res.status(404).json({ message: "no valid entry found for provided ID" }); } }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); // patching sysntax // [ // { "propName" : "name" , "value": "harry potter 6" } // ] router.patch('/:productsid', (req, res, next) => { const id = req.params.productsid; const updateOps = {}; for (const ops of req.body) { updateOps[ops.propName] = ops.value; } Product.update({ _id: id }, { $set: updateOps }) .exec() .then(result => { res.status(200).json({ message: "product updated", request: { type: 'GET', url: "http://localhost:3000/products/" + id } }) }) .catch(err => { console.log(err) res.status(500).json({ error: err }) }) }) router.delete('/:productsid', (req, res, next) => { const id = req.params.productsid; Product.remove({ _id: id }).exec() .then(result => { res.status(200).json({ message: 'product deleted', request: { type: 'POST', url: 'http://localhost:3000/products', body: { name: 'string', price: 'number' } } }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); module.exports = router;<file_sep>/README.md # restfulapi the project is to create a shopping cart with cloud connection to mongo server with basic functionality of authentication , geolocation and to create a working shopping cart. to run the project type npm start in terminal this will start the nodemon server with linking to the mongo cloud connection .
024b5908bf04f3acd1797e78a590cb8ccbc354c5
[ "JavaScript", "Markdown" ]
2
JavaScript
parthsarthiprasad/restfulapi
c908e022ffa8e482d98344bb907bc138b42f5e37
802fc3fa299d39b042c0e2a8a1433006974896a6
refs/heads/master
<repo_name>nateplusplus/nateplusplus<file_sep>/src/pages/projects.js import React from "react" import SEO from "../components/seo" const IndexPage = () => ( <> <SEO title="Home" /> <section> <h3>All the weird stuff I've made</h3> <ul> <li> <a href="https://samplesaurus.com/" target="_blank" rel="noopener noreferrer">Samplesaurus</a> </li> <li> <a href="https://mydailyplanter.com/" target="_blank" rel="noopener noreferrer">Daily Planter</a> </li> </ul> </section> </> ) export default IndexPage <file_sep>/src/templates/page.js import React from "react" import Layout from "../components/layout" import { graphql } from "gatsby" export default function WpPage({ data }) { const page = data.allWpPage.nodes[0] return ( <Layout> <div> <h1>{page.title}</h1> <div dangerouslySetInnerHTML={{ __html: page.content }} /> </div> </Layout> ) } export const query = graphql` query($pageId: Int!) { wpPage(databaseId: { eq: $pageId } ) { title content } } `<file_sep>/src/pages/bookmarks.js import React from "react" import SEO from "../components/seo" const IndexPage = () => ( <> <SEO title="Home" /> <section> <h3>Cool web dev stuff</h3> <ul> <li> <a href="http://www.uigoodies.com/" target="_blank" rel="noopener noreferrer">UI Goodies</a> </li> </ul> </section> </> ) export default IndexPage <file_sep>/src/pages/social.js import React from "react" import SEO from "../components/seo" const SocialPage = () => ( <> <SEO title="Home" /> <section> <h3>Places to stalk me</h3> <ul> <li> <a href="https://github.com/nateplusplus" target="_blank" rel="noopener noreferrer">GitHub madness</a> </li> <li> <a href="https://codepen.io/nateplusplus" target="_blank" rel="noopener noreferrer">Codepen doodles</a> </li> <li> <a href="https://www.instagram.com/nateplusplus/" target="_blank" rel="noopener noreferrer">Later-grams</a> </li> <li> <a href="https://twitter.com/nateplusplus" target="_blank" rel="noopener noreferrer">That account I sometimes remember</a> </li> <li> <a href="#nofb" target="_blank" style={{ textDecoration: 'line-through' }} rel="noopener noreferrer">Facebook</a> <small>Nah, you don't need that.</small> </li> </ul> </section> </> ) export default SocialPage <file_sep>/src/components/header.js import { Link } from "gatsby" import PropTypes from "prop-types" import React from "react" import SvgImageText from '../scripts/svgText'; class Header extends React.Component { constructor( props ) { super(props) } componentDidMount() { new SvgImageText(); } render () { return( <> <header> <Link to="/"> <svg viewBox="0 0 1550 300" preserveAspectRatio="xMidYMid meet"> <defs> <mask id="text-mask-1"> <text id="bgText" x="0" y="270" shapeRendering="geometricPrecision" fill="#FFF">{this.props.siteTitle.toUpperCase()}</text> </mask> </defs> <g mask="url(#text-mask-1)"> <image id="img1" href="https://source.unsplash.com/sp-p7uuT0tw/1920x1000/" width="150%" /> <image id="img2" className="is-transparent" href="https://source.unsplash.com/featured/1920x1000/?nature" width="150%" /> <image id="img3" className="is-transparent" href="https://source.unsplash.com/featured/1920x1000/?architecture" width="150%" /> <image id="img4" className="is-transparent" href="https://source.unsplash.com/featured/1920x1000/?textures-patterns" width="150%" /> <image id="img5" className="is-transparent" href="https://source.unsplash.com/featured/1920x1000/?experimental" width="150%" /> </g> </svg> </Link> </header> <nav> <ul id="menubar" role="menubar"> <li role="none"> <Link id="one" className="menu-item" to="/" role="menuitem">Welcome</Link> </li> <li role="none"> <Link id="two" className="menu-item" to="/social" role="menuitem">Social</Link> </li> <li role="none"> <Link id="three" className="menu-item" to="/projects" role="menuitem">Projects</Link> </li> <li role="none"> <Link id="four" className="menu-item" to="/bookmarks" role="menuitem">Bookmarks</Link> </li> </ul> </nav> </> ); } } Header.propTypes = { siteTitle: PropTypes.string, } Header.defaultProps = { siteTitle: ``, } export default Header <file_sep>/src/pages/index.js import React from "react" import SEO from "../components/seo" import { useStaticQuery, graphql, Link } from "gatsby" const IndexPage = () => { const pageData = useStaticQuery(graphql` query WPPageContentQuery { wpPage(slug: {eq: "homepage"}) { content } allWpPage(filter: {status: {eq: "publish"}, isFrontPage: {eq: false}}) { nodes { databaseId slug title content } } } `) return( <> <SEO title="Home" /> <section dangerouslySetInnerHTML={{ __html : pageData.wpPage.content }} ></section> {/* <section> <p>Testing auto-generated Gatsby pages from WPGraphQL:</p> { pageData.allWpPage.nodes.map((node) => ( <Link to={node.slug}>{node.title}</Link> )) } </section> */} </> ) } export default IndexPage
84dede2a83a5df17a16494c1eaddbd0ed66f36fa
[ "JavaScript" ]
6
JavaScript
nateplusplus/nateplusplus
cf54aac91c845e38932c8e5469a379b602335647
25efa901857cf93f05208b46041ed03369803003
refs/heads/master
<repo_name>XuZhangCoding/github<file_sep>/github/github/适配/CrossDevicesLayout.h // // CrossDevicesLayout.h // GW // // Created by 艾呦呦 on 16/12/23. // Copyright © 2016年 apple. All rights reserved. // 跨设备的尺寸转换 #ifndef CrossDevicesLayout_h #define CrossDevicesLayout_h // 适配iOS 11 //TableView #define iOS11_TableViewAdjust(name)\ if (@available(iOS 11.0, *)) {\ if ([self respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {\ self.name.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;\ }\ self.estimatedRowHeight = 0;\ self.estimatedSectionHeaderHeight = 0;\ self.estimatedSectionFooterHeight = 0;\ } else {\ self.automaticallyAdjustsScrollViewInsets = NO;\ }\ //iphoneX 375 x 812 #define KiphoneXStatusBar (44.0f) #define KiphoneXNavBar (44.0f) #define KiphoneXTableBar (49.0f) #define KiphoneXHomeBar (34.0f) #define KiphoneXHeader (88.0f) #define KiphoneXFooter (83.0f) #define KiphoneXWidth (375.0f) #define KiphoneXHeight (812.0f) #define KiPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125,2436), [[UIScreen mainScreen] currentMode].size) : NO) #define KUITableViewFrame ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGRectMake(0, 88, kScreenWidth, kScreenHeight - 88 - 83) : CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64 - 49)) // 设计屏幕尺寸 iPhone6 #define kDesignWidth (375.0f) #define kDesignHeight (667.0f) // 当前主屏幕尺寸 #define kScreenWidth [[UIScreen mainScreen] bounds].size.width #define kScreenHeight [[UIScreen mainScreen] bounds].size.height // 缩放因子 (当前屏幕宽高与设计屏幕宽高比) #define kHorizontalScaleFactor (kScreenWidth / kDesignWidth) #define kVerticalScaleFactor (kScreenHeight / kDesignHeight) // 传入设计图上的数值 转换成跨设备的数值(向下取浮点数) #define CGCrossDevicesX(x) floorf(x * kHorizontalScaleFactor) #define CGCrossDevicesY(y) floorf(y * kVerticalScaleFactor) #define CGCrossDevicesWidth(w) floorf(w * kHorizontalScaleFactor) #define CGCrossDevicesHeight(h) floorf(h * kVerticalScaleFactor) #define CGCrossDevicesPointMake(x, y) CGPointMake(CGCrossDevicesX(x), CGCrossDevicesY(y)) #define CGCrossDevicesSizeMake(w, h) CGSizeMake(CGCrossDevicesWidth(w), CGCrossDevicesHeight(h)) // 由于开发中的坐标原点不确定,所以设置 frame 时,使用 CGRectMake(x, y, w, h), 根据需求对其中的数值进行跨设备转换 #endif /* CrossDevicesLayout_h */
117fe2f447418fd8d3395c433b1fc179c533e812
[ "C" ]
1
C
XuZhangCoding/github
3bb2428e543a3925cd9911164ca792ad0573b0a3
0acf4f07b09436727489b7fbe4960197c5188707
refs/heads/master
<file_sep>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.text.DecimalFormat; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printWriter = new PrintWriter(System.out); int N; double R,length=0; StringTokenizer stk = new StringTokenizer(bufferedReader.readLine()); N = Integer.parseInt(stk.nextToken()); R = Double.parseDouble(stk.nextToken()); double [][] coords = new double[N][2]; for (int i = 0; i < N; i++) { stk = new StringTokenizer(bufferedReader.readLine()); coords[i][0] = Double.parseDouble(stk.nextToken()); coords[i][1] = Double.parseDouble(stk.nextToken()); } for (int i=0;i<N-1; i++) { length += Math.sqrt(Math.pow(coords[i][0]-coords[i+1][0],2)+Math.pow(coords[i][1]-coords[i+1][1],2)); } if (N>1) length += Math.sqrt(Math.pow(coords[0][0]-coords[N-1][0],2)+Math.pow(coords[0][1]-coords[N-1][1],2)); length+=2*Math.PI*R; DecimalFormat df = new DecimalFormat("#.##"); printWriter.println(df.format(length)); printWriter.flush(); } } <file_sep>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printWriter = new PrintWriter(System.out); int N = Integer.parseInt(bufferedReader.readLine()); long[] primes = new long[15001]; int ctr = 0; for (long i = 2; ctr < 15000 && i<Long.MAX_VALUE; i++) { if (phi(i)==i-1) primes[++ctr] = i; } int req = 0; for (int i=0; i<N; i++) { req = Integer.parseInt(bufferedReader.readLine()); printWriter.println(primes[req]); } printWriter.flush(); } public static long phi(long n) { long result = n; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { while (n % i == 0) n /= i; result -= result / i; } } if (n > 1) result -= result / n; return result; } } <file_sep>#include <iostream> using namespace std; int main() { int ngroup, groups[101], minSum=0, tmp, reqGroup; // +information input cin >> ngroup; for (int c=0; c<ngroup; ++c) { cin >> groups[c]; } // -information input // +information sort if (ngroup>1) { for (int c=1; c<ngroup; ++c) { if (groups[c]<groups[c-1]) { tmp=groups[c]; groups[c]=groups[c-1]; groups[c-1]=tmp; }; for (int v=c; v>0; --v) { if (groups[v]<groups[v-1]) { tmp=groups[v]; groups[v]=groups[v-1]; groups[v-1]=tmp; }; } } } // +information sort reqGroup=(ngroup-1)/2+1; //finding required amout of groups voted FOR the party for (int c=0; c<reqGroup; ++c) { minSum+=(groups[c]-1)/2+1; } cout << minSum; } <file_sep>#include <cstdio> #include <cmath> #include <cstdlib> void main() { int i = 0; int k; double b; double *a = (double*)malloc(sizeof(double)*1000000); while(scanf("%lf",&b) != EOF) { a[i] = sqrt(b); i++; } for(k = i - 1;k >= 0; k--) { printf("%.4lf\n",a[k]); } } <file_sep>#include <cstdio> #include <fstream> using namespace std; int main(void) { int N = 0,K = 0; scanf("%d", N); scanf("%d", K); // printf("%s%d%s%d%s\n", "Hello World (",N,",",K,")"); return 0; } <file_sep>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; //UNFINISHED public class Main { public static long variant = 1; public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printWriter = new PrintWriter(System.out); int N = Integer.parseInt(bufferedReader.readLine()); calculate(N, 1); printWriter.flush(); } public static void calculate(int N, int currentHeight) { int lc = 0; int maxCurrent; if (currentHeight != 1) { //if not on first stair if (currentHeight * 2 + 1 == N); // variant++; if (currentHeight * 2 + 1 > N); // variant++; } if (currentHeight * 2 + 1 < N) { if (N % 2 == 0) maxCurrent = (N - 2) / 2; else maxCurrent = (N - 1) / 2; variant += maxCurrent - currentHeight; } for (; (currentHeight * 2) + 1 <= N; currentHeight++) { calculate(N - currentHeight, currentHeight + 1); lc += 1; } if (lc > 0) variant *= lc; } } <file_sep>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter printWriter = new PrintWriter(System.out); int n = Integer.parseInt(bufferedReader.readLine()); int arr[][] = new int[n][n]; int ctr=1; int x=0,y=0; for (int i=n-1; i>=0; i--) { x=i; y=0; while (y<n-i) { arr[y][x] = ctr++; x+=1; y+=1; } } for (int i=1; i<n; i++) { x=0; y=i; while (x<n-i) { arr[y][x] = ctr++; x+=1; y+=1; } } for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { if (j!=0) printWriter.print(" "); printWriter.print(arr[i][j]); } printWriter.println(); } printWriter.flush(); } }
b01c50325a0eadd839a7d1cd6eec3da295004ea8
[ "Java", "C++" ]
7
Java
truegff/timus
b85af9596cf0f4d5c0124d6b7e94216c092ddb65
c22a4d29d7ecf9b870085c09a0a8f06bcf313bea
refs/heads/master
<repo_name>hengAmethyst/Ada<file_sep>/src/http/fly.js /* fly配置文件 by:David 2018.6.14 */ //引入 fly var Fly = require("flyio/dist/npm/wx") var fly = new Fly; import config from './config' //配置请求基地址 // //定义公共headers // fly.config.headers={xx:5,bb:6,dd:7} // //设置超时 fly.config.timeout = config.timeout; // //设置请求基地址 fly.config.baseURL = config.host //添加请求拦截器 fly.interceptors.request.use((request) => { wx.showLoading({ title: "加载中", mask:true }); //给所有请求添加自定义header request.headers = { "X-Tag": "flyio", 'content-type': 'application/json' }; //打印出请求体 // console.log(request.body) //终止请求 //var err=new Error("xxx") //err.request=request //return Promise.reject(new Error("")) // let authParams = { // //公共参数 // "categoryType": "SaleGoodsType@sim", // "streamNo": "wxapp153570682909641893", // "reqSource": "MALL_H5", // "appid": "string", // "timestamp": new Date().getTime(), // "sign": "string" // }; // request.body && Object.keys(request.body).forEach((val) => { // if(request.body[val] === ""){ // delete request.body[val] // }; // }); // request.body = { // ...request.body, // ...authParams // } //可以显式返回request, 也可以不返回,没有返回值时拦截器中默认返回request return request; }) //添加响应拦截器,响应拦截器会在then/catch处理之前执行 fly.interceptors.response.use((response) => { wx.hideLoading(); //只将请求结果的data字段返回 return response.data }, (err) => { console.log(err); wx.hideLoading(); if(err){ return "请求失败"; }; //发生网络错误后会走到这里 //return Promise.resolve("ssss") } ) // Vue.prototype.$http=fly //将fly实例挂在vue原型上 export default fly<file_sep>/src/utils/common.js // 配置 const appid = ''; const appKey = ''; const imageUrl = 'http://insurance.awbchina.com/ada/' // 图片资源 const common = { appid, appKey, imageUrl } export default common;<file_sep>/src/store/mutation-types.js // 方便书写和检测 export const SET_OPEN_ID = 'SET_OPEN_ID'; export const SET_LOCATION = 'SET_LOCATION'; // 菜品识别上传的图片临时地址 export const dishInfo = 'DISHINFO'
d31ab543e805728b06cb3ddb54a99728dae7193a
[ "JavaScript" ]
3
JavaScript
hengAmethyst/Ada
351c04abfd81071829f1a1d3406fb32f5df08923
7e33e5944648c80bd0b05588d405bd80c6e24e18
refs/heads/master
<file_sep> CSE 533: NETWORK PROGRAMMING ============================ ASSIGNMENT: 2 Group Members: <NAME> : 109838041 <NAME> : 109176677 1. Handling of unicast addresses: --------------------------------- In order to handle unicast address, each interface address retrieved using get_ifi_info_plus method is checked for flag:IFF_BROADCAST. If the flage is not set, then it is considered as unicast address and serve as an interface to handle clients' requests. In order to contain the information about the interfaces, following struct is used: struct nw_interface { int sockfd; // socket file descriptor struct sockaddr *ifi_addr; //IP address bound to socket struct sockaddr *ifi_maskaddr; //network mask struct sockaddr *ifi_subaddr; //subnet address }; 2. RTT and RTO determination ----------------------------- The methods provided by Mr. <NAME>, have been used as a foundation to determine RTO and RTT. For RTT and RTO determination three methods have been created: int rtt_minmax(int rto); void determine_rto(struct rtt_info* rtti_ptr); void set_alarm(struct sliding_win *sld_win_buff, struct rtt_info* rtti_ptr, struct win_probe_rto_info* win_prob_rti_ptr); First method, int rtt_minmax(int rto); is similar to the one introduced in the book. Second method, void determine_rto(struct rtt_info* rtti_ptr); is amalgamation of rtt_init and rtt_stop. Secondly, rtt_ts which determine the difference in millisec has been moved to process_client_ack method in the program. For RTT determination the difference in current day time at the receipt of is compared with corresponding sent segment. For retransmited segments RTT determination and RTO determination are not done following Kern/Patridge algorithm. 3. TCP Mechanisms: ------------------- 3.1 Sliding Window: A sliding window has been maintained on both server and receiver side. The implementaion is done using a linked list whose reference is stored in sliding window buffer, struct sliding_win { uint32_t advt_rcv_win_size; /* receiving window size */ uint32_t cwin_size; /* congestion window size */ struct win_segment *buffer_head; /* sliding window head pointer */ uint32_t no_of_seg_in_transit; /* no of segments in transit */ uint32_t no_ack_in_rtt; /* no of acknowledgement received in an RTT */ uint32_t ssthresh; /* slow start threshold */ uint32_t fin_ack_received; }; For Automatic repeat request, retransmission timer is used. Once a time out happens retransmission is performed. Secondly a persistance timer has also been implemented, which check for receiver window deadlock. In this scenario, a window probe message is generated which is sent with constant window probing interval. This has been implemented in method "file_transfer". 3.2 Congestion Control: 3.2.1. Slow Start: Slow start functionality has been implemented in process_client_ack method. 3.2.2. Congetion avoidance: This functionality has been implemented in process_client_ack method. 3.2.3. Time out: This use case has been implemented in file_transfer method 3.2.4. Fast Recovery: This functionality has been implemented in process_client_ack method. 4. TCP connection termination: For this a fin flag has been used in trasmitted data, header struct tcp_header{ uint32_t seq_num; uint32_t ack_num; uint16_t ack; uint16_t syn; uint16_t fin; uint32_t rcv_wnd_size; }; First server sends a FIN along with the last data payload. Client responds this by sending an combine ack and fin with both flags set. Server again responds with an acknowledgemet with an ack set and seqeunce no :0. This information, presence of seqeunce no 0 is used by client to termination the processing. If the last ack from server is lost, then a time out has been implemented on client side which wiil terminate the connection after 3 sec. <file_sep>#include <string.h> #include <math.h> #include <stdio.h> #include "unpifiplus.h" //------------------------ALL STRUCT DEFINITIONS----------------------- struct tcp_header{ uint32_t seq_num; uint32_t ack_num; uint16_t ack; uint16_t syn; uint16_t fin; uint32_t rcv_wnd_size; }; // datagram payload : size 512 bytes struct tcp_segment{ struct tcp_header head; char data[368]; }; struct win_segment{ struct tcp_segment tcp_seg; struct win_segment *next_seg; uint32_t no_of_sent; //no use on client side uint32_t timeout; //no use on client side }; struct buffer{ uint32_t window_size_max; uint32_t window_size_avilable; struct win_segment *buffer_head; struct win_segment *buffer_tail; uint32_t last_consumed_seg_seq; }; struct consumed_list{ int item; struct consumed_list* next; }; //------------------END OF ALL STRUCT DEFINITIONS----------------------- //-------------------GLOBAL VARIABLES----------------------------------- //For thread safe pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //Make the root global, otherwise consumer thread can't see struct win_segment *root_win_seg = NULL; struct consumed_list *root_consumed_list = NULL; uint32_t cur_win_size; //make current window size global, so that everyone can access it uint32_t cur_ack_num = 2; uint32_t actual_win_size; uint32_t last_consumed_num = 1; int isFin = 0; //------------------END OF GLOBAL VARIABLES----------------------------- //------------------ALL METHODS DECLEARATIONS--------------------------- /*Function declerations*/ struct tcp_segment* create_pac(uint32_t seq_num, uint32_t ack_num, uint8_t ack, uint8_t syn, uint8_t fin,uint32_t rcv_wnd_size, char *msg);//my faking construction method to creat a tcp_segment void reset_pac(struct tcp_segment *tcp_seg,uint32_t seq_num, uint32_t ack_num, uint8_t ack, uint8_t syn, uint8_t fin,uint32_t rcv_wnd_size,char *msg);// reset items inside tcp_segment struct struct win_segment* create_win_seg(struct tcp_segment* tcp_segg); void produce_window(struct win_segment **,struct tcp_segment *); void update_ack_win_size(struct win_segment* node); int consume_from_root(struct win_segment** root); /*Methods to maintein the consumed list*/ struct consumed_list* creat_consume_list_node(int item); void add_consumed_list_node(struct consumed_list **root,int item); struct consumed_list* is_consume_list(struct consumed_list *root,int item); /*Methods to maintein the consumed list*/ int drop(float i); static void * consumer_thread(void *); /*End of function declerations*/ //----------------END OF ALL METHODS DECLEARATIONS---------------------- int main() { FILE *fp_param; char *mode = "r"; char data[32]; char ip_str[16]; int opt_val_set = 1; int counter, read_count,i; unsigned long check1, check2; char test[32]; int is_server_local = 0; char *separator = "-----------------------------------------------------"; struct param{ char serv_ip_addr[16]; short serv_port; char fname[32]; int rcv_win_size; int rnd_seed; float p_loss; int mean; } input_param; struct sockaddr_in *clientaddr_ptr, *client_snet_mask_ptr, fin_cli_smask, fin_cliaddr, clientaddr, client_snet_mask, fin_cliaddr_prnt, servaddr_prnt, servaddr_1, servaddr; struct ifi_info *ifi, *ifihead; int sockfd; socklen_t addr_size; struct tcp_segment *send_seg,*recv_seg; fd_set rset; struct timeval timeout; int maxfd; pthread_t tid; int *iptr;//this int[] is the argument of the consuming thread //iptr[0] = mean, iptr[1] = sockfd // TEST VARIABLE int conn_res = 0; int sel_res; // Read the parameter file, client.in if((fp_param = fopen("client.in", mode)) == NULL ) { fprintf(stderr, "Parameter File, client.in can't be opened\n"); exit(1); } counter = 0; memset(&input_param,0,sizeof(input_param)); while( (read_count = fscanf(fp_param, "%s", data )) != EOF) { if( read_count != 1 ) { fprintf(stderr, "Input parameter are not maintained correctly in client.in \n"); exit(1); } ++counter; switch(counter) { case 1: strcpy(input_param.serv_ip_addr, data); printf("IP address: %s\n", input_param.serv_ip_addr ); break; case 2: input_param.serv_port = (short)atoi(data); printf("Port: %d\n", input_param.serv_port); break; case 3: strcpy(input_param.fname, data); printf("File name: %s\n", input_param.fname ); break; case 4: input_param.rcv_win_size = atoi(data); actual_win_size = cur_win_size = input_param.rcv_win_size; printf("Window size: %d\n", cur_win_size ); break; case 5: input_param.rnd_seed = atoi(data); printf("seed: %d\n", input_param.rnd_seed); break; case 6: input_param.p_loss = atof(data); printf("Probability: %f\n", input_param.p_loss ); break; case 7: input_param.mean = atoi(data); iptr = malloc(sizeof(int)); *iptr = input_param.mean; printf("Mean: %d\n", *iptr ); break; default: fprintf(stderr, "Invalid no of parameters\n"); exit(1); } memset(data, 0, sizeof(data)); } // Prepare server address information //call srand to initialize the random function srand(input_param.rnd_seed); printf("IP ADDRESS LENGTH: %d\n",(int)strlen(input_param.serv_ip_addr)); if( input_param.serv_port != 0 && input_param.serv_ip_addr != 0) { bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(input_param.serv_port); if(inet_pton(AF_INET, input_param.serv_ip_addr, &servaddr.sin_addr) != 1 ) { fprintf(stderr, "Presentation to network address conversion error:%s\n", strerror(errno)); exit(1); } } // Read interface infomration memset(&clientaddr,0,sizeof(clientaddr)); memset(&fin_cliaddr,0,sizeof(fin_cliaddr)); memset(&client_snet_mask,0,sizeof(client_snet_mask)); memset(&fin_cli_smask,0,sizeof(fin_cli_smask)); memset(&fin_cliaddr_prnt,0,sizeof(fin_cliaddr_prnt)); memset(&servaddr_prnt,0,sizeof(servaddr_prnt)); fprintf(stdout, "%s\n", separator); // Check local interfaces to determine client IP address fprintf(stdout, "Available Local Interface:\n"); for(ifi = ifihead = Get_ifi_info_plus(AF_INET, 1); ifi != NULL ; ifi = ifi->ifi_next) { clientaddr_ptr = (struct sockaddr_in *)ifi->ifi_addr; client_snet_mask_ptr = (struct sockaddr_in *)ifi->ifi_ntmaddr; memcpy(&clientaddr,clientaddr_ptr,sizeof(*clientaddr_ptr)); memcpy(&client_snet_mask,client_snet_mask_ptr,sizeof(*client_snet_mask_ptr)); fprintf(stdout, "Intarface Name: %s\n", ifi->ifi_name ); if(ifi->ifi_ntmaddr != NULL) { fprintf(stdout, "Subnet Mask: %s\n", sock_ntop_host((SA *)&client_snet_mask, sizeof(client_snet_mask)) ); } if(ifi->ifi_addr != NULL) { fprintf(stdout, "IP Address: %s\n", sock_ntop_host((SA *)&clientaddr, sizeof(clientaddr)) ); } fprintf(stdout, "%s\n", separator); // check if server belongs to same network check1 = client_snet_mask.sin_addr.s_addr & clientaddr.sin_addr.s_addr; check2 = client_snet_mask.sin_addr.s_addr & servaddr.sin_addr.s_addr; if( check1 == check2 ) { is_server_local = 1; // set if a match is found if(fin_cli_smask.sin_addr.s_addr == 0 && fin_cliaddr.sin_addr.s_addr == 0) { fin_cli_smask = client_snet_mask; fin_cliaddr = clientaddr; } if(fin_cli_smask.sin_addr.s_addr < client_snet_mask.sin_addr.s_addr) { fin_cli_smask = client_snet_mask; fin_cliaddr = clientaddr; } } } // If server is not local, assign last entry in the ifi_info result as client address if(is_server_local == 0) { fprintf(stdout, "%s\n", separator); fprintf(stdout, "Info: server is not local; client will be assigned IP address randomly\n"); fin_cli_smask = client_snet_mask; fin_cliaddr = clientaddr; } else { fprintf(stdout, "%s\n", separator); fprintf(stdout, "Info: server is local to the client network\n"); } fprintf(stdout, "Chosen Subnet Mask: %s\n", inet_ntop(AF_INET, &fin_cli_smask.sin_addr, ip_str, sizeof(ip_str))); fprintf(stdout, "Chosen IPclient: %s\n", inet_ntop(AF_INET, &fin_cliaddr.sin_addr, ip_str, sizeof(ip_str))) ; fprintf(stdout, "Given IPserver: %s\n", inet_ntop(AF_INET, &servaddr.sin_addr, ip_str, sizeof(ip_str))) ; fprintf(stdout, "Server Port no: %d\n", ntohs(servaddr.sin_port) ); // Create UDP socket if((sockfd = socket(AF_INET, SOCK_DGRAM,0)) == -1) { fprintf(stderr, "Socket creation error: %s\n", strerror(errno)); exit(1); } // give sockfd to iptr[1], consumer thread has to send server a msg //when window size changes from 0 to available // set DONOTROUTE option if server is local if(is_server_local == 1) { if(setsockopt(sockfd, SOL_SOCKET, SO_DONTROUTE, &opt_val_set, sizeof(opt_val_set)) == -1) { fprintf(stderr, "Socket set option error: %s\n", strerror(errno)); exit(1); } } // Bind UDP socket fin_cliaddr.sin_port = htons(0); /*assign 0 as the port no which we be replaced by kernel so other ephemeral port*/ if((bind(sockfd, (SA*)(&fin_cliaddr), sizeof(fin_cliaddr))) == -1) { fprintf(stdout, "Socket bind error: %s\n", strerror(errno)); } // Get assigned port no after bind addr_size = sizeof(fin_cliaddr_prnt); if(getsockname(sockfd, (SA*)(&fin_cliaddr_prnt), &addr_size) == -1) { fprintf(stderr, "Get socket name error: %s\n", strerror(errno)); exit(1); } // Print ephemeral port no assigned to client fprintf(stdout, "%s\nClient address information after binding:\n", separator); fprintf(stdout, "Client IP address: %s\n", inet_ntop(AF_INET, &fin_cliaddr_prnt.sin_addr, ip_str, sizeof(ip_str))) ; fprintf(stdout, "Client ephemeral port no: %d\n", ntohs(fin_cliaddr_prnt.sin_port)); // Connect socket to server if((conn_res = connect(sockfd, (SA *)&servaddr, sizeof(servaddr))) == -1 ) { fprintf(stderr, "Socket connects to servaddr error: %d\n", errno); exit(1); } // Get server socket information if(getpeername(sockfd, (struct sockaddr*)(&servaddr_prnt), &addr_size) == -1) { fprintf(stdout, "Get server/peer info error: %s\n", strerror(errno)); } fprintf(stdout, "%s\nServer address information after connect:\n", separator); fprintf(stdout, "Server IP address: %s\n", inet_ntop(AF_INET, &servaddr_prnt.sin_addr, ip_str, sizeof(ip_str))) ; fprintf(stdout, "Server port no: %d\n", ntohs(servaddr_prnt.sin_port)); // Initiate Handshaking, create a seg for sending // and dont forget to give recv_seg a memory space char tempfilename[MAXLINE]; strcpy(tempfilename, input_param.fname); printf("\nFile requested: %s\n", tempfilename); send_seg = create_pac(0,0,0,1,0,0,tempfilename); recv_seg = create_pac(0,0,0,0,0,0,NULL); //as a purpose to avoid confusion, let's use a while(1) exclusively //for the three way handshake, one thing to notice is, if the client //damps the 1st datagram 3 times in a row, then print out what's //going on, and exit the program counter = 0; while(1){ if(drop(input_param.p_loss)){ // drop the very 1st datagram counter++; printf("The very 1st SYN is lost: No.%d.\n\n",counter); if(counter == 12){ printf("Sending 1st SYN failed 3 times in row, exit!!!\n"); exit(1); } continue; }else{ // the very 1st datagram not dropped counter = 0; send_syn: if((send(sockfd, send_seg, sizeof(*send_seg), 0)) < 0 ){ fprintf(stderr, "\nSYN message for connecttion establishment failed: %s\n", strerror(errno)); exit(1); } else{ fprintf(stdout, "\nFirst handshaking message for connection establishment sent successfully\n"); } } fprintf(stdout, "\nWating for second handshake from server\n"); //The ACK from server is dropped if(drop(input_param.p_loss)){ if(recv(sockfd, recv_seg, sizeof(*recv_seg), 0) < 0){ fprintf(stderr, "\nError in receiving second handshake from server: %s\n", strerror(errno)); exit(1); } printf("ACK from server is dropped. Client times out, a new SYN will be send agian...\n\n"); goto send_syn; }else{//The ACK from server not dropped recv_ack: if(recv(sockfd, recv_seg, sizeof(*recv_seg), 0) < 0){ fprintf(stderr, "\nError in receiving second handshake from server: %s\n", strerror(errno)); exit(1); } // second handshake received, update server port address servaddr_prnt.sin_port = (atoi(recv_seg->data)); printf("\nnew port num from server is %d,\n", servaddr_prnt.sin_port); if((conn_res = connect(sockfd, (SA *)&servaddr_prnt, sizeof(servaddr_prnt))) == -1 ){ fprintf(stderr, "Socket connect error (line 368): %s\n", strerror(errno)); exit(1); } fprintf(stdout, "Socket connect result: %d\n", conn_res); // Get server socket information if(getpeername(sockfd, (struct sockaddr*)(&servaddr), &addr_size) == -1){ fprintf(stdout, "Get server/peer info error: %s\n", strerror(errno)); } fprintf(stdout, "%s\nServer address information after reconnect:\n", separator); fprintf(stdout, "Server IP address: %s\n", inet_ntop(AF_INET, &servaddr.sin_addr, ip_str, sizeof(ip_str))) ; fprintf(stdout, "Server port no: %d\n", ntohs(servaddr.sin_port)); } //The second ACK from client is dropped if(drop(input_param.p_loss)){ printf("The response ACK of client(3rd handshake) is dropped, wait again for ACK from server...\n\n"); goto recv_ack; }else{//The second ACK from client is not dropped reset_pac(send_seg,0,2,1,0,0,input_param.rcv_win_size,NULL); if((send(sockfd, send_seg, sizeof(*send_seg), 0)) < 0 ){ fprintf(stderr, "\n3rd handshaking message sent failed: %s\n", strerror(errno)); exit(1); } else{ fprintf(stdout, "\nThird handshaking message for connection establishment sent successfully\n"); break; } } } /*File transfer starts from here!!!*/ printf("\n3 way Handshake finished,File transfer gets started......\n"); /****************File transmission starts from here*******************************/ //1st: create a consumer thread to consume buffer pthread_create(&tid,NULL,&consumer_thread,iptr); //2nd: I know Steve is the least professional programmer, but I need //the timer to time out the Recv method here // struct timeval tv; // tv.tv_sec = 10; // tv.tv_usec = 0; // setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,(char *)&tv,sizeof(struct timeval)); isFin = 0; //flag to check if fin is received int isFull = 0;//flag to check if window is full //2nd: a while(1), which read the incoming data packet and simulate drop while(1){ //the received packet if(drop(input_param.p_loss)){ if(recv(sockfd, recv_seg, sizeof(*recv_seg), 0)==-1){ // if( errno == EAGAIN && errno == EWOULDBLOCK){ // printf("Client recv time out, retransmit an ack\n"); // goto ack; // }else{ printf("recv error:%s\n", strerror(errno)); exit(1); //} } printf("Received datagram is dropped.\n\n"); if((recv_seg->head.fin == 1)&&(recv_seg->head.seq_num == 0)){ sleep(3); printf("Time wait compeleted\n"); break; } continue; }else{ reset_pac(recv_seg,0,0,0,0,0,0,NULL); if(recv(sockfd, recv_seg, sizeof(*recv_seg), 0)==-1){ // if( errno == EAGAIN && errno == EWOULDBLOCK){ // printf("Client recv time out, retransmit an ack\n"); // goto ack; // }else{ printf("recv error:%s\n", strerror(errno)); exit(1); //} } printf("Received datagram is accepted.\n"); printf("Seqence num is %d\n\n.",recv_seg->head.seq_num); //Lock the producer thread, since produce is gonna //put the received seg into window if(pthread_mutex_lock(&mutex) != 0){ printf("Lock error:%s\n",strerror(errno)); exit(1); } //get the seq_num and give to cur_ack_num if(cur_ack_num == recv_seg->head.seq_num) { cur_ack_num = recv_seg->head.seq_num + 1; //check if it's a fin with seq_num != 0 if((recv_seg->head.fin == 1)&&(recv_seg->head.seq_num != 0)){ //last datagram //printf("Last Payload received from server, send a fin back to server.\n"); //reset_pac(send_seg,0,cur_ack_num,1,0,1,0,NULL);// ack_num, ack and fin isFin = 1; } } //real fin from server if((recv_seg->head.fin == 1)&&(recv_seg->head.seq_num == 0)){ printf("Fin received\n"); //unlock this thread if(pthread_mutex_unlock(&mutex) != 0){ printf("Unlock error:%s\n",strerror(errno)); exit(1); } break; } //means the window is full, try to send //an ACK by all means if(cur_win_size == 0) { printf("\nWindow is full\n"); isFull = 1; reset_pac(send_seg,0,0,0,0,0,0,NULL);// ack_num, ack and fin Send(sockfd,send_seg,sizeof(*send_seg),0); //unlock this thread if(pthread_mutex_unlock(&mutex) != 0) { printf("Unlock error:%s\n",strerror(errno)); exit(1); } continue; } else { isFull = 0; } produce_window(&root_win_seg,recv_seg); printf("Current window size is:%d.",cur_win_size); //unlock this thread if(pthread_mutex_unlock(&mutex) != 0){ printf("Unlock error:%s\n",strerror(errno)); exit(1); } } //Send the ACK ack: if(drop(input_param.p_loss)){ printf("The responding ACK is dropped.\n\n"); continue; }else{ //the reason to lock this up is because, two threads share // cur_ack_num and cur_win_size printf("The responding ACK will be sent.\n\n"); if(pthread_mutex_lock(&mutex) != 0){ printf("Sending ACK lock error:%s\n",strerror(errno)); exit(1); } if(!isFin && !isFull){ //happens when it's not a fin nor a fullwindow reset_pac(send_seg,0,0,0,0,0,0,NULL); reset_pac(send_seg,0,cur_ack_num,1,0,0,cur_win_size,NULL); printf("Sending ACK, ack_num is %d, and current window size is %d.\n",cur_ack_num,cur_win_size); } //if(isFull) // printf("Recv Window is full, send an alert to server\n"); if(isFin) { reset_pac(send_seg,0,cur_ack_num,1,0,1,0,NULL);// ack_num, ack and fin printf("Last datapayload received, send the response to server\n"); } Send(sockfd,send_seg,sizeof(*send_seg),0); if(pthread_mutex_unlock(&mutex) != 0){ printf("Sending ACK Unlock error:%s\n",strerror(errno)); exit(1); } } } //file transfer finished printf("File transmission finished, Main thread JOB DONE!!\n"); pthread_join(tid,NULL); return 0; } //--------------------------All THE SUB ROUTINES------------------------- /*Consumer thread, consume items on the receiver window*/ static void * consumer_thread(void *arg){ struct timeval tv; struct timespec ts; double sleeptime; int *mean = (int *)arg; // struct tcp_segment *send_pac = NULL; // send_pac = create_pac(0,0,0,0,0,0,NULL); /* if(pthread_detach(pthread_self())) * err_sys("Error detaching the thread: %s\n", strerror(errno)) ; */ while(1){ printf("mean: %d\n", *mean); sleeptime = -1 * (*mean) * log((double)rand()/(double)RAND_MAX); if(gettimeofday(&tv,NULL) < 0){ printf("Get day time error:%s\n",strerror(errno)); exit(1); } ts.tv_sec = tv.tv_sec; ts.tv_nsec = tv.tv_usec * 1000; ts.tv_sec += ceil(sleeptime/1000.0); //lock the thread if(pthread_mutex_lock(&mutex) != 0){ printf("Lock error:%s\n",strerror(errno)); exit(1); } //let this thread sleep for ts amount of time printf("\n----------Consumer Thread sleeps %f milliseconds--------\n", sleeptime); pthread_cond_timedwait(&cond,&mutex,&ts); //sleep(sleeptime/1000); printf("\n----------Consumer Thread wakes up--------\n"); //Call the consume_from_root method to consume the win_seg inside //the window, also update the cur_win_size variable // returns a 1, means that last datagram has been received if(consume_from_root(&root_win_seg)){ // reset_pac(send_pac,0,0,1,0,0,cur_win_size,NULL); // Send(*sockfd,send_pac,sizeof(*send_pac), 0); printf("\nThe last datagram has been consumed,consumer thread JOB DONE!!!\n"); if(pthread_mutex_unlock(&mutex) != 0) { printf("Unlock error:%s\n",strerror(errno)); } break; } // printf("\n----------Consuming process ended--------\n"); //unlock this thread if(pthread_mutex_unlock(&mutex) != 0){ printf("Unlock error:%s\n",strerror(errno)); exit(1); } }//end of while(1) return NULL; } /*This method consumers item on the window(win_segment linked list) */ /*and update the global var cur_win_size, and add the comsumed seq_num*/ /*to the consumed list(struct consumed_list linked list)*/ /*return 1 if it's last datagram, otherwise 0*/ int consume_from_root(struct win_segment** root){ int val = 0; if((*root) == NULL){ printf("Nothing to consume at all!!\n"); return val; } if((*root)->tcp_seg.head.seq_num - last_consumed_num != 1){ printf("The first segment on window is not in order, can't consume\n"); return val; } printf("there are things to consume!!\n"); int last_item = 0,i = 1; struct win_segment *tempNode; while((*root)->next_seg != NULL){ if((((*root)->tcp_seg.head.seq_num - last_item) != 1) && i != 1){ printf("Item num not in sequence, stop consuming\n"); return 0; } printf("The consumed sequence is %d,\nContent is \n\"%s\"\n\n",(*root)->tcp_seg.head.seq_num,(*root)->tcp_seg.data); add_consumed_list_node(&root_consumed_list,(*root)->tcp_seg.head.seq_num); // add this seq_num to the consumed_list last_item =(*root)->tcp_seg.head.seq_num; last_consumed_num = last_item; tempNode = (*root); i++; (*root) = (*root)->next_seg; free(tempNode); cur_win_size++; actual_win_size++; } if((*root)->tcp_seg.head.fin) val = 1; if(i==1){ printf("Consumed only one item, No.%d,\nContent is \n\"%s\"\n",(*root)->tcp_seg.head.seq_num,(*root)->tcp_seg.data); add_consumed_list_node(&root_consumed_list,(*root)->tcp_seg.head.seq_num); // add this seq_num to the consumed_list last_consumed_num = (*root)->tcp_seg.head.seq_num; } else{ if(((*root)->tcp_seg.head.seq_num - last_item) != 1) return 0; printf("The consumed sequence is %d,\ncontent is \n\"%s\"\n",(*root)->tcp_seg.head.seq_num,(*root)->tcp_seg.data); add_consumed_list_node(&root_consumed_list,(*root)->tcp_seg.head.seq_num); // add this seq_num to the consumed_list last_consumed_num = (*root)->tcp_seg.head.seq_num; } free((*root)); (*root) = NULL; cur_win_size++; actual_win_size++; return val; } /*this sub basically just add tcp_segment to root_win_seg in order */ /*This sub runs on the main thread, also update cur_win_size global var*/ void produce_window(struct win_segment **root,struct tcp_segment *seg){ //before putting anything to recv window, check if the incoming seg_num //has been on the consumed list, if so, then just return without //producing anything if(seg->head.seq_num == 0 && seg->head.fin != 1 ) return; if(is_consume_list(root_consumed_list,seg->head.seq_num) != NULL){// on the list, just return return; } int item = seg->head.seq_num; struct win_segment *tempNode,*rootcopy; if((*root) == NULL){ tempNode = create_win_seg(seg); (*root) = tempNode; actual_win_size--; if(cur_ack_num == item + 1) cur_win_size--; printf("Received segment No.%d put in receiving window\n",seg->head.seq_num); return; } //if the incoming data has the same seq_num as root, then just return if(item == ((*root)->tcp_seg.head.seq_num)) return; if(item < ((*root)->tcp_seg.head.seq_num)){ tempNode = create_win_seg(seg); tempNode->next_seg = (*root); (*root) = tempNode; actual_win_size--; if(cur_ack_num == item + 1) cur_win_size--; printf("Received segment No.%d put in receiving window\n",seg->head.seq_num); update_ack_win_size(tempNode); return; } if((*root)->next_seg == NULL){ tempNode = create_win_seg(seg); (*root)->next_seg = tempNode; actual_win_size--; if(cur_ack_num == item + 1) cur_win_size--; printf("Received segment No.%d put in receiving window\n",seg->head.seq_num); update_ack_win_size(tempNode); return; } rootcopy = *root; struct win_segment *tnode; while(rootcopy->next_seg != NULL){ //if the incoming data has the same seq_num as root, then just return if(item == (rootcopy->next_seg->tcp_seg.head.seq_num)) return; if(item < (rootcopy->next_seg->tcp_seg.head.seq_num)){ tempNode = create_win_seg(seg); tnode = rootcopy->next_seg; rootcopy->next_seg = tempNode; tempNode->next_seg = tnode; actual_win_size--; if(cur_ack_num == item + 1) cur_win_size--; printf("Received segment No.%d put in receiving window\n",seg->head.seq_num); update_ack_win_size(tempNode); return; } else{ rootcopy = rootcopy->next_seg; } } tempNode = create_win_seg(seg); rootcopy->next_seg = tempNode; actual_win_size--; if(cur_ack_num == item + 1) cur_win_size--; printf("Received segment No.%d\n",seg->head.seq_num); update_ack_win_size(tempNode); } void update_ack_win_size(struct win_segment* node) { if(node->tcp_seg.head.seq_num == cur_ack_num - 1) { node = node->next_seg; while(node != NULL) { if(node->tcp_seg.head.seq_num == cur_ack_num) { cur_ack_num++; actual_win_size--; cur_win_size--; if(node->tcp_seg.head.fin == 1 && node->tcp_seg.head.seq_num != 0) isFin = 1; node = node->next_seg; } else { break; } } } } /*Faking constructor to create a tcp_segment*/ struct tcp_segment* create_pac(uint32_t seq_num, uint32_t ack_num, uint8_t ack, uint8_t syn, uint8_t fin,uint32_t rcv_wnd_size,char *msg){ struct tcp_segment *node = malloc(sizeof(struct tcp_segment)); node->head.seq_num = (seq_num); node->head.ack_num = (ack_num); node->head.ack = (ack); node->head.syn = (syn); node->head.fin = (fin); node->head.rcv_wnd_size = (rcv_wnd_size); if(msg!=NULL){ strcpy(node->data,msg); } else node->data[0] = '\0'; return node; } /*Faking constructor to create a win_segment*/ struct win_segment* create_win_seg(struct tcp_segment* tcp_segg){ struct win_segment *node = malloc(sizeof(struct win_segment)); node->tcp_seg = *tcp_segg; node->next_seg = NULL; return node; } /*Reset the content inside a tcp_segment*/ void reset_pac(struct tcp_segment *tcp_seg,uint32_t seq_num, uint32_t ack_num, uint8_t ack, uint8_t syn, uint8_t fin,uint32_t rcv_wnd_size,char *msg){ tcp_seg->head.seq_num = (seq_num); tcp_seg->head.ack_num = (ack_num); tcp_seg->head.ack = (ack); tcp_seg->head.syn = (syn); tcp_seg->head.fin = (fin); tcp_seg->head.rcv_wnd_size = (rcv_wnd_size); if(msg!=NULL){ strcpy(tcp_seg->data,msg); } else tcp_seg->data[0] = '\0'; } /*Faking constructor to create a consumed_list node*/ struct consumed_list* creat_consume_list_node(int item){ struct consumed_list *node; node = malloc(sizeof(struct consumed_list)); node->item = item; node->next = NULL; return node; } /*Method to add an item to a consumed_list(linked list)*/ void add_consumed_list_node(struct consumed_list **root,int item){ struct consumed_list *tempNode,*nextNode; if((*root) == NULL){ tempNode = creat_consume_list_node(item); (*root) = tempNode; return; } nextNode = *root; while(nextNode->next != NULL){ nextNode = nextNode->next; } tempNode = creat_consume_list_node(item); nextNode->next = tempNode; } /*Method to check if a given item(seq_num) is on the consumed_list*/ /*if yes, return the addr or that item, otherwise return NULL*/ struct consumed_list* is_consume_list(struct consumed_list *root,int item){ if(root==NULL) return NULL; if(root->item == item){ return root; }else{ while(root->next != NULL){ root = root->next; if(root->item == item) return root; } return NULL; } } /*very simple function for probablistic test*/ /* return 1 means drop, 0 means not*/ int drop(float i){ float tempf = (double)rand()/(double)RAND_MAX; printf("\n\n\nCurrent Probability is %f\n",tempf); if(tempf < i) return 1; else return 0; } <file_sep>#include <stdio.h> #include <math.h> #include "unpifiplus.h" #include <sys/time.h> #include <setjmp.h> #define INITIAL_SEQ_NO 1 /* define RTT related macros */ #define RTT_RXTMIN 1000 #define RTT_RXTMAX 3000 #define RTT_MAXNREXMT 12 /*****************************************VARIABLES FOR CHILD PROCESS*****************************************/ sigjmp_buf jmpbuf; struct tcp_header{ uint32_t seq_num; uint32_t ack_num; uint16_t ack; uint16_t syn; uint16_t fin; uint32_t rcv_wnd_size; }; // datagram payload : size 512 bytes struct tcp_segment{ struct tcp_header head; char data[368]; }; struct win_segment{ struct tcp_segment segment; struct win_segment *next_segment; /* next segment in the window */ uint32_t no_of_sends; /* no of retransmission */ uint64_t time_of_send; /* time msec since LINUX initial time */ uint32_t no_of_ack_rcvd; /* no of ack received for segement */ }; struct sliding_win { uint32_t advt_rcv_win_size; /* receiving window size */ uint32_t cwin_size; /* congestion window size */ struct win_segment *buffer_head; /* sliding window head pointer */ uint32_t no_of_seg_in_transit; /* no of segments in transit */ uint32_t no_ack_in_rtt; /* no of acknowledgement received in an RTT */ uint32_t ssthresh; /* slow start threshold */ uint32_t fin_ack_received; }; struct rtt_info { int rtt; /* current recent rtt in msec */ int srtt; /* smoothed rtt estimator multiplied by 8 */ int rttvar; /* estimated mean deviator multiplied by 4*/ int rto; /* current rto in msec */ }; struct win_probe_rto_info { int win_probe_time_out; }; /*****************************************VARIABLES FOR CHILD PROCESS*****************************************/ /*****************************************VARIABLES FOR PARENT PROCESS*****************************************/ struct client{ struct client* next_client; uint32_t ip; uint16_t port_num; int pipefd; pid_t pid; }; struct client *head; /***********************************VARIABLES FOR PARENT PROCESS*************************************/ /***********************************VARIABLES COMMON*************************************/ struct nw_interface{ int sockfd; // socket file descriptor struct sockaddr *ifi_addr; //IP address bound to socket struct sockaddr *ifi_maskaddr; //network mask struct sockaddr *ifi_subaddr; //subnet address }; /***********************************VARIABLES COMMON*************************************/ /***********************************CLIENT QUEUE HANDLING FUNCTIONS*************************************/ struct client* is_client_present(struct client* r,uint32_t ip,uint16_t port_num); struct client* create_cli(int32_t ip,uint16_t port_num,int pipefd,pid_t pid); void add_cli(struct client** r,int32_t ip,uint16_t port_num,int pipefd,pid_t pid); void rm_cli(pid_t child_pid); /***********************************CLIENT QUEUE HANDLING FUNCTIONS*************************************/ /***********************************SLIDING WINDOW HANDLING FUNCTIONS*************************************/ void add_win_seg_to_sld_win(struct sliding_win* sld_win_buff, struct win_segment* win_seg); void send_tcp_segment(struct sliding_win* sld_win_buff_ptr, struct win_segment *win_seg_ptr, int conn_sock_fd, struct sockaddr_in* cliaddr, struct rtt_info *rtti_ptr, struct win_probe_rto_info* win_prob_rti_ptr, int is_set_alarm_req); void remove_win_seg_from_sld_win(struct sliding_win* sld_win_buff, struct win_segment* win_seg_ptr); /***********************************SLIDING WINDOW HANDLING FUNCTIONS*************************************/ /***********************************RTT RELATED FUNCTIONS*************************************/ int rtt_minmax(int rto); void determine_rto(struct rtt_info* rtti_ptr); void set_alarm(struct sliding_win *sld_win_buff, struct rtt_info* rtti_ptr, struct win_probe_rto_info* win_prob_rti_ptr); void sig_alrm(int signo); /***********************************RTT RELATED FUNCTIONS*************************************/ /***********************************FILE TRANSFER FUNCTION*************************************/ void file_transfer(char *filename, struct nw_interface* list,int num, int i, struct sockaddr_in *clientaddr,int winsize, int pipefd); void process_client_ack(struct sliding_win *sld_win_buff, struct tcp_segment *tcp_seg_ptr, struct rtt_info *rtti, struct win_probe_rto_info *win_probe_rti, int conn_sock_fd, struct sockaddr_in* cliaddr); void sig_child(int sig_no); /***********************************FILE TRANSFER FUNCTION*************************************/ int main() { int serv_port_num, advt_win_size; int i = 0; const char input_file[] = "server.in"; char ip_str[16]; int sockfd,maxfd, pid; struct ifi_info *ifi; struct sockaddr_in *sa = NULL, clientaddr, *clientaddr_ptr = NULL; fd_set rset; FD_ZERO(&rset); struct tcp_segment rcvd_seg; int no_of_interfaces = 0; /* Initilizing the client list*/ head = NULL; FILE *file = fopen ( input_file, "r" ); //'r' is just for reading /* Get server input parameters*/ if ( file != NULL ) { char line [128]; while ( fgets ( line, sizeof line, file ) != NULL ) { if(i==0) sscanf(line, "%d", &serv_port_num); else sscanf(line, "%d", &advt_win_size); i++; //fputs ( line, stdout ); } fclose ( file ); } else { perror ( input_file ); // file open is wrong } for(ifi = get_ifi_info_plus(AF_INET,1); ifi != NULL; ifi = ifi->ifi_next) no_of_interfaces++; struct nw_interface nw_interfaces[no_of_interfaces]; /* Print and bind all unicast IP interface at server*/ i = 0; for(ifi = get_ifi_info_plus(AF_INET,1); ifi != NULL; ifi = ifi->ifi_next){ if(ifi->ifi_flags != IFF_BROADCAST){ // make sure the program only bind to unicast IP addresses sockfd = Socket(AF_INET,SOCK_DGRAM,0); sa = (struct sockaddr_in *) ifi->ifi_addr; sa->sin_family = AF_INET; sa->sin_port = htons(serv_port_num); Bind(sockfd,(SA *)sa, sizeof(*sa)); nw_interfaces[i].sockfd = sockfd; nw_interfaces[i].ifi_addr = ifi->ifi_addr; //Obtain IP address nw_interfaces[i].ifi_maskaddr = ifi->ifi_ntmaddr; //Obtain network mask //calculate the subnet address using bit-wise calculation //between IP address and its network mask struct sockaddr_in *ip = (struct sockaddr_in *)ifi->ifi_addr; struct sockaddr_in *ntm = (struct sockaddr_in *)ifi->ifi_ntmaddr; uint32_t ipint = ip->sin_addr.s_addr; uint32_t ntmint = ntm->sin_addr.s_addr; uint32_t subint = ipint & ntmint; //bit-wise calculation struct sockaddr_in sub; bzero(&sub,sizeof(sub)); sub.sin_addr.s_addr = subint; sub.sin_family = AF_INET; nw_interfaces[i].ifi_subaddr = (SA*)&sub; //now since everything inside nw_interfaces is obtained //let's print out the info in the required format printf("\nInterface No.%d is %s.\n",i+1,ifi->ifi_name); printf("IP address is %s.\n",Sock_ntop_host(nw_interfaces[i].ifi_addr, sizeof(*nw_interfaces[i].ifi_addr))); printf("Network mask is %s.\n",Sock_ntop_host(nw_interfaces[i].ifi_maskaddr, sizeof(*nw_interfaces[i].ifi_maskaddr))); printf("Subnet address is %s.\n",Sock_ntop_host(nw_interfaces[i].ifi_subaddr, sizeof(*nw_interfaces[i].ifi_subaddr))); } i++; } while(1) { //First of all, let's find the biggest file descriptor maxfd = 0; for(i=0;i<no_of_interfaces;i++){ FD_SET(nw_interfaces[i].sockfd,&rset); if(nw_interfaces[i].sockfd > maxfd) maxfd = nw_interfaces[i].sockfd; } maxfd = maxfd+1; if(select(maxfd,&rset,NULL,NULL,NULL) < 0) { if(errno == EINTR) { continue; } else { fprintf(stdout, "\nError on select: %s\n", strerror(errno)); exit(1); } } for(i=0; i < no_of_interfaces; i++) { socklen_t len = sizeof(*clientaddr_ptr); if(FD_ISSET(nw_interfaces[i].sockfd,&rset)){//if this FD is available, three-way handshake /* first handshake from client, requesting the file name*/ clientaddr_ptr = malloc(sizeof(struct sockaddr_in)); Recvfrom(nw_interfaces[i].sockfd, &rcvd_seg, 512, 0,(SA*)clientaddr_ptr,&len); memset(&clientaddr,0,sizeof(clientaddr)); memcpy(&clientaddr,clientaddr_ptr,sizeof(*clientaddr_ptr)); char filename[strlen(rcvd_seg.data) + 1]; strcpy(filename,rcvd_seg.data); /* check if this client has been put onto the list, if yes tell corresponding child to trigger the second handshake again*/ struct client *node; char msg[] = "Client Requests File Again."; node = NULL; if((node = is_client_present(head,clientaddr.sin_addr.s_addr, clientaddr.sin_port)) != NULL) { if(write(node->pipefd,msg,strlen(msg)) < 0) { printf("\nError writing client existance check:%s\n",strerror(errno)); exit(1); } printf("This client is already present in the processing queue...\n"); /* Enter the code to tell client to send the second handshake again*/ } else { fprintf(stdout, "\nFirst handshake received...\n"); fprintf(stdout, "File requested from client: \"%s\"\n", filename); fprintf(stdout, "Client Port no: %d\n", ntohs(clientaddr.sin_port)); fprintf(stdout, "Client IP address: %s\n\n", inet_ntop(AF_INET, &clientaddr.sin_addr, ip_str, sizeof(ip_str))) ; int pipefd[2]; if(pipe(pipefd) < 0) { printf("Pipe Error; %s\n", strerror(errno)); exit(1); } /* Create a chile to process client request*/ if((pid = fork()) < 0) { printf("Fork Error; %s\n", strerror(errno)); exit(1); } else if(pid > 0) { /* parent process */ /* close read end of child process, the child will just read*/ close(pipefd[0]); add_cli(&head, clientaddr.sin_addr.s_addr, clientaddr.sin_port, pipefd[1], pid); } else { /* child process */ /* close write end of child process, the child will just read*/ close(pipefd[1]); // /* Intiate file transfer */ file_transfer(filename,nw_interfaces,no_of_interfaces,i,&clientaddr,min(advt_win_size, ntohl(rcvd_seg.head.rcv_wnd_size)),pipefd[0]); /*File transfer done, exit the process */ close(pipefd[0]); exit(0); } } } } } return 0; } /********************************** start of sig_chld handling function *******************************/ void sig_child(int sig_no) { pid_t pid; int stat; /* when the child server process complete the processing of the client, remove that client from processing list*/ while( (pid = waitpid(-1, &stat, WNOHANG)) > 0) { rm_cli(pid); } return; } /********************************** end of sig_chld handling function *******************************/ /***********************************Start of file_transfer function*************************************/ /* Performs handshaking as well as file transfer*/ void file_transfer(char *filename, struct nw_interface* list,int no_of_interfaces, int n, struct sockaddr_in *clientaddr,int winsize, int pipefd){ int i,islocal = 0,j; int on = 1; int conn_socket_fd; struct sockaddr_in conn_socket_addr_temp,conn_socket_addr; struct tcp_segment tcp_seg; uint64_t factor = 1000; int second_hshake_sent = 0; fd_set rset; char local_buffer[128]; struct timeval wait_time; int maxfd = 0; uint32_t len; uint32_t curr_recv_wnd_size = 0; struct sliding_win sld_win_buff; FILE *file_req = NULL; uint32_t tcp_seg_seq_num = INITIAL_SEQ_NO; struct win_segment *win_seg_ptr = NULL; struct itimerval test_itime_val; int effective_win_size = 0; uint16_t is_file_read_complete; struct rtt_info rtti; sigset_t alarm_mask; struct timeval time_val; struct win_probe_rto_info win_prob_rti; int flight_size; /* check if the incoming client is local */ for(i=0; i < no_of_interfaces; i++) { if(i != n) { close(list[i].sockfd); // closing other listening sockets } // Remeber all ip addr in struct nw_interface are generic uint32_t serip = (((struct sockaddr_in*)list[i].ifi_addr)->sin_addr.s_addr) & (((struct sockaddr_in*)list[i].ifi_maskaddr)->sin_addr.s_addr); uint32_t cliip = (clientaddr->sin_addr.s_addr) & (((struct sockaddr_in*)list[i].ifi_maskaddr)->sin_addr.s_addr); if((cliip ^ serip )== 0){ if(setsockopt(list[i].sockfd,SOL_SOCKET, SO_DONTROUTE,&on,sizeof(on)) < 0){ printf("Setsockopt listening socket error:%s\n",strerror(errno)); exit(1); } islocal = 1; } } /* create the connection socket */ conn_socket_fd = Socket(AF_INET,SOCK_DGRAM,0); if(islocal == 0) { printf("Client doesn't belong to local network...\n"); /* Set this connection socket option to address reusable */ if(setsockopt(conn_socket_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0 ){ printf("Setsockopt connecting socket error:%s\n",strerror(errno)); exit(1); } } else { printf("\nClient belongs to local network...\n"); //Set this connection socket option to DONTROUTE. if(setsockopt(conn_socket_fd, SOL_SOCKET, SO_DONTROUTE, &on, sizeof(on)) < 0 ){ printf("Setsockopt connecting socket error:%s\n",strerror(errno)); exit(1); } } conn_socket_addr_temp = *((struct sockaddr_in *) list[n].ifi_addr); conn_socket_addr_temp.sin_family = AF_INET; conn_socket_addr_temp.sin_port = htons(0); /* bind the connection socket */ Bind(conn_socket_fd,(SA *)&conn_socket_addr_temp, sizeof(conn_socket_addr_temp)); len = sizeof(conn_socket_addr); if(getsockname(conn_socket_fd,(SA *)&conn_socket_addr,&len)<0){ printf("\ngetsockname error:%s\n",strerror(errno)); exit(1); } else { printf("\nThe IP address of child server is: %s\n",Sock_ntop_host((SA *)&conn_socket_addr, sizeof(conn_socket_addr))); printf("The connection port number of child server is: %d\n", ntohs(conn_socket_addr.sin_port)); } Connect(conn_socket_fd,(SA *)clientaddr,sizeof(*clientaddr)); fprintf(stdout, "\nChild server process successfully connected to client...\n"); len = sizeof(*clientaddr); /***************************************Handshaking processing intiated***********************************/ while(1) { tcp_seg.head.ack = 1; tcp_seg.head.syn = 1; tcp_seg.head.seq_num = INITIAL_SEQ_NO; sprintf(tcp_seg.data, "%d", conn_socket_addr.sin_port); if(second_hshake_sent == 1) { if(send(conn_socket_fd, &tcp_seg, sizeof(tcp_seg), 0) == -1 ) { fprintf(stderr, "\nError sending second handshake: %s\n", strerror(errno)); exit(1); } fprintf(stdout, "\nSecond handshake sent successfully from connecting socket with new port no...\n"); } if(sendto(list[n].sockfd, &tcp_seg, sizeof(tcp_seg), 0, (SA *)clientaddr, sizeof(*clientaddr)) == -1 ) { fprintf(stdout, "\nError sending second handshake: %s\n", strerror(errno)); exit(1); } fprintf(stdout, "\nSecond handshake sent successfully from listening socket...\n"); second_hshake_sent = 1; read_again: memset(&wait_time, 0, sizeof(wait_time)); FD_ZERO(&rset); FD_SET( pipefd, &rset); FD_SET( conn_socket_fd, &rset); wait_time.tv_sec = 1; wait_time.tv_usec = 300000; maxfd = max(conn_socket_fd, pipefd) + 1; if(select(maxfd, &rset, NULL, NULL, &wait_time) < 0) { fprintf(stderr, "\nError while select: %s\n", strerror(errno)); exit(1); } if(FD_ISSET(pipefd, &rset)) { if( read(pipefd, local_buffer, 128) < 0) { fprintf(stderr, "\nError while reading messsage from parent server through pipe:%s\n", strerror(errno)); } fprintf(stdout,"\nMessage from parent server: %s\n", local_buffer); continue; } if( FD_ISSET(conn_socket_fd, &rset)) { memset(&tcp_seg, 0, sizeof(tcp_seg)); len = sizeof(*clientaddr); // recvfrom(conn_socket_fd, &tcp_seg, sizeof(tcp_seg), 0, (SA *)clientaddr, &len) if( recvfrom(conn_socket_fd, &tcp_seg, sizeof(tcp_seg), 0, NULL, &len)< 0 ) { if(errno == 111 || errno == 146) goto read_again; else { fprintf(stderr, "\nError while receiving third handshake from client:%d\n", errno); exit(1); } } curr_recv_wnd_size = tcp_seg.head.rcv_wnd_size; fprintf(stdout, "\nThird handshake from client received...\n"); fprintf(stdout, "File transder will be initiated...\n"); fprintf(stdout, "Received window size: %d\n", curr_recv_wnd_size); break; } } close(list[n].sockfd); /***************************************Handshaking processing complete***********************************/ /***************************************Initiate File Transfer Processing**********************************************/ /*Intialize variables related to file transfer*/ /* Here intialization values are taken from steven's Unix Programming book */ rtti.rtt = 0; rtti.rttvar = 3000; /* in fraction it would be 3/4 and since it is using msec scale thus after multiplication by 4 and millisec scale rttvar = 3000*/ rtti.srtt = 0; rtti.rto = 3000; sld_win_buff.ssthresh = 512; is_file_read_complete = 0; win_prob_rti.win_probe_time_out = 1500; sld_win_buff.advt_rcv_win_size = curr_recv_wnd_size; sld_win_buff.buffer_head = NULL; sld_win_buff.cwin_size = 1 ; /* SLOW START*/ sld_win_buff.no_of_seg_in_transit = 0; if((file_req = fopen(filename, "r")) == NULL ) { fprintf(stderr, "\nError opening requested file: %s\n", strerror(errno)); exit(1); } fprintf(stdout, "\nFile: %s opened successfully...\n", filename); if(sigemptyset(&alarm_mask) == -1) { fprintf(stderr, "/nError while emptying the mask set: %s\n", strerror(errno)); exit(1); } if(sigaddset(&alarm_mask, SIGALRM) == -1) { fprintf(stderr, "/nError while setting the SIGALRM in mask set: %s\n", strerror(errno)); exit(1); } signal(SIGALRM, sig_alrm); while(1) { /* if all packets are received by reciver and all data is transferred - Mission Mayhem accomplished*/ if(is_file_read_complete == 1 && sld_win_buff.no_of_seg_in_transit == 0 && sld_win_buff.fin_ack_received == 1) { fprintf(stdout, "\nFile transfer completed successfully!!!"); fprintf(stdout,"Client acknowledged final data segement...\n"); fprintf(stdout,"Connection is being closed...\n\n"); win_seg_ptr = (struct win_segment*)malloc(sizeof (struct win_segment)); memset(win_seg_ptr, 0, sizeof(struct win_segment)); /* 0 sequence no is indicating connection close to client*/ win_seg_ptr->segment.head.seq_num = 0; win_seg_ptr->segment.head.ack = 1; win_seg_ptr->segment.head.fin = 1; win_seg_ptr->next_segment = NULL; memset(&time_val, 0, sizeof(time_val)); /* get current time */ if(gettimeofday(&time_val, NULL)) { fprintf(stderr, "\nError settign the timestamp for a tcp segment: %s\n", strerror(errno)); exit(1); } /* first get the millisecond from second and microsecond elapsed since epoch */ win_seg_ptr->time_of_send = (uint64_t)(time_val.tv_usec/factor) + (uint64_t)(time_val.tv_sec*factor); if(send(conn_socket_fd, &(win_seg_ptr->segment), 512, 0) == -1) { fprintf(stderr, "\nError while sending final acknowledgement: %s\n", strerror(errno) ); exit(1); } fprintf(stdout, "Final segament informing connection close on server side sent...\n"); close(conn_socket_fd); return; } if(sigsetjmp(jmpbuf, 1) != 0) { /* Process receiver deadlock by sending window probing message */ if(sld_win_buff.no_of_seg_in_transit == 0 && sld_win_buff.advt_rcv_win_size == 0 && is_file_read_complete != 1 ) { fprintf(stdout, "\nReceiver window is locked...\n"); /* prepare window probe message */ struct win_segment probe_win_seg; memset(&probe_win_seg, 0, sizeof(struct win_segment)); //tcp_seg_seq_num += 1; probe_win_seg.segment.head.seq_num = 0; probe_win_seg.next_segment = NULL; memset(&time_val, 0, sizeof(time_val)); /* get current time */ if(gettimeofday(&time_val, NULL)) { fprintf(stderr, "\nError setting the timestamp for a tcp segment: %s\n", strerror(errno)); } /* first get the millisecond from second and microsecond elapsed since epoch */ probe_win_seg.time_of_send = (uint64_t)(time_val.tv_usec/1000) + (uint64_t)(time_val.tv_sec*1000); /* send the probe window segement to the client */ if(send(conn_socket_fd, &(probe_win_seg.segment), sizeof(probe_win_seg.segment), 0) == -1) { fprintf(stderr, "\nError while sending the tcp segment with sequence no %d: %s\n", win_seg_ptr->segment.head.seq_num, strerror(errno) ); exit(1); } set_alarm(&sld_win_buff, &rtti, &win_prob_rti); fprintf(stdout, "Window Probing segement sent...\n"); } /* Normal time out use case */ if(sld_win_buff.no_of_seg_in_transit != 0 && sld_win_buff.advt_rcv_win_size != 0) { fprintf(stdout, "\nRetranmission time out happened...\n"); fprintf(stdout, "\nCurrent congestion window: %d\n", sld_win_buff.cwin_size); fprintf(stdout, "Current congestion window threshold: %d\n", sld_win_buff.ssthresh); fprintf(stdout, "\nSlow start threshold and congestion window size will be modified...\n"); flight_size = min(sld_win_buff.advt_rcv_win_size, sld_win_buff.cwin_size); sld_win_buff.ssthresh = max(2, (int)(ceil(flight_size/2.0)) ); sld_win_buff.cwin_size = 1; sld_win_buff.no_ack_in_rtt = 0; fprintf(stdout, "New congestion window: %d\n", sld_win_buff.cwin_size); fprintf(stdout, "New congestion window threshold: %d\n", sld_win_buff.ssthresh); if(sld_win_buff.buffer_head != NULL) { if(sld_win_buff.buffer_head->no_of_sends == RTT_MAXNREXMT) { fprintf(stdout, "\nSegment %d has already been transmitted %d times,\n", sld_win_buff.buffer_head->segment.head.seq_num, RTT_MAXNREXMT); fprintf(stdout, "File transfer connection is being dropped!!!\n"); close(conn_socket_fd); return; } else { rtti.rto = rtt_minmax(rtti.rto*2); fprintf(stdout, "\nRetransmitting the segment %d...\n", sld_win_buff.buffer_head->segment.head.seq_num); fprintf(stdout, "New retransmission time out interval %d msec...\n", rtti.rto); send_tcp_segment(&sld_win_buff, sld_win_buff.buffer_head, conn_socket_fd, clientaddr, &rtti, &win_prob_rti, 1); } } } } /* prevent the timeout to affect the sending of data and receving of acknowledgement */ /* mask the sigalarm*/ if(sigprocmask(SIG_BLOCK, &alarm_mask, NULL) == -1) { fprintf(stderr, "\nError while blocking the SIGALARM: %s\n", strerror(errno)); exit(1); } /************************************* File read and segment send part start **********************************/ /* if file has been read completely => no need to read the file again*/ if(is_file_read_complete == 1) { fprintf(stdout, "\nFile read is complete.\nNo new tcp segments will be trasmitted...\n"); fprintf(stdout, "Old tcp segements may be retrasmitted, if required..\n"); } else { /* Get the effectvie window size which represents no of segements that can be sent further */ effective_win_size = min(sld_win_buff.cwin_size , sld_win_buff.advt_rcv_win_size ) - sld_win_buff.no_of_seg_in_transit; j=1; if(effective_win_size < 0) effective_win_size = 0; /* print window size information */ fprintf(stdout, "\n Current congestion window size:%d\n", sld_win_buff.cwin_size ); fprintf(stdout, "Advertised receiver window size:%d\n", sld_win_buff.advt_rcv_win_size); fprintf(stdout, "No of segment in transit: %d\n", sld_win_buff.no_of_seg_in_transit); fprintf(stdout, "Available window size for transmisson:%d\n", effective_win_size); while(j <= effective_win_size) { j++; /* prepare the window segment with tcp segement */ win_seg_ptr = (struct win_segment*)malloc(sizeof (struct win_segment)); memset(win_seg_ptr, 0, sizeof(struct win_segment)); tcp_seg_seq_num += 1; win_seg_ptr->segment.head.seq_num = tcp_seg_seq_num; win_seg_ptr->next_segment = NULL; memset(&time_val, 0, sizeof(time_val)); /* get current time */ if(gettimeofday(&time_val, NULL)) { fprintf(stderr, "\nError settign the timestamp for a tcp segment: %s\n", strerror(errno)); } /* first get the millisecond from second and microsecond elapsed since epoch */ win_seg_ptr->time_of_send = (uint64_t)(time_val.tv_usec/factor) + (uint64_t)(time_val.tv_sec*factor); /* read the requested file to create a tcp segement */ if(fread(win_seg_ptr->segment.data, 1, sizeof(win_seg_ptr->segment.data), file_req) < sizeof(win_seg_ptr->segment.data)) { if(ferror(file_req)) { fprintf(stderr, "\nError reading requested file: %s\n", strerror(errno)); exit(1); } } /* If file read is over, set the is_file_read_complete indicator to true*/ if(feof(file_req)) { win_seg_ptr->segment.head.fin = 1; is_file_read_complete = 1; } /* add the tcp segment to sliding window buffer */ add_win_seg_to_sld_win(&sld_win_buff, win_seg_ptr); /* send the added window segement to the client */ send_tcp_segment(&sld_win_buff, win_seg_ptr, conn_socket_fd, clientaddr, &rtti, &win_prob_rti, 1); /* If file read is over, no need to read anymore */ if(feof(file_req)) { fprintf(stdout, "\nFile read is complete.\nLast new tcp segments is being trasmitted\n"); fprintf(stdout, "Old tcp segements may be retrasmitted, if required in case of packet loss...\n"); break; } } } /************************************* File read and segment send part end **********************************/ /* important processing complete: unmask the sigalarm*/ if(sigprocmask(SIG_UNBLOCK, &alarm_mask, NULL) == -1) { fprintf(stderr, "\nError while blocking the SIGALARM: %s\n", strerror(errno)); exit(1); } /********************************** ack read part start ******************************************************/ memset(&tcp_seg, 0, sizeof(tcp_seg)); fprintf(stdout, "\nWaiting to receive an acknowledgement\n..."); memset(&test_itime_val, 0, sizeof(test_itime_val)); getitimer(ITIMER_REAL, &test_itime_val); fprintf(stdout, "Remaining time left in timeout: %lu sec - %lu microsec...\n", test_itime_val.it_value.tv_sec, test_itime_val.it_value.tv_usec); if( recvfrom(conn_socket_fd, &tcp_seg, sizeof(tcp_seg), 0, (SA *)clientaddr, &len) < 0 ) { fprintf(stderr, "\nError while receiving an acknowledgement from client:%s\n", strerror(errno)); exit(1); } if(tcp_seg.head.ack == 1) { fprintf(stdout, "\nReceived an acknowledgement from client\n"); fprintf(stdout, "Next sequance no. expected is:%d\n", tcp_seg.head.ack_num); process_client_ack(&sld_win_buff, &tcp_seg, &rtti, &win_prob_rti, conn_socket_fd, clientaddr); if(tcp_seg.head.fin == 1) { sld_win_buff.fin_ack_received = 1; } } /********************************** ack read part end ********************************************************/ } /***************************************Complete File Transfer Processing**********************************************/ } /********************************************completion of file_transfer function*****************************************************/ /**************************************** Start process_client_ack function ******************************************************************************/ void process_client_ack(struct sliding_win *sld_win_buff, struct tcp_segment *tcp_seg_ptr, struct rtt_info *rtti, struct win_probe_rto_info *win_probe_rti, int conn_sock_fd, struct sockaddr_in* cliaddr) { struct win_segment *win_seg_lcl_ptr = sld_win_buff->buffer_head; struct win_segment prev_win_seg; struct timeval time_val; int flight_size; sld_win_buff->advt_rcv_win_size = tcp_seg_ptr->head.rcv_wnd_size; uint64_t factor = 1000; memset(&prev_win_seg, 0, sizeof(prev_win_seg)); /* If sliding window head is null, and an ack is received then it must be the ack updating the advertised window from 0 to a certain value and explicitely asking server to send a tcp segment, if availble*/ if( sld_win_buff->buffer_head == NULL) { return; } else { /* Remove all the sent segment till the sequence no specified in ack*/ while(win_seg_lcl_ptr->segment.head.seq_num < tcp_seg_ptr->head.ack_num) { /* Implement congestion control protocol*/ /* Increase the cwin size for every ack received in an RTT => exponential increase */ if(sld_win_buff->cwin_size < sld_win_buff->ssthresh) { sld_win_buff->cwin_size += 1; fprintf(stdout, "\nCongestion control is in slow start phase...\n"); fprintf(stdout, "After receving an ack during slow start phase, new congestion window: %d\n", sld_win_buff->cwin_size); } else { /* Congestion aviodance phase has been reached */ /* Now congestion window will increase linerarly */ fprintf(stdout, "\nCongestion control is in congestion aviodance phase...\n"); sld_win_buff->no_ack_in_rtt++; if(sld_win_buff->no_ack_in_rtt%sld_win_buff->cwin_size == 0) { sld_win_buff->cwin_size += 1; fprintf(stdout, "After receving %d no of acknowledge in an RTT, new congestion window size: %d\n", sld_win_buff->no_ack_in_rtt, sld_win_buff->cwin_size); /* To initiate next RTT processing */ sld_win_buff->no_ack_in_rtt = 0; } else { fprintf(stdout, "Integer based calculaton is being used...\n"); fprintf(stdout, "Since no of ack received in current RTT %d is less than current congestion window size %d - no increase in cognestion window size...\n",sld_win_buff->no_ack_in_rtt, sld_win_buff->cwin_size); } } memset(&prev_win_seg, 0, sizeof(prev_win_seg)); prev_win_seg = *(win_seg_lcl_ptr); /* remove the segment from the sliding window */ fprintf(stdout, "\nSegment %d will be removed from the sliding window...\n", win_seg_lcl_ptr->segment.head.seq_num); remove_win_seg_from_sld_win(sld_win_buff, win_seg_lcl_ptr); if(sld_win_buff->buffer_head != NULL) { win_seg_lcl_ptr = sld_win_buff->buffer_head; } else break; } if(prev_win_seg.no_of_sends > 1) { /* do not recalculate RTO */ } else { /* determine RTO based on current measured RTT */ memset(&time_val, 0, sizeof(time_val)); /* get current time */ if(gettimeofday(&time_val, NULL)) { fprintf(stderr, "\nError getting the current timestamp for RTT determination: %s\n", strerror(errno)); exit(1); } rtti->rtt = (int)(time_val.tv_usec/factor + time_val.tv_sec*factor - prev_win_seg.time_of_send); fprintf(stdout, "Measured RTT after receving an acknowledge from client: %d millisec\n", rtti->rtt); determine_rto(rtti); fprintf(stdout, "Measured RTO after receving an acknowledge from client: %d millisec\n", rtti->rto); } /* Fast retransmit/ Fast recovery processing for congestion control*/ if(sld_win_buff->buffer_head != NULL) { if(sld_win_buff->buffer_head->segment.head.seq_num == tcp_seg_ptr->head.ack_num) { ++sld_win_buff->buffer_head->segment.head.ack_num; fprintf(stdout, "\nReceived %d duplicate acknowledgement for segment %d...\n", sld_win_buff->buffer_head->segment.head.ack_num, sld_win_buff->buffer_head->segment.head.seq_num); if( (sld_win_buff->buffer_head->segment.head.ack_num) == 3 ) { fprintf(stdout, "\nPerforming fast recovery...\n"); fprintf(stdout, "Current congestion window: %d\n", sld_win_buff->cwin_size); fprintf(stdout, "Current congestion window threshold: %d\n", sld_win_buff->ssthresh); /* slash the threshold to half of the current window size*/ flight_size = min(sld_win_buff->advt_rcv_win_size, sld_win_buff->cwin_size); sld_win_buff->ssthresh = max(2, (int)(ceil(flight_size/2.0)) ); sld_win_buff->cwin_size = sld_win_buff->ssthresh; /* again we are in congestion avoidance phase */ sld_win_buff->no_ack_in_rtt = 0; fprintf(stdout, "\nNew congestion window: %d\n", sld_win_buff->cwin_size); fprintf(stdout, "New congestion window threshold: %d\n", sld_win_buff->ssthresh); fprintf(stdout, "\nRetrasmitting the segment after three duplicate acks...\n"); send_tcp_segment(sld_win_buff, sld_win_buff->buffer_head, conn_sock_fd, cliaddr, rtti, win_probe_rti, 1); } } } else { /* If sliding window is empty and received window size 0, it means a receiver window deadlock*/ /* in such case set, persistance timer*/ if(sld_win_buff->advt_rcv_win_size == 0) { fprintf(stdout,"\nReceiver window deadlock, persistant timer will be set...\n"); set_alarm(sld_win_buff, rtti, win_probe_rti); } } } } /**************************************** Start process_client_ack function ******************************************************************************/ /********************************************start of add_win_seg_to_sld_win function*****************************************************/ void add_win_seg_to_sld_win(struct sliding_win* sld_win_buff_ptr, struct win_segment* win_seg_ptr) { struct win_segment* current_win_seg_ptr; if(sld_win_buff_ptr->buffer_head == NULL ) { sld_win_buff_ptr->buffer_head = win_seg_ptr; } else { current_win_seg_ptr = sld_win_buff_ptr->buffer_head; while(current_win_seg_ptr->next_segment != NULL) current_win_seg_ptr = current_win_seg_ptr->next_segment; current_win_seg_ptr->next_segment = win_seg_ptr; } sld_win_buff_ptr->no_of_seg_in_transit += 1; } /********************************************end of add_win_seg_to_sld_win function*****************************************************/ /************************************* start of remove_win_seg_from_sld_win function*************************************/ void remove_win_seg_from_sld_win(struct sliding_win* sld_win_buff, struct win_segment* win_seg_ptr) { if(sld_win_buff->buffer_head == NULL) return; else { sld_win_buff->no_of_seg_in_transit--; fprintf(stdout, "No of segment in transit: %d\n", sld_win_buff->no_of_seg_in_transit); if(sld_win_buff->buffer_head->segment.head.seq_num == win_seg_ptr->segment.head.seq_num) sld_win_buff->buffer_head = sld_win_buff->buffer_head->next_segment; /* release the memory consumed by the window segment*/ free(win_seg_ptr); } } /************************************* end of remove_win_seg_from_sld_win function*************************************/ /********************************************start of send_tcp_segment function*****************************************************/ void send_tcp_segment(struct sliding_win* sld_win_buff_ptr, struct win_segment *win_seg_ptr, int conn_sock_fd, struct sockaddr_in* cliaddr, struct rtt_info *rtti_ptr, struct win_probe_rto_info* win_probe_rti_ptr, int is_set_alarm_req) { win_seg_ptr->no_of_sends += 1; if(send(conn_sock_fd, &(win_seg_ptr->segment), 512, 0) == -1) { fprintf(stderr, "\nError while sending the tcp segment with sequence no %d: %s\n", win_seg_ptr->segment.head.seq_num, strerror(errno) ); exit(1); } fprintf(stdout, "\nSegment sent with sequence no: %d\n", win_seg_ptr->segment.head.seq_num); fprintf(stdout, "No of time segement sent: %d \n", win_seg_ptr->no_of_sends); /* if it is an opening segment for sliding window, set the alarm, which will be used for all segments sent in this RTT*/ if(sld_win_buff_ptr->buffer_head->segment.head.seq_num == win_seg_ptr->segment.head.seq_num && is_set_alarm_req == 1) { set_alarm(sld_win_buff_ptr, rtti_ptr, win_probe_rti_ptr); } } /********************************************end of send_tcp_segment function*****************************************************/ /********************************************start of rtt_minmax function*****************************************************/ int rtt_minmax(int rto) { if (rto < RTT_RXTMIN) rto = RTT_RXTMIN; else if (rto > RTT_RXTMAX) rto = RTT_RXTMAX; return (rto); } /********************************************end of rtt_minmax function*****************************************************/ /********************************************start of determin_rto function*****************************************************/ void determine_rto(struct rtt_info* rtti_ptr) { int measured_rtt = rtti_ptr->rtt; measured_rtt -= (rtti_ptr->srtt>>3); if(measured_rtt < 0) measured_rtt = 0 - measured_rtt; measured_rtt -= (rtti_ptr->rttvar>>2); rtti_ptr->rttvar += measured_rtt; rtti_ptr->rto = rtt_minmax((rtti_ptr->srtt>>3) + rtti_ptr->rttvar) ; } /********************************************end of determine_rto function*****************************************************/ /********************************************start of set_alarm function*****************************************************/ void set_alarm(struct sliding_win *sld_win_buff, struct rtt_info* rtti_ptr, struct win_probe_rto_info* win_prob_rti_ptr) { /* Two alarms are implemented * 1. Persistance Alarm * 2. Transmission Time Out Alarm */ struct itimerval itime_val; memset(&itime_val, 0, sizeof(itime_val)); /* If sliding window header is NULL, then there are two possibilities. Either advertised window is 0, in which case * Persistance alarm comes into the picture. If advertised window is not empty, then clear the existing timer as the * timer will be set again while sending a new segment, in which case alarm will be set. */ if(sld_win_buff->buffer_head == NULL) { if(sld_win_buff->advt_rcv_win_size == 0) { /* First get the seconds value by converting to microsec and then back to sec */ itime_val.it_value.tv_sec = (int)((win_prob_rti_ptr->win_probe_time_out*1000)/1000000) ; /* Get the microseconds value, mod is required because previous sec calculation will omit fractional part */ itime_val.it_value.tv_usec = (int)((win_prob_rti_ptr->win_probe_time_out*1000000)%1000000); fprintf(stdout, "Persistance timer interval set: %lu sec - %lu microsec\n...", itime_val.it_value.tv_sec, itime_val.it_value.tv_usec); if(setitimer(ITIMER_REAL, &itime_val, NULL) == -1) { fprintf(stderr, "\nError while setting persistance timer for window probing: %s\n", strerror(errno)); exit(1); } } else { /* Clear the retransmission timer */ if(setitimer(ITIMER_REAL, &itime_val, NULL) == -1) { fprintf(stderr, "\nError while clearing retransmission timer: %s\n", strerror(errno)); exit(1); } } } else { /* Set the timer based on current calculated RTO */ /* First get the seconds value by converting to microsec and then back to sec */ itime_val.it_value.tv_sec = (int)((rtti_ptr->rto*1000)/1000000) ; /* Get the microseconds value, mod is required because previous sec calculation will omit fractional part */ itime_val.it_value.tv_usec = (int)((rtti_ptr->rto*1000000)%1000000); fprintf(stdout, "Retransmission timer interval set: %lu sec - %lu microsec\n...", itime_val.it_value.tv_sec, itime_val.it_value.tv_usec); if(setitimer(ITIMER_REAL, &itime_val, NULL) == -1) { fprintf(stderr, "\nError while setting persistance timer for window probing: %s\n", strerror(errno)); exit(1); } } } /********************************************start of set_alarm function*****************************************************/ /******************************start og sig_alarm handling function*************************************/ void sig_alrm(int signo) { siglongjmp(jmpbuf, 1); } /******************************start og sig_alarm handling function*************************************/ //***this is function to check whether a node is on the list struct client* is_client_present(struct client* root,uint32_t ip,uint16_t port_num) { if(root == NULL) return NULL; while(root != NULL) { if(root->ip == ip && root->port_num == port_num) { break; } root = root->next_client; } return root; } void rm_cli(pid_t child_pid) { struct client *node = head, *prev_node = NULL; while(node != NULL) { if(node->pid == child_pid) { if(node == head) { head = node->next_client; } else { prev_node->next_client = node->next_client; } free(node); } prev_node = node; node = node->next_client; } } void add_cli(struct client **root,int32_t ip,uint16_t port_num,int pipefd,pid_t pid) { struct client *client_node; if((*root)== NULL) { (*root) = create_cli(ip,port_num,pipefd,pid); return; } client_node = *root; while(client_node->next_client != NULL) { client_node = client_node->next_client; } client_node->next_client = create_cli(ip,port_num,pipefd,pid); return; } struct client* create_cli(int32_t ip,uint16_t port_num,int pipefd,pid_t pid) { struct client *node = (struct client*)malloc(sizeof(struct client)); node->ip = ip; node->port_num = port_num; node->pipefd = pipefd; node->pid = pid; node->next_client = NULL; return node; } <file_sep>CC = gcc CFLAGS = -I/home/courses/cse533/Stevens/unpv13e_solaris2.10/lib/ -g -O2 -D_REENTRANT -Wall -D__EXTENSIONS__ LIBS = /home/courses/cse533/Stevens/unpv13e_solaris2.10/libunp.a -lresolv -lsocket -lnsl -lpthread CLEANFILES = core core.* *.core *.o temp.* *.out typescript* \ *.lc *.lh *.bsdi *.sparc *.uw PROGS = client server all: ${PROGS} get_ifi_info_plus.o: get_ifi_info_plus.c ${CC} ${CFLAGS} -c get_ifi_info_plus.c client: client.o get_ifi_info_plus.o ${CC} ${CFLAGS} -o client client.o get_ifi_info_plus.o ${LIBS} -lm server: server.o get_ifi_info_plus.o ${CC} ${CFLAGS} -o server server.o get_ifi_info_plus.o ${LIBS} -lm server.o: server.c ${CC} ${CFLAGS} -c server.c client.o: client.c ${CC} ${CFLAGS} -c client.c clean: rm -f ${PROGS} ${CLEANFILES}
55394f60e78e501b424f97e9536124c8870039fa
[ "Markdown", "C", "Makefile" ]
4
Markdown
StevenYue/TCP-Reno-Like-File-Transfer-Protocol
e5e522fbe8269de7e8eecd0c868e9c5ea6ba6dc8
c3ecad305772d89b96a86f5a7436e3590648497c
refs/heads/master
<file_sep>#include <stdio.h> void main(void) { int year = 0; while(year<=2019) { int case_i=0; if (year % 4 == 0){ case_i = 1; } else {} if (year % 100 == 0) { case_i = 0; } else {} if (year % 400 == 0) { case_i = 1; } else {} switch (case_i) { case 0: break; case 1: printf("%8d", year); break; default: break; } year++; } }
db53c1d71a5705bb466e7c114aaed5b9b62b79e8
[ "C" ]
1
C
amazon00070/leap-year
425458c6526111c5658409983a137024b72144ab
d2cd31b40f001d75e85fdd8ec9b312e3cda745c7
refs/heads/master
<file_sep>{% extends 'base.html' %} {% block content %} <div class="search-form"> <div class="card"> <form method="POST" > <ul> <li>{{ form.query.label }}</li> <li>{{ form.query }}</li> <li>{{ form.price.label }}</li> <small>ex:(1000)</small> <li>${{ form.price }}</li> <li>{{ form.city.label }}</li> <li>{{ form.city(class="city") }}</li> <li>{{ form.submit }}</li> </ul> </form> </div> </div> {% endblock %}<file_sep>alembic==1.4.2 attrs==20.1.0 Automat==20.2.0 blinker==1.4 certifi==2020.6.20 cffi==1.14.2 chardet==3.0.4 click==7.1.2 constantly==15.1.0 cryptography==3.1 cssselect==1.1.0 Flask==1.1.2 Flask-Login==0.5.0 Flask-Mail==0.9.1 flask-marshmallow==0.13.0 Flask-Migrate==2.5.3 Flask-OAuthlib==0.9.5 Flask-SQLAlchemy==2.4.4 Flask-WTF==0.14.3 gunicorn==20.0.4 httplib2==0.18.1 hyperlink==20.0.1 idna==2.10 incremental==17.5.0 itemadapter==0.1.0 itemloaders==1.0.2 itsdangerous==1.1.0 Jinja2==2.11.2 jmespath==0.10.0 lxml==4.5.2 Mako==1.1.3 MarkupSafe==1.1.1 marshmallow==3.7.1 marshmallow-sqlalchemy==0.23.1 numpy==1.19.1 pandas==1.1.1 parsel==1.6.0 Protego==0.1.16 psycopg2-binary==2.8.5 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.20 PyDispatcher==2.0.5 PyHamcrest==2.0.2 pyOpenSSL==19.1.0 python-dateutil==2.8.1 python-editor==1.0.4 pytz==2020.1 queuelib==1.5.0 requests==2.24.0 requests-oauthlib==1.3.0 Scrapy==2.3.0 service-identity==18.1.0 six==1.15.0 SQLAlchemy==1.3.19 Twisted==20.3.0 urllib3==1.25.10 w3lib==1.22.0 Werkzeug==1.0.1 WTForms==2.3.3 zope.interface==5.1.0 <file_sep>from wtforms import Form, StringField, IntegerField, SelectField, PasswordField, validators, SubmitField from wtforms.validators import DataRequired, Length, EqualTo class LoginForm(Form): id = '' email = StringField('Email', validators=[DataRequired()]) password = StringField('Password', validators=[ Length(min=6, max=20), DataRequired()]) submit = SubmitField('Login') class RegistrationForm(Form): id = '' email = StringField('Email', validators=[DataRequired()]) password = StringField('Password', validators=[ Length(min=6, max=20), DataRequired()]) password2 = StringField('Confirm Password', validators=[ EqualTo(password), DataRequired()]) submit = SubmitField('Login') class SearchForm(Form): query = StringField('Search', validators=[ DataRequired()], default='Lawnmower') city = SelectField('City', choices=[ # Alabama ('auburn', 'Auburn, Alabama'), ('bham', 'Birmingham, Alabama'), ('dothan', 'Dothan, Alabama'), ('shoals', 'Florence / Shoals, Alabama'), ('gadsden', 'Gadsden-Anniston, Alabama'), ('huntsville', 'Hunstville / Decatur, Alabama'), ('mobile', 'Mobile, Alabama'), ('montgomery', 'Montgomery, Alabama'), ('tuscaloosa', 'Tuscaloosa, Alabama'), # Alaska ('anchorage', 'Anchorage, Alaska'), ('fairbanks', 'Anchorage, Alaska'), ('kenai', 'Kenai Peninsula, Alaska'), ('juneau', 'Southeast Alaska, Alaska'), # Arizona ('flagstaff', 'Flagstaff / Sedona, Arizona'), ('mohave', 'mohave, Arizona'), ('phoenix', 'Phoenix, Arizona'), ('prescott', 'Prescott, Arizona'), ('showlow', 'Show Low, Arizona'), ('sierravista', 'Sierra Vista, Arizona'), ('tucson', 'Tucson, Arizona'), ('yuma', 'Yuma, Arizona'), # Arkansas ('fayar', 'Fayetteville, Arkansas'), ('fortsmith', '<NAME>, Arkansas'), ('jonesboro', 'Jonesboro, Arkansas'), ('littlerock', 'Little Rock, Arkansas'), ('texarkana', 'Texarkana, Arkansas'), # California ('bakersfield', 'Bakersfield, California'), ('chico', 'Chico, California'), ('fresno', 'Fresno, California'), ('goldcountry', 'Gold Country, California'), ('hanford', 'Hanford-Corcoran, California'), ('humboldt', 'Humboldt County, California'), ('imperial', 'Imperial County, California'), ('inlandempire', 'Inland Empire, California'), ('losangeles', 'Los Angeles, California'), ('mendocino', 'Mendocino County, California'), ('merced', 'Merced, California'), ('modesto', 'Modesto, California'), ('monteray', 'Monteraybay, California'), ('orangecounty', 'Orange County, California'), ('palmsprings', 'Palm Springs, California'), ('redding', 'Redding, California'), ('sacramento', 'Sacramento, California'), ('sandiego', 'San Diego, California'), ('sfbay', 'San Francisco Bay Area, California'), ('slo', 'San Luis Obispo, California'), ('santabarbara', 'Santa Barbara, California'), ('santamaria', 'Santa Maria, California'), ('siskiyou', 'Siskiyou County, California'), ('stockton', 'Stockton, California'), ('susanville', 'Susanville, California'), ('ventura', 'Ventura County, California'), ('visalia', 'Visalia-Tulare, California'), ('yubasutter', 'Yuba-Sutter, California'), # Colorado ('boulder', 'Boulder, Colorado'), ('cosprings', 'Colorado Springs, Colorado'), ('denver', 'Denver, Colorado'), ('eastco', 'easternco, Colorado'), ('fortcollins', 'Fort Collins / North CO, Colorado'), ('rockies', 'highrockies, Colorado'), ('pueblo', 'pueblo, Colorado'), ('westslope', 'westernslope, Colorado'), # Connecticut ('newlondon', 'Eastern Connecticut'), ('hartford', 'Hartford, Connecticut'), ('newhaven', 'New Haven, Connecticut'), ('nwct', 'Northwest Connecticut'), # Delaware ('delaware', 'Delaware'), # District of Columbia ('washingtondc', 'Washington DC'), # Florida ('miami', 'Broward County, Florida'), ('daytona', 'Daytona Beach, Florida'), ('keys', 'Florida Keys, Florida'), ('miami', 'Fort Lauderdale, Florida'), ('fortmyers', 'ft myers / SW florida, Florida'), ('gainesville', 'Gainesville, Florida'), ('cfl', 'Heartland, Florida'), ('jacksonville', 'Jacksonville, Florida'), ('lakeland', 'Lakeland, Florida'), ('miami', 'Miami / Dade, Florida'), ('lakecity', 'North Central, Florida'), ('ocala', 'Ocala, Florida'), ('okaloosa', 'Okaloosa / Walton, Florida'), ('orlando', 'Orlando, Florida'), ('panamacity', 'Panama City, Florida'), ('pensacola', 'Pensacola, Florida'), ('sarasota', 'Sarasota-Bradenton, Florida'), ('miami', 'South Florida, Florida'), ('spacecoast', 'Space Coast, Florida'), ('staugustine', 'St Augustine, Florida'), ('tallahassee', 'Tallahassee, Florida'), ('tampa', 'Tampa Bay Area, Florida'), ('treasure', 'Treasure Coast, Florida'), ('miami', 'Palm Beach County, Florida'), # Georgia ('albanyga', 'Albany, Georgia'), ('athensga', 'Athens, Georgia'), ('atlanta', 'Atlanta, Georgia'), ('augusta', 'Augusta, Georgia'), ('brunswick', 'Brunswick, Georgia'), ('columbusga', 'Columbus, Georgia'), ('macon', 'Macon / <NAME>, Georgia'), ('nwga', 'Northwest, Georgia'), ('savannah', 'Savannah / Hinesville, Georgia'), ('statesboro', 'Statesboro, Georgia'), ('valdosta', 'Valdosta, Georgia'), # Hawaii ('honolulu', 'Hawaii'), # Idaho ('boise', 'Boise, Idaho'), ('eastidaho', 'East Idaho'), ('lewiston', 'Lewiston / Clarkston, Idaho'), ('twinfalls', 'Twin Falls, Idaho'), # Illinois ('bn', 'Bloomington-Normal'), ('champana', 'Champaign Urbana, Illinois'), ('chicago', 'Chicago, Illinois'), ('decatur', 'Decatur, Illinois'), ('lasalle', 'La Salle Co, Illinois'), ('mattoon', 'Mattoon-Charleston, Illinois'), ('peoria', 'Peoria, Illinois'), ('rockford', 'Rockford, Illinois'), ('carbondale', 'Southern Illinois'), ('springfieldil', 'Springfield, Illinois'), ('quincy', 'Wester Illinois'), # Indiana ('bloomington', 'Bloomington, Indiana'), ('evansville', 'Evansville, Indiana'), ('fortwayne', 'Fort Wayne, Indiana'), ('indianapolis', 'Indianapolis, Indiana'), ('kokomo', 'Kokomo, Indiana'), ('tippecanoe', 'Lafayette / West Lafayette, Indiana'), ('muncie', 'Muncie / Anderson, Indiana'), ('richmondin', 'Richmond, Indiana'), ('southbend', 'South Bend / Michiana, Indiana'), ('terrehaute', '<NAME>, Indiana'), # Iowa ('ames', 'Ames, Iowa'), ('cedarrappids', 'Cedar Rapids, Iowa'), ('desmoines', 'Des Moines, Iowa'), ('dubuque', 'Dubuque, Iowa'), ('fortdodge', 'Fort Dodge, Iowa'), ('iowacity', 'Iowa City, Iowa'), ('masoncity', 'Mason City, Iowa'), ('quadcities', 'Quad Cities, Iowa/Illinois'), ('siouxcity', 'Sioux City, Iowa'), ('ottumwa', 'Southeast Iowa'), ('waterloo', 'Waterloo / Cedar Falls, Iowa'), # Kansas ('lawrence', 'Lawrence, Kansas'), ('ksu', 'Manhatten, Kansas'), ('nwks', 'Northwest Kansas'), ('salina', 'Salina, Kansas'), ('seks', 'Southeast Kansas'), ('swks', 'Southwest Kansas'), ('topeka', 'Topeka, Kansas'), ('wichita', 'Wichita, Kansas'), # Kentucy ('bgky', 'Bowling Green, Kentucky'), ('eastky', 'Eastern Kentucky'), ('lexington', 'Lexington, Kentucky'), ('louisville', 'Louisville, Kentucky'), ('owensboro', 'Owensboro, Kentucky'), ('westky', 'Western Kentucky'), # Louisiana ('batonrouge', 'Baton Rouge, Louisiana'), ('cenla', 'Central Louisiana'), ('houma', 'Houma, Louisiana'), ('lafayette', 'Lake Charles, Louisiana'), ('lakecharles', 'Monroe, Louisiana'), ('monroe', 'Monroe, Louisiana'), ('neworleans', 'New Orleans, Louisiana'), ('shreveport', 'Shreveport, Louisiana'), # Maine ('maine', 'Maine'), # Maryland ('annapolis', 'Annapolis, Maryland'), ('baltimore', 'Baltimore, Maryland'), ('easternshore', 'Eastern Shore, Maryland'), ('frederick', 'Frederick, Maryland'), ('smd', 'Southern Maryland'), ('westmd', 'Western Maryland'), # Massachusetts ('boston', 'Boston, Massachusettes'), ('capecod', 'Cape Cod / Islands, Massachusettes'), ('southcoast', 'South Coast, Massachusettes'), ('westernmass', 'Western Massachusettes'), ('worcester', 'Worcester, / Central Massachusettes'), # Michigan ('annarbor', 'Ann Arbor, Michigan'), ('battlecreek', 'Battle Creek, Michigan'), ('centralmich', 'Central Michigan'), ('detroit', 'Detroit Metro, Michigan'), ('flint', 'Flint, Michigan'), ('grandrapids', 'Grand Rapids, Michigan'), ('holland', 'Holland, Michigan'), ('jxn', 'Jackson, Michigan'), ('kalamazoo', 'Kalamazoo, Michigan'), ('lansing', 'Lansing, Michigan'), ('monroemi', 'Monroe, Michigan'), ('muskegon', 'Muskegon, Michigan'), ('nmi', 'Northern Michigan'), ('porthuron', 'Port Huron, Michigan'), ('saginaw', 'Sagina-Midland-BayCity, Michigan'), ('swmi', 'Southwest Michigan'), ('thumb', 'The Thumb, Michigan'), ('battlecreek', 'Upper Peninsula, Michigan'), # Minnesota ('bemidji', 'Bemidji, Minnesota'), ('brainerd', 'Brainerd, Minnesota'), ('duluth', 'Duluth / Superior, Minnesota'), ('mankato', 'Mankato, Minnesota'), ('minneapolis', 'Minneapolis / St Paul, Minnesota'), ('rmn', 'Rochester, Minnesota'), ('marshall', 'Southerwest Minnesota'), ('stcloud', 'St Cloud, Minnesota'), # Mississippi ('gulfport', 'Gulfport / Biloxi, Mississippi'), ('jackson', 'Jackson, Mississippi'), ('meridian', 'Meridian, Mississippi'), ('northmiss', 'North Mississippi'), ('natchez', 'Southwest Mississippi'), # Missouri ('columbiamo', 'Columbia / Jeff City, Missouri'), ('joplin', 'Joplin, Missouri'), ('kansascity', 'Kansas City, Missouri'), ('kirksville', 'Kirksville, Missouri'), ('loz', 'Lake of the Ozarks, Missouri'), ('semo', 'Southeast Missouri'), ('springfield', 'Springfield, Missouri'), ('stjoseph', 'St Joseph, Missouri'), ('stlouis', 'St Louis, Missouri'), # Montana ('billings', 'Billings, Montana'), ('bozeman', 'Bozeman, Montana'), ('butte', 'Butte, Montana'), ('greatfalls', 'Great Falls, Montana'), ('helena', 'Helena, Montana'), ('kalispell', 'Kalispell, Montana'), ('missoula', 'Missoula, Montana'), ('montana', 'Eastern Montana'), # Nebraska ('grandisland', 'Grand Island, Nebraska'), ('lincoln', 'Lincoln, Nebraska'), ('northplatte', 'North Platte, Nebraska'), ('omaha', 'Omaha / Council Bluffs, Nebraska'), ('scottsbluff', 'Scottsbluff / Panhandle, Nebraska'), # Nevada ('elko', 'Elko, Nevada'), ('lasvegas', 'Las Vegas, Nevada'), ('reno', 'Reno / Tahoe, Nevada'), # New Hampshire ('nh', 'New Hampshire'), # New Jersey ('cnj', 'Central New Jersey'), ('jerseyshore', 'Jersey Shore, New Jersey'), ('newjersey', 'North New Jersey'), ('southjersey', 'South New Jersey'), # New Mexico ('albuquerque', 'Albuquerque, New Mexico'), ('clovis', 'Clovis / Portales, New Mexico'), ('farmington', 'Farmington, New Mexico'), ('lascruces', 'Las Cruces, New Mexico'), ('roswell', 'Roswell / Carlsbad, New Mexico'), ('santafe', 'Santa Fe / Taos, New Mexico'), # New York ('albany', 'Albany, New York'), ('bringhamton', 'Binghamton, New York'), ('buffalo', 'Buffalo, New York'), ('catskills', 'Catskills, New York'), ('chautauqua', 'Chautauqua, New York'), ('elmira', 'Elmira-Corning, New York'), ('fingerlakes', 'Finger Lakes, New York'), ('glenfalls', 'Glen Falls, New York'), ('hudsonvalley', 'Hudson Valley, New York'), ('ithica', 'Ithica, New York'), ('longisland', 'Long Island, New York'), ('newyork', 'New York City, New York'), ('oneonta', 'Oneonta, New York'), ('plattsburgh', 'Plattsburgh-Adirondacks, New York'), ('potsdam', 'Potsdam-Canton-Messena, New York'), ('rochester', 'Rochester, New York'), ('syracuse', 'Syracuse, New York'), ('twintiers', 'Twin Tiers, New York / Pennsylvania'), ('utica', 'Utica / Rome / Oneida, New York'), ('watertown', 'Watertown, New York'), # North Carolina ('asheville', 'Asheville, North Carolina'), ('boone', 'Boone, North Carolina'), ('charlotte', 'Charlotte, North Carolina'), ('eastnc', 'Eastern North Carolina'), ('fayetteville', 'Fayetteville, North Carolina'), ('greensboro', 'Greensboro, North Carolina'), ('hickory', 'Hickory / Lenoir, North Carolina'), ('onslow', 'Jacksonville, North Carolina'), ('outerbanks', 'Outer Banks North Carolina'), ('raleigh', 'Raleigh / Durham / CH, North Carolina'), ('wilmington', 'Wilmington, North Carolina'), ('winstonsalem', 'Winston / Salem, North Carolina'), # North Dakota ('bismarck', 'Bismarck, North Dakota'), ('fargo', 'Fargo / Moorhead, North Dakota'), ('grandforks', 'Grand Forks, North Dakota'), ('nd', 'North Dakota'), # Ohio ('akroncanton', 'Akron / Canton, Ohio'), ('ashtabula', 'Ashtabula, Ohio'), ('athensohio', 'Athens, Ohio'), ('cincinatti', 'Cincinatti, Ohio'), ('chillicothe', 'Chillicothe, Ohio'), ('cleveland', 'Cleveland, Ohio'), ('columbus', 'Columbus, Ohio'), ('dayton', 'Dayton / Springfield, Ohio'), ('limaohio', 'Lima Findlay, Ohio'), ('mansfield', 'Mansfield, Ohio'), ('toledo', 'Toledo, Ohio'), ('sandusky', 'Sandusky, Ohio'), ('tuscarawas', 'Tuscarawas Co, Ohio'), ('youngstown', 'Youngstown, Ohio'), ('zanesville', 'Zanesville / Cambridge, Ohio'), # Oklahoma ('lawton', 'Lawton, Oklahoma'), ('enid', 'Northwest Oklahoma'), ('oklahomacity', 'Oklahoma City, Oklahoma'), ('stillwater', 'Stillwater, Oklahoma'), ('tulsa', 'Tulsa, Oklahoma'), # Oregon ('bend', 'Bend, Oregon'), ('corvallis', 'Corvallis/Albany, Oregon'), ('eastoregon', 'East Oregon'), ('eugene', 'Eugene, Oregon'), ('klamath', 'Klamath Falls, Oregon'), ('medford', 'Medford / Ashland, Oregon'), ('oregoncoast', 'Oregon Coast, Oregon'), ('portland', 'Portland, Oregon'), ('roseburg', 'Roseburg, Oregon'), ('salem', 'Salem, Oregon'), # Pennsylvania ('altoona', 'Altoona / Johnstown, Pennsylvania'), ('chambersburg', 'Cumberland Valley, Pennsylvania'), ('erie', 'Erie, Pennsylvania'), ('harrisburg', 'Harrisburg, Pennsylvania'), ('lancaster', 'Lancaster, Pennsylvania'), ('allentown', 'Lehigh Valley, Pennsylvania'), ('meadville', 'Meadville, Pennsylvania'), ('philadelphia', 'Philadelphia, Pennsylvania'), ('pittsburgh', 'Pittsburgh, Pennsylvania'), ('poconos', 'Poconos, Pennsylvania'), ('reading', 'Reading, Pennsylvania'), ('scranton', 'Scranton / Wilkes-Barre, Pennsylvania'), ('pennstate', 'State College, Pennsylvania'), ('williamsport', 'Williamsport, Pennsylvania'), ('york', 'York, Pennsylvania'), # Rhode Island ('providence', 'Rhode Island'), # South Carolina ('charleston', 'Charleston, South Carolina'), ('columbia', 'Columbia, South Carolina'), ('florencesc', 'Florence, South Carolina'), ('greenville', 'Greenville / Upstate, South Carolina'), ('hiltonhead', 'Hilton Head, South Carolina'), ('myrtlebeach', 'Myrtle Beach, South Carolina'), # South Dakota ('nesd', 'Northeast South Dakota'), ('csd', 'Pierre / Central South Dakota'), ('rapidcity', 'Rapid City / West South Dakota'), ('siouxfalls', 'Sioux Falls / Southeast South Dakota'), ('sd', 'South Dakota'), # Tennessee ('chattanooga', 'Chattanooga, Tennessee'), ('clarksville', 'Clarksville, Tennessee'), ('cookeville', 'Cookeville, Tennessee'), ('jacksontn', 'Jackson, Tennessee'), ('knoxville', 'Knoxville, Tennessee'), ('memphis', 'Memphis, Tennessee'), ('nashville', 'Nashville, Tennessee'), ('tricities', 'Tri-Cities, Tennessee'), # Texas ('abilene', 'Abilene, Texas'), ('amarillo', 'Amarillo, Texas'), ('austin', 'Austin, Texas'), ('beaumont', 'Beaumont / Port Arthur, Texas'), ('brownsville', 'Brownsville, Texas'), ('collegestation', 'College Station, Texas'), ('corpuschristi', 'Corpus Christi, Texas'), ('dallas', 'Dallas / Fort Worth, Texas'), ('nacogdoches', 'Deep East Texas'), ('delrio', 'Del Rio / Eagle Pass, Texas'), ('elpaso', 'El Paso, Texas'), ('houston', 'Galveston, Texas'), ('galveston', 'Houston, Texas'), ('killeen', 'Killeen / Temple / Ft Hood, Texas'), ('laredo', 'Laredo, Texas'), ('lubbock', 'Lubbock, Texas'), ('mcallen', 'McCallen / Edinburg, Texas'), ('odessa', 'Odessa / Midland, Texas'), ('sanangelo', 'San Angelo, Texas'), ('sanantonio', 'San Antonio, Texas'), ('sanmarcos', 'San Marcos, Texas'), ('bigbend', 'Southwest Texas'), ('texoma', 'Texoma, Texas'), ('easttexas', 'Tyler / East Texas'), ('victoriatx', 'Victoria, Texas'), ('waco', 'Waco, Texas'), ('wichitafalls', 'Wichita Falls, Texas'), # Utah ('logan', 'Logan, Utah'), ('ogden', 'Ogden-Clearfield, Utah'), ('provo', 'Provo / Orem, Utah'), ('saltlakecity', 'Salt Lake City, Utah'), ('stgeorge', 'St George, Utah'), # Vermont ('vermon', 'Vermont'), # Virginia ('charlottesville', 'Charlottesville, Virginia'), ('danville', 'Danville, Virginia'), ('fredericksburg', 'Fredericksburg, Virginia'), ('norfolk', 'Norfolk, Virginia'), ('harrisonburg', 'Harrisonburg, Virginia'), ('lynchburg', 'Lynchburg, Virginia'), ('blacksburg', 'Blacksburg, Virginia'), ('richmond', 'Richmond, Virginia'), ('roanoke', 'Roanoke, Virginia'), ('swva', 'Southwest Virginia'), ('winchester', 'Winchester, Virginia'), # Washington ('bellingham', 'Bellingham, Washington'), ('kpr', 'Kennewick-Pasco-Richland, Washington'), ('moseslake', 'Moses Lake, Washington'), ('olympic', 'Olympic Peninsula, Washington'), ('pullman', 'Pullman / Moscow, Washington'), ('seattle', 'Seattle-Tacoma, Washington'), ('skagit', 'Skagit / Island / SJI, Washington'), ('spokane', 'Spokane / Coeur D\'alene, Washington'), ('wenatchee', 'Wenatchee, Washington'), ('yakima', 'Yakima, Washington'), # West Virginia ('charlestonwv', 'Charleston, West Virginia'), ('martinsburg', 'Eastern Panhandle, West Virginia'), ('huntington', 'Huntington-Ashland, West Virginia'), ('morgantown', 'Morgantown, West Virginia'), ('wheeling', 'Northern Panhandle, West Virginia'), ('parkersburg', 'Parkersburg-Marietta, West Virginia'), ('swv', 'Southern West Virginia'), ('wv', 'Old West Virginia'), # Wisconsin ('appleton', 'Appleton-Oshkosh-FDL, Wisconsin'), ('eauclaire', '<NAME>, Wisconsin'), ('greenbay', 'Green Bay, Wisconsin'), ('janesville', 'Janesville, Wisconsin'), ('racine', 'Kenosha-Racine, Wisconsin'), ('lacrosse', 'La Crosse, Wisconsin'), ('madison', 'Madison, Wisconsin'), ('milwaukee', 'Milwaukee, Wisconsin'), ('northernwi', 'Northern Wisconsin'), ('sheboygan', 'Sheboygan, Wisconsin'), ('wausau', 'Wauau, Wisconsin'), # Wyoming ('wyoming', 'Wyoming'), # Territories ('micronesia', 'Guam-Micronesia'), ('puertorico', 'Puerto Rico'), ('virgin', 'Virgin Islands'), ]) price = IntegerField(default=500) submit = SubmitField('Search') <file_sep>from flask import Flask, redirect, current_app, g, session, request, render_template from admin.admin import admin from main.main import main from db import db, ma from flask_migrate import Migrate import os def create_app(): app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://hwpahxlqhtzioo:<EMAIL>:5432/dlfvt18p3ebom' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.register_blueprint(main) app.register_blueprint(admin) with app.app_context(): db.init_app(app) db.create_all() migrate = Migrate() migrate.init_app(app) ma.init_app(app) return app app = create_app() app.config.update( SECRET_KEY=os.urandom(24), # Set the session cookie to be secure SESSION_COOKIE_SECURE=True, # Set the session cookie for our app to a unique name SESSION_COOKIE_NAME='Portfolio-WebSession', # Set CSRF tokens to be valid for the duration of the session. This assumes you’re using WTF-CSRF protection WTF_CSRF_TIME_LIMIT=None, # Configure Environment FLASK_ENV='production', # Debug DEBUG=False ) app.app_context().push() @app.route('/') def index(): ''' This route shall redirect to the main folder index.html file ''' return redirect('main/index') if __name__ == '__main__': app.run() <file_sep>from flask import Blueprint, render_template, request, redirect, url_for, session from models import LoginForm, RegistrationForm admin = Blueprint('admin', __name__, template_folder='templates', static_folder='static', url_prefix='/admin') @admin.route('/') @admin.route('/login', methods=['POST', 'GET']) def login(): ''' Route to admin.html ''' form = LoginForm() if request.method == 'POST': if request.form['email']: user = request.form['email'] session['user'] = user print(session['user']) return redirect(url_for('main.index')) else: return render_template('login.html', title='Login', form=form) @admin.route('/register', methods=['POST', 'GET']) def register(): ''' Route to admin.html ''' form = RegistrationForm() if request.method == 'POST': print(request) return redirect(url_for('main.index')) return render_template('register.html', title='Login', form=form) @admin.route('/logout', methods=['POST', 'GET']) def logout(): return redirect('login') <file_sep>from flask import Blueprint, render_template, request, redirect, g, current_app, session, url_for, abort from models import SearchForm from db import SearchQuery, User, Results, search_schema, searchs_schema, db import pandas as pd import os from time import sleep import subprocess main = Blueprint('main', __name__, template_folder='templates', static_folder='static', url_prefix="/home" ) class ScrapeControl(): def get_data(): '''This runs the subprocess to actuate the scraper. ''' subprocess.run(['scrapy', 'crawl', 'fleam_spider', '-o', 'result.csv']) return 'ran' def kill_scraper(): if os.path.exists('result.csv'): with open('result.csv', "w+") as f: f.close() print('deleted results') @main.route('/') @main.route('/home', methods=['POST', 'GET']) def index(): ScrapeControl.kill_scraper() form = SearchForm() if request.method == 'POST': query = request.form['query'], city = request.form['city'], price = request.form['price'], db_query = SearchQuery(query, city, price) db.session.add(db_query) db.session.commit() ScrapeControl.get_data() sleep(2) # Redirect here to scrape the data. return redirect(url_for('main.result')) return render_template('index.html', form=form) @main.route('/result') def result(): error = None # Pull items from database db_id = db.session.query(SearchQuery.id).order_by( SearchQuery.id.desc()).first(), db_query = db.session.query(SearchQuery.query).order_by( SearchQuery.id.desc()).first(), db_city = db.session.query(SearchQuery.city).order_by( SearchQuery.id.desc()).first(), db_price = db.session.query(SearchQuery.price).order_by( SearchQuery.id.desc()).first(), city_name = db.session.query(SearchQuery.city).order_by( SearchQuery.id.desc()).first() # cleaning up data. This chooses the first item in database response. id = db_id query = db_query[0] city = db_city[0] price = db_price[0] # Converts tuple to((query, )) to 'query' query = query.query city = city.city price = price.price if 'result.csv': with open('result.csv', 'r') as scraped: response = pd.read_csv(scraped, delimiter=",") df = pd.DataFrame(data=response) #print(f'This is the df variable: {df}') return render_template('result.html', tables=[df.to_html(classes='dataframe', index=False, render_links=True, sparsify=True)], titles=df.columns.values, query=query, city=city ) else: abort(500) return redirect(url_for('main.index')) @main.route('/about') def about(): return render_template('about.html') <file_sep>{% extends 'admin_base.html' %} {% block content %} <div class="login"> <div class="card"> <h1>Fleam</h1> <h2>Login</h2> <form method="POST" > <ul> <li>{{ form.email.label }}</li> <li>{{ form.email }}</li> <li>{{ form.password.label }}</li> <li>{{ form.password }}</li> <li>{{ form.submit }}</li> </ul> <small>Need to <a href="#">register?</a></small> </form> </div> </div> {% endblock %}<file_sep>from flask_sqlalchemy import SQLAlchemy from sqlalchemy import ForeignKey from flask_marshmallow import Marshmallow db = SQLAlchemy() ma = Marshmallow() class User(db.Model): __tablename__ = 'Users' id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String()) last_name = db.Column(db.String()) email = db.Column(db.String()) password = db.Column(db.String()) location = db.Column(db.String()) def __init__(self, first_name, last_name, password, email, location): self.first_name = first_name self.last_name = last_name self.email = email self.password = <PASSWORD> self.location = location def __repr__(self): return f'<id: {self.id} name {self.first_name} {self.last_name}>' class SearchQuery(db.Model): __tablename__ = 'Queries' id = db.Column(db.Integer, primary_key=True) query = db.Column(db.String()) city = db.Column(db.String()) price = db.Column(db.Integer()) def __init__(self, query, city, price): self.query = query self.city = city self.price = price def __repr__(self): return f'<id: {self.id},\n query: {self.query}>' class Results(db.Model): __tablename__ = 'Results' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String()) city = db.Column(db.String()) price = db.Column(db.Integer()) url = db.Column(db.String()) date_posted = db.Column(db.String()) source = db.Column(db.String()) def __init__(self, title, city, price, url, date_posted, source): self.title = title self.city = city self.price = price self.url = url self.date_posted = date_posted self.source = source def __repr__(self): return f'<id: {self.id} Title {self.title}, {self.city}>' #Schema class UserSchema(ma.Schema): class Meta: fields = ('id', 'first_name', 'last_name', 'email') user_schema = UserSchema() users_schema = UserSchema(many=True) class SearchSchema(ma.Schema): class Meta: fields = ('id', 'query', 'city', 'price') search_schema = SearchSchema() searchs_schema = SearchSchema(many=True) class ResultsSchema(ma.Schema): class Meta: fields = ('id', 'title', 'city', 'price', 'url', 'date_posted', 'source') result_schema = ResultsSchema() results_schema = ResultsSchema(many=True)<file_sep>import scrapy from flask import request, g, session, current_app from models import SearchForm from db import db, SearchQuery, search_schema, searchs_schema, ma from app import app # Offer up, Craigslist, FB letgo class FleamSpider(scrapy.Spider): name = "fleam_spider" '''THIS SPIDER TO RECEIVE DATA FROM THE INPUT OF THE FLASK FORM THEORETICALLY FROM DATABASE THAT IT JUST ADDED BEFORE RUNNING''' query = db.session.query(SearchQuery.query).order_by( SearchQuery.id.desc()).first() city = db.session.query(SearchQuery.city).order_by( SearchQuery.id.desc()).first() max_price = db.session.query(SearchQuery.price).order_by( SearchQuery.id.desc()).first() #dbq = db.session.query(SearchQuery.city).order_by(SearchQuery.id.desc()).first() query.query.replace(' ', '%20') # clean up data from db query = query.query city = city.city max_price = max_price.price craigsearch = f'https://{city}.craigslist.org/search/sss?query={query}&max_price={max_price}' offerup_search = f'https://offerup.com/search/?q={query}' # facebook_search = f'https://www.facebook.com/108116349210397/search/?q={query}' recycler = f'https://www.recycler.com/search?keyword={query}&location={city}&category=' hoobly = f'https://www.hoobly.com/search?q={query}' # Running tests with these sites first. start_urls = [ craigsearch, # offerup_search, # hoobly, ] def parse(self, response): # items = FleamscrapeItem() custom_settings = { 'FEED_URI': '/tmp/result.json' } # dbq = SearchQuery.query.order_by(SearchQuery.id.desc()).first() # print(dbq.id) # Choose a search engine to acquire data scrape_sites = ['cl', 'ou', 'fb', 'hbly'] # CraigsList Functionality for search_engine in scrape_sites: if search_engine == 'cl': results = response.css('ul.rows') # Grabbing Craigslist for i in results: for r in i.css('li.result-row'): # title = r.css('a.result-title::text').get() # price = r.css('span::text').get() # Link = r.css('a::attr(href)').get() # date_posted = r.css('time.result-date::text').get() # image = r.xpath( # '/html/body/section/form/div[4]/ul/li[1]/a/div[1]/div/div[1]/img').extract(), # source = 'Craigslist' yield { 'title': r.css('a.result-title::text').get(), 'price': r.css('span::text').get(), 'Link': r.css('a::attr(href)').get(), 'date_posted': r.css('time.result-date::text').get(), # 'image': r.css('a.result-img.gallery').get(), # 'source': 'Craigslist' } # Offer Up Functionality elif search_engine == 'ou': result = response.css('div#db-item-list') # Grabbing Offerup for data in result: for data in result.css('a._109rpto'): # for data in r: title = data.css('span._nn5xny4::text').get() price = data.css('span._s3g03e4::text').get() Link = data.css('a::attr(href)').get() date_posted = None image = data.css('img._ipfql6::attr(src)')[ 1].extract(), source = 'Offer Up' yield { 'title': data.css('span._nn5xny4::text').get(), 'price': data.css('span._s3g03e4::text').get(), 'Link': f'http://www.offerup.com/{Link}', 'date_posted': None, 'image': image[0], 'source': 'Offer Up' } elif search_engine == 'hbly': results_hbl = response.css( 'body > div.container > div > div.col-sm-9.col-md-9.col-lg-9 > table') # Grabbing Craigslist' print(f'This is the thing a thing{results_hbl}') for i in results_hbl: yield { 'title': r.css('#vGEZ4 > td:nth-child(2) > h4 > a').get(), 'price': r.css('span::text').get(), 'Link': r.css('a::attr(href)').get(), 'date_posted': r.css('time.result-date::text').get(), 'image': r.css('a.result-img.gallery').get(), 'source': 'Craigslist' } <file_sep># Search will scrape multiple online marketplaces for items and return lowest to hightest price. from __future__ import unicode_literals from flask_wtf.csrf import CSRFProtect from werkzeug.middleware.proxy_fix import ProxyFix import re from subprocess import Popen, PIPE import subprocess import pandas as pd import csv import bs4 from bs4 import BeautifulSoup import requests import json import os import smtplib from time import sleep from urllib.request import Request, urlopen from datetime import datetime, timedelta from pymongo import MongoClient from wtforms.validators import DataRequired, Email from flask_marshmallow import Marshmallow from flask_migrate import Migrate from flask_pymongo import pymongo from flask_sqlalchemy import SQLAlchemy from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField, SelectField, IntegerField, FloatField from flask import Flask, render_template, jsonify, url_for, flash, redirect, request, flash, jsonify, session, Blueprint #from .selen import ScraperBot app = Flask(__name__) #ui = WebUI(app) app.permanent_session_lifetime = timedelta(minutes=5) app.config.update( # Set the secret key to a sufficiently random value SECRET_KEY=os.urandom(24), # Set the session cookie to be secure SESSION_COOKIE_SECURE=True, # Set the session cookie for our app to a unique name SESSION_COOKIE_NAME='Portfolio-WebSession', # Set CSRF tokens to be valid for the duration of the session. This assumes you’re using WTF-CSRF protection WTF_CSRF_TIME_LIMIT=None, # Configure Environment # FLASK_ENV='production', # Set Flask App # FLASK_APP='app.py', # Debug DEBUG=False ) ### Config ########################################## app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) migrate = Migrate(app, db) ma = Marshmallow(app) date = datetime.utcnow() ######################### Control panel for scraper ####################################### scrape_sites = [('cl', 'Craigslist'), ('ou', 'Offerup'), ('fb', 'Facebook'), ] class RegisterForm(FlaskForm): id = StringField() user = StringField(label='Username', validators=[DataRequired()]) email = StringField(label='Email', validators=[DataRequired()]) password = SelectField(label='Password', choices=scrape_sites) password2 = StringField(label='Password Confirmation', validators=[DataRequired(password)]) metro = StringField(label='Nearest Metro Area') zip_code = IntegerField(label='Zip Code') submit = SubmitField(label='Submit') # input form class FleamForm(FlaskForm): id = StringField() search = StringField(default='Lawnmower') city = StringField(default='Sandusky') selector = SelectField(label='Selector', choices=scrape_sites) distance_miles = StringField(default=50) max_price = IntegerField(default=500) zipcode = IntegerField(default=44870) submit = SubmitField(label='Submit') # DB Creation // Initilization class SearchQuery(db.Model): id = db.Column(db.Integer, primary_key=True) search = db.Column(db.String(120), nullable=False) # Title of search city = db.Column(db.String(120), nullable=False) # Title of search selector = db.Column(db.String(120), nullable=False) # Title of search distance = db.Column(db.Float) # Heighest price to spend price = db.Column(db.Float) # Heighest price to spend zip_code = db.Column(db.Integer) def __init__(self, search, city, selector, distance, price, zip_code): self.search = search self.city = city self.selector = selector self.distance = distance self.price = price self.zip_code = zip_code def __repr__(self): return '<SearchQuery %r>' % self.search class SearchSchema(ma.Schema): class Meta: fields = ('id', 'search', 'city', 'price', 'distance', 'zip_code', 'selector' ) # Init schema search_schema = SearchSchema() searchs_schema = SearchSchema(many=True) class ScrapeControl(): def get_data(): '''This runs the subprocess to actuate the scraper. ''' subprocess.run(['scrapy', 'crawl', 'fleam', '-o', 'result.csv']) return def kill_scraper(): if os.path.exists('result.csv'): with open('result.csv', "w+") as f: f.close() print('deleted results') # Front End # Crawler # Home Page // Search @app.route('/', methods=["POST", "GET"]) @app.route('/index', methods=["POST", "GET"]) def index(): ''' Home Page of FLEAM The purpose of this section is to take in form data, send it through the scrapy scraper attached by the hip, and find the things for the user. ''' ScrapeControl.kill_scraper() form = FleamForm() print(f'Index. {date}') if request.method == 'POST': # handling results from form input print(f'Submitted at {date}') search_query = {} search_query['search'] = form.search.data search_query['city'] = form.city.data search_query['selector'] = form.selector.data search_query['distance'] = form.distance_miles.data search_query['price'] = form.max_price.data search_query['zip_code'] = form.zipcode.data print('after search_query') session["scraper"] = search_query['search'] # cleaning the data for entry into db search = search_query['search'] city = search_query['city'] selector = search_query['selector'] distance = search_query['distance'] price = search_query['price'] zip_code = search_query['zip_code'] print(search_query['search']) # INSERT THE SEARCH INTO THE DATABASE THEN IT CAN BE RETREIVED BY SCRAPY AND RAN new_query = SearchQuery(search, city, selector, distance, price, zip_code) db.session.add(new_query) db.session.commit() # initialize Selenium First (Trial) ScrapeControl.get_data() # Pulls data from Scrapy which includes Craigslist and Offerup # sleep(4) ############## THIS IS WHERE FACEBOOK LIVES ########## #bot = ScraperBot() # sleep(5) # # Facebook # facebook = bot.get_facebook(search) # collect html data from facebook # sleep(2) # fbsoup = BeautifulSoup(facebook, features='html.parser') # # # Now the the data is stored in the data base it will start the scraper and collect and display the results. # with open('facescrape.html', 'w') as facescrape: # facescrape.write(fbsoup) # session['scraper'] = search # # Write a FOR loop to iterate over result date right here # # HTML code line 1753 # for fb in fbsoup: # fb_item = [] # # make this a list full of comma separated values then append each line to csv # # another for loop with the container of the below items # for load in fb.find_all('div', 'fjf4s8hc'): # for i in load.find_all( # 'span', 'oi732d6d ik7dh3pa d2edcug0 qv66sw1b c1et5uql a8c37x1j muag1w35 enqfppq2 jq4qci2q a3bd9o3v knj5qynh oo9gr5id'): # for j in i: # data = j.get_text() # print(f'Data title: = {data}') # fb_item.append([data]) # for h in load.find_all( # 'span', 'oi732d6d ik7dh3pa d2edcug0 qv66sw1b c1et5uql a8c37x1j muag1w35 enqfppq2 a5q79mjw g1cxx5fr lrazzd5p oo9gr5id'): # for j in i: # data = j.get_text() # print(f'Data price: = {data}') # fb_item.append([data]) # for k in load.find_all( # 'a', 'oajrlxb2 g5ia77u1 qu0x051f esr5mh6w e9989ue4 r7d6kgcz rq0escxv nhd2j8a9 nc684nl6 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso i1ao9s8h esuyzwwr f1sip0of lzcic4wl gmql0nx0 p8dawk7l'): # for j in i: # data = j.get_text() # print(f'Data third: = {data}') # fb_item.append([data]) # print(f'This is result for item fb{fb_item}') # fb_item.clear() # # Append FACEBOOK DATA to RESULT.CSV # with open('result.csv', 'w') as f: # # LetGo # letgo = bot.letgo_getter(search) # # sleep(2) # lgsoup = BeautifulSoup(letgo, features='lxml') # # Returns a bunch of HTML # grid = lgsoup.find('div', {'class': 'sc-fzoyAV givzfL'}) # # Iterate over HTML to get Item = [Title, Price, Link] # collection = [] # for div in grid.find_all('div', {'class': 'sc-fzqARJ edUkoJ sc-fzoYkl cLtUmm sc-pZaHX hYxXbw'}): # for div_title in div.find_all('p', 'sc-fznYue gkrhoz'): # title = div_title.get_text() # print(title) # for div_location in div.find_all('p', 'sc-fznYue dkOCRO'): # location = div_location.get_text() # print(location) # # title,price,Link,date_posted,image,source,images,files # Link = None # date_posted = None # image = None # source = 'LetGo' # images = None # files = None # price = None # collection.append( # f'{title},{price},{location},{Link},{date_posted},{image},{source}, \n') # print(collection) # with open('result.csv', 'a') as f: # f.writelines(collection) # collection.clear() # # Write a FOR loop to iterate over result date right here # # Close the browser # bot.close_browser() print('data created successfully') return redirect('result') return render_template('index.html', form=form) @app.route('/result', methods=["POST", "GET"]) def result(): session = {"scraper": "scraper"} if "scraper" in session: search_session = session["scraper"] print(f'''\n From datetime:{date} \n ''') dbq = SearchQuery.query.order_by(SearchQuery.id.desc()).first() query = dbq.search download_link = {} with open('result.csv', 'r') as scraped: response = pd.read_csv(scraped, delimiter=",") df = pd.DataFrame(data=response) print(f'This is the df variable: {df}') return render_template('result.html', tables=[df.to_html(classes='dataframe', index=False, render_links=True, sparsify=True)], titles=df.columns.values, query=query, download_link=download_link) else: return redirect(url_for('index')) @app.route("/login") def login(): if request.method == "POST": user = request.form["nm"] session["user"] = user return redirect(url_for("index")) else: if "user" in session: return redirect(url_for("login")) @app.route("/logout") def logout(): session.pop("scraper", None) return redirect("login") if __name__ == '__main__': app.run()
850376ad82bf22ebc1a0d255852dd1ad94603fc0
[ "Python", "Text", "HTML" ]
10
HTML
Pneuro/fleam-updated
131afb652e23865c5f812ef74454021cf310c7d0
602ff9da7be857c1be957a355242684c110e0618
refs/heads/master
<repo_name>jitendrameghwal/stockmanagement<file_sep>/backend/script.js var express = require('express'); var mysql = require('mysql'); var cors = require('cors') var bodyParser = require('body-parser'); const { response } = require('express'); var app = express(); var connection = mysql.createPool({ multipleStatements: true, connectionLimit: 50, host: 'localhost', user: 'sammy', password: '<PASSWORD>', database: 'Stock' }); app.use(bodyParser.json()); app.use(cors()); app.get('/getProducts', function (req, resp) { connection.getConnection(function (error, tempCont) { if (!!error) { tempCont.release(); console.log('Error'); } else { console.log('Successful execution'); tempCont.query("SELECT * FROM Product", function (error, rows, fields) { tempCont.release(); if (!!error) { console.log('Error'); } else { resp.json(rows); } }); } }); }); app.get('/getWarehouses', function (req, resp) { connection.getConnection(function (error, tempCont) { if (!!error) { tempCont.release(); console.log('Error'); } else { console.log('Successful execution'); tempCont.query("SELECT * FROM Warehouse", function (error, rows, fields) { tempCont.release(); if (!!error) { console.log('Error'); } else { resp.json(rows); } }); } }); }); app.get('/getStock', function (req, resp) { connection.getConnection(function (error, tempCont) { if (!!error) { tempCont.release(); console.log('Error'); } else { console.log('Successful execution'); tempCont.query("SELECT * FROM ProductStock s INNER JOIN Product p ON s.SKU_CODE = p.SKU_CODE", function (error, rows, fields) { tempCont.release(); if (!!error) { console.log('Error'); } else { resp.json(rows); } }); } }); }); app.post('/setProductInfo', function (req, resp) { connection.getConnection(function (error, tempCont) { if (!!error) { tempCont.release(); console.log('Error'); } else { console.log(req); tempCont.query(`UPDATE ProductStock SET ITEM_COUNT=${req.body.ITEM_COUNT}, LOW_ITEM_THRESHOLD=${req.body.LOW_ITEM_THRESHOLD} WHERE SKU_CODE='${req.body.SKU_CODE}'`, function (error, rows, fields) { tempCont.release(); if (!!error) { console.log(error); } else { resp.json({ success: true }); } }); } }); }); app.post('/createWarehouse', function (req, resp) { connection.getConnection(function (error, tempCont) { if (!!error) { tempCont.release(); console.log('Error'); } else { console.log(req); tempCont.query(createQuery(req), function (error, rows, fields) { tempCont.release(); if (!!error) { console.log(error); } else { resp.json({ success: true }); } }); } }); }); function createQuery(req) { var query = `INSERT INTO Warehouse (WH_CODE, MAX_CAPACITY, NAME, PINCODE) VALUES ('${req.body.WH_CODE}', '${req.body.MAX_CAPACITY}', '${req.body.NAME}', '${req.body.PINCODE}');`; req.body.products.forEach(product => { query += `INSERT INTO ProductStock (SKU_CODE, WH_CODE, ITEM_COUNT, LOW_ITEM_THRESHOLD) VALUES ('${product.SKU_CODE}', '${req.body.WH_CODE}', '0', '10');`; }); return query; } app.listen(1337);<file_sep>/Stock.sql -- phpMyAdmin SQL Dump -- version 4.6.6deb5 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Sep 13, 2020 at 07:03 PM -- Server version: 5.7.31-0ubuntu0.18.04.1 -- PHP Version: 7.2.24-0ubuntu0.18.04.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `Stock` -- -- -------------------------------------------------------- -- -- Table structure for table `Product` -- CREATE TABLE `Product` ( `SKU_CODE` char(8) NOT NULL, `NAME` varchar(255) NOT NULL, `PRICE` float NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `Product` -- INSERT INTO `Product` (`SKU_CODE`, `NAME`, `PRICE`) VALUES ('PROD1234', 'PRODUCT1', 123), ('PROD1235', 'Pencil', 8), ('PROD1236', 'PencilBox', 20), ('PROD1237', 'Box', 40), ('PROD1238', 'Rubber', 2), ('PROD1239', 'Sharpner', 5), ('PROD1240', 'Blanket', 200), ('PROD1241', 'Pillow', 200), ('PROD1242', 'Suitcase', 1000), ('PROD1243', 'Bedsheets', 500), ('PROD1244', 'Jumpsuit', 2000), ('PROD1245', 'Leggings', 300), ('PROD1246', 'Bottle', 50), ('PROD1247', 'Milk powder', 110), ('PROD1248', 'Laptop', 50000), ('PROD1249', 'Pendrive', 1800); -- -------------------------------------------------------- -- -- Table structure for table `ProductStock` -- CREATE TABLE `ProductStock` ( `ID` int(11) NOT NULL, `SKU_CODE` varchar(8) NOT NULL, `WH_CODE` varchar(16) NOT NULL, `ITEM_COUNT` int(11) NOT NULL, `LOW_ITEM_THRESHOLD` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `ProductStock` -- INSERT INTO `ProductStock` (`ID`, `SKU_CODE`, `WH_CODE`, `ITEM_COUNT`, `LOW_ITEM_THRESHOLD`) VALUES (1, 'PROD1234', 'WH1234', 20, 12), (2, 'PROD1234', 'WH1235', 20, 12), (3, 'PROD1234', 'WH1236', 20, 12), (4, 'PROD1234', 'WH1236', 20, 12), (5, 'PROD1235', 'WH1236', 20, 100), (6, 'PROD1236', 'WH1236', 10, 7), (7, 'PROD1237', 'WH1236', 10, 8), (8, 'PROD1238', 'WH1236', 10, 9), (9, 'PROD1239', 'WH1236', 99, 99), (26, 'PROD1234', 'BtHgwvJb', 20, 12), (27, 'PROD1235', 'BtHgwvJb', 0, 10), (28, 'PROD1236', 'BtHgwvJb', 0, 10), (29, 'PROD1237', 'BtHgwvJb', 0, 10), (30, 'PROD1238', 'BtHgwvJb', 0, 10), (31, 'PROD1239', 'BtHgwvJb', 0, 10), (32, 'PROD1240', 'BtHgwvJb', 0, 10), (33, 'PROD1241', 'BtHgwvJb', 0, 10), (34, 'PROD1242', 'BtHgwvJb', 0, 10), (35, 'PROD1243', 'BtHgwvJb', 0, 10), (36, 'PROD1244', 'BtHgwvJb', 0, 10), (37, 'PROD1245', 'BtHgwvJb', 0, 10), (38, 'PROD1246', 'BtHgwvJb', 0, 10), (39, 'PROD1247', 'BtHgwvJb', 0, 10), (40, 'PROD1248', 'BtHgwvJb', 0, 10), (41, 'PROD1249', 'BtHgwvJb', 0, 10), (42, 'PROD1234', 'B377rQWq', 20, 12), (43, 'PROD1235', 'B377rQWq', 0, 10), (44, 'PROD1236', 'B377rQWq', 0, 10), (45, 'PROD1237', 'B377rQWq', 0, 10), (46, 'PROD1238', 'B377rQWq', 0, 10), (47, 'PROD1239', 'B377rQWq', 0, 10), (48, 'PROD1240', 'B377rQWq', 0, 10), (49, 'PROD1241', 'B377rQWq', 0, 10), (50, 'PROD1242', 'B377rQWq', 0, 10), (51, 'PROD1243', 'B377rQWq', 0, 10), (52, 'PROD1244', 'B377rQWq', 0, 10), (53, 'PROD1245', 'B377rQWq', 0, 10), (54, 'PROD1246', 'B377rQWq', 0, 10), (55, 'PROD1247', 'B377rQWq', 0, 10), (56, 'PROD1248', 'B377rQWq', 0, 10), (57, 'PROD1249', 'B377rQWq', 0, 10); -- -------------------------------------------------------- -- -- Table structure for table `Warehouse` -- CREATE TABLE `Warehouse` ( `WH_CODE` varchar(16) NOT NULL, `NAME` varchar(255) NOT NULL, `PINCODE` varchar(10) NOT NULL, `MAX_CAPACITY` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `Warehouse` -- INSERT INTO `Warehouse` (`WH_CODE`, `NAME`, `PINCODE`, `MAX_CAPACITY`) VALUES ('B377rQWq', 'Udaipur', '560034', 1234), ('BtHgwvJb', 'Jaipur', '0140', 1234), ('WH1234', 'New Delhi', '110016', 500), ('WH1235', 'Bangalore', '560047', 1500), ('WH1236', 'Mumbai', '400004', 2000); -- -- Indexes for dumped tables -- -- -- Indexes for table `Product` -- ALTER TABLE `Product` ADD PRIMARY KEY (`SKU_CODE`); -- -- Indexes for table `ProductStock` -- ALTER TABLE `ProductStock` ADD PRIMARY KEY (`ID`), ADD KEY `SKU_CODE` (`SKU_CODE`), ADD KEY `WH_CODE` (`WH_CODE`); -- -- Indexes for table `Warehouse` -- ALTER TABLE `Warehouse` ADD PRIMARY KEY (`WH_CODE`), ADD UNIQUE KEY `NAME` (`NAME`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `ProductStock` -- ALTER TABLE `ProductStock` MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=58; -- -- Constraints for dumped tables -- -- -- Constraints for table `ProductStock` -- ALTER TABLE `ProductStock` ADD CONSTRAINT `SKU_CODE` FOREIGN KEY (`SKU_CODE`) REFERENCES `Product` (`SKU_CODE`), ADD CONSTRAINT `WH_CODE` FOREIGN KEY (`WH_CODE`) REFERENCES `Warehouse` (`WH_CODE`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/frontend/src/app/app.component.ts import { Component, OnInit, ViewChild } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Product, Stock, Warehouse } from './models/app.model'; import { FormGroup, NgModel } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less'] }) export class AppComponent implements OnInit { warehouse: Warehouse = new Warehouse(); warehouseErrorMessage: string = null; newWarehouse = false; products: Product[]; showList = true; showProduct = false; currentProduct: Product; productChanges: any = { ITEM_COUNT: null, LOW_ITEM_THRESHOLD: null }; errorMessage: string; stocks: Stock[]; tableData: any; warehouses: Warehouse[]; @ViewChild('productEditForm') productEditForm: FormGroup; @ViewChild('createWarehouseForm') createWarehouseForm: FormGroup; constructor(private httpClient: HttpClient) { } ngOnInit() { this.getProducts(); this.getStock(); this.getWarehouses(); } getProducts() { this.httpClient.get<Product[]>('http://localhost:1337/getProducts') .subscribe((res: Product[]) => { this.products = res; }, err => { console.log(err); }); } getWarehouses() { this.httpClient.get<Warehouse[]>('http://localhost:1337/getWarehouses') .subscribe((res: Warehouse[]) => { this.warehouses = res; }, err => { console.log(err); }); } getStock() { this.httpClient.get<Stock[]>('http://localhost:1337/getStock').subscribe((res: Stock[]) => { this.stocks = res; this.tableData = this.products; this.stocks.map(stock => { const prodIndex = this.tableData.findIndex(data => data.SKU_CODE === stock.SKU_CODE); this.tableData[prodIndex] = { ... this.tableData[prodIndex], [stock.WH_CODE]: { count: stock.ITEM_COUNT, threshold: stock.LOW_ITEM_THRESHOLD } }; }); console.log(this.tableData); this.showList = true; this.newWarehouse = false; this.errorMessage = null; if (!!this.productChanges) { this.productChanges.ITEM_COUNT = null; this.productChanges.LOW_ITEM_THRESHOLD = null; } this.warehouse = new Warehouse(); this.warehouseErrorMessage = null; this.currentProduct = null; this.showProduct = false; }, err => { console.log(err); }); } toggleProduct(product: Product) { this.showList = false; this.showProduct = true; this.newWarehouse = false; this.currentProduct = product; } saveProductDetails() { if (this.productEditForm.valid) { console.log(this.productChanges); this.productChanges = { ...this.productChanges, SKU_CODE: this.currentProduct.SKU_CODE }; const config = { headers: new HttpHeaders().set('Content-Type', 'application/json') }; this.httpClient.post('http://localhost:1337/setProductInfo', JSON.stringify(this.productChanges), config).subscribe( res => { console.log('Done'); this.getStock(); }, err => { this.errorMessage = 'Operation could not be completed. Please try after sometime.'; } ); } } showRed(product: any, wh_code: any) { if (product[wh_code] && (product[wh_code].count < product[wh_code].threshold)) { return true; } return false; } createWarehouse() { this.showProduct = false; this.showList = false; this.newWarehouse = true; } saveWarehouse() { if (this.createWarehouseForm.valid) { console.log(this.warehouse); const config = { headers: new HttpHeaders().set('Content-Type', 'application/json') }; const data = { ...this.warehouse, products: this.products, WH_CODE: this.makeid(8) }; this.httpClient.post('http://localhost:1337/createWarehouse', JSON.stringify(data), config).subscribe( res => { console.log('Done'); setTimeout(() => { this.getStock(); }, 1000) }, err => { this.warehouseErrorMessage = 'Operation could not be completed. Please try after sometime.'; } ); } } makeid(length) { let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } } <file_sep>/README.md Context You need to create a simple live inventory management system that allows storing a list of products, a list of warehouses, count and minimum stock thresholds of all products at all warehouses. ● Product has an 8 character unique sku_code, a name and a price. ● A warehouse has a 4 to 16 character unique wh_code, a name, a pincode and max_capacity. ● For every product at every warehouse, we wish to maintain an item_count and a low_item_threshold. Assignment You need to create a angular.js/node.js/mysql app that does the following - ● On the root url, show the current list of products and their counts in all warehouses in a table with the following structure - ○ The first column contains product sku codes. ○ The second column contains the product names ○ Every warehouse is represented as a column after this showing the count of the product at the warehouse. If a count is below threshold then it is shown with a red background. ○ Clicking on a product code allows us to go to the product edit page. ● Going to a product edit page allows us to change the counts and thresholds of that product at all warehouses. ● Going to create warehouse displays a form that allows creating a warehouse and on creating the warehouse automatically sets a threshold of 10 and a count of 0 for all existing products for that warehouse. <file_sep>/frontend/src/app/models/app.model.ts export class Product { NAME: string; SKU_CODE: string; PRICE: number; } export class Warehouse { constructor() { this.NAME = null; this.WH_CODE = null; this.PINCODE = null; this.MAX_CAPACITY = null; } NAME: string; WH_CODE: string; PINCODE: string; MAX_CAPACITY: number; } export class Stock { ID: number; SKU_CODE: string; WH_CODE: string; ITEM_COUNT: number; LOW_ITEM_THRESHOLD: number; NAME: string; PRICE: number; }
f98c666807d1681bc1ff0869090505bb229ab50a
[ "JavaScript", "SQL", "TypeScript", "Markdown" ]
5
JavaScript
jitendrameghwal/stockmanagement
2a7dec9dc3d341056504a654a09dc1d798b0b01c
43625e7dba6f75bb2d0ac3541997aba6275b68d9
refs/heads/master
<file_sep>#include "ofApp.h" const int MAX_POINTS = 5000000; const int CHECK_NUM_POINTS = 10000; const string FILENAME = "pc.txt"; // pc.txt ofIndexType vi[MAX_POINTS]; ofVec3f v[MAX_POINTS]; ofFloatColor c[MAX_POINTS]; int NUM_POINTS = 0; //-------------------------------------------------------------- void ofApp::setup(){ // --- open file ofFile file; file.open(FILENAME); // open the XYZ file if(!file.exists()){ cout << "geomLayer::loadXYZ => no such file found: " << FILENAME << endl; // TODO: handle the error ofExit(); } if(!file.canRead()) { cout << "geomLayer::loadXYZ => can't read file: " << FILENAME << endl; // TODO: handle the error ofExit(); } // ---- main loop: read lines, save coordinates and track min/max int i = 0; int m = 0; float minX = 9999999; float maxX = -9999999; float minY = 9999999; float maxY = -9999999; string line; while(file.get() != EOF) { getline(file, line); vector<string> coords = ofSplitString(line, " "); float x = ofToFloat(coords[0]); // - 136881.84 - 2500.0 + 19250.0; float y = ofToFloat(coords[1]); //- 487500.0 - 2500.0 + 3500.0; float z = ofToFloat(coords[2]); // * 1.0; //cout << "x: " << setprecision(10) << x << " y: " << y << " z: " << z << endl; if (m == CHECK_NUM_POINTS){ if (x < minX) minX = x; if (x > maxX) maxX = x; if (y < minY) minY = y; if (y > maxY) maxY = y; cout << ofToString(i) + "/" + ofToString(MAX_POINTS) << endl; m = 0; } vi[i] = i; // indices // colors: from blue to yellow c[i].r = ofMap(z, -5.0, 20.0, 0.0, 1.0); c[i].g = ofMap(z, 10.0, 20.0, 0.0, 1.0); c[i].b = ofMap(z, -5.0, 20.0, 0.5, 0.1);; // coordinates v[i][0] = x; v[i][1] = y; v[i][2] = z; // iteration i++; m++; // reach max of points if (i >= MAX_POINTS){ break; } } NUM_POINTS = i; // center cloud float centerX = (maxX - minX)/2.0 + minX; float centerY = (maxY - minY)/2.0 + minY ; cout << "x: [" << setprecision(10) << minX << "-" << maxX << "] y: [" << minY << "-" << maxY << "]" << endl; cout << "center: [ " << centerX << "," << centerY << endl; for (int p = 0; p < NUM_POINTS; p++) { v[p][0] -= centerX; v[p][1] -= centerY; } // --- vbo.setVertexData( &v[0], NUM_POINTS, GL_STATIC_DRAW ); vbo.setColorData( &c[0], NUM_POINTS, GL_STATIC_DRAW ); vbo.setIndexData( &vi[0], NUM_POINTS, GL_STATIC_DRAW ); //glEnable(GL_DEPTH_TEST); ofEnableDepthTest(); glPointSize(2.0); cam = ofEasyCam(); ofSetVerticalSync(true); glEnable(GL_POINT_SMOOTH); ofBackground(0,0,0); } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ cam.begin(); vbo.drawElements( GL_POINTS, NUM_POINTS); ofSetWindowTitle(ofToString(ofGetFrameRate())); cam.end(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <file_sep># ahn2viewer Simple but quick viewer for pointclouds in XYZ text format. Using GL VBO 10M points without any performance hit. Nice for playing with Dutch AHN2 dataset. Usage: * Download and install a IDE. I used free and open source Code::Blocks http://www.codeblocks.org/ * Download and install OpenFrameworks lib: http://openframeworks.cc/ * Open the .workspace file in repository in CodeBlocks * Compile and run It should look like this: http://oscity.eu/projects/ahn2-testrun/ * a test XYZ pointcloud file is located in the bin/data directory (thanks to <NAME>, tjoadesign.nl) * you can download LAZ files of you favorite part of the Netherlands via the AHN2 Website: http://www.ahn.nl/index.html * convert from LAZ to XYZ with LasTools: http://www.cs.unc.edu/~isenburg/lastools/ Licence: WTFPL
6861b2f34e6a9a312f47e011e7894083e6e4b497
[ "Markdown", "C++" ]
2
C++
OSCityNL/pointcloud-viewer
b752cfbe052023a2c79a71de60dc9ae085ea08f3
d90ef3fa0b787c948616e94cb66aabdade4cbe73
refs/heads/master
<file_sep>const app = getApp() const innerAudioContext = wx.createInnerAudioContext() innerAudioContext.autoplay = false innerAudioContext.loop = true innerAudioContext.src = '/pages/letter/mp3/happy.mp3' Page({ data: { }, onLoad: function () { innerAudioContext.play(); }, })
692a1379ddfa76e07c2f75a952debf82f2fe6ae5
[ "JavaScript" ]
1
JavaScript
cuiyinghh/happy_wx
d618bc65fae05d294368c76559dde692012d129f
6055d94cdb305ae41bd3fc9854747d4485c10a5c
refs/heads/master
<file_sep>using System; namespace Lab1Ex1 { class Program { static void Main(string[] args) { string msg = MessageProvider.Provider.GetMessage(); msg = System.Web.HttpUtility.UrlEncode(msg); Console.WriteLine(msg); Console.ReadLine(); } } } <file_sep>using System; class Program { static void Main(string[] args) { Employee emp1 = CreateEmployee(); Console.WriteLine(emp1); Employee emp2 = emp1; Console.WriteLine(emp1.Equals(emp2)); Employee emp3 = CreateEmployee(); Console.WriteLine(emp1.Equals(emp3)); } static Employee CreateEmployee() { Employee emp = new Employee(); emp.ID = 100; emp.FirstName = "Motti"; emp.LastName = "Shaked"; return emp; } } class Employee { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public override string ToString() { return "Employee " + this.ID + ": " + this.FirstName + " " + this.LastName; } public override bool Equals(object obj) { // this object is not null - if the other is null return false if (obj == null) return false; // make sure the object is of the same type // don't use is or as because it can be satisfied if // the compared object derives from Employee if (obj.GetType() != this.GetType()) return false; // cast Employee otherEmp = (Employee)obj; // compare id // probably enough in the case of Employee // because we don't expect two different employees of the same id // in other cases you may want to compare everything return otherEmp.ID == this.ID; } public override int GetHashCode() { return this.ID; } }
d2eadd74e110c0cc128741be256610902f275a0e
[ "C#" ]
2
C#
stavrossk/Motti_Shaked_.NET_Tutorial_Lab_Exercises
c7c55bedc606a2215df56910fa85a650c9b4cec0
7863f008b9242d94fe52d7725cdd6b5468cf8438
refs/heads/master
<repo_name>agaric/image_resize_filter<file_sep>/src/Plugin/Filter/FilterImageResize.php <?php namespace Drupal\image_resize_filter\Plugin\Filter; use Drupal\Core\Image\ImageFactory; use Symfony\Component\DependencyInjection\ContainerInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Drupal\filter\FilterProcessResult; use Drupal\filter\Plugin\FilterBase; use Drupal\Core\Form\FormStateInterface; /** * Provides a filter to resize images. * * @Filter( * id = "filter_image_resize", * title = @Translation("Image resize filter"), * description = @Translation("The image resize filter analyze <img> tags and compare the given height and width attributes to the actual file. If the file dimensions are different than those given in the <img> tag, the image will be copied and the src attribute will be updated to point to the resized image."), * type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE, * settings = { * "image_locations" = {}, * } * ) */ class FilterImageResize extends FilterBase implements ContainerFactoryPluginInterface { /** * ImageFactory instance. * * @var \Drupal\Core\Image\ImageFactory */ protected $imageFactory; /** * FilterImageResize constructor. * @param array $configuration * @param string $plugin_id * @param mixed $plugin_definition * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository * The entity Repository. * @param \Drupal\Core\Image\ImageFactory $image_factory * Image Factory. */ public function __construct( array $configuration, $plugin_id, $plugin_definition, ImageFactory $image_factory) { parent::__construct($configuration, $plugin_id, $plugin_definition); $this->imageFactory = $image_factory; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get('image.factory') ); } /** * {@inheritdoc} */ public function process($text, $langcode) { return new FilterProcessResult($this->getImages($text)); } /** * Locate all images in a piece of text that need replacing. * * An array of settings that will be used to identify which images need * updating. Includes the following: * * - image_locations: An array of acceptable image locations. * of the following values: "remote". Remote image will be downloaded and * saved locally. This procedure is intensive as the images need to * be retrieved to have their dimensions checked. * * @param string $text * The text to be updated with the new img src tags. * * @return string $images * An list of images. */ private function getImages($text) { $images = image_resize_filter_get_images($this->settings, $text); $search = []; $replace = []; foreach ($images as $image) { // Copy remote images locally. if ($image['location'] == 'remote') { $local_file_path = 'resize/remote/' . md5(file_get_contents($image['local_path'])) . '-' . $image['expected_size']['width'] . 'x' . $image['expected_size']['height'] . '.'. $image['extension']; $image['destination'] = file_default_scheme() . '://' . $local_file_path; } // Destination and local path are the same if we're just adding attributes. elseif (!$image['resize']) { $image['destination'] = $image['local_path']; } else { $path_info = image_resize_filter_pathinfo($image['local_path']); $local_file_dir = file_uri_target($path_info['dirname']); $local_file_path = 'resize/' . ($local_file_dir ? $local_file_dir . '/' : '') . $path_info['filename'] . '-' . $image['expected_size']['width'] . 'x' . $image['expected_size']['height'] . '.' . $path_info['extension']; $image['destination'] = $path_info['scheme'] . '://' . $local_file_path; } if (!file_exists($image['destination'])) { // Basic flood prevention of resizing. $resize_threshold = 10; $flood = \Drupal::flood(); if (!$flood->isAllowed('image_resize_filter_resize', $resize_threshold, 120)) { drupal_set_message(t('Image resize threshold of @count per minute reached. Some images have not been resized. Resave the content to resize remaining images.', ['@count' => floor($resize_threshold / 2)]), 'error', FALSE); continue; } $flood->register('image_resize_filter_resize', 120); // Create the resize directory. $directory = dirname($image['destination']); file_prepare_directory($directory, FILE_CREATE_DIRECTORY); // Move remote images into place if they are already the right size. if ($image['location'] == 'remote' && !$image['resize']) { $handle = fopen($image['destination'], 'w'); fwrite($handle, file_get_contents($image['local_path'])); fclose($handle); } // Resize the local image if the sizes don't match. elseif ($image['resize']) { $copy = file_unmanaged_copy($image['local_path'], $image['destination'], FILE_EXISTS_RENAME); $res = $this->imageFactory->get($copy); if ($res) { // Image loaded successfully; resize. $res->resize($image['expected_size']['width'], $image['expected_size']['height']); $res->save(); } else { // Image failed to load - type doesn't match extension or invalid; keep original file $handle = fopen($image['destination'], 'w'); fwrite($handle, file_get_contents($image['local_path'])); fclose($handle); } } @chmod($image['destination'], 0664); } // Delete our temporary file if this is a remote image. image_resize_filter_delete_temp_file($image['location'], $image['local_path']); // Replace the existing image source with the resized image. // Set the image we're currently updating in the callback function. $search[] = $image['img_tag']; $replace[] = image_resize_filter_image_tag($image, $this->settings); } return str_replace($search, $replace, $text); } /** * {@inheritdoc} */ function settingsForm(array $form, FormStateInterface $form_state) { $settings['image_locations'] = [ '#type' => 'checkboxes', '#title' => $this->t('Resize images stored'), '#options' => [ 'local' => $this->t('Locally'), 'remote' => $this->t('On remote servers (note: this copies <em>all</em> remote images locally)') ], '#default_value' => $this->settings['image_locations'], '#description' => $this->t('This option will determine which images will be analyzed for &lt;img&gt; tag differences. Enabling resizing of remote images can have performance impacts, as all images in the filtered text needs to be transferred via HTTP each time the filter cache is cleared.'), ]; return $settings; } }
89dd4637b1752a7122e818e0e40bd4aff126e20d
[ "PHP" ]
1
PHP
agaric/image_resize_filter
d05f988b7308156d86b7b19d3952f1cd5c7c7ec5
bc630dfed723b84f0d725be0c2677c7db3452720
refs/heads/master
<file_sep>#ifndef _DC_LOC_H #define _DC_LOC_H #include "lsa_cldap.h" DOMAIN_CONTROLLER_INFO * dc_locate(const char *, const char *); #endif /* _DC_LOC_H */ <file_sep>#include <stdlib.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <poll.h> #include <netdb.h> #include <ldap.h> #include <lber.h> #include <string.h> #include <sys/socket.h> #include "lsa_cldap.h" #include "lsa_srv.h" static int lsa_bind() { int fd; struct sockaddr_in6 addr; if ((fd = socket(PF_INET6, SOCK_DGRAM, 0)) < 0) return (fd); /* * Bind to all available addresses and any port. */ addr.sin6_family = AF_INET6; addr.sin6_addr = in6addr_any; addr.sin6_port = 0; if (bind(fd, (struct sockaddr *)&addr, sizeof (addr)) < 0) goto fail; return (fd); fail: (void) close(fd); return (-1); } void lsa_srv_output(lsa_srv_ctx_t *ctx) __attribute__((weak)); DOMAIN_CONTROLLER_INFO * dc_locate(const char *prefix, const char *dname) { lsa_srv_ctx_t *ctx; srv_rr_t *sr; BerElement *pdu = NULL, *ret; struct _berelement *be, *rbe; DOMAIN_CONTROLLER_INFO *dci = NULL; int r, fd = -1; struct sockaddr_storage addr; struct sockaddr_in6 *paddr; socklen_t addrlen; char *dcaddr = NULL, *dcname = NULL; ctx = lsa_srv_init(); if (ctx == NULL) goto fail; r = lsa_srv_lookup(ctx, prefix, dname); if (r <= 0) goto fail; if (lsa_srv_output) lsa_srv_output(ctx); if ((fd = lsa_bind()) < 0) goto fail; if ((pdu = ber_alloc()) == NULL) goto fail; /* * Is ntver right? It certainly works on w2k8... If others are needed, * that might require changes to lsa_cldap_parse */ r = lsa_cldap_setup_pdu(pdu, dname, NULL, NETLOGON_NT_VERSION_5EX); struct pollfd pingchk = {fd, POLLIN, 0}; if ((dcaddr = malloc(INET6_ADDRSTRLEN + 2)) == NULL) goto fail; if (strncpy(dcaddr, "\\\\", 3) == NULL) goto fail; if ((dcname = malloc(MAXHOSTNAMELEN + 3)) == NULL) goto fail; be = (struct _berelement *)pdu; sr = NULL; while ((sr = lsa_srv_next(ctx, sr)) != NULL) { r = sendto(fd, be->ber_buf, (size_t)(be->ber_end - be->ber_buf), 0, (struct sockaddr *)&sr->addr, sizeof(sr->addr)); if (poll(&pingchk, 1, 100) == 0) continue; if ((ret = ber_alloc()) == NULL) goto fail; rbe = (struct _berelement *)ret; recvfrom(fd, rbe->ber_buf, (size_t)(rbe->ber_end - rbe->ber_buf), 0, (struct sockaddr *)&addr, &addrlen); if ((dci = malloc(sizeof (DOMAIN_CONTROLLER_INFO))) == NULL) { ber_free(ret, 1); goto fail; } dci->DomainControllerName = dcname; r = lsa_cldap_parse(ret, dci); ber_free(ret, 1); if (r == 0) break; if (r > 1) goto fail; } if (sr == NULL) goto fail; paddr = (struct sockaddr_in6 *)&addr; inet_ntop(paddr->sin6_family, &paddr->sin6_addr, dcaddr+2, INET6_ADDRSTRLEN); dci->DomainControllerAddress = dcaddr; dci->DomainControllerAddressType = DS_INET_ADDRESS; ber_free(pdu, 1); lsa_srv_fini(ctx); (void) close(fd); return (dci); fail: lsa_srv_fini(ctx); if (dci) freedci(dci); else free(dcname); free(dcaddr); ber_free(pdu, 1); if (fd >= 0) (void) close(fd); return (NULL); } <file_sep>/* * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. */ /* * Copyright 2013 Nexenta Systems, Inc. All rights reserved. */ #include <stdlib.h> #include <stdio.h> #include <stddef.h> #include <inttypes.h> #include <string.h> #include <netdb.h> #include "lsa_cldap.h" extern int ldap_put_filter(BerElement *ber, char *); static int lsa_cldap_escape_le64(char *buf, uint64_t val, int bytes) { char *p = buf; while (bytes != 0) { p += sprintf(p, "\\%.2" PRIx8, (uint8_t)(val & 0xff)); val >>= 8; bytes--; } return (p - buf); } /* * Construct CLDAPMessage PDU for NetLogon search request. * * CLDAPMessage ::= SEQUENCE { * messageID MessageID, * protocolOp searchRequest SearchRequest; * } * * SearchRequest ::= * [APPLICATION 3] SEQUENCE { * baseObject LDAPDN, * scope ENUMERATED { * baseObject (0), * singleLevel (1), * wholeSubtree (2) * }, * derefAliases ENUMERATED { * neverDerefAliases (0), * derefInSearching (1), * derefFindingBaseObj (2), * derefAlways (3) * }, * sizeLimit INTEGER (0 .. MaxInt), * timeLimit INTEGER (0 .. MaxInt), * attrsOnly BOOLEAN, * filter Filter, * attributes SEQUENCE OF AttributeType * } */ int lsa_cldap_setup_pdu(BerElement *ber, const char *dname, const char *host, uint32_t ntver) { int ret = 0, len = 0, msgid; char *basedn = ""; int scope = LDAP_SCOPE_BASE, deref = LDAP_DEREF_NEVER, sizelimit = 0, timelimit = 0, attrsonly = 0; char filter[MAXHOSTNAMELEN]; char ntver_esc[13]; /* * XXX Crappy semi-unique msgid. */ msgid = gethrtime() & 0xffff; /* * Encode CLDAPMessage and beginning of SearchRequest sequence. */ if (ber_printf(ber, "{it{seeiib", msgid, LDAP_REQ_SEARCH, basedn, scope, deref, sizelimit, timelimit, attrsonly) < 0) goto fail; /* * Format NtVer as little-endian with LDAPv3 escapes. */ lsa_cldap_escape_le64(ntver_esc, ntver, sizeof (ntver)); /* * Construct search filter in LDAP format. */ len += snprintf(filter, sizeof (filter), "(&(DnsDomain=%s)", dname); if (len >= sizeof (filter)) goto fail; if (host != NULL) { len += snprintf(filter + len, sizeof (filter) - len, "(Host=%s)", host); if (len >= sizeof (filter)) goto fail; } len += snprintf(filter + len, sizeof (filter) - len, "(NtVer=%s))", ntver_esc); if (len >= sizeof (filter)) goto fail; /* * Encode Filter sequence. */ if (ldap_put_filter(ber, filter) < 0) goto fail; /* * Encode attribute and close Filter and SearchRequest sequences. */ if (ber_printf(ber, "{s}}}", NETLOGON_ATTR_NAME) < 0) goto fail; /* * Success */ ret = msgid; fail: if (ret < 0) ber_free(ber, 1); return (ret); } /* * Parse incoming search responses and attribute to correct hosts. * * CLDAPMessage ::= SEQUENCE { * messageID MessageID, * searchResponse SEQUENCE OF * SearchResponse; * } * * SearchResponse ::= * CHOICE { * entry [APPLICATION 4] SEQUENCE { * objectName LDAPDN, * attributes SEQUENCE OF SEQUENCE { * AttributeType, * SET OF * AttributeValue * } * }, * resultCode [APPLICATION 5] LDAPResult * } */ static int lsa_decode_name(uchar_t *base, uchar_t *cp, char *str) { uchar_t *tmp = NULL, *st = cp; uint8_t len; /* * there should probably be some boundary checks on str && cp * maybe pass in strlen && msglen ? */ while (*cp != 0) { if (*cp == 0xc0) { if (tmp == NULL) tmp = cp + 2; cp = base + *(cp+1); } for (len = *cp++; len > 0; len--) *str++ = *cp++; *str++ = '.'; } if (cp != st) *(str-1) = '\0'; else *str = '\0'; return ((tmp == NULL ? cp+1 : tmp) - st); } int lsa_cldap_parse(BerElement *ber, DOMAIN_CONTROLLER_INFO *dci) { uchar_t *base = NULL, *cp = NULL; char val[512]; /* how big should val be? */ int l, i, msgid, rc = 0; uint16_t opcode; uint8_t *gid = dci->DomainGuid; field_5ex_t f = OPCODE; /* * Later, compare msgid's/some validation? */ if (ber_scanf(ber, "{i{x{{x[la", &msgid, &l, &cp) == LBER_ERROR) { rc = 1; goto out; } for (base = cp; ((cp - base) < l) && (f <= LM_20_TOKEN); f++) { val[0] = '\0'; switch(f) { case OPCODE: opcode = *(uint16_t *)cp; cp +=2; /* If there really is an alignment issue, when can do this opcode = *cp++; opcode |= (*cp++ << 8); */ break; case SBZ: cp +=2; break; case FLAGS: dci->Flags = *(uint32_t *)cp; cp +=4; /* If there really is an alignment issue, when can do this dci->Flags = *cp++; for(i = 1; i < 4; i++) dci->Flags |= (*cp++ << 8*i); */ break; case DOMAIN_GUID: for (i = 0; i < 16; i++) gid[i] = *cp++; break; case FOREST_NAME: cp += lsa_decode_name(base, cp, val); if ((dci->DnsForestName = strdup(val)) == NULL) { rc = 2; goto out; } break; case DNS_DOMAIN_NAME: cp += lsa_decode_name(base, cp, val); if ((dci->DomainName = strdup(val)) == NULL) { rc = 2; goto out; } break; case DNS_HOST_NAME: cp += lsa_decode_name(base, cp, val); if (((strncpy(dci->DomainControllerName, "\\\\", 3)) == NULL) || (strcat(dci->DomainControllerName, val) == NULL)) { rc = 2; goto out; } break; case NET_DOMAIN_NAME: /* * DCI doesn't seem to use this */ cp += lsa_decode_name(base, cp, val); break; case NET_COMP_NAME: /* * DCI doesn't seem to use this */ cp += lsa_decode_name(base, cp, val); break; case USER_NAME: /* * DCI doesn't seem to use this */ cp += lsa_decode_name(base, cp, val); break; case DC_SITE_NAME: cp += lsa_decode_name(base, cp, val); if ((dci->DcSiteName = strdup(val)) == NULL) { rc = 2; goto out; } break; case CLIENT_SITE_NAME: cp += lsa_decode_name(base, cp, val); if (((dci->ClientSiteName = strdup(val)) == NULL) && (val[0] != '\0')) { rc = 2; goto out; } break; /* * These are all possible, but we don't really care about them. * Sockaddr_size && sockaddr might be useful at some point */ case SOCKADDR_SIZE: case SOCKADDR: case NEXT_CLOSEST_SITE_NAME: case NTVER: case LM_NT_TOKEN: case LM_20_TOKEN: break; default: rc = 3; goto out; } } out: if (base) free(base); else if (cp) free(cp); return (rc); } void freedci(DOMAIN_CONTROLLER_INFO *dci) { if (dci == NULL) return; free(dci->DomainControllerName); free(dci->DomainControllerAddress); free(dci->DomainName); free(dci->DnsForestName); free(dci->DcSiteName); free(dci->ClientSiteName); free(dci); } <file_sep>#include "dc_locate.h" #include "lsa_srv.h" #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <inttypes.h> void lsa_srv_output(lsa_srv_ctx_t *ctx) { srv_rr_t *sr = NULL; char buf[INET6_ADDRSTRLEN]; while ((sr = lsa_srv_next(ctx, sr)) != NULL) { inet_ntop(sr->addr.sin6_family, &sr->addr.sin6_addr, buf, INET6_ADDRSTRLEN); printf("target %s:%" PRIu16 ", pri %" PRIu16 ", weight %" PRIu16 " addr %s\n", sr->sr_name, sr->sr_port, sr->sr_priority, sr->sr_weight, buf); } printf("\n"); } int main(int argc, char *argv[]) { DOMAIN_CONTROLLER_INFO *dci; int i; if (argc < 3) { printf("usage: ./a.out prefix dname\n"); return 0; } dci = dc_locate(argv[1], argv[2]); if (dci != NULL) { printf("DomainControllerName: %s\n", dci->DomainControllerName); printf("DomainControllerAddress: %s\n", dci->DomainControllerAddress); printf("DomainControllerAddressType: %d\n", dci->DomainControllerAddressType); printf("DomainGuid: "); printf("%x", *((unsigned int *)dci->DomainGuid)); printf("-"); for(i = 0; i < 2; i++) { printf("%x", *((unsigned short *)(dci->DomainGuid+4+2*i)) & 0xffff); printf("-"); } int j; for(i = j = 8; i - j < 2; i++) printf("%x", *(dci->DomainGuid+i) & 0xff); printf("-"); for(i = j = 10; i - j < 6; i++) printf("%x", *(dci->DomainGuid+i) & 0xff); printf("\n"); printf("DomainName: %s\n", dci->DomainName); printf("DnsForestName: %s\n", dci->DnsForestName); printf("Flags: 0x%lx\n", dci->Flags); printf("DcSiteName: %s\n", dci->DcSiteName); printf("ClientSiteName: %s\n", dci->ClientSiteName); } freedci(dci); return 0; } <file_sep>/* * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. */ /* * Copyright 2013 Nexenta Systems, Inc. All rights reserved. */ #ifndef _LSA_SRV_H #define _LSA_SRV_H #include <sys/list.h> #include <resolv.h> #define s6_addr8 _S6_un._S6_u8 #define s6_addr32 _S6_un._S6_u32 #define P_SUCCESS 0 #define P_ERR_SKIP 1 /* ignored a record - continue parsing */ #define P_ERR_FAIL -1 /* parsing failed */ typedef struct addr_rr { list_node_t addr_node; char *name; in6_addr_t *addr; int type; } addr_rr_t; typedef struct srv_rr { list_node_t sr_node; boolean_t sr_used; char *sr_name; uint16_t sr_port; uint16_t sr_priority; uint16_t sr_weight; struct sockaddr_in6 addr; } srv_rr_t; typedef struct lsa_srv_ctx { struct __res_state lsc_state; list_t lsc_list; } lsa_srv_ctx_t; void lsa_srvlist_sort(lsa_srv_ctx_t *ctx); lsa_srv_ctx_t *lsa_srv_init(void); void lsa_srv_fini(lsa_srv_ctx_t *); int lsa_srv_lookup(lsa_srv_ctx_t *, const char *, const char *); srv_rr_t *lsa_srv_next(lsa_srv_ctx_t *, srv_rr_t *); #endif /* _LSA_SRV_H */ <file_sep>#include <ldap.h> #include <resolv.h> #include <netinet/in.h> #include <arpa/nameser.h> #include <string.h> #include <stdio.h> #include <netdb.h> #include "lsa_cldap.h" int main(int argc, char *argv[]){ DOMAIN_CONTROLLER_INFO *dci; int r; if ((dci = malloc(sizeof (DOMAIN_CONTROLLER_INFO))) == NULL) { return 1; } memset(dci, 0, sizeof(*dci)); BerElement *ret = ber_alloc(); struct _berelement *re = ret; char c = 0; int i = 0; char *rbe = re->ber_buf; while((c = getchar()) != EOF) rbe[i++] = c; dci->DomainControllerName = malloc(MAXHOSTNAMELEN + 3); r = lsa_cldap_parse(ret, dci); printf("%d\n",r); printf("DomainControllerName: %s\n", dci->DomainControllerName); printf("DomainControllerAddress: %s\n", dci->DomainControllerAddress); printf("DomainControllerAddressType: %l\n", dci->DomainControllerAddressType); printf("DomainGuid: "); printf("%x", *((unsigned int *)dci->DomainGuid)); printf("-"); for(i = 0; i < 2; i++) { printf("%x", *((unsigned short *)(dci->DomainGuid+4+2*i)) & 0xffff); printf("-"); } int j; for(i = j = 8; i - j < 2; i++) printf("%x", *(dci->DomainGuid+i) & 0xff); printf("-"); for(i = j = 10; i - j < 6; i++) printf("%x", *(dci->DomainGuid+i) & 0xff); printf("\n"); printf("DomainName: %s\n", dci->DomainName); printf("DnsForestName: %s\n", dci->DnsForestName); printf("Flags: 0x%lx\n", dci->Flags); printf("DcSiteName: %s\n", dci->DcSiteName); printf("ClientSiteName: %s\n", dci->ClientSiteName); ber_free(ret, 1); freedci(dci); /* in6_addr_t t; int i; unsigned int a; char c[4] = {0xcc, 0x98, 0xba, 0x33}; char *cp = c; unsigned short *n = &t; char *p = &a; inet_pton(AF_INET6, "fdf8:f53e:61e4::18", &t); */ /* for(i = 0 ; i < 4 ; i++) printf("0x%x %x\n", cp+i, (c[i] & 0xff)); NS_GET32(a, cp); */ /* for(i = 0 ; i < 8 ; i++) printf("0x%x %x\n", n+i, (n[i])); */ /* for(i = 0 ; i < 4 ; i++) printf("0x%x %x\n", p+i, (p[i] && 0xff)); */ while(1); return 0; } <file_sep>#include "lsa_cldap.h" #include "lsa_srv.h" DOMAIN_CONTROLLER_INFO * dc_locate(const char *svcname, const char *dname) { lsa_cldap_t *lc; lsa_cldap_host_t *lch; lsa_srv_ctx_t *ctx; srv_rr_t *sr = NULL; DOMAIN_CONTROLLER_INFO *dci = NULL; int r; ctx = lsa_srv_init(); if (ctx == NULL) return (1); r = lsa_srv_lookup(ctx, svcname, dname); if (r < 0) return (1); lc = lsa_cldap_init(); while((sr = lsa_srv_next(ctx, sr)) != NULL) { lch = lsa_cldap_open(lc, sr->sr_name, LDAP_PORT); r = lsa_cldap_net_logon_search(lc, lch, sr->sr_name, ntver); if (r != 0) { lsa_cldap_close(lch); continue; } /* XXX reply/timeout? */ lsa_cldap_close(lch); if ((lch = lsa_cldap_netlogon_reply(lc)) != NULL) break; } if (lch != NULL) { dci = (DOMAIN_CONTROLLER_INFO *) malloc(sizeof (DOMAIN_CONTROLLER_INFO)); *dci = lch-> <file_sep>/* * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. */ /* * Copyright 2013 Nexenta Systems, Inc. All rights reserved. */ #include <stdio.h> #include <inttypes.h> #include "lsa_srv.h" int main(int argc, char **argv) { lsa_srv_ctx_t *ctx; int r; srv_rr_t *sr = NULL; if (argc != 3) { fprintf(stderr, "usage: %s rr domain\n", argv[0]); return (1); } ctx = lsa_srv_init(); if (ctx == NULL) { return (1); } printf("attempting lookup for %s in domain %s\n", argv[1], argv[2]); r = lsa_srv_lookup(ctx, argv[1], argv[2]); if (r < 0) { fprintf(stderr, "error in lookup\n"); return (1); } while ((sr = lsa_srv_next(ctx, sr)) != NULL) { printf("target %s:%" PRIu16 ", pri %" PRIu16 ", weight %" PRIu16 " %d\n", sr->sr_name, sr->sr_port, sr->sr_priority, sr->sr_weight, sr->addr.sin6_addr); } lsa_srv_fini(ctx); return (0); } <file_sep>/* * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. */ /* * Copyright 2013 Nexenta Systems, Inc. All rights reserved. */ #ifndef _LSA_CLDAP_H #define _LSA_CLDAP_H #include <ldap.h> #include <sys/list.h> typedef struct _DOMAIN_CONTROLLER_INFO { char *DomainControllerName; char *DomainControllerAddress; unsigned long DomainControllerAddressType; uint8_t DomainGuid[16]; char *DomainName; char *DnsForestName; unsigned long Flags; char *DcSiteName; char *ClientSiteName; } DOMAIN_CONTROLLER_INFO; struct _berelement { char *ber_buf; char *ber_ptr; char *ber_end; }; #define DS_INET_ADDRESS 0x0001 #define DS_NETBIOS_ADDRESS 0x0002 #define DS_PDC_FLAG 0x00000001 /* DC is PDC of domain */ #define DS_GC_FLAG 0x00000004 /* DC is GC server for forest */ #define DS_LDAP_FLAG 0x00000008 /* LDAP server */ #define DS_DS_FLAG 0x00000010 /* DC is DS server for domain */ #define DS_KDC_FLAG 0x00000020 /* DC is KDC for domain */ #define DS_TIMESERV_FLAG 0x00000040 /* DC has time service */ #define DS_CLOSEST_FLAG 0x00000080 /* DC in same site as client */ #define DS_WRITABLE_FLAG 0x00000100 /* Writable directory service */ #define DS_GOOD_TIMESERV_FLAG 0x00000200 /* Time service is reliable */ #define DS_NDNC_FLAG 0x00000400 /* Name context not a domain */ #define DS_SELECT_SECRET_DOMAIN_6_FLAG 0x00000800 /* Read-only W2k8 DC */ #define DS_FULL_SECRET_DOMAIN_6_FLAG 0x00001000 /* Writable W2k8 DC */ #define DS_PING_FLAGS 0x0000ffff /* Flags returned on ping */ #define DS_DNS_CONTROLLER_FLAG 0x20000000 /* DC name is DNS format */ #define DS_DNS_DOMAIN_FLAG 0x40000000 /* Domain name is DNS format */ #define DS_DNS_FOREST_FLAG 0x80000000 /* Forest name is DNS format */ #define NETLOGON_ATTR_NAME "NetLogon" #define NETLOGON_NT_VERSION_1 0x00000001 #define NETLOGON_NT_VERSION_5 0x00000002 #define NETLOGON_NT_VERSION_5EX 0x00000004 #define NETLOGON_NT_VERSION_5EX_WITH_IP 0x00000008 #define NETLOGON_NT_VERSION_WITH_CLOSEST_SITE 0x00000010 #define NETLOGON_NT_VERSION_AVOID_NT4EMUL 0x01000000 typedef enum { OPCODE = 0, SBZ, FLAGS, DOMAIN_GUID, FOREST_NAME, DNS_DOMAIN_NAME, DNS_HOST_NAME, NET_DOMAIN_NAME, NET_COMP_NAME, USER_NAME, DC_SITE_NAME, CLIENT_SITE_NAME, SOCKADDR_SIZE, SOCKADDR, NEXT_CLOSEST_SITE_NAME, NTVER, LM_NT_TOKEN, LM_20_TOKEN } field_5ex_t; int lsa_cldap_setup_pdu(BerElement *, const char *, const char *, uint32_t); int lsa_cldap_parse(BerElement *, DOMAIN_CONTROLLER_INFO *); void freedci(DOMAIN_CONTROLLER_INFO *); #endif /* _LSA_CLDAP_H */ <file_sep>all: gcc -g -c dc_locate.c gcc -g -c lsa_cldap.c gcc -g -c lsa_srv.c gcc -g test_dc.c lsa_cldap.o lsa_srv.o dc_locate.o -lldap -lsocket -lnsl -lresolv -lcmdutils -lumem <file_sep>/* * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. */ /* * Copyright 2013 Nexenta Systems, Inc. All rights reserved. */ /* * DNS SRV record lookup for AD Domain Controllers. */ #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <inttypes.h> #include <netinet/in.h> #include <arpa/nameser.h> #include <resolv.h> #include <netdb.h> #include <ldap.h> #include "lsa_srv.h" static void lsa_srvlist_insert(list_t *l, srv_rr_t *rr) { srv_rr_t *sr; uint16_t pri = rr->sr_priority; uint16_t weight = rr->sr_weight; for (sr = list_tail(l); sr != NULL; sr = list_prev(l, sr)) { if ((sr->sr_priority < pri) || ((sr->sr_priority == pri) && (sr->sr_weight < weight))) { list_insert_after(l, sr, rr); return; } } list_insert_head(l, rr); } static void lsa_addrlist_destroy(list_t *l) { addr_rr_t *ar; for (ar = list_head(l); ar != NULL; ar = list_head(l)) { free(ar->name); free(ar->addr); list_remove_head(l); free(ar); } } static void lsa_srvlist_destroy(list_t *l) { srv_rr_t *sr; for (sr = list_head(l); sr != NULL; sr = list_head(l)) { free(sr->sr_name); list_remove_head(l); free(sr); } } /* * Parse SRV record into a srv_rr_t. * Returns a pointer to the next record on success, NULL on failure. */ static int lsa_parse_srv(const uchar_t *msg, const uchar_t *eom, uchar_t **cp, uchar_t *namebuf, size_t bufsize, srv_rr_t *sr) { /* * Get priority, weight, port, and target name. */ uint16_t priority, weight, port; int len; char *name; NS_GET16(priority, *cp); NS_GET16(weight, *cp); NS_GET16(port, *cp); len = dn_expand(msg, eom, *cp, namebuf, bufsize); if (len < 0) return P_ERR_FAIL; /* * According to RFC 2782, SRV records for which there is no service * use target ".". */ if (namebuf[0] == '.' && namebuf[1] == '\0') return P_ERR_SKIP; if ((name = strdup(namebuf)) == NULL) return P_ERR_FAIL; sr->sr_name = name; sr->sr_port = port; sr->sr_priority = priority; sr->sr_weight = weight; return P_SUCCESS; } /* * Parse A record into a v4-mapped IPv6 address. */ static int lsa_parse_a(const uchar_t *msg, const uchar_t *eom, uchar_t **cp, uchar_t *namebuf, addr_rr_t *ar) { in6_addr_t *addr6 = NULL; char *name = NULL; int i; if ((name = strdup(namebuf)) == NULL) goto fail; if ((addr6 = malloc(sizeof (*addr6))) == NULL) goto fail; addr6->s6_addr32[1] = addr6->s6_addr32[0] = 0; addr6->s6_addr32[2] = 0xffff0000; /* addr6->s6_addr32[3] = *(uint32_t *)*cp; *cp += 4; */ for (i = 12; i < 16; i++) addr6->s6_addr8[i] = *(*cp)++; if (*cp > eom) goto fail; ar->addr = addr6; ar->name = name; ar->type = AF_INET; return P_SUCCESS; fail: free(addr6); free(name); return P_ERR_FAIL; } static int lsa_parse_aaaa(const uchar_t *msg, const uchar_t *eom, uchar_t **cp, uchar_t *namebuf, addr_rr_t *ar) { int i; in6_addr_t *addr6 = NULL; char *name = NULL; if ((name = strdup(namebuf)) == NULL) goto fail; if ((addr6 = malloc(sizeof (*addr6))) == NULL) goto fail; /* for (i = 0; i < 4; i++) { addr6->s6_addr32[i] = *(uint32_t *)*cp; *cp += 4; } */ for (i = 0; i < 16; i++) addr6->s6_addr8[i] = *(*cp)++; if (*cp > eom) goto fail; ar->addr = addr6; ar->name = name; ar->type = AF_INET6; return P_SUCCESS; fail: free(addr6); free(name); return P_ERR_FAIL; } static int lsa_parse_common(const uchar_t *msg, const uchar_t *eom, uchar_t **cp, void *rr) { uchar_t namebuf[NS_MAXDNAME]; uint16_t type, class, size; uint32_t ttl; int len; /* * Skip searched RR name and attributes. */ len = dn_expand(msg, eom, *cp, namebuf, sizeof (namebuf)); if (len < 0) return P_ERR_FAIL; *cp += len; /* * We started on a compressed name, so we need to adjust cp */ if (**cp == 0xc0) *cp += 2; NS_GET16(type, *cp); NS_GET16(class, *cp); NS_GET32(ttl, *cp); NS_GET16(size, *cp); if ((*cp + size) > eom) return P_ERR_FAIL; if (type == T_SRV) return lsa_parse_srv(msg, eom, cp, namebuf, sizeof(namebuf), (srv_rr_t *) rr); if (type == T_A) return lsa_parse_a(msg, eom, cp, namebuf, (addr_rr_t *) rr); if (type == T_AAAA) return lsa_parse_aaaa(msg, eom, cp, namebuf, (addr_rr_t *) rr); /* * If we get here, skip parsing the record entirely; * we're not interested. */ *cp += size; return P_ERR_SKIP; } /* * Look up and return a sorted list of SRV records for a domain. * Returns number of records on success, -1 on failure. * Also matches associated A records if returned, and gets them if not. */ int lsa_srv_lookup(lsa_srv_ctx_t *ctx, const char *svcname, const char *dname) { int ret = -1, anslen, len, n, nq, na, ns, nr, e, skip = 0; union { HEADER h; uchar_t b[NS_MAXMSG]; } *ansbuf; uchar_t *ap, *eom; char namebuf[NS_MAXDNAME]; list_t la; srv_rr_t *sr; list_create(&la, sizeof (addr_rr_t), offsetof(addr_rr_t, addr_node)); ansbuf = malloc(sizeof (*ansbuf)); if (ansbuf == NULL) goto out; ap = ansbuf->b; /* * Use virtual circuits (TCP) for resolver. */ ctx->lsc_state.options |= RES_USEVC; /* * Traverse parent domains until an answer is found. */ anslen = res_nquerydomain(&ctx->lsc_state, svcname, dname, C_IN, T_SRV, ap, sizeof (*ansbuf)); if (anslen > sizeof (*ansbuf) || anslen <= (HFIXEDSZ + QFIXEDSZ)) goto out; eom = ap + anslen; /* * Get question and answer count. */ nq = ntohs(ansbuf->h.qdcount); na = ntohs(ansbuf->h.ancount); ns = ntohs(ansbuf->h.nscount); nr = ntohs(ansbuf->h.arcount); if (nq != 1 || na < 1) goto out; /* * Skip header and question. */ ap += HFIXEDSZ; len = dn_expand(ansbuf->b, eom, ap, namebuf, sizeof (namebuf)); if (len < 0) goto out; ap += len + QFIXEDSZ; /* * Expand names in answer(s) and insert into RR list. */ for (n = 0; (n < na) && (ap < eom); n++) { sr = malloc(sizeof (srv_rr_t)); if (sr == NULL) { lsa_srvlist_destroy(&ctx->lsc_list); goto out; } memset(sr, 0, sizeof (*sr)); e = lsa_parse_common(ansbuf->b, eom, &ap, sr); if (e == P_ERR_FAIL) { free(sr); lsa_srvlist_destroy(&ctx->lsc_list); goto out; } if (e == P_ERR_SKIP) { skip++; free(sr); continue; } lsa_srvlist_insert(&ctx->lsc_list, sr); } /* Return number of records found. */ ret = n - skip; if (ret == 0) goto out; for (n = 0; (n < (ns + nr)) && (ap < eom); n++) { addr_rr_t *ar = malloc(sizeof (addr_rr_t)); if (ar == NULL) goto out; memset(ar, 0, sizeof (*ar)); e = lsa_parse_common(ansbuf->b, eom, &ap, ar); if (e == P_ERR_FAIL) goto out; if (e == P_ERR_SKIP) { free(ar); continue; } /* * Do we care about using IPv6 if its available, or * should we only use it if it's the only one available? * This currently sets up the next loop to "fall back" to * v4-mapped IPv6 if pure IPv6 wasn't provided. */ if (ar->type == AF_INET) list_insert_tail(&la, ar); else list_insert_head(&la, ar); } for (sr = list_head(&ctx->lsc_list); sr != NULL; sr = list_next(&ctx->lsc_list, sr)) { addr_rr_t *ar = NULL; sr->addr.sin6_family = AF_INET6; sr->addr.sin6_port = htons(LDAP_PORT); for (ar = list_head(&la); ar != NULL; ar = list_next(&la, ar)) if (strcmp(sr->sr_name, ar->name) == 0) { sr->addr.sin6_addr = *ar->addr; break; } if (ar == NULL) { struct addrinfo *res = NULL; struct addrinfo ai = { AI_ADDRCONFIG | AI_V4MAPPED, AF_INET6, 0, 0, 0, NULL, NULL, NULL }; struct sockaddr_in6 sa; if ((getaddrinfo(sr->sr_name, NULL, &ai, &res) != 0) || (res == NULL)) { ret = -1; goto out; } (void) memcpy(&sa, res->ai_addr, res->ai_addrlen); sr->addr.sin6_addr = sa.sin6_addr; freeaddrinfo(res); } } out: free(ansbuf); lsa_addrlist_destroy(&la); list_destroy(&la); return (ret); } lsa_srv_ctx_t * lsa_srv_init(void) { lsa_srv_ctx_t *ctx; ctx = malloc(sizeof (*ctx)); if (ctx == NULL) return (NULL); memset(&ctx->lsc_state, 0, sizeof(ctx->lsc_state)); if (res_ninit(&ctx->lsc_state) != 0) { free(ctx); return (NULL); } list_create(&ctx->lsc_list, sizeof (srv_rr_t), offsetof(srv_rr_t, sr_node)); return (ctx); } void lsa_srv_fini(lsa_srv_ctx_t *ctx) { if (ctx == NULL) return; lsa_srvlist_destroy(&ctx->lsc_list); list_destroy(&ctx->lsc_list); res_ndestroy(&ctx->lsc_state); free(ctx); } static void lsa_srv_reset(lsa_srv_ctx_t *ctx) { list_t *l = &ctx->lsc_list; srv_rr_t *sr; for (sr = list_head(l); sr != NULL; sr = list_next(l, sr)) { sr->sr_used = B_FALSE; } } srv_rr_t * lsa_srv_next(lsa_srv_ctx_t *ctx, srv_rr_t *rr) { list_t *l = &ctx->lsc_list; srv_rr_t *sr, *first = NULL; uint16_t pri = 0; uint32_t sum = 0, r; if (rr == NULL) { /* * Start over and mark all records unused. */ lsa_srv_reset(ctx); } else { rr->sr_used = B_TRUE; pri = rr->sr_priority; } for (sr = list_head(l); sr != NULL; sr = list_next(l, sr)) { /* * Skip used and lower-numbered priority records. */ if ((sr->sr_used) || (sr->sr_priority < pri)) continue; if (sr->sr_priority > pri) { /* * Have we seen all of the records with the * current priority? */ if (first != NULL) break; /* Try the next priority number */ first = sr; pri = sr->sr_priority; } else { /* * Remember the first unused record at this priority. */ if (first == NULL) first = sr; } /* * Sum the weights at this priority, for randomised selection. */ /*sum += sr->sr_weight;*/ } /* * No more records remaining? */ if (first == NULL) return (NULL); /* * If all weights are 0, return first unused record. */ /* XXX this will always trigger until weight is implemented */ if (sum == 0) return (first); /* * Generate a random number in the interval [0, sum]. */ r = random() % (sum + 1); /* * Go through all of the records at the current priority to locate * the next selection. */ sum = 0; for (sr = first; sr != NULL; sr = list_next(l, sr)) { if (sr->sr_used) continue; /* * We somehow fell off the end? */ if (sr->sr_priority > pri) { sr = NULL; break; } /* * Since the ordering is constant, we know the next record * will be found when the random number from the range * falls between the previous sum and the current sum. */ sum += sr->sr_weight; if (sum >= r) break; } return (sr); }
0fce23fa9d842d6beaecfbc8ad81a7067e1cdfde
[ "C", "Makefile" ]
11
C
mbarden/dclocate
53f2ccc75491bb45e5769b30f3610200b050cfe6
3b17e13148b146a53668e8a17f274d1b043aae15
refs/heads/main
<repo_name>xulonc/QNDroidIMSDK<file_sep>/settings.gradle include ':app' include ':lib:lib_network' include ':lib:bzuiEmoji' include(':lib:bzuicomp_bottomInput') rootProject.name = "QNDroidIMSDK"<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/pubchat/InputMsgReceiver.kt package com.qiniu.qndroidimsdk.pubchat import android.content.Context import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import com.qiniu.droid.imsdk.QNIMClient import com.qiniu.qndroidimsdk.UserInfoManager import com.qiniu.qndroidimsdk.pubchat.msg.RtmTextMsg import im.floo.floolib.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import android.graphics.BitmapFactory import android.media.MediaMetadataRetriever import android.net.Uri import com.qiniu.qndroidimsdk.pubchat.msg.RtmImgMsg import com.qiniu.qndroidimsdk.pubchat.msg.RtmMessage import com.qiniu.qndroidimsdk.pubchat.msg.RtmVoiceMsg import java.lang.Exception import android.os.Build import android.util.Log import androidx.core.content.FileProvider import com.hapi.mediapicker.ContentUriUtil import java.io.File class InputMsgReceiver(val context: Context) : LifecycleObserver { private val mChatListener: BMXChatServiceListener = object : BMXChatServiceListener() { override fun onStatusChanged(msg: BMXMessage?, error: BMXErrorCode?) { super.onStatusChanged(msg, error) Log.d( "mjl", "${msg?.msgId()} ${msg?.attachment()?.type()} ${error?.name} ${error?.swigValue()}" ) } override fun onAttachmentStatusChanged( msg: BMXMessage?, error: BMXErrorCode?, percent: Int ) { super.onAttachmentStatusChanged(msg, error, percent) var id = msg?.msgId() Log.d( "mjl", " onAttachmentStatusChanged ${id} ${percent}" ) GlobalScope.launch(Dispatchers.Main) { PubChatMsgManager.onMsgAttachmentStatusChanged(id.toString(),percent) } } override fun onReceive(list: BMXMessageList) { super.onReceive(list) //收到消息 if (list.isEmpty) { return } for (i in 0 until list.size().toInt()) { list[i]?.let { var msg: RtmMessage? = null //当前这个群 if (it.toId() != UserInfoManager.mIMGroup!!.im_group_id) { return } if (it.contentType() == BMXMessage.ContentType.Text) { msg = JsonUtils.parseObject(it.content(), RtmTextMsg::class.java) ?: return } if (it.contentType() == BMXMessage.ContentType.Image) { QNIMClient.getChatManager().downloadAttachment(it) val at: BMXImageAttachment = BMXImageAttachment.dynamic_cast(it.attachment()) val rtmImgMsg = RtmImgMsg() val path = at.path() rtmImgMsg.thumbnailUrl = Uri.fromFile(File(path)) rtmImgMsg.h = at.size().mHeight rtmImgMsg.w = at.size().mWidth rtmImgMsg.attachmentProcess = 0 msg = rtmImgMsg; } if (it.contentType() == BMXMessage.ContentType.Voice) { QNIMClient.getChatManager().downloadAttachment(it) val at: BMXVoiceAttachment = BMXVoiceAttachment.dynamic_cast(it.attachment()) val rtmVoiceMsg = RtmVoiceMsg() val path = at.path() val t3 = at.url() val file = File(path) Log.d("mjl", "${it.msgId()} ${path} ${t3} ${path}\n" + file.exists()) rtmVoiceMsg.url = Uri.fromFile(File(path)) rtmVoiceMsg.duration = at.duration(); msg = rtmVoiceMsg msg?.attachmentProcess=0 } msg?.msgId = it.msgId().toString() msg?.sendImId = it.fromId().toString() msg?.sendImName = it.senderName() msg?.toImId = it.toId().toString() GlobalScope.launch(Dispatchers.Main) { PubChatMsgManager.onNewMsg(msg) } } } } //} } init { QNIMClient.getChatManager().addChatListener(mChatListener) } /** * 发公聊消息 */ fun buildMsg(msgEdit: String) { val pubChatMsgModel = PubChatMsgModel().apply { senderId = UserInfoManager.mIMUser?.im_uid.toString() senderName = UserInfoManager.mIMUser?.im_username msgContent = msgEdit } val msg = RtmTextMsg( PubChatMsgModel.action_pubText, JsonUtils.toJson( pubChatMsgModel ) ) val imMsg = BMXMessage.createMessage( UserInfoManager.mIMUser!!.im_uid, UserInfoManager.mIMGroup!!.im_group_id, BMXMessage.MessageType.Group, UserInfoManager.mIMGroup!!.im_group_id, JsonUtils.toJson(msg) ) imMsg.setSenderName(UserInfoManager.mIMUser?.im_username) QNIMClient.sendMessage(imMsg) msg.sendImName = UserInfoManager.mIMUser?.im_username msg.toImId = UserInfoManager.mIMGroup!!.im_group_id.toString() msg.sendImId = UserInfoManager.mIMUser!!.im_uid.toString() PubChatMsgManager.onNewMsg(msg) } fun buildImgMsg(uri: Uri) { val filePath = ContentUriUtil.getDataFromUri( context!!, uri, ContentUriUtil.ContentType.image ) ?: "" val bm = BitmapFactory.decodeFile(filePath) val size = BMXMessageAttachment.Size(bm?.width?.toDouble() ?: 0.0, bm?.height?.toDouble() ?: 0.0) val imageAttachment = BMXImageAttachment(filePath, size) val msg: BMXMessage = BMXMessage.createMessage( UserInfoManager.mIMUser!!.im_uid, UserInfoManager.mIMGroup!!.im_group_id, BMXMessage.MessageType.Group, UserInfoManager.mIMGroup!!.im_group_id, imageAttachment ) msg.setSenderName(UserInfoManager.mIMUser?.im_username) QNIMClient.sendMessage(msg) val rtmImgMsg = RtmImgMsg() rtmImgMsg.thumbnailUrl = uri rtmImgMsg.h = size.mHeight rtmImgMsg.w = size.mWidth rtmImgMsg.sendImName = UserInfoManager.mIMUser?.im_username rtmImgMsg.toImId = UserInfoManager.mIMGroup!!.im_group_id.toString() rtmImgMsg.sendImId = UserInfoManager.mIMUser!!.im_uid.toString() rtmImgMsg.attachmentProcess = 100 PubChatMsgManager.onNewMsg(rtmImgMsg) } private fun getRingDuring(mUri: Uri): String { var duration: String? = null val mmr = MediaMetadataRetriever() try { if (mUri != null) { var headers: HashMap<String?, String?>? = null if (headers == null) { headers = HashMap() headers["User-Agent"] = "Mozilla/5.0 (Linux; U; Android 4.4.2; zh-CN; MW-KW-001 Build/JRO03C) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 UCBrowser/1.0.0.001 U4/0.8.0 Mobile Safari/533.1" } mmr.setDataSource(context, mUri) // videoPath 本地视频的路径 } duration = ((mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toInt() ?: 0) / 1000).toString() } catch (ex: Exception) { ex.printStackTrace() } finally { mmr.release() } return duration ?: "0" } fun buildVoiceMsg(filePath: String) { val uri = FileProvider.getUriForFile( context, context.getPackageName().toString() + ".fileProvider", File(filePath) ) val duration = getRingDuring(uri).toInt() val imageAttachment = BMXVoiceAttachment(filePath, duration) val msg: BMXMessage = BMXMessage.createMessage( UserInfoManager.mIMUser!!.im_uid, UserInfoManager.mIMGroup!!.im_group_id, BMXMessage.MessageType.Group, UserInfoManager.mIMGroup!!.im_group_id, imageAttachment ) msg.setSenderName(UserInfoManager.mIMUser?.im_username) QNIMClient.sendMessage(msg) val rtmVoiceMsg = RtmVoiceMsg() rtmVoiceMsg.url = uri rtmVoiceMsg.duration = duration rtmVoiceMsg.sendImName = UserInfoManager.mIMUser?.im_username rtmVoiceMsg.toImId = UserInfoManager.mIMGroup!!.im_group_id.toString() rtmVoiceMsg.sendImId = UserInfoManager.mIMUser!!.im_uid.toString() rtmVoiceMsg.attachmentProcess = 100 PubChatMsgManager.onNewMsg(rtmVoiceMsg) } fun sendEnterMsg() { val pubMsg = PubChatWelCome().apply { senderId = UserInfoManager.mIMUser?.im_uid.toString() senderName = UserInfoManager.mIMUser?.im_username msgContent = "进入了房间" } val msg = RtmTextMsg( PubChatWelCome.action_welcome, JsonUtils.toJson( pubMsg ) ) val imMsg = BMXMessage.createMessage( UserInfoManager.mIMUser!!.im_uid, UserInfoManager.mIMGroup!!.im_group_id, BMXMessage.MessageType.Group, UserInfoManager.mIMGroup!!.im_group_id, JsonUtils.toJson(msg) ) imMsg.setSenderName(UserInfoManager.mIMUser?.im_username) QNIMClient.sendMessage(imMsg) msg.sendImName = UserInfoManager.mIMUser?.im_username msg.toImId = UserInfoManager.mIMGroup!!.im_group_id.toString() msg.sendImId = UserInfoManager.mIMUser!!.im_uid.toString() PubChatMsgManager.onNewMsg(msg) } fun sendQuitMsg() { val pubMsg = PubChatQuitRoom().apply { senderId = UserInfoManager.mIMUser?.im_uid.toString() senderName = UserInfoManager.mIMUser?.im_username msgContent = "退出了房间" } val msg = RtmTextMsg( PubChatQuitRoom.action_quit_room, JsonUtils.toJson( pubMsg ) ) val imMsg = BMXMessage.createMessage( UserInfoManager.mIMUser!!.im_uid, UserInfoManager.mIMGroup!!.im_group_id, BMXMessage.MessageType.Group, UserInfoManager.mIMGroup!!.im_group_id, JsonUtils.toJson(msg) ) imMsg.setSenderName(UserInfoManager.mIMUser?.im_username) QNIMClient.sendMessage(imMsg) msg.sendImName = UserInfoManager.mIMUser?.im_username msg.toImId = UserInfoManager.mIMGroup!!.im_group_id.toString() msg.sendImId = UserInfoManager.mIMUser!!.im_uid.toString() PubChatMsgManager.onNewMsg(msg) } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { QNIMClient.getChatManager().removeChatListener(mChatListener) } }<file_sep>/lib/bzuiEmoji/src/main/java/com/qiniu/bzui/emoji/EmojiManager.java package com.qiniu.bzui.emoji; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.ImageSpan; import java.util.ArrayList; import java.util.List; import java.util.logging.Handler; public class EmojiManager { private final String TAG = "EmojiManager"; private Context gContext; private ArrayList<Integer> emojiCodeList = new ArrayList<>(); private ArrayList<Integer> emojiResourceList = new ArrayList<>(); private static EmojiManager emojiManager = null; public static EmojiManager getInstance(Context context){ if(emojiManager==null){ emojiManager=new EmojiManager(context); } return emojiManager; } private EmojiManager(Context context) { gContext = context.getApplicationContext(); Resources resources = gContext.getResources(); int[] codes = resources.getIntArray(R.array.chatroom_emoji_code_list); TypedArray array = resources.obtainTypedArray(R.array.chatroom_emoji_res_list); if (codes.length != array.length()) { array.recycle(); throw new IndexOutOfBoundsException("Code and resource are not match in Emoji xml."); } for (int i = 0; i < codes.length; i++) { emojiCodeList.add(codes[i]); emojiResourceList.add(array.getResourceId(i, -1)); } array.recycle(); } public int getSize() { return emojiCodeList.size(); } public int getCode(int position) { return emojiCodeList.get(position); } public List<Integer> getResourceList(int start, int count) { return new ArrayList<>(emojiResourceList.subList(start, start + count)); } private int getResourceByCode(int code) throws Resources.NotFoundException { for (int i = 0; i < emojiCodeList.size(); i++) { if (emojiCodeList.get(i) == code) { return emojiResourceList.get(i); } } throw new Resources.NotFoundException("Unsupported emoji code <" + code + ">, which is not in Emoji list."); } public CharSequence parse(String text, int textSize) { if (text == null) { return ""; } final char[] chars = text.toCharArray(); final SpannableStringBuilder ssb = new SpannableStringBuilder(text); int codePoint; boolean isSurrogatePair; for (int i = 0; i < chars.length; i++) { if (Character.isHighSurrogate(chars[i])) { continue; } else if (Character.isLowSurrogate(chars[i])) { if (i > 0 && Character.isSurrogatePair(chars[i - 1], chars[i])) { codePoint = Character.toCodePoint(chars[i - 1], chars[i]); isSurrogatePair = true; } else { continue; } } else { codePoint = (int) chars[i]; isSurrogatePair = false; } if (emojiCodeList.contains(codePoint)) { Bitmap bitmap = BitmapFactory.decodeResource(gContext.getResources(), getResourceByCode(codePoint)); BitmapDrawable bmpDrawable = new BitmapDrawable(gContext.getResources(), bitmap); bmpDrawable.setBounds(0, 0, (int) textSize, (int) textSize); CenterImageSpan imageSpan = new CenterImageSpan(bmpDrawable); ssb.setSpan(imageSpan, isSurrogatePair ? i - 1 : i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } return ssb; } private class CenterImageSpan extends ImageSpan { public CenterImageSpan(Drawable draw) { super(draw); } @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { Drawable b = getDrawable(); Paint.FontMetricsInt fm = paint.getFontMetricsInt(); int transY = ((bottom - top) - getDrawable().getBounds().bottom) / 2 + top; canvas.save(); canvas.translate(x, transY); b.draw(canvas); canvas.restore(); } } } <file_sep>/lib/bzuicomp_bottomInput/src/main/java/com/qiniu/bzuicomp/bottominput/ext.kt package com.qiniu.bzuicomp.bottominput import androidx.annotation.StyleRes import android.view.ViewGroup import android.view.Window fun Window.applyGravityStyle(gravity: Int, @StyleRes resId: Int?, width: Int = ViewGroup.LayoutParams.MATCH_PARENT, height: Int = ViewGroup.LayoutParams.WRAP_CONTENT, x: Int = 0, y: Int = 0) { val attributes = this.attributes attributes.gravity = gravity attributes.width = width attributes.height = height attributes.x = x attributes.y = y this.attributes = attributes resId?.let { this.setWindowAnimations(it) } }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/room/RoomActivity.java package com.qiniu.qndroidimsdk.room; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageButton; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentTransaction; import com.qiniu.droid.rtc.QNAudioFrame; import com.qiniu.droid.rtc.QNAudioFrameListener; import com.qiniu.droid.rtc.QNCameraSwitchResultCallback; import com.qiniu.droid.rtc.QNCameraVideoTrackConfig; import com.qiniu.droid.rtc.QNClientEventListener; import com.qiniu.droid.rtc.QNConnectionState; import com.qiniu.droid.rtc.QNJoinResultCallback; import com.qiniu.droid.rtc.QNMicrophoneAudioTrackConfig; import com.qiniu.droid.rtc.QNPublishResultCallback; import com.qiniu.droid.rtc.QNRTC; import com.qiniu.droid.rtc.QNRTCClient; import com.qiniu.droid.rtc.QNRTCEventListener; import com.qiniu.droid.rtc.QNRTCSetting; import com.qiniu.droid.rtc.QNSurfaceView; import com.qiniu.droid.rtc.QNTrack; import com.qiniu.droid.rtc.QNVideoFormat; import com.qiniu.droid.rtc.model.QNAudioDevice; import com.qiniu.qndroidimsdk.R; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; public class RoomActivity extends AppCompatActivity implements QNRTCEventListener, QNClientEventListener { private static final String TAG = "RoomActivity"; private static final String TAG_CAMERA = "camera"; private static final String TAG_MICROPHONE = "microphone"; private QNSurfaceView mLocalVideoSurfaceView; private QNSurfaceView mRemoteVideoSurfaceView; private QNRTCSetting mSetting; private QNRTCClient mClient; private String mRoomToken; private QNTrack mLocalVideoTrack; private QNTrack mLocalAudioTrack; private boolean mIsVideoUnpublished = false; private boolean mIsAudioUnpublished = false; private Button mBtnRecord; private ClientPcmRecorder mClientPcmRecorder; private ChatRoomFragment chatRoomFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_room); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); mLocalVideoSurfaceView = findViewById(R.id.local_video_surface_view); mRemoteVideoSurfaceView = findViewById(R.id.remote_video_surface_view); mRemoteVideoSurfaceView.setZOrderOnTop(true);// QNSurfaceView 是 SurfaceView 的子类, 会受层级影响 Intent intent = getIntent(); mRoomToken = intent.getStringExtra("roomToken"); mSetting = new QNRTCSetting(); // 配置默认摄像头 ID,此处配置为前置摄像头 mSetting.setCameraID(QNRTCSetting.QNCameraFacing.FRONT); // 相机预览分辨率、帧率配置为 640x480、20fps mSetting.setCameraPreviewFormat(new QNVideoFormat(640, 480, 30)); // 初始化 QNRTC QNRTC.init(getApplicationContext(), mSetting, this); // 创建本地 Camera 采集 track if (mLocalVideoTrack == null) { QNCameraVideoTrackConfig cameraVideoTrackConfig = new QNCameraVideoTrackConfig(TAG_CAMERA) .setVideoEncodeFormat(new QNVideoFormat(640, 480, 30)) .setBitrate(1200); mLocalVideoTrack = QNRTC.createCameraVideoTrack(cameraVideoTrackConfig); } // 设置预览窗口 mLocalVideoTrack.play(mLocalVideoSurfaceView); // 创建本地音频采集 track if (mLocalAudioTrack == null) { QNMicrophoneAudioTrackConfig microphoneAudioTrackConfig = new QNMicrophoneAudioTrackConfig(TAG_MICROPHONE) .setBitrate(100); mLocalAudioTrack = QNRTC.createMicrophoneAudioTrack(microphoneAudioTrackConfig); } // 创建 QNRTCClient mClient = QNRTC.createClient(this); mClient.join(mRoomToken, new QNJoinResultCallback() { @Override public void onJoined() { Log.i(TAG, "join success"); // 保证房间内只有2人 if (mClient.getRemoteUsers().size() > 1) { Toast.makeText(RoomActivity.this, "You can't enter the room.", Toast.LENGTH_SHORT).show(); QNRTC.deinit(); finish(); } // 加入房间成功后发布音视频数据,发布成功会触发 QNPublishResultCallback#onPublished 回调 mClient.publish(new QNPublishResultCallback() { @Override public void onPublished(List<QNTrack> list) { Log.i(TAG, "onPublished"); } @Override public void onError(int errorCode, String errorMessage) { Log.i(TAG, "publish failed : " + errorCode + " " + errorMessage); } }, mLocalVideoTrack, mLocalAudioTrack); } @Override public void onError(int errorCode, String errorMessage) { Log.i(TAG, "join failed : " + errorCode + " " + errorMessage); } }); chatRoomFragment = new ChatRoomFragment(); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.flCover,chatRoomFragment); transaction.commit(); } @Override protected void onDestroy() { super.onDestroy(); // 需要及时销毁 QNRTCEngine 以释放资源 QNRTC.deinit(); } /** * 房间状态改变时会回调此方法 * 房间状态回调只需要做提示用户,或者更新相关 UI; 不需要再做加入房间或者重新发布等其他操作! * @param state 房间状态,可参考 {@link QNConnectionState} */ @Override public void onConnectionStateChanged(QNConnectionState state) { switch (state) { case IDLE: // 初始化状态 Log.i(TAG, "IDLE"); break; case CONNECTING: // 正在连接 Log.i(TAG, "CONNECTING"); break; case CONNECTED: // 连接成功,即加入房间成功 Log.i(TAG, "CONNECTED"); break; case RECONNECTING: // 正在重连,若在通话过程中出现一些网络问题则会触发此状态 Log.i(TAG, "RECONNECTING"); break; case RECONNECTED: // 重连成功 Log.i(TAG, "RECONNECTED"); break; } } /** * 当退出房间执行完毕后触发该回调,可用于切换房间 */ @Override public void onLeft() { Log.i(TAG, "onLeft"); } /** * 远端用户加入房间时会回调此方法 * @see QNRTCClient#join(String, String, QNJoinResultCallback) 可指定 userData 字段 * * @param remoteUserId 远端用户的 userId * @param userData 透传字段,用户自定义内容 */ @Override public void onUserJoined(String remoteUserId, String userData) { Log.i(TAG, "onUserJoined : " + remoteUserId); } /** * 远端用户开始重连时会回调此方法 * * @param remoteUserId 远端用户 ID */ @Override public void onUserReconnecting(String remoteUserId) { Log.i(TAG, "onUserReconnecting : " + remoteUserId); } /** * 远端用户重连成功时会回调此方法 * * @param remoteUserId 远端用户 ID */ @Override public void onUserReconnected(String remoteUserId) { Log.i(TAG, "onUserReconnected : " + remoteUserId); } /** * 远端用户离开房间时会回调此方法 * * @param remoteUserId 远端离开用户的 userId */ @Override public void onUserLeft(String remoteUserId) { Log.i(TAG, "onUserLeft : " + remoteUserId); } /** * 远端用户 tracks 成功发布时会回调此方法 * * @param remoteUserId 远端用户 userId * @param trackList 远端用户发布的 tracks 列表 */ @Override public void onUserPublished(String remoteUserId, List<QNTrack> trackList) { Log.i(TAG, "onUserPublished : " + remoteUserId); } /** * 远端用户 tracks 成功取消发布时会回调此方法 * * @param remoteUserId 远端用户 userId * @param trackList 远端用户取消发布的 tracks 列表 */ @Override public void onUserUnpublished(String remoteUserId, List<QNTrack> trackList) { Log.i(TAG, "onUserUnpublished : " + remoteUserId); for (QNTrack track : trackList) { if (TAG_CAMERA.equals(track.getTag())) { // 当远端视频取消发布时隐藏远端窗口 mRemoteVideoSurfaceView.setVisibility(View.GONE); } } } /** * 成功订阅远端用户的 tracks 时会回调此方法 * * @param remoteUserId 远端用户 userId * @param trackList 订阅的远端用户 tracks 列表 */ @Override public void onSubscribed(String remoteUserId, List<QNTrack> trackList) { Log.i(TAG, "onSubscribed : " + remoteUserId); // 筛选出视频 Track 以渲染到窗口 for (QNTrack track : trackList) { if (TAG_CAMERA.equals(track.getTag())) { // 设置渲染窗口 track.play(mRemoteVideoSurfaceView); // 成功订阅后显示远端窗口 mRemoteVideoSurfaceView.setVisibility(View.VISIBLE); } } } /** * 当音频路由发生变化时会回调此方法 * * @param qnAudioDevice 音频设备, 详情请参考{@link QNAudioDevice} */ @Override public void onPlaybackDeviceChanged(QNAudioDevice qnAudioDevice) { Log.i(TAG, "onPlaybackDeviceChanged : " + qnAudioDevice.name()); } /** * 系统相机出错时会触发此回调 * * @param errorCode 错误码 * @param errorMessage 错误原因 */ @Override public void onCameraError(int errorCode, String errorMessage) { Log.i(TAG, "onCameraError : " + errorCode + " " + errorMessage); } public void clickPublishVideo(View view) { ImageButton button = (ImageButton) view; if (mIsVideoUnpublished) { mClient.publish(new QNPublishResultCallback() { @Override public void onPublished(List<QNTrack> list) { Log.i(TAG, "local video track published"); } @Override public void onError(int errorCode, String errorMessage) { Log.i(TAG, "publish failed : " + errorCode + " " + errorMessage); } }, mLocalVideoTrack); } else { mClient.unpublish(mLocalVideoTrack); } mIsVideoUnpublished = !mIsVideoUnpublished; button.setImageDrawable(mIsVideoUnpublished ? getResources().getDrawable(R.mipmap.video_close) : getResources().getDrawable(R.mipmap.video_open)); } public void clickPublishAudio(View view) { ImageButton button = (ImageButton) view; if (mIsAudioUnpublished) { mClient.publish(new QNPublishResultCallback() { @Override public void onPublished(List<QNTrack> list) { Log.i(TAG, "local audio track published"); } @Override public void onError(int errorCode, String errorMessage) { Log.i(TAG, "publish failed : " + errorCode + " " + errorMessage); } }, mLocalAudioTrack); } else { mClient.unpublish(mLocalAudioTrack); } mIsAudioUnpublished = !mIsAudioUnpublished; button.setImageDrawable(mIsAudioUnpublished ? getResources().getDrawable(R.mipmap.microphone_disable) : getResources().getDrawable(R.mipmap.microphone)); } public void clickSwitchCamera(View view) { final ImageButton button = (ImageButton) view; // 切换摄像头 QNRTC.switchCamera(new QNCameraSwitchResultCallback() { @Override public void onCameraSwitchDone(final boolean isFrontCamera) { runOnUiThread(new Runnable() { @Override public void run() { button.setImageDrawable(isFrontCamera ? getResources().getDrawable(R.mipmap.camera_switch_front) : getResources().getDrawable(R.mipmap.camera_switch_end)); } }); } @Override public void onCameraSwitchError(String errorMessage) { } }); } public void clickHangUp(View view) { // 离开房间 mClient.leave(); // 释放资源 QNRTC.deinit(); finish(); } public synchronized void clickToggleRecordAudio(View view) { if (mClientPcmRecorder == null) { String pcmRecordingPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/test_record_pcm.pcm"; mClientPcmRecorder = new ClientPcmRecorder(mClient, pcmRecordingPath); if (!mClientPcmRecorder.startRecordAudio()) { mClientPcmRecorder = null; Toast.makeText(this, "房间录音失败", Toast.LENGTH_SHORT).show(); } else { mBtnRecord.setText("停止录音"); Toast.makeText(this, "房间录音开始", Toast.LENGTH_SHORT).show(); } } else { mClientPcmRecorder.stopAudioRecord(); mClientPcmRecorder = null; Toast.makeText(this, "房间录音结束", Toast.LENGTH_SHORT).show(); mBtnRecord.setText("开始录音"); } } private static class ClientPcmRecorder { private QNRTCClient client; private String dstPath = null; private File pcmFile = null; private BufferedOutputStream bos = null; private QNAudioFrameListener listener = new QNAudioFrameListener() { @Override public void onAudioFrameAvailable(QNAudioFrame audioFrame) { writeAudioData(audioFrame.buffer, audioFrame.size, audioFrame.format.getBitsPerSample(), audioFrame.format.getSampleRate(), audioFrame.format.getChannels()); } }; private ClientPcmRecorder(QNRTCClient client, String dstPath) { this.client = client; this.dstPath = dstPath; } public boolean startRecordAudio() { try { pcmFile = new File(dstPath); if (pcmFile.exists()) { pcmFile.delete(); } bos = new BufferedOutputStream(new FileOutputStream(pcmFile)); } catch (FileNotFoundException e) { e.printStackTrace(); bos = null; pcmFile = null; return false; } client.addAllAudioDataMixedListener(listener); return true; } public void stopAudioRecord() { client.removeAllAudioDataMixedListener(listener); if (bos != null) { try { bos.flush(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } bos = null; pcmFile = null; } private void writeAudioData(ByteBuffer audioData, int size, int bitsPerSample, int sampleRate, int numberOfChannels) { try { Log.d(TAG, "client pcm recording --> size="+size + ",bitsPerSample="+bitsPerSample + ",sampleRate=" + sampleRate + ",numberOfChannels="+numberOfChannels); bos.write(audioData.array(), 0, size); } catch (IOException e) { e.printStackTrace(); } } } } <file_sep>/lib/bzuicomp_bottomInput/src/main/java/com/qiniu/bzuicomp/bottominput/FinalDialogFragment.kt package com.qiniu.bzuicomp.bottominput import android.os.Bundle import android.view.* import androidx.annotation.StyleRes import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction import java.lang.reflect.Field abstract class FinalDialogFragment : DialogFragment() { var mDefaultListener: BaseDialogListener? = null private val INVALID_LAYOUT_ID = -1 private var mCancelable: Boolean = true private var mGravityEnum: Int = Gravity.CENTER private var mdimAmount = -1.0f @StyleRes private var animationStyleresId: Int? = null fun setDefaultListener(defaultListener: BaseDialogListener): FinalDialogFragment { mDefaultListener = defaultListener return this } fun applyCancelable(cancelable: Boolean): FinalDialogFragment { mCancelable = cancelable return this } fun applyGravityStyle(gravity: Int): FinalDialogFragment { mGravityEnum = gravity return this } fun applyAnimationStyle(@StyleRes resId: Int): FinalDialogFragment { animationStyleresId = resId return this } fun applyDimAmount(dimAmount:Float): FinalDialogFragment { mdimAmount = dimAmount return this } /** The system calls this to get the DialogFragment's layout, regardless * of whether it's being displayed as a dialog or an embedded fragment. */ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { var rootView: View? // Inflate the layout to use as dialog or embedded fragment if (getViewLayoutId() != INVALID_LAYOUT_ID) { rootView = inflater.inflate(getViewLayoutId(), container, false) } else { rootView = super.onCreateView(inflater, container, savedInstanceState) } return rootView } override fun onStart() { super.onStart() //STYLE_NO_FRAME设置之后会调至无法自动点击外部自动消失,因此添加手动控制 dialog?.setCanceledOnTouchOutside(true) dialog?.window?.applyGravityStyle(mGravityEnum, animationStyleresId) if(mdimAmount>=0){ val window = dialog!!.window val windowParams: WindowManager.LayoutParams = window!!.attributes windowParams . dimAmount =mdimAmount window.attributes = windowParams } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //取消系统对dialog样式上的干扰,防止dialog宽度无法全屏 setStyle(androidx.fragment.app.DialogFragment.STYLE_NO_FRAME, R.style.dialogFullScreen) } override fun onResume() { super.onResume() dialog?.setCanceledOnTouchOutside(mCancelable) if (!mCancelable) { dialog?.setOnKeyListener { v, keyCode, event -> keyCode == KeyEvent.KEYCODE_BACK } } } override fun show( manager: FragmentManager, tag: String? ) { try { val mDismissed: Field = this.javaClass.superclass.getDeclaredField("mDismissed") val mShownByMe: Field = this.javaClass.superclass.getDeclaredField("mShownByMe") mDismissed.setAccessible(true) mShownByMe.setAccessible(true) mDismissed.setBoolean(this, false) mShownByMe.setBoolean(this, true) } catch (e: NoSuchFieldException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } val ft: FragmentTransaction = manager.beginTransaction() ft.add(this, tag) ft.commitAllowingStateLoss() } abstract fun getViewLayoutId(): Int override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) init() } abstract fun init() override fun dismiss() { super.dismiss() mDefaultListener?.onDismiss(this) } open class BaseDialogListener { /** * 点击确定,并携带指定类型参数 */ open fun onDialogPositiveClick( dialog: androidx.fragment.app.DialogFragment, any: Any = Any() ) { } open fun onDialogNegativeClick( dialog: androidx.fragment.app.DialogFragment, any: Any = Any() ) { } open fun onDismiss(dialog: androidx.fragment.app.DialogFragment) {} } }<file_sep>/lib/lib_network/src/main/java/com/qiniu/network/NetBzException.java package com.qiniu.network; public class NetBzException extends RuntimeException { private int code; private NetBzException() { } public NetBzException(String detailMessage) { super(detailMessage); } public NetBzException(int code, String detailMessage) { super(detailMessage); this.code = code; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } } <file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/pubchat/PubChatMsgManager.java package com.qiniu.qndroidimsdk.pubchat; import com.qiniu.qndroidimsdk.pubchat.msg.RtmMessage; public class PubChatMsgManager { protected static IChatMsgCall iChatMsgCall = null; public static void onNewMsg(RtmMessage msg) { if (iChatMsgCall != null) { iChatMsgCall.onNewMsg(msg); } } public static void onMsgAttachmentStatusChanged(String msgId,int percent){ if (iChatMsgCall != null) { iChatMsgCall.onMsgAttachmentStatusChanged(msgId, percent); } } protected interface IChatMsgCall { public void onNewMsg(RtmMessage msg); public void onMsgAttachmentStatusChanged(String msgId,int percent); } } <file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/pubchat/PubChatView.kt package com.qiniu.qndroidimsdk.pubchat import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.FrameLayout import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import androidx.recyclerview.widget.LinearLayoutManager import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.BaseViewHolder import com.qiniu.qndroidimsdk.R import com.qiniu.qndroidimsdk.pubchat.msg.RtmMessage import kotlinx.android.synthetic.main.view_bzui_pubchat.view.* /** * 公屏 */ class PubChatView : FrameLayout, LifecycleObserver { private var adapter: BaseQuickAdapter<RtmMessage, BaseViewHolder> = PubChatAdapter() constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ) { val view = LayoutInflater.from(context).inflate(R.layout.view_bzui_pubchat, this, false) addView(view) chatRecy.layoutManager = LinearLayoutManager(context) chatRecy.adapter = adapter } fun onRoomLeaving() { adapter.data.clear() adapter.notifyDataSetChanged() } private var mIChatMsgCall = object : PubChatMsgManager.IChatMsgCall { override fun onNewMsg(msg: RtmMessage?) { adapter.addData(msg!!) chatRecy.smoothScrollToPosition(adapter.data.size - 1) } override fun onMsgAttachmentStatusChanged( msgId:String, percent: Int) { adapter.data.forEachIndexed { index, rtmMessage -> if(rtmMessage.msgId==msgId){ rtmMessage.attachmentProcess=percent if(percent>=100){ adapter.notifyItemChanged(index) } } } } } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { // RtmChannelKit.removeRtmChannelListener(channelListener) // RoomManager.removeRoomLifecycleMonitor(roomMonitor) PubChatMsgManager.iChatMsgCall = null } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreate() { // RtmChannelKit.addRtmChannelListener(channelListener) // RoomManager.addRoomLifecycleMonitor(roomMonitor) PubChatMsgManager.iChatMsgCall = mIChatMsgCall } }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/SplashActivity.kt package com.qiniu.qndroidimsdk import android.Manifest import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.lifecycle.lifecycleScope import com.qiniu.droid.imsdk.QNIMClient import com.qiniu.network.RetrofitManager import com.tbruyelle.rxpermissions2.RxPermissions import im.floo.floolib.BMXErrorCode import kotlinx.android.synthetic.main.activity_splash.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class SplashActivity : AppCompatActivity() { @SuppressLint("CheckResult") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) ivAd.setImageResource(R.drawable.spl_bg) RxPermissions(this).request( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO ).doFinally { lifecycleScope.launch(Dispatchers.Main) { if (UserInfoManager.getUserId().isEmpty() || (UserInfoManager.mIMUser?.im_username ?: "").isEmpty() ) { val i = Intent(this@SplashActivity, LoginActivity::class.java) startActivity(i) return@launch } val code = QNIMClient.fastSignInByName(UserInfoManager.mIMUser!!.im_username,UserInfoManager.mIMUser!!.im_password) if(code == BMXErrorCode.NoError){ val i = Intent(this@SplashActivity,MainActivity::class.java) startActivity(i) }else{ val i = Intent(this@SplashActivity, LoginActivity::class.java) startActivity(i) } } } .subscribe { } } }<file_sep>/README.MD # Android SDK 集成说明 ## SDK 架构 七牛IM SDK 底层使用 C++ 实现,各平台(Android、iOS、Linux等)在此基础上再行封装, 完成本地库的开发,以达到多平台复用的目的,并保持跨平台协议实现的一致性。 floo-android 作为供安卓使用的本地应用库,有两种 API 可供开发者使用,即低级 API 和高级 API,也即同步接口和异步接口。 低级 API (low-level) 同步调用接口,类名以Service结尾,为方便理解,下文说明中用 L/S 表示,其中 L 表示 Low-level, S 表示 Sync。 如前所述,floo-android 主体由 SWIG 框架自动生成。用 SWIG 生成的 Java 代码,通过 JNI 方式调用底层 C++ 类库,因此大部分接口均为同步,即调用接口后,完成后返回结果。 代码生成和转换的过程中,相关数据结构得以直接映射到底层类库,减少了内存拷贝,因此其性能接近于直接调用底层库。 同步方式的服务类如下: - QNClient: SDK功能聚合类,包含了所有的service类、实现了网络事件监听接口 - BMXChatRoomService: 聊天室管理 加入、退出、销毁、成员 - BMXChatService: 消息发送、消息历史获取、会话列表 - BMXUserService: 注册账号、登入、登出、我的设置 - BMXRosterService: 好友列表、黑名单 - BMXGroupService: 群管理(创建、解散、查找、设置、成员管理、邀请、申请、接受、拒绝) ### 高级 API (high-level) 异步调用接口,类名以Manager结尾,为方便理解,下文用 H/A 表示,其中 H 表示 High-level, A 表示 Async。 考虑到开发者集成方便,我们也基于此类重新封装了高级 API,使用了更为友好的数据结构,并完成了异步封装。 简单来讲,相关调用会在子线程执行具体操作(例如:搜索好友),当前线程会直接返回不会阻塞。具体操作的结果则通过回调函数通知调用方,后者可以在其中处理 UI 刷新等业务逻辑。 异步方式的服务类如下: - BaseManeger:Manger管理基础类 - ChatManager:消息发送、消息历史获取、会话列表 - chatRoomManager: 聊天室管理 加入、退出、销毁、成员 - UserManager:注册账号、登入、登出、我的设置 - RosterManager:好友列表、黑名单 - BMXCallBack:无类型接口回调 - BMXDataCallBack<T>: 泛型类型带数据回调 ### 其他工具类 - BMXGroupServiceListener:群事件监听 - BMXUserServiceListener:用户事件监听 - BMXRosterServiceListener:好友事件监听 - BMXNetworkListener:网络事件监听接口,由QNClient实现 - BMXConversation:会话 - BMXMessage:消息 - BMXGroup:群 - BMXRosterItem花名册项(好友、陌生人、黑名单、前好友) - BMXUserProfile:用户信息 ### 类库示意图如下 ``` +---> BMXChatRoomService | +---> BMXUserService | +---------------+ +---> BMXChatService | | | +---+ 低级 API: L/S +------> BMXRosterService | | | | | +---------------+ +---> BMXGroupService | | | | | +---> BMXChatRoomManager | | | +---> BMXUserManager | +---------------+ | +----------------------+ | | | +---> BMXChatManager | | +---+ 高级 API: H/A +-----+ | 七牛 IM SDK: Floo +--+ | | +---> BMXRosterManager | | | +---------------+ | +----------------------+ | +---> BMXGroupManager | | +---> QNClient | +----------------+ | | | | +---> BMXSDKConfig +---+ Utility:工具类 +--+ | | +---> BMXMessage +----------------+ | +---> BMXConversation | +---> BMXUserProfile | +---> BMXGroup | +---> BMXDevice ``` ### 申请imAppId 创建七牛账号,并创建七牛[IMAppId](https://portal.qiniu.com/rtn/app) ### 导入SDK SDK导入可以选择aar格式或者jar+so格式 aar格式 下载aar文件到项目的libs目录 在build.gradle文件dependencies块中增加依赖,参照im-android源码使用最新版。 implementation (name:'qndroid-imsdk-1.0.0',ext:"aar") jar+so格式 下载jar包和so库到项目的libs目录 在build.gradle文件中增加:implementation fileTree(dir: ‘libs’, include: [’*.jar’]) 权限配置 ``` 在AndroidManifest.xml 里增加加以下权限: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.CALL_PHONE" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> ``` ## 快速集成 ### QNClient初始化 ### 第一步 导入so库文件 在 app 入口类中增加导入 ``` static { System.loadLibrary("floo"); } ``` ### 第二步 初始化QNClient ``` // 设置存储路径 String appPath = AppContextUtils.getAppContext().getFilesDir().getPath(); File dataPath = new File(appPath + "/data_dir"); File cachePath = new File(appPath + "/cache_dir"); dataPath.mkdirs(); cachePath.mkdirs(); // 设置推送平台对应的ID String pushId = getPushId(); // 配置sdk config BMXSDKConfig config = new BMXSDKConfig(BMXClientType.Android, "1", dataPath.getAbsolutePath(), cachePath.getAbsolutePath(), TextUtils.isEmpty(pushId) ? "MaxIM" : pushId); config.setConsoleOutput(true); config.setLogLevel(BMXLogLevel.Debug); // 初始化QNClient QNClient.init(conf); ``` 注意: 如果使用高级API(异步调用方式),需要通过以下方法获取到服务类API的实体: - ChatManager: 通过QNIMClient.getChatManager()获取到消息的manager对象。 - UserManager: 通过QNIMClient.getUserManager()获取到用户的manager对象。 - GroupManager: 通过QNIMClient.getGroupManager()获取到群相关的manager对象。 - RosterManager: 通过QNIMClient.getRosterManager()获取到roster的manager对象。 ### 注册用户 ``` L/S: 同步调用传入BMXUserProfile对象引用,调用之后即可获取profile信息。 QNIMClient.signUpNewUser("zhangsan", "sFo!slk1x", new BMXUserProfile()); H/A: 异步调用在BMXDataCallBack回调中返回profile实例。 QNIMClient.getUserManager().signUpNewUser("zhangsan", "sFo!slk1x", new BMXDataCallBack<BMXUserProfile>(){ @Override public void onResult(BMXErrorCode bmxErrorCode, BMXUserProfile bmxUserProfile) { //返回profile } }); ``` ### 登录 两种登录模式:一种是普通手动登录,另一种是快速登录模式,手动登录包含了获取token和建立tcp连接的两个步骤,快速登录则将token缓存至本地。 ``` L/S: 通过返回值BMXErrorCode判断是否成功。 // 参数:username(用户名) password(密码) QNIMClient.getUserService().signInByName("zhangsan", "sFo!slk1x"); QNIMClient.getUserService().fastSignInByName("zhangsan", "sFo!slk1x"); H/A: 在BMXCallBack回调中返回BMXErrorCode 判断是否成功。 QNIMClient.getUserManager().signInByName("zhangsan", "sFo!slk1x", new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { } }); QNIMClient.getUserManager().signInByName("zhangsan", "sFo!slk1x", new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { } }); 获取会话列表 L/S: 通过传入BMXConversationList对象引用,调用成功后即可获取会话列表。 BMXConversationList cl = QNIMClient.getChatService().getAllConversations(); for (int i=0; i<cl.size(); i++){ BMXConversation c = cl.get(i); Log.e("conversation id:",""+c.conversationId()); } H/A: 在BMXDataCallBack回调中获取到会话列表。 QNIMClient.getChatManager().getAllConversations(new BMXDataCallBack<BMXConversationList>() { @Override public void onResult(BMXErrorCode bmxErrorCode, BMXConversationList list) { //返回BMXConversation实例 for (int i=0; i<cl.size(); i++){ BMXConversation c = cl.get(i); Log.e("conversation id:",""+c.conversationId()); } } }); 断开连接 L/S: 通过返回值获取到BMXErrorCode判断是否成功。 QNIMClient.getUserService().signOut(); H/A: 在BMXCallBack回调中根据BMXErrorCode判断。 QNIMClient.getUserManager().signOut(new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErrorCode } }); ``` ### 用户体系 ### 添加好友 ``` L/S: 通过返回值获取到BMXErrorCode判断是否成功。 参数说明: rosterId reason(申请添加原因) QNIMClient.getRosterService().apply(22342342, "Hi, I'm Lisi"); H/A: 在BMXCallBack回调中获取到BMXErrorCode判断是否成功。 QNIMClient.getRosterManager().apply(22342342, "Hi, I'm Lisi", new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErrorCode } }); ``` ### 删除好友 ``` L/S: 通过返回值获取到BMXErrorCode判断是否成功。 QNIMClient.getRosterService().remove(22342342); H/A: 在BMXCallBack回调中获取到BMXErrorCode判断是否成功。 QNIMClient.getRosterManager().remove(22342342, new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErrorCode } }); ``` ### 同意添加好友 ``` L/S: 通过返回值获取到BMXErrorCode判断是否成功。 //参数说明: rosterId QNIMClient.getRosterService().accept(333453112); H/A: 在BMXCallBack回调中获取到BMXErrorCode判断是否成功。 QNIMClient.getRosterManager().accept(333453112, new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErrorCode } }); ``` ### 拒绝添加好友 ``` L/S: 通过返回值获取到BMXErrorCode判断是否成功。 //参数说明: rosterId reason(拒绝原因) QNIMClient.getRosterService().decline(333453112,"I'm not Lisi"); H/A: 在BMXCallBack回调中获取到BMXErrorCode判断是否成功。 QNIMClient.getRosterManager().decline(333453112,"I'm not Lisi", new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErrorCode } }); ``` ### 获取花名册 ``` L/S: 通过传入ListOfLongLong对象引用, 调用成功后可获取rosterId的列表。 ListOfLongLong roster = new ListOfLongLong(); QNIMClient.getRosterService().get(roster, true); for (int i=0; i<roster.size(); i++){ long roster_id = roster.get(i); Log.e("roster id:",""+roster_id); } H/A: 在BMXDataCallBack回调中获取rosterId列表。 QNIMClient.getRosterManager().get(roster, true, new BMXDataCallBack<ListOfLongLong>(){ @Override public void onResult(BMXErrorCode bmxErrorCode, ListOfLongLong list) { //返回ListOfLongLong实例 for (int i=0; i<list.size(); i++){ long roster_id = list.get(i); Log.e("roster id:",""+roster_id); } } }); ``` ### 基础功能 ### 单聊 单聊是指一对一的聊天功能,单聊的 BMXConversationType 是 BMXConversationSingle,toId 是单聊对象的 userId。 ### 聊天室 聊天室是指附带角色和权限的用户集合内进行的内部广播方式的聊天功能,相比群聊,聊天室加入房间没有验证BMXConversationType 是 BMXConversationGroup,toId 是群组 Id。 ### 创建聊天室 ``` L/S: 通过传入BMXGroup对象引用, 调用成功后可获取群信息。 //参数说明: name(聊天室名字) group(群信息) BMXGroup group = new BMXGroup(); QNIMClient.getChatRoomService().create("name", group); H/A: 在BMXDataCallBack回调中获取群信息。 QNIMClient.getChatRoomManager().create("name", new BMXDataCallBack<BMXGroup>(){ @Override public void onResult(BMXErrorCode bmxErrorCode, BMXGroup group) { //返回BMXGroup实例 //取到groupid } }); ``` ### 加入聊天室 ``` L/S: 通过返回值获取到BMXErrorCode判断是否成功。 //参数说明: groupId(群id) QNIMClient.getChatRoomService().join(groupId); H/A: 在BMXCallBack回调中获取到BMXErrorCode判断是否成功。 QNIMClient.getChatRoomManager().join(groupId, new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErrorCode实例 } }); ``` ### 退出聊天室 ``` L/S: 通过返回值获取到BMXErrorCode判断是否成功。 //参数说明: groupId(群id) QNIMClient.getChatRoomService().leave(groupId); H/A: 在BMXCallBack回调中获取到BMXErrorCode判断是否成功。 QNIMClient.getChatRoomManager().leave(groupId, new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErrorCode实例 } }); ``` ### 解散聊天室 ``` L/S: 通过返回值获取到BMXErrorCode判断是否成功。 //参数说明: groupId(群id) QNIMClient.getChatRoomService().destroy(groupId); H/A: 在BMXCallBack回调中获取到BMXErrorCode判断是否成功。 QNIMClient.getChatRoomManager().destroy(groupId, new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErrorCode实例 } }); ``` ### 获取聊天室成员列表 ``` L/S: 通过传入BMXGroupMemberList对象引用, 调用成功后可获取群成员列表信息。 //参数说明: groupId(群id) forceRefresh(是否从server获取) boolean forceRefresh = true; BMXGroupMemberList memberList = new BMXGroupMemberList(); QNIMClient.getChatRoomService().getMembers(groupId, memberList, forceRefresh); H/A: 在BMXDataCallBack回调中获取群成员列表信息。 QNIMClient.getChatRoomManager().getMembers(groupId, forceRefresh, new BMXDataCallBack<BMXGroupMemberList>(){ @Override public void onResult(BMXErrorCode bmxErrorCode, BMXGroupMemberList list) { //返回BMXGroupMemberList实例 } }); ``` ### 群聊 群聊是指附带角色和权限的用户集合内进行的内部广播方式的聊天功能, BMXConversationType 是 BMXConversationGroup,toId 是群组 Id。 群组管理 ### 创建群组 ``` L/S: 通过传入BMXGroup对象引用, 调用成功后可获取群信息。 //参数说明: option(群配置信息) group(群信息) BMXGroupService.CreateGroupOptions options = new BMXGroupService.CreateGroupOptions(name, desc, publicCheckStatus); options.setMMembers(members); BMXGroup group = new BMXGroup(); QNIMClient.getGroupService().create(options, group); H/A: 在BMXDataCallBack回调中获取群信息。 QNIMClient.getGroupManager().create(option, new BMXDataCallBack<BMXGroup>(){ @Override public void onResult(BMXErrorCode bmxErrorCode, BMXGroup group) { //返回BMXGroup实例 } }); ``` ### 加入群组 ``` L/S: 通过返回值获取到BMXErrorCode判断是否成功。 //参数说明: group(群信息) message(申请入群原因) QNIMClient.getGroupService().join(group, message); H/A: 在BMXCallBack回调中获取到BMXErrorCode判断是否成功。 QNIMClient.getGroupManager().join(group, message, new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErrorCode实例 } }); ``` ### 退出群组 参数说明: group(群信息) ``` L/S: 通过返回值获取到BMXErrorCode判断是否成功。 QNIMClient.getGroupService().leave(group); H/A: 在BMXCallBack回调中获取到BMXErrorCode判断是否成功。 QNIMClient.getGroupManager().leave(group, new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErrorCode实例 } }); ``` ### 解散群组 ``` L/S: 通过返回值获取到BMXErrorCode判断是否成功。 //参数说明: group(群信息) QNIMClient.getGroupService().destroy(group); H/A: 在BMXCallBack回调中获取到BMXErrorCode判断是否成功。 QNIMClient.getGroupManager().destroy(group, new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErrorCode实例 } }); ``` ### 获取群成员列表 ``` L/S: 通过传入BMXGroupMemberList对象引用, 调用成功后可获取群成员列表信息。 //参数说明: group(群信息) forceRefresh(是否从server获取) boolean forceRefresh = true; BMXGroupMemberList memberList = new BMXGroupMemberList(); QNIMClient.getGroupService().getMembers(group, memberList, forceRefresh); H/A: 在BMXDataCallBack回调中获取群成员列表信息。 QNIMClient.getGroupManager().getMembers(group, forceRefresh, new BMXDataCallBack<BMXGroupMemberList>(){ @Override public void onResult(BMXErrorCode bmxErrorCode, BMXGroupMemberList list) { //返回BMXGroupMemberList实例 } }); ``` ### 获取群组列表 ``` L/S: 通过传入BMXGroupList对象引用, 调用成功后可获取群列表信息。 //参数说明: forceRefresh(是否从server获取) BMXGroupList list = new BMXGroupList(); QNIMClient.getGroupService().search(list, true); H/A: 在BMXDataCallBack回调中获取群列表信息。 QNIMClient.getGroupManager().getGroupList(true, new BMXDataCallBack<BMXGroupList>(){ @Override public void onResult(BMXErrorCode bmxErrorCode, BMXGroupList list) { //返回BMXGroupList实例 } }); ``` ### 获取群组信息 ``` L/S: 通过传入BMXGroup对象引用, 调用成功后可获取群信息。 //参数说明: groupId forceRefresh(是否从server获取) BMXGroup bmxGroup = new BMXGroup(); QNIMClient.getGroupService().search(mGroupId, bmxGroup, true); H/A: 在BMXDataCallBack回调中获取群信息。 QNIMClient.getGroupManager().getGroupList(mGroupId, true, new BMXDataCallBack<BMXGroup>(){ @Override public void onResult(BMXErrorCode bmxErrorCode, BMXGroup group) { //返回BMXGroup实例 } }); ``` ### 消息发送 登录成功之后才能进行聊天操作。发消息时,单聊和群聊调用的是统一接口,区别只是要设置下 BMXConversationType 消息的远程推送 开发者配置好远程推送的证书,且在代码中申请好权限,并将 deviceToken 传给MaxIM服务器,当接收者不在线的时候,MaxIM服务器会自动通过远程推送将消息发过去。 注: 推送的内容由发送消息接口的 pushContent 字段决定,内置消息发送的时候如果该字段没有值,将使用默认内容推送;自定义消息必须设置该字段,否则将不会推送。 deviceToken传给MaxIM接口 ``` L/S: 通过返回值获取到BMXErrorCode判断是否成功。 //参数说明: pushToken(推送token) QNIMClient.getUserService().bindDevice(pushToken); H/A: 在BMXCallBack回调中获取到BMXErrorCode判断是否成功。 QNIMClient.getUserManager().bindDevice(pushToken, new BMXCallBack(){ @Override public void onResult(BMXErrorCode bmxErrorCode) { //返回BMXErroeCode实例 } }); ``` ### 消息内容格式 ### 文本消息 ``` //参数说明: from(发送者id) to(接收者id) type(单群聊类型) text(文本内容) BMXMessage msg = BMXMessage.createMessage(from, to, type, to, text); 图片消息 //参数说明: from(发送者id) to(接收者id) type(单群聊类型) w(图片宽) h(图片高) path(图片本地路径) size(图片大小) BMXImageAttachment.Size size = new BMXMessageAttachment.Size(w, h); BMXImageAttachment imageAttachment = new BMXImageAttachment(path, size); BMXMessage msg = BMXMessage.createMessage(from, to, type, to, imageAttachment); 文件消息 参数说明: from(发送者id) to(接收者id) type(单群聊类型) path(文件本地路径) name(文件名称) BMXFileAttachment fileAttachment = new BMXFileAttachment(path, name); BMXMessage msg = BMXMessage.createMessage(from, to, type, to, fileAttachment); 位置消息 参数说明: from(发送者id) to(接收者id) type(单群聊类型) latitude(纬度) longitude(经度) address(地址) BMXLocationAttachment locationAttachment = new BMXLocationAttachment(latitude, longitude, address); BMXMessage msg = BMXMessage.createMessage(from, to, type, to, locationAttachment); 语音消息 参数说明: from(发送者id) to(接收者id) type(单群聊类型) path(语音本地路径) time(语音时长) BMXVoiceAttachment voiceAttachment = new BMXVoiceAttachment(path, time); BMXMessage msg = BMXMessage.createMessage(from, to, type, to, voiceAttachment); 消息操作 发送 L/S: //参数说明: BMXMessage(消息实体) QNIMClient.getChatService().sendMessage(msg); H/A: //发送消息状态,需要注册消息接收监听 QNIMClient.getChatManager().sendMessage(msg); 转发 L/S: //参数说明: BMXMessage(消息实体) QNIMClient.getChatService().forwardMessage(msg); H/A: //发送消息状态,需要注册消息接收监听 //参数说明: BMXMessage(消息实体) QNIMClient.getChatManager().forwardMessage(msg); 重发 L/S: //参数说明: BMXMessage(消息实体) QNIMClient.getChatService().resendMessage(msg); H/A: //发送消息状态,需要注册消息接收监听 QNIMClient.getChatManager().resendMessage(msg); 撤回 L/S: //参数说明: BMXMessage(消息实体) QNIMClient.getChatService().recallMessage(msg); H/A: //发送消息状态,需要注册消息接收监听 QNIMClient.getChatManager().recallMessage(msg); 下载消息附件 调用说明: 在FileCallBack中传入下载url,onProgress获取下载进度,onFail返回下载失败,onFinish返回成功的路径。 QNIMClient.getChatManager().downloadAttachment(message, new FileCallback(body.url()) { @Override protected void onProgress(long percent, String path, boolean isThumbnail) { } @Override protected void onFinish(String url, boolean isThumbnail) { BMImageLoader.getInstance().display(mImageView, "file://" + body.path(), mImageConfig); } @Override protected void onFail(String path, boolean isThumbnail) { } }); ``` ### 消息接收监听 ### 注册消息回调 ``` private BMXChatServiceListener mChatListener = new BMXChatServiceListener() { @Override public void onStatusChanged(BMXMessage msg, BMXErrorCode error) { //消息状态更新 } @Override public void onAttachmentStatusChanged(BMXMessage msg, BMXErrorCode error, int percent) { //附件状态更新 } @Override public void onRecallStatusChanged(BMXMessage msg, BMXErrorCode error) { //撤回状态更新 } @Override public void onReceive(BMXMessageList list) { //收到消息 } @Override public void onReceiveSystemMessages(BMXMessageList list) { //收到系统通知 } @Override public void onReceiveReadAcks(BMXMessageList list) { //收到已读回执 } @Override public void onReceiveDeliverAcks(BMXMessageList list) { //收到消息到达回执 } @Override public void onReceiveRecallMessages(BMXMessageList list) { //收到撤回消息通知 } @Override public void onAttachmentUploadProgressChanged(BMXMessage msg, int percent) { //附件上传进度更新 } }; ``` ### 功能进阶 BMXMessageObject实体中,提供可扩展属性(extensionJson 和 configJson) extensionJson 为开发使用的扩展字段,例如编辑状态。 configJson 为SDK自用的扩展字段,例如mention功能,push功能 群组@功能 群组中支持 @ 功能,满足您 @ 指定用户或 @所有人的需求,开发者在BMXMessage中通过设置config字段来实现群主@功能,已经@成员后的会下发推送通知 ``` // 文本功能添加@对象 if (atMap != null && !atMap.isEmpty()) { MentionBean mentionBean = new MentionBean(); mentionBean.setSenderNickname(senderName); mentionBean.setPushMessage(pushText); // @对象的存储信息 包括全部成员或者部分成员 if (atMap.containsKey("-1")) { // @全部 String atTitle = atMap.get("-1"); if (!TextUtils.isEmpty(atTitle) && text.contains(atTitle)) { // 如果包含全部直接走全部 还需要判断文本消息是否包含完成的@名称 如果没有就不触发@ mentionBean.setMentionAll(true); } } else { // @部分成员 需要遍历添加@信息 List<Long> atIds = new ArrayList<>(); mentionBean.setMentionAll(false); for (Map.Entry<String, String> entry : atMap.entrySet()) { // 发送文字包含@对象的名称时再加入 防止输入框@对象名称被修改 if (entry.getValue() != null && !TextUtils.isEmpty(entry.getValue()) && text.contains(entry.getValue())) { // @部分成员 feed信息只需要feedId和userId 所以需要去除无用的信息 atIds.add(Long.valueOf(entry.getKey())); } } mentionBean.setMentionList(atIds); } msg.setConfig(new Gson().toJson(mentionBean)); } 消息正在输入状态 String INPUT_STATUS = "input_status"; interface InputStatus { // 空 String NOTHING_STATUS = "nothing"; // 键盘弹起 String TYING_STATUS = "typing"; } String extension = ""; try { JSONObject object = new JSONObject(); object.put(INPUT_STATUS, tag == MessageInputBar.OnInputPanelListener.TAG_OPEN ? InputStatus.TYING_STATUS : InputStatus.NOTHING_STATUS); extension = object.toString(); } catch (JSONException e) { e.printStackTrace(); } BMXMessage msg = BMXMessage.createMessage(from, to, type, to, ""); if (msg == null) { return null; } msg.setDeliveryQos(BMXMessage.DeliveryQos.AtMostOnce); msg.setExtension(extension); ```<file_sep>/lib/lib_network/src/main/java/com/qiniu/network/RetrofitManager.kt package com.qiniu.network import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import io.reactivex.schedulers.Schedulers import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import okhttp3.Response import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import java.util.concurrent.Executors import java.util.concurrent.TimeUnit object RetrofitManager { var okHttp: OkHttpClient = OkHttpClient() private set var retrofit = Retrofit.Builder() .client(okHttp) .baseUrl("https://api.github.com/") .build() private set private val scheduler = Schedulers.from(Executors.newFixedThreadPool(10)); fun resetConfig(config: NetConfig) { okHttp = config.okBuilder.callTimeout(10 * 1000L, TimeUnit.MILLISECONDS).build() retrofit = Retrofit.Builder() .client(okHttp) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(scheduler)) .addConverterFactory(config.converterFactory) .baseUrl(config.base) .build() } fun <T> create(service: Class<T>?): T { return retrofit.create(service) } fun post(url: String, body: RequestBody): Response { val request = Request.Builder() .url(url) .post(body) .build(); val call = okHttp.newCall(request); return call.execute() } fun get(url: String): Response { val request = Request.Builder() .url(url) .get() .build(); val call = okHttp.newCall(request); return call.execute() } }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/pubchat/msg/MsgType.kt package com.qiniu.qndroidimsdk.pubchat.msg enum class MsgType { //文本消息 MsgTypeText,MsgTypeImg,MsgTypeVoice }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/Ext.kt package com.qiniu.qndroidimsdk import android.widget.Toast import com.qiniu.qndroidimsdk.util.AppCache fun String.asToast(){ Toast.makeText(AppCache.getContext(),this, Toast.LENGTH_SHORT).show() }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/LoginActivity.kt package com.qiniu.qndroidimsdk import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.lifecycle.lifecycleScope import com.qiniu.droid.imsdk.QNIMClient import com.qiniu.network.RetrofitManager import com.qiniu.qndroidimsdk.mode.IMUser import im.floo.BMXDataCallBack import im.floo.floolib.BMXErrorCode import im.floo.floolib.BMXUserProfile import kotlinx.android.synthetic.main.activity_login.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch class LoginActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) initViewData() } fun signUpNewUser(name: String, pwd: String) { val mBMXUserProfile = BMXUserProfile() val signCode = QNIMClient.signUpNewUser(name, pwd, mBMXUserProfile) if (signCode == BMXErrorCode.NoError) { val reLoginCode = QNIMClient.signInByName(name, pwd) if (reLoginCode == BMXErrorCode.NoError) { UserInfoManager.updateUserInfo(IMUser().apply { im_password = pwd im_username = name Log.d("signUpNewUser","mBMXUserProfile.userId() "+mBMXUserProfile.userId()) im_uid = mBMXUserProfile.userId() }) val i = Intent(this@LoginActivity, MainActivity::class.java) startActivity(i) } else { Toast.makeText( this@LoginActivity, "im登录失败 ${reLoginCode.name}", Toast.LENGTH_SHORT ).show() } } else { Toast.makeText( this@LoginActivity, "im登录失败 ${signCode.name}", Toast.LENGTH_SHORT ).show() } } fun initViewData() { bt_login_login.setOnClickListener { var phone = et_login_phone.text.toString() ?: "" var pwd = et_login_verification_code.text.toString() ?: "" if (phone.isEmpty()) { "请输入用户名".asToast() return@setOnClickListener } if (pwd.isEmpty()) { "请输入密码".asToast() return@setOnClickListener } lifecycleScope.launch(Dispatchers.Main) { try { val code = QNIMClient.signInByName(phone, pwd) if (code == BMXErrorCode.NoError) { val mBMXUserProfile = BMXUserProfile() QNIMClient.getUserManager().getProfile( false ) { p0, p1 -> if (p0 == BMXErrorCode.NoError) { UserInfoManager.updateUserInfo(IMUser().apply { im_password = pwd im_username = phone im_uid = p1.userId() }) } } val i = Intent(this@LoginActivity, MainActivity::class.java) startActivity(i) } else { if (BMXErrorCode.UserAuthFailed == code) { signUpNewUser(phone, pwd) } else { Toast.makeText( this@LoginActivity, "im登录失败 ${code.name}", Toast.LENGTH_SHORT ).show() } } } catch (e: Exception) { e.printStackTrace() e.message?.asToast() } } } } }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/pubchat/PubChatQuitRoom.java package com.qiniu.qndroidimsdk.pubchat; import org.jetbrains.annotations.NotNull; import java.io.Serializable; public class PubChatQuitRoom implements IChatMsg , Serializable { public static String action_quit_room="quit_room"; private String senderId; private String senderName; private String msgContent; public String getSenderId() { return senderId; } public void setSenderId(String senderId) { this.senderId = senderId; } public String getSenderName() { return senderName; } public void setSenderName(String senderName) { this.senderName = senderName; } public String getMsgContent() { return msgContent; } public void setMsgContent(String msgContent) { this.msgContent = msgContent; } @NotNull @Override public String getMsgHtml() { return "<font color='#ffb83c'>"+ " :"+msgContent+"</font>"; } @NotNull @Override public String getMsgAction() { return action_quit_room; } } <file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/util/AppCache.java package com.qiniu.qndroidimsdk.util; import android.app.Application; /** * Created by athoucai on 2017/7/10. * */ public class AppCache { private static Application context; public static Application getContext() { return context; } public static void setContext(Application app) { if (app == null) { AppCache.context = null; return; } AppCache.context = app; } }<file_sep>/lib/bzuicomp_bottomInput/src/main/java/com/qiniu/bzuicomp/bottominput/SoftInputUtil.java package com.qiniu.bzuicomp.bottominput; import android.app.Activity; import android.content.Context; import android.view.View; import android.view.inputmethod.InputMethodManager; /** * @author athoucai * @date 2017/7/10 */ public class SoftInputUtil { /** * 隐藏键盘,不知道键盘焦点在哪个view上 * * @param activity */ public static void hideSoftInputView(Activity activity) { hideSoftInputView(activity.getCurrentFocus()); } /** * 隐藏focusView上的键盘 * * @param focusView 获取键盘焦点的view */ public static void hideSoftInputView(View focusView) { if (focusView != null) { InputMethodManager manager = ((InputMethodManager) focusView.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE)); manager.hideSoftInputFromWindow(focusView.getWindowToken(), 0); } } /** * 根据focusView弹出键盘 * * @param focusView */ public static void showSoftInputView(View focusView) { if (focusView != null) { InputMethodManager manager = ((InputMethodManager) focusView.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE)); manager.showSoftInput(focusView, 0); } } /** * 判断软键盘是否弹出 */ public static boolean isShowKeyboard(Context context, View v) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if (imm.hideSoftInputFromWindow(v.getWindowToken(), 0)) { imm.showSoftInput(v, 0); return true; } else { return false; } } } <file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/util/SPConstant.kt package com.qiniu.qndroidimsdk.util object SPConstant { object User { var SpName = "config:user" val KEY_UID = "uid" val KEY_USER_INFO = "user_info" val KEY_USER_LOGIN_MODEL = "USER_LOGIN_MODEL" } object Config { } object AppConfig{ } } <file_sep>/lib/bzuicomp_bottomInput/src/main/java/com/qiniu/bzuicomp/bottominput/TIMMentionEditText.java package com.qiniu.bzuicomp.bottominput; import android.content.Context; import android.text.Editable; import android.text.Spannable; import android.text.TextUtils; import android.text.TextWatcher; import android.text.style.ForegroundColorSpan; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputConnectionWrapper; import android.widget.EditText; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TIMMentionEditText extends androidx.appcompat.widget.AppCompatEditText { public static final String TIM_METION_TAG = "@"; public static final Pattern TIM_MENTION_PATTERN = Pattern.compile("@[\\u4e00-\\u9fa5\\w\\-]+\\s");//@[^\s]+\s private Map<String, Pattern> mPatternMap = new HashMap<>(); private int mTIMMentionTextColor; private boolean mIsSelected; private Range mLastSelectedRange; private List<Range> mRangeArrayList = new ArrayList<>(); private OnMentionInputListener mOnMentionInputListener; public TIMMentionEditText(Context context) { super(context); init(); } public TIMMentionEditText(Context context, AttributeSet attrs) { super(context, attrs); init(); } public TIMMentionEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } @Override public InputConnection onCreateInputConnection(EditorInfo outAttrs) { return new HackInputConnection(super.onCreateInputConnection(outAttrs), true, this); } @Override protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { colorMentionString(); } @Override protected void onSelectionChanged(int selStart, int selEnd) { super.onSelectionChanged(selStart, selEnd); if (mLastSelectedRange != null && mLastSelectedRange.isEqual(selStart, selEnd)) { return; } Range closestRange = getRangeOfClosestMentionString(selStart, selEnd); if (closestRange != null && closestRange.to == selEnd) { mIsSelected = false; } Range nearbyRange = getRangeOfNearbyMentionString(selStart, selEnd); if (nearbyRange == null) { return; } //forbid cursor located in the mention string. if (selStart == selEnd) { setSelection(nearbyRange.getAnchorPosition(selStart)); } else { if (selEnd < nearbyRange.to) { setSelection(selStart, nearbyRange.to); } if (selStart > nearbyRange.from) { setSelection(nearbyRange.from, selEnd); } } } public void setTIMMentionTextColor(int color) { mTIMMentionTextColor = color; } public List<String> getMentionList(boolean excludeMentionCharacter) { List<String> mentionList = new ArrayList<>(); if (TextUtils.isEmpty(getText().toString())) { return mentionList; } for (Map.Entry<String, Pattern> entry : mPatternMap.entrySet()) { Matcher matcher = entry.getValue().matcher(getText().toString()); while (matcher.find()) { String mentionText = matcher.group(); if (excludeMentionCharacter) { mentionText = mentionText.substring(1, mentionText.length()-1); } if (!mentionList.contains(mentionText)) { mentionList.add(mentionText); } } } return mentionList; } public void setOnMentionInputListener(OnMentionInputListener onMentionInputListener) { mOnMentionInputListener = onMentionInputListener; } private void init() { //mTIMMentionTextColor = Color.RED; mPatternMap.clear(); mPatternMap.put(TIM_METION_TAG, TIM_MENTION_PATTERN); //setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); addTextChangedListener(new MentionTextWatcher()); } private void colorMentionString() { mIsSelected = false; if (mRangeArrayList != null) { mRangeArrayList.clear(); } Editable spannableText = getText(); if (spannableText == null || TextUtils.isEmpty(spannableText.toString())) { return; } //clear ForegroundColorSpan[] oldSpans = spannableText.getSpans(0, spannableText.length(), ForegroundColorSpan.class); for (ForegroundColorSpan oldSpan : oldSpans) { spannableText.removeSpan(oldSpan); } String text = spannableText.toString(); int lastMentionIndex = -1; for (Map.Entry<String, Pattern> entry : mPatternMap.entrySet()) { Matcher matcher = entry.getValue().matcher(text); while (matcher.find()) { String mentionText = matcher.group(); int start; if (lastMentionIndex != -1) { start = text.indexOf(mentionText, lastMentionIndex); } else { start = text.indexOf(mentionText); } int end = start + mentionText.length(); spannableText.setSpan(null/*new ForegroundColorSpan(mTIMMentionTextColor)*/, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); lastMentionIndex = end; mRangeArrayList.add(new Range(start, end)); } } } private Range getRangeOfClosestMentionString(int selStart, int selEnd) { if (mRangeArrayList == null) { return null; } for (Range range : mRangeArrayList) { if (range.contains(selStart, selEnd)) { return range; } } return null; } private Range getRangeOfNearbyMentionString(int selStart, int selEnd) { if (mRangeArrayList == null) { return null; } for (Range range : mRangeArrayList) { if (range.isWrappedBy(selStart, selEnd)) { return range; } } return null; } private class MentionTextWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int index, int i1, int count) { if (count == 1 && !TextUtils.isEmpty(charSequence)) { char mentionChar = charSequence.toString().charAt(index); for (Map.Entry<String, Pattern> entry : mPatternMap.entrySet()) { if (entry.getKey().equals(String.valueOf(mentionChar)) && mOnMentionInputListener != null) { mOnMentionInputListener.onMentionCharacterInput(entry.getKey()); } } } } @Override public void afterTextChanged(Editable editable) { } } private class HackInputConnection extends InputConnectionWrapper { private EditText editText; HackInputConnection(InputConnection target, boolean mutable, TIMMentionEditText editText) { super(target, mutable); this.editText = editText; } @Override public boolean sendKeyEvent(KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_DEL) { int selectionStart = editText.getSelectionStart(); int selectionEnd = editText.getSelectionEnd(); Range closestRange = getRangeOfClosestMentionString(selectionStart, selectionEnd); if (closestRange == null) { mIsSelected = false; return super.sendKeyEvent(event); } if (mIsSelected || selectionStart == closestRange.from) { mIsSelected = false; return super.sendKeyEvent(event); } else { mIsSelected = true; mLastSelectedRange = closestRange; setSelection(closestRange.to, closestRange.from); sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)); } return true; } return super.sendKeyEvent(event); } @Override public boolean deleteSurroundingText(int beforeLength, int afterLength) { if (beforeLength == 1 && afterLength == 0) { return sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)) && sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL)); } return super.deleteSurroundingText(beforeLength, afterLength); } } private class Range { int from; int to; Range(int from, int to) { this.from = from; this.to = to; } boolean isWrappedBy(int start, int end) { return (start > from && start < to) || (end > from && end < to); } boolean contains(int start, int end) { return from <= start && to >= end; } boolean isEqual(int start, int end) { return (from == start && to == end) || (from == end && to == start); } int getAnchorPosition(int value) { if ((value - from) - (to - value) >= 0) { return to; } else { return from; } } } public interface OnMentionInputListener { void onMentionCharacterInput(String tag); } } <file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/pubchat/IChatMsg.kt package com.qiniu.qndroidimsdk.pubchat import com.alibaba.fastjson.annotation.JSONField /** * 公屏数据抽象 */ interface IChatMsg { /** * 返回 html格式公屏样式 */ @JSONField(serialize = false) fun getMsgHtml():String @JSONField(serialize = false) fun getMsgAction():String }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/util/Utils.java package com.qiniu.qndroidimsdk.util; import android.app.Activity; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; import android.util.Base64; import androidx.loader.content.CursorLoader; public final class Utils { /** * Decode base64 string */ public static String base64Decode(String msg) { try { return new String(Base64.decode(msg.getBytes(), Base64.DEFAULT)); } catch (IllegalArgumentException e) { return null; } } } <file_sep>/lib/bzuicomp_bottomInput/src/main/java/com/qiniu/bzuicomp/bottominput/RoomInputDialog.kt package com.qiniu.bzuicomp.bottominput import android.annotation.SuppressLint import android.app.Activity import android.content.DialogInterface import android.media.MediaPlayer import android.net.Uri import android.provider.MediaStore import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.Gravity import android.view.KeyEvent import android.view.MotionEvent import android.view.View import android.widget.Toast import androidx.core.content.FileProvider import androidx.loader.content.CursorLoader import com.hapi.mediapicker.ContentUriUtil import com.hapi.mediapicker.ImagePickCallback import com.hapi.mediapicker.PicPickHelper import kotlinx.android.synthetic.main.dialog_room_input.* import java.io.File import java.lang.Exception /** * 底部输入框 */ class RoomInputDialog(var type: Int = type_text) : FinalDialogFragment() { companion object { const val type_text = 1 const val type_danmu = 2 } init { applyGravityStyle(Gravity.BOTTOM) applyDimAmount(0f) } /** * 发消息拦截回调 */ var sendPubTextCall: ((msg: String) -> Unit)? = null var sendImgCall :((url: Uri)->Unit)?=null var sendVoiceCall:((url: String)->Unit)?=null // private val faceFragment by lazy { FaceFragment() } private val mSoftKeyBoardListener by lazy { SoftKeyBoardListener(requireActivity()) } override fun getViewLayoutId(): Int { return R.layout.dialog_room_input } private var inputType = 0 private var mVoiceRecorder: VoiceRecorder? = null private var lastTime = 0L @SuppressLint("ClickableViewAccessibility") override fun init() { //表情暂时没写 chat_message_input.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { if (s?.toString()?.isEmpty() == true) { send_btn.visibility = View.GONE } else { send_btn.visibility = View.VISIBLE } } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } }) chat_message_input.setOnClickListener { hideFace() hideMore() hideVoice() } chat_message_input.requestFocus() chat_message_input.post { SoftInputUtil.showSoftInputView(chat_message_input) } face_btn.setOnClickListener { checkShowFace() } mSoftKeyBoardListener.setOnSoftKeyBoardChangeListener(object : SoftKeyBoardListener.OnSoftKeyBoardChangeListener { override fun keyBoardShow(height: Int) { hideFace() } override fun keyBoardHide(height: Int) { } }) send_btn.setOnClickListener { val msgEdit = chat_message_input.text.toString() sendPubTextCall?.invoke(msgEdit) dismiss() } voice_input_switch.setOnClickListener { if (voice_input_switch.isSelected) { hideVoice() } else { SoftInputUtil.hideSoftInputView(chat_message_input) hideFace() hideMore() showVoice() } voice_input_switch.isSelected = !voice_input_switch.isSelected } emojiBoard.setItemClickListener { code -> if (code == "/DEL") { chat_message_input.dispatchKeyEvent( KeyEvent( KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL ) ) } else { chat_message_input.getText()?.insert(chat_message_input.selectionStart, code) } } more_btn.setOnClickListener { if (more_btn.isSelected) { hideMore() } else { SoftInputUtil.hideSoftInputView(chat_message_input) hideFace() showMore() } more_btn.isSelected = !more_btn.isSelected } btnSendImg.setOnClickListener { PicPickHelper(activity!!).fromLocal(null, object : ImagePickCallback { override fun onSuccess(result: String?, url: Uri?) { url?.let { sendImgCall?.invoke(url) } Log.d("mjl", "${result} ${url.toString()}") } }) } btnTakePhoto.setOnClickListener { } chat_voice_input.setOnTouchListener { v, event -> fun stop() { Log.d("mjl", "stop recorder") mVoiceRecorder?.let { if ((System.currentTimeMillis() - lastTime) < 1000) { Toast.makeText(context, "录音时间太短了", Toast.LENGTH_SHORT).show() } else { val path = it.stopRecord() if(path.isNotEmpty()){ sendVoiceCall?.invoke( path) } Log.d("mjl", "path ${path}") } } mVoiceRecorder = null } fun start() { Log.d("mjl", "start recorder") mVoiceRecorder = VoiceRecorder() mVoiceRecorder?.startRecord(this@RoomInputDialog.context) lastTime = System.currentTimeMillis() } when (event.action) { MotionEvent.ACTION_DOWN -> start() MotionEvent.ACTION_UP -> { stop() } MotionEvent.ACTION_CANCEL -> { stop() } } false } } override fun onDismiss(dialog: DialogInterface) { super.onDismiss(dialog) mSoftKeyBoardListener.detach() } private fun checkShowFace() { if (inputType == 0) { showFace() } else { hideFace() } } private fun showMore() { llMore.visibility = View.VISIBLE } private fun hideMore() { llMore.visibility = View.GONE } private fun showVoice() { chat_message_input.visibility = View.GONE chat_voice_input.visibility = View.VISIBLE face_btn.visibility = View.GONE more_btn.visibility = View.GONE send_btn.visibility = View.GONE } private fun hideVoice() { chat_message_input.visibility = View.VISIBLE chat_voice_input.visibility = View.GONE face_btn.visibility = View.VISIBLE more_btn.visibility = View.VISIBLE } private fun hideFace() { emojiBoard.visibility = View.GONE inputType = 0 face_btn.isSelected = false } private fun showFace() { SoftInputUtil.hideSoftInputView(chat_message_input) emojiBoard.visibility = View.VISIBLE inputType = 1 face_btn.isSelected = true } fun getAbsoluteImagePath(activity: Activity, contentUri: Uri): String { //如果是对媒体文件,在android开机的时候回去扫描,然后把路径添加到数据库中。 //由打印的contentUri可以看到:2种结构。正常的是:content://那么这种就要去数据库读取path。 //另外一种是Uri是 file:///那么这种是 Uri.fromFile(File file);得到的 println(contentUri) val projection = arrayOf(MediaStore.Images.Media.DATA) var urlpath: String? val loader = CursorLoader(activity!!, contentUri, projection, null, null, null) val cursor = loader.loadInBackground() try { val column_index = cursor!!.getColumnIndex(MediaStore.Images.Media.DATA) cursor.moveToFirst() urlpath = cursor.getString(column_index) //如果是正常的查询到数据库。然后返回结构 return urlpath } catch (e: Exception) { e.printStackTrace() // TODO: handle exception } finally { cursor?.close() } //如果是文件。Uri.fromFile(File file)生成的uri。那么下面这个方法可以得到结果 urlpath = contentUri.path return urlpath?:"" } }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/UserInfoManager.kt package com.qiniu.qndroidimsdk import android.text.TextUtils import com.qiniu.qndroidimsdk.mode.IMGroup import com.qiniu.qndroidimsdk.mode.IMUser import com.qiniu.qndroidimsdk.mode.LoginToken import com.qiniu.qndroidimsdk.mode.UserInfo import com.qiniu.qndroidimsdk.pubchat.JsonUtils import com.qiniu.qndroidimsdk.util.SPConstant import com.qiniu.qndroidimsdk.util.SpUtil object UserInfoManager { var mIMUser: IMUser? = null var mIMGroup: IMGroup? = null private var uid = "" fun init() { mIMUser = JsonUtils.parseObject( SpUtil.get(SPConstant.User.SpName)?.readString( SPConstant.User.KEY_USER_INFO ) ?: "", IMUser::class.java ) as IMUser? uid = mIMUser?.im_uid?.toString()?:"" } /** * 快捷获取 uid */ fun getUserId(): String { return uid } fun updateUserInfo(userInfo: IMUser) { uid = mIMUser?.im_uid?.toString()?:"" mIMUser = userInfo saveUserInfoToSp() } //存sp private fun saveUserInfoToSp() { mIMUser?.let { SpUtil.get(SPConstant.User.SpName) .saveData(SPConstant.User.KEY_USER_INFO, JsonUtils.toJson(it)) } } fun onLogout(toastStr:String="") { } fun clearUser(){ SpUtil.get(SPConstant.User.SpName).clear() uid = "" mIMUser = null } }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/MainActivity.kt package com.qiniu.qndroidimsdk import android.content.Intent import android.os.Build import android.os.Bundle import android.text.TextUtils import android.util.Log import android.view.View import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.alibaba.fastjson.JSON import com.qiniu.droid.imsdk.QNIMClient import com.qiniu.network.RetrofitManager import com.qiniu.qndroidimsdk.mode.HttpDate import com.qiniu.qndroidimsdk.mode.IMGroup import com.qiniu.qndroidimsdk.pubchat.JsonUtils import com.qiniu.qndroidimsdk.room.RoomActivity import com.qiniu.qndroidimsdk.util.PermissionChecker import com.qiniu.qndroidimsdk.util.Utils import com.uuzuche.lib_zxing.activity.CaptureActivity import com.uuzuche.lib_zxing.activity.CodeUtils import im.floo.BMXDataCallBack import im.floo.floolib.BMXErrorCode import im.floo.floolib.BMXGroup import kotlinx.android.synthetic.main.activity_main.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.launch import okhttp3.MediaType.Companion.toMediaType import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import okhttp3.internal.wait import org.json.JSONObject class MainActivity : AppCompatActivity() { var token1 = "<KEY> <KEY> //debug "<KEY>" var token2 = "<KEY> // "<KEY> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) findViewById<View>(R.id.buttonToken1).setOnClickListener { v -> room_token_edit_text.setText(token1) joinRoom(v) } findViewById<View>(R.id.buttonToken2).setOnClickListener { v -> room_token_edit_text.setText(token2) joinRoom(v) } } fun joinRoom(view: View?) { // 在进入房间前,必须有相对应的权限,在 Android 6.0 后除了在 Manifest 文件中声明外还需要动态申请权限。 if (!isPermissionOK) { Toast.makeText(this, "Some permissions is not approved !!!", Toast.LENGTH_SHORT).show() return } if (!TextUtils.isEmpty(room_token_edit_text!!.text)) { lifecycleScope.launch(Dispatchers.Main) { try { val roomToken = room_token_edit_text!!.text val tokens: Array<String> = roomToken.split(":".toRegex()).toTypedArray() if (tokens.size != 3) { return@launch } val roomInfo: String = Utils.base64Decode(tokens[2]) val json = JSONObject(roomInfo) val mRoomName = json.optString("roomName") val body = "{\"group_id\":\"${mRoomName}\"}".toRequestBody("application/json".toMediaType()) val response = async<Response>(Dispatchers.IO) { val response= RetrofitManager.post("https://im-test.qiniuapi.com/v1/mock/group",body) response }.await() val jsonStr = response.body?.string() Log.d("mRoomName"," jsonStr "+ jsonStr) if( response.code == 200){ val json = JsonUtils.parseObject(jsonStr, HttpDate::class.java)?.data UserInfoManager.mIMGroup = json Log.d("mRoomName"," groupInfo.im_group_id "+ json?.group_id) val intent = Intent(this@MainActivity, RoomActivity::class.java) intent.putExtra("roomToken", room_token_edit_text!!.text.toString()) startActivity(intent) }else{ "创建房间失败".asToast() } } catch (e: Exception) { e.printStackTrace() e.message?.asToast() } } } } fun clickToScanQRCode(view: View?) { // 扫码也用到了相机权限 if (!isPermissionOK) { Toast.makeText(this, "Some permissions is not approved !!!", Toast.LENGTH_SHORT).show() return } val intent = Intent(this, CaptureActivity::class.java) startActivityForResult(intent, QRCODE_RESULT_REQUEST_CODE) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == 1) { // 处理扫描结果 if (null != data) { val bundle = data.extras ?: return if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) { val result = bundle.getString(CodeUtils.RESULT_STRING) room_token_edit_text!!.setText(result) } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) { Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show() } } } } private val isPermissionOK: Boolean private get() { val checker = PermissionChecker(this) return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checker.checkPermission() } companion object { private const val QRCODE_RESULT_REQUEST_CODE = 1 } }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/room/ChatRoomFragment.kt package com.qiniu.qndroidimsdk.room import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.qiniu.bzuicomp.bottominput.RoomInputDialog import com.qiniu.droid.imsdk.QNIMClient import com.qiniu.qndroidimsdk.R import com.qiniu.qndroidimsdk.UserInfoManager import com.qiniu.qndroidimsdk.pubchat.InputMsgReceiver import im.floo.floolib.BMXErrorCode import kotlinx.android.synthetic.main.chat_fragment.* import kotlinx.coroutines.delay import kotlinx.coroutines.launch class ChatRoomFragment : Fragment() { private val mInputMsgReceiver by lazy { InputMsgReceiver(requireContext()) } // private val mWelComeReceiver by lazy { // WelComeReceiver() // } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return layoutInflater.inflate(R.layout.chat_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) lifecycle.addObserver(mInputMsgReceiver) lifecycle.addObserver(pubChatView) buttonSend.setOnClickListener { RoomInputDialog() .apply { sendPubTextCall = { msgEdit -> mInputMsgReceiver.buildMsg(msgEdit) } sendImgCall = { mInputMsgReceiver.buildImgMsg(it) } sendVoiceCall = { mInputMsgReceiver.buildVoiceMsg(it) } } .show(childFragmentManager, "RoomInputDialog") } Log.d( "mRoomName", " 加入聊天 groupInfo.im_group_id " + UserInfoManager.mIMGroup!!.im_group_id ) QNIMClient.getChatRoomManager().join( UserInfoManager.mIMGroup!!.im_group_id ) { p0 -> if (p0 == BMXErrorCode.NoError || p0 == BMXErrorCode.GroupMemberExist) { // "加入聊天室成功".asToast() Log.d("mRoomName", " 加入聊天 加入聊天室成功 " + UserInfoManager.mIMGroup!!.im_group_id) lifecycleScope.launch { delay(1000) mInputMsgReceiver.sendEnterMsg() } } else { Log.d("mRoomName", " 加入聊天 加入聊天室失 " + UserInfoManager.mIMGroup!!.im_group_id) } } } override fun onDestroy() { super.onDestroy() mInputMsgReceiver.sendQuitMsg() QNIMClient.getChatRoomManager().leave(UserInfoManager.mIMGroup!!.im_group_id) { } } }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/mode/LoginToken.java package com.qiniu.qndroidimsdk.mode; import java.io.Serializable; public class LoginToken implements Serializable { private String loginToken; private String accountId; public String getLoginToken() { return loginToken; } public void setLoginToken(String loginToken) { this.loginToken = loginToken; } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } } <file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/pubchat/PubChatAdapter.kt package com.qiniu.qndroidimsdk.pubchat import android.annotation.SuppressLint import android.graphics.drawable.AnimationDrawable import android.text.Html import android.view.View import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.BaseViewHolder import com.qiniu.qndroidimsdk.R import com.qiniu.qndroidimsdk.pubchat.msg.* import com.qiniu.qndroidimsdk.util.AudioPlayer import kotlinx.android.synthetic.main.bzui_item_pub_chat.view.* class PubChatAdapter : BaseQuickAdapter<RtmMessage, BaseViewHolder>( R.layout.bzui_item_pub_chat, ArrayList<RtmMessage>() ) { @SuppressLint("SetTextI18n") override fun convert(holder: BaseViewHolder, item: RtmMessage) { holder.itemView.tvText.visibility = View.GONE holder.itemView.ivImgAttach.visibility = View.GONE holder.itemView.llVoice.visibility = View.GONE holder.itemView.tvName.text = item.sendImName if(item.attachmentProcess>=100 || item.attachmentProcess<0){ holder.itemView.loading_progress.visibility= View.GONE }else{ holder.itemView.loading_progress.visibility= View.VISIBLE } when (item.msgType) { MsgType.MsgTypeText -> { holder.itemView.tvText.visibility = View.VISIBLE val msg = item as RtmTextMsg val text = when (msg.action) { (PubChatMsgModel.action_pubText) -> { JsonUtils.parseObject(msg.msgStr, PubChatMsgModel::class.java)?.getMsgHtml() ?: "" } PubChatWelCome.action_welcome -> JsonUtils.parseObject(msg.msgStr, PubChatWelCome::class.java)?.getMsgHtml() ?: "" PubChatQuitRoom.action_quit_room -> JsonUtils.parseObject(msg.msgStr, PubChatQuitRoom::class.java)?.getMsgHtml() ?: "" else -> { "" } } holder.itemView.tvText.text = Html.fromHtml(text, null, null); } MsgType.MsgTypeVoice -> { holder.itemView.ivVoiceAnim.setImageResource(R.drawable.play_voice_message); holder.itemView.llVoice.visibility = View.VISIBLE holder.itemView.tvVoiceDuration.text = (item as RtmVoiceMsg).duration.toString()+"'" holder.itemView.ivVoiceAnim.setOnClickListener { val animationDrawable: AnimationDrawable? = holder.itemView.ivVoiceAnim.getDrawable() as AnimationDrawable? animationDrawable?.start() AudioPlayer.getInstance().startPlay(mContext,(item as RtmVoiceMsg).url) { holder.itemView.ivVoiceAnim.post { animationDrawable?.stop() holder.itemView.ivVoiceAnim.setImageResource(R.drawable.play_voice_message); } } } } MsgType.MsgTypeImg -> { holder.itemView.ivImgAttach.visibility = View.VISIBLE Glide.with(mContext) .load((item as RtmImgMsg).thumbnailUrl) .into(holder.itemView.ivImgAttach) } } } }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/pubchat/InterviewRoomTipMsg.kt package com.qiniu.qndroidimsdk.pubchat class InterviewRoomTipMsg(val msgContent:String) : IChatMsg { /** * 返回 html格式公屏样式 */ override fun getMsgHtml(): String { return " <font color='#50000'>$msgContent</font> " } override fun getMsgAction(): String { return "InterviewRoomTipMsg" } }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/mode/IMGroup.kt package com.qiniu.qndroidimsdk.mode class IMGroup { var group_id: String? = null var im_group_id: Long = 0; } class HttpDate { var code = 0 var msg = "" var data: IMGroup? = null }<file_sep>/lib/lib_network/src/main/java/com/qiniu/network/NetConfig.kt package com.qiniu.network import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Converter import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit class NetConfig { var base = "" var converterFactory: Converter.Factory = GsonConverterFactory.create() var logInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } var okBuilder = OkHttpClient.Builder().connectTimeout(30000, TimeUnit.MILLISECONDS) .retryOnConnectionFailure(true) }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/pubchat/JsonUtils.kt package com.qiniu.qndroidimsdk.pubchat import android.text.TextUtils import com.alibaba.fastjson.JSON import com.alibaba.fastjson.util.ParameterizedTypeImpl import java.lang.Exception object JsonUtils { fun <T> parseObject(text: String?, clazz: ParameterizedTypeImpl): T? { if(TextUtils.isEmpty(text)){ return null } var t:T?=null try { t= JSON.parseObject(text, clazz) }catch (e:Exception){ e.printStackTrace() } return t } fun <T> parseObject(text: String?, clazz: Class<T>): T? { if(TextUtils.isEmpty(text)){ return null } var t:T?=null try { t= JSON.parseObject(text, clazz) }catch (e:Exception){ e.printStackTrace() } return t } fun toJson(any: Any):String { return JSON.toJSONString(any) } }<file_sep>/app/src/main/java/com/qiniu/qndroidimsdk/App.kt package com.qiniu.qndroidimsdk import android.app.Application import android.util.Log import com.qiniu.droid.imsdk.QNIMClient import com.qiniu.network.NetConfig import com.qiniu.network.RetrofitManager import com.qiniu.qndroidimsdk.util.AppCache import com.uuzuche.lib_zxing.activity.ZXingLibrary import im.floo.floolib.* import java.io.File class App : Application() { companion object { init { System.loadLibrary("floo") } } override fun onCreate() { super.onCreate() AppCache.setContext(this) AppContextUtils.initApp(this) val appPath = AppContextUtils.getAppContext().filesDir.path val dataPath = File("$appPath/data_dir") val cachePath = File("$appPath/cache_dir") dataPath.mkdirs() cachePath.mkdirs() // 配置sdk config val config = BMXSDKConfig( BMXClientType.Android, "1", dataPath.absolutePath, cachePath.absolutePath, "MaxIM" ) config.consoleOutput = true config.logLevel = BMXLogLevel.Debug config.appID ="cigzypnhoyno" config.setEnvironmentType(BMXPushEnvironmentType.Production) // 初始化BMXClient QNIMClient.init(config) UserInfoManager.init() RetrofitManager.resetConfig(NetConfig().apply { base = "https://niucube-api.qiniu.com/" }) // 初始化使用的第三方二维码扫描库,与 QNRTC 无关,请忽略 ZXingLibrary.initDisplayOpinion(applicationContext) } }
f3d6a1c5e728275b187c0e0261fe84adcf31af57
[ "Markdown", "Java", "Kotlin", "Gradle" ]
33
Gradle
xulonc/QNDroidIMSDK
250bb59ee32033580bf09251f64fa3c7b7865262
493fae633009dd48d5b30ff0063c8a77de9c7e21
refs/heads/master
<file_sep>driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/product user=root password= <file_sep>package com.mindteck.service; import java.util.List; import com.mindteck.model.CartItem; public interface CartService { public void insertIntoCart(CartItem cartItem); public void removeFromCart(int id); public void changeCartItems(CartItem cartItem); public List<CartItem> viewCartItems(); public CartItem getFromCartById(int id); public List<CartItem> listCartItemsByUsername(String username); } <file_sep>package com.mindteck.util; import java.sql.Connection; import java.sql.DriverManager; import java.util.ResourceBundle; public class ConnectionFactory { private static Connection connection = null; public static Connection getConnection() { if(connection != null) return connection; else { try { ResourceBundle bundle=ResourceBundle.getBundle("db"); String driver = bundle.getString("driver"); String url = bundle.getString("url"); String user = bundle.getString("user"); Class.forName(driver); connection = DriverManager.getConnection(url, user, ""); } catch(Exception e) { e.printStackTrace(); } return connection; } } } <file_sep>package com.mindteck.service; import java.util.List; import com.mindteck.dao.CartItemDAO; import com.mindteck.dao.CartItemDAOImpl; import com.mindteck.model.CartItem; public class CartServiceImpl implements CartService { CartItemDAO dao = new CartItemDAOImpl(); public void insertIntoCart(CartItem cartItem) { dao.addToCart(cartItem); } public void removeFromCart(int id) { dao.deleteFromCart(id); } public void changeCartItems(CartItem cartItem) { dao.updateCart(cartItem); } public List<CartItem> viewCartItems() { return dao.listShoppingCart(); } public CartItem getFromCartById(int id) { return dao.getCartItemById(id); } public List<CartItem> listCartItemsByUsername(String username) { return dao.getCartItemsByUsername(username); } } <file_sep>package com.mindteck.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.mindteck.dao.ConnectionManager; import com.mindteck.model.CartItem; import com.mindteck.util.ConnectionFactory; import com.mindteck.model.Order; public class CartItemDAOImpl implements CartItemDAO { //private Connection connection = null; public CartItemDAOImpl() { /* try { connection = ConnectionManager.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } /* This methods inserts products into the shopping cart */ public void addToCart(CartItem cartItem) { Connection connection = null; try { connection = ConnectionManager.getConnection(); System.out.println("Inside the function"); PreparedStatement pst = connection.prepareStatement( "insert into cartItems(id, username, description,quantity, price, orderId) values (?, ?, ?, ?,?,?)"); pst.setInt(1, cartItem.getProductId()); pst.setString(2, cartItem.getUsername()); pst.setString(3, cartItem.getDescription()); pst.setInt(4, cartItem.getQuantity()); pst.setDouble(5, cartItem.getPrice()); pst.setInt(6, cartItem.getOrderId()); pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } } /* delete from the cart a product with a given id */ public void deleteFromCart(int id) { Connection connection = null; try { connection = ConnectionManager.getConnection(); PreparedStatement pst = connection.prepareStatement("delete from cartItems where cartId=?"); pst.setInt(1, id); pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } } public void updateCart(CartItem cartItem) { Connection connection = null; try { connection = ConnectionManager.getConnection(); PreparedStatement pst = connection.prepareStatement("update cartItems set price=?, quantity=?" + " where id=?"); pst.setDouble(1, cartItem.getPrice()); pst.setInt(2, cartItem.getQuantity()); pst.setInt(3, cartItem.getCartId()); pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } } /* add cart items from database to an arrayList and return the arrayList */ public List<CartItem> listShoppingCart() { Connection connection = null; List<CartItem> cartItems = new ArrayList<CartItem>(); try { connection = ConnectionManager.getConnection(); Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("select * from cartItems"); while (rs.next()) { CartItem cartItem = new CartItem(); cartItem.setCartId(rs.getInt("cartId")); cartItem.setProductId(rs.getInt("id")); cartItem.setDescription(rs.getString("description")); cartItem.setPrice(rs.getDouble("price")); cartItem.setQuantity(rs.getInt("quantity")); cartItem.setOrderId(rs.getInt("orderId")); cartItems.add(cartItem); } } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } return cartItems; } public List<CartItem> getCartItemsByUsername(String username) { Connection connection = null; List<CartItem> cartItems = new ArrayList<CartItem>(); try { connection = ConnectionManager.getConnection(); PreparedStatement pst = connection.prepareStatement("select * from cartItems where username=?"); pst.setString(1, username); ResultSet rs = pst.executeQuery(); while (rs.next()) { CartItem cartItem = new CartItem(); cartItem.setCartId(rs.getInt("cartId")); cartItem.setProductId(rs.getInt("id")); cartItem.setDescription(rs.getString("description")); cartItem.setPrice(rs.getDouble("price")); cartItem.setQuantity(rs.getInt("quantity")); cartItem.setOrderId(rs.getInt("orderId")); cartItems.add(cartItem); } } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } return cartItems; } /* This method returns a cart item with a given id */ public CartItem getCartItemById(int id) { Connection connection = null; CartItem cartItem = new CartItem(); try { connection = ConnectionManager.getConnection(); PreparedStatement pst = connection.prepareStatement("select * from cartItems where id=?"); pst.setInt(1, id); ResultSet rs = pst.executeQuery(); if (rs.next()) { cartItem.setCartId(rs.getInt("cartId")); cartItem.setDescription(rs.getString("description")); cartItem.setPrice(rs.getDouble("price")); cartItem.setQuantity(rs.getInt("quantity")); } } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } return cartItem; } } <file_sep>package com.mindteck.dao; import java.util.List; import com.mindteck.model.User; public interface UserDAO { public boolean getLoginInfo(String username, String password) throws Exception; public boolean checkIfUserExists(String username, String email) throws Exception; public void addUser(User user); public void deleteUser(String userId); public List<User> getAllUsers(); public User getUserById(String userid); } <file_sep>package com.mindteck.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.mindteck.dao.ConnectionManager; import com.mindteck.model.CartItem; import com.mindteck.model.Order; import com.mindteck.model.User; import com.mindteck.util.ConnectionFactory; public class OrderDAOImpl implements OrderDAO { //private Connection connection = null; public OrderDAOImpl() { /*try { connection = ConnectionManager.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ } /* Insert user order into the orders table */ public void addOrder(Order order) { Connection connection = null; try { connection = ConnectionManager.getConnection(); System.out.println("Inside the function"); PreparedStatement pst = connection.prepareStatement( "insert into orders(orderId, Orderamount, email, firstname, lastname, phone, orderDate, orderNumber) values (?, ?, ?, ?, ?, ?,?,?)"); pst.setInt(1, order.getOrderId()); pst.setDouble(2, order.getOrderAmount()); pst.setString(3, order.getEmail()); pst.setString(4, order.getFirstname()); pst.setString(5, order.getLastname()); pst.setString(6, order.getPhone()); pst.setDate(7, new java.sql.Date(order.getOrderDate().getTime())); pst.setString(8, order.getOrderNumber()); pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } } /* Delete a product from the cart */ public void deleteFromCart(int id) { Connection connection = null; try { connection = ConnectionManager.getConnection(); PreparedStatement pst = connection.prepareStatement("delete from cart where cartId=?"); pst.setInt(1, id); pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } } /* Add shopping cart items into an array and return the array */ public List<CartItem> getCartItems(String username) { CartItemDAOImpl item = new CartItemDAOImpl(); List<CartItem> li = new ArrayList<CartItem>(); li = item.getCartItemsByUsername(username); return li; } /* Get user details given user's username */ public User getUserByUsername(String username) { UserDAOImpl dao = new UserDAOImpl(); User user = new User(); user = dao.getUserById(username); return user; } /* * When a customer places an order, the order details are added to the * orders table */ public void placeOrder(Order order) { Connection connection = null; try { connection = ConnectionManager.getConnection(); PreparedStatement pst = connection.prepareStatement( "insert into orders (orderId, orderAmount, email, firstname, lastname, phone, orderDate, orderNumber) values (?, ?, ?, ?, ?, ?,?, ?)"); pst.setInt(1, order.getOrderId()); pst.setDouble(2, order.getOrderAmount()); pst.setString(3, order.getEmail()); pst.setString(4, order.getFirstname()); pst.setString(5, order.getLastname()); pst.setString(6, order.getPhone()); pst.setDate(7, new java.sql.Date(order.getOrderDate().getTime())); pst.setString(8, order.getOrderNumber()); pst.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } } /* This method empties the cart after user places an order */ public void clearCart(String username) { Connection connection = null; //Statement statement; try { connection = ConnectionManager.getConnection(); //statement = connection.createStatement(); PreparedStatement pst = connection.prepareStatement("delete from cartItems where username=?"); pst.setString(1, username); pst.executeUpdate(); //statement.executeUpdate("delete from cart where username=?"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } } /* * This methods add orders from cart table to an orders arrayList and * returns the ArrayList */ public List<Order> viewOrder(String username) { Connection connection = null; List<Order> orders = new ArrayList<Order>(); try { PreparedStatement pst = connection.prepareStatement("select * from cartItems where username=?"); pst.setString(1, username); ResultSet rs = pst.executeQuery(); while (rs.next()) { Order order = new Order(); order.setOrderId(rs.getInt("orderId")); order.setOrderAmount(rs.getDouble("orderAmount")); order.setEmail(rs.getString("email")); order.setFirstname(rs.getString("firstname"));// order.setLastname(rs.getString("lastname")); order.setPhone(rs.getString("phone")); order.setOrderDate(rs.getDate("orderDate")); order.setOrderNumber(rs.getString("orderNumber")); orders.add(order); } } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } return orders; } /* * Given an email address, this method searches the orders table for records * which match the emial address and returns an orders arrayList with the * records */ public List<Order> getOrderByEmail(String email) { Connection connection = null; List<Order> orders = new ArrayList<Order>(); try { connection = ConnectionManager.getConnection(); PreparedStatement pst = connection.prepareStatement("select * from orders where email=?"); pst.setString(1, email); ResultSet rs = pst.executeQuery(); while (rs.next()) { Order order = new Order(); System.out.println("Inside while Loop"); order.setOrderId(rs.getInt("orderId")); order.setEmail(rs.getString("email")); order.setOrderAmount(rs.getDouble("orderAmount")); order.setOrderNumber(rs.getString("orderNumber")); order.setOrderDate(rs.getDate("orderDate")); order.setFirstname(rs.getString("firstname")); order.setLastname(rs.getString("lastname")); orders.add(order); System.out.println("Inside dao email is " + order.getEmail()); } } catch (SQLException e) { e.printStackTrace(); } finally { ConnectionManager.closeConnection(connection); } return orders; } } <file_sep>package com.mindteck.controller; import java.io.*; import java.sql.*; import org.json.*; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.*; import com.mindteck.dao.UserDAO; import com.mindteck.model.User; import com.mindteck.service.UserService; import com.mindteck.service.UserServiceImpl; public class UserController extends HttpServlet { private static final long serialVersionUID = 1L; public UserController() { super(); } /* * This function receives input from the user using the doGet Method. It * gets the user action The actions are delete, edit and listUser. If the * action is delete, the user is deleted by username. If the action is edit * the function gets the user by id. The request attribute is set to update * and the request is forwarded to User.jsp */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserService service = new UserServiceImpl(); String action = request.getParameter("action"); if (action.equalsIgnoreCase("delete")) { String userId = request.getParameter("username"); try { service.removeUser(userId); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { request.setAttribute("users", service.returnAllUsers()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } RequestDispatcher req = request.getRequestDispatcher("listUser.jsp"); req.forward(request, response); } else if (action.equalsIgnoreCase("edit")) { User user; try { user = service.returnUserById(request.getParameter("userId")); request.setAttribute("user", user); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("label", "Update User"); RequestDispatcher req = request.getRequestDispatcher("User.jsp"); req.forward(request, response); } else if (action.equalsIgnoreCase("listUser")) { try { request.setAttribute("users", service.returnAllUsers()); } catch (Exception e) { e.printStackTrace(); } RequestDispatcher req = request.getRequestDispatcher("listUser.jsp"); req.forward(request, response); } else { String userId = request.getParameter("userId"); request.setAttribute("label", "Add User"); RequestDispatcher req = request.getRequestDispatcher("user.jsp"); req.forward(request, response); } } /* * This function gets requests sent from register.jsp and login.jsp and * processes them. It checks if the username is already in use before * registering user. If the username is available it adds registration * information to the users table and sends user back to registrer.jsp. * Otherwise, an error message is sent back to the user. If the user is * logged in, the session attribute is set to loggedIn, otherwise if the * username is invalid, an error message is given. */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { UserService service = new UserServiceImpl(); User user = new User(); PrintWriter out = response.getWriter(); String action = request.getParameter("action"); System.out.println(action); HttpSession session = request.getSession(); if (action.equals("register")) { try { String pass = request.getParameter("pass"); String fname = request.getParameter("firstName"); String lname = request.getParameter("lastName"); String email = request.getParameter("email"); String userid = request.getParameter("username"); System.out.println(userid); if (pass == null || fname == null || email == null || lname == null || userid == null || pass.equals("") || fname.equals("") || email.equals("") || lname.equals("") || userid.equals("")) { request.setAttribute("message", "Please provide valid data"); RequestDispatcher req = request.getRequestDispatcher("register.jsp"); req.forward(request, response); } else { user.setFirstName(fname); user.setLastName(lname); user.setEmail(email); user.setPassword(<PASSWORD>); user.setUserid(userid); if (!(service.isLoggedInOrNot(userid, email))) { service.insertUser(user); RequestDispatcher view = request.getRequestDispatcher("registrationConfirm.jsp"); request.setAttribute("users", service.returnAllUsers()); view.forward(request, response); } else { request.setAttribute("message", "Username already exists. Choose a different username or email."); RequestDispatcher req = request.getRequestDispatcher("register.jsp"); req.include(request, response); } } } catch (Exception e) { e.printStackTrace(); } } else if (action.equals("login")) { System.out.println("action is login."); String pass = request.getParameter("pass"); String userid = request.getParameter("username"); System.out.println("Inside logged in username is " + userid); session.setAttribute("username", userid); session.setAttribute("pass", pass); try { if (userid == null || pass == null || userid.equals("") || pass.equals("")) { request.setAttribute("message", "Please enter a user name or password"); RequestDispatcher req = request.getRequestDispatcher("login.jsp"); req.forward(request, response); } else { if (service.authenticateUser(userid, pass) == true) { session.setAttribute("loggedIn", request.getParameter("username")); session.setAttribute("users", service.returnAllUsers()); RequestDispatcher req = request.getRequestDispatcher("home.jsp"); req.forward(request, response); } else { request.setAttribute("message", "Invalid username or password"); RequestDispatcher rd = request.getRequestDispatcher("login.jsp"); rd.include(request, response); } } } catch (Exception e) { e.printStackTrace(); } } } } <file_sep>package com.mindteck.service; import java.util.List; import com.mindteck.dao.OrderDAO; import com.mindteck.dao.OrderDAOImpl; import com.mindteck.model.CartItem; import com.mindteck.model.Order; import com.mindteck.model.User; public class OrderServiceImpl implements OrderService { OrderDAO dao = new OrderDAOImpl(); public void insertOrderToTable(Order order) { dao.addOrder(order); } public List<CartItem> retrieveItemsInCart(String username) { return dao.getCartItems(username); } public User findUserByUserId(String username) { return dao.getUserByUsername(username); } public void orderNow(Order order) { dao.placeOrder(order); } public void deleteAllFromCart(String username) { dao.clearCart(username); } public List<Order> displayOrder(String username) { return dao.viewOrder(username); } public List<Order> LinkOrderByEmail(String email) { return dao.getOrderByEmail(email); } } <file_sep>package com.mindteck.dao; import java.util.List; import com.mindteck.model.CartItem; import com.mindteck.model.Order; import com.mindteck.model.User; public interface OrderDAO { public void addOrder(Order order); public List<CartItem> getCartItems(String username); public User getUserByUsername(String username); public void placeOrder(Order order); public void clearCart(String username); public List<Order> viewOrder(String username); public List<Order> getOrderByEmail(String email); } <file_sep>package com.mindteck.service; import java.util.List; import com.mindteck.model.CartItem; import com.mindteck.model.Order; import com.mindteck.model.User; public interface OrderService { public void insertOrderToTable(Order order); public List<CartItem> retrieveItemsInCart(String username); public User findUserByUserId(String username); public void orderNow(Order order); public void deleteAllFromCart(String username); public List<Order> displayOrder(String username); public List<Order> LinkOrderByEmail(String email); }
fb0917ffdea4e315b4a5d0b706dc94db86438d5b
[ "Java", "INI" ]
11
INI
Bkzbroscius/Java-Online-Shopping-Cart
e68421694f002c4c01b6a0719aa525ebdd321070
c8f6bffc8f018672b026e5db1ab220be2b845e9a
refs/heads/master
<repo_name>Amphiprion/vers-de-terre<file_sep>/README.md # Vers de terre<file_sep>/src/ui.R # Author: Amphiprion library(shiny) ; library(ggplot2) shinyUI(fluidPage( titlePanel(title="evolution de la biomasse des vers de terre sous different traitement"), sidebarLayout( sidebarPanel( selectInput("varX","Variable X",choices=c("time"=4)), selectInput("varY","Variable Y",choices=c("bm"=5)), selectInput("Precision","precision",choices=c("all_publie","by_publie")), selectInput("Species","species",choices=unique(my_data$species.raw)), selectInput("Publie","publie",choices="",selected = ""), selectInput("Figure","figure",choices="",selected = ""), numericInput("Min","min",0)), mainPanel(tabsetPanel(type="tab", tabPanel("plot",plotOutput("plot1")), tabPanel("data_publie",tableOutput("data_publie")), tabPanel("summary_publie",verbatimTextOutput("summary_publie")), tabPanel("data",tableOutput("data")) ),"Pour Lofs-Holmin_1980, bien penser a supprimer son nom de 'publie' avant de le reselectionner, sinon le changement d'espece ne fonctionne pas" ) ) )) <file_sep>/src/global.R # Author: Amphiprion library(shiny) ; library(ggplot2) ; library(shinyapps) ; library(nlme) ; library(r2excel) # setwd("/Users/USER/Desktop/stage/stage_Paris/analyse_growth_tox_R/Tox_Mathieu/vers_de_terre/") file="tableau_growth_Jerome.xls" # ex=read.xlsx(file,sheetIndex = 1,header=TRUE) my_data=ex my_data$species.raw=as.character(my_data$species.raw) my_data$auteur=as.character(my_data$auteur) my_data$figure=as.character(my_data$figure) gompertz = function(x,Min=0,Asym=0,xmid=0,scal=0){ x$treatment=factor(x$treatment, levels=unique(x$treatment)) ggplot(x,aes(x$time,x$bm,col=x$treatment))+ geom_point()+theme_bw()+ geom_smooth(method="nls", method.args=list(formula=y~Min+Asym*exp(-exp(-scal*(x-xmid))), start=list(Asym=Asym,xmid=xmid,scal=scal)),se=F,fullrange=F)+ xlab("time (day)")+ylab("biomasse (mg)")+facet_grid(~treatment)+ theme(legend.position="none")+ scale_color_manual(values=c("black","red", "blue", "green","orange","purple","brown")) } logistique = function(x,Min=0,Asym=0,xmid=0,scal=0){ x$treatment=factor(x$treatment, levels=unique(x$treatment)) ggplot(x,aes(x$time,x$bm,col=x$treatment))+ geom_point()+theme_bw()+ geom_smooth(method="nls", method.args=list(formula=y~Min+(Asym-Min)/(1+exp((xmid-x)/scal)), start=list(Asym=Asym,xmid=xmid,scal=scal)),se=F,fullrange=F)+ xlab("time (day)")+ylab("biomasse (mg)")+facet_grid(~treatment)+ theme(legend.position="none")+ scale_color_manual(values=c("black","red", "blue", "green","orange","purple","brown")) } brain_cousen = function(x,Min=0,Asym=0,xmid=0,scal=0,horm=0){ x$time2=abs(x$time-max(x$time)) x$treatment=factor(x$treatment, levels=unique(x$treatment)) ggplot(x,aes(x$time2,x$bm,col=x$treatment))+ geom_point()+theme_bw() + geom_smooth(method="nls", method.args=list(formula=y~Min+(Asym-Min+horm*x)/(1+exp(scal*log(x/xmid))), start=list(Asym=Asym,horm=horm,scal=scal,xmid=xmid)),se=F,fullrange=F)+ xlab("time (day) [reverse values]")+ylab("biomasse (mg)")+ ggtitle("la figure est inverse par rapport a la realite")+facet_grid(~treatment)+ theme(legend.position="none")+ scale_color_manual(values=c("black","red", "blue", "green","orange","purple","brown")) } brain_cousen_sans_horm = function(x,Min=0,Asym=0,xmid=0,scal=0){ x$time2=abs(x$time-max(x$time)) x$treatment=factor(x$treatment, levels=unique(x$treatment)) ggplot(x,aes(x$time2,x$bm,col=x$treatment))+ geom_point()+theme_bw()+ geom_smooth(method="nls", method.args=list(formula=y~Min+(Asym-Min)/(1+exp(scal*log(x/xmid))), start=list(Asym=Asym,scal=scal,xmid=xmid)),se=F,fullrange=F)+ xlab("time (day) [reverse values]")+ylab("biomasse (mg)") + ggtitle("la figure est inverse par rapport a la realite")+facet_grid(~treatment)+ theme(legend.position="none")+ scale_color_manual(values=c("black","red", "blue", "green","orange","purple","brown")) } double_brain_cousen = function(x,Min=0,Asym=0,xmid=0,scal=0,horm=0,xmid2=0){ x$time2=abs(x$time-max(x$time)) x$treatment=factor(x$treatment, levels=unique(x$treatment)) ggplot(x,aes(x$time2,x$bm,col=x$treatment))+ geom_point()+theme_bw()+ geom_smooth(method="nls", method.args=list(formula=y~Min+(Asym-Min)/(1+exp(scal*log(x/xmid)))+ (horm*x)/(1+exp((xmid2-x)/-scal)), start=list(Asym=Asym,horm=horm,scal=scal, xmid=xmid,xmid2=xmid2)),se=F,fullrange=F)+ xlab("time (day) [reverse values]")+ylab("biomasse (mg)") + ggtitle("la figure est inverse par rapport a la realite")+facet_grid(~treatment)+ theme(legend.position="none")+ scale_color_manual(values=c("black","red", "blue", "green","orange","purple","brown")) } linear = function(x){ x$time2=abs(x$time-max(x$time)) x$treatment=factor(x$treatment, levels=unique(x$treatment)) ggplot(x,aes(x$time2,x$bm,col=x$treatment))+ geom_point()+theme_bw()+ geom_smooth(method="lm",se=T,fullrange=F) + xlab("time (day) [reverse values]")+ylab("biomasse (mg)")+ ggtitle("la figure est inverse par rapport a la realite")+facet_grid(~treatment)+ theme(legend.position="none")+ scale_color_manual(values=c("black","red", "blue", "green","orange","purple","brown")) } non_analyse = function(text="text",size=5){ ggplot()+geom_blank(aes(1,1))+ theme(plot.background = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), panel.background = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.x = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(), axis.line = element_blank() )+annotate(geom="text",x=1,y=1,label=text,size=size,col="red") } <file_sep>/src/server.R # Author: Amphiprion library(shiny) ; library(ggplot2) ; library(shinyapps) ; library(nlme) function(session,input,output){ observeEvent(input$Species, updateSelectInput(session,"Publie","publie", choices = my_data$auteur[my_data$species.raw==input$Species])) observeEvent(input$Publie, updateSelectInput(session,"Figure","figure", choices = my_data$figure[my_data$species.raw==input$Species & my_data$auteur==input$Publie ])) my_data2 <- reactive({ my_data=my_data[my_data$auteur==input$Publie & my_data$figure==input$Figure,] }) output$plot1 <- renderPlot({ axeX=as.numeric(input$varX) axeY=as.numeric(input$varY) selec=input$Precision }) output$data <- renderTable({ my_data }) output$summary_publie <- renderPrint({ summary(my_data2()) }) output$data_publie <- renderTable({ my_data2() }) output$plot1 <- renderPlot({ colmX=as.numeric(input$varX) colmY=as.numeric(input$varY) autor=input$Publie figure=input$Figure species=input$Species select=input$Precision min=input$Min if(select=="by_publie"){ if(species=="Aporrectodea.caliginosa" & autor=="Vercesi_2006" | species=="Aporrectodea.longa" | autor=="Lofs-Holmin_1980" & figure=="figure4"){ linear(my_data2()) }else{ if(species=="Dendrobaena.octaedra" & autor=="Addison_1995" & figure=="figure1" | species=="Dendrobaena.octaedra" & autor=="Addison_1995" & figure=="figure3"| species=="Dendrobaena.octaedra" & autor=="Fisker_2011"){ brain_cousen(my_data2(),min,400,70,5,2) }else{ if(species=="Dendrobaena.octaedra" & autor!="Fisker_2011"){ brain_cousen_sans_horm(my_data2(),min,400,70,5) }else{ if(species=="drawida.willsi"){ logistique(my_data2(),min,20,45,5) }else{ if((autor=="Lofs-Holmin_1980" & figure=="figure5")){ gompertz(my_data2(),min,250,35,0.05) }else{ if(species=="Eisenia.andrei" & autor=="Van-gestal_1991"){ brain_cousen_sans_horm(my_data2(),min,500,30,2) }else{ if(autor=="Brunninger_1994" & figure=="figure1"){ double_brain_cousen(my_data2(),min,480,200,24,1,400) }else{ if(autor=="Brunninger_1994" & figure=="figure2"){ brain_cousen(my_data2(),min,600,200,24,1) }else{ if(species=="Eisenia.fetida" & autor=="Fernandez_Gomez_2011" & figure=="figure1"){ brain_cousen_sans_horm(my_data2(),min,500,40,3) }else{ if(species=="Eisenia.fetida" & autor=="Fernandez_Gomez_2011" & figure=="figure2"){ brain_cousen_sans_horm(my_data2()[-c(12:14),],min,700,60,5)+ ggtitle("la figure est inverse par rapport a la realite ;\nles 3 derniers points de la figure 1 sont supprimes") }else{ if(species=="Eisenia.fetida" & autor!="Helling_2000"){ brain_cousen_sans_horm(my_data2(),min,500,40,3) }else{ if(species=="Eisenia.fetida" & autor=="Helling_2000"){ brain_cousen(my_data2(),min,500,40,5,1) }else{ if(species=="Lumbricus.rubellus"){ gompertz(my_data2(),min,1500,100,0.01) }else{ if(species=="Pontoscolex.corethrurus"){ brain_cousen(my_data2(),min,1000,100,5,10) }else{ if(species=="Perionyx.sansibaricus"){ logistique(my_data2(),min,60,15,15) }else{ if(autor=="Lofs-Holmin_1980" & figure=="figure3"){ logistique(my_data2(),min,350,35,5) }else{ if(species=="Lumbricus.terrestris"){ logistique(my_data2(),min ,200,8,5) }else{ if(species=="Allolobophora.caliginosa"){ logistique(my_data2(),min ,500,70,5) }else{ if(autor=="Springett_1992"){ non_analyse("donnees non analyse car curieuse",5) } } } } } } } } } } } } } } } } } } } }else{ggplot(my_data,aes(my_data$time,my_data$bm,col=my_data$treatment))+ geom_point()+theme_bw()+theme(legend.position='none')+ggtitle("all data")} } ) }
7c3049d35d38cd1baae2988094ab12fe11bdd4d9
[ "Markdown", "R" ]
4
Markdown
Amphiprion/vers-de-terre
b7a1ba26c0779645fff08f1a98c4ef58f98dd376
0690e6e2fb5287a76ae7de81f1701de76801c587
refs/heads/master
<repo_name>bogatuadrian/WebDevRubyTDD<file_sep>/CGOL/cgol.rb require 'set' class Cell < Struct.new(:x, :y) def +(cell) Cell.new(self[:x] + cell[:x], self[:y] + cell[:y]) end end class Directions def Directions::getDirections() directions = Array.new (-1..1).each do |i| (-1..1).each do |j| directions << Cell.new(i, j) unless i == 0 && j == 0 end end directions end end def get_neighbours(cell) directions = Directions::getDirections res = Array.new directions.each do |d| neighbour = cell + d res << neighbour if (yield neighbour) end res end =begin def alive_neighbours(cell, alive_cells) directions = Directions::getDirections res = Array.new directions.each do |d| neighbour = cell + d res << neighbour if alive_cells[neighbour] == true end res end =end def direct_surroundings_of(alive_cells) neighbours = Array.new alive_cells.keys.each do |cell| neighbours = neighbours + (get_neighbours(cell) { |k| alive_cells[k] != true }) end neighbours end def dead_cells_that_become_alive(alive_cells) dead_cells = direct_surroundings_of(alive_cells) new_alive_cells = Array.new dead_cells.each do |cell| neighbours = get_neighbours(cell) { |k| alive_cells[k] == true } new_alive_cells << cell if neighbours.count == 3 end new_alive_cells end def alive_cells_that_stay_alive(alive_cells) new_alive_cells = Array.new alive_cells.each do |cell, v| neighbours = get_neighbours(cell) { |k| alive_cells[k] == true } new_alive_cells << cell if neighbours.count == 2 || neighbours.count == 3 end new_alive_cells end def evolve_universe(seed) return [].to_set if seed == [].to_set alive_cells = Hash.new seed.each do |e| alive_cells[e] = true end =begin res = Array.new new_alive_cells.each do |k, v| res << k if new_alive_cells[k] == true end =end res = alive_cells_that_stay_alive(alive_cells) + dead_cells_that_become_alive(alive_cells) res.to_set end <file_sep>/PascalsTriangle/pascalstriangle.rb def compute_row(n) return nil unless n.is_a? Integer return [] if n < 1 return [1] if n == 1 curr = [] n.times do result = [] curr.inject(0) do |acc, x| result << (x + acc) x end result << 1 curr = result end curr end __END__ 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 <file_sep>/AbstractPoker/abstractpoker.rb MAX_BOUND = 1000 class Fixnum def of_a_kind(poker_hand) # returns how many self-tuples are in a hand counter = {} poker_hand.each do |x| if counter[x] == nil counter[x] = 1 else counter[x] += 1 end end counter.select { |k, v| v == self }.count end end def straight(poker_hand) sorted_poker_hand = poker_hand.sort count = 0 max_count = 0 (sorted_poker_hand.count - 1).times do |i| count = 0 unless sorted_poker_hand[i] + 1 == sorted_poker_hand[i + 1] count += 1 if sorted_poker_hand[i] + 1 == sorted_poker_hand[i + 1] if count > max_count max_count = count end end max_count + 1 end def is_high_card?(poker_hand) count = straight(poker_hand) count == 4 || count == 3 end def straight?(poker_hand) straight(poker_hand) == 5 end def one_pair?(poker_hand) 2.of_a_kind(poker_hand) == 1 end def two_pairs?(poker_hand) 2.of_a_kind(poker_hand) == 2 end def three_of_a_kind?(poker_hand) 3.of_a_kind(poker_hand) == 1 end def four_of_a_kind?(poker_hand) 4.of_a_kind(poker_hand) == 1 end def full_house?(poker_hand) one_pair?(poker_hand) && three_of_a_kind?(poker_hand) end def classify_poker_hand(poker_hand) return :not_a_ruby_array unless poker_hand.is_a? Array return :too_many_or_too_few_cards unless poker_hand.count == 5 return :at_least_one_card_is_not_an_integer unless poker_hand.select { |x| !x.is_a?(Integer) }.empty? return :at_least_one_card_is_out_of_bounds unless poker_hand.select { |x| x > MAX_BOUND }.empty? return :impossible_hand if 5.of_a_kind(poker_hand) > 0 return :four_of_a_kind if four_of_a_kind?(poker_hand) return :full_house if full_house?(poker_hand) return :straight if straight?(poker_hand) return :three_of_a_kind if three_of_a_kind?(poker_hand) return :two_pairs if two_pairs?(poker_hand) return :one_pair if one_pair?(poker_hand) return :high_card if is_high_card?(poker_hand) return :valid_but_nothing_special end
7b9355cca64ba6f3d136bf23df8bf0a19310c592
[ "Ruby" ]
3
Ruby
bogatuadrian/WebDevRubyTDD
6e932b4ba335be625298bd789b867a9a22f1e9b2
d97fdb75b56c29eea570a92d9e0e6569c01eeaab
refs/heads/master
<repo_name>amilamadhushanka/englishbuddy<file_sep>/flask/test.py __author__ = '<NAME>' import nltk def find_tence(sentence): tagged_sent = nltk.pos_tag(sentence.split()) print tagged_sent if [word for word, pos in tagged_sent if pos == 'NNS']: noun_plural = [word for word, pos in tagged_sent if pos == 'NNS'] print 'noun_plural : ' + noun_plural[0] if noun_plural[0].find("'s") and noun_plural[0].find("'s") > 0: tence = "3rd person singular present" return tence elif [word for word, pos in tagged_sent if pos == 'VBZ']: tence = "3rd person singular present" return tence elif [word for word, pos in tagged_sent if pos == 'VBP']: tence = "singular present" return tence elif [word for word, pos in tagged_sent if pos == 'VBN']: tence = "past participlet" return tence elif [word for word, pos in tagged_sent if pos == 'VBG']: tence = "present participle" return tence elif [word for word, pos in tagged_sent if pos == 'VBD']: tence = "past tense" return tence elif [word for word, pos in tagged_sent if pos == 'VB']: tence = "base form" return tence return "null" def check_tence(question, answer): question = find_tence(question) answer = find_tence(answer) if question == answer: return True return False <file_sep>/flask/check_tense.py __author__ = '<NAME>' import nltk def find_tense(sentence): tense = 'null' array = [] tagged_sent = nltk.pos_tag(sentence.split()) print tagged_sent if [word for word, pos in tagged_sent if pos == 'NNS']: array = ([word for word, pos in tagged_sent if pos == 'NNS']) for word in array: if word.find("'s") and word.find("'s") > 0: tense = "3rd person singular present" return tense if [word for word, pos in tagged_sent if pos == 'NNP']: array = ([word for word, pos in tagged_sent if pos == 'NNP']) for word in array: if (word.find("'s") and word.find("'s") > 0) or word.find("'ll") and word.find("'ll") > 0: tense = "3rd person singular present" return tense if [word for word, pos in tagged_sent if pos == 'VBZ']: tense = "3rd person singular present" elif [word for word, pos in tagged_sent if pos == 'VBP'] or [word for word, pos in tagged_sent if pos == 'MD']: tense = "singular present" elif [word for word, pos in tagged_sent if pos == 'VBN']: tense = "past participlet" elif [word for word, pos in tagged_sent if pos == 'VBG']: tense = "present participle" elif [word for word, pos in tagged_sent if pos == 'VBD']: tense = "past tense" elif [word for word, pos in tagged_sent if pos == 'VB']: tense = "base form" return tense def check_tense(question, answer): question = find_tense(question) answer = find_tense(answer) if question == answer: return True return False # print check_tense("Have you money to buy this?", "She have two thousand rupees. I hope that, it'll be enough.") <file_sep>/flask/routes.py from random import shuffle import random import json import os import conjunctions as ConjunctionClass import coordinatingConjunctions as CoordinatingConjunctionClass import dialog as DialogClass import ginger_python2_new as ginger import ginger_python2 as Grammar import check_tense as TenseClass import socket import keywords import en import webbrowser from threading import Thread import pyttsx from nltk.corpus import brown from ansi2html import Ansi2HTMLConverter from flask import Flask, render_template, url_for, redirect from flask import request, flash, session, escape from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.utils import secure_filename from pymsgbox import * from flask.ext.mail import Mail, Message from nltk.tokenize import RegexpTokenizer import MySQLdb from MySQLdb import escape_string import numpy import nltk from nltk import pos_tag, word_tokenize from nltk.tag import pos_tag from nltk.stem import WordNetLemmatizer from nltk.tokenize import sent_tokenize import notice import invitation import note from flask import jsonify app = Flask(__name__) app.config.update(dict( DEBUG=True, MAIL_SERVER='smtp.gmail.com', MAIL_PORT=587, MAIL_USE_TLS=True, MAIL_USE_SSL=False, MAIL_USERNAME='<EMAIL>', MAIL_PASSWORD='<PASSWORD>', )) mail = Mail(app) app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # Set secret key app.config['SECRET_KEY'] = 'F34TF$($e34D'; # This is the path to the upload directory app.config['UPLOAD_FOLDER'] = 'static/uploads/' # These are the extension that we are accepting to be uploaded app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg', 'gif']) # Open database connection db = MySQLdb.connect("localhost", "root", "00000444", "english_buddy") @app.route('/') def index(): if 'username' in session: return 'Logged in as %s' % escape(session['username']) return render_template('login.html') # ------------------------------------- Sign up ----------------------------------------------- # # Register ## @app.route('/register') def register(): return render_template('register.html') # # Register new user ## @app.route('/save', methods=['POST']) def register_user(): if request.method == 'POST': fName = request.form['txtFirstName'] lName = request.form['txtLastName'] email = request.form['txtEmail'] password = request.form['txtPassword'] confirm_password = request.form['txtConPassword'] phone = request.form['txtPhone'] role = request.form['listRole'] if role != 'Parent': school = request.form['txtSchool'] sql = """SELECT email FROM users where email=%s""" try: cursor = db.cursor() # Execute the SQL command cursor.execute(sql, [email]) # fetch a single row using fetchone() method. data = cursor.fetchone() if data: error = 'You have been alreay registered!' flash(error) return render_template('register.html', error=error) else: hashPassword = generate_password_hash(password) #create password hash cursor = db.cursor() if role != 'Parent': sql = """INSERT INTO users (email,fName,lName,password,phone,school,role,placement_test) VALUES(%s,%s,%s,%s,%s,%s,%s,'false')""" else: sql = """INSERT INTO users (email,fName,lName,password,phone,role,placement_test) VALUES(%s,%s,%s,%s,%s,%s,'false')""" try: # Execute the SQL command if role != 'Parent': cursor.execute(sql, [email, fName, lName, hashPassword, phone, school, role]) else: cursor.execute(sql, [email, fName, lName, hashPassword, phone, role]) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() # disconnect from server db.close() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() alert(text='User Registered Successfully !', title='English Buddy', button='OK') if check_internet_connection(): ## Send email ## msg = Message('English Buddy', sender="<EMAIL>") msg.recipients = [email] msg.html = "<body bgcolor='#DCEEFC'><center>===============================<br><br><b>Hi,</b> <br><b>Welcome to English Buddy !</b><br><br>Sign in to get started:<br><br><font color='blue'>User name: " + email + " </font><br><br>Have fun!<br>English Buddy Team<br><br><a href='http://127.0.0.1:5000/'>Sign in Now</a><br><br>===============================<br></center></body>" mail.send(msg) #redirect to login page return render_template('login.html') # ---------------------------------- Sign in ----------------------------------------------- ## login ## @app.route('/login', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': userName = request.form['txtEmail'] password = request.form['txtPassword'] # Open database connection db = MySQLdb.connect("localhost", "root", "00000444", "english_buddy") cursor = db.cursor() sql = """SELECT password,placement_test,role,fName,image FROM users where email=%s""" try: # Execute the SQL command cursor.execute(sql, [userName]) # fetch a single row using fetchone() method. data = cursor.fetchall() for row in data: dbPassword = row[0] placementTestStatus = row[1] role = row[2] fName = row[3] image = row[4] #print(placementTestStatus) userCheck = check_password_hash(dbPassword, password) if userCheck: session['username'] = userName session['role'] = role session['profilePic'] = image session['level'] = placementTestStatus session['fName'] = fName #login_user(data) data = {'username': userName, 'role': role, 'level': placementTestStatus, 'fName': fName} query = getSenderData(userName) count = getCount(userName) if session['role'] == "Teacher": # Get student subscribe request count count=student_subscribe_request_count() # Get student subscribe request details query=display_student_subscribe_request_details() return render_template('home_teacher.html',query=query,count=count) if session['role'] == "Parent": AcceptedList = getAcceptedData(userName) return render_template('home_parent.html', List=AcceptedList) if session['role'] == "Student": if placementTestStatus == "false": return render_template('home_pt.html', data=data) elif placementTestStatus == "Elementary": return render_template('home_1.html', data=data, query=query, count=count) elif placementTestStatus == "Preliminary": return render_template('home_2.html', data=data, query=query, count=count) elif session['level'] == "Intermediate": return render_template('home_3.html', data=data, query=query, count=count) elif session['level'] == "Advanced": return render_template('home_4.html', data=data, query=query, count=count) else: flash('Invalid Username or Password !') # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() flash('Invalid Username or Password !') return render_template('login.html', error=error,) ## Get student subscribe request count ## def student_subscribe_request_count(): cursor = db.cursor() sql = """SELECT COUNT(status) as count FROM subscribe_teacher WHERE teacher=%s AND status='pending'""" try: # Execute the SQL command cursor.execute(sql, [session['username']]) # fetch a single row using fetchone() method. data = cursor.fetchall() for row in data: requests = row[0] session['subscribe_requests'] = requests except: # Rollback in case there is any error db.rollback() return data ## Get student subscribe request details ## def display_student_subscribe_request_details(): cursor = db.cursor() sql = """SELECT u.fName,u.lName,u.school,u.image,u.placement_test,s.status,s.student FROM users u, subscribe_teacher s WHERE u.email=s.student AND s.status='pending' AND s.teacher=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username']]) # fetch rows using fetchall() method. result = cursor.fetchall() except: # Rollback in case there is any error db.rollback() return result # ---------------------------------------- log out --------------------------------------------- ## logout ## @app.route('/logout') def logout(): session.clear() # del session['username'] # del session['profilePic'] # del session['level'] # del session['fName'] # # if session['role'] == 'Teacher': # del session['subscribe_requests'] # # del session['role'] return redirect(url_for('login')) # -------------------------------------------- Reset Password ----------------------------------------- # ## Forgot password ## @app.route('/view_forgot_password', methods=['GET', 'POST']) def view_forgot_password(): return render_template('forgot_password.html') ## Forgot password ## @app.route('/forgot_password', methods=['GET', 'POST']) def forgot_password(): if request.method == 'POST': email = request.form['txtEmail'] status = check_email_exists(email) if status: send_reset_password_email(email, status) data = {'email': email} return render_template('forgot_password_success.html', data=data) return redirect(url_for('login')) ## Check email exists ## def check_email_exists(email): cursor = db.cursor() sql = """SELECT fName FROM users where email=%s""" try: # Execute the SQL command cursor.execute(sql, [email]) # fetch a single row using fetchone() method. data = cursor.fetchall() for row in data: fName = row[0] if data: return fName except: # Rollback in case there is any error db.rollback() return False ## Send reset password email ## def send_reset_password_email(email, firstname): email_code = generate_password_hash(app.secret_key + firstname) ## Send email ## msg = Message('English Buddy - Reset Password', sender="<EMAIL>") msg.recipients = [email] msg.html = "<body bgcolor='#DCEEFC'><center>===============================<br><br><b><b>Dear, " + firstname + "</b><br><br><p>Please <strong><a href='http://127.0.0.1:5000/reset_password_form/?email=" + email + "&email_code=" + email_code + "'> click here</a></strong>&nbsp;to reset your password.</p><p>Thank you!</p><br>English Buddy Team<br><br><a href='http://127.0.0.1:5000/'>Sign in Now</a><br><br>===============================<br></center></body>" mail.send(msg) ## Reset password ## @app.route('/reset_password_form/', methods=['GET']) def reset_password_form(): email = request.args.get('email') email_code = request.args.get('email_code') print "send emial_code: " + email_code verified = verify_reset_password_code(email, email_code) if verified: email_hash = email + email_code data = {'email_hash': email_hash, 'email_code': email_code, 'email': email} return render_template('reset_password.html', data=data) return redirect(url_for('login')) ## Verify reset password ## def verify_reset_password_code(email, code): cursor = db.cursor() sql = """SELECT fName FROM users where email=%s""" try: # Execute the SQL command cursor.execute(sql, [email]) # fetch a single row using fetchone() method. data = cursor.fetchall() for row in data: fName = row[0] print "fName:" + fName if data: generated_code = app.secret_key + fName send_code = check_password_hash(code, generated_code) if send_code: return True else: return False except: # Rollback in case there is any error db.rollback() return False ## Update New Password ## @app.route('/update_password', methods=['POST']) def update_password(): if request.method == 'POST': email = request.form['txtEmail'] password = request.form['txtNew<PASSWORD>'] confirm_password = request.form['txtComfirmPassword'] if password != confirm_password: error = "Password didn't match" flash(error) return render_template('reset_password.html', error=error) hashPassword = generate_password_hash(password) #create password hash cursor = db.cursor() sql = """UPDATE users SET password=%s WHERE email=%s""" try: # Execute the SQL command cursor.execute(sql, [hashPassword, email]) # Commit your changes in the database db.commit() alert(text='Password Updated Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return redirect(url_for('login')) # ------------------------------------------- User Profile -------------------------------------------- # ## View profile details ## @app.route('/view_profile') def view_profile(): userName = session['username'] query = "" cursor = db.cursor() sql = """SELECT * FROM users where email=%s""" try: # Execute the SQL command cursor.execute(sql, [userName]) # fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() if session['role']=='Teacher': # Get student subscribe request count count=student_subscribe_request_count() # Get student subscribe request details query1=display_student_subscribe_request_details() return render_template('profile.html', data=query, query=query1, count=count) else: return render_template('profile.html', data=query) ## pass profile data to the modal ## @app.route('/user_info', methods=['GET', 'POST']) def user_info(): username = session['username'] cursor = db.cursor() sql = """SELECT * FROM users where email=%s""" try: # Execute the SQL command cursor.execute(sql, [username]) # fetch a single row using fetchone() method. query = cursor.fetchall() for row in query: fname = row[1] lname = row[2] phone = row[4] school = row[5] role = row[7] except: db.rollback() return json.dumps(dict(fname=fname, lname=lname, phone=phone, school=school)) ## edit profile data ## @app.route('/edit_profile', methods=['POST']) def edit_profile(): fname = request.form['fname'] lname = request.form['lname'] phone = request.form['phone'] id = request.form['id'] cursor = db.cursor() sql = """update users set fName=%s,lName=%s,phone=%s where email=%s""" try: # Execute the SQL command cursor.execute(sql, [fname, lname, phone, id]) # Commit your changes in the database db.commit() #flash('Successfully Updated !') except: # Rollback in case there is any error db.rollback() return redirect(url_for('view_profile')) # For a given file, return whether it's an allowed type or not def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS'] ## Update profile picture ## @app.route('/upload', methods=['POST']) def upload(): # Get the name of the uploaded file file = request.files['file'] # Check if the file is one of the allowed types/extensions if file and allowed_file(file.filename): # Make the filename safe, remove unsupported chars filename = secure_filename(file.filename) # Move the file form the temporal folder to # the upload folder we setup file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) # Redirect the user to the uploaded_file route, which # will basicaly show on the browser the uploaded file cursor = db.cursor() sql = """update users set image=%s where email=%s""" try: # Execute the SQL command cursor.execute(sql, [filename, session['username']]) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return redirect(url_for('view_profile')) # ------------------------------------- home --------------------------------------------------- ## Home ## @app.route('/home') def home(): if session['role'] == "Teacher": # Get student subscribe request count count=student_subscribe_request_count() # Get student subscribe request details query=display_student_subscribe_request_details() return render_template('home_teacher.html',query=query, count=count) elif session['role'] == "Parent": AcceptedList = getAcceptedData(session['username']) return render_template("home_parent.html", List=AcceptedList) elif session['level'] == "false": return render_template('home_pt.html') elif session['level'] == "Elementary": query = getSenderData(session['username']) count = getCount(session['username']) return render_template('home_1.html', query=query, count=count) elif session['level'] == "Preliminary": query = getSenderData(session['username']) count = getCount(session['username']) return render_template('home_2.html', query=query, count=count) elif session['level'] == "Intermediate": query = getSenderData(session['username']) count = getCount(session['username']) return render_template('home_3.html', query=query, count=count) elif session['level'] == "Advanced": query = getSenderData(session['username']) count = getCount(session['username']) return render_template('home_4.html', query=query, count=count) return render_template('login.html') ## Level 1 ## @app.route('/level1') def level1(): if session['role'] == "Teacher": # Get student subscribe request count count=student_subscribe_request_count() # Get student subscribe request details query=display_student_subscribe_request_details() return render_template('home_1.html',query=query, count=count) ## Level 2 ## @app.route('/level2') def level2(): if session['role'] == "Teacher": # Get student subscribe request count count=student_subscribe_request_count() # Get student subscribe request details query=display_student_subscribe_request_details() return render_template('home_2.html',query=query, count=count) ## Level 3 ## @app.route('/level3') def level3(): if session['role'] == "Teacher": # Get student subscribe request count count=student_subscribe_request_count() # Get student subscribe request details query=display_student_subscribe_request_details() return render_template('home_3.html',query=query, count=count) ## Level 4 ## @app.route('/level4') def level4(): if session['role'] == "Teacher": # Get student subscribe request count count=student_subscribe_request_count() # Get student subscribe request details query=display_student_subscribe_request_details() return render_template('home_4.html',query=query, count=count) ## Teacher Home ## @app.route('/home_teacher') def home_teacher(): # Get student subscribe request count count=student_subscribe_request_count() # Get student subscribe request details query=display_student_subscribe_request_details() return render_template('home_teacher.html',query=query, count=count) # -------------------------------- Placement Test ----------------------------------------- ## Placement Test ## @app.route('/Placement_T') def Placement_T(): print Level_One_Questions() print Level_Two_Questions() print Level_Three_Questions() print Level_Four_Questions() return render_template('PlacementTest.html', data_level1=Level_One_Questions(),data_level2=Level_Two_Questions(),data_level3=Level_Three_Questions(),data_level4=Level_Four_Questions()) ## question level 1 , 10 quetsions in random ## def Level_One_Questions(): cursor = db.cursor() sql = """ SELECT * FROM tbl_placement_test_dc WHERE qno between 1 and 30 order by rand() limit 10""" try: # Execute the SQL command select all rows cursor.execute(escape_string(sql.decode('cp1250', 'ignore'))) # fetch rows using fetchall() method. stringSet = cursor.fetchall() except: # Rollback in case there is any error db.rollback() request.form return stringSet ## question level 2 , 10 quetsions in random ## def Level_Two_Questions(): cursor = db.cursor() sql = """ SELECT * FROM tbl_placement_test_dc WHERE qno between 31 and 60 order by rand() limit 10""" try: # Execute the SQL command select all rows cursor.execute(escape_string(sql.decode('cp1250', 'ignore'))) # fetch rows using fetchall() method. stringSet = cursor.fetchall() except: # Rollback in case there is any error db.rollback() request.form return stringSet ## question level 3 , 5 quetsions in random ## def Level_Three_Questions(): cursor = db.cursor() sql = """ SELECT * FROM tbl_placement_test_dc WHERE qno between 61 and 80 order by rand() limit 5""" try: # Execute the SQL command select all rows cursor.execute(escape_string(sql.decode('cp1250', 'ignore'))) # fetch rows using fetchall() method. stringSet = cursor.fetchall() except: # Rollback in case there is any error db.rollback() request.form return stringSet ## question level 4 , 5 quetsions in random ## def Level_Four_Questions(): cursor = db.cursor() sql = """ SELECT * FROM tbl_placement_test_dc WHERE qno between 81 and 100 order by rand() limit 5""" try: # Execute the SQL command select all rows cursor.execute(escape_string(sql.decode('cp1250', 'ignore'))) # fetch rows using fetchall() method. stringSet = cursor.fetchall() except: # Rollback in case there is any error db.rollback() request.form return stringSet ## Evaluate Placement Test @app.route('/Placement_Report', methods=['POST']) def Placement_Report(): if request.method == 'POST': count = 0; level = '' select1 = request.form['select1'] select2 = request.form['select2'] select3 = request.form['select3'] select4 = request.form['select4'] select5 = request.form['select5'] print select1 select6 = request.form['select6'] select7 = request.form['select7'] select8 = request.form['select8'] select9 = request.form['select9'] select10 = request.form['select10'] select11 = request.form['select11'] select12 = request.form['select12'] select13 = request.form['select13'] select14 = request.form['select14'] select15 = request.form['select15'] select16 = request.form['select16'] select17 = request.form['select17'] select18 = request.form['select18'] select19 = request.form['select19'] select20 = request.form['select20'] select21 = request.form['select21'] select22 = request.form['select22'] select23 = request.form['select23'] select24 = request.form['select24'] select25 = request.form['select25'] select26 = request.form['select26'] select27 = request.form['select27'] select28 = request.form['select28'] select29 = request.form['select29'] select30 = request.form['select30'] print request.form['answer1'] if select1 == request.form['answer1']: count = count + 1 if (select2 == request.form['answer2']): count = count + 1 if (select3 == request.form['answer3']): count = count + 1 if (select4 == request.form['answer4']): count = count + 1 if (select5 == request.form['answer5']): count = count + 1 if (select6 == request.form['answer6']): count = count + 1 if select7 == request.form['answer7']: count = count + 1 if (select8 == request.form['answer8']): count = count + 1 if (select9 == request.form['answer9']): count = count + 1 if (select10 == request.form['answer10']): count = count + 1 if (select11 == request.form['answer11']): count = count + 1 if (select12 == request.form['answer12']): count = count + 1 if select13 == request.form['answer13']: count = count + 1 if (select14 == request.form['answer14']): count = count + 1 if (select15 == request.form['answer15']): count = count + 1 if (select16 == request.form['answer16']): count = count + 1 if (select17 == request.form['answer17']): count = count + 1 if (select18 == request.form['answer18']): count = count + 1 if select19 == request.form['answer19']: count = count + 1 if (select20 == request.form['answer20']): count = count + 1 if (select21 == request.form['answer21']): count = count + 1 if (select22 == request.form['answer22']): count = count + 1 if (select23 == request.form['answer23']): count = count + 1 if (select24 == request.form['answer24']): count = count + 1 if (select25 == request.form['answer25']): count = count + 1 if (select26 == request.form['answer26']): count = count + 1 if (select27 == request.form['answer27']): count = count + 1 if (select28 == request.form['answer28']): count = count + 1 if (select29 == request.form['answer29']): count = count + 1 if (select30 == request.form['answer30']): count = count + 1 if count < 7: level = 'Elementary' elif 7 <= count and count < 13: level = 'Preliminary' elif 13 <= count and count < 23: level = 'Intermediate' elif 23 < count and count <= 30: level = 'Advanced' session['level'] = level data = {'count': count, 'level': level} cursor = db.cursor() sql = """update users set placement_test=%s where email=%s""" try: cursor.execute(sql, [level, session['username']]) db.commit() except: db.rollback() return render_template('Placement_Report.html', data=data) ## ------------------------------------- Add Questions Main Page ---------------------------------- ## @app.route('/view_addQuestions') def view_addQuestions(): # Get student subscribe request count count=student_subscribe_request_count() # Get student subscribe request details query=display_student_subscribe_request_details() return render_template('AddQuestions.html', query=query, count=count) ## ------------------------------ LEVEL 1 - ELEMENTARY LEVEL ----------------------------------- # ------------------------ Level 1 - Conjunctions ----------------------------------------------- ## Conjunction Questions for level 1 NEW ## @app.route('/add_conjunction_questions_new') def add_conjunction_questions_new(): return render_template('add_conjunction_questions_new.html') ## Add conjunction question for level 1 NEW ## @app.route('/save_conjunction_question_new', methods=['POST']) def save_conjunction_question_new(): if request.method == 'POST': question1 = request.form['question_1'] question2 = request.form['question_2'] question3 = request.form['question_3'] answer1 = request.form['answer_1'] answer2 = request.form['answer_2'] answer3 = request.form['answer_3'] author = session['username'] question1_exist=False question2_exist=False question3_exist=False cursor = db.cursor() sql = """SELECT * FROM conjunctions WHERE question=%s OR question=%s OR question=%s""" try: # Execute the SQL command cursor.execute(sql, [question1, question2, question3]) result = cursor.fetchall() if result: for row in result: if row[2]==question1: question1_exist=True elif row[2]==question2: question2_exist=True elif row[2]==question3: question3_exist=True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors={'question1':question1, 'question2':question2, 'question3':question3, 'answer1':answer1, 'answer2':answer2, 'answer3':answer3, 'question1Status':question1_exist, 'question2Status':question2_exist, 'question3Status':question3_exist} return render_template('add_conjunction_questions_new.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() rows = [] if question1 != '' and answer1 != '': rows.append((question1, answer1, author)) if question2 != '' and answer2 != '': rows.append((question2, answer2, author)) if question3 != '' and answer3 != '': rows.append((question3, answer3, author)) cursor = db.cursor() sql = """INSERT INTO conjunctions (level,question,answer,author) VALUES('level1',%s,%s,%s)""" try: # Execute the SQL command cursor.executemany(sql, rows) # Commit your changes in the database db.commit() #flash('Question successfully added !') alert(text='Questions Added Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return redirect(url_for('add_conjunction_questions_new')) ## Display all conjunction questions ## @app.route('/display_conjunction_questions/', methods=['GET']) def display_conjunction_questions(): level = request.args.get('level') cursor = db.cursor() if level=='level1': sql = """SELECT * FROM conjunctions WHERE author=%s AND level=%s""" elif level=='level3': sql = """SELECT * FROM level3_conjunctions WHERE author=%s AND level=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username'], level]) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() levelData={'level':level} return render_template('display_conjunction_questions.html', data=result, levelData=levelData) ## Edit level 1 conjunction questions ## @app.route('/edit_conjunction', methods=['GET', 'POST']) def edit_conjunction(): qNo = request.args.get('qNo') level = request.args.get('level') cursor = db.cursor() sql = """SELECT * FROM conjunctions where level=%s and author=%s and qNo=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [level, session['username'], qNo]) # fetch rows using fetchall() method. result = cursor.fetchall() for row in result: question = row[2] answer = row[3] except: db.rollback() return json.dumps( dict(question=question, answer=answer)) ## Save edited conjunction question for level 1 ## @app.route('/save_edited_conjunction_question', methods=['POST']) def save_edited_conjunction_question(): if request.method == 'POST': qNo = request.form['qNo'] level = request.form['level'] question = request.form['question_1'] if level=='level1': answer = request.form['answer_1'] cursor = db.cursor() if level=='level1': sql = """UPDATE conjunctions SET question=%s,answer=%s WHERE qNo=%s""" elif level=='level3': sql = """UPDATE level3_conjunctions SET question=%s WHERE qNo=%s""" try: # Execute the SQL command if level=='level1': cursor.execute(sql, [question, answer, qNo]) elif level=='level3': cursor.execute(sql, [question, qNo]) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() url='/display_conjunction_questions/?level='+level return redirect(url) ## Delete conjunction questions ## @app.route('/delete_conjunction_questions/', methods=['GET']) def delete_conjunction_questions(): qNo = request.args.get('qNo') level = request.args.get('level') cursor = db.cursor() if level=='level1': sql = """DELETE FROM conjunctions WHERE qNo=%s""" elif level=='level3': sql = """DELETE FROM level3_conjunctions WHERE qNo=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [qNo]) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() url='/display_conjunction_questions/?level='+level return redirect(url) ## Level 1 Conjunctions Activity NEW## @app.route('/level1_conjunctions_new') def level1_conjunctions_new(): array=[] cursor = db.cursor() sql = """SELECT * FROM conjunctions where level='level1' order by rand() limit 5 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. result = cursor.fetchall() for row in result: answer = row[3] array.append(answer) except: # Rollback in case there is any error db.rollback() shuffle(array) shuffledData = {'shuffledArray': array} return render_template('level1_conjunctions_new.html', data=result, shuffledData=shuffledData) ## Evaluate level1 conjunction question answers NEW ## @app.route('/evaluate_level1_conjunctions_new', methods=['POST']) def evaluate_level1_conjunctions_new(): if request.method == 'POST': marks = 0 question1=request.form['question1'] question2=request.form['question2'] question3=request.form['question3'] question4=request.form['question4'] question5=request.form['question5'] correctAnswer1 = request.form['correctAnswer1'] correctAnswer2 = request.form['correctAnswer2'] correctAnswer3 = request.form['correctAnswer3'] correctAnswer4 = request.form['correctAnswer4'] correctAnswer5 = request.form['correctAnswer5'] pa1 = request.form['one'] pa2 = request.form['two'] pa3 = request.form['three'] pa4 = request.form['four'] pa5 = request.form['five'] data = [['','',question1],['','',question2],['','',question3],['','',question4],['','',question5]] array=[correctAnswer1, correctAnswer2, correctAnswer3, correctAnswer4, correctAnswer5] shuffle(array) shuffledData = {'shuffledArray': array} if correctAnswer1 == pa1: a1_status = "Correct" marks = marks + 1 else: a1_status = "Wrong" if correctAnswer2 == pa2: a2_status = "Correct" marks = marks + 1 else: a2_status = "Wrong" if correctAnswer3 == pa3: a3_status = "Correct" marks = marks + 1 else: a3_status = "Wrong" if correctAnswer4 == pa4: a4_status = "Correct" marks = marks + 1 else: a4_status = "Wrong" if correctAnswer5 == pa5: a5_status = "Correct" marks = marks + 1 else: a5_status = "Wrong" data_array = {'pa1': pa1, 'pa2': pa2, 'pa3': pa3, 'pa4': pa4, 'pa5': pa5, 'a1': correctAnswer1, 'a2': correctAnswer2, 'a3': correctAnswer3, 'a4': correctAnswer4, 'a5': correctAnswer5, 'a1_status': a1_status, 'a2_status': a2_status, 'a3_status': a3_status, 'a4_status': a4_status, 'a5_status': a5_status, 'marks': marks} return render_template('level1_conjunctions_new.html', answer_data=data_array, shuffledData=shuffledData,data=data) return redirect(url_for('level1_conjunctions_new')) # ---------------------------- Adjectives ------------------------------------- #view AddQues_adjective page ## @app.route('/AddQues_adjectives') def AddQues_adjectives(): return render_template('AddQues_adjectives.html') ## Level 1 Adjectives Add Questions ## @app.route('/Save_adjectives', methods=['POST']) def Save_adjectives(): question = request.form['txtQuestion'] a = request.form['txtAnswer1'] b = request.form['txtAnswer2'] c = request.form['txtAnswer3'] answer = request.form['txtCorrectAnswer'] author = session['username'] question_exit = False cursor = db.cursor() sql = """SELECT * FROM level_1_adjectives where question=%s""" try: cursor.execute(sql, [question]) result = cursor.fetchall() # Commit your changes in the database print sql if result: for row in result: if row[1] == question: question_exit = True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors = {'question': question, 'a': a, 'b': b, 'c': c, 'answer': answer, 'questionStatus': question_exit} return render_template('AddQues_adjectives.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() cursor = db.cursor() sql = """INSERT INTO level_1_adjectives(question,a,b,c,answer,author) VALUES(%s,%s,%s,%s,%s,%s)""" try: # Execute the SQL command cursor.execute(sql, [question, a, b, c, answer, author]) # Commit your changes in the database db.commit() #flash('Question successfully added !') alert(text='Questions Added Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return render_template('AddQues_adjectives.html') ## Display all adjectives questions ## @app.route('/Update_adjectives') def Update_adjectives(): cursor = db.cursor() sql = """SELECT qno,question,a,b,c,answer FROM level_1_adjectives where author=%s """ try: # Execute the SQL command cursor.execute(sql, [session['username']]) #fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return render_template('Update_adjectives.html', data=query) ## get data to display in modal in edit adjective question ## @app.route('/edit_adjectives', methods=['GET', 'POST']) def edit_adjectives(): qno = request.args['qno'] cursor = db.cursor() sql = """SELECT * FROM level_1_adjectives where qno=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [qno]) # fetch a single row using fetchone() method. query = cursor.fetchall() for row in query: question = row[1] a = row[2] b = row[3] c = row[4] answer = row[5] except: db.rollback() return json.dumps(dict(question=question, a=a, b=b, c=c, answer=answer)) ## Save Edited adjectives question ## @app.route('/save_edited_adjectives', methods=['POST']) def save_edited_adjectives(): qno = request.form['qno'] question = request.form['inputQues'] a = request.form['Answer1'] b = request.form['Answer2'] c = request.form['Answer3'] answer = request.form['Answer'] cursor = db.cursor() sql = """update level_1_adjectives set question=%s,a=%s,b=%s,c=%s,answer=%s where qno=%s""" try: # Execute the SQL command cursor.execute(sql, [question, a, b, c, answer, qno]) # fetch a single row using fetchone() method. db.commit() except: db.rollback() return redirect(url_for('Update_adjectives')) ## Delete adjectives question ## @app.route('/delete_adjectives/', methods=['GET']) def delete_adjectives(): qno = request.args.get('qNo') cursor = db.cursor() sql = """delete from level_1_adjectives where qno=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [qno]) # fetch a single row using fetchone() method. db.commit() except: db.rollback() return redirect(url_for('Update_adjectives')) ## Level 1 Adjectives Activity ## @app.route('/level_1_adjectives') def level_1_adjectives(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_1_adjectives order by rand() limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() except: db.rollback() return render_template('level_1_adjectives.html', data=query) ## ------------------------------------------ Prepositions ---------------------------------------- ## ## View Add prepositions question ## @app.route('/add_prepositions_question') def add_prepositions_question(): return render_template('add_preposition_questions.html') ## Add prepositions question ## @app.route('/addPrepositions', methods=['POST']) def addPrepositions(): question1 = request.form['question_1'] question2 = request.form['question_2'] question3 = request.form['question_3'] Q1correct = request.form['Q1_txtCorrect'] Q1answer1 = request.form['Q1_txtAnswer1'] Q1answer2 = request.form['Q1_txtAnswer2'] Q1answer3 = request.form['Q1_txtAnswer3'] Q2correct = request.form['Q2_txtCorrect'] Q2answer1 = request.form['Q2_txtAnswer1'] Q2answer2 = request.form['Q2_txtAnswer2'] Q2answer3 = request.form['Q2_txtAnswer3'] Q3correct = request.form['Q3_txtCorrect'] Q3answer1 = request.form['Q3_txtAnswer1'] Q3answer2 = request.form['Q3_txtAnswer2'] Q3answer3 = request.form['Q3_txtAnswer3'] author =session['username'] question1_exist=False question2_exist=False question3_exist=False cursor = db.cursor() sql = """SELECT * FROM prepositions WHERE question=%s OR question=%s OR question=%s""" try: # Execute the SQL command cursor.execute(sql, [question1, question2, question3]) result = cursor.fetchall() if result: for row in result: if row[1]==question1: question1_exist=True elif row[1]==question2: question2_exist=True elif row[1]==question3: question3_exist=True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors={'question1':question1, 'question2':question2, 'question3':question3, 'correct1':Q1correct, 'Q1answer1':Q1answer1, 'Q1answer2':Q1answer2,'Q1answer3':Q1answer3,'correct2':Q2correct, 'Q2answer1':Q2answer1, 'Q2answer2':Q2answer2,'Q2answer3':Q2answer3,'correct3':Q3correct, 'Q3answer1':Q3answer1, 'Q3answer2':Q3answer2,'Q3answer3':Q3answer3, 'question1Status':question1_exist, 'question2Status':question2_exist, 'question3Status':question3_exist} return render_template('add_preposition_questions.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() rows = [] if question1 != '' and Q1correct != '' and Q1answer1 != '' and Q1answer2 != '' and Q1answer3 != '': array = [Q1correct, Q1answer1, Q1answer2, Q1answer3] shuffle(array) rows.append((array[0],array[1],array[2],array[3],Q1correct,question1,author)) if question2 != '' and Q2correct != '' and Q2answer1 != '' and Q2answer2 != '' and Q2answer3 != '': array = [Q2correct, Q2answer1, Q2answer2, Q2answer3] shuffle(array) rows.append((array[0],array[1],array[2],array[3],Q2correct,question2,author)) if question3 != '' and Q3correct != '' and Q3answer1 != '' and Q3answer2 != '' and Q3answer3 != '': array = [Q3correct, Q3answer1, Q3answer2, Q3answer3] shuffle(array) rows.append((array[0],array[1],array[2],array[3],Q3correct,question3,author)) cursor = db.cursor() sql = """INSERT INTO prepositions (answer1,answer2,answer3,answer4,correct,question,author) VALUES(%s,%s,%s,%s,%s,%s,%s)""" try: # Execute the SQL command cursor.executemany(sql, rows) # Commit your changes in the database db.commit() #flash('Question successfully added !') alert(text='Question Added Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return render_template('add_preposition_questions.html') ##View all Preposition Questions @app.route('/editPreQuestions') def editPreQuestions(): cursor = db.cursor() sql = """SELECT id,question FROM prepositions where author=%s""" try: # Execute the SQL command cursor.execute(sql, [session['username']]) #fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return render_template('EditPreQuestion.html', data=query) ## Edit preposition ## @app.route('/edit_preposition', methods=['GET', 'POST']) def edit_preposition(): id = request.args['id'] cursor = db.cursor() sql = """SELECT * FROM prepositions where id=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [id]) # fetch a single row using fetchone() method. query = cursor.fetchall() for row in query: question = row[1] correct = row[2] answer1 = row[3] answer2 = row[4] answer3 = row[5] answer4 = row[6] except: db.rollback() return json.dumps( dict(question=question, correct=correct, answer1=answer1, answer2=answer2, answer3=answer3, answer4=answer4)) ## Save edited prepositions question ## @app.route('/save_edited_preposition', methods=['POST']) def save_edited_preposition(): id = request.form['id'] question = request.form['inputQues'] correct = request.form['correct'] Answer1 = request.form['Answer1'] Answer2 = request.form['Answer2'] Answer3 = request.form['Answer3'] Answer4 = request.form['Answer4'] cursor = db.cursor() sql = """update prepositions set question=%s,correct=%s,answer1=%s,answer2=%s,answer3=%s,answer4=%s where id=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [question, correct, Answer1, Answer2, Answer3, Answer4, id]) # fetch a single row using fetchone() method. db.commit() except: db.rollback() return redirect(url_for('editPreQuestions')) ## Delete Preposition Question ## @app.route('/delete_preposition/', methods=['GET']) def delete_preposition(): id = request.args.get('qNo') cursor = db.cursor() sql = """delete from prepositions where id=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [id]) # fetch a single row using fetchone() method. db.commit() except: db.rollback() return redirect(url_for('editPreQuestions')) ## level 1 prepositions activity ## @app.route('/viewPrepositions') def viewPrepositions(): cursor = db.cursor() sql = """SELECT * FROM prepositions order by rand()limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return render_template('prepositions.html', data=query) ## ------------------------------------------ Articles ---------------------------------------- ## ## Articles Questions for level 1 ## @app.route('/add_articles_questions') def add_articles_questions(): return render_template('add_articles_questions.html') ## Add Articles question for level 1 ## @app.route('/save_articles_questions', methods=['POST']) def save_articles_questions(): if request.method == 'POST': question1 = request.form['question_1'] question2 = request.form['question_2'] question3 = request.form['question_3'] answer1 = request.form['answer_1'] answer2 = request.form['answer_2'] answer3 = request.form['answer_3'] author = session['username'] question1_exist=False question2_exist=False question3_exist=False cursor = db.cursor() sql = """SELECT * FROM level1_articles WHERE question=%s OR question=%s OR question=%s""" try: # Execute the SQL command cursor.execute(sql, [question1, question2, question3]) result = cursor.fetchall() if result: for row in result: if row[1]==question1: question1_exist=True elif row[1]==question2: question2_exist=True elif row[1]==question3: question3_exist=True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors={'question1':question1, 'question2':question2, 'question3':question3, 'answer1':answer1, 'answer2':answer2, 'answer3':answer3, 'question1Status':question1_exist, 'question2Status':question2_exist, 'question3Status':question3_exist} return render_template('add_articles_questions.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() rows = [] if question1 != '' and answer1 != '': rows.append((question1, answer1, author)) if question2 != '' and answer2 != '': rows.append((question2, answer2, author)) if question3 != '' and answer3 != '': rows.append((question3, answer3, author)) print rows cursor = db.cursor() sql = """INSERT INTO level1_articles (question,answer,author,level) VALUES(%s,%s,%s,'level1')""" try: # Execute the SQL command cursor.executemany(sql, rows) # Commit your changes in the database db.commit() #flash('Question successfully added !') alert(text='Question Added Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return redirect(url_for('add_articles_questions')) ## Display all article questions ## @app.route('/display_article_questions') def display_article_questions(): cursor = db.cursor() sql = """SELECT * FROM level1_articles where author=%s """ try: # Execute the SQL command select all rows cursor.execute(sql, [session['username']]) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return render_template('display_article_questions.html', data=result) ## Edit article questions ## @app.route('/edit_article', methods=['GET', 'POST']) def edit_article(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """SELECT * FROM level1_articles where level='level1' and author=%s and articleId=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username'], qNo]) # fetch rows using fetchall() method. result = cursor.fetchall() for row in result: question = row[1] answer = row[2] except: db.rollback() return json.dumps(dict(question=question, answer=answer)) ## Save edited article question for level 1 ## @app.route('/save_edited_article_question', methods=['POST']) def save_edited_article_question(): if request.method == 'POST': qNo = request.form['qNo'] question = request.form['question'] answer = request.form['answer'] author = session['username'] #print author cursor = db.cursor() sql = """UPDATE level1_articles SET question=%s,answer=%s WHERE articleId=%s""" try: # Execute the SQL command cursor.execute(sql, [question, answer, qNo]) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_article_questions')) ## Delete article questions ## @app.route('/delete_article_questions/', methods=['GET']) def delete_article_questions(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """DELETE FROM level1_articles where articleId=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [qNo]) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_article_questions')) ## Level 1 Article Activity ## @app.route('/Level1article') def Level1article(): cursor = db.cursor() sql = """SELECT * FROM level1_articles order by rand()limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return render_template('Level1article.html', data=query) ## Level 1 Test ## @app.route('/level1_test') def level1_test(): #Conjunction Question array=[] cursor = db.cursor() sql = """SELECT * FROM conjunctions where level='level1' order by rand() limit 5 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. conjunctionResult = cursor.fetchall() for row in conjunctionResult: answer = row[3] array.append(answer) except: # Rollback in case there is any error db.rollback() shuffle(array) shuffledData = {'shuffledArray': array} #Article Question cursor = db.cursor() sql = """SELECT * FROM level1_articles order by rand()limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch a single row using fetchone() method. articleResult = cursor.fetchall() except: db.rollback() #Preposition Question cursor = db.cursor() sql = """SELECT * FROM prepositions order by rand()limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch a single row using fetchone() method. prepositionResult = cursor.fetchall() except: db.rollback() #Adjective Question cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_1_adjectives order by rand() limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch rows using fetchall() method. adjectiveResult = cursor.fetchall() except: db.rollback() return render_template('level1_test.html', conjunctionData=conjunctionResult, shuffledData=shuffledData, articleData=articleResult, prepositionData=prepositionResult, adjectiveData=adjectiveResult) ## Evaluate level1 test ## @app.route('/evaluate_level1_test', methods=['POST']) def evaluate_level1_test(): if request.method == 'POST': marks = 0 #Conjunction conjunction_provided_answer1=request.form['conjunction_provided_answer1'] conjunction_provided_answer2=request.form['conjunction_provided_answer2'] conjunction_provided_answer3=request.form['conjunction_provided_answer3'] conjunction_provided_answer4=request.form['conjunction_provided_answer4'] conjunction_provided_answer5=request.form['conjunction_provided_answer5'] conjunction_correct_answer1=request.form['conjunction_correct_answer1'] conjunction_correct_answer2=request.form['conjunction_correct_answer2'] conjunction_correct_answer3=request.form['conjunction_correct_answer3'] conjunction_correct_answer4=request.form['conjunction_correct_answer4'] conjunction_correct_answer5=request.form['conjunction_correct_answer5'] #Articles article_provided_answer1=request.form['article_provided_answer1'] article_provided_answer2=request.form['article_provided_answer2'] article_provided_answer3=request.form['article_provided_answer3'] article_provided_answer4=request.form['article_provided_answer4'] article_provided_answer5=request.form['article_provided_answer5'] article_correct_answer1=request.form['article_correct_answer1'] article_correct_answer2=request.form['article_correct_answer2'] article_correct_answer3=request.form['article_correct_answer3'] article_correct_answer4=request.form['article_correct_answer4'] article_correct_answer5=request.form['article_correct_answer5'] #Prepositions preposition_provided_answer1=request.form['preposition_provided_answer1'] preposition_provided_answer2=request.form['preposition_provided_answer2'] preposition_provided_answer3=request.form['preposition_provided_answer3'] preposition_provided_answer4=request.form['preposition_provided_answer4'] preposition_provided_answer5=request.form['preposition_provided_answer5'] preposition_correct_answer1=request.form['preposition_correct_answer1'] preposition_correct_answer2=request.form['preposition_correct_answer2'] preposition_correct_answer3=request.form['preposition_correct_answer3'] preposition_correct_answer4=request.form['preposition_correct_answer4'] preposition_correct_answer5=request.form['preposition_correct_answer5'] #Adjectives adjectives_provided_answer1=request.form['adjectives_provided_answer1'] adjectives_provided_answer2=request.form['adjectives_provided_answer2'] adjectives_provided_answer3=request.form['adjectives_provided_answer3'] adjectives_provided_answer4=request.form['adjectives_provided_answer4'] adjectives_provided_answer5=request.form['adjectives_provided_answer5'] adjectives_correct_answer1=request.form['adjectives_correct_answer1'] adjectives_correct_answer2=request.form['adjectives_correct_answer2'] adjectives_correct_answer3=request.form['adjectives_correct_answer3'] adjectives_correct_answer4=request.form['adjectives_correct_answer4'] adjectives_correct_answer5=request.form['adjectives_correct_answer5'] if conjunction_provided_answer1==conjunction_correct_answer1: marks=marks+1 if conjunction_provided_answer2==conjunction_correct_answer2: marks=marks+1 if conjunction_provided_answer3==conjunction_correct_answer3: marks=marks+1 if conjunction_provided_answer4==conjunction_correct_answer4: marks=marks+1 if conjunction_provided_answer5==conjunction_correct_answer5: marks=marks+1 if article_provided_answer1==article_correct_answer1: marks=marks+1 if article_provided_answer2==article_correct_answer2: marks=marks+1 if article_provided_answer3==article_correct_answer3: marks=marks+1 if article_provided_answer4==article_correct_answer4: marks=marks+1 if article_provided_answer5==article_correct_answer5: marks=marks+1 if preposition_provided_answer1==preposition_correct_answer1: marks=marks+1 if preposition_provided_answer2==preposition_correct_answer2: marks=marks+1 if preposition_provided_answer3==preposition_correct_answer3: marks=marks+1 if preposition_provided_answer4==preposition_correct_answer4: marks=marks+1 if preposition_provided_answer5==preposition_correct_answer5: marks=marks+1 if adjectives_provided_answer1==adjectives_correct_answer1: marks=marks+1 if adjectives_provided_answer2==adjectives_correct_answer2: marks=marks+1 if adjectives_provided_answer3==adjectives_correct_answer3: marks=marks+1 if adjectives_provided_answer4==adjectives_correct_answer4: marks=marks+1 if adjectives_provided_answer5==adjectives_correct_answer5: marks=marks+1 marks_percentage=float(marks)/20*100 if marks_percentage>=75: level='Preliminary' if session['level']=='Elementary': cursor = db.cursor() sql = """update users set placement_test=%s where email=%s""" try: cursor.execute(sql, [level, session['username']]) db.commit() except: db.rollback() else: level='Elementary' data = {'marks': marks, 'level': level} return render_template('level1_test_report.html', data=data) ## ----------------------------------- LEVEL 2 - PRELIMINARY LEVEL ---------------------------------- # ----------------------- Level 2 - Dialog ---------------------------------------------------------- ## Dialog Questions for level 2 ## @app.route('/add_dialog_questions') def add_dialog_questions(): return render_template('add_dialog_questions.html') ## Add dialog question for level 2 ## @app.route('/save_dialog_question', methods=['POST']) def save_dialog_question(): if request.method == 'POST': question = request.form['question'] answers = request.form['answers'] a1 = request.form['answer1'] a2 = request.form['answer2'] a3 = request.form['answer3'] a4 = request.form['answer4'] a5 = request.form['answer5'] author = session['username'] cursor = db.cursor() sql = """INSERT INTO dialogs (level,question,answers,a1,a2,a3,a4,a5,author) VALUES('level2',%s,%s,%s,%s,%s,%s,%s,%s)""" try: # Execute the SQL command cursor.execute(sql, [question, answers, a1, a2, a3, a4, a5, author]) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() alert(text='Question Added Successfully !', title='English Buddy', button='OK') return redirect(url_for('add_dialog_questions')) ## Display all dialog questions ## @app.route('/display_dialog_questions/', methods=['GET']) def display_dialog_questions(): level = request.args.get('level') cursor = db.cursor() if level=='level2': sql = """SELECT * FROM dialogs where author=%s AND level=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username'], level]) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return render_template('display_dialog_questions.html', data=result) elif level=='level4': sql = """SELECT * FROM level4_dialogs where author=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username']]) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return render_template('display_dialog_questions_level4.html', data=result) ## Edit dialog questions ## @app.route('/edit_dialog', methods=['GET', 'POST']) def edit_dialog(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """SELECT * FROM dialogs where level='level2' and author=%s and qNo=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username'], qNo]) # fetch rows using fetchall() method. result = cursor.fetchall() for row in result: question = row[2] answer = row[3] a1 = row[4] a2 = row[5] a3 = row[6] a4 = row[7] a5 = row[8] except: db.rollback() session['level2DialogQuestion']=question session['level2DialogAnswer']=answer return json.dumps(dict(question=question, answer=answer, a1=a1, a2=a2, a3=a3, a4=a4, a5=a5)) ## Save edited dialog question for level 2 ## @app.route('/save_edited_dialog_question', methods=['POST']) def save_edited_dialog_question(): if request.method == 'POST': qNo = request.form['qNo'] question = request.form['question'] answers = request.form['answers'] a1 = request.form['answer1'] a2 = request.form['answer2'] a3 = request.form['answer3'] a4 = request.form['answer4'] a5 = request.form['answer5'] cursor = db.cursor() sql = """UPDATE dialogs SET question=%s,answers=%s,a1=%s,a2=%s,a3=%s,a4=%s,a5=%s WHERE qNo=%s""" try: # Execute the SQL command cursor.execute(sql, [question, answers, a1, a2, a3, a4, a5, qNo]) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_dialog_questions')) ## Delete dialog questions ## @app.route('/delete_dialog_questions/', methods=['GET']) def delete_dialog_questions(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """DELETE FROM dialogs where qNo=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [qNo]) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_dialog_questions')) ## Level 2 dialog Activity ## @app.route('/level1_dialogs') def level1_dialogs(): cursor = db.cursor() sql = """SELECT * FROM dialogs where level='level2' order by rand() limit 1 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return render_template('level1_dialogs.html', data=result) ## Evaluate level2 dialog question answers ## @app.route('/evaluate_level1_dialogs', methods=['POST']) def evaluate_level1_dialogs(): if request.method == 'POST': marks = 0 qNo = request.form['qNo'] pa1 = request.form['one'] pa2 = request.form['two'] pa3 = request.form['three'] pa4 = request.form['four'] pa5 = request.form['five'] cursor = db.cursor() sql = """SELECT * FROM dialogs where qNo=%s""" try: # Execute the SQL command cursor.execute(sql, [qNo]) # fetch a single row using fetchone() method. data = cursor.fetchall() for row in data: a1 = row[4] a2 = row[5] a3 = row[6] a4 = row[7] a5 = row[8] question = row[2] answers = row[3] if a1 == pa1: a1_status = "Correct" marks = marks + 1 else: a1_status = "Wrong" if a2 == pa2: a2_status = "Correct" marks = marks + 1 else: a2_status = "Wrong" if a3 == pa3: a3_status = "Correct" marks = marks + 1 else: a3_status = "Wrong" if a4 == pa4: a4_status = "Correct" marks = marks + 1 else: a4_status = "Wrong" if a5 == pa5: a5_status = "Correct" marks = marks + 1 else: a5_status = "Wrong" #print marks data_array = {'qNo': qNo, 'a1': a1, 'a2': a2, 'a3': a3, 'a4': a4, 'a5': a5, 'question': question, 'pa1': pa1, 'pa2': pa2, 'pa3': pa3, 'pa4': pa4, 'pa5': pa5, 'a1_status': a1_status, 'a2_status': a2_status, 'a3_status': a3_status, 'a4_status': a4_status, 'a5_status': a5_status, 'marks': marks, 'answers': answers} return render_template('level1_dialogs_answers.html', data=data_array) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return redirect(url_for('level1_dialogs')) ## Show level2 dialog question answers ## @app.route('/display_level1_dialog_answers') def display_level1_dialog_answers(): return render_template('level1_dialogs_answers.html') #------------------------------------ Pronouns ---------------------------- ## Display Add pronoun question question page ## @app.route('/AddQues_pronoun') def AddQues_pronoun(): return render_template('AddQues_pronoun.html') ## Add pronoun question ## @app.route('/Save_pronoun', methods=['POST']) def Save_pronoun(): question1 = request.form['txtQuestion1'] question2 = request.form['txtQuestion2'] question3 = request.form['txtQuestion3'] answer1 = request.form['txtAnswer1'] answer2 = request.form['txtAnswer2'] answer3 = request.form['txtAnswer3'] author = session['username'] question1_exist = False question2_exist = False question3_exist = False cursor = db.cursor() sql = """SELECT * FROM level_2_pronoun WHERE question=%s OR question=%s OR question=%s""" try: # Execute the SQL command cursor.execute(sql, [question1, question2, question3]) result = cursor.fetchall() if result: for row in result: if row[1] == question1: question1_exist = True elif row[1] == question2: question2_exist = True elif row[1] == question3: question3_exist = True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors = {'question1': question1, 'question2': question2, 'question3': question3, 'answer1': answer1, 'answer2': answer2, 'answer3': answer3, 'question1Status': question1_exist, 'question2Status': question2_exist, 'question3Status': question3_exist} return render_template('AddQues_pronoun.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() rows = [] if question1 != '' and answer1 != '': rows.append((question1, answer1, author)) if question2 != '' and answer2 != '': rows.append((question2, answer2, author)) if question3 != '' and answer3 != '': rows.append((question3, answer3, author)) cursor = db.cursor() sql = """INSERT INTO level_2_pronoun (question,answer,author) VALUES(%s,%s,%s)""" try: # Execute the SQL command cursor.executemany(sql, rows) # Commit your changes in the database db.commit() #flash('Question successfully added !') alert(text='Questions Added Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return redirect(url_for('AddQues_pronoun')) ## View all pronoun questions ## @app.route('/Update_pronoun') def Update_pronoun(): cursor = db.cursor() sql = """SELECT qno,question,answer FROM level_2_pronoun where author=%s""" try: # Execute the SQL command cursor.execute(sql, [session['username']]) #fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return render_template('Update_pronoun.html', data=query) ## Edit pronoun question ## @app.route('/edit_pronoun', methods=['GET', 'POST']) def edit_pronoun(): qno = request.args['qno'] cursor = db.cursor() sql = """SELECT * FROM level_2_pronoun where qno=%s""" try: # Execute the SQL command cursor.execute(sql, [qno]) # fetch a single row using fetchone() method. query = cursor.fetchall() for row in query: question = row[1] answer = row[2] except: db.rollback() return json.dumps(dict(question=question, answer=answer)) ## Save updated pronoun question data in the database ## @app.route('/save_edited_pronoun', methods=['POST']) def save_edited_pronoun(): qno = request.form['qno'] question = request.form['question'] answer = request.form['answer'] cursor = db.cursor() sql = """UPDATE level_2_pronoun SET question=%s,answer=%s WHERE qno=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [question, answer, qno]) db.commit() # fetch a single row using fetchone() method. except: db.rollback() return redirect(url_for('Update_pronoun')) ## Delete pronoun question ## @app.route('/delete_pronoun/', methods=['GET']) def delete_pronoun(): qno = request.args.get('qNo') cursor = db.cursor() sql = """delete from level_2_pronoun where qno=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [qno]) # fetch a single row using fetchone() method. db.commit() except: db.rollback() return redirect(url_for('Update_pronoun')) ## Level 2 Pronouns Activity @app.route('/level_2_pronoun') def level_2_pronoun(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_2_pronoun order by rand() limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() except: db.rollback() db.close() return render_template('level_2_pronoun.html', data=query) # --------------------------------------- Level 2 Match (Synonyms) ------------------------------------------ ## Matching Words Questions for level 1 ## @app.route('/add_matching_words_questions') def add_matching_words_questions(): return render_template('add_matching_words_questions.html') ## Add Matching Words question for level 1 ## @app.route('/save_matching_words_questions', methods=['POST']) def save_matching_words_questions(): if request.method == 'POST': question1 = request.form['question_1'] question2 = request.form['question_2'] question3 = request.form['question_3'] answer1 = request.form['answer_1'] answer2 = request.form['answer_2'] answer3 = request.form['answer_3'] author = session['username'] question1_exist=False question2_exist=False question3_exist=False cursor = db.cursor() sql = """SELECT * FROM level2_match WHERE question=%s OR question=%s OR question=%s""" try: # Execute the SQL command cursor.execute(sql, [question1, question2, question3]) result = cursor.fetchall() if result: for row in result: if row[1]==question1: question1_exist=True elif row[1]==question2: question2_exist=True elif row[1]==question3: question3_exist=True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors={'question1':question1, 'question2':question2, 'question3':question3, 'answer1':answer1, 'answer2':answer2, 'answer3':answer3, 'question1Status':question1_exist, 'question2Status':question2_exist, 'question3Status':question3_exist} return render_template('add_matching_words_questions.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() rows = [] if question1 != '' and answer1 != '': rows.append((question1, answer1, author)) if question2 != '' and answer2 != '': rows.append((question2, answer2, author)) if question3 != '' and answer3 != '': rows.append((question3, answer3, author)) #print rows cursor = db.cursor() sql = """INSERT INTO level2_match (level,question,answer,author) VALUES('level2',%s,%s,%s)""" try: # Execute the SQL command cursor.executemany(sql, rows) # Commit your changes in the database db.commit() #flash('Question successfully added !') alert(text='Question Added Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return redirect(url_for('add_matching_words_questions')) ## Display all matchWords questions ## @app.route('/display_match_words_questions') def display_match_words_questions(): cursor = db.cursor() sql = """SELECT * FROM level2_match where author=%s """ try: # Execute the SQL command select all rows cursor.execute(sql, [session['username']]) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return render_template('display_match_words_questions.html', data=result) ## Edit matchWords questions ## @app.route('/edit_match_words', methods=['GET', 'POST']) def edit_match_words(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """SELECT * FROM level2_match where level='level2' and author=%s and matchId=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username'], qNo]) # fetch rows using fetchall() method. result = cursor.fetchall() for row in result: question = row[1] answer = row[2] except: db.rollback() return json.dumps(dict(question=question, answer=answer)) ## Save edited matchWords question for level 1 ## @app.route('/save_edited_match_words_question', methods=['POST']) def save_edited_match_words_question(): if request.method == 'POST': qNo = request.form['qNo'] question = request.form['question'] answer = request.form['answer'] author = session['username'] #print author cursor = db.cursor() sql = """UPDATE level2_match SET question=%s,answer=%s WHERE matchId=%s""" try: # Execute the SQL command cursor.execute(sql, [question, answer, qNo]) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_match_words_questions')) ## Delete matchWords questions ## @app.route('/delete_match_words_questions/', methods=['GET']) def delete_match_words_questions(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """DELETE FROM level2_match where matchId=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [qNo]) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_match_words_questions')) ## Level 2 Match (Synonyms) Activity ## @app.route('/Level2Match') def Level2Match(): cursor = db.cursor() sql = """SELECT * FROM level2_match order by rand()limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return render_template('Level2Match.html', data=query) ## ------------------------------------------ Jumble Sentences ---------------------------------------- ## ## Display Add jumble sentences question ## @app.route('/add_jumble_sentences') def add_jumble_sentences(): return render_template('Add_JumbleSentences.html') ## Add jumble sentences question ## @app.route('/AddJumbleSentences', methods=['POST']) def AddJumbleSentences(): wrongSentence1 = request.form['txtWrong1'] correctSentence1 = request.form['txtCorrect1'] wrongSentence2 = request.form['txtWrong2'] correctSentence2 = request.form['txtCorrect2'] wrongSentence3 = request.form['txtWrong3'] correctSentence3 = request.form['txtCorrect3'] question1_exist=False question2_exist=False question3_exist=False cursor = db.cursor() sql ="""SELECT * FROM jumblesentences WHERE wrong_sentence=%s OR wrong_sentence=%s OR wrong_sentence=%s""" try: # Execute the SQL command cursor.execute(sql,[wrongSentence1,wrongSentence2,wrongSentence3]) result = cursor.fetchall() print(cursor.fetchall()) if result: for row in result: if row[1]==wrongSentence1: question1_exist=True elif row[1]== wrongSentence2: question2_exist=True elif row[1]==wrongSentence3: question3_exist=True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors={'wrongsentence1':wrongSentence1, 'wrongsentence2':wrongSentence2, 'wrongsentence3':wrongSentence3, 'correctSentence1':correctSentence1, 'correctSentence2':correctSentence2, 'correctSentence3':correctSentence3,'question1Status':question1_exist, 'question2Status':question2_exist, 'question3Status':question3_exist} return render_template('Add_JumbleSentences.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() rows = [] if request.form.get('txtWrong1') != '' and request.form.get('txtCorrect1') != '': wrongSentence1 = request.form['txtWrong1'] correctSentence1 = request.form['txtCorrect1'] rows.append(( wrongSentence1.strip(), correctSentence1.strip(), session['username'])) if request.form.get('txtWrong2') != '' and request.form.get('txtCorrect2') != '': wrongSentence2 = request.form['txtWrong2'] correctSentence2 = request.form['txtCorrect2'] rows.append(( wrongSentence2.strip(), correctSentence2.strip(), session['username'])) if request.form.get('txtWrong3') != '' and request.form.get('txtCorrect3') != '': wrongSentence3 = request.form['txtWrong3'] correctSentence3 = request.form['txtCorrect3'] rows.append(( wrongSentence3.strip(), correctSentence3.strip(), session['username'])) cursor = db.cursor() sql = """INSERT INTO jumblesentences (wrong_sentence,correct_sentence,author) VALUES(%s,%s,%s)""" try: # Execute the SQL command #cursor.execute(sql,[qusetion1,answer1]) print 'add' cursor.executemany(sql, rows) db.commit() except: db.rollback() return render_template('Add_JumbleSentences.html') ## Show all jumble sentences questions ## @app.route('/editJumbleQuestions') def editJumbleQuestions(): cursor = db.cursor() sql = """SELECT * FROM jumblesentences where author=%s""" try: # Execute the SQL command cursor.execute(sql, [session['username']]) #fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return render_template('EditJumbleSentences.html', data=query) ## Edit jumble sentences question ## @app.route('/edit_jumbleSentences', methods=['GET', 'POST']) def edit_jumbleSentences(): id = request.args['id'] cursor = db.cursor() sql = """SELECT * FROM jumblesentences where id=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [id]) # fetch a single row using fetchone() method. query = cursor.fetchall() for row in query: wrong = row[1] correct = row[2] except: db.rollback() return json.dumps(dict(wrong=wrong, correct=correct)) ## Save edited jumble sentences question ## @app.route('/save_edited_jumblesentences', methods=['POST']) def save_edited_jumbleSentences(): id = request.form['id'] wrong = request.form['wrong'] correct = request.form['correct'] cursor = db.cursor() sql = """update jumblesentences set wrong_sentence=%s,correct_sentence=%s where id=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [wrong, correct, id]) # fetch a single row using fetchone() method. db.commit() except: db.rollback() return redirect(url_for('editJumbleQuestions')) ## Delete jumble sentences question ## @app.route('/delete_jumbleSentences/', methods=['GET']) def delete_jumbleSentences(): id = request.args.get('qNo') cursor = db.cursor() sql = """delete from jumblesentences where id=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [id]) # fetch a single row using fetchone() method. db.commit() except: db.rollback() return redirect(url_for('editJumbleQuestions')) ## Level 2 Jumble Sentences Activity ## @app.route('/viewJumbleSentences') def viewJumbleSentences(): cursor = db.cursor() sql = """SELECT * FROM jumblesentences order by rand()limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return render_template('JumbleSentences.html', data=query) ## Level 2 Test## @app.route('/level2_test') def level2_test(): #Pronoun Question cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_2_pronoun order by rand() limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch rows using fetchall() method. pronounResult = cursor.fetchall() except: db.rollback() #Jumble Sentences Question cursor = db.cursor() sql = """SELECT * FROM jumblesentences order by rand()limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch a single row using fetchone() method. jumbleSentenceResult = cursor.fetchall() except: db.rollback() #Match words Question cursor = db.cursor() sql = """SELECT * FROM level2_match order by rand()limit 5""" try: # Execute the SQL command cursor.execute(sql) # fetch a single row using fetchone() method. matchWordsResult = cursor.fetchall() except: db.rollback() #Dialogue Question cursor = db.cursor() sql = """SELECT * FROM dialogs where level='level2' order by rand() limit 1 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. dialogResult = cursor.fetchall() except: # Rollback in case there is any error db.rollback() return render_template('level2_test.html', pronounData=pronounResult, jumbleSentenceData=jumbleSentenceResult, matchWordsData=matchWordsResult, dialogData=dialogResult) ## Evaluate level2 test ## @app.route('/evaluate_level2_test', methods=['POST']) def evaluate_level2_test(): if request.method == 'POST': marks = 0 #pronuon pronoun_correct_answer1=request.form['pronoun_correct_answer1'] pronoun_correct_answer2=request.form['pronoun_correct_answer2'] pronoun_correct_answer3=request.form['pronoun_correct_answer3'] pronoun_correct_answer4=request.form['pronoun_correct_answer4'] pronoun_correct_answer5=request.form['pronoun_correct_answer5'] pronoun_provided_answer1=request.form['pronoun_provided_answer1'] pronoun_provided_answer2=request.form['pronoun_provided_answer2'] pronoun_provided_answer3=request.form['pronoun_provided_answer3'] pronoun_provided_answer4=request.form['pronoun_provided_answer4'] pronoun_provided_answer5=request.form['pronoun_provided_answer5'] #jumble Sentences jumbleSentences_correct1=request.form['jumbleSentence_correct_answer1'] jumbleSentences_correct2=request.form['jumbleSentence_correct_answer2'] jumbleSentences_correct3=request.form['jumbleSentence_correct_answer3'] jumbleSentences_correct4=request.form['jumbleSentence_correct_answer4'] jumbleSentences_correct5=request.form['jumbleSentence_correct_answer5'] jumbleSentence_provided_answer1=request.form['jumbleSentence_provided_answer1'] jumbleSentence_provided_answer2=request.form['jumbleSentence_provided_answer2'] jumbleSentence_provided_answer3=request.form['jumbleSentence_provided_answer3'] jumbleSentence_provided_answer4=request.form['jumbleSentence_provided_answer4'] jumbleSentence_provided_answer5=request.form['jumbleSentence_provided_answer5'] #dialogs dialog_provided_answer1=request.form['dialog_provided_answer1'] dialog_provided_answer2=request.form['dialog_provided_answer2'] dialog_provided_answer3=request.form['dialog_provided_answer3'] dialog_provided_answer4=request.form['dialog_provided_answer4'] dialog_provided_answer5=request.form['dialog_provided_answer5'] dialog_correct_answer1=request.form['dialog_correct_answer1'] dialog_correct_answer2=request.form['dialog_correct_answer2'] dialog_correct_answer3=request.form['dialog_correct_answer3'] dialog_correct_answer4=request.form['dialog_correct_answer4'] dialog_correct_answer5=request.form['dialog_correct_answer5'] matchMarks=request.form['matchMarks'] print matchMarks if pronoun_provided_answer1==pronoun_correct_answer1: marks=marks+1 if pronoun_provided_answer2==pronoun_correct_answer2: marks=marks+1 if pronoun_provided_answer3==pronoun_correct_answer3: marks=marks+1 if pronoun_provided_answer4==pronoun_correct_answer4: marks=marks+1 if pronoun_provided_answer5==pronoun_correct_answer5: marks=marks+1 if jumbleSentence_provided_answer1.strip()==jumbleSentences_correct1: marks=marks+1 if jumbleSentence_provided_answer2.strip()==jumbleSentences_correct2: marks=marks+1 if jumbleSentence_provided_answer3.strip()==jumbleSentences_correct3: marks=marks+1 if jumbleSentence_provided_answer4.strip()==jumbleSentences_correct4: marks=marks+1 if jumbleSentence_provided_answer5.strip()==jumbleSentences_correct5: marks=marks+1 if dialog_provided_answer1==dialog_correct_answer1: marks=marks+1 if dialog_provided_answer2==dialog_correct_answer2: marks=marks+1 if dialog_provided_answer3==dialog_correct_answer3: marks=marks+1 if dialog_provided_answer4==dialog_correct_answer4: marks=marks+1 if dialog_provided_answer5==dialog_correct_answer5: marks=marks+1 newMarks=marks+int(matchMarks) marks_out_of_100=float(newMarks)/20*100 if marks_out_of_100>=75: level='Intermediate' if session['level']=='Preliminary': cursor = db.cursor() sql = """update users set placement_test=%s where email=%s""" try: cursor.execute(sql, [level, session['username']]) db.commit() except: db.rollback() else: level='Preliminary' data = {'marks': marks_out_of_100, 'level': level, 'correct': newMarks} return render_template('level2_test_report.html', data=data) ## ------------------------------------- Level 3 ----------------------------------------------- ## # ------------------------ Level 3 - Conjunctions ----------------------------------------------- # ## Display Add Conjunction Questions for level 3 ## @app.route('/level3_add_conjunction_questions') def level3_add_conjunction_questions(): return render_template('level3_add_conjunction_questions.html') ## Add conjunction question for level 3 ## @app.route('/level3_save_conjunction_question', methods=['POST']) def level3_save_conjunction_question(): if request.method == 'POST': question1 = request.form['question_1'] question2 = request.form['question_2'] question3 = request.form['question_3'] author = session['username'] rows = [] if question1 != '': rows.append((question1, author)) if question2 != '': rows.append((question2, author)) if question3 != '': rows.append((question3, author)) cursor = db.cursor() sql = """INSERT INTO level3_conjunctions (level,question,author) VALUES('level3',%s,%s)""" try: # Execute the SQL command cursor.executemany(sql, rows) # Commit your changes in the database db.commit() #flash('Question successfully added !') alert(text='Question Added Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return redirect(url_for('level3_add_conjunction_questions')) # # Edit level 3 conjunction questions ## @app.route('/level3_edit_conjunction', methods=['GET', 'POST']) def level3_edit_conjunction(): qNo = request.args.get('qNo') level = 'level3' cursor = db.cursor() sql = """SELECT * FROM level3_conjunctions where level=%s and author=%s and qNo=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [level, session['username'], qNo]) # fetch rows using fetchall() method. result = cursor.fetchall() for row in result: question = row[2] except: db.rollback() return json.dumps(dict(question=question)) ## Level 3 Conjunctions Activity ## @app.route('/level3_conjunctions_activity') def level3_conjunctions_activity(): cursor = db.cursor() sql = """SELECT * FROM level3_conjunctions where level='level3' order by rand() limit 5 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. result = cursor.fetchall() except: # Rollback in case there is any error db.rollback() return render_template('level3_conjunctions_activity.html', data=result) ## Level 3 Conjunction Evaluate Answers ## @app.route('/evaluate_level3_conjunction_activity', methods=['POST']) def evaluate_level3_conjunction_activity(): if request.method == 'POST': marks = 0 question1=request.form['question1'] question2=request.form['question2'] question3=request.form['question3'] question4=request.form['question4'] question5=request.form['question5'] pa1 = request.form['one'].strip() pa2 = request.form['two'].strip() pa3 = request.form['three'].strip() pa4 = request.form['four'].strip() pa5 = request.form['five'].strip() #Capitalize the first letter of the question if question1.split(" ")[0]=='#,' or question1.split(" ")[0]=='#': pa1=pa1.capitalize() if question2.split(" ")[0]=='#,' or question2.split(" ")[0]=='#': pa2=pa2.capitalize() if question3.split(" ")[0]=='#,' or question3.split(" ")[0]=='#': pa3=pa3.capitalize() if question4.split(" ")[0]=='#,' or question4.split(" ")[0]=='#': pa4=pa4.capitalize() if question5.split(" ")[0]=='#,' or question5.split(" ")[0]=='#': pa5=pa5.capitalize() #Complete questions with provided answer complete_question1=question1.split("#")[0]+pa1+question1.split("#")[1] complete_question2=question2.split("#")[0]+pa2+question2.split("#")[1] complete_question3=question3.split("#")[0]+pa3+question3.split("#")[1] complete_question4=question4.split("#")[0]+pa4+question4.split("#")[1] complete_question5=question5.split("#")[0]+pa5+question5.split("#")[1] data = [['','',question1],['','',question2],['','',question3],['','',question4],['','',question5]] question1_suggestion='' question2_suggestion='' question3_suggestion='' question4_suggestion='' question5_suggestion='' # if ConjunctionClass.check(complete_question1, pa1): # marks = marks + 1 # question1_status = "Correct" # else: # question1_suggestion=ConjunctionClass.find_correct_conjunction(question1) # question1_status = "Wrong" # # if ConjunctionClass.check(complete_question2, pa2): # marks = marks + 1 # question2_status = "Correct" # else: # question2_suggestion=ConjunctionClass.find_correct_conjunction(question2) # question2_status = "Wrong" # # if ConjunctionClass.check(complete_question3, pa3): # marks = marks + 1 # question3_status = "Correct" # else: # question3_suggestion=ConjunctionClass.find_correct_conjunction(question3) # question3_status = "Wrong" # # if ConjunctionClass.check(complete_question4, pa4): # marks = marks + 1 # question4_status = "Correct" # else: # question4_suggestion=ConjunctionClass.find_correct_conjunction(question4) # question4_status = "Wrong" # # if ConjunctionClass.check(complete_question5, pa5): # marks = marks + 1 # question5_status = "Correct" # else: # question5_suggestion=ConjunctionClass.find_correct_conjunction(question5) # question5_status = "Wrong" if CoordinatingConjunctionClass.check(complete_question1, pa1): marks = marks + 1 question1_status = "Correct" else: question1_suggestion=CoordinatingConjunctionClass.find_correct_conjunction(question1) question1_status = "Wrong" if CoordinatingConjunctionClass.check(complete_question2, pa2): marks = marks + 1 question2_status = "Correct" else: question2_suggestion=CoordinatingConjunctionClass.find_correct_conjunction(question2) question2_status = "Wrong" if CoordinatingConjunctionClass.check(complete_question3, pa3): marks = marks + 1 question3_status = "Correct" else: question3_suggestion=CoordinatingConjunctionClass.find_correct_conjunction(question3) question3_status = "Wrong" if CoordinatingConjunctionClass.check(complete_question4, pa4): marks = marks + 1 question4_status = "Correct" else: question4_suggestion=CoordinatingConjunctionClass.find_correct_conjunction(question4) question4_status = "Wrong" if CoordinatingConjunctionClass.check(complete_question5, pa5): marks = marks + 1 question5_status = "Correct" else: question5_suggestion=CoordinatingConjunctionClass.find_correct_conjunction(question5) question5_status = "Wrong" data_array = {'pa1': pa1, 'pa2': pa2, 'pa3': pa3, 'pa4': pa4, 'pa5': pa5, 'a1': question1_suggestion, 'a2': question2_suggestion, 'a3': question3_suggestion, 'a4': question4_suggestion, 'a5': question5_suggestion, 'a1_status': question1_status, 'a2_status': question2_status, 'a3_status': question3_status, 'a4_status': question4_status, 'a5_status': question5_status, 'marks': marks} return render_template('level3_conjunctions_activity.html', answer_data=data_array, data=data) return redirect(url_for('level3_conjunctions_activity')) # ------------------------ Level 3 - Notice/Invitation ----------------------------------------------- # #Darani ## Notice or invitation Questions for level 1 ## @app.route('/add_notice_invitation_questions') def add_notice_invitation_questions(): return render_template('add_notice_invitation_questions.html') ## Add notice or invitation question for level 1 ## @app.route('/save_notice_invitation_questions', methods=['POST']) def save_notice_invitation_questions(): if request.method == 'POST': question1 = request.form['question_1'] question2 = request.form['question_2'] question3 = request.form['question_3'] type1 = request.form['notice1'] type2 = request.form['notice2'] type3 = request.form['notice3'] author = session['username'] question1_exist=False question2_exist=False question3_exist=False cursor = db.cursor() sql = """SELECT * FROM level3_notice_invitation WHERE question=%s OR question=%s OR question=%s""" try: # Execute the SQL command cursor.execute(sql, [question1, question2, question3]) result = cursor.fetchall() if result: for row in result: if row[1]==question1: question1_exist=True elif row[1]==question2: question2_exist=True elif row[1]==question3: question3_exist=True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors={'question1':question1, 'question2':question2, 'question3':question3, 'question1Status':question1_exist, 'question2Status':question2_exist, 'question3Status':question3_exist} return render_template('add_notice_invitation_questions.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() if type1 == 'notice': type1_ = 'N' else : type1_ = 'I' if type2 == 'notice': type2_ = 'N' else : type2_ = 'I' if type3 == 'notice': type3_ = 'N' else : type3_ = 'I' rows = [] if question1 != '' : rows.append((question1, author, type1_)) if question2 != '' : rows.append((question2, author, type2_)) if question3 != '' : rows.append((question3, author, type3_)) print rows cursor = db.cursor() sql = """INSERT INTO level3_notice_invitation (question,author,type) VALUES(%s,%s,%s)""" try: # Execute the SQL command cursor.executemany(sql, rows) # Commit your changes in the database db.commit() #flash('Question successfully added !') alert(text='Question Added Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return redirect(url_for('add_notice_invitation_questions')) ## Display all notice or invitation questions ## @app.route('/display_notice_invitation_questions') def display_notice_invitation_questions(): cursor = db.cursor() sql = """SELECT * FROM level3_notice_invitation where author=%s """ try: # Execute the SQL command select all rows cursor.execute(sql, [session['username']]) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return render_template('display_notice_invitation_questions.html', data=result) ## Edit notice or invitation questions ## @app.route('/edit_notice_invitation', methods=['GET', 'POST']) def edit_notice_invitation(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """SELECT * FROM level3_notice_invitation where author=%s and NI_Id=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username'], qNo]) # fetch rows using fetchall() method. result = cursor.fetchall() for row in result: question = row[1] except: db.rollback() return json.dumps(dict(question=question)) ## Save edited notice or invitation question for level 1 ## @app.route('/save_edited_notice_invitation_question', methods=['POST']) def save_edited_notice_invitation_question(): if request.method == 'POST': qNo = request.form['qNo'] question = request.form['question'] author = session['username'] #print author cursor = db.cursor() sql = """UPDATE level3_notice_invitation SET question=%s WHERE NI_Id=%s""" try: # Execute the SQL command cursor.execute(sql, [question,qNo]) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_notice_invitation_questions')) ## Delete notice or invitation questions ## @app.route('/delete_notice_invitation_questions/', methods=['GET']) def delete_notice_invitation_questions(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """DELETE FROM level3_notice_invitation where NI_Id=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [qNo]) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_notice_invitation_questions')) ## Level 3 Notice_Invitation Activity NEW## @app.route('/level3_Notice_Invitation') def level3_Notice_Invitation(): cursor = db.cursor() sql = """SELECT * FROM level3_notice_invitation order by rand() limit 1""" try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. result = cursor.fetchall() print result except: # Rollback in case there is any error db.rollback() return render_template('level3_Notice_Invitation.html', data=result) ## Level 3 evaluate Notice_Invitation Activity NEW## @app.route('/evaluate_level3_Notice_Invitation' , methods=['POST']) def evaluate_level3_Notice_Invitation(): question = request.form['question'] answer = request.form['answer'] type = request.form['type'] struct_total = 0 grammar_total = 0 name = '' address = '' statusN = '' statusI = '' showtime = '' showdate = '' showvenue = '' #count senetences sent_count = 0 sentences_qus= sent_tokenize(answer) for sentence_qus in sentences_qus: sent_count = sent_count+1 if type == 'N': count1,name,address =notice.designation(answer, question) count2,statusN = notice.checkTypeWordCount(answer,question) count3,showtime,showdate,showvenue = notice.dateTimeVenue(answer) count4 = notice.includes(answer,question) if sent_count <= 2: struct_total = 0 else : struct_total = count1+count2+count3+count4 else: count1,name,address = invitation.designation(answer, question) count2,statusI = invitation.checkTypeWordCount(answer,question) count3,showtime,showdate,showvenue = invitation.dateTimeVenue(answer) count4 = invitation.includes(answer,question) if sent_count <= 2: struct_total = 0.0 else : struct_total = count1+count2+count3+count4 conv =Ansi2HTMLConverter() array=[] array=ginger.main(" ".join(answer.split())) original_text=conv.convert(array[0]) fixed_text=conv.convert(array[1]) wrong_count = array[2] if fixed_text=='Good English..!!' or wrong_count <=2 : grammar_total=grammar_total+2.5 elif wrong_count >2 and wrong_count <= 4 : grammar_total=grammar_total+1.0 elif sent_count <= 2 : grammar_total=grammar_total+0.0 else: grammar_total=grammar_total+0.5 print 'wrong',wrong_count print 'tot_grama',grammar_total print 'tot_struct',struct_total print 'ans = '," ".join(answer.split()) total = struct_total+grammar_total print 'total = ',total return render_template('level3_N_I_grammar_spelling.html ' ,ans = answer, qus = question ,tot= total, struc_tot = struct_total ,grammar_tot=grammar_total,post = name , add = address ,statN = statusN, statI = statusI , date = showdate , time = showtime , venue = showvenue, original = original_text, fixed = fixed_text ) @app.route('/structure_evaluation',methods=['POST'] ) def structure_evaluation(): answer = request.form['answer'] question = request.form['question'] struct_total = request.form['total'] grammar_total = request.form['grammar_total'] total_cal = request.form['total_val'] name = request.form['name'] address = request.form['address'] statusN = request.form['statusN'] statusI = request.form['statusI'] showdate = request.form['showdate'] showtime = request.form['showtime'] showvenue = request.form['showvenue'] return render_template('level3_Notice_Invitation_evaluation.html',ans = answer, qus = question , total = total_cal,tot = struct_total ,gramm_tot = grammar_total, post = name , add = address ,statN = statusN, statI = statusI , date = showdate , time = showtime , venue = showvenue ) # ------------------------ Level 3 - Notice/Invitation ----------------------------------------------- # #--------------------------------Grammar------------------------- #Display Add grammar question @app.route('/add_grammar_questions') def add_grammar_questions(): return render_template('add_grammar_questions.html') # Add grammar questions @app.route('/save_grammar', methods=['POST']) def save_grammar(): question1 = request.form['txtQuestion1'] question2 = request.form['txtQuestion2'] question3 = request.form['txtQuestion3'] type1 = request.form['type1'] type2 = request.form['type2'] type3 = request.form['type3'] author = session['username'] question1_exist = False question2_exist = False question3_exist = False cursor = db.cursor() sql = """SELECT * FROM level_3_grammar WHERE question=%s OR question=%s OR question=%s""" try: # Execute the SQL command cursor.execute(sql, [question1, question2, question3]) result = cursor.fetchall() if result: for row in result: if row[1] == question1: question1_exist = True elif row[1] == question2: question2_exist = True elif row[1] == question3: question3_exist = True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors = {'question1': question1, 'question2': question2, 'question3': question3, 'type1': type1, 'type2': type2, 'type3': type3, 'question1Status': question1_exist, 'question2Status': question2_exist, 'question3Status': question3_exist} return render_template('add_grammar_questions.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() rows = [] if question1 != '' and type1 != '': rows.append((question1, type1, author)) if question2 != '' and type2 != '': rows.append((question2, type2, author)) if question3 != '' and type3 != '': rows.append((question3, type3, author)) cursor = db.cursor() sql = """INSERT INTO level_3_grammar (question,type,author) VALUES(%s,%s,%s)""" try: # Execute the SQL command cursor.executemany(sql, rows) # Commit your changes in the database db.commit() #flash('Question successfully added !') alert(text='Questions Added Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return redirect(url_for('add_grammar_questions')) #---------------update grammar question------ #--- View all grammar questions----- @app.route('/Update_grammar_questions') def Update_grammar_questions(): cursor = db.cursor() sql = """SELECT qno,question,type FROM level_3_grammar where author=%s""" try: # Execute the SQL command cursor.execute(sql, [session['username']]) #fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return render_template('Update_grammar_questions.html', data=query) ## Edit grammar question ## @app.route('/edit_grammar', methods=['GET', 'POST']) def edit_grammar(): qno = request.args['qno'] cursor = db.cursor() sql = """SELECT * FROM level_3_grammar where qno=%s""" try: # Execute the SQL command cursor.execute(sql, [qno]) # fetch a single row using fetchone() method. query = cursor.fetchall() for row in query: question = row[1] type = row[2] except: db.rollback() return json.dumps(dict(question=question, type=type)) ## Save updated grammar question data in the database ## @app.route('/save_edited_grammar', methods=['POST']) def save_edited_grammar(): qno = request.form['qno'] question = request.form['question'] type = request.form['type'] cursor = db.cursor() sql = """UPDATE level_3_grammar SET question=%s,type=%s WHERE qno=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [question, type, qno]) db.commit() # fetch a single row using fetchone() method. except: db.rollback() return redirect(url_for('Update_grammar_questions')) ## Delete grammar question ## @app.route('/delete_grammar/', methods=['GET']) def delete_grammar(): qno = request.args.get('qNo') cursor = db.cursor() sql = """delete from level_3_grammar where qno=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [qno]) # fetch a single row using fetchone() method. db.commit() except: db.rollback() return redirect(url_for('Update_grammar_questions')) #--------display grammar questions--------------------------- @app.route('/level3_grammar_activity') def level3_grammar_activity(): print 'heloo = ', Present_Tense() print Past_Tense() print Present_Continuous() print Past_Continuous() print Future_Tense() print Future_Continuous() return render_template('level3_grammar_activity.html', data_Present_Tense=Present_Tense(), data_Past_Tense=Past_Tense(), data_Future_Tense=Future_Tense(), data_Present_Continuous=Present_Continuous(), data_Past_Continuous=Past_Continuous(), data_Future_Continuous=Future_Continuous()) def Present_Tense(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_3_grammar where type='Present Tense' order by rand() limit 2 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() except: # Rollback in case there is any error db.rollback() request.form return query # get past tense data def Past_Tense(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_3_grammar where type='Past Tense' order by rand() limit 2 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() except: # Rollback in case there is any error db.rollback() request.form return query # get Future tense data def Future_Tense(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_3_grammar where type='Future Tense' order by rand() limit 2 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() except: # Rollback in case there is any error db.rollback() request.form return query #get Present Continuous Tense data def Present_Continuous(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_3_grammar where type='Present Continuous Tense' order by rand() limit 2 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() except: # Rollback in case there is any error db.rollback() request.form return query #get Past Continuous Tense data def Past_Continuous(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_3_grammar where type='Past Continuous Tense' order by rand() limit 2 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() except: # Rollback in case there is any error db.rollback() request.form return query #get Future Continuous Tense data def Future_Continuous(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_3_grammar where type='Future Continuous Tense' order by rand() limit 2 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() except: # Rollback in case there is any error db.rollback() request.form return query #---------------------------Evaluate grammar question answers----- @app.route('/evaluate_level3_grammar', methods=['POST']) def evaluate_level3_grammar(): count = 0 data_set = [] question1 = request.form['question1'] question3 = request.form['question3'] question4 = request.form['question4'] answer1 = request.form['txtAnswerSet1'] answer3 = request.form['txtAnswerSet3'] answer4 = request.form['txtAnswerSet4'] past_participle1 = '' past_participle2 = '' past_participle3 = '' past_participle4 = '' present_simple1='' present_simple2='' present_simple3='' present_simple4='' present_simple5='' present2 = '' present3 = '' present4 = '' past_plural_1 = '' past_plural_2 = '' past_singular_1 = '' past_singular_2 = '' Future_tense1 = '' Future_tense2 = '' Future_continous_1='' Future_continous_2='' present_participle1 = '' present_participle2 = '' present_participle3 = '' present_participle4 = '' present_participle5 = '' present_participle6 = '' text = nltk.word_tokenize(question1) tagged_sent = nltk.pos_tag(text) print tagged_sent print'#--------------------present tense----------------------------------------' if [word for word, pos in tagged_sent if pos == '#']: tok = [word for word, pos in tagged_sent if pos == '#'] token = tok[0], '#' # to get the current position of '#' current_position = tagged_sent.index(token) # PRP Personal pronoun and RB Adverb pnoun= tagged_sent[current_position - 1][0] pnoun2=tagged_sent[current_position - 2][0] ptag=tagged_sent[current_position - 1][1] ptag2=tagged_sent[current_position - 2][1] print 'pnoun = ',pnoun if ptag == 'RB': print 'pnoun2 = ',pnoun2 if pnoun2 == 'I' or pnoun2=='We' or pnoun2=='You' or pnoun2=='They' or ptag2=='NNS': verb = tagged_sent[current_position + 2][0] present_simple1 = en.verb.present(verb, person=1) elif pnoun2=='He' or pnoun2=='She' or pnoun2=='It' or ptag2=='NN' or ptag2=='NNP': print 'pnoun2 = ',pnoun2 verb = tagged_sent[current_position + 2][0] # simple present tense present_simple2 = en.verb.present(verb, person=3) elif ptag =='NNP' or ptag=='NNS': if pnoun == 'I' or pnoun=='We' or pnoun=='You' or pnoun=='They' or ptag=='NNS': verb = tagged_sent[current_position + 2][0] present_simple1 = en.verb.present(verb, person=1) elif pnoun=='He' or pnoun=='She' or pnoun=='It' or ptag=='NN' or ptag=='NNP': verb = tagged_sent[current_position + 2][0] # simple present tense present_simple2 = en.verb.present(verb, person=3) elif [word for word, pos in tagged_sent if pos == 'VBP']: tok = [word for word, pos in tagged_sent if pos == 'VBP'] token = tok[0], 'VBP' current_position = tagged_sent.index(token) pnoun= tagged_sent[current_position - 1][0] ptag=tagged_sent[current_position - 1][1] print 'pnoun = ',pnoun # Verb, non-2nd person singular if pnoun== 'You' or pnoun=='We' or pnoun=='They' or pnoun=='These' or pnoun=='Those' or ptag=='NNS' : verb = tagged_sent[current_position + 2][0] present_simple3 = en.verb.present(verb, person=2) # Verb, non-3rd person singular elif pnoun == 'He' or pnoun=='She' or pnoun=='It'or pnoun=='This' or pnoun=='That' or ptag=='NN' : verb = tagged_sent[current_position + 2][0] present_simple4= en.verb.present(verb, person=3) elif pnoun == 'I': verb=tagged_sent[current_position+2][0] print verb if verb=='be': present_t='am' present_simple5 =present_t else: present_t=en.verb.present(verb) present_simple5 =present_t if present_simple1 == answer1: count = count + 1 print 'Correct present1' elif present_simple2 == answer1: count = count + 1 print 'Correct present2' elif present_simple3 == answer1: count = count + 1 print 'Correct present3' elif present_simple4 == answer1: count = count + 1 print 'Correct present4' elif present_simple5 == answer1: count = count + 1 print 'Correct present5' else: print 'Wrong presentx' else: print 'Wrong Answer' print '# --------------past tense-----------------------' question2 = request.form['question2'] answer2 = request.form['txtAnswerSet2'] text = nltk.word_tokenize(question2) tagged_sent = nltk.pos_tag(text) print tagged_sent if [word for word, pos in tagged_sent if pos == '#']: tok = [word for word, pos in tagged_sent if pos == '#'] token = tok[0], '#' # to get the current position of '#' current_position = tagged_sent.index(token) pnoun= tagged_sent[current_position - 1][0] ptag=tagged_sent[current_position - 1][1] print 'pnoun = ',pnoun #NN-Noun, singular or mass,NNP-Proper noun, singular if pnoun == 'I' or pnoun=='He' or pnoun=='he' or pnoun=='She' or pnoun=='she' or pnoun=='It' or pnoun=='it' or ptag=='NNP' or ptag=='NN': verb = tagged_sent[current_position + 2][0] past_singular_1 = en.verb.past(verb, person=3) #RB-Adverb,NNS-Plural,Verb, 3rd person singular present elif pnoun=='We' or pnoun=='we' or pnoun=='You' or pnoun=='you' or pnoun=='They' or pnoun=='they'or pnoun=='Those' or ptag=='NNS' or ptag== 'VBZ'or ptag=='RB': verb = tagged_sent[current_position + 2][0] past_plural_1 = en.verb.past(verb, person=2) elif [word for word, pos in tagged_sent if pos == 'VBP']: tok = [word for word, pos in tagged_sent if pos == 'VBP'] token = tok[0], 'VBP' current_position = tagged_sent.index(token) pnoun= tagged_sent[current_position - 1][0] ptag=tagged_sent[current_position - 1][1] if pnoun=='We' or pnoun=='we' or pnoun=='You' or pnoun=='you' or pnoun=='They' or pnoun=='they'or pnoun=='Those' or ptag=='NNS' or ptag== 'VBZ': verb = tagged_sent[current_position + 2][0] past_plural_2 = en.verb.past(verb, person=2) # Verb, non-3rd past singular elif pnoun == 'I' or pnoun=='He' or pnoun=='he' or pnoun=='She' or pnoun=='she' or pnoun=='It' or pnoun=='it' or ptag=='NNP' or ptag=='NN' or ptag=='RB': verb = tagged_sent[current_position + 2][0] past_singular_2 = en.verb.past(verb, person=3) if past_singular_1 == answer2: count = count + 1 print 'Correct1' elif past_singular_2 == answer2: count = count + 1 print 'Correct 2' elif past_plural_1 == answer2: count = count + 1 print 'Correct ' elif past_plural_2 == answer2: count = count + 1 print 'Correct ' else: print 'Wrong presentx' print '# ----------Present Continuous--------------------------------------' text = nltk.word_tokenize(question3) tagged_sent = nltk.pos_tag(text) print tagged_sent if [word for word, pos in tagged_sent if pos == '#']: tok = [word for word, pos in tagged_sent if pos == '#'] token = tok[0], '#' # to get the current position of 'VBP' current_position = tagged_sent.index(token) pnoun= tagged_sent[current_position - 1][0] ptag=tagged_sent[current_position - 1][1] print 'pnoun = ',pnoun if pnoun == 'She' or pnoun=='she' or pnoun=='He' or pnoun=='he' or pnoun=='It' or pnoun=='it' or ptag=='NN' or ptag=='NNP': verb = tagged_sent[current_position + 2][0] # present continuous tense present1 = en.verb.present_participle(verb) present_participle1 = 'is ' + present1 elif pnoun == 'We' or pnoun=='we' or pnoun=='You' or pnoun=='you' or pnoun=='They' or pnoun=='they' or ptag=='NNS': verb = tagged_sent[current_position + 2][0] # present continuous tense present2 = en.verb.present_participle(verb) present_participle2 = 'are ' + present2 elif pnoun == 'I': verb = tagged_sent[current_position + 2][0] # present continuous tense present3 = en.verb.present_participle(verb) present_participle3 = 'am ' + present3 else: print 'wrong' elif [word for word, pos in tagged_sent if pos == 'VBP']: tok = [word for word, pos in tagged_sent if pos == 'VBP'] token = tok[0], 'VBP' # to get the current position of 'VBP' current_position = tagged_sent.index(token) pnoun= tagged_sent[current_position - 1][0] ptag=tagged_sent[current_position - 1][1] print 'pnoun = ',pnoun if pnoun == 'She' or pnoun=='she' or pnoun=='He' or pnoun=='he' or pnoun=='It' or pnoun=='it' or ptag=='NN' or ptag=='NNP': verb = tagged_sent[current_position + 2][0] # present continuous tense present4 = en.verb.present_participle(verb) present_participle4 = 'is ' + present4 elif pnoun=='We' or pnoun=='we' or pnoun=='You' or pnoun=='you' or pnoun=='They' or pnoun=='they' or ptag=='NNS': verb = tagged_sent[current_position + 2][0] # present continuous tense present5 = en.verb.present_participle(verb) present_participle5 = 'are ' + present5 elif pnoun=='I': verb = tagged_sent[current_position + 2][0] # present continuous tense present6 = en.verb.present_participle(verb) present_participle6 = 'am ' + present6 else: print 'wrong' else: print 'Wrong Present Continuous' if present_participle1 == answer3: count = count + 1 print 'Correct1' elif present_participle2 == answer3: count = count + 1 print 'Correct 2' elif present_participle3 == answer3: count = count + 1 print 'Correct ' elif present_participle4 == answer3: count = count + 1 print 'Correct ' elif present_participle5 == answer3: count = count + 1 print 'Correct ' elif present_participle6 == answer3: count = count + 1 print 'Correct ' else: print 'Wrong presentx' print'# -----------------------------Past continuous tense------------------------------------------------------' text = nltk.word_tokenize(question4) tagged_sent = nltk.pos_tag(text) print tagged_sent if [word for word, pos in tagged_sent if pos == '#']: tok = [word for word, pos in tagged_sent if pos == '#'] token = tok[0], '#' # to get the current position of 'VBP' current_position = tagged_sent.index(token) pnoun= tagged_sent[current_position - 1][0] ptag=tagged_sent[current_position - 1][1] print 'pnoun = ',pnoun if pnoun == 'She' or pnoun=='she' or pnoun=='He' or pnoun=='he' or pnoun=='It' or pnoun=='I' or pnoun=='it' or ptag=='NN' or ptag=='NNP': verb = tagged_sent[current_position + 2][0] past = en.verb.present_participle(verb) past_participle1 = 'was ' + past print 'x' elif pnoun == 'We' or pnoun=='we' or pnoun=='You' or pnoun=='you' or pnoun=='They' or pnoun=='they' or ptag=='NNS': verb = tagged_sent[current_position + 2][0] # past continuous tense past = en.verb.present_participle(verb) past_participle2 = 'were ' + past print 'y' else: print 'error' elif [word for word, pos in tagged_sent if pos == 'VBP']: tok = [word for word, pos in tagged_sent if pos == 'VBP'] token = tok[0], 'VBP' # to get the current position of 'VBP' current_position = tagged_sent.index(token) pnoun= tagged_sent[current_position - 1][0] ptag=tagged_sent[current_position - 1][1] if pnoun == 'She' or pnoun=='I' or pnoun=='she' or pnoun=='He' or pnoun=='he' or pnoun=='It' or pnoun=='it' or ptag=='NN' or ptag=='NNP': verb = tagged_sent[current_position + 2][0] past = en.verb.present_participle(verb) past_participle3 = 'was ' + past print 'z' elif pnoun == 'We' or pnoun=='we' or pnoun=='You' or pnoun=='you' or pnoun=='They' or pnoun=='they' or ptag=='NNS': verb = tagged_sent[current_position + 2][0] past = en.verb.present_participle(verb) past_participle4 = 'were ' + past print 'zz' else: print 'Wrong past Continuous' if past_participle1 == answer4: count = count + 1 print 'Correct1' elif past_participle2 == answer4: count = count + 1 print 'Correct 2' elif past_participle3 == answer4: count = count + 1 print 'Correct ' elif past_participle4 == answer4: count = count + 1 print 'Correct ' else: print 'Wrong presentx' print'#--------------Future tense---------------------------------------------------#' question5 = request.form['question5'] answer5 = request.form['txtAnswerSet5'] text = nltk.word_tokenize(question5) tagged_sent = nltk.pos_tag(text) print tagged_sent if [word for word, pos in tagged_sent if pos == '#']: tok = [word for word, pos in tagged_sent if pos == '#'] token = tok[0], '#' # to get the current position of '#' current_position = tagged_sent.index(token) verb = tagged_sent[current_position + 2][0] Future1 = en.verb.infinitive(verb) Future_tense1 = 'will ' + Future1 elif [word for word, pos in tagged_sent if pos == 'VBP']: tok = [word for word, pos in tagged_sent if pos == 'VBP'] token = tok[0], 'VBP' # to get the current position of '#' current_position = tagged_sent.index(token) verb = tagged_sent[current_position + 2][0] Future2 = en.verb.infinitive(verb) Future_tense2 = 'will ' + Future2 if Future_tense1 == answer5: count = count + 1 print 'Correct1' elif Future_tense2 == answer5: count = count + 1 print 'Correct 2' else: print 'Wrong presentx' print'#-----------------------Future Continuous Tense-------------------------' question6 = request.form['question6'] answer6 = request.form['txtAnswerSet6'] text = nltk.word_tokenize(question6) tagged_sent = nltk.pos_tag(text) print tagged_sent if [word for word, pos in tagged_sent if pos == '#']: tok = [word for word, pos in tagged_sent if pos == '#'] token = tok[0], '#' # to get the current position of '#' current_position = tagged_sent.index(token) verb = tagged_sent[current_position + 2][0] Future_c = en.verb.present_participle(verb) Future_continous_1 = 'will be ' + Future_c elif [word for word, pos in tagged_sent if pos == 'VBP']: tok = [word for word, pos in tagged_sent if pos == 'VBP'] token = tok[0], 'VBP' # to get the current position of '#' current_position = tagged_sent.index(token) verb = tagged_sent[current_position + 2][0] Future4 = en.verb.present_participle(verb) Future_continous_2 = 'will be ' + Future4 print 'count:',count #return 'sucess' if Future_continous_1 == answer6: count = count + 1 print 'Correct1' elif Future_continous_2 == answer6: count = count + 1 print 'Correct 2' else: print 'Wrong presentx' data_set = {'question1':question1 ,'question2':question2,'question3':question3,'question4':question4,'question5':question5,'question6':question6, 'answer1': answer1,'answer2': answer2,'answer3': answer3,'answer4': answer4,'answer5': answer5,'answer6': answer6, 'past_singular_1': past_singular_1,'past_plural_1': past_plural_1,'past_plural_2':past_plural_2,'past_singular_2': past_singular_2, 'present_participle1':present_participle1,'present_participle2':present_participle2,'present_participle3':present_participle3, 'present_participle4':present_participle4,'present_participle5':present_participle5,'present_participle6':present_participle6, 'Future_continous_1':Future_continous_1,'Future_continous_2':Future_continous_2,'Future_tense1':Future_tense1,'Future_tense2':Future_tense2, 'past_participle1':past_participle1,'past_participle2':past_participle2,'past_participle3':past_participle3,'past_participle4':past_participle4, 'count':count,'present_simple1':present_simple1,'present_simple2':present_simple2,'present_simple3':present_simple3,'present_simple4':present_simple4,'present_simple5':present_simple5} return render_template('level3_grammar_evaluate.html', data_set=data_set) #return redirect(url_for('level3_grammar_activity')) #--------------------------------Grammar------------------------- ## ------------------------------------- Level 4 ----------------------------------------------- ## # ----------------------- Level 4 - Dialog ---------------------------------------------------------- ## View Add Dialog Questions for level 4 ## @app.route('/level4_add_dialog_questions') def level4_add_dialog_questions(): return render_template('level4_add_dialog_questions.html') ## Add dialog question for level 4 ## @app.route('/level4_save_dialog_question', methods=['POST']) def level4_save_dialog_question(): if request.method == 'POST': question1 = request.form['question1'] answer1 = request.form['answer1'] question2 = request.form['question2'] answer2 = request.form['answer2'] question3 = request.form['question3'] answer3 = request.form['answer3'] question4 = request.form['question4'] answer4 = request.form['answer4'] question5 = request.form['question5'] answer5 = request.form['answer5'] question6 = request.form['question6'] author = session['username'] cursor = db.cursor() sql = """INSERT INTO level4_dialogs (q1,a1,q2,a2,q3,a3,q4,a4,q5,a5,q6,author) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""" try: # Execute the SQL command cursor.execute(sql, [question1, answer1, question2, answer2, question3, answer3, question4, answer4, question5, answer5, question6, author]) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() alert(text='Question Added Successfully !', title='English Buddy', button='OK') return redirect(url_for('level4_add_dialog_questions')) ## Edit level 4 dialog questions ## @app.route('/edit_level4_dialog', methods=['GET', 'POST']) def edit_level4_dialog(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """SELECT * FROM level4_dialogs WHERE author=%s and qNo=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username'], qNo]) # fetch rows using fetchall() method. result = cursor.fetchall() for row in result: q1 = row[1] a1 = row[2] q2 = row[3] a2 = row[4] q3 = row[5] a3 = row[6] q4 = row[7] a4 = row[8] q5 = row[9] a5 = row[10] q6 = row[11] except: db.rollback() return json.dumps(dict(q1=q1, q2=q2, q3=q3, q4=q4, q5=q5, q6=q6, a1=a1, a2=a2, a3=a3, a4=a4, a5=a5)) ## Save edited level4 dialog question ## @app.route('/save_edited_level4_dialog_question', methods=['POST']) def save_edited_level4_dialog_question(): if request.method == 'POST': qNo = request.form['qNo'] question1 = request.form['question1'] answer1 = request.form['answer1'] question2 = request.form['question2'] answer2 = request.form['answer2'] question3 = request.form['question3'] answer3 = request.form['answer3'] question4 = request.form['question4'] answer4 = request.form['answer4'] question5 = request.form['question5'] answer5 = request.form['answer5'] question6 = request.form['question6'] cursor = db.cursor() sql = """UPDATE level4_dialogs SET q1=%s,q2=%s,q3=%s,q4=%s,q5=%s,q6=%s,a1=%s,a2=%s,a3=%s,a4=%s,a5=%s WHERE qNo=%s""" try: # Execute the SQL command cursor.execute(sql, [question1, question2, question3, question4, question5, question6, answer1, answer2, answer3, answer4, answer5, qNo]) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() url='/display_dialog_questions/?level=level4' return redirect(url) ## Delete dialog questions ## @app.route('/delete_level4_dialog_questions/', methods=['GET']) def delete_level4_dialog_questions(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """DELETE FROM level4_dialogs where qNo=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [qNo]) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() url='/display_dialog_questions/?level=level4' return redirect(url) ## Level 4 Dialog Activity ## @app.route('/level4_dialogs_activity') def level4_dialogs_activity(): cursor = db.cursor() sql = """SELECT * FROM level4_dialogs order by rand() limit 1""" try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return render_template('level4_dialogs_activity.html', data=result) ## Level 4 Dialog Evaluate Answers ## @app.route('/evaluate_level4_dialog_activity', methods=['POST']) def evaluate_level4_dialog_activity(): qNo=request.form['qNo'] question_1=request.form['question1'].strip() question_2=request.form['question2'].strip() question_3=request.form['question3'].strip() question_4=request.form['question4'].strip() question_5=request.form['question5'].strip() if request.form['question6'] != None: question_6=request.form['question6'].strip() answer_1=request.form['one'].strip() answer_2=request.form['two'].strip() answer_3=request.form['three'].strip() answer_4=request.form['four'].strip() answer_5=request.form['five'].strip() # for keyword in keywordClass.test(question_1): # if keyword in answer_1: # count=count+1 # print(count) # print(count) # # for keyword in en.content.keywords(question_1): # if keyword in answer_1: # count=count+1 # print count # # Answer 1 evaluation # answer1_content_marks = 0 # question1_key_words = en.content.keywords(question_1) # # answer1_key_words = en.content.keywords(answer_1) # answer1_key_words = answer_1.split(" ") # # print question1_key_words # print answer1_key_words # # for word in question1_key_words: # for answer in answer1_key_words: # if (answer.upper().find(word[1])!=-1) or (answer.lower().find(word[1])!=-1): # answer1_content_marks=answer1_content_marks+1 # print "Answer 1 Content Marks : "+str(answer1_content_marks) # # # # Answer 2 evaluation # answer2_content_marks = 0 # question2_key_words = en.content.keywords(question_2) # answer2_key_words = answer_2.split(" ") # # print question2_key_words # print answer2_key_words # # for word in question2_key_words: # for answer in answer2_key_words: # if (answer.upper().find(word[1])!=-1) or (answer.lower().find(word[1])!=-1): # answer2_content_marks=answer2_content_marks+1 # print "Answer 2 Content Marks : "+str(answer2_content_marks) # # # # Answer 3 evaluation # answer3_content_marks = 0 # question3_key_words = en.content.keywords(question_3) # answer3_key_words = answer_3.split(" ") # # print question3_key_words # print answer3_key_words # # for word in question3_key_words: # for answer in answer3_key_words: # if (answer.upper().find(word[1])!=-1) or (answer.lower().find(word[1])!=-1): # answer3_content_marks=answer3_content_marks+1 # print "Answer 3 Content Marks : "+str(answer3_content_marks) # # # # Answer 4 evaluation # answer4_content_marks = 0 # question4_key_words = en.content.keywords(question_4) # answer4_key_words = answer_4.split(" ") # # print question4_key_words # print answer4_key_words # # for word in question4_key_words: # for answer in answer4_key_words: # if (answer.upper().find(word[1])!=-1) or (answer.lower().find(word[1])!=-1): # answer4_content_marks=answer4_content_marks+1 # print "Answer 4 Content Marks : "+str(answer4_content_marks) # # # # Answer 5 evaluation # answer5_content_marks = 0 # question5_key_words = en.content.keywords(question_5) # answer5_key_words = answer_5.split(" ") # # print question5_key_words # print answer5_key_words # # for word in question5_key_words: # for answer in answer5_key_words: # if (answer.upper().find(word[1])!=-1) or (answer.lower().find(word[1])!=-1): # answer5_content_marks=answer5_content_marks+1 # print "Answer 5 Content Marks : "+str(answer5_content_marks) # return "Answer 1 Content Marks : " + str(answer1_content_marks) + " | " + "Answer 2 Content Marks : " + str( # answer2_content_marks) + " | " + "Answer 3 Content Marks : " + str( # answer3_content_marks) + " | " + "Answer 4 Content Marks : " + str(answer4_content_marks)+ " | " +"Answer 5 Content Marks : "+str(answer5_content_marks) a1_status = 0 a2_status = 0 a3_status = 0 a4_status = 0 a5_status = 0 marks = 0 a1_wrong_grammar = '' a2_wrong_grammar = '' a3_wrong_grammar = '' a4_wrong_grammar = '' a5_wrong_grammar = '' a1_corrected_grammar = '' a2_corrected_grammar = '' a3_corrected_grammar = '' a4_corrected_grammar = '' a5_corrected_grammar = '' conv = Ansi2HTMLConverter() if answer_1 != '': # Content Checking a1_status = DialogClass.check(question_1, answer_1) if a1_status == 0: a1_status = DialogClass.check(answer_1, question_2) # Tence Checking # if TenseClass.check_tense(question_1,answer_1): # Grammar Checking grammar_status = ginger.main(answer_1) if grammar_status[1] =="Good English": if a1_status != 0: marks = marks + 2 a1_wrong_grammar = 'none' a1_corrected_grammar = 'none' else: a1_wrong_grammar = conv.convert(grammar_status[0]) a1_corrected_grammar = conv.convert(grammar_status[1]) if answer_2 != '': a2_status = DialogClass.check(question_2, answer_2) if a2_status == 0: a2_status = DialogClass.check(answer_2, question_3) grammar_status = ginger.main(answer_2) if grammar_status[1] =="Good English": if a2_status != 0: marks = marks + 2 a2_wrong_grammar = 'none' a2_corrected_grammar = 'none' else: a2_wrong_grammar = conv.convert(grammar_status[0]) a2_corrected_grammar = conv.convert(grammar_status[1]) if answer_3 != '': a3_status = DialogClass.check(question_3, answer_3) if a3_status == 0: a3_status = DialogClass.check(answer_3, question_4) grammar_status = ginger.main(answer_3) if grammar_status[1] =="Good English": if a3_status != 0: marks = marks + 2 a3_wrong_grammar = 'none' a3_corrected_grammar = 'none' else: a3_wrong_grammar = conv.convert(grammar_status[0]) a3_corrected_grammar = conv.convert(grammar_status[1]) if answer_4 != '': a4_status = DialogClass.check(question_4, answer_4) if a4_status == 0: a4_status = DialogClass.check(answer_4, question_5) grammar_status = ginger.main(answer_4) if grammar_status[1] =="Good English": if a4_status != 0: marks = marks + 2 a4_wrong_grammar = 'none' a4_corrected_grammar = 'none' else: a4_wrong_grammar = conv.convert(grammar_status[0]) a4_corrected_grammar = conv.convert(grammar_status[1]) if answer_5 != '': a5_status = DialogClass.check(question_5, answer_5) if a5_status == 0 and question_6 != '': a5_status = DialogClass.check(answer_5, question_6) grammar_status = ginger.main(answer_5) if grammar_status[1] =="Good English": if a5_status != 0: marks = marks + 2 a5_wrong_grammar = 'none' a5_corrected_grammar = 'none' else: a5_wrong_grammar = conv.convert(grammar_status[0]) a5_corrected_grammar = conv.convert(grammar_status[1]) data_array = {'pa1': answer_1, 'pa2': answer_2, 'pa3': answer_3, 'pa4': answer_4, 'pa5': answer_5, 'a1_status': a1_status, 'a2_status': a2_status, 'a3_status': a3_status, 'a4_status': a4_status, 'a5_status': a5_status, 'marks': marks, 'a1_wrong_grammar':a1_wrong_grammar, 'a1_corrected_grammar':a1_corrected_grammar, 'a2_wrong_grammar':a2_wrong_grammar, 'a2_corrected_grammar':a2_corrected_grammar, 'a3_wrong_grammar':a3_wrong_grammar, 'a3_corrected_grammar':a3_corrected_grammar, 'a4_wrong_grammar':a4_wrong_grammar, 'a4_corrected_grammar':a4_corrected_grammar, 'a5_wrong_grammar':a5_wrong_grammar, 'a5_corrected_grammar':a5_corrected_grammar} cursor = db.cursor() sql = """SELECT * FROM level4_dialogs WHERE qNo=%s""" try: # Execute the SQL command select all rows cursor.execute(sql,[qNo]) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return render_template('level4_dialogs_activity.html', answer_data=data_array, data=result) # ------------------------ Level 4 - Note ----------------------------------------------- # #Darani ## Note Questions for level 1 ## @app.route('/add_note_questions') def add_note_questions(): return render_template('add_note_questions.html') ## Add note question for level 1 ## @app.route('/save_note_questions', methods=['POST']) def save_note_questions(): if request.method == 'POST': question1 = request.form['question_1'] question2 = request.form['question_2'] question3 = request.form['question_3'] author = session['username'] question1_exist=False question2_exist=False question3_exist=False cursor = db.cursor() sql = """SELECT * FROM level4_note WHERE question=%s OR question=%s OR question=%s""" try: # Execute the SQL command cursor.execute(sql, [question1, question2, question3]) result = cursor.fetchall() if result: for row in result: if row[1]==question1: question1_exist=True elif row[1]==question2: question2_exist=True elif row[1]==question3: question3_exist=True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors={'question1':question1, 'question2':question2, 'question3':question3, 'question1Status':question1_exist, 'question2Status':question2_exist, 'question3Status':question3_exist} return render_template('add_note_questions.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() rows = [] if question1 != '' : rows.append((question1, author)) if question2 != '' : rows.append((question2, author)) if question3 != '' : rows.append((question3, author)) print rows cursor = db.cursor() sql = """INSERT INTO level4_note (question,author) VALUES(%s,%s)""" try: # Execute the SQL command print cursor.executemany(sql, rows) # Commit your changes in the database db.commit() #flash('Question successfully added !') alert(text='Question Added Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return redirect(url_for('add_note_questions')) ## Display all note questions ## @app.route('/display_note_questions') def display_note_questions(): cursor = db.cursor() sql = """SELECT * FROM level4_note where author=%s """ try: # Execute the SQL command select all rows cursor.execute(sql, [session['username']]) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return render_template('display_note_questions.html', data=result) ## Edit note questions ## @app.route('/edit_note', methods=['GET', 'POST']) def edit_note(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """SELECT * FROM level4_note where author=%s and noteId=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username'], qNo]) # fetch rows using fetchall() method. result = cursor.fetchall() for row in result: question = row[1] except: db.rollback() return json.dumps(dict(question=question)) ## Save edited note question for level 1 ## @app.route('/save_edited_note_question', methods=['POST']) def save_edited_note_question(): if request.method == 'POST': qNo = request.form['qNo'] question = request.form['question'] author = session['username'] #print author cursor = db.cursor() sql = """UPDATE level4_note SET question=%s WHERE noteId=%s""" try: # Execute the SQL command cursor.execute(sql, [question,qNo]) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_note_questions')) ## Delete note questions ## @app.route('/delete_note_questions/', methods=['GET']) def delete_note_questions(): qNo = request.args.get('qNo') cursor = db.cursor() sql = """DELETE FROM level4_note where noteId=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [qNo]) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_note_questions')) ## Level 3 note Activity NEW## @app.route('/level4_Note') def level4_Note(): cursor = db.cursor() sql = """SELECT * FROM level4_note order by rand() limit 1""" try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. result = cursor.fetchall() except: # Rollback in case there is any error db.rollback() return render_template('level4_Note.html', data=result) ## Level 3 evaluate note Activity NEW## @app.route('/evaluate_level4_Note' , methods=['POST']) def evaluate_level4_Note(): answer = request.form['answer'] question = request.form['question'] struct_total = 0 grammar_total =0 status_write = '' status_receiver = '' status_your = '' sent_count = 0 sentences_qus= sent_tokenize(answer) for sentence_qus in sentences_qus: sent_count = sent_count+1 count1 = note.word_count(answer,question) count2,status_receiver = note.note_receiver(answer) count3,status_write,status_your = note.note_writer(answer) count4 = note.note_body(answer,question) if sent_count <= 2: struct_total = 0.0 else : struct_total = count1+count2+count3+count4 conv =Ansi2HTMLConverter() array=[] array=ginger.main(" ".join(answer.split())) original_text=conv.convert(array[0]) fixed_text=conv.convert(array[1]) wrong_count = array[2] if fixed_text=='Good English..!!' or wrong_count <=2 : grammar_total = 2.5 elif wrong_count >2 and wrong_count <= 4 : grammar_total = 1.0 elif sent_count <= 2 : grammar_total = 0.0 else: grammar_total = 0.5 print 'wrong',wrong_count print 'tot_grama',grammar_total print 'tot_struct',struct_total print 'ans = '," ".join(answer.split()) total = struct_total+ grammar_total print 'total = ',total return render_template('level4_Note_grammar_spelling.html', ans = answer,qus = question,tot = total,struct_tot = struct_total,grammar_tot = grammar_total,stat_writer = status_write,stat_receiver = status_receiver,stat_your = status_your,original = original_text, fixed = fixed_text ) @app.route('/structure_evaluation_note',methods=['POST'] ) def structure_evaluation_note(): answer = request.form['answer'] question = request.form['question'] struct_total = request.form['total'] writer = request.form['writer'] receiver = request.form['receiver'] your = request.form['yours'] grammar_total = request.form['grammar_total'] total = request.form['total_val'] return render_template('level4_Note_evaluation.html',ans = answer,qus = question,tot = total,gramm_tot = grammar_total,struct_tot = struct_total,stat_writer = writer,stat_receiver = receiver,stat_your = your ) # ------------------------ Level 4 - Note ----------------------------------------------- # #-------------------------------CHAMIKA---------------------------------------------------------- #----------------level 4 Active Passive-CHAMIKA--------------- # Level 4 Active Passive @app.route('/level4_active_passive') def level4_active_passive(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_4_activepassive where type='Active Voice' order by rand() limit 3""" try: # Execute the SQL command cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() except: db.rollback() db.close() return render_template('level4_active_passive.html', data=query) # Level 4 Passive Active @app.route('/level4_passive_active') def level4_passive_active(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level_4_activepassive where type='Passive Voice' order by rand() limit 3""" try: # Execute the SQL command cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() except: db.rollback() db.close() return render_template('level4_passive_active.html', data=query) #Display Add active passive question @app.route('/add_active_passive_questions') def add_active_passive_questions(): return render_template('add_active_passive_questions.html') # Add active passive questions @app.route('/save_active_passive', methods=['POST']) def save_active_passive(): question1 = request.form['txtQuestion1'] question2 = request.form['txtQuestion2'] question3 = request.form['txtQuestion3'] type1 = request.form['type1'] type2 = request.form['type2'] type3 = request.form['type3'] author = session['username'] question1_exist = False question2_exist = False question3_exist = False cursor = db.cursor() sql = """SELECT * FROM level_4_activepassive WHERE question=%s OR question=%s OR question=%s""" try: # Execute the SQL command cursor.execute(sql, [question1, question2, question3]) result = cursor.fetchall() if result: for row in result: if row[1] == question1: question1_exist = True elif row[1] == question2: question2_exist = True elif row[1] == question3: question3_exist = True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors = {'question1': question1, 'question2': question2, 'question3': question3, 'type1': type1, 'type2': type2, 'type3': type3, 'question1Status': question1_exist, 'question2Status': question2_exist, 'question3Status': question3_exist} return render_template('add_active_passive_questions.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() rows = [] if question1 != '' and type1 != '': rows.append((question1, type1, author)) if question2 != '' and type2 != '': rows.append((question2, type2, author)) if question3 != '' and type3 != '': rows.append((question3, type3, author)) cursor = db.cursor() sql = """INSERT INTO level_4_activepassive (question,type,author) VALUES(%s,%s,%s)""" try: # Execute the SQL command cursor.executemany(sql, rows) # Commit your changes in the database db.commit() #flash('Question successfully added !') alert(text='Questions Added Successfully !', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return redirect(url_for('add_active_passive_questions')) #---------------update active passive question------ #--- View all active passive questions----- @app.route('/Update_active_passive') def Update_active_passive(): cursor = db.cursor() sql = """SELECT qno,question,type FROM level_4_activepassive where author=%s""" try: # Execute the SQL command cursor.execute(sql, [session['username']]) #fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return render_template('Update_active_passive.html', data=query) ## Edit active passive question ## @app.route('/edit_active_passive', methods=['GET', 'POST']) def edit_active_passive(): qno = request.args['qno'] cursor = db.cursor() sql = """SELECT * FROM level_4_activepassive where qno=%s""" try: # Execute the SQL command cursor.execute(sql, [qno]) # fetch a single row using fetchone() method. query = cursor.fetchall() for row in query: question = row[1] type = row[2] except: db.rollback() return json.dumps(dict(question=question, type=type)) ## Save active passive question data in the database ## @app.route('/save_edited_active_passive', methods=['POST']) def save_edited_active_passive(): qno = request.form['qno'] question = request.form['question'] type = request.form['type'] cursor = db.cursor() sql = """UPDATE level_4_activepassive SET question=%s,type=%s WHERE qno=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [question, type, qno]) db.commit() # fetch a single row using fetchone() method. except: db.rollback() return redirect(url_for('Update_active_passive')) ## Delete Active passive question ## @app.route('/delete_active_passive/', methods=['GET']) def delete_active_passive(): qno = request.args.get('qNo') cursor = db.cursor() sql = """delete from level_4_activepassive where qno=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [qno]) # fetch a single row using fetchone() method. db.commit() except: db.rollback() return redirect(url_for('Update_active_passive')) #----------------------Evaluate active passive-------------------------- # This is the fast Part of Speech tagger ############################################################################# brown_train = brown.tagged_sents(categories='news') regexp_tagger = nltk.RegexpTagger( [(r'^-?[0-9]+(.[0-9]+)?$', 'CD'), (r'(-|:|;)$', ':'), (r'\'*$', 'MD'), (r'(The|the|A|a|An|an)$', 'AT'), (r'.*able$', 'JJ'), (r'^[A-Z].*$', 'NNP'), (r'.*ness$', 'NN'), (r'.*ly$', 'RB'), (r'.*s$', 'NNS'), (r'.*ing$', 'VBG'), (r'.*ed$', 'VBD'), (r'.*', 'NN') ]) unigram_tagger = nltk.UnigramTagger(brown_train, backoff=regexp_tagger) bigram_tagger = nltk.BigramTagger(brown_train, backoff=unigram_tagger) ############################################################################# # This is the semi-CFG; Extend it according to your own needs ############################################################################# cfg = {} cfg["NNP"] = "NNP" cfg["NNP+NNP"] = "NNP" cfg["NN+NN"] = "NNI" cfg["NNI+NN"] = "NNI" cfg["JJ+JJ"] = "JJ" cfg["JJ+NN"] = "NNI" cfg["AT+NN"] = "NNT" cfg["AT+NNS"] = "NNS" cfg["AT+NNP"] = "NP" ############################################################################# class NPExtractor(object): def __init__(self, sentence): self.sentence = sentence # Split the sentence into single words/tokens def tokenize_sentence(self, sentence): tokens = nltk.word_tokenize(sentence) return tokens # Normalize brown corpus' tags ("NN", "NN-PL", "NNS" > "NN") def normalize_tags(self, tagged): n_tagged = [] for t in tagged: if t[1] == "NP-TL" or t[1] == "NP": n_tagged.append((t[0], "NNP")) continue if t[1].endswith("-TL"): n_tagged.append((t[0], t[1][:-3])) continue if t[1].endswith("S"): n_tagged.append((t[0], t[1][:-1])) continue n_tagged.append((t[0], t[1])) return n_tagged # Extract the main topics from the sentence def extract(self): tokens = self.tokenize_sentence(self.sentence) tags = self.normalize_tags(bigram_tagger.tag(tokens)) merge = True while merge: merge = False for x in range(0, len(tags) - 1): t1 = tags[x] t2 = tags[x + 1] key = "%s+%s" % (t1[1], t2[1]) value = cfg.get(key, '') if value: merge = True tags.pop(x) tags.pop(x) match = "%s %s" % (t1[0], t2[0]) pos = value tags.insert(x, (match, pos)) break matches = [] for t in tags: if t[1] == "NNP" or t[1] == "NNI" or t[1] == "NN" or t[1] == "NNS" or t[1] == "NP" or t[1] == "NNT": matches.append(t[0]) return matches @app.route('/evaluate_level4_active_passive', methods=['POST']) def evaluate_level4_active_passive(): sentence1 = request.form['question1'] answer1 = request.form['answer1'] answer2 = request.form['answer2'] answer3 = request.form['answer3'] sentence2 = request.form['question2'] sentence3 = request.form['question3'] count=0 p1='' p2='' p3='' p4='' p5='' p6='' p7='' p8='' s1='' s2='' s3='' s4='' s5='' s6='' s7='' s8='' t1='' t2='' t3='' t4='' t5='' t6='' t7='' t8='' print '---------------------------------1------------------------------------' text = nltk.word_tokenize(sentence1) tagged_sent = nltk.pos_tag(text) print 'tagged_sent:',tagged_sent np_extractor = NPExtractor(sentence1) result = np_extractor.extract() print "result:" print result sub = result[0] obj = result[-1] object = obj.capitalize() if [word for word, pos in tagged_sent if pos == 'NNP']: subject = sub.capitalize() else: subject = sub.lower() print "subject:" + subject print "object:" + object result_sent = nltk.pos_tag(result) print 'result_sent:',result_sent if [word for word, pos in tagged_sent if pos == 'VBD']: tok = [word for word, pos in tagged_sent if pos == 'VBD'] verb = ''.join(tok) past_participle = en.verb.past_participle(verb) if [word for word, pos in result_sent if pos == 'NNP' or pos =='NNI' or pos =='NNT' or pos =='NP']: print result_sent[-1][1] if result_sent[-1][1] == 'NNS': p1 = object + " were " + past_participle + " by " + subject + "." print 'p1: ' + p1 else: p2 = object + " was " + past_participle + " by " + subject + "." print 'p2: ' + p2 elif [word for word, pos in result_sent if pos == 'NNS']: print result_sent[-1][1] if result_sent[-1][1] == 'NNS': p3 = object + " were " + past_participle + " by " + subject + "." print 'p3: ' + p3 else: p4 = object + " was " + past_participle + " by " + subject + "." print 'p4: ' + p4 else: print'wrong' elif [word for word, pos in tagged_sent if pos == 'VBP']: tok = [word for word, pos in tagged_sent if pos == 'VBP'] verb = ''.join(tok) past_participle = en.verb.past_participle(verb) if [word for word, pos in result_sent if pos == 'NNP' or 'NNI' or 'NNT' or 'NP']: print result_sent[-1][1] if result_sent[-1][1] == 'NNS': p5 = object + " were " + past_participle + " by " + subject + "." print 'p5: ' + p5 else: p6 = object + " was " + past_participle + " by " + subject + "." print 'p6 :' + p6 elif [word for word, pos in result_sent if pos == 'NNS']: print result_sent[-1][1] if result_sent[-1][1] == 'NNS': p7 = object + " were " + past_participle + " by " + subject + "." print 'p7 :' + p7 else: p8 = object + " was " + past_participle + " by " + subject + "." print 'p8 :' + p8 else: print 'Wrongs' if answer1==p1: count=count+1 print 'correct1' elif answer1==p2: count=count+1 print 'correct2' elif answer1==p3: count=count+1 print 'correct3' elif answer1==p4: count=count+1 print 'correct4' elif answer1==p5: count=count+1 print 'correct5' elif answer1==p6: count=count+1 print 'correct6' elif answer1==p7: count=count+1 print 'correct7' elif answer1==p8: count=count+1 print 'correct8' print '--------------------------------------------2---------------------------' text = nltk.word_tokenize(sentence2) tagged_sent = nltk.pos_tag(text) print 'tagged_sent:',tagged_sent np_extractor = NPExtractor(sentence2) result3 = np_extractor.extract() print "result3:" print result3 sub = result3[0] obj = result3[-1] object2 = obj.capitalize() if [word for word, pos in tagged_sent if pos == 'NNP']: subject2 = sub.capitalize() else: subject2 = sub.lower() print "subject:" + subject2 print "object:" + object2 result_sent2 = nltk.pos_tag(result3) print 'result_sent:',result_sent2 if [word for word, pos in tagged_sent if pos == 'VBD']: tok = [word for word, pos in tagged_sent if pos == 'VBD'] verb = ''.join(tok) past_participle = en.verb.past_participle(verb) if [word for word, pos in result_sent2 if pos == 'NNP' or 'NNI' or 'NNT' or 'NP']: print result_sent2[-1][1] if result_sent2[-1][1] == 'NNS': s1 = object2 + " were " + past_participle + " by " + subject2 + "." print 's1: ' + s1 else: s2 = object2 + " was " + past_participle + " by " + subject2 + "." print 's2: ' + s2 elif [word for word, pos in result_sent2 if pos == 'NNS']: print result_sent2[-1][1] if result_sent2[-1][1] == 'NNS': s3 = object2 + " were " + past_participle + " by " + subject2 + "." print 's3: ' + s3 else: s4 = object2 + " was " + past_participle + " by " + subject2 + "." print 's4: ' + s4 elif [word for word, pos in tagged_sent if pos == 'VBP']: tok = [word for word, pos in tagged_sent if pos == 'VBP'] verb = ''.join(tok) past_participle = en.verb.past_participle(verb) if [word for word, pos in result_sent2 if pos == 'NNP' or 'NNI' or 'NNT' or 'NP']: print result_sent2[-1][1] if result_sent2[-1][1] == 'NNS': s5 = object2 + " were " + past_participle + " by " + subject2 + "." print 's5: ' + s5 else: s6 = object2 + " was " + past_participle + " by " + subject2 + "." print 's6 :' + s6 elif [word for word, pos in result_sent2 if pos == 'NNS']: print result_sent2[-1][1] if result_sent2[-1][1] == 'NNS': s7 = object2 + " were " + past_participle + " by " + subject2 + "." print 's7 :' + s7 else: s8 = object2 + " was " + past_participle + " by " + subject2 + "." print 's8 :' + s8 else: print 'Wrongs' if answer2 == s1: count = count + 1 print'correct1' elif answer2 == s2: count = count + 1 print'correct2' elif answer2 == s3: count = count + 1 print'correct3' elif answer2 == s4: count = count + 1 print'correct4' if answer2 == s5: count = count + 1 print'correct5' elif answer2 == s6: count = count + 1 print'correct6' elif answer2 == s7: count = count + 1 print'correct7' elif answer2 == s8: count = count + 1 print'correct8' print '--------------------------------------------3---------------------------' text = nltk.word_tokenize(sentence3) tagged_sent = nltk.pos_tag(text) print 'tagged_sent:',tagged_sent np_extractor = NPExtractor(sentence3) result3 = np_extractor.extract() print "result3:" print result3 sub = result3[0] obj = result3[-1] object3 = obj.capitalize() if [word for word, pos in tagged_sent if pos == 'NNP']: subject3 = sub.capitalize() else: subject3 = sub.lower() print "subject:" + subject3 print "object:" + object3 result_sent2 = nltk.pos_tag(result3) print 'result_sent:',result_sent2 if [word for word, pos in tagged_sent if pos == 'VBD']: tok = [word for word, pos in tagged_sent if pos == 'VBD'] verb = ''.join(tok) past_participle = en.verb.past_participle(verb) if [word for word, pos in result_sent2 if pos == 'NNP' or 'NNI' or 'NNT' or 'NP']: print result_sent2[-1][1] if result_sent2[-1][1] == 'NNS': t1 = object3 + " were " + past_participle + " by " + subject3 + "." print 't1: ' + t1 else: t2 = object3 + " was " + past_participle + " by " + subject3 + "." print 't2: ' + t2 elif [word for word, pos in result_sent2 if pos == 'NNS']: print result_sent2[-1][1] if result_sent2[-1][1] == 'NNS': t3 = object3 + " were " + past_participle + " by " + subject3 + "." print 't3: ' + t3 else: t4 = object3 + " was " + past_participle + " by " + subject3 + "." print 't4: ' + t4 elif [word for word, pos in tagged_sent if pos == 'VBP']: tok = [word for word, pos in tagged_sent if pos == 'VBP'] verb = ''.join(tok) past_participle = en.verb.past_participle(verb) if [word for word, pos in result_sent2 if pos == 'NNP' or 'NNI' or 'NNT' or 'NP']: print result_sent2[-1][1] if result_sent2[-1][1] == 'NNS': t5 = object3 + " were " + past_participle + " by " + subject3 + "." print 't5: ' + t5 else: t6 = object3 + " was " + past_participle + " by " + subject3 + "." print 't6 :' + t6 elif [word for word, pos in result_sent2 if pos == 'NNS']: print result_sent2[-1][1] if result_sent2[-1][1] == 'NNS': t7 = object3 + " were " + past_participle + " by " + subject3 + "." print 't7 :' + t7 else: t8 = object3 + " was " + past_participle + " by " + subject3 + "." print 't8 :' + t8 if answer3 == t1: count = count + 1 print'correct1' elif answer3 == t2: count = count + 1 print'correct2' elif answer3 == t3: count = count + 1 print'correct3' elif answer3 == t4: count = count + 1 print'correct4' elif answer3 == t5: count = count + 1 print'correct5' elif answer3 == t6: count = count + 1 print'correct6' elif answer3 == t7: count = count + 1 print'correct7' elif answer3 == t8: count = count + 1 print'correct8' else: print 'Wrongs' data_set={'s1':s1,'s2':s2,'s3':s3,'s4':s4,'s5':s5,'s6':s6,'s7':s7,'s8':s8,'t1':t1,'t2':t2,'t3':t3,'t4':t4,'t5':t5,'t6':t6,'t7':t7,'t8':t8, 'object':object,'p1':p1,'p2':p2,'p3':p3,'p4':p4,'p5':p5,'sentence1':sentence1,'sentence2':sentence2,'sentence3':sentence3, 'p6':p6,'p7':p7,'p8':p8,'answer1':answer1,'answer2':answer2,'answer3':answer3,'subject':subject,'subject2':subject2,'object2':object2, 'subject3':subject3,'object3':object3,'count':count} return render_template('level4_active_passive_evaluate.html', data_set=data_set) #----------------level 4 Active Passive-CHAMIKA--------------- ## ------------------------------------- Subscribe Teacher ----------------------------------------- ## ## Display All Teachers ## @app.route('/display_teachers') def display_teachers(): cursor = db.cursor() sql = """SELECT * FROM users where role=%s """ try: # Execute the SQL command select all rows cursor.execute(sql, ['Teacher']) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() cursor1 = db.cursor() sql1 = """SELECT u.fName,u.lName,s.teacher FROM users u, subscribe_teacher s where u.email=s.teacher AND s.status='pending' AND s.student=%s """ try: # Execute the SQL command select all rows cursor1.execute(sql1, [session['username']]) # fetch rows using fetchall() method. result1 = cursor1.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() cursor1 = db.cursor() sql1 = """SELECT u.fName,u.lName,s.teacher FROM users u, subscribe_teacher s where u.email=s.teacher AND s.status='accepted' AND s.student=%s """ try: # Execute the SQL command select all rows cursor1.execute(sql1, [session['username']]) # fetch rows using fetchall() method. subscribedResult = cursor1.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() return render_template('display_teachers.html', data=result, student_data=result1, subscribedData=subscribedResult) ## Subscribe Teacher ## @app.route('/subscribe_teacher/', methods=['GET']) def subscribe_teacher(): student = session['username'] teacher = request.args.get('email') cursor = db.cursor() sql = """INSERT INTO subscribe_teacher (student,teacher) VALUES(%s,%s)""" try: # Execute the SQL command select all rows cursor.execute(sql, [student, teacher]) # Commit your changes in the database db.commit() alert(text='Your request under pending.', title='English Buddy', button='OK') except: # Rollback in case there is any error db.rollback() return redirect(url_for('home')) ## Cancel Subscribe Teacher Request ## @app.route('/cancel_teacher_subscribe_request/', methods=['GET']) def cancel_teacher_subscribe_request(): student = session['username'] teacher = request.args.get('email') cursor = db.cursor() sql = """DELETE FROM subscribe_teacher WHERE teacher=%s AND student=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [teacher, student]) # Commit your changes in the database db.commit() # Get student subscribe request count student_subscribe_request_count() except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_teachers')) ## Display All Subscribe Requests ## @app.route('/display_student_subscribe_requests') def display_student_subscribe_requests(): cursor = db.cursor() sql = """SELECT u.fName,u.lName,u.school,u.image,u.placement_test,s.status,s.student FROM users u, subscribe_teacher s WHERE u.email=s.student AND s.status='pending' AND s.teacher=%s ORDER BY u.fName ASC""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username']]) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() # Get student subscribe request count count=student_subscribe_request_count() # Get student subscribe request details query=display_student_subscribe_request_details() except: # Rollback in case there is any error db.rollback() return render_template('display_student_requests.html', data=result, query=query, count=count) ## Accept Subscribe Teacher Request ## @app.route('/accept_teacher_subscribe_request/', methods=['GET']) def accept_teacher_subscribe_request(): teacher = session['username'] student = request.args.get('email') cursor = db.cursor() sql = """UPDATE subscribe_teacher SET status='accepted' WHERE teacher=%s AND student=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [teacher, student]) # Commit your changes in the database db.commit() # Get student subscribe request count student_subscribe_request_count() except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_student_subscribe_requests')) ## Decline Subscribe Teacher Request ## @app.route('/decline_teacher_subscribe_request/', methods=['GET']) def decline_teacher_subscribe_request(): teacher = session['username'] student = request.args.get('email') cursor = db.cursor() sql = """DELETE FROM subscribe_teacher WHERE teacher=%s AND student=%s""" try: # Execute the SQL command select all rows cursor.execute(sql, [teacher, student]) # Commit your changes in the database db.commit() # Get student subscribe request count student_subscribe_request_count() except: # Rollback in case there is any error db.rollback() return redirect(url_for('display_student_subscribe_requests')) ## Display all students details who subscribes a teacher ## @app.route('/display_subscribe_student_details') def display_subscribe_student_details(): cursor = db.cursor() sql = """SELECT u.fName,u.lName,u.school,u.image,u.placement_test,s.status,s.student FROM users u, subscribe_teacher s WHERE u.email=s.student AND s.status='accepted' AND s.teacher=%s ORDER BY u.fName ASC""" try: # Execute the SQL command select all rows cursor.execute(sql, [session['username']]) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() # Get student subscribe request count count=student_subscribe_request_count() # Get student subscribe request details query=display_student_subscribe_request_details() except: # Rollback in case there is any error db.rollback() return render_template('display_subscribe_student_details.html', data=result, query=query, count=count) ## ------------------------------------------------ Notifications --------------------------------------- ## @app.route('/addChildren/', methods=['GET']) def addChildren(): Receiver = request.args.get('email') cursor = db.cursor() sql = """INSERT INTO notification (sender_email,receiver_email) VALUES(%s,%s)""" try: # Execute the SQL command cursor.execute(sql, [session['username'], Receiver]) db.commit() except: db.rollback() return redirect(url_for('displayChildren')) @app.route('/displayChildren') def displayChildren(): cursor = db.cursor() sql = """SELECT email,fname,lname,school,image FROM users WHERE role ='Student' AND email NOT IN (SELECT receiver_email FROM notification WHERE sender_email =%s) ORDER BY fname""" try: # Execute the SQL command cursor.execute(sql, [session['username']]) #fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return render_template('addChild.html', data=query) @app.route('/delete_request/', methods=['GET']) def delete_request(): id = request.args.get('id') cursor = db.cursor() sql = """delete from notification where id=%s""" try: # Execute the SQL command cursor.execute(escape_string(sql), [id]) # fetch a single row using fetchone() method. db.commit() except: db.rollback() return redirect(url_for("home")) @app.route('/accept_request/', methods=['GET']) def accept_request(): id = request.args.get('no') cursor = db.cursor() sql = """update notification set status='Accepted' where id=%s""" try: # Execute the SQL command cursor.execute(sql, [id]) # fetch a single row using fetchone() method. db.commit() print('success') except: db.rollback() return redirect(url_for('home')) def getSenderData(username): cursor = db.cursor() sql = """SELECT n.id,u.fName,u.lName,u.image FROM users u,notification n WHERE n.sender_email=u.email AND n.receiver_email=%s AND n.status='pending'""" try: # Execute the SQL command cursor.execute(sql, [username]) #fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return query def getCount(username): cursor = db.cursor() sql = """SELECT count(*) from notification where receiver_email=%s and status='pending'""" try: # Execute the SQL command cursor.execute(sql, [username]) #fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return query def getAcceptedData(username): cursor = db.cursor() sql = """SELECT n.receiver_email,u.fname,u.lname,u.image FROM users u, notification n WHERE n.receiver_email = u.email and status='Accepted' and n.sender_email=%s""" try: # Execute the SQL command cursor.execute(sql, [username]) #fetch a single row using fetchone() method. query = cursor.fetchall() except: db.rollback() return query ## ------------------------------------------level3_summary---------------------------------------------------------------------- ## ## ------------------------------------------level3_summary---------------------------------------------------------------------- ## @app.route('/loadSummaryQues') def loadSummaryQues(): return render_template('Add_level3_summary.html') @app.route('/addSummaryQues',methods=['POST']) def addSummaryQues(): Question1 = request.form['Question1'] Question2 = request.form['Question2'] Question3 = request.form['Question3'] question1_exist=False question2_exist=False question3_exist=False cursor = db.cursor() sql ="""SELECT * FROM level3_summary WHERE question=%s OR question=%s OR question=%s""" try: # Execute the SQL command cursor.execute(sql,[Question1,Question2,Question3]) result = cursor.fetchall() print(cursor.fetchall()) if result: for row in result: if row[1]==Question1: question1_exist=True elif row[1]== Question2: question2_exist=True elif row[1]==Question3: question3_exist=True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors={'Question1':Question1, 'Question2':Question2, 'Question3':Question3,'question1Status':question1_exist, 'question2Status':question2_exist, 'question3Status':question3_exist} return render_template('Add_level3_summary.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() rows = [] if request.form.get('Question1') != '' : Question1 = request.form['Question1'] rows.append(( Question1.strip(), session['username'])) if request.form.get('Question2') != '' : Question2 = request.form['Question2'] rows.append((Question2.strip(),session['username'])) if request.form.get('Question3') != '': Question3 = request.form['Question3'] rows.append((Question3.strip(),session['username'])) cursor = db.cursor() sql = """INSERT INTO level3_summary (question,author) VALUES(%s,%s)""" try: # Execute the SQL command #cursor.execute(sql,[qusetion1,answer1]) print 'add' cursor.executemany(sql, rows) db.commit() except: db.rollback() return render_template('Add_level3_summary.html') @app.route('/level_3_summary') def level_3_summary(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level3_summary order by rand() limit 1 """ try: # Execute the SQL command cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() for row in query: data=row[1] except: db.rollback() return render_template('summary_level3.html', data=data) @app.route('/evaluateSummary',methods=['POST']) def evaluateSummary(): value=request.form['Ques'].strip() answer=request.form['Answer'].strip() count_keywords=0 status="" grammar=0 content=0 answer_sentences=sent_tokenize(answer) tokenizer = RegexpTokenizer(r'\w+') wordCount= len(tokenizer.tokenize(answer)) print tokenizer.tokenize(answer) marks=0 #check whether number of sentences equal to one # check sentence already existing in the question print answer_sentences print sent_tokenize(value) if any(sentence in sent_tokenize(value) for sentence in answer_sentences): status= 'Sentence already in the passage!' return render_template('summaryResult.html', answer=answer,status=status) else: top=keywords.top(value) print top print len(top) for count,word in top: if word in answer: count_keywords=count_keywords+1 half=len(top)/2 if count_keywords>0: conv =Ansi2HTMLConverter() array=[] array=ginger.main(answer) original_text=conv.convert(array[0]) fixed_text=conv.convert(array[1]) if array[1] =="Good English": if wordCount >=5 and wordCount<=20: if(count_keywords>=half): marks=4.5 content=3 grammar=1.5 else: marks=4 content=2.5 grammar=1.5 else: marks=1.5 content=0 else: if wordCount >=5 and wordCount<=20: if(count_keywords>=half): if (array[2]>=2): marks=3.5 grammar=0.5 content=3 else: marks=3.5 grammar=1 content=2.5 else: if (array[2]>=2): marks=2 grammar=0.5 content=1.5 else: marks=2.5 grammar=1 content=1.5 else: marks=0.5 content=0 grammar=0.5 print marks return render_template('summaryResult.html',original=original_text,fixed=fixed_text,answer=answer,status=status,wordCount=wordCount,grammar=grammar,content=content) else: status='Answer not complete!' return render_template('summaryResult.html', answer=answer,status=status) status='Your answer not relevant to the Question!' return render_template('summaryResult.html', answer=answer,status=status) ## ---------------------------------------------------------------------------------------------------------------- ## ###############level4 summary############### ###level4 summary########## @app.route('/loadSummaryQues_level4') def loadSummaryQues_level4(): return render_template('Add_level4_summary.html') @app.route('/addSummaryQues_Level4',methods=['POST']) def addSummaryQues_Level4(): Question1 = request.form['Question1'] Question2 = request.form['Question2'] Question3 = request.form['Question3'] question1_exist=False question2_exist=False question3_exist=False cursor = db.cursor() sql ="""SELECT * FROM level4_summary WHERE question=%s OR question=%s OR question=%s""" try: # Execute the SQL command cursor.execute(sql,[Question1,Question2,Question3]) result = cursor.fetchall() print(cursor.fetchall()) if result: for row in result: if row[1]==Question1: question1_exist=True elif row[1]== Question2: question2_exist=True elif row[1]==Question3: question3_exist=True alert(text='Questions Already exists !', title='English Buddy', button='OK') errors={'Question1':Question1, 'Question2':Question2, 'Question3':Question3,'question1Status':question1_exist, 'question2Status':question2_exist, 'question3Status':question3_exist} return render_template('Add_level4_summary.html', errors=errors) #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() rows = [] if request.form.get('Question1') != '' : Question1 = request.form['Question1'] rows.append(( Question1.strip(), session['username'])) if request.form.get('Question2') != '' : Question2 = request.form['Question2'] rows.append((Question2.strip(),session['username'])) if request.form.get('Question3') != '': Question3 = request.form['Question3'] rows.append((Question3.strip(),session['username'])) cursor = db.cursor() sql = """INSERT INTO level4_summary (question,author) VALUES(%s,%s)""" try: # Execute the SQL command #cursor.execute(sql,[qusetion1,answer1]) print 'add' cursor.executemany(sql, rows) db.commit() except: db.rollback() return render_template('Add_level4_summary.html') @app.route('/level_4_summary') def level_4_summary(): cursor = db.cursor() sql = """SELECT * FROM english_buddy.level4_summary order by rand() limit 1 """ try: # Execute the SQL command cursor.execute(sql) # fetch rows using fetchall() method. query = cursor.fetchall() for row in query: data=row[1] except: db.rollback() return render_template('summary_level4.html', data=data) @app.route('/evaluateSummary_level4',methods=['POST']) def evaluateSummary_level4(): value=request.form['Ques'].strip() answer=request.form['Answer'].strip() count_keywords=0 status="" answer_sentences=sent_tokenize(answer) wordCount= len(word_tokenize(answer)) print word_tokenize(answer) marks=0 #check whether number of sentences equal to one # check sentence already existing in the question print sent_tokenize(value) if any(sentence in sent_tokenize(value) for sentence in answer_sentences): status= 'Sentence already in the passage!' return render_template('summaryResult.html', answer=answer,status=status) else: top=keywords.top(value) print top for count,word in top: if word in answer: count_keywords=count_keywords+1 print(count_keywords) half=len(top)/2 if count_keywords>0: conv =Ansi2HTMLConverter() array=[] array=ginger.main(answer) original_text=conv.convert(array[0]) fixed_text=conv.convert(array[1]) if array[1] =="Good English": if len(word_tokenize(answer))>=5 and len(word_tokenize(answer))<=35: if(count_keywords>=half): marks=4.5 else: marks=4 else: marks=1.5 else: if len(word_tokenize(answer))>=5 and len(word_tokenize(answer))<=35: if(count_keywords>=half): if (array[2]>=2): marks=3 else: marks=3.5 else: if (array[2]>=2): marks=2 else: marks=2.5 else: marks=0.5 print marks return render_template('summaryResult.html',original=original_text,fixed=fixed_text,answer=answer,status=status,wordCount=wordCount) else: status='Answer not complete!' return render_template('summaryResult.html', answer=answer,status=status) status='Your answer not relevant to the Question!' return render_template('summaryResult.html', answer=answer,status=status) ############level4 sumary####################### ##level 1 ranking ## @app.route('/level1_ranking') def level1_ranking(): marks=0 cursor=db.cursor() sql="""select marks from marks where user=%s""" try: cursor.execute(sql,[session['username']]) result=cursor.fetchall() if result: for row in result: marks=row[0] db.commit() except: db.rollback() cursor = db.cursor() sql = """Insert into temp (question,answer) (select question,answer from level1_articles order by rand() limit 5) union (select question,answer from level_1_adjectives order by rand() limit 5) union (select question,correct from prepositions order by rand() limit 5) union (select question,answer from conjunctions order by rand() limit 5)""" try: # Execute the SQL command select all rows cursor.execute(sql) # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() cursor = db.cursor() array=[] sql = """SELECT question,answer FROM temp order by rand() limit 10""" try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database for row in result: answer =row[1] array.append(answer) shuffle(array) db.commit() except: # Rollback in case there is any error db.rollback() return render_template('level1_rating.html',result=result,answer=array,marks=marks) @app.route('/evaluate_ranking', methods=['POST']) def evaluate_ranking(): count=0 provided_answer1=request.form['provideAnswer1'] provided_answer2=request.form['provideAnswer2'] provided_answer3=request.form['provideAnswer3'] provided_answer4=request.form['provideAnswer4'] provided_answer5=request.form['provideAnswer5'] provided_answer6=request.form['provideAnswer6'] provided_answer7=request.form['provideAnswer7'] provided_answer8=request.form['provideAnswer8'] provided_answer9=request.form['provideAnswer9'] provided_answer10=request.form['provideAnswer10'] correct_answer1=request.form['correct_answer1'] correct_answer2=request.form['correct_answer2'] correct_answer3=request.form['correct_answer3'] correct_answer4=request.form['correct_answer4'] correct_answer5=request.form['correct_answer5'] correct_answer6=request.form['correct_answer6'] correct_answer7=request.form['correct_answer7'] correct_answer8=request.form['correct_answer8'] correct_answer9=request.form['correct_answer9'] correct_answer10=request.form['correct_answer10'] if provided_answer1.strip()==correct_answer1: count=count+1 if provided_answer2.strip()==correct_answer2: count=count+1 if provided_answer3.strip()==correct_answer3: count=count+1 if provided_answer4.strip()==correct_answer4: count=count+1 if provided_answer5.strip()==correct_answer5: count=count+1 if provided_answer6.strip()==correct_answer6: count=count+1 if provided_answer7.strip()==correct_answer7: count=count+1 if provided_answer8.strip()==correct_answer8: count=count+1 if provided_answer9.strip()==correct_answer9: count=count+1 if provided_answer10.strip()==correct_answer10: count=count+1 print(count) sql = """SELECT user,marks FROM marks where user=%s""" try: cursor = db.cursor() # Execute the SQL command cursor.execute(sql,[session['username']]) # fetch a single row using fetchone() method. data = cursor.fetchall() if data: for row in data: marks=row[1] last_mark=marks+count cursor = db.cursor() sql = """update marks set marks=%s where user=%s""" try: # Execute the SQL command cursor.execute(sql, [last_mark,session['username']]) # Commit your changes in the database db.commit() #flash('Successfully Updated !') except: # Rollback in case there is any error db.rollback() else: cursor = db.cursor() sql = """INSERT INTO marks(marks,user) VALUES(%s,%s)""" try: # Execute the SQL command cursor.execute(sql, [count, session['username']]) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() cursor = db.cursor() sql = """Truncate table temp""" try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() except: db.rollback() return redirect(url_for('view_level1_ratings')) @app.route('/view_level1_ratings') def view_level1_ratings(): #display first five rankings cursor = db.cursor() sql = """SELECT u.fName,u.lName,u.image,m.marks,u.email FROM users u ,marks m where u.placement_test='Elementary' and u.email=m.user order by marks DESC limit 5""" try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. firstFive = cursor.fetchall() includeFirstFive='false' for row in firstFive: if row[4]==session['username']: includeFirstFive='true' except: db.rollback() sql = """select u.image,u.fName,u.lName,m.marks,u.email from marks m, users u where u.email=m.user AND m.marks IN (SELECT MIN(m1.marks) FROM marks m1, users u1 WHERE u1.placement_test='Elementary' AND u1.email=m1.user AND m1.marks>(select m3.marks from marks m3 where m3.user=%s)) UNION select u.image,u.fName,u.lName,m.marks,u.email from marks m, users u where u.email=m.user AND m.user=%s AND u.placement_test='Elementary' UNION select u.image,u.fName,u.lName,m.marks,u.email from marks m, users u where u.email=m.user AND m.marks IN (SELECT MAX(m1.marks) FROM marks m1, users u1 WHERE u1.placement_test='Elementary' AND u1.email=m1.user AND m1.marks<(select m3.marks from marks m3 where m3.user=%s)) """ try: # Execute the SQL command select all rows cursor.execute(sql,[session['username'], session['username'], session['username']]) # fetch rows using fetchall() method. data = cursor.fetchall() except: db.rollback() return render_template("viewRatings.html", firstFive=firstFive,data=data,includeFirstFive=includeFirstFive) @app.route('/view_level2_ratings') def view_level2_ratings(): # display first five rankings cursor = db.cursor() sql = """SELECT u.fName,u.lName,u.image,m.marks,u.email FROM users u ,marks m where u.placement_test='Preliminary' and u.email=m.user order by marks DESC limit 5""" try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. firstFive = cursor.fetchall() includeFirstFive = 'false' for row in firstFive: if row[4] == session['username']: includeFirstFive = 'true' except: db.rollback() sql = """select u.image,u.fName,u.lName,m.marks,u.email from marks m, users u where u.email=m.user AND m.marks IN (SELECT MIN(m1.marks) FROM marks m1, users u1 WHERE u1.placement_test='Preliminary' AND u1.email=m1.user AND m1.marks>(select m3.marks from marks m3 where m3.user=%s)) UNION select u.image,u.fName,u.lName,m.marks,u.email from marks m, users u where u.email=m.user AND m.user=%s AND u.placement_test='Preliminary' UNION select u.image,u.fName,u.lName,m.marks,u.email from marks m, users u where u.email=m.user AND m.marks IN (SELECT MAX(m1.marks) FROM marks m1, users u1 WHERE u1.placement_test='Preliminary' AND u1.email=m1.user AND m1.marks<(select m3.marks from marks m3 where m3.user=%s)) """ try: # Execute the SQL command select all rows cursor.execute(sql, [session['username'], session['username'], session['username']]) # fetch rows using fetchall() method. data = cursor.fetchall() except: db.rollback() return render_template("viewLevel2Ratings.html", firstFive=firstFive,data=data, includeFirstFive=includeFirstFive) @app.route('/level2_Ranking_Test') def level2_Ranking_Test(): marks=0 cursor=db.cursor() sql="""select marks from marks where user=%s""" try: cursor.execute(sql,[session['username']]) result=cursor.fetchall() if result: for row in result: marks=row[0] db.commit() except: db.rollback() array=[] value= random.choice([1,2,3]) print value if value==1: category='jumble_sentences' cursor = db.cursor() sql = """SELECT * FROM jumblesentences order by rand()limit 10""" try: # Execute the SQL command cursor.execute(sql) # fetch a single row using fetchone() method. result = cursor.fetchall() except: db.rollback() if value==2: category='dialogs' cursor = db.cursor() sql = """SELECT * FROM dialogs where level='level2' order by rand() limit 1 """ try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. result = cursor.fetchall() # Commit your changes in the database db.commit() except: # Rollback in case there is any error db.rollback() if value==3: category='match_pronoun' cursor=db.cursor(); sql="""Insert into temp2 (question,answer) (select question,answer from level2_match order by rand() limit 6) union (select question,answer from level_2_pronoun order by rand() limit 6)""" try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. except: # Rollback in case there is any error db.rollback() cursor = db.cursor() array=[] sql = """SELECT question,answer FROM temp2 order by rand() limit 10""" try: # Execute the SQL command select all rows cursor.execute(sql) # fetch rows using fetchall() method. result = cursor.fetchall() print(result) # Commit your changes in the database for row in result: answer =row[1] array.append(answer) shuffle(array) except: # Rollback in case there is any error db.rollback() return render_template("level2_rating.html",category=category,result=result,answer=array,marks=marks) @app.route('/evaluate_level2_ranking',methods=['POST']) def evaluate_level2_ranking(): category=request.form['category'] count=0 if category=='jumble_sentences': provided_answer1=request.form['jumbleSentence_provided_answer1'] provided_answer2=request.form['jumbleSentence_provided_answer2'] provided_answer3=request.form['jumbleSentence_provided_answer3'] provided_answer4=request.form['jumbleSentence_provided_answer4'] provided_answer5=request.form['jumbleSentence_provided_answer5'] provided_answer6=request.form['jumbleSentence_provided_answer6'] provided_answer7=request.form['jumbleSentence_provided_answer7'] provided_answer8=request.form['jumbleSentence_provided_answer8'] provided_answer9=request.form['jumbleSentence_provided_answer9'] provided_answer10=request.form['jumbleSentence_provided_answer10'] correct_answer1=request.form['jumbleSentence_correct_answer1'] correct_answer2=request.form['jumbleSentence_correct_answer2'] correct_answer3=request.form['jumbleSentence_correct_answer3'] correct_answer4=request.form['jumbleSentence_correct_answer4'] correct_answer5=request.form['jumbleSentence_correct_answer5'] correct_answer6=request.form['jumbleSentence_correct_answer6'] correct_answer7=request.form['jumbleSentence_correct_answer7'] correct_answer8=request.form['jumbleSentence_correct_answer8'] correct_answer9=request.form['jumbleSentence_correct_answer9'] correct_answer10=request.form['jumbleSentence_correct_answer10'] if provided_answer1.strip()==correct_answer1: count=count+1 if provided_answer2.strip()==correct_answer2: count=count+1 if provided_answer3.strip()==correct_answer3: count=count+1 if provided_answer4.strip()==correct_answer4: count=count+1 if provided_answer5.strip()==correct_answer5: count=count+1 if provided_answer6.strip()==correct_answer6: count=count+1 if provided_answer7.strip()==correct_answer7: count=count+1 if provided_answer8.strip()==correct_answer8: count=count+1 if provided_answer9.strip()==correct_answer9: count=count+1 if provided_answer10.strip()==correct_answer10: count=count+1 if category=='match_pronoun': provided_answer1=request.form['match_pronoun_provideAnswer1'] provided_answer2=request.form['match_pronoun_provideAnswer2'] provided_answer3=request.form['match_pronoun_provideAnswer3'] provided_answer4=request.form['match_pronoun_provideAnswer4'] provided_answer5=request.form['match_pronoun_provideAnswer5'] provided_answer6=request.form['match_pronoun_provideAnswer6'] provided_answer7=request.form['match_pronoun_provideAnswer7'] provided_answer8=request.form['match_pronoun_provideAnswer8'] provided_answer9=request.form['match_pronoun_provideAnswer9'] provided_answer10=request.form['match_pronoun_provideAnswer10'] correct_answer1=request.form['match_pronounAnswer1'] correct_answer2=request.form['match_pronounAnswer2'] correct_answer3=request.form['match_pronounAnswer3'] correct_answer4=request.form['match_pronounAnswer4'] correct_answer5=request.form['match_pronounAnswer5'] correct_answer6=request.form['match_pronounAnswer6'] correct_answer7=request.form['match_pronounAnswer7'] correct_answer8=request.form['match_pronounAnswer8'] correct_answer9=request.form['match_pronounAnswer9'] correct_answer10=request.form['match_pronounAnswer10'] if provided_answer1.strip()==correct_answer1: count=count+1 if provided_answer2.strip()==correct_answer2: count=count+1 if provided_answer3.strip()==correct_answer3: count=count+1 if provided_answer4.strip()==correct_answer4: count=count+1 if provided_answer5.strip()==correct_answer5: count=count+1 if provided_answer6.strip()==correct_answer6: count=count+1 if provided_answer7.strip()==correct_answer7: count=count+1 if provided_answer8.strip()==correct_answer8: count=count+1 if provided_answer9.strip()==correct_answer9: count=count+1 if provided_answer10.strip()==correct_answer10: count=count+1 if category=='dialogs' : qNo = request.form['qNo'] pa1 = request.form['dialog_answer1'] pa2 = request.form['dialog_answer2'] pa3 = request.form['dialog_answer3'] pa4 = request.form['dialog_answer4'] pa5 = request.form['dialog_answer5'] cursor = db.cursor() sql = """SELECT * FROM dialogs where qNo=%s""" try: # Execute the SQL command cursor.execute(sql, [qNo]) # fetch a single row using fetchone() method. data = cursor.fetchall() for row in data: a1 = row[4] a2 = row[5] a3 = row[6] a4 = row[7] a5 = row[8] if a1 == pa1: count=count+2 if a2 == pa2: count=count+2 if a3 == pa3: count=count+2 if a4 == pa4: count=count+2 if a5 == pa5: count=count+2 except: db.rollback() sql = """SELECT user,marks FROM marks where user=%s""" try: cursor = db.cursor() # Execute the SQL command cursor.execute(sql,[session['username']]) # fetch a single row using fetchone() method. data = cursor.fetchall() if data: for row in data: marks=row[1] last_mark=marks+count cursor = db.cursor() sql = """update marks set marks=%s where user=%s""" try: # Execute the SQL command cursor.execute(sql, [last_mark,session['username']]) # Commit your changes in the database db.commit() #flash('Successfully Updated !') except: # Rollback in case there is any error db.rollback() else: cursor = db.cursor() sql = """INSERT INTO marks(marks,user) VALUES(%s,%s)""" try: # Execute the SQL command cursor.execute(sql, [count, session['username']]) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() cursor = db.cursor() sql = """Truncate table temp2""" try: # Execute the SQL command cursor.execute(sql) # Commit your changes in the database db.commit() #flash('Question successfully added !') except: # Rollback in case there is any error db.rollback() except: db.rollback() return redirect(url_for('view_level2_ratings')) ### ----------------------------------- Contact Teacher -------------------------------------------- ### ## Display Contact Teacher Page ## @app.route('/view_contact_teacher') def view_contact_teacher(): cursor = db.cursor() sql = """SELECT u.fName,u.lName,u.image,u.email FROM users u, subscribe_teacher s WHERE u.email=s.teacher AND s.status='accepted' AND s.student=%s""" try: # Execute the SQL command cursor.execute(sql,[session['username']]) # fetch a single row using fetchone() method. result = cursor.fetchall() if result: return render_template('contact_teacher.html',data=result) else: #alert(text='You are not subscribe a teacher yet. Please Subscribe a teacher to send messages.', title='English Buddy', button='OK') return render_template('contact_teacher.html') except: db.rollback() #return render_template('contact_teacher.html') ## Contact Teacher - Send email ## @app.route('/contact_teacher',methods=['POST']) def contact_teacher(): teacher = request.form['teacher'] student = request.form['student'] message = request.form['question'] ## Send email ## msg = Message('English Buddy - Student Questions', sender="<EMAIL>") msg.recipients = [teacher] msg.html = "<body bgcolor='#DCEEFC'><b>Dear Sir/Mis,</b><br><br><p>" + message + " </p><br><br><br><br>Student email : "+ student +"<br><br><a href='http://127.0.0.1:5000/'>Sign in Now</a><br></body>" mail.send(msg) alert(text='Message sent successfully ! Please check your e-mail for a reply.', title='English Buddy', button='OK') return redirect(url_for('view_contact_teacher')) ## ---------------------------------------------------------------------------------------------------------------- ## def check_internet_connection(): REMOTE_SERVER = "www.google.com" try: # see if we can resolve the host name -- tells us if there is # a DNS listening host = socket.gethostbyname(REMOTE_SERVER) # connect to the host -- tells us if the host is actually # reachable s = socket.create_connection((host, 80), 2) return True except: pass return False # ------------------------------------------------------------- # Listen to the level4 dialog question @app.route('/speak_dialog', methods=['GET']) def speak_dialog(): question1 = request.args.get('question1').split(":")[1] question2 = request.args.get('question2').split(":")[1] question3 = request.args.get('question3').split(":")[1] question4 = request.args.get('question4').split(":")[1] question5 = request.args.get('question5').split(":")[1] if request.args.get('question6') != "": question6 = request.args.get('question6').split(":")[1] else: question6 = "" answer1 = request.args.get('answer1') answer2 = request.args.get('answer2') answer3 = request.args.get('answer3') answer4 = request.args.get('answer4') answer5 = request.args.get('answer5') engine = pyttsx.init() engine.setProperty('rate', 120) engine.say(question1) engine.say(answer1) engine.say(question2) engine.say(answer2) engine.say(question3) engine.say(answer3) engine.say(question4) engine.say(answer4) engine.say(question5) engine.say(answer5) engine.say(question6) engine.runAndWait() return 'True' # Stop level4 dialog reading @app.route('/stop_dialog_reading', methods=['GET']) def stop_dialog_reading(): return 'True' # Listen to level1 and level3 conjunction activity questions @app.route('/speak_conjunction', methods=['GET']) def speak_conjunction(): statement = request.args.get('question').split("#")[0]+request.args.get('answer')+request.args.get('question').split("#")[1] engine = pyttsx.init() engine.setProperty('rate', 120) engine.say(statement) engine.runAndWait() return 'True' # -------------------------------------------------------------- if __name__ == '__main__': app.run(debug=True) <file_sep>/flask/coordinatingConjunctions.py __author__ = '<NAME>' import nltk import ginger_python2_new as Grammar # Valid conjunctions list valid_conjunctions = ['and', 'or', 'but', 'for', 'yet', 'nor', 'So', 'so'] # Check the conjunction is correct def check(sentence, answer): tagged_sent = nltk.pos_tag(sentence.split()) print tagged_sent if [word for word, pos in tagged_sent if pos == 'CC' and word == answer]: conjunction = [word for word, pos in tagged_sent if pos == 'CC' and word == answer] conjunctions = conjunction[0], 'CC' print 'Conjunction : ' + conjunction[0] if conjunction[0] == 'or': if "neither" in sentence: if sentence.find("nor") < 0: # print 'wrong' return False elif (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VBD' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNS') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'VB' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'JJ' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'NNP'): if Grammar.main(sentence)[1] =="Good English": # print sentence return True else: # print 'wrong' return False elif conjunction[0] == 'but': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'JJ' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'RB' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNS' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'RB'): if Grammar.main(sentence)[1] =="Good English": # print sentence return True else: # print 'wrong' return False else: # print 'wrong' return False elif conjunction[0] == 'and': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNS' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'JJ') and \ tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'NNP': if Grammar.main(sentence)[1] =="Good English": # print sentence return True else: # print 'wrong' return False else: # print 'wrong' return False elif conjunction[0] == 'nor': if "neither" in sentence: if sentence.find("neither") < sentence.find("nor"): if Grammar.main(sentence)[1] =="Good English": # print sentence return True else: # print 'wrong' return False else: # print 'wrong' return False elif (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VBD' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == '-NONE-') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'NNP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'WP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'MD' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'VBZ'): if Grammar.main(sentence)[1] =="Good English": # print sentence return True else: # print 'wrong' return False else: # print 'wrong' return False else: print 'else' return False elif [word for word, pos in tagged_sent if pos == 'RB' and word == answer]: conjunction = [word for word, pos in tagged_sent if pos == 'RB' and word == answer] conjunctions = conjunction[0], 'RB' # print 'Conjunction : ' + conjunction[0] if conjunction[0] == 'so': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'JJ') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'RB' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): if Grammar.main(sentence)[1] =="Good English": # print sentence return True else: # print 'wrong' return False else: # print 'wrong' return False elif conjunction[0] == 'yet': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNP') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): if Grammar.main(sentence)[1] =="Good English": # print sentence return True else: # print 'wrong' return False else: # print 'wrong' return False else: print 'else' return False elif [word for word, pos in tagged_sent if pos == 'IN' and word == answer]: conjunction = [word for word, pos in tagged_sent if pos == 'IN' and word == answer] conjunctions = conjunction[0], 'IN' # print 'Conjunction : ' + conjunction[0] if conjunction[0] == 'so': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'VBP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): if Grammar.main(sentence)[1] =="Good English": # print sentence return True else: # print 'wrong' return False else: # print 'wrong' return False elif conjunction[0] == 'for': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'RB') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): if Grammar.main(sentence)[1] =="Good English": # print sentence return True else: # print 'wrong' return False else: # print 'wrong' return False else: print 'else' return False elif [word for word, pos in tagged_sent if (pos == 'NN') and (word == answer or word == answer + ',')]: conjunction = [word for word, pos in tagged_sent if pos == 'NN' and (word == answer or word == answer + ',')] conjunctions = conjunction[0], 'NN' # print 'Conjunction : ' + conjunction[0] if conjunction[0] == 'So,': if (tagged_sent.index(conjunctions) == 0) and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'DT' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): if Grammar.main(sentence)[1] =="Good English": # print sentence return True else: # print 'wrong' return False else: # print 'wrong' return False else: print 'else' return False else: return False # Find correct conjunction def find_correct_conjunction(sentence): for item in valid_conjunctions: newSentence=sentence.split("#")[0]+item+sentence.split("#")[1] status=check(newSentence, item) if status == True: return item # sentence = "He is neither sane nor brilliant." # answer = "nor" # # # Execute Function # check(sentence, answer) # find_correct_conjunction("You'd better do your homework, # you'll get a terrible grade.") <file_sep>/flask/conjunctions.py __author__ = '<NAME>' import nltk # Valid conjunctions list valid_conjunctions = ['and', 'or', 'but', 'for', 'yet', 'nor', 'So', 'so', 'Although', 'although', 'Since', 'since', 'Because', 'because', 'after', 'Before', 'before', 'If', 'if', 'Once', 'once', 'until', 'Unless', 'unless', 'When', 'when', 'while', 'where', 'whether', 'As', 'as', 'though'] # Check the conjunction is correct def check(sentence, answer): tagged_sent = nltk.pos_tag(sentence.split()) print tagged_sent if [word for word, pos in tagged_sent if pos == 'CC' and word == answer]: conjunction = [word for word, pos in tagged_sent if pos == 'CC' and word == answer] conjunctions = conjunction[0], 'CC' print 'Conjunction : ' + conjunction[0] if conjunction[0] == 'or': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VBD' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNS') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'VB' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'NNP'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'but': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'JJ' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNS' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'RB'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'and': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNS' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'JJ') and \ tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'NNP': print sentence return True else: print 'wrong' return False elif conjunction[0] == 'nor': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VBD' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == '-NONE-') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'NNP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'WP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'MD' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'VBZ'): print sentence return True else: print 'wrong' return False else: print 'else' return False elif [word for word, pos in tagged_sent if pos == 'RB' and word == answer]: conjunction = [word for word, pos in tagged_sent if pos == 'RB' and word == answer] conjunctions = conjunction[0], 'RB' print 'Conjunction : ' + conjunction[0] if conjunction[0] == 'so': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'JJ') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'RB' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'yet': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'once': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'RP') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'DT' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'Once': if (tagged_sent.index(conjunctions) == 0) and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$' or \ tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or \ tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'DT'): print sentence return True else: print 'wrong' return False else: print 'else' return False elif [word for word, pos in tagged_sent if pos == 'IN' and word == answer]: conjunction = [word for word, pos in tagged_sent if pos == 'IN' and word == answer] conjunctions = conjunction[0], 'IN' print 'Conjunction : ' + conjunction[0] if conjunction[0] == 'so': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'VBP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): print sentence return True else: print 'wrong' return False # elif conjunction[0] == 'for': # if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNP' or # tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN') and ( # tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$' or # tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): # print sentence # return True # else: # print 'wrong' # return False elif conjunction[0] == 'Although': if (tagged_sent.index(conjunctions) == 0) and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'although': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'JJ' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'IN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'JJ'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'Since': if (tagged_sent.index(conjunctions) == 0) and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'JJ'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'since': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VBN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VBG' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNS') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'JJ' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'after': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNS' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'RP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'DT'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'because': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'IN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNS') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'JJ'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'Because': if (tagged_sent.index(conjunctions) == 0) and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'before': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NNS' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'RP') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'DT' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'Before': if (tagged_sent.index(conjunctions) == 0) and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'If': if (tagged_sent.index(conjunctions)==0) and (tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'if': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'until': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'RB' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'RP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VB' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'DT' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'NN'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'unless': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'RP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'IN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'Unless': if (tagged_sent.index(conjunctions) == 0) and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'while': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VBD' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VBG' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'IN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'DT' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'whether': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'JJ' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VB' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'PRP') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'CC'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'As': if (tagged_sent.index(conjunctions) == 0) and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or \ tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'NNP' or \ tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'JJ'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'as': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'IN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'RB'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'though': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'IN') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): print sentence return True else: print 'wrong' return False else: print 'else' return False elif [word for word, pos in tagged_sent if (pos == 'NN') and (word == answer or word == answer + ',')]: conjunction = [word for word, pos in tagged_sent if pos == 'NN' and (word == answer or word == answer + ',')] conjunctions = conjunction[0], 'NN' print 'Conjunction : ' + conjunction[0] if conjunction[0] == 'So,': if (tagged_sent.index(conjunctions) == 0) and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'DT' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): print sentence return True else: print 'wrong' return False else: print 'else' return False elif [word for word, pos in tagged_sent if pos == 'WRB' and word == answer]: conjunction = [word for word, pos in tagged_sent if pos == 'WRB' and word == answer] conjunctions = conjunction[0], 'WRB' print 'Conjunction : ' + conjunction[0] if conjunction[0] == 'When': if (tagged_sent.index(conjunctions) == 0) and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'when': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'RP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'NN' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'PRP') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$'): print sentence return True else: print 'wrong' return False elif conjunction[0] == 'where': if (tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VBZ' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VB' or tagged_sent[tagged_sent.index(conjunctions) - 1][1] == 'VBP') and ( tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'PRP$' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'NNP' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'DT' or tagged_sent[tagged_sent.index(conjunctions) + 1][1] == 'JJ'): print sentence return True else: print 'wrong' return False else: print 'else' return False else: return False # Find correct conjunction def find_correct_conjunction(sentence): for item in valid_conjunctions: newSentence=sentence.split("#")[0]+item+sentence.split("#")[1] status=check(newSentence, item) if status == True: return item # sentence = "I want to go there again, for it was a wonderful trip." # answer = "for" # # # Execute Function # check(sentence, answer) # find_correct_conjunction("I want to go there again # it was a wonderful trip.") <file_sep>/flask/notice.py __author__ = 'Darani' import numpy import nltk from nltk import pos_tag, word_tokenize from nltk.tag import pos_tag from nltk.tokenize import sent_tokenize import re import en import keywords def checkTypeWordCount(answer,question): count = 0 status = '' sum = 0 status1 = 'false' for word1 in word_tokenize(answer): if word1 == '.' or word1 == ',' or word1 == '\'' or word1 == '\"' or word1 == ':' or word1 == ';' or word1 == '?' or word1 == '/' or word1 == '\\' or word1 == '|' or word1 == ']' or word1 == '[' or word1 == '}' or word1 == '{' or word1 == '(' or word1 == ')' or word1 == '*' or word1 == '&' or word1 == '^' or word1 == '%' or word1 == '$' or word1 == '#' or word1 == '@' or word1 == '!' or word1 == '`' or word1 == '~' or word1 == '-' or word1 == '_' or word1 == '='or word1 == '+': print 'error' else: sum = sum +1 #print word1 print sum words_ans = word_tokenize(answer) words_qus = word_tokenize(question) if words_ans[0]=="NOTICE"or words_ans[0]=="Notice": print "Correct" count = count+0.25 else: status = "Wrong" for word in words_qus: if en.is_number(word) and words_qus[words_qus.index(word)+1]== 'words': if sum >= word: print word count = count+0.25 status1='true' if status1 == 'false': count = count+0.25 return count,status def includes(answer,question): count_ans = 0 sentences_qus= sent_tokenize(question) words_ans = word_tokenize(answer) matching_count = 0 for sentence_qus in sentences_qus: top = keywords.top(sentence_qus, nouns=True) words_qus = word_tokenize(sentence_qus) for word_qus in words_qus: if word_qus == 'Include' or word_qus == 'include' or word_qus == 'Include:' : for count,word in top: for word_ans in words_ans: if word in word_ans: #print word matching_count = matching_count+1 #print matching_count #print len(top) defferent = len(top)- matching_count if (defferent+2)== 0 or (defferent+2)== 1 or (defferent+2)== 2: count_ans = count_ans + 0.5 print 'include',count_ans return count_ans def designation(answer, question): sentences_qus= sent_tokenize(question) count = 0 name = ' ' address = ' ' for sentence_qus in sentences_qus: words_qus = word_tokenize(sentence_qus) # print sentence_qus # print words_qus words_ans = word_tokenize(answer) # print words_ans for word in words_qus: if word == 'You' or word == 'you' and words_qus[words_qus.index(word)+1] == 'are': #print 'heloo' index_you = words_qus.index(word) index_are = index_you+1 index_last = words_qus.index('.') for s in range(index_are,index_last): #check the post of writer if words_qus[s]== 'of': index_of = words_qus.index(words_qus[s]) for x in range(index_are, index_of): i=7 for y in range(len(words_ans)-i, len(words_ans)): print words_ans[y].lower(), words_qus[x].lower() if words_qus[x].lower() == words_ans[y].lower(): name = 'Correct' break else: name = 'Wrong' #print sentences_qus[x],',,',sentences_ans[y] i= i-1 #address of the writer for p in range(index_of, index_last): j=7 for q in range(len(words_ans)-j, len(words_ans)): if words_qus[p].lower() == words_ans[q].lower(): address = 'Correct' break else: address = 'Wrong' #print address j= j-1 elif word == 'As' or word == 'as': index_as = words_ans.index(word) for s in range(index_as,len(words_qus)): if words_qus[s]== 'of': index_of = words_qus.index(words_qus[s]) for x in range(index_as, index_of): i= 7 for y in range(len(words_ans)-i, len(words_ans)): if sentence_qus[x].lower() == words_ans[y].lower() or sentence_qus[x].lower() == words_ans[y].lower() : name = 'Correct' print 'name',words_ans[y].lower() break else: name = 'Wrong' i= i-1 j= 7 for p in range(index_of, len(words_qus)): for q in range(len(words_ans)-j, len(words_ans)): if sentence_qus[p].lower() == words_ans[q].lower(): address = 'Correct' break else: address = 'Wrong' j= j-1 if name == 'Wrong' and address == 'Wrong' : i= 7 for y in range(len(words_ans)-i, len(words_ans)): if 'secretary' == words_ans[y].lower() or 'monitor' == words_ans[y].lower() or 'principle' == words_ans[y].lower() or "teacher" == words_ans[y].lower() or 'head' == words_ans[y].lower() or 'leader' == words_ans[y].lower() or 'students' == words_ans[y].lower() or 'student' == words_ans[y].lower(): name = 'Correct' address = 'Correct' break else: name = 'Wrong' i= i-1 #print name,address if name == 'Correct' and address == 'Correct': count = 0.5 return count , name, address def dateTimeVenue(answer): #date and time count = 0 time = '' date = '' showtime = 'true' showdate = 'true' showvenue = 'true' sentences_ans= sent_tokenize(answer) for sentence_ans in sentences_ans: #print sentence_ans dateTime = re.findall( r"""(?ix) # case-insensitive, verbose regex \b # match a word boundary (?: # match the following three times: (?: # either \d+ # a number, (?:\.|st|nd|rd|th|a\.m|p\.m)* # followed by a dot, st, nd, rd, or th (optional) | # or a month name (?:(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*) ) [\s./-]? # followed by a date separator or whitespace (optional) ){3} # do this three times \b """, sentence_ans) print dateTime if len(dateTime) == 3 or len(dateTime) == 2 or len(dateTime) == 1 : for d_time in dateTime: checkTime = re.findall((r'\d[\d]?\.\d\da\.m|\d[\d]?\.\d\dp\.m|\d[\d]?\.\d\d'),d_time) print 'c',checkTime if len(checkTime) != 0: time = d_time print 't',len(time) else: date = d_time print 'd',len(date) #venue venue = re.findall(r'in .([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|at .([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|venue .([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|place .([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|in: - .([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|at: -.([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|venue: -.([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|place: -.([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|in - .([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|at -.([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|venue -.([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|place -.([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)',sentence_ans.lower()) print len(venue),len(time),len(date) print "ve",venue if len(time) != 0 and len(date) != 0 and len(venue) != 0: count = 0.5 showtime = 'true' showdate = 'true' showvenue = 'true' break else: if len(time) == 0: showtime = 'false' else: showtime = 'true' if len(date) == 0: showdate = 'false' else: showdate = 'true' if len(venue) == 0: showvenue = 'false' else: showvenue = 'true' return count,showtime,showdate,showvenue<file_sep>/flask/templates/level1_dialogs.html <!DOCTYPE html> <head> <style type="text/css"> .form-group { width: 976px; } </style> <link href="/static/css/main2.css" rel="stylesheet"> </head> {% extends "home2.html" %} {% block content %} <body style="overflow: auto; overflow-x: hidden"> <br><br><br> <form style="margin-left: 100px;margin-top: -60px ;width: 1150px;height: 550px; background-image: url('/static/img/formback.png')" name="level1_dialogs" method="post" action="{{ url_for('evaluate_level1_dialogs') }}"> <br><br> <label style="margin-left: 150px; color: #A319A3;font-size: 20px; margin-top: -5px">Match the answers with the correct responses. (Tick the correct radio button.)</label><br><br> <div class="form-group" style="margin-top: -20px; text-align :left; margin-left: 150px;overflow: auto;height: 360px;overflow-x: hidden"> {% for key in data %} <input type="hidden" name="qNo" value="{{ key[0] }}"/> <br> <div> <div style="border: solid; border-color:#f08080; width: 900px; line-height:30px;"> <div style="padding-left: 10px"><font style="color: blue; font-size: 16px;">{{ key[3] |safe }}</font></div> </div> <br> <font style="color: #000000; line-height: 2em"> {{ key[2].split("1)")[0] |safe }} &nbsp; <div style="background-color: #f08080; display: inline;"> <font color="black" style="font-weight: bold"> 1)&nbsp; <input type="radio" name="one" value="a" required>a &nbsp;&nbsp; <input type="radio" name="one" value="b">b &nbsp;&nbsp; <input type="radio" name="one" value="c">c &nbsp;&nbsp; <input type="radio" name="one" value="d">d &nbsp;&nbsp; <input type="radio" name="one" value="e">e &nbsp;&nbsp; {# <input type="radio" name="one" value="f">f &nbsp;&nbsp;#} </font> </div> {{ key[2].split("1)")[1].split("2)")[0] |safe }} &nbsp; <div style="background-color: #f08080; display: inline;"> <font color="black" style="font-weight: bold"> 2)&nbsp; <input type="radio" name="two" value="a" required>a &nbsp;&nbsp; <input type="radio" name="two" value="b">b &nbsp;&nbsp; <input type="radio" name="two" value="c">c &nbsp;&nbsp; <input type="radio" name="two" value="d">d &nbsp;&nbsp; <input type="radio" name="two" value="e">e &nbsp;&nbsp; {# <input type="radio" name="two" value="f">f &nbsp;&nbsp;#} </font> </div> {{ key[2].split("2)")[1].split("3)")[0] |safe }} &nbsp; <div style="background-color: #f08080; display: inline;"> <font color="black" style="font-weight: bold"> 3)&nbsp; <input type="radio" name="three" value="a" required>a &nbsp;&nbsp; <input type="radio" name="three" value="b">b &nbsp;&nbsp; <input type="radio" name="three" value="c">c &nbsp;&nbsp; <input type="radio" name="three" value="d">d &nbsp;&nbsp; <input type="radio" name="three" value="e">e &nbsp;&nbsp; {# <input type="radio" name="three" value="f">f &nbsp;&nbsp;#} </font> </div> {{ key[2].split("3)")[1].split("4)")[0] |safe }} &nbsp; <div style="background-color: #f08080; display: inline;"> <font color="black" style="font-weight: bold"> 4)&nbsp; <input type="radio" name="four" value="a" required>a &nbsp;&nbsp; <input type="radio" name="four" value="b">b &nbsp;&nbsp; <input type="radio" name="four" value="c">c &nbsp;&nbsp; <input type="radio" name="four" value="d">d &nbsp;&nbsp; <input type="radio" name="four" value="e">e &nbsp;&nbsp; {# <input type="radio" name="four" value="f">f &nbsp;&nbsp;#} </font> </div> {{ key[2].split("4)")[1].split("5)")[0] |safe }} &nbsp; <div style="background-color: #f08080; display: inline;"> <font color="black" style="font-weight: bold"> 5)&nbsp; <input type="radio" name="five" value="a" required>a &nbsp;&nbsp; <input type="radio" name="five" value="b">b &nbsp;&nbsp; <input type="radio" name="five" value="c">c &nbsp;&nbsp; <input type="radio" name="five" value="d">d &nbsp;&nbsp; <input type="radio" name="five" value="e">e &nbsp;&nbsp; {# <input type="radio" name="five" value="f">f &nbsp;&nbsp;#} </font> </div> {{ key[2].split("5)")[1] |safe }} </font><br><br> </div> {% endfor %} </div> <br><br> <input id="markAnswers" onmouseover="bigImg(this)" onmouseout="normalImg(this)" type="image" src="/static/img/buttonMs.png" border="0" alt="Submit" name="sub_but" style="margin-left: 20px;margin-top: -130px;outline: none;" height="170" width="150"/> </form> </body> <script> function bigImg(x) { x.style.height = "200px"; x.style.width = "170px"; } function normalImg(x) { x.style.height = "170px"; x.style.width = "150px"; } </script> <script type="text/javascript"> function openWin() { window.location.href ="http://127.0.0.1:5000/level1_dialogs" } </script> {% endblock %}<file_sep>/flask/dialog.py __author__ = '<NAME>' import nltk import en import re def check(question, answer): # tagged_sent = nltk.pos_tag(question.split(" ")) # print tagged_sent # # tagged_sent = nltk.pos_tag(answer.split(" ")) # print tagged_sent answer_content_marks = 0 question_key_words = en.content.keywords(question) answer_array = answer.strip('.').split(" ") # print question_key_words # print answer_array for word in question_key_words: for answer in answer_array: if (answer.upper().find(word[1]) != -1) or (answer.lower().find(word[1]) != -1): answer_content_marks = answer_content_marks + 2 if answer_content_marks == 0: answer_content_marks = find_place(question, answer) if answer_content_marks == 0: answer_content_marks = find_date_time(question, answer) if answer_content_marks == 0: answer_content_marks = find_adjectives(question, answer_array) if answer_content_marks == 0: answer_content_marks = find_color(question, answer_array) # print answer_content_marks # print "Answer Content Marks : " + str(answer_content_marks) # print "##########" # print word_suggestions # answer_grammar_marks = GrammarCheckClass.check(answer) # print answer_grammar_marks return answer_content_marks def find_place(question, answer): place_list=['where', 'Where'] place = '' for word in place_list: if word in question: place = re.findall(r'in the.([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)' r'|at the.([A-Z]?[a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)', answer) if len(place) != 0: return len(place) return 0 def find_date_time(question, answer): date_time_list=['When', 'when', 'date', 'time'] for word in date_time_list: if word in question: dateTime = re.findall( r"""(?ix) # case-insensitive, verbose regex \b # match a word boundary (?: # match the following three times: (?: # either \d+ # a number, (?:\.|st|nd|rd|th|a\.m|p\.m)* # followed by a dot, st, nd, rd, or th (optional) | # or a month name (?:(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*) ) [\s./-]? # followed by a date separator or whitespace (optional) ){3} # do this three times \b """, answer) if len(dateTime) == 2 or len(dateTime) == 1: for d_time in dateTime: checkTime = re.findall((r'\d[\d]?\.\d\da\.m|\d[\d]?\.\d\dp\.m'), d_time) if len(checkTime) != 0: time = d_time return 2 print time else: date = d_time return 2 print date # print place # print len(place) return 0 def find_adjectives(question, answer_array): adjectives_array = [] answer_array_without_punctuation = [] adjectives = [] tagged_sent = nltk.pos_tag(question.split(" ")) # print tagged_sent if [word for word, pos in tagged_sent if pos == 'JJ']: adjectives = [word for word, pos in tagged_sent if pos == 'JJ'] for adj in adjectives: adj = adj.strip(',') adjectives_array.append(adj) for ans in answer_array: ans = ans.strip(",") answer_array_without_punctuation.append(ans) for word in answer_array_without_punctuation: if word in adjectives_array: return 2 return 0 def find_color(question, answer_array): status = False color_synonyms = ['color', 'colour', 'paint', 'dye'] color_names = ['Yellow', 'Red', 'Silver', 'Gray', 'Purple', 'Maroon', 'Green', 'Blue', 'Black', 'Pink', 'Magenta'] color_names_1 = [] for color in color_names: color_names_1.append(color.lower()) for color in color_synonyms: if question.find(color) > 0: status = True break if status == False: return 0 else: for color in color_names: if color in answer_array: return 2 for color in color_names_1: if color in answer_array: return 2 return 0 # # test # check("Fay: Hi Jerry. The school year is almost over. Do you have any plans for the summer holiday?", # "Actually, I'm plannin on to go down to Guizhou Province.", # "Fay: Really? Why would you go to Guizhou? It's not a very popular tourist site.") # find_place("Where are you?", "I'm in the class.") # find_date_time("When is the party?","2015/09/12")<file_sep>/flask/grammer.py import nltk from nltk.tokenize import sent_tokenize text="Keep quiet or go out." sentences=sent_tokenize(text) for sentence in sentences: ################simple present ########################################################## tagged_sent = nltk.pos_tag(sentence.split()) print tagged_sent if[word for word,pos in tagged_sent if pos == 'PRP']: noun= [word for word,pos in tagged_sent if pos == 'PRP'] nouns = noun[0],'PRP' currant = tagged_sent.index(nouns) if noun[0]=='He' or noun[0]=='She' or noun[0]=='It' or noun[0]=='he' or noun[0]=='she' or noun[0]=='it': if tagged_sent[currant+1][1]=='VBZ': if tagged_sent[currant+1][0]=='is': if tagged_sent[currant+2][1]=='VBG' or tagged_sent[currant+2][1]=='RB' : print sentence else: print sentence elif tagged_sent[currant+1][0]=='didn\'t' or tagged_sent[currant+1][0]=='did not': if tagged_sent[currant+2][1]=='VBP': print sentence else: print('wrong') elif tagged_sent[currant+1][1]=='RB': if tagged_sent[currant+2][1]=='VBZ': print sentence else: print('wrong') #past tense elif tagged_sent[currant+1][0]=='was': print sentence elif tagged_sent[currant+1][1]=='VBD': print sentence #future tense elif tagged_sent[currant+1][1]=='MD': if tagged_sent[currant+2][1]=='VB': print sentence elif tagged_sent[currant+2][0]=='not': print(sentence) else: print('wrong') elif noun[0]=='I': if tagged_sent[currant+1][1]=='VBP': print sentence elif tagged_sent[currant+1][0]=='don\'t' or tagged_sent[currant+1][0]=='do not': if tagged_sent[currant+2][1]=='VBP': print sentence else: print('wrong') elif tagged_sent[currant+1][1]=='RB': if tagged_sent[currant+2][1]=='VBZ': print sentence else: print('wrong') #past tense elif tagged_sent[currant+1][0]=='were': print sentence #future tense elif tagged_sent[currant+1][1]=='MD': if tagged_sent[currant+2][1]=='VB': print sentence elif tagged_sent[currant+2][0]=='not': print(sentence) else: print('wrong') elif tagged_sent[currant+1][1]=='RB': if tagged_sent[currant+2][1]=='VBP': print sentence elif tagged_sent[currant+2][1]=='VB': print sentence #check elif tagged_sent[currant+2][1]=='VBD': print sentence else: print('wrong') elif tagged_sent[currant+1][1]=='VBP': print sentence elif tagged_sent[currant+1][1]=='VB': print sentence #past tense elif tagged_sent[currant+1][0]=='were': print sentence elif tagged_sent[currant+1][1]=='VBD': print sentence #future tense elif tagged_sent[currant+1][1]=='MD': if tagged_sent[currant+2][1]=='VB': print sentence elif tagged_sent[currant+2][0]=='not': print(sentence) else: print('wrong') elif [word for word,pos in tagged_sent if pos == 'NN']: noun = [word for word,pos in tagged_sent if pos == 'NN'] nouns = noun[0],'NN' # currant = tagged_sent.index(nouns) # if currant==1: if tagged_sent[currant-1][1]=='DT': if tagged_sent[currant-1][0]=='This' or tagged_sent[currant-1][0]=='That': if tagged_sent[currant+1][1]=='VBZ': print sentence elif tagged_sent[currant+1][1]=='RB': if tagged_sent[currant+2][1]=='VBZ': print sentence else: print('wrong') #past tense elif tagged_sent[currant+1][1]=='VBD': print sentence elif tagged_sent[currant+1][0]=='was': print sentence #future tense elif tagged_sent[currant+1][1]=='MD': if tagged_sent[currant+2][1]=='VB': print sentence elif tagged_sent[currant+2][0]=='not': print(sentence) else: print 'wrong' else: print('wrong') else: if tagged_sent[currant+1][1]=='VBZ': print sentence elif tagged_sent[currant+1][1]=='RB': if tagged_sent[currant+2][1]=='VBZ': print sentence else: print('wrong') #past tense elif tagged_sent[currant+1][1]=='VBD': print sentence elif tagged_sent[currant+1][0]=='was': print sentence #future tense elif tagged_sent[currant+1][1]=='MD': if tagged_sent[currant+2][1]=='VB': print sentence elif tagged_sent[currant+2][0]=='not': print(sentence) else: print 'wrong' else: if tagged_sent[currant+1][1]=='VBZ': print sentence elif tagged_sent[currant+1][1]=='RB': if tagged_sent[currant+2][1]=='VBZ': print sentence else: print('wrong') #past tense elif tagged_sent[currant+1][1]=='VBD': print sentence elif tagged_sent[currant+1][0]=='was': print sentence #future tense elif tagged_sent[currant+1][1]=='MD': if tagged_sent[currant+2][1]=='VB': print sentence elif tagged_sent[currant+2][0]=='not': print(sentence) else: print 'wrong' elif( [word for word,pos in tagged_sent if pos == 'NNS']): noun=[word for word,pos in tagged_sent if pos == 'NNS'] nouns = noun[0],'NNS' currant = tagged_sent.index(nouns) if currant==1: if tagged_sent[currant-1][1]=='DT': if tagged_sent[currant-1][0]=='These' or tagged_sent[currant-1][0]=='Those': if tagged_sent[currant+1][1]=='VBP': print sentence elif tagged_sent[currant+1][1]=='VB': print sentence #past tense elif tagged_sent[currant+1][0]=='were': print sentence elif tagged_sent[currant+1][1]=='RB': if tagged_sent[currant+2][1]=='VBP': print sentence elif tagged_sent[currant+2][1]=='VB': print sentence else: print('wrong') #future tense elif tagged_sent[currant+1][1]=='MD': if tagged_sent[currant+2][1]=='VB': print sentence elif tagged_sent[currant+2][0]=='not': print(sentence) else: print('wrong') else: print('wrong') else: if tagged_sent[currant+1][1]=='VBP': print sentence elif tagged_sent[currant+1][1]=='VB': print sentence #past tense elif tagged_sent[currant+1][0]=='were': print sentence elif tagged_sent[currant+1][1]=='RB': if tagged_sent[currant+2][1]=='VBP': print sentence elif tagged_sent[currant+2][1]=='VB': print sentence else: print('wrong') #future tense elif tagged_sent[currant+1][1]=='MD': if tagged_sent[currant+2][1]=='VB': print sentence elif tagged_sent[currant+2][0]=='not': print(sentence) else: print('wrong') else: if tagged_sent[currant+1][1]=='VBP': print sentence elif tagged_sent[currant+1][1]=='VB': print sentence #past tense elif tagged_sent[currant+1][0]=='were': print sentence elif tagged_sent[currant+1][1]=='RB': if tagged_sent[currant+2][1]=='VBP': print sentence elif tagged_sent[currant+2][1]=='VB': print sentence else: print('wrong') #future tense elif tagged_sent[currant+1][1]=='MD': if tagged_sent[currant+2][1]=='VB': print sentence elif tagged_sent[currant+2][0]=='not': print(sentence) else: print('wrong') elif [word for word,pos in tagged_sent if pos == 'NNP']: noun = [word for word,pos in tagged_sent if pos == 'NNP'] nouns = noun[0],'NNP' # currant = tagged_sent.index(nouns) if tagged_sent[currant+1][1]=='VBZ': print sentence elif tagged_sent[currant+1][1]=='RB': if tagged_sent[currant+2][1]=='VBZ': print sentence else: print('wrong') #past tense elif tagged_sent[currant+1][0]=='was': print sentence elif tagged_sent[currant+1][1]=='VBD': print sentence #future tense elif tagged_sent[currant+1][1]=='MD': if tagged_sent[currant+2][1]=='VB': print sentence elif tagged_sent[currant+2][0]=='not': print(sentence) else: print 'wrong' # #simple present 2 elif [word for word,pos in tagged_sent if pos == 'NNS']: # noun = [word for word,pos in tagged_sent if pos == 'NNS'] nouns = noun[0],'NNS' # currant = tagged_sent.index(nouns) # if tagged_sent[currant+1][0]=='do' or tagged_sent[currant+1][0]=='do not' or tagged_sent[currant+1][0]=='don\'t': if tagged_sent[currant+2][1]=='VBP' or tagged_sent[currant+2][1]=='VB': print(sentence) else: print 'wrong' elif tagged_sent[currant+1][1]=='RB': if tagged_sent[currant+2][0]=='do' or tagged_sent[currant+2][0]=='do not' or tagged_sent[currant+2][0]=='don\'t': if tagged_sent[currant+3][1]=='VBP' or tagged_sent[currant+3][1]=='VB': print sentence else: print('wrong') elif tagged_sent[currant+1][0]=='did' or tagged_sent[currant+1][0]=='did not' or tagged_sent[currant+1][0]=='didn\'t': if tagged_sent[currant+2][1]=='VB': print(sentence) else: print('wrong') else: print 'wrong' else: print('wrong') ###################simple present ########################################################## ########################simple past ############################################################### ###################simple past ########################################################## <file_sep>/flask/note.py __author__ = 'Darani' import numpy import nltk from nltk import pos_tag, word_tokenize from nltk.tag import pos_tag from nltk.tokenize import sent_tokenize import re import en import keywords def sum_of_words(answer): sum = 0 for word1 in word_tokenize(answer): if word1 == '.' or word1 == ',' or word1 == '\'' or word1 == '\"' or word1 == ':' or word1 == ';' or word1 == '?' or word1 == '/' or word1 == '\\' or word1 == '|' or word1 == ']' or word1 == '[' or word1 == '}' or word1 == '{' or word1 == '(' or word1 == ')' or word1 == '*' or word1 == '&' or word1 == '^' or word1 == '%' or word1 == '$' or word1 == '#' or word1 == '@' or word1 == '!' or word1 == '`' or word1 == '~' or word1 == '-' or word1 == '_' or word1 == '='or word1 == '+': print 'error' else: sum = sum +1 #print word1 return sum def word_count(answer,question): words_qus = word_tokenize(question) count = 0 status1 = 'false' for word in words_qus: if en.is_number(word) and words_qus[words_qus.index(word)+1]== 'words': if sum_of_words(answer) >= word: print word count = count+0.5 status1 = 'true' if status1 == 'false': count = count+0.5 return count def note_receiver(answer): count = 0 status = 'false' tag_words = pos_tag(answer.split()) if (tag_words[0][1]=='NNP'or tag_words[1][1]=='NNP') and (tag_words[0][0].isupper() or tag_words[1][0].isupper): if (tag_words[0][1] == 'Dear' or tag_words[1][1] == 'Dear' ): print tag_words[0][0] else: count = count + 0.5 status = 'true' return count,status def note_writer(answer): count = 0 status = 'false' status_your = 'correct' tag_words = pos_tag(answer.split()) print 'val:', len(tag_words) word = tag_words[len(tag_words)-1][0] print 'll ',tag_words[len(tag_words)-1][0] if tag_words[len(tag_words)-3][0] == 'Yours' and (tag_words[len(tag_words)-2][0] == 'sincerely,' or tag_words[len(tag_words)-2][0] == 'Sincerely,' or tag_words[len(tag_words)-2][0] == 'faithfully,' or tag_words[len(tag_words)-2][0] == 'Faithfully,'): count = count + 0 status_your = 'wrong' elif tag_words[len(tag_words)-2][0] == 'Yours' and (tag_words[len(tag_words)-1][0] == 'sincerely,' or tag_words[len(tag_words)-1][0] == 'Sincerely,' or tag_words[len(tag_words)-1][0] == 'faithfully,' or tag_words[len(tag_words)-1][0] == 'Faithfully,'): count = count + 0 status_your = 'wrong' elif tag_words[len(tag_words)-2][0] == 'Your' : count = count + 0 status_your = 'wrong' if tag_words[len(tag_words)-1][1] == 'NNP' and word[0].isupper() : if (word == 'Faithfully,') or (word == 'Sincerely,'): print 'yes' else: print tag_words[len(tag_words)-1][0] count = count + 0.5 status = 'true' print 'stat',status print 'stat1',status_your return count,status,status_your def note_body(answer,question): count = 0 sentences_qus= sent_tokenize(question) for sentence_qus in sentences_qus: top = keywords.top(sentence_qus) words_ans = word_tokenize(answer) matching_count = 0 for count,word in top: for word_ans in words_ans: if word == word_ans: print word matching_count = matching_count+1 different = len(top)- matching_count if (different+2)== 0 or (different+2)== 1 or (different+2)== 2: count = count + 0.5 return count
7c01dffec3beb4bfe87fba1b21326be1fdd13efd
[ "Python", "HTML" ]
10
Python
amilamadhushanka/englishbuddy
1b6d870a4ec6a77463248d579e0b15f61c42cc69
ac593a48b98791ae5dca85157578ceaf11f885cd
refs/heads/master
<repo_name>LupusAnay/gateway-prototype<file_sep>/auth/tests/test_session.py import json from unittest import skip from flask import current_app from auth.tests.base_test_case import BaseTestCase from auth.tests.api_methods import register_user, login, logout class TestSession(BaseTestCase): def setUp(self): super().setUp() response = register_user(self, 'user', 'pass', '<EMAIL>') data = json.loads(response.data.decode()) self.token = data.get('jwt') def test_login(self): response = login(self, 'user', 'pass') current_app.logger.info(response) self.assert200(response) data = json.loads(response.data.decode()) self.assertEqual(self.token, data.get('jwt')) def test_login_with_wrong_data(self): response_wrong_both = login(self, 'wrong_user', 'wrong_pass') response_wrong_pass = login(self, 'user', 'wrong_pass') response_wrong_user = login(self, 'wrong_user', 'pass') self.assert404(response_wrong_both) self.assert404(response_wrong_pass) self.assert404(response_wrong_user) @skip('Not implemented') def test_logout(self): response = logout(self, self.token) self.assertEqual(response.status_code, 204) def test_login_with_invalid_json(self): response = self.client.post('/session', data=json.dumps('wrong_data'), content_type='application/json') self.assertEqual(response.status_code, 422) <file_sep>/serivce/run.py import requests import json from flask.cli import FlaskGroup from flask import jsonify from serivce.app import create_app app = create_app() data = json.dumps(dict(name='service', port='8000')) headers = {'Content-type': 'application/json'} requests.post('http://localhost:5000/instance', headers=headers, data=data) cli = FlaskGroup(app) if __name__ == '__main__': cli() <file_sep>/auth/app/views/__init__.py from flask import Blueprint, Response, make_response, jsonify, request, \ current_app from jsonschema import validate, ValidationError from functools import wraps from ..models import User def require_auth(role='user'): # TODO: Implement proper roles check """ Checks JWT from request 'Authorization' header WARN: roles not implemented :param: role: role that required to proceed request :return: Returning 403 error if token is not valid, otherwise executes decorated function """ def wrap(f): @wraps(f) def wrapped_f(*args, **kwargs): current_app.logger.info('Attempt to access to protected resource') header = request.headers.get('Authorization') if header is not None: token = header.replace('Bearer ', '') payload = User.decode_auth_token(token) if type(payload) is dict: current_app.logger.info('Access granted') return f(*args, **kwargs) current_app.logger.info('Attempt rejected, invalid token') return create_response(403, status='error', message='forbidden') return wrapped_f return wrap def create_response(code=204, **kwargs) -> Response: """ Creating JSON response from key word arguments :param code: Status code of response :param kwargs: key=value args to create json with :return: Response object with given status code and arguments """ return make_response(jsonify(kwargs), code) def validate_json(schema): """ Validating JSON from request, comparing it with given JSON schema :param schema: JSON Schema to compare it with request's :return: Response with status code 422 if JSON is invalid or result of decorated function json is valid """ def decorator(func): @wraps(func) def wrapper(*args, **kw): try: validate(request.get_json(), schema) except ValidationError as e: current_app.logger.info( f'User provided wrong json schema: {request.get_json()}') return create_response(422, status='error', reason='Invalid json', message=e.message) return func(*args, **kw) return wrapper return decorator users_blueprint = Blueprint('auth', __name__) session_blueprint = Blueprint('session', __name__) from .SessionAPI import SessionAPI from .UsersAPI import UsersAPI session_api = SessionAPI.as_view('session_api') users_api = UsersAPI.as_view('users_api') users_blueprint.add_url_rule( '/users', view_func=users_api, methods=['POST'] ) users_blueprint.add_url_rule( '/users/<string:username>', view_func=users_api, methods=['GET', 'PUT', 'DELETE'] ) session_blueprint.add_url_rule( '/session', view_func=session_api ) <file_sep>/registry/app/models.py from app import db class Service(db.Model): __tablename__ = 'services' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String, nullable=False, unique=True) def __init__(self, name): self.name = name class Instance(db.Model): __tablename__ = 'instances' id = db.Column(db.Integer, primary_key=True, autoincrement=True) service_id = db.Column(db.Integer, db.ForeignKey('services.id'), nullable=False) host = db.Column(db.String, nullable=False, default='http://localhost') port = db.Column(db.Integer, nullable=False) service = db.relationship('Service', backref=db.backref('posts', lazy=True)) def as_dict(self): return { 'host': self.host, 'port': self.port } def __init__(self, host, port, service_id): self.host = host self.port = port self.service_id = service_id <file_sep>/serivce/app/views.py from flask import Blueprint, make_response, jsonify, request from functools import wraps from serivce.jwt_decoder import decode_auth_token service_blueprint = Blueprint('service', __name__, url_prefix='/service') def require_auth(role=''): def wrap(f): @wraps(f) def wrapped_f(*args, **kwargs): token = request.headers.get('Authorization').replace('Bearer ', '') payload = decode_auth_token(token) print(payload) if type(payload) is not dict: return make_response(jsonify({'error': 'token_error', 'token': payload})) return f(*args, **kwargs) return wrapped_f return wrap @service_blueprint.route('/') @require_auth(role='fuck') def get(): token = request.headers.get('Authorization').replace('Bearer ', '') data = decode_auth_token(token) print('im here') response = { 'result': 'success', 'secret_resource': 'hello from hell', 'token': data } print('im after token decoding', response) return make_response(jsonify(response)), 200 <file_sep>/auth/tests/test_update_user.py import json from auth.tests.base_test_case import BaseTestCase from auth.tests.api_methods import update_user, register_user class TestUpdateUser(BaseTestCase): def setUp(self): super().setUp() register_user(self, 'wrong_user', 'pass', '<EMAIL>') response = register_user(self, 'user', 'pass', '<EMAIL>') data = json.loads(response.data.decode()) self.token = data.get('jwt') def test_update_user(self): new_info = dict(email='<EMAIL>', username='new_user', password='<PASSWORD>') response = update_user(self, self.token, 'user', new_info) self.assertEqual(response.status_code, 204) def test_update_user_without_rights(self): new_info = dict(email='<EMAIL>', username='new_user', password='<PASSWORD>') response_wrong_token = update_user(self, 'wrong_token', 'user', new_info) response_wrong_user = update_user(self, self.token, 'wrong_user', new_info) self.assertEqual(response_wrong_user.status_code, 403) self.assertEqual(response_wrong_token.status_code, 403) def test_update_without_data(self): new_info = None response = update_user(self, self.token, 'user', new_info) self.assertEqual(response.status_code, 422) def test_update_with_taken_data(self): new_info = dict(email='<EMAIL>', username='wrong_user', password='<PASSWORD>') response = update_user(self, self.token, 'user', new_info) self.assertEqual(response.status_code, 409) <file_sep>/registry/app/views.py from functools import wraps from jsonschema import validate, ValidationError from flask import Blueprint, make_response, jsonify, request, current_app from flask.views import MethodView from app import db from app.models import Service, Instance instance_blueprint = Blueprint('registry', __name__) register_schema = { "type": "object", "properties": { "name": {"type": "string"}, "port": {"type": "string"} }, "required": ["name", "port"] } def response(code=200, **kwargs): rsp = jsonify(kwargs) if kwargs else '' return make_response(rsp), code def validate_schema(schema): def decorator(f): @wraps(f) def wrapper(*args, **kw): try: validate(request.get_json(), schema) except ValidationError as e: print(e.message) return response(400, status='error', reason='wrong json', message=e.message) return f(*args, **kw) return wrapper return decorator class InstanceAPI(MethodView): @staticmethod def get(name): service = Service.query.filter_by(name=name).first() inst_list = Instance.query.filter_by(service_id=service.id).all() print(inst_list) inst = [x.as_dict() for x in inst_list] return response(200, instances=inst) @staticmethod @validate_schema(register_schema) def post(): host = request.remote_addr port = request.get_json().get('port') name = request.get_json().get('name') service = Service.query.filter_by(name=name).first() current_app.logger.info( f"Searching for service {name}, result: {service}") if not service: current_app.logger.info(f"No service with name {name} " f"were found. Creating new one") service = Service(name) db.session.add(service) db.session.commit() service = Service.query.filter_by(name=name).first() instance = Instance(host, port, service.id) # TODO: make error exception db.session.add(instance) db.session.commit() return response(204) @staticmethod @validate_schema(register_schema) def delete(): port = request.get_json().get('port') host = request.remote_addr Instance.query.filter_by(port=port, host=host).delete() db.session.commit() return response(204) instance_view = InstanceAPI.as_view('register_api') instance_blueprint.add_url_rule('/instance', view_func=instance_view, methods=['POST', 'DELETE']) instance_blueprint.add_url_rule('/instance/<string:name>', view_func=instance_view, methods=['GET']) <file_sep>/auth/app/models.py import jwt from sqlalchemy import inspect from datetime import datetime, timedelta from flask import current_app from . import db, bcrypt class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(255), nullable=False, unique=True) email = db.Column(db.String(255), nullable=False, unique=True) password = db.Column(db.String(255), nullable=False) role = db.Column(db.String(255), nullable=False) registered_on = db.Column(db.DateTime, nullable=False) def __init__(self, user, password, email, role='user'): self.username = user self.password = <PASSWORD>.generate_password_hash(password, 5).decode() self.email = email self.role = role self.registered_on = datetime.now() def as_dict(self): return {c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs} # TODO: Implement role functional def encode_auth_token(self): try: payload = { 'exp': datetime.utcnow() + timedelta(days=1, seconds=0), 'iat': datetime.utcnow(), 'user_id': self.id, 'username': self.username, 'user_role': self.role } return jwt.encode(payload, current_app.config.get('SECRET_KEY'), algorithm='HS256') except Exception as e: return e @staticmethod def decode_auth_token(auth_token): try: payload = jwt.decode(auth_token, current_app.config.get('SECRET_KEY'), algorithm='HS256') return payload except jwt.ExpiredSignatureError: return 'Signature expired. Please log in again.' except jwt.InvalidTokenError: return 'Invalid token. Please log in again.' <file_sep>/auth/tests/test_create_user.py import json from flask import current_app from auth.tests.base_test_case import BaseTestCase from auth.tests.api_methods import register_user class TestCreateUser(BaseTestCase): def test_registration(self): response = register_user(self, 'user', '<PASSWORD>', '<EMAIL>') current_app.logger.info(response) self.assert200(response) data = json.loads(response.data.decode()) self.assertTrue(data.get('jwt') is not None) def test_registration_with_already_registered_user(self): register_user(self, 'user', 'password', '<EMAIL>') response = register_user(self, 'user', '<PASSWORD>', '<EMAIL>') self.assertEqual(response.status_code, 409) current_app.logger.info(response) data = json.loads(response.data.decode()) self.assertTrue(data is not None) self.assertEqual(data['status'], 'error') def test_register_with_invalid_json(self): response = self.client.post("/users", data=json.dumps("wrong_data"), content_type='application/json') self.assertEqual(response.status_code, 422) <file_sep>/serivce/app/__init__.py import requests from flask import Flask, jsonify from flask_cors import CORS def create_app(): app = Flask(__name__) CORS(app) from serivce.app.views import service_blueprint app.register_blueprint(service_blueprint) return app <file_sep>/auth/app/__init__.py import os from flask import Flask from flask_bcrypt import Bcrypt from flask_cors import CORS from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() bcrypt = Bcrypt() def create_app(config_filename='app.config.DevelopmentConfig'): app = Flask(__name__) CORS(app) app_settings = os.getenv( 'APP_SETTINGS', config_filename ) app.config.from_object(app_settings) bcrypt.init_app(app) db.init_app(app) from .views import session_blueprint, users_blueprint app.register_blueprint(session_blueprint) app.register_blueprint(users_blueprint) @app.shell_context_processor def ctx(): return {'app': app, 'db': db} return app <file_sep>/auth/run.py import os import json import requests from flask_migrate import Migrate, MigrateCommand from flask.cli import FlaskGroup from app import create_app, db app = create_app() migrate = Migrate(app, db) cli = FlaskGroup(app) app.cli.add_command('db', MigrateCommand) cli.load_dotenv = os.getenv('FLASK_LOAD_DOTENV', 'False') data = json.dumps(dict(name='auth', port='8001')) headers = {'Content-type': 'application/json'} requests.post('http://localhost:5000/instance', headers=headers, data=data) @cli.command('recreate_db') def recreate_db(): db.drop_all() db.create_all() db.session.commit() if __name__ == '__main__': cli() <file_sep>/gateway/app/__init__.py from flask import Flask from flask_cors import CORS def create_app(): app = Flask(__name__) CORS(app) from gateway.app.views import proxy_blueprint app.register_blueprint(proxy_blueprint) return app <file_sep>/auth/tests/base_test_case.py from flask import current_app from flask_testing import TestCase from auth.app import create_app, db class BaseTestCase(TestCase): def create_app(self): return create_app('auth.app.config.TestingConfig') def setUp(self): db.drop_all() current_app.logger.info('Creating database') db.create_all() db.session.commit() def tearDown(self): current_app.logger.info('Dropping database') db.session.remove() db.drop_all() <file_sep>/auth/Dockerfile FROM python:alpine WORKDIR /usr/src/app COPY ./requirements.txt /usr/src/app/requirements.txt RUN apk update && \ apk add postgresql-libs && \ apk add --virtual .build-deps gcc musl-dev postgresql-dev && \ apk add --no-cache --virtual .pynacl_deps build-base python3-dev libffi-dev && \ python3 -m pip install -r requirements.txt --no-cache-dir && \ apk --purge del .build-deps .pynacl_deps COPY ./entrypoint.sh /usr/src/app/entrypoint.sh RUN ["chmod", "+x", "/usr/src/app/entrypoint.sh"] COPY . /usr/src/app CMD ["/usr/src/app/entrypoint.sh"]<file_sep>/auth/tests/test_get_user_info.py import json from jsonschema import validate from auth.tests.base_test_case import BaseTestCase from auth.tests.api_methods import get_user_info, register_user, delete_user info_schema = { 'type': 'object', 'properties': { 'status': {'type': 'string'}, 'user_info': { 'type': 'object', 'properties': { 'email': {'type': 'string', 'format': 'email'}, 'id': {'type': 'integer'}, 'registered_on': { 'type': 'string', 'format': 'datetime' }, 'role': {'type': 'string'}, 'username': {'type': 'string'} }, 'required': ['email', 'id', 'registered_on', 'role', 'username'] } }, 'required': ['status', 'user_info'] } class TestGetUserInfo(BaseTestCase): def setUp(self): super().setUp() register_user(self, 'wrong_user', 'pass', '<EMAIL>') response = register_user(self, 'user', 'pass', '<EMAIL>') data = json.loads(response.data.decode()) self.token = data.get('jwt') def test_get_user_info(self): response = get_user_info(self, self.token, 'user') self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode()) validate(data, info_schema) def test_get_user_info_without_rights(self): response_wrong_user = get_user_info(self, self.token, 'wrong_user') response_wrong_token = get_user_info(self, 'wrong_token', 'user') self.assertEqual(response_wrong_user.status_code, 403) self.assertEqual(response_wrong_token.status_code, 403) def test_get_info_without_user(self): delete_user(self, self.token, 'user') response = get_user_info(self, self.token, 'user') self.assert404(response) <file_sep>/auth/tests/api_methods.py from flask import Response, current_app import json def register_user(self, username, password, email) -> Response: return self.client.post("/users", data=json.dumps(dict(username=username, password=<PASSWORD>, email=email)), content_type='application/json') def login(self, username, password) -> Response: return self.client.post('/session', data=json.dumps(dict(username=username, password=<PASSWORD>) ), content_type='application/json') def logout(self, token) -> Response: return self.client.delete('/session', headers=dict(authorization=f'Bearer {token}') ) def delete_user(self, token, username) -> Response: return self.client.delete(f'/users/{username}', headers=dict(authorization=f'Bearer {token}')) def get_user_info(self, token, username): return self.client.get(f'/users/{username}', headers=dict(authorization=f'Bearer {token}')) def update_user(self, token, username, new_info: dict) -> Response: return self.client.put(f'/users/{username}', data=json.dumps(new_info), content_type='application/json', headers=dict(authorization=f'Bearer {token}')) <file_sep>/gateway/app/views.py import requests from flask import Blueprint, make_response, request proxy_blueprint = Blueprint('proxy', __name__) app_methods = ['GET', 'POST', 'PUT', 'DELETE'] @proxy_blueprint.route('/<string:name>/', defaults={'path': ''}, methods=app_methods) @proxy_blueprint.route('/<string:name>/<path:path>', methods=app_methods) def service_request(name, path): instances = requests.get(f'http://localhost:5000/instance/{name}') data = instances.json() instance = data.get('instances')[0] resp = requests.request( method=request.method, url=f"http://{instance.get('host')}:{instance.get('port')}/{path}", headers={key: value for key, value in request.headers if key != 'Host'}, data=request.get_data(), allow_redirects=False) return make_response(resp.content, resp.status_code) <file_sep>/serivce/jwt_decoder/__init__.py import jwt def decode_auth_token(auth_token): try: payload = jwt.decode(auth_token, 'key', algorithm='HS256') return payload except jwt.ExpiredSignatureError: return 'Signature expired. Please log in again.' except jwt.InvalidTokenError: return 'Invalid token. Please log in again.' <file_sep>/auth/app/config.py import os basedir = os.path.abspath(os.path.dirname(__file__)) pg_user = os.getenv('DB_USER', 'postgres') pg_pw = os.getenv('DB_PASS', '<PASSWORD>') pg_name = os.getenv('DB_NAME', 'postgres') pg_host = os.getenv('DB_HOST', 'localhost') pg_port = os.getenv('DB_PORT', '5432') postgre_url = f"postgresql://{pg_user}:{pg_pw}@{pg_host}:{pg_port}/{pg_name}" sqlite_db = 'sqlite:////tmp/auth.db' class BaseConfig: SECRET_KEY = os.getenv('SECRET_KEY', 'key') SQLALCHEMY_TRACK_MODIFICATIONS = False DEBUG = False SQLALCHEMY_DATABASE_URI = sqlite_db class TestingConfig(BaseConfig): DEBUG = True class DevelopmentConfig(BaseConfig): DEBUG = True class ProductionConfig(BaseConfig): SQLALCHEMY_DATABASE_URI = postgre_url <file_sep>/auth/tests/test_delete_user.py import json from auth.tests.base_test_case import BaseTestCase from auth.tests.api_methods import register_user, delete_user class TestDeleteUser(BaseTestCase): def setUp(self): super().setUp() register_user(self, 'wrong_user', 'pass', '<EMAIL>') response = register_user(self, 'user', 'pass', '<EMAIL>') data = json.loads(response.data.decode()) self.token = data.get('jwt') def test_delete_user(self): response = delete_user(self, self.token, 'user') self.assertEqual(response.status_code, 204) def test_delete_user_without_permission(self): response_invalid_token = delete_user(self, 'invalid_token', 'user') response_invalid_user = delete_user(self, self.token, 'wrong_user') self.assertEqual(response_invalid_token.status_code, 403) self.assertEqual(response_invalid_user.status_code, 403) <file_sep>/auth/app/views/UsersAPI.py from flask import request, current_app from flask.views import MethodView from sqlalchemy import exc from . import create_response, validate_json, require_auth from .. import db, bcrypt from ..models import User register_schema = { 'type': 'object', 'properties': { 'username': {'type': 'string'}, 'password': {'type': 'string'}, 'email': {'type': 'string', 'format': 'email'} }, 'required': ['username', 'password', 'email'] } update_schema = { 'type': 'object', 'properties': { 'username': {'type': 'string'}, 'password': {'type': 'string'}, 'email': {'type': 'string', 'format': 'email'} } } class UsersAPI(MethodView): @staticmethod @require_auth() def get(username): """ Returning user info object This request is 'self_only', the request can be executed only if the bearers's username is the same as the parameter `username` :param username: Username of user about whom info need to be returned :return: Returning user info structure or 404 if user not found, or 403 if requesting info without authorization """ current_app.logger.info('Attempt to get info about user') token = request.headers.get('Authorization').replace('Bearer ', '') payload = User.decode_auth_token(token) if payload['username'] != username: current_app.logger.info('Attempt rejected, wrong username') return create_response(403, status='error', message='forbidden') user = User.query.filter_by(username=username).first() if user is None: current_app.logger.info('Attempt rejected, no such user') return create_response(404, status='error', message='not found') user_dict = user.as_dict() user_dict.pop('password') current_app.logger.info('User info returned') return create_response(200, status='success', user_info=user_dict) @staticmethod @validate_json(register_schema) def post(): """ Creating a new user :return: Returning 200 and JWT if data is valid, 409 if user with such data is exists, or 422 if provided invalid JSON schema """ current_app.logger.info('Attempt to register a new user') data = request.get_json() user = User( user=data.get('username'), password=data.get('<PASSWORD>'), email=data.get('email') ) db.session.add(user) try: db.session.commit() except exc.IntegrityError: db.session.rollback() current_app.logger.info('Rejecting attempt to create a new user. ' 'Such user already exists') return create_response(409, status='error', message='email taken') current_app.logger.info('New user created') token = user.encode_auth_token().decode() return create_response(200, jwt=token) @staticmethod @require_auth() @validate_json(update_schema) def put(username): # TODO: Implement roles logic, admins should be allowed to this method """ Updating user info This request is 'self_only', the request can be executed only if the bearers's username is the same as the parameter `username` :param username: Username of user to update :return: Returning 204 if info updated or 409 if cannot update due conflict or 404 in there is no user with such username, or 403 if token is invalid """ current_app.logger.info('Attempt to change user data') data = request.get_json() if 'password' in data: pw = data['password'] data['password'] = bcrypt.generate_password_hash(pw, 5).decode() token = request.headers.get('Authorization').replace('Bearer ', '') payload = User.decode_auth_token(token) if payload['username'] == username: try: User.query.filter_by(username=username).update(data) db.session.commit() except exc.IntegrityError: db.session.rollback() current_app.logger.info('Attempt rejected. Data conflict') return create_response(409, status='error') current_app.logger.info('User data changed') return create_response() current_app.logger.info('Attempt rejected. Insufficient rights') return create_response(403, status='error', message='forbidden') @staticmethod @require_auth() def delete(username): # TODO: Implement roles logic, admins should be allowed to this method """ Deleting user This request is 'self_only', the request can be executed only if the bearers's username is the same as the parameter `username` :param: username: Username of user to delete :return: Returning 204 if user deleted or 404 if there is no such user or 403 if client do not have rights to delete user """ current_app.logger.info('Attempt to delete user') token = request.headers.get('Authorization').replace('Bearer ', '') payload = User.decode_auth_token(token) if payload['username'] == username: try: User.query.filter_by(username=username).delete() db.session.commit() except exc.IntegrityError: db.session.rollback() current_app.logger.info('Attempt rejected. Data conflict') return create_response(400, status='error') current_app.logger.info('User deleted') return create_response() current_app.logger.info('Attempt rejected. Insufficient rights') return create_response(403, status='error', message='forbidden') <file_sep>/auth/requirements.txt pip setuptools click alembic bcrypt cffi Click Flask Flask-Bcrypt Flask-Cors Flask-Migrate Flask-Script Flask-SQLAlchemy Flask-Testing itsdangerous Jinja2 Mako MarkupSafe pycparser python-dateutil python-editor six SQLAlchemy Werkzeug coverage psycopg2 psycopg2-binary python-dotenv PyJWT<file_sep>/README.md # Gateway Prototype Proof of concept for the "Movie List" microservice based project. Purposes of this application - is to show possibility of creating microservice based application using stack Python/Flask/Docker **Work In Progress** For this moment finished auth service. And created simple version of gateway, which just proxying requests to given service. Also created simple service registry, without health checking and other required features. <file_sep>/auth/app/views/SessionAPI.py from flask import request, current_app from flask.views import MethodView from .. import bcrypt from ..models import User from . import validate_json, create_response, require_auth login_schema = { "type": "object", "properties": { "username": {"type": "string"}, "password": {"type": "string"} }, "required": ["username", "password"] } class SessionAPI(MethodView): @staticmethod @validate_json(login_schema) def post(): """ Post method Accepting user's username and password Creating JWT for user :return: Returning auth token in credentials are valid, else returning 404 error. If provided JSON is invalid returning 422 """ username = request.get_json().get('username') password = request.get_json().get('password') user = User.query.filter_by(username=username).first() if user is not None: if bcrypt.check_password_hash(user.password, password): token = user.encode_auth_token().decode() current_app.logger.info('Detected user login') return create_response(code=200, jwt=token) current_app.logger.info("User's login rejected") return create_response(code=404, status='error', message='Credentials rejected') @staticmethod @require_auth() def delete(token_data=None): # TODO: Implement token invalidation # in microservice structure token invalidation need to be implemented # on API gateway level, but token blacklisting won't be redundant """ ---NOT IMPLEMENTED--- Blacklisting user's token. :return: Returning 403 if token is invalid """ current_app.logger.warning('Attempt to logout. ' 'Not implemented, request has no effect') return create_response(202, status='none')
12777ab271b6731202dbf94f3ae983c4ab4ecda8
[ "Markdown", "Python", "Text", "Dockerfile" ]
25
Python
LupusAnay/gateway-prototype
e40426e05ca7b2a83bfd8d31fec252086f586eb8
fe4244ad1c08a545869eadda77744238381d0ca0
refs/heads/master
<repo_name>FernoSantiago/appResultadosDigitais<file_sep>/spec/views/leads/leads_spec.rb require 'rails_helper' require 'capybara/rspec' RSpec.describe "Leads Integration Tests", :type => :feature do let(:user) { create(:user, email: '<EMAIL>', senha: '<PASSWORD>!') } let(:login_page) { LoginPageObject.new } let(:index_page) { IndexLeadsPageObject.new } let(:edit_page) { EditLeadsPageObject.new } context '#valid_user' do before :each do login_page.visit_page.login(user) end context 'List Leads' do let!(:lead) { create(:lead, email: '<EMAIL>') } it "Render the Lists of Leads" do index_lead_page.visit_page expect(index_lead_page).to have_lead(lead) end end it 'Click on New' do index_lead_page.visit_page new_lead_page = index_lead_page.click_on_insert_lead expect(new_lead_page).to have_current_path(new_admin_lead_path) end context "Create a Lead" do let(:new_lead) { build(:lead, email: '<EMAIL>') } before { index_lead_page.visit_page } it 'Creates a valid lead' do new_lead_page = index_lead_page.click_on_insert_lead new_lead_page.fill_in_with_lead(new_lead) edit_lead_page = new_lead_page.click_on_save #edit_lead_page == form expect(edit_lead_page).to have_content(new_lead) end it 'Create with invalid value' do new_lead_page = index_lead_page.click_on_insert_lead new_lead_page.fill_in_with_lead(new_lead) new_lead_page.make_blank_field('#lead_email') new_lead_page.click_on_save expect(new_lead_page).to have_message('Não foi possível criar o Lead, por favor verifique os campos') end end context "Editing a Lead" do let!(:lead) { create(:lead, email: '<EMAIL>') } before { index_lead_page.visit_page } it 'Edit the lead with success' do edit_lead_page = index_lead_page.click_on_edit('<EMAIL>') edit_lead_section_page = edit_lead_page.click_on_edit edit_lead_section_page.change_field('#inputEmail', lead) edit_lead_page = edit_lead_section_page.click_on_save expect(edit_lead_page).to have_message('Lead atualizado com sucesso.') end it 'Edit with invalid value' do edit_lead_page = index_lead_page.click_on_edit('<EMAIL>') edit_lead_page.change_field('#lead_email', '') edit_lead_page.click_on_save expect(edit_lead_page).to have_invalid_message_on_div('Não foi possível atualizar o Lead.') end end context "Remove lead" do let!(:lead) { create(:lead, email: '<EMAIL>') } before { index_lead_page.visit_page } it 'Remove the lead' do edit_lead_page = index_lead_page.click_on_edit('<EMAIL>') index_lead_page = edit_lead_page.click_on_remove expect(index_lead_page).to have_message('Lead excluído!') end end end end <file_sep>/spec/views/leadspage/edit_leads_section_page.rb class EditLeadsSectionPageObject < BaseObject def click_on_save click_on 'Salvar' end end <file_sep>/spec/views/loginpage/login_page.rb class LoginPageObject < BaseObject Capybara.current_driver = :selenium Capybara.app_host = 'https://app-staging.rdstation.com.br' def visit_page visit '/login' self end def login(user) within("#login-form") do fill_in 'Email', with: user.email fill_in 'Senha', with: user.senha end click_button 'Entrar' end end <file_sep>/README.md Copyright (C) 2017 - 2017 [<NAME>](https://github.com/FernoSantiago) <file_sep>/spec/views/leadspage/new_leads_page.rb class NewLeadsPageObject < BaseObject def has_current_path?(path) current_path == path end def fill_in_with_lead(lead) find("#lead_email").set(lead.email) end def click_on_save click_on 'Salvar' EditLeadsPageObject.new end def has_message?(message) has_content?(message) end def make_blank_field(field) find(field).set('') end end <file_sep>/spec/views/leadspage/edit_leads_page.rb class EditLeadsPageObject < BaseObject def click_on_edit click_on 'Editar' EditLeadsSectionPageObject.new end def change_field(id, value) find(id).set(value) end def click_on_save click_on 'Salvar' end def has_content(message) has_content?(message) end def has_message?(message) has_content?(message) end def click_on_remove click_link I18n.t('.exclude-lead-link') end end <file_sep>/spec/views/leadspage/index_leads_page.rb class IndexLeadsPageObject < BaseObject Capybara.current_driver = :selenium Capybara.app_host = 'https://app-staging.rdstation.com.br' def visit_page visit '/leads' self end def has_lead?(lead) content = find(:xpath, '//*[@id="leads-list"]') has_expected_fields_in_table(content, lead) end private def has_expected_fields_in_table(content, lead) content.has_content?(lead.email) end def click_on_insert_lead click_link I18n.t('.add-link-button') NewLeadsPageObject.new end def click_on_edit(email_lead) click_link(email_lead) EditLeadsSectionPageObject.new end end
74035ceea7c4182af00cb60c1b0e132cda133c5c
[ "Markdown", "Ruby" ]
7
Ruby
FernoSantiago/appResultadosDigitais
0ac93423d55a7beef07e20e4613e8f89fa3091d3
65e43e6d5f3533fa3bcf07f67d12952489c4ec14
refs/heads/master
<file_sep>package zencoder import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net" "net/http" "time" ) const ( DEFAULT_ZENCODER_API_ENDPOINT = "https://app.zencoder.com/api/v2/jobs" DEFAULT_RESPONSE_TYPE = "application/json" ) type Client struct { apiKey string apiEndpoint string responseType string timeout int } type Options struct { ApiKey string ApiEndpoint string ResponseType string Timeout int } type JobSpec struct { Test bool `json:"test,omitempty"` Region string `json:"region,omitempty"` Input string `json:"input,omitempty"` Outputs []*Output `json:"outputs,omitempty"` Notifications []string `json:"notifications,omitempty"` } type Output struct { Public bool `json:"public,omitempty"` Credentials string `json:"credentials,omitempty"` Label string `json:"label,omitempty"` StreamingDeliveryFormat string `json:"streaming_delivery_format,omitempty"` StreamingDeliveryProfile string `json:"streaming_delivery_profile,omitempty"` VideoBitrate int `json:"video_bitrate,omitempty"` Type string `json:"type,omitempty"` Url string `json:"url,omitempty"` Height int `json:"height,omitempty"` BaseUrl string `json:"base_url,omitempty"` FileName string `json:"filename,omitempty"` Streams []*Stream `json:"streams,omitempty"` Notifications []string `json:"notifications,omitempty"` Headers *Headers `json:"headers,omitempty"` } type Headers struct { GoogleAcl string `json:"x-goog-acl,omitempty"` CacheControl string `json:"Cache-Control,omitempty"` } type Stream struct { Source string `json:"source,omitempty"` Path string `json:"path,omitempty"` } type Notification struct { Outputs []struct { Height int `json:"height,omitempty"` Audio_sample_rate int `json:"audio_sample_rate,omitempty"` Frame_rate float64 `json:"frame_rate,omitempty"` Channels string `json:"channels,omitempty"` Duration_in_ms int `json:"duration_in_ms,omitempty"` Video_bitrate_in_kbps int `json:"video_bitrate_in_kbps,omitempty"` Video_codec string `json:"video_codec,omitempty"` Format string `json:"format,omitempty"` Audio_codec string `json:"audio_codec,omitempty"` Label string `json:"label,omitempty"` File_size_in_bytes int `json:"file_size_in_bytes,omitempty"` Width int `json:"width,omitempty"` Audio_bitrate_in_kbps int `json:"audio_bitrate_in_kbps,omitempty"` Id int `json:"id,omitempty"` Total_bitrate_in_kbps int `json:"total_bitrate_in_kbps,omitempty"` State string `json:"state,omitempty"` Url string `json:"url,omitempty"` Md5_checksum string `json:"md5_checksum,omitempty"` Thumbnails []struct { Label string `json:"label,omitempty"` Images []struct { Url string `json:"url,omitempty"` Format string `json:"format,omitempty"` File_size_bytes int `json:"file_size_bytes,omitempty"` Dimensions string `json:"dimensions,omitempty"` } } } Job struct { Created_at string `json:"created_at,omitempty"` Pass_through string `json:"pass_through,omitempty"` Updated_at string `json:"updated_at,omitempty"` Submitted_at string `json:"submitted_at,omitempty"` Id int `json:"id,omitempty"` State string `json:"state,omitempty"` } Input struct { Height int `json:"height,omitempty"` Audio_sample_rate int `json:"audio_sample_rate,omitempty"` Frame_rate float64 `json:"frame_rate,omitempty"` Channels string `json:"channels,omitempty"` Duration_in_ms int `json:"duration_in_ms,omitempty"` Video_bitrate_in_kbps int `json:"video_bitrate_in_kbps,omitempty"` Video_codec string `json:"video_codec,omitempty"` Format string `json:"format,omitempty"` Audio_codec string `json:"audio_codec,omitempty"` File_size_in_bytes int `json:"file_size_in_bytes,omitempty"` Width int `json:"width,omitempty"` Audio_bitrate_in_kbps int `json:"audio_bitrate_in_kbps,omitempty"` Id int `json:"id,omitempty"` State string `json:"state,omitempty"` Total_bitrate_in_kbps int `json:"total_bitrate_in_kbps,omitempty"` Md5_checksum string `json:"md5_checksum,omitempty"` } } func NewClient(options *Options) (*Client, error) { if options == nil { err := fmt.Errorf("error: cannot init Zencoder client without Options") return nil, err } if len(options.ApiKey) == 0 { err := fmt.Errorf("error: must supply ApiKey option to init") return nil, err } responseType := DEFAULT_RESPONSE_TYPE if len(options.ResponseType) > 0 { if options.ResponseType == "application/xml" { responseType = "application/xml" } else { err := fmt.Errorf("error: unsupported response type. response type may be application/json (default) or application/xml") return nil, err } } timeout := 30 if options.Timeout > 0 { timeout = options.Timeout } apiEndpoint := DEFAULT_ZENCODER_API_ENDPOINT if len(options.ApiEndpoint) > 0 { apiEndpoint = options.ApiEndpoint } return &Client{ apiKey: options.ApiKey, apiEndpoint: apiEndpoint, responseType: responseType, timeout: timeout, }, nil } func (c *Client) Zencode(spec *JobSpec) (map[string]interface{}, error) { jsonRequest, err := json.Marshal(spec) if err != nil { return nil, err } fmt.Printf("jsonRequest: %s", string(jsonRequest)) if req, err := http.NewRequest("POST", c.apiEndpoint, bytes.NewBuffer(jsonRequest)); err != nil { return nil, err } else { req.Header.Add("Content-Type", c.responseType) req.Header.Add("Zencoder-Api-Key", c.apiKey) tr := http.Transport{ Dial: func(network, addr string) (net.Conn, error) { return net.DialTimeout(network, addr, time.Duration(c.timeout)*time.Second) }, } if res, err := tr.RoundTrip(req); err != nil { return nil, err } else { defer res.Body.Close() strResp, _ := ioutil.ReadAll(res.Body) if res.StatusCode >= 400 { return nil, fmt.Errorf("error: %s", string(strResp)) } var response map[string]interface{} json.Unmarshal(strResp, &response) return response, nil } } } <file_sep>package main import ( "encoding/json" "flag" zencoder "github.com/streamrail/zencoder" "log" ) var ( apiKey = flag.String("key", "", "your zencoder api key") input = flag.String("input", "https://s3.amazonaws.com/mybucket/myfolder/default.mp4", "a video you want to zencode") //// encode a simpler video: // outputs = flag.String("outputs", "[{ \"url\": \"s3://mybucket/myfolder/output.mp4\", \"credentials\": \"s3_production\" }]", "outputs for the zencoded video") outputs = flag.String("outputs", "[{\"streaming_delivery_format\": \"dash\",\"video_bitrate\": 700,\"type\": \"segmented\",\"url\": \"s3://mybucket/myfolder/dash_test.mpd\", \"credentials\": \"s3_production\" }]", "outputs for the zencoded video") ) func main() { flag.Parse() if *apiKey == "" { log.Fatalf("Required flag: -key") } if *input == "" { log.Fatalf("Required flag: -input") } if *outputs == "" { log.Fatalf("Required flag: -outputs") } var o []map[string]interface{} err := json.Unmarshal([]byte(*outputs), &o) if err != nil { log.Fatal(err.Error()) } if client, err := zencoder.NewClient(&zencoder.Options{ ApiKey: *apiKey, }); err != nil { log.Fatal(err.Error()) } else { if res, err := client.Zencode(*input, o); err != nil { log.Fatal(err.Error()) } else { str, _ := json.Marshal(res) log.Printf("response: %s", str) } } } <file_sep># Zencoder Zencoder client for Go ## usage - import the package with an alias for easy usage ```go import ( zencoder "github.com/streamrail/zencoder" ) ``` - init zencoder.Client with a zencoder.Options pointer reference. default options: ```go type Options struct { ApiKey string // mandatory ApiEndpoint string // https://app.zencoder.com/api/v2/jobs ResponseType string // application/json Timeout int // 30 seconds } ``` - for example, if you have a string flag called apiKey with your Zencoder key: ```go if client, err := zencoder.NewClient(&zencoder.Options{ ApiKey: *apiKey, }); err != nil { log.Fatal(err.Error()) } ``` - client.Zencode function returns a JSON object (map[string]interface{}): ```go if res, err := client.Zencode(*input, o); err != nil { log.Fatal(err.Error()) } else { str, _ := json.Marshal(res) log.Printf("response: %s", str) } ``` ## examples check out example/example.go. - example: zencode a video into [MPEG-DASH](https://app.zencoder.com/docs/guides/encoding-settings/dash) and saving the result on an S3 Bucket (read [this](https://app.zencoder.com/docs/guides/getting-started/working-with-s3) to understand how to setup Zencoder with your S3 credentials). this would be a POST to the Zencoder API with a JSON that looks like this: ```json { "input": "http://s3.amazonaws.com/zencodertesting/test.mov", "outputs": [ { "streaming_delivery_format": "dash", "video_bitrate": 700, "type": "segmented", "url": "s3://mybucket/dash-examples/sbr/rendition.mpd" } ] } ``` ```go package main import ( "encoding/json" "flag" zencoder "github.com/streamrail/zencoder" "log" ) var ( apiKey = flag.String("key", "", "your zencoder api key") input = flag.String("input", "http://s3.amazonaws.com/zencodertesting/test.mov", "a video you want to zencode") outputs = flag.String("outputs", "[{\"streaming_delivery_format\": \"dash\",\"video_bitrate\": 700,\"type\": \"segmented\",\"url\": \"s3://mybucket/dash-examples/sbr/rendition.mpd\"}]", "outputs for the zencoded video") ) func main() { flag.Parse() if *apiKey == "" { log.Fatalf("Required flag: -key") } if *input == "" { log.Fatalf("Required flag: -input") } if *outputs == "" { log.Fatalf("Required flag: -outputs") } var o []map[string]interface{} err := json.Unmarshal([]byte(*outputs), &o) if err != nil { log.Fatal(err.Error()) } if client, err := zencoder.NewClient(&zencoder.Options{ ApiKey: *apiKey, }); err != nil { log.Fatal(err.Error()) } else { if res, err := client.Zencode(*input, o); err != nil { log.Fatal(err.Error()) } else { str, _ := json.Marshal(res) log.Printf("response: %s", str) } } } ``` ## google app engine google app engine does not support using the net/http package directly. the [zencoder-gae](http://github.com/streamrail/zencoder-gae) package uses appengine/urlfetch instead ## license MIT (see LICENSE file)
5f38ddb307597569c65c70bb467d8cc2933050da
[ "Markdown", "Go" ]
3
Go
streamrail/zencoder
7c5f37e799431826b3e3758ac166673f1401aeca
e42ec54536f34b6edd56e5526dee5c3894b8c3c4
refs/heads/master
<repo_name>RashikaKarki/MIT_GSL<file_sep>/contact.php <?php if (isset($_POST['name'])){ $name = $_POST['name']; $email=$_POST['email']; $phone=$_POST['phone'] ?? ""; $message = $_POST['message']; $con = mysqli_connect("localhost","root","","contact"); if (mysqli_connect_errno()){ $info = "Error connecting database."; } else { $sql = "INSERT INTO contact (name,email,phone,message) VALUES ('$name','$email','$phone','$message')"; $info = "Submitted successfully."; mysqli_query($con, $sql); mysqli_close($con); } } else { $info = ""; } ?> <HTML> <head> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/> <!--Import materialize.css--> <link rel="stylesheet" href="css/materialize.css"> <link rel="stylesheet" href="first.cpp"> <title>CONTACT PAGE</title> <meta charset="utf-8"> </head> <body> <!--navigational Bar--> <nav> <div class="nav-wrapper teal lighten-1"> <a href="#!" class="brand-logo">NepVenture.</a> <a href="#" data-activates="mobile-demo" class="button-collapse"><i class="material-icons">menu</i></a> <ul class="right hide-on-med-and-down"> <li><a href="HOME.html">Home</a> <li><a href="#">About</a></li> <li><a href="#">Contact us</a></li> </ul> <ul class="side-nav" id="mobile-demo"> <li><a href="HOME.html">Home</a> <li><a href="#">About</a></li> <li><a href="#">Contact us</a></li> </ul> </div> </nav> <!-- Section: Contact --> <section id="contact" class="section section-contact scrollspy"> <div class="container"> <div class="row"> <div class="col s12 m6"> <div class="card-panel teal lighten-3 white-text center"> <i class="material-icons medium">email</i> <h5>Contact Us For Any Inquiry </h5> <p></p> </div> <ul class="collection with-header"> <li class="collection-header"> <h4>Location</h4> </li> <li class="collection-item">NepVenture.</li> <li class="collection-item">Kathmandu,Nepal</li> <li class="collection-item"><EMAIL></li> </ul> </div> <div class="col s12 m6"> <div class="card-panel grey lighten-3"> <h5>Please fill out this form</h5> <form class='form-horizontal' method="post" style="margin-top:20px;"> <?php if (strlen($info) > 0){ ?> <div class="alert alert-info"><?php echo $info;?></div> <?php } ?> <div class="form-group"> <label class='control-label col-md-2'>Name</label> <div class='col-md-10'> <input type='text' name="name" class='form-control'> </div> </div> <div class="form-group"> <label class='control-label col-md-2'>Email</label> <div class='col-md-10'> <input type='text' name="email" class='form-control'> </div> </div> <div class="form-group"> <label class='control-label col-md-2'>Phone Number</label> <div class='col-md-10'> <input type='text' name="phone" class='form-control'> </div> </div> <div class="form-group"> <label class='control-label col-md-2'>Message</label> <div class='col-md-10'> <input type='text' name="message" class='form-control'> </div> </div> <button class="btn btn-primary btn-lg" style="float:right;">Submit</button> </form> </div> </div> </div> </div> </section> <!-- Footer --> <footer class="section teal lighten-1 white-text center"> <p class="flow-text">NepVenture. &copy; 2018</p> </footer> <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <!--JavaScript at end of body for optimized loading--> <script type="text/javascript" src="js/materialize.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script> <script> $(document).ready(function(){ // Init Sidenav $('.button-collapse').sideNav(); }); </script> </body> </HTML><file_sep>/whole.php <html> <head> <title>Paging Using PHP</title> </head> <body> <?php $rec_limit = 10; $con = mysqli_connect("localhost","root","","hotels"); if(! $conn ) { die('Could not connect: ' . mysql_error()); } mysql_select_db('test_db'); /* Get total number of records */ $sql = "SELECT * FROM hotels"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } $row = mysql_fetch_array($retval, MYSQL_NUM ); $rec_count = $row[0]; if( isset($_GET{'page'} ) ) { $page = $_GET{'page'} + 1; $offset = $rec_limit * $page ; }else { $page = 0; $offset = 0; } $left_rec = $rec_count - ($page * $rec_limit); "FROM employee ". "LIMIT $offset, $rec_limit"; $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {?> <div class="col s12 m12"> <div class="card-panel"> <H1><?php echo $row['Name']; ?></H1><br> <img src="hotel<?php echo $count ?>.jpg " class="responsive-img"><br> <p><?php echo $row['Info']?><br></p> <?php echo $row['Address']; ?><br><?php echo $row['Phone_no']; ?> </div> </div> <?php if( $page > 0 ) { $last = $page - 2; echo "<a href = \"$_PHP_SELF?page = $last\">Last 10 Records</a> |"; echo "<a href = \"$_PHP_SELF?page = $page\">Next 10 Records</a>"; }else if( $page == 0 ) { echo "<a href = \"$_PHP_SELF?page = $page\">Next 10 Records</a>"; }else if( $left_rec < $rec_limit ) { $last = $page - 2; echo "<a href = \"$_PHP_SELF?page = $last\">Last 10 Records</a>"; } mysql_close($conn); ?> </body> </html><file_sep>/README.md # MIT_GSL Prototype for MIT Global StartupLab 2018 <file_sep>/insert.php <?php if (isset($_POST['Name'])){ $name = $_POST['Name']; $Email=$_POST['Email'] ?? ""; $Info=$_POST['Info'] ?? ""; $TotalRooms = $_POST['Total_no_rooms'] ?? ""; $phoneNumber = $_POST['Phone_no'] ?? ""; $address = $_POST['Address'] ?? ""; $Cost = $_POST['Cost'] ?? ""; $con = mysqli_connect("localhost","root","","hotels"); if (mysqli_connect_errno()){ $info = "Error connecting database."; } else { $sql = "INSERT INTO hotels (Name,Email,Info,Total_no_rooms,Phone_no,Address,Cost) VALUES ('$name','$Email','$Info','$TotalRooms','$phoneNumber','$address','$Cost')"; $info = "Inserted successfully."; mysqli_query($con, $sql); mysqli_close($con); } } else { $info = ""; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Insert</title> <link rel="stylesheet" href="css/bootstrap.css"> </head> <body> <div class="container"> <form class='form-horizontal' method="post" style="margin-top:20px;"> <?php if (strlen($info) > 0){ ?> <div class="alert alert-info"><?php echo $info;?></div> <?php } ?> <div class="form-group"> <label class='control-label col-md-2'>Hotel Name</label> <div class='col-md-10'> <input type='text' name="Name" class='form-control'> </div> </div> <div class="form-group"> <label class='control-label col-md-2'>Address</label> <div class='col-md-10'> <input type='text' name="Address" class='form-control'> </div> </div> <div class="form-group"> <label class='control-label col-md-2'>Phone Number</label> <div class='col-md-10'> <input type='text' name="Phone_no" class='form-control'> </div> </div> <div class="form-group"> <label class='control-label col-md-2'>No of rooms</label> <div class='col-md-10'> <input type='number' name="Total_no_rooms" class='form-control'> </div> </div> <div class="form-group"> <label class='control-label col-md-2'>Email</label> <div class='col-md-10'> <input type='text' name="Email" class='form-control'> </div> </div> <div class="form-group"> <label class='control-label col-md-2'>Cost</label> <div class='col-md-10'> <input type='number' name="Cost" class='form-control'> </div> </div> <div class="form-group"> <label class='control-label col-md-2'>Information</label> <div class='col-md-10'> <input type='text' name="Info" class='form-control'> </div> </div> <button class="btn btn-primary btn-lg" style="float:right;">Insert</button> </form> </div> </body> </html><file_sep>/hotel_read.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Insert</title> <link rel="stylesheet" href="css/bootstrap.css"> <!--Import materialize.css--> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/> <link type="text/css" rel="stylesheet" href="first.css" media="screen,projection"/> </head> <body> <div class="topnav" id="myTopnav"> <a href="#!" class="active">NepVenture</a> <div style="float:right;" id="rightDiv"> <a href="HOME.html">Home</a> <a href="contact.php">Contact</a> <a href="#about">About</a> <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">&#9776;</a> </div> </div> <div class="container"> <div class="row"> <?php $con = mysqli_connect("localhost","root","","hotels"); if (mysqli_connect_errno()){ $info = "Error connecting database."; } else { $sql = "SELECT * FROM hotels LIMIT 10"; } $result = mysqli_query($con,$sql); $count=0; $page=0; while($row = mysqli_fetch_array($result)){ $count=$count+1; ?> <div class="col s12 m12"> <div class="card-panel" id="news"> <p class="flow-text"><?php echo $row['Name']; ?></p><br> <img src="hotel<?php echo $count ?>.jpg " class="responsive-img"><br> <p class="flow-text"><?php echo $row['Info']?><br></p> <?php echo $row['Address']; ?><br><?php echo $row['Phone_no']; ?> </div> </div> <?php } ?> </div> </div> <ul class="pagination"> <li class="disabled"><a href=""><i class="material-icons">chevron_left</i></a></li> <li class="active"><a href="#">1</a></li> <li class="waves-effect"><a href=""><i class="material-icons">chevron_right</i></a></li> </ul> <script type="text/javascript" src="js/materialize.js"></script> <!--JavaScript at end of body for optimized loading--> <script type="text/javascript" src="js/materialize.min.js"></script> <script> $(document).ready(function(){ // Init Sidenav $('.button-collapse').sideNav(); }); </script> <script> function myFunction() { var x = document.getElementById("myTopnav"); if (x.className === "topnav") { x.className += " responsive"; document.getElementById('rightDiv').style.float='none'; } else { document.getElementById('rightDiv').style.float='right'; x.className = "topnav"; } } </script> <!-- Footer --> <footer class="section teal lighten-1 white-text center"> <p class="flow-text">NepVenture &copy; 2018</p> </footer> </body> </html>
a1ed31b291ac9583c22634503a2df3b7da0263f1
[ "Markdown", "PHP" ]
5
PHP
RashikaKarki/MIT_GSL
1ffac07188cc2e849b463f908262c25a8a1eff9e
ad89c99bb3f2f2ae4d4219b8f76f4e58cbf298d3
refs/heads/main
<file_sep> ##install necessary packages install.packages("tidyverse") install.packages("gt") install.packages("cluster") #load packages library(readxl) library(tidyverse) library(gt) library(cluster) #importing data from Excel ca <- read.csv("C:\\Users\\LENOVO\\Documents\\SmartWatch.csv") #explore data set names(ca) summary(ca) ##Part 1 df <- ca names(df) ##Segmentation step #standardize values dfz <- scale(df) ## Ward Hierarchical Clustering # calculate distance matrix with euclidian distance dis <- dist(dfz, method = "euclidean") #clustering algorithm fit <- hclust(dis, method="ward.D2") # display dendrogram plot(fit) # cut dendrogram into 4 clusters cluster <- cutree(fit, k=4) cluster table(cluster) # draw dendogram with red borders around the 4 clusters rect.hclust(fit, k=4, border="red") #add cluster to original data set df_final <- cbind(df, cluster) names(df_final) View(df_final) ##Part 2 ##Description step #calculate segment size in percentages proportions <- table(df_final$cluster)/length(df_final$cluster) percentages <- proportions*100 percentages #Explore mean values of variables in clusters segments <- df_final %>% group_by(cluster) %>% summarise_at(vars(TimelyInf, TaskMgm, DeviceSt, Wellness, Athlete, Style, AmznP,Female, Degree, Income, Age, cluster), list(M = mean)) segments #Create simple table with Mean values segments %>% gt() %>% tab_header( title = md("Cluster's Mean Values ")) ##Part1 and Part2 Cna run separately to get Dendogram and Mean Value Table <file_sep>--- output: flexdashboard::flex_dashboard: default html_document: default runtime: shiny --- title: "R Package Download Information" output: flexdashboard::flex_dashboard: orientation: rows vertical_layout: scroll source_code: embed runtime: shiny --- ```{r setup, include=FALSE} library(shiny) library(flexdashboard) # Libraries required are being loaded here library(miniCRAN) library(pkgsearch) library(cranlogs) library(packageRank) ``` ### Details & Description of Package ```{r} textInput("package_selected", "Please Enter Package Name", "ggplot2") renderPrint(packageDescription(input$package_selected)) ``` ### Date wise Spiky Graph of Downloads - Please Select Date Range ```{r} textInput("from", "From", "2020-01-01") textInput("to", "To", "2020-12-31") renderPlot(plot(cranDownloads(packages = input$package_selected, from = input$from, to = input$to), r.version = TRUE)) ``` ### Date wise Table of Download Details ```{r} renderPrint(cranDownloads(packages = input$package_selected, from = input$from, to = input$to)) ``` Authors {data-orientation=rows} ===================================== ### Once user enters the name of the package, the dashboard will show its description, and further by mentioning the date range it will show a spiky graph of downloads for a given date range followed by a table with details of downloads. This dashboard is highly beneficial for a data scientist, R package maintainers, and other R users to get information about R package and downloads at one point. It is also helpful to undersatnd the usage freqency and popularity of the package.
366d40802eb62e3b7498193b09436d0579bddeae
[ "R", "RMarkdown" ]
2
R
kaustubh2599/BAProjects
2ffcfc6744237412207bf2ffa7bf7bbba8d0f59a
9870f324fb7d907ec074a378e409ceec754d1e9d
refs/heads/master
<file_sep>/*jslint node : true, nomen: true, plusplus: true, vars: true, eqeq:true*/ "use strict"; var fs = require('fs'), unbundle = require('cert-unbundle'); var encoding = { encoding: 'utf-8' }; module.exports = { parsePathSync: function (pathArray) { var paths = Array.isArray(pathArray) ? pathArray : [pathArray]; return paths.reduce(function (carry, value) { return carry.concat(unbundle(fs.readFileSync(value, encoding))); }, []); }, parsePath: function (pathArray, cb) { var paths = Array.isArray(pathArray) ? pathArray : [pathArray]; var promises = paths.map(function (value) { return new Promise(function (resolve, reject) { fs.readFile(value, encoding, function (err, data) { if (err) { return reject(err); } return resolve(unbundle(data)); }) }); }); var all = Promise.all(promises); if (cb) { return all.then(function (res) { return cb(null, [].concat.apply([], res)); }).catch(function (err) { return cb(err); }); } return all; } }; <file_sep># ca-splitter Split CA chain to array of CA ### Installation ```javascript npm install ca-splitter --save ``` ### Usage ```javascript var caSplitter = require('ca-splitter'); var caList = caSplitter.parsePathSync([ 'path1/certs_chain.pem', 'path2/certificate.pem' ]); ```
0784abfbaf03264d1b3e99921895a4ab6c5f09b8
[ "JavaScript", "Markdown" ]
2
JavaScript
bimedia-fr/ca-splitter
baae3061aa58dc25d96ac2348c16717e37fd9569
7dc9bf38f167dd930abbafd98a5861e95c446890
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { MenuItem } from 'primeng/api'; @Component({ selector: 'app-menu', templateUrl: './menu.component.html', styleUrls: ['./menu.component.css'] }) export class MenuComponent implements OnInit { items: MenuItem[]; constructor() { } ngOnInit(): void { this.items = [ { label: 'Início', icon: 'pi pi-fw pi-home' }, { label: 'Comercial', icon: 'pi pi-fw pi-chart-bar', items: [ { label: 'Clientes', icon: 'pi pi-fw pi-user' }, { label: 'Contratos', icon: 'pi pi-fw pi-paperclip' }, { label: 'Pedidos de Venda', icon: 'pi pi-fw pi-shopping-cart' }, { label: 'Relatórios', icon: 'pi pi-fw pi-file-pdf', items: [ { label: 'Pedidos por cliente', icon: 'pi pi-fw pi-file-pdf' }, { label: 'Contratos por cliente', icon: 'pi pi-fw pi-file-pdf' } ] }, ] }, { label: 'Recursos Humanos', icon: 'pi pi-fw pi-users', items: [ { label: 'Ficha funcional', icon: 'pi pi-fw pi-user-edit', }, { label: 'Transferências', icon: 'pi pi-fw pi-sort-alt', }, { label: 'Relatórios', icon: 'pi pi-fw pi-file-pdf', items: [ { label: 'Aniversariantes', icon: 'pi pi-fw pi-file-pdf' }, { label: 'Listagem de funcionários', icon: 'pi pi-fw pi-file-pdf' } ] } ] }, { label: 'Financeiro', icon: 'pi pi-fw pi-money-bill', items: [ { label: 'Contas a pagar', icon: 'pi pi-fw pi-window-maximize' }, { label: 'Contas a receber', icon: 'pi pi-fw pi-window-minimize' }, { label: 'Fluxo de Caixa', icon: 'pi pi-fw pi-chart-line' }, { label: 'Relatórios', icon: 'pi pi-fw pi-file-pdf', items: [ { label: 'Contas a pagar', icon: 'pi pi-fw pi-file-pdf' }, { label: 'Contas a receber', icon: 'pi pi-fw pi-file-pdf' } ] } ] }, { separator: true }, { label: 'Sair', icon: 'pi pi-fw pi-power-off' } ]; } }
6902c03087b5084134e2b3950bfda0a766bf5877
[ "TypeScript" ]
1
TypeScript
mhobson/angular-layout-template
669305ac828a8662f459b4e76acdfdf2b8cf9fef
8698bf4738db53a1f7711ce167e3546cbed8da1e
refs/heads/master
<repo_name>rokhos82/mobius-test<file_sep>/modules/mobius.helper/mobius.helper.js (function() { /* mobius.helper - containers general helper services and other items * for mobius projects * */ var module = angular.module("mobius.helper",[]); })(); <file_sep>/LICENSE.md Copyright (C) 2020 <NAME> <file_sep>/modules/mobius.helper/logger.js (function() { ////////////////////////////////////////////////////////////////////////////// // Logging levels: // 1) error // 2) warning // 3) log // 4) info // 5) detail ////////////////////////////////////////////////////////////////////////////// function factoryCtrl() { var services = {}; var settings = {}; /* This function takes a dictionary of logging levels mapped to * one or more CSS classes. These classes are used by the logger * component. */ services.setLevelCSSClasses = function(data) { settings.levelClassMap = data; }; return services; } factoryCtrl.$inject = []; angular.module("mobius.helper").factory("mobius.helper.logger",factoryCtrl); })(); <file_sep>/modules/mobius.helper/unitFactory.js (function() { /* unitFactory * */ function factoryCtrl() { var services = {}; var unitObject = { "name": "", "size": 0, "type": "", "components": [], "effects": { defense: 0, ar: 0 }, "pools": [], "attacks": [], "crits": [1,2,3,4,5], "state": { active: true, flee: false, effects: {}, pools: [], attacks: [], crits: [1,2,3,4,5] } }; var unitObject2 = { "info": { "name": "", "type": "", "size": 0 }, "components": [], "channels": {}, "state": { active: true, flee: false, effects: { defense: 0 }, pools: [], actions: [] } }; var componentObject = { name: "", crit: "" }; var fleetObject = { name: "", units: [] }; var critObject = {}; var unitLog = { uuid: "", actions: [], // Things the unit did effects: [] // Things done to the unit }; // Valid verbs: attack, flee var unitAction = { actor: "", // UUID of the actor target: "", // UUID of the target verb: "", data: {} // specifics vary depending on the verb }; services.newUnit = function() { return _.cloneDeep(unitObject2); }; services.newComponent = function() { return _.cloneDeep(componentObject); }; services.newFleet = function() { return _.cloneDeep(fleetObject); }; services.newCrit = function() { return _.cloneDeep(critObject); }; services.newUnitLog = function() { return _.cloneDeep(unitLog); } services.newUnitAction = function() { return _.cloneDeep(unitAction); } return services; } factoryCtrl.$inject = [] angular.module("mobius.helper").factory("mobius.helper.objectFactory",factoryCtrl); })(); <file_sep>/modules/mobius.helper/udlParser.js (function() { /* udlParser - converts old-school FOTS unit description lines (UDLs) to a more useful format. * */ function factoryCtrl(objectFactory) { var services = {}; function buildAttack(bracket) { var c = objectFactory.newComponent(); c.name = "attack"; c.crit = "battery"; c.type = "beam"; c.attack = {}; c.attack.affinity = {}; c.attack.volley = _.parseInt(bracket.match(/\[(?<volley>\d+)/).groups.volley); c.attack.battery = 1; c.attack.channel = "hitpoints"; if(/target\s+\d+/.test(bracket)) { c.attack.target = _.parseInt(bracket.match(/target\s+(?<tar>\d+)/).groups.tar) * 10; } if(/\s+long/.test(bracket)) { c.attack.long = true; } if(/ammo\s+\d+/.test(bracket)) { c.attack.ammo = _.parseInt(bracket.match(/ammo\s+(?<ammo>\d+)/).groups.ammo); } if(/yield\s+\d+/.test(bracket)) { c.attack.yield = _.parseInt(bracket.match(/yield\s+(?<yield>\d+)/).groups.yield) * 10; } if(/mis..../.test(bracket)) { c.type = "torp"; c.attack.battery = c.attack.volley; c.attack.volley = _.parseInt(bracket.match(/mis..(?<packet>.)./).groups.packet,16); } if(/multi\s+\d+/.test(bracket)) { var packet = _.parseInt(bracket.match(/multi\s+(?<packet>\d+)/).groups.packet); c.attack.battery = c.attack.volley / packet; c.attack.volley = packet; } if(/vibro/.test(bracket)) { c.attack.vibro = true; } if(/meson/.test(bracket)) { c.attack.meson = true; } if(/low/.test(bracket)) { c.attack.low = true; } if(/heat/.test(bracket)) { c.attack.heat = true; } if(/crack/.test(bracket)) { c.attack.crack = true; } if(/global/.test(bracket)) { c.attack.global = true; } if(/offline/.test(bracket)) {} if(/pen/.test(bracket)) { c.attack.penetrate = true; } // Check if the bracket has a hull search // hull A B // A := center point of search // B := steps away from center point that will match if(/hull\s+\d+\s+\d+/.test(bracket)) {} // Check for anti-fighter only targeting if(/af/.test(bracket)) {} // Check for artillery tag // These units can fire from the back (reserve) of the group if(/artillery/.test(bracket)) {} // Check if the weapon is a shield cracker if(/crack/.test(bracket)) {} // Check if the bracket is in a datalink if(/dl\s*\w*\s*/.test(bracket)) {} // Check if the bracket is a field effect if(/field/.test(bracket)) { c.attack.field = true; } // Check if the bracket is flak if(/flak/.test(bracket)) {} // Check if the bracket has a rate of fire // rof A B // A := Reload Delay // B := First Shot Delay // For example, rof 2 0 fires every other round and starts round 1 // To continue, rof 2 1 fires every other round and starts round 2 if(/rof\s*\d*\s*\d*/.test(bracket)) { // How to mondel this? } // Check if the brack has a scan // scan A B // A := targeting value (center point) // B := scope of search (deviation from center point) if(/scan\s+\d+\s+\d+/.test(bracket)) { var scan = bracket.match(/scan\s*(?<center>\d*)\s*(?<scope>\d*/).groups; c.attack.affinity.center = _.parseInt(scan.center); c.attack.affinity.scope = _.parseInt(scan.scope); } return c; } services.parseFots = function(udl) { // Split the UDL by the 'commas' var rawParts = _.split(udl,","); var data = {}; data.errors = []; if(rawParts.length != 13) { data.errors.push(`Incorrect UDL. Part count is ${rawParts.length}; should be 13: ${udl}`); } else { var parts = { name: _.trim(rawParts[0],'"'), beam: _.parseInt(rawParts[1]), shields: _.parseInt(rawParts[3]), hull: _.parseInt(rawParts[7]), tags: rawParts[12] }; var channels = ["hull","shield","crew","boarding","power","realspace","superluminal"]; var groups = { hitpoints: ["hull","shield"] }; // Get the parts of the tags string that are bracketed var brackets = parts.tags.match(/\[.*?\]/g); // Get everything after the last bracket var nonBracket = _.trim(parts.tags.slice(parts.tags.lastIndexOf("]")+1)); // Extract information from the non-bracketed tags if(/^\s*DEFENSE\s+(-?\d+)\s*/.test(nonBracket)) { parts.defense = _.parseInt(nonBracket.match(/^\s*DEFENSE\s+(?<def>-?\d+)\s*/).groups.def); } if(/^\s*TARGET\s+(-?\d+)\s*/.test(nonBracket)) { parts.target = _.parseInt(nonBracket.match(/^\s*TARGET\s+(?<tar>-?\d+)\s*/).groups.tar); } if(/^\s*AR\s+(\d+)\s*/.test(nonBracket)) { parts.ar = _.parseInt(nonBracket.match(/^\s*AR\s+(?<ar>\d+)\s*/).groups.ar); } if(/^\s*SR\s+(\d+)\s*/.test(nonBracket)) { parts.sr = _.parseInt(nonBracket.match(/^\s*SR\s+(?<sr>\d+)\s*/).groups.sr); } if(/^\s*RESIST\s+(\d+)\s*/.test(nonBracket)) { parts.resist = _.parseInt(nonBracket.match(/^\s*RESIST\s+(?<resist>\d+)\s*/).groups.resist); } if(/^\s*FLICKER\s+(\d+)\s*/.test(nonBracket)) { parts.flicker = _.parseInt(nonBracket.match(/^\s*FLICKER\s+(?<flicker>\d+)\s*/).groups.flicker); } if(/^\s*DELAY\s+(\d+)/.test(nonBracket)) {} if(/^\s*DAMAGE\s+(\d+)/.test(nonBracket)) {} if(/^\s*BREAK\s+(\d+)/.test(nonBracket)) {} if(/^\s*RESERVE\s+(\d+)/.test(nonBracket)) {} if(/^\s*PD\s+(\d+)/.test(nonBracket)) {} if(/^\s*REGEN\s+(\d+)\s+(\d+)\s+/.test(nonBracket)) {} if(/^\s*DL\s+(\w+)\s+/.test(nonBracket)) {} if(/^\s*HULL\s+(\d+)\s+(\d+)\s+/.test(nonBracket)) {} // Check if the unit has a TIME tag // TIME A // A := Unit flees after A rounds if(/^\s*TIME\s+\d+/.test(nonBracket)) {} // Check if the unit has a DELAY tag // DELAY A // A := Unit enters combat after A rounds if(/^\s*DELAY\s+\d+/.test(nonBracket)) {} // Check if the unit has a personal break off tag // DAMAGE A // A := Amount of hitpoints left // A=100 is fight until shields are depleted // A=50 is fight until half of hull is depleted // A=150 is fight until half of shields are depleted // Check if the unit has a fleet break off tag // BREAK A // A := the morale of the unit // A=100 means fight to the last man // A=50 means fight till half the total hull of the fleet is gone // Fill out a unit object var u = objectFactory.newUnit(); u.info.tags = parts.tags; u.info.name = parts.name; u.info.size = parts.hull; u.info.type = "unit"; var hull = objectFactory.newComponent(); hull.name = "hull"; hull.crit = "unitBase"; hull.health = { pool: parts.hull, priority: 1 }; hull.presence = { magnitude: parts.hull, channel: 1 }; hull.effects = {}; if(parts.defense > 0) { hull.effects.defense = parts.defense * 10; } if(parts.ar > 0) { hull.effects.deflect = parts.ar; } hull.channel = "hull"; u.components.push(hull); if(parts.shields >= 0) { var shield = objectFactory.newComponent(); shield.name = "shield", shield.crit = "shield", shield.health = { pool: parts.shields, transfer: true, priority: 2 } shield.channel = "shield"; u.components.push(shield); } _.forEach(brackets,function(bracket) { var c = buildAttack(bracket); // If the component is a battery (multi) then duplicate it if(c.attack.battery == 1) { // Just one battery, input the component u.components.push(c); } else { // Multiple batteries, duplicate the component and add each battery individually var battery = c.attack.battery; for(i = 0;i < battery;i++) { var cc = _.cloneDeep(c); cc.attack.battery = 1; u.components.push(cc); } } }); if(!_.isArray(brackets) && parts.beam != 0) { // Then use the beam rating from the UDL and grab any non-bracketed weapons tags. var beam = objectFactory.newComponent(); beam.name = "beam"; beam.crit = "battery"; beam.attack = {}; beam.attack.volley = parts.beam; beam.attack.target = parts.target; u.components.push(beam); } data.unit = u; } return data; }; return services; } factoryCtrl.$inject = ["mobius.helper.objectFactory"]; angular.module("mobius.helper").factory("mobius.helper.udlParser",factoryCtrl); })(); <file_sep>/modules/mobius.helper/fleetParser.js (function() { /* fleetParser * */ function factoryCtrl(udl,factory) { var services = {}; services.parseFots = function(fleetString) { var data = {}; data.errors = []; var fleet = factory.newFleet(); var lines = _.split(fleetString,"\n"); var firstLine = _.split(lines[0],","); var unitLines = _.drop(lines,1); fleet.name = firstLine[0]; _.forEach(unitLines,function(line) { var d = udl.parseFots(line); if(d.errors.length == 0) { fleet.units.push(d.unit); } else { data.errors.push(d.errors); } }); data.group = fleet; data.errors = _.flatten(data.errors); return data; }; return services; } factoryCtrl.$inject = ["mobius.helper.udlParser","mobius.helper.objectFactory"] angular.module("mobius.helper").factory("mobius.helper.fleetParser",factoryCtrl); })(); <file_sep>/components/resultsTable.js (function (){ // Unit Card function controller() { var $ctrl = this; $ctrl.$onInit = function() { $ctrl.isPre = ($ctrl.pre === "true"); $ctrl.units = _.filter($ctrl.group.units,function(unit) { return unit.state.active; }); } } controller.$inject = []; var component = angular.module("mobius-test").component("resultsTable",{ templateUrl: "./components/resultsTable.html", controller: controller, bindings: { group: "<", pre: "@" } }); })(); <file_sep>/modules/mobius.helper/components/logger/mobiusLogger.js (function (){ /* mobiusLogger - a better loggin UI */ function controller() { var $ctrl = this; } controller.$inject = []; var component = angular.module("mobius-test").component("mobiusLogger",{ templateUrl: "./modules/mobius.helper/components/logger/logger.html", controller: controller, bindings: { entries: "<" } }); })(); <file_sep>/components/results.js (function (){ // Unit Card function controller() { var $ctrl = this; $ctrl.$onInit = function() { $ctrl.blue = $ctrl.state.groups.blue; $ctrl.red = $ctrl.state.groups.red; $ctrl.isPre = ($ctrl.pre === "true"); } } controller.$inject = []; var component = angular.module("mobius-test").component("results",{ templateUrl: "./components/results.html", controller: controller, bindings: { state: "<", pre: "@" } }); })(); <file_sep>/components/unitCard.js (function (){ // Unit Card function controller() { var $ctrl = this; } controller.$inject = []; var component = angular.module("mobius-test").component("unitCard",{ templateUrl: "./components/unitCard.html", controller: controller, bindings: { unit: "<" } }); })();
d1d479b2fd531e30c23c25666d5097e714874ebf
[ "JavaScript", "Markdown" ]
10
JavaScript
rokhos82/mobius-test
4f65e1820fc859edc8a684120900b7a3a73b6ed5
791efd3879b2ff0ee09b1e386da0434496a2d553
refs/heads/master
<file_sep>package br.com.gustavocaloi.viagens.ui.activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import br.com.gustavocaloi.viagens.R; public class ListaPacotesActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lista_pacotes); } }
bf62860f2601fd506c1f6f919376aff7afc10f5d
[ "Java" ]
1
Java
gustavocaloi/viagens-android
6d9d7b5e0372110829820b52df19ec9e04d07372
2903dcc560b94d0f1d9ecff40c28ee59e659bf15
refs/heads/master
<repo_name>thinkful-ei-jaguar/scott-googlebooks<file_sep>/src/App.js import React, { Component } from 'react'; import Header from './components/Header'; import Form from './components/Form'; import BookList from './components/Booklist'; // const books = [ // { // title:"Google", // author:"Joe", // image:"https://i.picsum.photos/id/727/200/300.jpg", // description:"No evil" // }, // { // title:"Yahoo", // author:"Bob", // image:"https://i.picsum.photos/id/237/200/300.jpg", // description:"Evil" // } // ]; class App extends Component { constructor(props) { super(props); this.state = { books: [], searchInput: '', printType: '', bookType: '' }; } setSearchInput = (value) => { this.setState({ searchInput: value }); } setPrintType = (value) => { this.setState({ printType: value }); } setBookType = (value) => { this.setState({ bookType: value }); } search = () => { //through function expression the fat arrow, binds the method with the class const url = `https://www.googleapis.com/books/v1/volumes?q=${this.state.searchInput}&printType=${this.state.printType}&filter=${this.state.bookType}&key=<KEY>`; const options = { method: 'GET', headers: { "Content-Type": "application/json" } }; fetch(url, options) .then(res => { if(!res.ok) { throw new Error('Something went wrong, please try again later.'); } return res; }) .then(res => res.json()) .then(data => { console.log(data) this.setState({ books: data.items, error: null }); }) .catch(err => { this.setState({ error: err.message }); }); } render() { return ( <main className='App'> <Header /> <Form searchInput={this.setSearchInput} search={this.search} bookType={this.setBookType} printType={this.setPrintType} /> <BookList books={this.state.books}/> </main> ); } } export default App;<file_sep>/src/components/Booklist.js import React, {Component} from 'react'; import Book from './Book'; class BookList extends Component { render() { const books = this.props.books.map((book, i) => <Book { ...book } key={i}/>); return ( <div className='bookList'> {books} </div> ); } } export default BookList;<file_sep>/src/components/Book.js import React from 'react'; import './Book.css'; const Book = (props) => { return ( <div className='book__single'> <div className="book__row"> <div className="book__title"> {props.volumeInfo.title} </div> <div className="book__author"> {props.volumeInfo.authors ? props.volumeInfo.authors.join(', ') : 'No authors saved'} </div> <div className="book__image"> <img src={props.volumeInfo.imageLinks.thumbnail} alt='' /> </div> {props.volumeInfo.description && <div className="book__description"> {props.volumeInfo.description} </div>} </div> </div> ); }; export default Book;
02897369b6fe6eeb23bed15aa3d85e31a70b0d6b
[ "JavaScript" ]
3
JavaScript
thinkful-ei-jaguar/scott-googlebooks
2f96038a414423f5aa7b7ef8a8b524f7733324bb
8ff65ec5a73fc0efa491fab27583e78eec70e7f7
refs/heads/master
<repo_name>Navneeths31/Machine-Learning-methods-for-finding-AQI<file_sep>/Project-1.py import numpy as np import pandas as pd df = pd.read_csv("data set\\state_weather_aqi_data_mf2.csv") x1 = df.iloc[:,:12].values z1 = pd.DataFrame(x1) y1 = df.iloc[:,12:13].values z2 = pd.DataFrame(y1) from sklearn.preprocessing import OneHotEncoder ohe = OneHotEncoder() x_new1 = pd.DataFrame(ohe.fit_transform(x1[:,[0]]).toarray()) #state x_new2 = pd.DataFrame(ohe.fit_transform(x1[:,[1]]).toarray()) #city x_new3 = pd.DataFrame(ohe.fit_transform(x1[:,[2]]).toarray()) #station feature_set = pd.concat([x_new1,x_new2,x_new3,pd.DataFrame(x1[:,5:12])],axis=1,sort=False) # importing ml libraries from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR x_train,x_test,y_train,y_test = train_test_split(feature_set,y1,test_size=0.25,random_state=0) #----------------------------------------------- #---- test data prediction --------------------- #----------------------------------------------- # multiple linear regression model mreg = LinearRegression() mreg.fit(x_train,y_train) mlr_y_predict = mreg.predict(x_test) # --------------------------------------------- # polynomial regression model # degree = 2 poly_reg = PolynomialFeatures(degree = 2) preg = LinearRegression() pf = poly_reg.fit_transform(x_train) preg.fit(pf,y_train) pr_y_predict = preg.predict(poly_reg.fit_transform(x_test)) #----------------------------------------------- # decision tree regression model dec_tree = DecisionTreeRegressor(random_state = 0) dec_tree.fit(x_train,y_train) dt_y_predict = dec_tree.predict(x_test) #----------------------------------------------- # random forest regression model # random forest with 500 trees rt_reg = RandomForestRegressor(n_estimators = 500, random_state = 0) rt_reg.fit(x_train,y_train) rt_y_predict = rt_reg.predict(x_test) #----------------------------------------------- # support vector regression model # --- feature scaling the paramenters for better results --- from sklearn.preprocessing import StandardScaler sc_x = StandardScaler() sc_y = StandardScaler() x_train_svr = sc_x.fit_transform(x_train) y_train_svr = sc_y.fit_transform(y_train) svr_reg = SVR() svr_reg.fit(x_train_svr,y_train_svr) svr_y_predict = sc_y.inverse_transform(svr_reg.predict(sc_x.transform(x_test))) #---------------------------------------------- # error estimation methods #---------------------------------------------- from math import sqrt from sklearn import metrics def rmsle(real, predicted): sum=0.0 for x in range(len(predicted)): if predicted[x]<0 or real[x]<0: continue p = np.log(predicted[x]+1) r = np.log(real[x]+1) sum = sum + (p - r)**2 return ((sum/len(predicted))**0.5)[0] #----- multiple linear regresion ------- rmse_mlr = sqrt(metrics.mean_squared_error(y_test, mlr_y_predict)) mae_mlr = metrics.mean_absolute_error(y_test, mlr_y_predict) r2_mlr = metrics.r2_score(y_test,mlr_y_predict) rmsle_mlr = rmsle(y_test,mlr_y_predict) #----- polynomial regression ------------ rmse_pr = sqrt(metrics.mean_squared_error(y_test, pr_y_predict)) mae_pr = metrics.mean_absolute_error(y_test, pr_y_predict) r2_pr = metrics.r2_score(y_test,pr_y_predict) rmsle_pr = rmsle(y_test,pr_y_predict) #----- decision tree regression --------- rmse_dt = sqrt(metrics.mean_squared_error(y_test, dt_y_predict)) mae_dt = metrics.mean_absolute_error(y_test, dt_y_predict) r2_dt = metrics.r2_score(y_test,dt_y_predict) rmsle_dt = rmsle(y_test,dt_y_predict) #----- random forest regression --------- rmse_rt = sqrt(metrics.mean_squared_error(y_test, rt_y_predict)) mae_rt = metrics.mean_absolute_error(y_test, rt_y_predict) r2_rt = metrics.r2_score(y_test,rt_y_predict) rmsle_rt = rmsle(y_test,rt_y_predict) #----- support vextor regression -------- rmse_svr = sqrt(metrics.mean_squared_error(y_test, svr_y_predict)) mae_svr = metrics.mean_absolute_error(y_test, svr_y_predict) r2_svr = metrics.r2_score(y_test,svr_y_predict) rmsle_svr = rmsle(y_test,svr_y_predict) ''' from sklearn.model_selection import cross_val_score from sklearn.preprocessing import StandardScaler sc_x = StandardScaler() fs = sc_x.fit_transform(feature_set) cvs = cross_val_score(mreg,fs,y1,cv=20) print("Accuracy: %0.2f (+/- %0.2f)" % (cvs.mean(), cvs.std() * 2)) ''' #------------------------------------ #---- training data prediction ------ #------------------------------------ # ---- MLR ------ mlr_ytp_rmse = sqrt(metrics.mean_squared_error(y_train, mreg.predict(x_train))) mlr_ytp_mae = metrics.mean_absolute_error(y_train, mreg.predict(x_train)) mlr_ytp_r2 = metrics.r2_score(y_train, mreg.predict(x_train)) m1 = mreg.predict(x_train) mlr_ytp_rmsle = rmsle(y_train, m1) #------ polynomial regression --------- pr_ytp_rmse = sqrt(metrics.mean_squared_error(y_train, preg.predict(poly_reg.fit_transform(x_train)))) pr_ytp_mae = metrics.mean_absolute_error(y_train, preg.predict(poly_reg.fit_transform(x_train))) pr_ytp_r2 = metrics.r2_score(y_train, preg.predict(poly_reg.fit_transform(x_train))) pr_ytp_rmsle = rmsle(y_train, preg.predict(poly_reg.fit_transform(x_train))) #mxp = preg.predict(poly_reg.fit_transform(x_train)) # ----- decision tree reg ------ dt_ytp_rmse = sqrt(metrics.mean_squared_error(y_train, dec_tree.predict(x_train))) dt_ytp_mae = metrics.mean_absolute_error(y_train, dec_tree.predict(x_train)) dt_ytp_r2 = metrics.r2_score(y_train, dec_tree.predict(x_train)) dt_ytp_rmsle = rmsle(y_train, dec_tree.predict(x_train)) # ----- random forest reg ----- rf_ytp_rmse = sqrt(metrics.mean_squared_error(y_train, rt_reg.predict(x_train))) rf_ytp_mae = metrics.mean_absolute_error(y_train, rt_reg.predict(x_train)) rf_ytp_r2 = metrics.r2_score(y_train, rt_reg.predict(x_train)) rf_ytp_rmsle = rmsle(y_train, rt_reg.predict(x_train)) # ----- svr ----- svr_ytp_rmse = sqrt(metrics.mean_squared_error(y_train,sc_y.inverse_transform(svr_reg.predict(sc_x.transform(x_train))))) svr_ytp_mae = metrics.mean_absolute_error(y_train,sc_y.inverse_transform(svr_reg.predict(sc_x.transform(x_train)))) svr_ytp_r2 = metrics.r2_score(y_train,sc_y.inverse_transform(svr_reg.predict(sc_x.transform(x_train)))) svr_ytp_rmsle = rmsle(y_train,sc_y.inverse_transform(svr_reg.predict(sc_x.transform(x_train)))) # ========================================== # =========== RESULT ======================= # ========================================== print("evaluating on training data:") print("models\tR^2\tRMSE\tMAE\tRMSLE") print("MLR\t{0:.4f}\t{1:.4f}\t{2:.4f}\t{3:.4f}".format(mlr_ytp_r2,mlr_ytp_rmse,mlr_ytp_mae,mlr_ytp_rmsle)) print("PR\t{0:.2f}\t{1:.2f}\t{2:.3f}\t{3:.4f}".format(pr_ytp_r2,pr_ytp_rmse,pr_ytp_mae,pr_ytp_rmsle)) print("DTR\t{0:.4f}\t{1:.4f}\t{2:.4f}\t{3:.4f}".format(dt_ytp_r2,dt_ytp_rmse,dt_ytp_mae,dt_ytp_rmsle)) print("RFR\t{0:.4f}\t{1:.4f}\t{2:.4f}\t{3:.4f}".format(rf_ytp_r2,rf_ytp_rmse,rf_ytp_mae,rf_ytp_rmsle)) print("SVR\t{0:.4f}\t{1:.3f}\t{2:.3f}\t{3:.4f}".format(svr_ytp_r2,svr_ytp_rmse,svr_ytp_mae,svr_ytp_rmsle)) print("evaluating on testing data:") print("models\tR^2\tRMSE\tMAE\tRMSLE") print("MLR\t{0:.4f}\t{1:.4f}\t{2:.4f}\t{3:.4f}".format(r2_mlr,rmse_mlr,mae_mlr,rmsle_mlr)) print("PR\t{0:.2f}\t{1:.2f}\t{2:.3f}\t{3:.4f}".format(r2_pr,rmse_pr,mae_pr,rmsle_pr)) print("DTR\t{0:.4f}\t{1:.4f}\t{2:.4f}\t{3:.4f}".format(r2_dt,rmse_dt,mae_dt,rmsle_dt)) print("RFR\t{0:.4f}\t{1:.4f}\t{2:.4f}\t{3:.4f}".format(r2_rt,rmse_rt,mae_rt,rmsle_rt)) print("SVR\t{0:.4f}\t{1:.4f}\t{2:.4f}\t{3:.4f}".format(r2_svr,rmse_svr,mae_svr,rmsle_svr))<file_sep>/Project-2.py import xml.etree.ElementTree as et import csv tree = et.parse("weather data xml\\data_aqi_cpcb (14).xml") root = tree.getroot() arr = [] pm2_array = [] pm10_array = [] no2_array =[] nh3_array = [] so2_array = [] co_array = [] o3_array = [] aqi_val_array = [] predominant_para_array = [] date_array = [] time_array = [] state_array = [] city_array = [] station_array = [] for country in root.findall("Country"): for state in country.findall("State"): for city in state.findall("City"): for station in city.findall("Station"): state_array.append(state.get('id')) city_array.append(city.get('id')) station_array.append(station.get('id')) dt = station.get("lastupdate") dt = dt.split() date_array.append(dt[0]) time_array.append(dt[1]) pol_arr = ["PM2.5","PM10","NO2","NH3","SO2","CO","OZONE"] aqi_present = "yes" for pindex in station.findall("Pollutant_Index"): #print(pindex.get('Avg')) if(pindex.get('id') == "PM2.5"): pm2_array.append(pindex.get('Avg')) pol_arr.remove('PM2.5') elif(pindex.get('id') == "PM10"): pm10_array.append(pindex.get('Avg')) pol_arr.remove('PM10') elif(pindex.get('id') == 'NO2'): no2_array.append(pindex.get('Avg')) pol_arr.remove("NO2") elif(pindex.get('id') == "NH3"): nh3_array.append(pindex.get('Avg')) pol_arr.remove("NH3") elif(pindex.get('id') == "SO2"): so2_array.append(pindex.get('Avg')) pol_arr.remove("SO2") elif(pindex.get('id') == "CO"): co_array.append(pindex.get('Avg')) pol_arr.remove("CO") elif(pindex.get('id') == "OZONE"): o3_array.append(pindex.get('Avg')) pol_arr.remove("OZONE") if(len(pol_arr)!=0): while(len(pol_arr) != 0): ele = pol_arr.pop(0) if(ele == "PM2.5"): pm2_array.append('NA') elif(ele == "PM10"): pm10_array.append('NA') elif(ele == "NO2"): no2_array.append('NA') elif(ele == "NH3"): nh3_array.append('NA') elif(ele == "SO2"): so2_array.append('NA') elif(ele == "CO"): co_array.append('NA') elif(ele == "OZONE"): o3_array.append('NA') if(station.find('Air_Quality_Index') is not None): aqi_val_array.append(station.find('Air_Quality_Index').get('Value')) predominant_para_array.append(station.find('Air_Quality_Index').get('Predominant_Parameter')) else: aqi_val_array.append('NA') predominant_para_array.append('NA') data_row = [] for a,b,c,d,e,i,j,k,l,m,n,p,q,r in zip(state_array,city_array,station_array,date_array,time_array,pm2_array,pm10_array,no2_array,nh3_array,so2_array,co_array,o3_array,aqi_val_array,predominant_para_array): data_row.append([a,b,c,d,e,i,j,k,l,m,n,p,q,r]) #data_row.insert(0,["state","city","station","date","time","PM2.5","PM10","NO2","NH3","SO2","CO","OZONE","AQI","Predominant_Parameter"]) for i in data_row: print(i) print("********") # with open("state_weather_aqi_data_two.csv",'a',newline='') as file: # writer = csv.writer(file) # writer.writerows(data_row) # print("file written") <file_sep>/README.md # Machine Learning models for AQI values Instances of fatalities along with diseases due to air pollution turn out to be growing every year. WHO’s 2018 report states that around six to seven million people die each and every year as a result of diseases attributable to air contamination. Thus it is extremely important to precisely monitor and anticipate the grades of contaminants in the surrounding air. In this project, we attempt to find the AQI limits by utilizing ML strategies like, Support Vector Regression (SVR), Decision Tree Regression (DTR), Multiple Linear Regression (MLR) and Random Forest Regression (RFR). Then we compare these ML models by judging them based on error metrics such as, Coefficient of Determination (R2), Root Mean Square Error (RMSE), Mean Absolute Error (MAE) and Root Mean Square Logarithmic Error (RMSLE). The preliminary outcomes showed that the performance shown by SVR was bad. MLR and DTR both performed acceptably well. RFR performed the best among every other regression examples.
5cc6544635e604b6ca58e7405944113ab7ab4536
[ "Markdown", "Python" ]
3
Python
Navneeths31/Machine-Learning-methods-for-finding-AQI
e817ad54cbca32ee0d483f56bbf4d8c28f012d09
190a14d9860e6af0a23a2121287b274689895c4e
refs/heads/master
<file_sep>/* * Copyright 2018 SUSE LINUX GmbH, Nuernberg, Germany.. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package cni import ( "io/ioutil" "os" "path" "github.com/golang/glog" "github.com/renstrom/dedent" "github.com/kubic-project/kubic-init/pkg/config" ) const ( // DefaultCNIConfName is the default configuration for CNI DefaultCNIConfName = "default.conflist" // DefaultCNIConflistContents is the default contents in the CNI file DefaultCNIConflistContents = ` { "name": "default", "cniVersion": "0.3.0", "plugins": [ { "type": "portmap", "capabilities": {"portMappings": true} } ] } ` ) // Prepare prepares the CNI deployment func Prepare(cfg *config.KubicInitConfiguration) error { cniConflist := path.Join(config.DefaultCniConfDir, DefaultCNIConfName) if len(cfg.Network.Cni.ConfDir) > 0 { cniConflist = path.Join(cfg.Network.Cni.ConfDir, DefaultCNIConfName) } if _, err := os.Stat(cniConflist); os.IsNotExist(err) { glog.V(1).Infof("[kubic] creating default configuration for CNI in '%s'", cniConflist) contents := []byte(dedent.Dedent(DefaultCNIConflistContents)) if err := ioutil.WriteFile(cniConflist, contents, 0644); err != nil { return err } } else { glog.V(1).Infof("[kubic] default CNI configuration already present at '%s'", cniConflist) } return nil } <file_sep>############################################################# # End To End Tests ############################################################# SEEDER := $(shell cd $(TF_LIBVIRT_FULL_DIR) && terraform output -json seeder 2>/dev/null | python -c 'import sys, json; print json.load(sys.stdin)["value"]' 2>/dev/null || echo "unknown") tf-e2e-tests: $(GO_NOMOD) get -u github.com/onsi/ginkgo/ginkgo cd tests && SEEDER=$(SEEDER) ./run_suites.sh <file_sep>/* * Copyright 2018 SUSE LINUX GmbH, Nuernberg, Germany.. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package config import ( "crypto/x509" "path/filepath" "strings" "github.com/golang/glog" "github.com/pkg/errors" "k8s.io/api/core/v1" "k8s.io/client-go/tools/clientcmd" certutil "k8s.io/client-go/util/cert" "k8s.io/kubernetes/cmd/kubeadm/app/constants" kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants" kubicutil "github.com/kubic-project/kubic-init/pkg/util" ) // GetNodeNameFromKubeletConfig gets the node name from a kubelet config file func GetNodeNameFromKubeletConfig() (string, error) { kubeconfigDir := constants.KubernetesDir // loads the kubelet.conf file fileName := filepath.Join(kubeconfigDir, constants.KubeletKubeConfigFileName) config, err := clientcmd.LoadFromFile(fileName) if err != nil { return "", err } // gets the info about the current user authInfo := config.AuthInfos[config.Contexts[config.CurrentContext].AuthInfo] // gets the X509 certificate with current user credentials var certs []*x509.Certificate if len(authInfo.ClientCertificateData) > 0 { // if the config file uses an embedded x509 certificate (e.g. kubelet.conf created by kubeadm), parse it if certs, err = certutil.ParseCertsPEM(authInfo.ClientCertificateData); err != nil { return "", err } } else if len(authInfo.ClientCertificate) > 0 { // if the config file links an external x509 certificate (e.g. kubelet.conf created by TLS bootstrap), load it if certs, err = certutil.CertsFromFile(authInfo.ClientCertificate); err != nil { return "", err } } else { return "", errors.New("invalid kubelet.conf. X509 certificate expected") } // We are only putting one certificate in the certificate pem file, so it's safe to just pick the first one // TODO: Support multiple certs here in order to be able to rotate certs cert := certs[0] // gets the node name from the certificate common name return strings.TrimPrefix(cert.Subject.CommonName, constants.NodesUserPrefix), nil } // KubeadmLeftovers returns true if some kubeadm configuration files are present func KubeadmLeftovers() bool { manifestsDir := filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.ManifestsSubDirName) mustNotExist := []string{ kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.KubeAPIServer, manifestsDir), kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.KubeControllerManager, manifestsDir), kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.KubeScheduler, manifestsDir), kubeadmconstants.GetStaticPodFilepath(kubeadmconstants.Etcd, manifestsDir), filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.KubeletKubeConfigFileName), filepath.Join(kubeadmconstants.KubernetesDir, kubeadmconstants.KubeletBootstrapKubeConfigFileName), } for _, f := range mustNotExist { if kubicutil.FileExists(f) { return true } } return false } // PrintNodeProperties prints some node properties func PrintNodeProperties(node *v1.Node) { glog.V(1).Infoln("[kubic] node properties:") if len(node.Status.Conditions) > 0 { last := len(node.Status.Conditions) - 1 glog.V(1).Infof("[kubic] - last condition: %s", node.Status.Conditions[last].Type) } glog.V(1).Infof("[kubic] - addresses: %s", node.Status.Addresses) glog.V(1).Infof("[kubic] - kubelet: %s", node.Status.NodeInfo.KubeletVersion) glog.V(1).Infof("[kubic] - OS: %s", node.Status.NodeInfo.OperatingSystem) glog.V(1).Infof("[kubic] - Distribution: %s", node.Status.NodeInfo.OSImage) glog.V(1).Infof("[kubic] - machine ID: %s", node.Status.NodeInfo.MachineID) glog.V(1).Infof("[kubic] - runtime: %s", node.Status.NodeInfo.ContainerRuntimeVersion) glog.V(1).Infof("[kubic] - created at: %s", node.CreationTimestamp) glog.V(1).Infoln("[kubic] - labels:") for k, v := range node.Labels { glog.V(1).Infof("[kubic] - %s = %s", k, v) } } <file_sep>/* * Copyright 2018 SUSE LINUX GmbH, Nuernberg, Germany.. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package cilium const ( // CiliumCniConfigMap the config map for cni config CiliumCniConfigMap = ` kind: ConfigMap apiVersion: v1 metadata: name: cni-config namespace: kube-system labels: tier: node app: cilium data: cni-conf.json: | { "name": "cilium", "type": "cilium-cni" } ` // CiliumEtcdConfigMap the config map for etcd credentials CiliumEtcdConfigMap = ` kind: ConfigMap apiVersion: v1 metadata: name: cilium-config namespace: kube-system labels: tier: node app: cilium data: # This etcd-config contains the etcd endpoints of your cluster. If you use # TLS please make sure you uncomment the ca-file line and add the respective # certificate has a k8s secret, see explanation below in the comment labeled # "ETCD-CERT" etcd-config: |- --- endpoints: - https://{{ .EtcdServer }}:2379 # # In case you want to use TLS in etcd, uncomment the following line # and add the certificate as explained in the comment labeled "ETCD-CERT" ca-file: '/tmp/cilium-etcd/ca.crt' # # In case you want client to server authentication, uncomment the following # lines and add the certificate and key in cilium-etcd-secrets below key-file: '/tmp/cilium-etcd/tls.key' cert-file: '/tmp/cilium-etcd/tls.crt' # If you want to run cilium in debug mode change this value to true debug: "false" disable-ipv4: "false" ` // CiliumDaemonSet cilium deamon set CiliumDaemonSet = ` kind: DaemonSet apiVersion: apps/v1 metadata: name: {{ .DaemonSetName}} namespace: kube-system spec: updateStrategy: type: "RollingUpdate" rollingUpdate: # Specifies the maximum number of Pods that can be unavailable during the update process. # The current default value is 1 or 100% for daemonsets; Adding an explicit value here # to avoid confusion, as the default value is specific to the type (daemonset/deployment). maxUnavailable: "100%" selector: matchLabels: k8s-app: cilium kubernetes.io/cluster-service: "true" template: metadata: labels: k8s-app: cilium kubernetes.io/cluster-service: "true" annotations: # This annotation plus the CriticalAddonsOnly toleration makes # cilium to be a critical pod in the cluster, which ensures cilium # gets priority scheduling. # https://kubernetes.io/docs/tasks/administer-cluster/guaranteed-scheduling-critical-addon-pods/ scheduler.alpha.kubernetes.io/critical-pod: '' scheduler.alpha.kubernetes.io/tolerations: >- [{"key":"dedicated","operator":"Equal","value":"master","effect":"NoSchedule"}] spec: serviceAccountName: {{ .ServiceAccount }} initContainers: - name: install-cni-conf image: {{ .Image }} command: - /bin/sh - "-c" - "cp -f /etc/cilium-cni/cni-conf.json /host/etc/cni/net.d/{{ .ConfName}}" volumeMounts: - name: host-cni-conf mountPath: /host/etc/cni/net.d - name: cilium-cni-config mountPath: /etc/cilium-cni/ - name: install-multus-cni-bin image: {{ .MultusImage }} command: - /bin/sh - "-c" - "cp -f /usr/bin/multus /host/opt/cni/bin/" volumeMounts: - name: host-cni-bin mountPath: /host/opt/cni/bin/ - name: install-cni-bin image: {{ .Image }} command: - /bin/sh - "-c" - "cp -f /usr/lib/cni/* /host/opt/cni/bin/" volumeMounts: - name: host-cni-bin mountPath: /host/opt/cni/bin/ containers: - image: {{ .Image }} imagePullPolicy: IfNotPresent name: cilium-agent command: [ "cilium-agent" ] args: - "--debug=$(CILIUM_DEBUG)" - "--disable-envoy-version-check" - "-t=vxlan" - "--kvstore=etcd" - "--kvstore-opt=etcd.config=/var/lib/etcd-config/etcd.config" - "--disable-ipv4=$(DISABLE_IPV4)" ports: - name: prometheus containerPort: 9090 lifecycle: preStop: exec: command: - "rm -f /host/etc/cni/net.d/10-cilium-cni.conf /host/opt/cni/bin/cilium-cni" env: - name: "K8S_NODE_NAME" valueFrom: fieldRef: fieldPath: spec.nodeName - name: "CILIUM_DEBUG" valueFrom: configMapKeyRef: name: cilium-config key: debug - name: "DISABLE_IPV4" valueFrom: configMapKeyRef: name: cilium-config key: disable-ipv4 livenessProbe: exec: command: - cilium - status # The initial delay for the liveness probe is intentionally large to # avoid an endless kill & restart cycle if in the event that the initial # bootstrapping takes longer than expected. initialDelaySeconds: 120 failureThreshold: 10 periodSeconds: 10 readinessProbe: exec: command: - cilium - status initialDelaySeconds: 5 periodSeconds: 5 volumeMounts: - name: bpf-maps mountPath: /sys/fs/bpf - name: cilium-run mountPath: /var/run/cilium - name: host-cni-bin mountPath: /host/opt/cni/bin/ - name: host-cni-conf mountPath: /host/etc/cni/net.d - name: docker-socket mountPath: /var/run/docker.sock readOnly: true - name: etcd-config-path mountPath: /var/lib/etcd-config readOnly: true - name: cilium-etcd-secret-mount mountPath: /tmp/cilium-etcd - name: cilium-cni-config mountPath: /etc/cilium-cni/ securityContext: capabilities: add: - "NET_ADMIN" privileged: true hostNetwork: true volumes: # To keep state between restarts / upgrades - name: cilium-run hostPath: path: /var/run/cilium # To keep state between restarts / upgrades - name: bpf-maps hostPath: path: /sys/fs/bpf # To read docker events from the node - name: docker-socket hostPath: path: /var/run/docker.sock # To install cilium cni plugin in the host - name: host-cni-bin hostPath: path: {{ .BinDir }} # To install cilium cni configuration in the host - name: host-cni-conf hostPath: path: {{ .ConfDir }} # To read the etcd config stored in config maps - name: etcd-config-path configMap: name: cilium-config items: - key: etcd-config path: etcd.config - name: cilium-etcd-secret-mount secret: secretName: {{.SecretName}} - name: cilium-cni-config configMap: name: cni-config restartPolicy: Always tolerations: - effect: NoSchedule key: node-role.kubernetes.io/master - effect: NoSchedule key: node.cloudprovider.kubernetes.io/uninitialized value: "true" # Mark cilium's pod as critical for rescheduling - key: CriticalAddonsOnly operator: "Exists" - key: node.kubernetes.io/not-ready operator: Exists effect: NoSchedule ` ) <file_sep># Quickstart: - DEPLOY KUBIC-INIT instructions Manually on 2vms : TODO(dmaiocchi/inercia) ### Configuring Kubic before bootstrapping the cluster * [Preparing the bootstrap](config-pre.md) * Deployments: * [Deployment examples](../deployments/README.md) * Using [`cloud-init`](../deployments/cloud-init/README.md). ### Post control-plane configuration The Kubernetes cluster running on Kubic can be configured * [External authentication](https://github.com/kubic-project/dex-operator/blob/master/README.md) * [Adding private Docker registries](https://github.com/kubic-project/registries-operator/blob/master/README.md) ### The configuration file There is an example [kubic-init.yaml](../config/kubic-init.yaml) that has all the possible configurations for kubic. #### Bootstrap The bootstrap section is reserved to the configuration that is needed in actions that take part before initializing kubic. ##### Registries Inside we have the section registries: this section will let you configure mirrors for registries * multiple mirrors can be set * each prefix can have multiple mirrors addresses * each mirror can have certificates configured. This will be used for security to validate the origin of the server. > Certificates: In this configuration you must add the Certificate content, the Fingerprint and the Hash Algorithm that was used. This is useful for air-gapped environments, where it is not possible to access upstream registries and you have configured a local mirror. In this scenario, you have to configure the daemon.json file for the container engine to be able to find the initial images, otherwise Kubic would not start if this was not configured. Example: ```yaml bootstrap: registries: - prefix: https://registry.suse.com mirrors: - url: https://airgapped.suse.com - url: https://airgapped2.suse.com certificate: "-----BEGIN CERTIFICATE----- MIIGJzCCBA+gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBsjELMAkGA1UEBhMCRlIx DzANBgNVBAgMBkFsc2FjZTETMBEGA1UEBwwKU3RyYXNib3VyZzEYMBYGA1UECgwP hnx8SB3sVJZHeer8f/UQQwqbAO+Kdy70NmbSaqaVtp8jOxLiidWkwSyRTsuU6D8i DiH5uEqBXExjrj0FslxcVKdVj5glVcSmkLwZKbEU1OKwleT/iXFhvooWhQ== -----END CERTIFICATE-----" fingerprint: "E8:73:0C:C5:84:B1:EB:17:2D:71:54:4D:89:13:EE:47:36:43:8D:BF:5D:3C:0F:5B:FC:75:7E:72:28:A9:7F:73" hashalgorithm: "SHA256" - prefix: https://registry.io mirrors: - url: https://airgapped.suse.com - url: https://airgapped2.suse.com certificate: "-----BEGIN CERTIFICATE----- MIIGJzCCBA+gAwIBAgIBATANBgkqhkiG9w0BAQUFADCBsjELMAkGA1UEBhMCRlIx DzANBgNVBAgMBkFsc2FjZTETMBEGA1UEBwwKU3RyYXNib3VyZzEYMBYGA1UECgwP hnx8SB3sVJZHeer8f/UQQwqbAO+Kdy70NmbSaqaVtp8jOxLiidWkwSyRTsuU6D8i DiH5uEqBXExjrj0FslxcVKdVj5glVcSmkLwZKbEU1OKwleT/iXFhvooWhQ==< -----END CERTIFICATE-----" fingerprint: "E8:73:0C:C5:84:B1:EB:17:2D:71:54:4D:89:13:EE:47:36:43:8D:BF:5D:3C:0F:5B:FC:75:7E:72:28:A9:7F:73" hashalgorithm: "SHA256" ``` <file_sep>package clusterhealth import ( "fmt" "os" . "github.com/kubic-project/kubic-init/tests/lib" . "github.com/onsi/ginkgo" ) var host string // use init function for reading IPs of cluster func init() { host = os.Getenv("SEEDER") if host == "" { panic("SEEDER IP not set") } } var _ = Describe("Check Master health", func() { It("kubic-init systemd service is up and running", func() { cmd := "systemctl is-active --quiet kubic-init.service" output, err := RunCmd(host, cmd) if err != nil { fmt.Printf("[ERROR]: kubic-init.service failed") panic(err) } fmt.Println(string(output)) }) }) <file_sep># End to End tests for Kubic-init This tests are BDD style, using ginkgo Kubernetes framework for doing specific `kubic-init` e2e tests. # Testsuites for kubic-init - cluster-health : this tests will check a `kubic-init` cluster health. # Prerequisites for e2e tests. 0) you need to have deployed kubic-init. `make tf-full-apply` on root of this dir. 1) Run the following script ```bash SEEDER=192.168.122.73 ./run_suites.sh ``` # Envinronment Variables supported Add here only needed variables. Try to autodectect and be minimalist. #### Mandatory `SEEDER`: MANDATORY- This will contain the IP adress of your master #### Optional `SEEDER_SSH_PWD`: OPTIONAL- This is the root password for connecting to your master via ssh, by default this is `linux`. Set this to change. # Architecture and design: A testsuite is a subdirectory of `tests` and exist conceptually like a indipendent microservice. The testsuite share only the `lib` directory which are utilty. The Common library is stored on `lib` directory, You should try to put code there to make clean the specs. This testsuite can be executed indipendently from each framework of deployment. You need only the `kubic-init` source code. You need only to pass the SEEDER as env variable, and you can run the tests to any deployed `kubic-init` cluster outside in the wild. Alls hosts/vms should have sshd enabled on port 22. We use linux as std password but you can change it with the ENV.variable. # Developing New Tests: ## Tests requirements: 0) All tests should be idempotent, meanining you can run them XX times, you will have the same results. 1) All tests can be run in parallel. 2) All tests doesn't require or have dependencies each others. Meaining: we can change order in which tests are executed, results will be the same. There is no hidden dependency between tests. ## Run the tests: ```golang ginkgo -r --randomizeAllSpecs --randomizeSuites --failOnPending --cover --trace --race --progress ``` This will run all sub-suites in random order, random sub-test. ## How to create a new suite: Generally we should avoid to create much subsuites if they are not needed. 0) Create a dir like `your_suite_name` 1) Create a pkg accordingly inside the dir. This pkg should be empty, only containing `pkg services` as example. 2) Use `ginkgo bootstrap` for createing the `testsuite` file 3) Use `ginkgo generate name_test` for generating specs. See upstream doc for further details. <file_sep># Jenkins-CI: # Goals: The goal of this pipelines is to be runned locally, and independently of jenkins-server. # Prerequisites for running a kubic-init pipeline - terraform - terraform-libvirt - libvirt-devel and libvirt daemon up and running. - proper bashrc in jenkins user (see file `bashrc`) - libvirtd.conf well setted ( see conf file.) warning: the file is relaxed on security and is used only as an example. feel free to improve security if you wish - golang installed ( kubic-init req.) - docker up and running (kubic-init req.) - java ( this is needed for the jenkins worker) - jenkins user with home dir ( this user should belong to kvm and docker groups, and access all things needed) # How to create a jenkins-worker quick tutorial. 0) Download the swarm plugin on the server you want to create as Jenkins worker. https://wiki.jenkins.io/display/JENKINS/Swarm+Plugin ```bash wget https://repo.jenkins-ci.org/releases/org/jenkins-ci/plugins/swarm-client/3.9/swarm-client-3.9.jar ``` 0.B) Make sure you have the jenkins user with the right credentials etc. (look at upstream doc) 1) Run the swarm plugin on the server you want to make ci-server with ( adapt this command with your PWD and user, and all the vars) ```bash /usr/bin/java -jar /usr/bin/swarm-client-3.9.jar -master https://ci.suse.de/ -disableSslVerification -disableClientsUniqueId -name kubic-ci -description "CI runner used by the kubic" -username containers -password <PASSWORD> -labels kubic-init -executors 3 -mode exclusive -fsroot /home/jenkins/build -deleteExistingClients ``` This will connect the Jenkins worker to the master server. 2) You can also create a systemd service. ( in case you reboot the worker is usefull) ```bash [Unit] Description=swarmplugin After=network.target [Service] User=jenkins EnvironmentFile=/etc/sysconfig/swarmplugin ExecStart=/usr/bin/java -Djava.util.logging.config.file=/usr/share/java/logging-swarm-client.properties -jar /usr/share/java/swarm-client-jar-with-dependencies.jar -master https://ci.suse.de/ -username BAUBAU -password <PASSWORD> -labels BAULABEL -executors 4 -disableSslVerification -name kubic-init -fsroot/home/jenkins/jenkins-build/ Restart=always [Install] WantedBy=multi-user.target ``` <file_sep>IMAGE_BASENAME = kubic-init IMAGE_NAME = kubic-project/$(IMAGE_BASENAME) IMAGE_TAR_GZ = $(IMAGE_BASENAME)-latest.tar.gz IMAGE_DEPS = $(KUBIC_INIT_EXE) Dockerfile # These will be provided to the target KUBIC_INIT_VERSION := 1.0.0 KUBIC_INIT_BUILD := `git rev-parse HEAD 2>/dev/null` KUBIC_INIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD 2> /dev/null || echo 'unknown') KUBIC_INIT_BUILD_DATE := $(shell date +%Y%m%d-%H:%M:%S) # extra args to add to the `kubic-init bootstrap` command KUBIC_INIT_EXTRA_ARGS = MANIFEST_LOCAL = deployments/kubelet/kubic-init-manifest.yaml MANIFEST_REM = deployments/kubic-init-manifest.yaml MANIFEST_DIR = /etc/kubernetes/manifests KUBE_DROPIN_SRC = init/kubelet.drop-in.conf KUBE_DROPIN_DST = /etc/systemd/system/kubelet.service.d/kubelet.drop-in.conf # sudo command (and version passing env vars) SUDO = sudo SUDO_E = $(SUDO) -E # the kubeconfig program generated by kubeadm/kube-init KUBECONFIG = /etc/kubernetes/admin.conf # the initial kubelet config SYS_KUBELET_CONFIG := /etc/kubernetes/kubelet-config.yaml LOCAL_KUBELET_CONFIG := init/kubelet-config.yaml KUBELET_CONFIG := $(shell [ -f $(SYS_KUBELET_CONFIG) ] && echo $(SYS_KUBELET_CONFIG) || echo $(LOCAL_KUBELET_CONFIG) ) # increase to 8 for detailed kubeadm logs... # Example: make local-run VERBOSE_LEVEL=8 VERBOSE_LEVEL = 3 # volumes to mount when running locally CONTAINER_VOLUMES = \ -v /etc/kubernetes:/etc/kubernetes \ -v /etc/hosts:/etc/hosts:ro \ -v /usr/bin/kubelet:/usr/bin/kubelet:ro \ -v /var/lib/kubelet:/var/lib/kubelet \ -v /etc/cni/net.d:/etc/cni/net.d \ -v /var/lib/dockershim:/var/lib/dockershim \ -v /var/lib/etcd:/var/lib/etcd \ -v /sys/fs/cgroup:/sys/fs/cgroup \ -v /var/run:/var/run ############################################################# # Some simple run targets # (for testing things locally) ############################################################# # we must "patch" the local kubelet by adding a drop-in unit # otherwise, the kubelet will be run with the wrong arguments /var/lib/kubelet/config.yaml: $(KUBELET_CONFIG) $(SUDO) cp -f $(KUBELET_CONFIG) /var/lib/kubelet/config.yaml $(KUBE_DROPIN_DST): $(KUBE_DROPIN_SRC) /var/lib/kubelet/config.yaml @echo ">>> Adding drop-in unit for the local kubelet" $(SUDO) mkdir -p `dirname $(KUBE_DROPIN_DST)` $(SUDO) cp -f $(KUBE_DROPIN_SRC) $(KUBE_DROPIN_DST) $(SUDO) systemctl daemon-reload kubeadm-reset: local-reset local-reset: $(KUBIC_INIT_EXE) @echo ">>> Resetting everything..." $(SUDO_E) $(KUBIC_INIT_EXE) reset \ -v $(VERBOSE_LEVEL) \ $(KUBIC_INIT_EXTRA_ARGS) # Usage: # - create a local seeder: # $ make local-run # - create a local seeder with a specific token: # $ env TOKEN=XXXX make local-run # - join an existing seeder: # $ env SEEDER=1.2.3.4 TOKEN=XXXX make local-run # - run a custom kubeadm, use docker, our own configuration and a higher debug level: # $ make local-run \ # KUBIC_INIT_EXTRA_ARGS="--config my-config-file.yaml --var Runtime.Engine=docker --var Paths.Kubeadm=/somewhere/linux/amd64/kubeadm" \ # VERBOSE_LEVEL=8 # # You can customize the args with something like: # make local-run VERBOSE_LEVEL=8 \ # KUBIC_INIT_EXTRA_ARGS="--config my-config-file.yaml --var Runtime.Engine=docker" # local-run: $(KUBIC_INIT_EXE) $(KUBE_DROPIN_DST) @echo ">>> Running $(KUBIC_INIT_EXE) as _root_" $(SUDO_E) $(KUBIC_INIT_EXE) bootstrap \ -v $(VERBOSE_LEVEL) \ --load-assets=false \ $(KUBIC_INIT_EXTRA_ARGS) # Usage: # - create a local seeder: make docker-run # - create a local seeder with a specific token: TOKEN=XXXX make docker-run # - join an existing seeder: env SEEDER=1.2.3.4 TOKEN=XXXX make docker-run docker-run: $(IMAGE_TAR_GZ) $(KUBE_DROPIN_DST) @echo ">>> Running $(IMAGE_NAME):latest in the local Docker" docker run -it --rm \ --privileged=true \ --net=host \ --security-opt seccomp:unconfined \ --cap-add=SYS_ADMIN \ --name=$(IMAGE_BASENAME) \ -e SEEDER \ -e TOKEN \ $(CONTAINER_VOLUMES) \ $(IMAGE_NAME):latest $(KUBIC_INIT_EXTRA_ARGS) docker-reset: kubeadm-reset $(IMAGE_TAR_GZ): $(IMAGE_DEPS) @echo ">>> Creating Docker image..." docker build -t $(IMAGE_NAME):latest . @echo ">>> Creating tar for image..." docker save $(IMAGE_NAME):latest | gzip > $(IMAGE_TAR_GZ) docker-image: $(IMAGE_TAR_GZ) docker-image-clean: rm -f $(IMAGE_TAR_GZ) -docker rmi $(IMAGE_NAME) # TODO: build the image for podman # TODO: implement podman-reset podman-run: podman-image $(KUBE_DROPIN_DST) $(SUDO_E) podman run -it --rm \ --privileged=true \ --net=host \ --security-opt seccomp:unconfined \ --cap-add=SYS_ADMIN \ --name=$(IMAGE_BASENAME) \ -h master \ -e SEEDER \ -e TOKEN \ $(CONTAINER_VOLUMES) \ $(IMAGE_NAME):latest $(KUBIC_INIT_EXTRA_ARGS) kubelet-run: $(IMAGE_TAR_GZ) $(KUBE_DROPIN_DST) @echo ">>> Pushing $(IMAGE_NAME):latest to docker Hub" docker push $(IMAGE_NAME):latest @echo ">>> Copying manifest to $(MANIFEST_DIR) (will require root password)" mkdir -p $(MANIFEST_DIR) $(SUDO) cp -f $(MANIFEST_LOCAL) $(MANIFEST_DIR)/`basename $(MANIFEST_REM)` $(SUDO) systemctl restart kubelet @echo ">>> Manifest copied. Waiting for kubelet to start things..." @while ! docker ps | grep $(IMAGE_BASENAME) | grep -q -v pause ; do echo "Waiting container..." ; sleep 2 ; done @docker logs -f "`docker ps | grep $(IMAGE_BASENAME) | grep -v pause | cut -d' ' -f1`" kubelet-reset: kubeadm-reset @echo ">>> Resetting everything..." @echo ">>> Stopping the kubelet..." @$(SUDO) systemctl stop kubelet @while [ ! -e /var/run/docker.sock ] ; do echo "Waiting for dockers socket..." ; sleep 2 ; done @echo ">>> Restoring a safe kubelet configuration..." $(SUDO) cp -f $(KUBELET_CONFIG) /var/lib/kubelet/config.yaml @-rm -f $(MANIFEST_DIR)/$(MANIFEST_REM) <file_sep>/* * Copyright 2018 SUSE LINUX GmbH, Nuernberg, Germany.. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package kubeadm import ( "encoding/json" "github.com/golang/glog" "k8s.io/kubernetes/cmd/kubeadm/app/cmd" "github.com/kubic-project/kubic-init/pkg/config" ) // NewVersion gets the kubeadm version information func NewVersion(kubicCfg *config.KubicInitConfiguration, args ...string) (cmd.Version, error) { args = append([]string{ "--output=json", }, args...) output, err := kubeadmCmdOut("version", kubicCfg, args...) if err != nil { return cmd.Version{}, err } glog.V(8).Infof("[kubic] `kubeadm` version output: %s", output.String()) v := cmd.Version{} dec := json.NewDecoder(&output) if err := dec.Decode(&v); err != nil { return cmd.Version{}, err } return v, nil } <file_sep>package lib import ( "os" "golang.org/x/crypto/ssh" ) // RunCmd execute command on remote systems func RunCmd(host, command string) ([]byte, error) { client, session, err := connectToHost("root", host) if err != nil { return nil, err } out, err := session.CombinedOutput(command) if err != nil { return out, err } client.Close() return out, nil } // We assume that connection ssh should be running on 22 port. // By default we use linux, via ENV var this can changed. func connectToHost(user, host string) (*ssh.Client, *ssh.Session, error) { var sshPassword string sshPassword = os.Getenv("SEEDER_SSH_PWD") // check if User has set another ssh pwd, default is linux if sshPassword == "" { sshPassword = "<PASSWORD>" } sshConfig := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ssh.Password(sshPassword)}, } sshConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey() client, err := ssh.Dial("tcp", host+":22", sshConfig) if err != nil { return nil, nil, err } session, err := client.NewSession() if err != nil { client.Close() return nil, nil, err } return client, session, nil } <file_sep>#!/usr/bin/env python # generate a kubeadm-compatible token import random import json import os # use the TOKEN variable if preset token = os.environ.get('TOKEN') if token is None: a = "%0x" % random.SystemRandom().getrandbits(13*8) token = a[:6] + "." + a[6:22] print(json.dumps({'token': token}, indent=2)) <file_sep>/* * Copyright 2018 SUSE LINUX GmbH, Nuernberg, Germany.. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package kubeadm import ( "bufio" "bytes" "fmt" "io/ioutil" "os" "os/exec" "strings" "github.com/golang/glog" "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm/validation" "k8s.io/kubernetes/cmd/kubeadm/app/features" kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util" "github.com/kubic-project/kubic-init/pkg/config" ) const kubeadmConfigTemplate = "kubic-kubeadm.*.yaml" type stringConsumer func(msg string) // kubeadm runs a "kubeadm" command func kubeadm(name string, kubicCfg *config.KubicInitConfiguration, stdoutProc stringConsumer, stderrProc stringConsumer, args ...string) error { args = append([]string{name}, args...) kubeadmPath := kubicCfg.Paths.Kubeadm // Now we can run the "kubeadm" command glog.V(1).Infof("[kubic] exec: %s %s", kubeadmPath, strings.Join(args, " ")) cmd := exec.Command(kubeadmPath, args...) stdoutPipe, _ := cmd.StdoutPipe() stderrPipe, _ := cmd.StderrPipe() stdoutScan := bufio.NewScanner(stdoutPipe) stderrScan := bufio.NewScanner(stderrPipe) if err := cmd.Start(); err != nil { return err } go func() { for stdoutScan.Scan() { stdoutProc(stdoutScan.Text()) } }() go func() { for stderrScan.Scan() { stderrProc(stderrScan.Text()) } }() return cmd.Wait() } // toKubeadmConfig is a function that can translate a kubic-init config to // a kubeadm config type toKubeadmConfig func(*config.KubicInitConfiguration, map[string]bool) ([]byte, error) // kubeadmWithConfig runs a "kubeadm" command func kubeadmWithConfig(name string, kubicCfg *config.KubicInitConfiguration, configer toKubeadmConfig, args ...string) error { featureGates, err := features.NewFeatureGate(&features.InitFeatureGates, config.DefaultFeatureGates) kubeadmutil.CheckErr(err) glog.V(3).Infof("[kubic] feature gates: %+v", featureGates) // generate a kubeadm config file // some kubeadm commands do not really need any configuration, so this is optional if configer != nil { configFile, err := ioutil.TempFile(os.TempDir(), kubeadmConfigTemplate) if err != nil { return err } defer os.Remove(configFile.Name()) // get the configuration marshalledBytes, err := configer(kubicCfg, featureGates) if err != nil { return err } if glog.V(3) { glog.Infoln("[kubic] kubeadm configuration produced:") for _, line := range strings.Split(string(marshalledBytes), "\n") { glog.Infof("[kubic] %s", line) } } // ... and write them in a file configFile.Write(marshalledBytes) args = append(args, "--config="+configFile.Name()) } printer := func(m string) { fmt.Println(m) } logger := func(m string) { glog.V(1).Infoln(m) } return kubeadm(name, kubicCfg, logger, printer, args...) } // kubeadmCmdOut runs a "kubeadm" command waiting for the func kubeadmCmdOut(name string, kubicCfg *config.KubicInitConfiguration, args ...string) (bytes.Buffer, error) { output := bytes.Buffer{} bufferer := func(m string) { output.WriteString(m) } if err := kubeadm(name, kubicCfg, bufferer, bufferer, args...); err != nil { return bytes.Buffer{}, err } return output, nil } // getIgnorePreflightArg returns the arg for ignoring pre-flight errors func getIgnorePreflightArg() string { ignorePreflightErrorsSet, err := validation.ValidateIgnorePreflightErrors(config.DefaultIgnoredPreflightErrors) if err != nil { panic(err) } arg := "--ignore-preflight-errors=" + strings.Join(ignorePreflightErrorsSet.List(), ",") return arg } func getVerboseArg() string { return "--v=3" // TODO: make this configurable } <file_sep>/* * Copyright 2018 SUSE LINUX GmbH, Nuernberg, Germany.. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package cilium import ( "crypto/x509" "fmt" "path/filepath" "github.com/golang/glog" apps "k8s.io/api/apps/v1" "k8s.io/api/core/v1" rbac "k8s.io/api/rbac/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kuberuntime "k8s.io/apimachinery/pkg/runtime" clientset "k8s.io/client-go/kubernetes" clientsetscheme "k8s.io/client-go/kubernetes/scheme" certutil "k8s.io/client-go/util/cert" kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util" "k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient" pkiutil "k8s.io/kubernetes/cmd/kubeadm/app/util/pkiutil" "github.com/kubic-project/kubic-init/pkg/cni" "github.com/kubic-project/kubic-init/pkg/config" ) const ( // CiliumClusterRoleName sets the name for the cilium ClusterRole CiliumClusterRoleName = "kubic:cilium" // CiliumClusterRoleNamePSP the PSP cluster role CiliumClusterRoleNamePSP = "kubic:psp:cilium" // CiliumServiceAccountName describes the name of the ServiceAccount for the cilium addon CiliumServiceAccountName = "kubic-cilium" //CiliumCertSecret the secret name to store tls credential CiliumCertSecret = "cilium-secret" ) var ( serviceAccount = v1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{ Name: CiliumServiceAccountName, Namespace: metav1.NamespaceSystem, }, } clusterRole = rbac.ClusterRole{ ObjectMeta: metav1.ObjectMeta{ Name: CiliumClusterRoleName, }, Rules: []rbac.PolicyRule{ { APIGroups: []string{"networking.k8s.io"}, Resources: []string{"networkpolicies"}, Verbs: []string{"get", "list", "watch"}, }, { APIGroups: []string{""}, Resources: []string{"namespaces", "services", "nodes", "endpoints", "componentstatuses"}, Verbs: []string{"get", "list", "watch"}, }, { APIGroups: []string{""}, Resources: []string{"pods", "nodes"}, Verbs: []string{"get", "list", "watch", "update"}, }, { APIGroups: []string{"extensions"}, Resources: []string{"networkpolicies", "thirdpartyresources", "ingresses"}, Verbs: []string{"get", "list", "watch", "create"}, }, { APIGroups: []string{"apiextensions.k8s.io"}, Resources: []string{"customresourcedefinitions"}, Verbs: []string{"create", "get", "list", "watch", "update"}, }, { APIGroups: []string{"cilium.io"}, Resources: []string{"ciliumnetworkpolicies", "ciliumnetworkpolicies/status", "ciliumendpoints", "ciliumendpoints/status"}, Verbs: []string{"*"}, }, }, } clusterRoleBinding = rbac.ClusterRoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: CiliumClusterRoleName, }, RoleRef: rbac.RoleRef{ APIGroup: rbac.GroupName, Kind: "ClusterRole", Name: CiliumClusterRoleName, }, Subjects: []rbac.Subject{ { Kind: rbac.ServiceAccountKind, Name: CiliumServiceAccountName, Namespace: metav1.NamespaceSystem, }, { Kind: "Group", Name: "system:nodes", }, }, } clusterRoleBindingPSP = rbac.ClusterRoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: CiliumClusterRoleNamePSP, }, RoleRef: rbac.RoleRef{ APIGroup: rbac.GroupName, Kind: "ClusterRole", Name: "suse:kubic:psp:privileged", }, Subjects: []rbac.Subject{ { Kind: rbac.ServiceAccountKind, Name: CiliumServiceAccountName, Namespace: metav1.NamespaceSystem, }, }, } ciliumBaseName = "cilium-etcd-client" ciliumCertConfig = certutil.Config{ CommonName: "cilium-etcd-client", Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, } ) func init() { // self-register in the CNI plugins registry cni.Registry.Register("cilium", EnsureCiliumAddon) } // EnsureCiliumAddon creates the cilium addons func EnsureCiliumAddon(cfg *config.KubicInitConfiguration, client clientset.Interface) error { etcdDir := filepath.Join(cfg.Certificates.Directory, "etcd") var ciliumCniConfigMapBytes, ciliumEtcdConfigMapBytes, ciliumDaemonSetBytes []byte caCert, caKey, err := pkiutil.TryLoadCertAndKeyFromDisk(etcdDir, "ca") if err != nil { return fmt.Errorf("etcd generation retrieval failed %v", err) } cert, key, err := pkiutil.NewCertAndKey(caCert, caKey, &ciliumCertConfig) if err != nil { return fmt.Errorf("error when creating etcd client certificate for cilium %v", err) } if err := pkiutil.WriteCertAndKey(etcdDir, ciliumBaseName, cert, key); err != nil { return fmt.Errorf("error when creating cilium etcd certificate: %v", err) } if err := createServiceAccount(client); err != nil { return fmt.Errorf("error when creating cilium service account: %v", err) } etcdServer, err := cfg.GetBindIP() if err != nil { return fmt.Errorf("error when trying to retrieve etcd server IP %v", err) } ciliumCniConfigMapBytes = nil if !cfg.Network.MultipleCni { ciliumCniConfigMapBytes, err = kubeadmutil.ParseTemplate(CiliumCniConfigMap, struct { EtcdServer string }{ etcdServer.String(), }) if err != nil { return fmt.Errorf("error when parsing cilium cni configmap template: %v", err) } } ciliumEtcdConfigMapBytes, err = kubeadmutil.ParseTemplate(CiliumEtcdConfigMap, struct { EtcdServer string }{ etcdServer.String(), }) if err != nil { return fmt.Errorf("error when parsing cilium etcd configmap template: %v", err) } secret := &v1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: CiliumCertSecret, Namespace: metav1.NamespaceSystem, }, Type: v1.SecretTypeTLS, Data: map[string][]byte{ v1.TLSCertKey: certutil.EncodeCertPEM(cert), v1.TLSPrivateKeyKey: certutil.EncodePrivateKeyPEM(key), "ca.crt": certutil.EncodeCertPEM(caCert), }, } if err = apiclient.CreateOrUpdateSecret(client, secret); err != nil { return fmt.Errorf("error when creating cilium secret %v", err) } image := cfg.Network.Cni.Image if len(image) == 0 { image = config.DefaultCiliumImage } glog.V(1).Infof("[kubic] using %s as cni image", image) daemonSetName := "cilium" confName := "10-cilium.conf" if cfg.Network.MultipleCni { daemonSetName = "cilium-with-multus" confName = "10-cilium-multus.conf" } ciliumDaemonSetBytes, err = kubeadmutil.ParseTemplate(CiliumDaemonSet, struct { Image string MultusImage string ConfDir string BinDir string SecretName string ServiceAccount string DaemonSetName string ConfName string }{ image, config.DefaultMultusImage, cfg.Network.Cni.ConfDir, cfg.Network.Cni.BinDir, CiliumCertSecret, CiliumServiceAccountName, daemonSetName, confName, }) if err != nil { return fmt.Errorf("error when parsing cilium daemonset template: %v", err) } if err := createRBACRules(client, cfg.Features.PSP); err != nil { return fmt.Errorf("error when creating flannel RBAC rules: %v", err) } if err := createCiliumAddon(ciliumCniConfigMapBytes, ciliumEtcdConfigMapBytes, ciliumDaemonSetBytes, client); err != nil { return err } glog.V(1).Infof("[kubic] installed cilium CNI driver") return nil } // CreateServiceAccount creates the necessary serviceaccounts that kubeadm uses/might use, if they don't already exist. func createServiceAccount(client clientset.Interface) error { return apiclient.CreateOrUpdateServiceAccount(client, &serviceAccount) } func createCiliumAddon(cniConfigMapBytes, etcdConfigMapBytes, daemonSetbytes []byte, client clientset.Interface) error { if cniConfigMapBytes != nil { ciliumCniConfigMap := &v1.ConfigMap{} if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), cniConfigMapBytes, ciliumCniConfigMap); err != nil { return fmt.Errorf("unable to decode cilium configmap %v", err) } // Create the ConfigMap for cilium or update it in case it already exists if err := apiclient.CreateOrUpdateConfigMap(client, ciliumCniConfigMap); err != nil { return err } } ciliumEtcdConfigMap := &v1.ConfigMap{} if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), etcdConfigMapBytes, ciliumEtcdConfigMap); err != nil { return fmt.Errorf("unable to decode cilium cni configmap %v", err) } // Create the ConfigMap for cilium or update it in case it already exists if err := apiclient.CreateOrUpdateConfigMap(client, ciliumEtcdConfigMap); err != nil { return err } ciliumDaemonSet := &apps.DaemonSet{} if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), daemonSetbytes, ciliumDaemonSet); err != nil { return fmt.Errorf("unable to decode cilium etcd daemonset %v", err) } // Create the DaemonSet for cilium or update it in case it already exists return apiclient.CreateOrUpdateDaemonSet(client, ciliumDaemonSet) } // CreateRBACRules creates the essential RBAC rules for a minimally set-up cluster func createRBACRules(client clientset.Interface, psp bool) error { var err error if err = apiclient.CreateOrUpdateClusterRole(client, &clusterRole); err != nil { return err } if err = apiclient.CreateOrUpdateClusterRoleBinding(client, &clusterRoleBinding); err != nil { return err } if psp { if err = apiclient.CreateOrUpdateClusterRoleBinding(client, &clusterRoleBindingPSP); err != nil { return err } } return nil } <file_sep># Design and architecture * [Bootstrapping](design/design-bootstrap.md) the cluster. * [Updating](design/design-updates.md) the cluster. * [Adding](design/design-node-addition.md) and [removing](design/design-node-removal.md) nodes to/from the cluster. <file_sep>/* * Copyright 2018 SUSE LINUX GmbH, Nuernberg, Germany.. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package cni import ( "fmt" "github.com/golang/glog" clientset "k8s.io/client-go/kubernetes" "github.com/kubic-project/kubic-init/pkg/config" ) // Plugin A CNI plugin is a function that is responsible for setting up everything type Plugin func(*config.KubicInitConfiguration, clientset.Interface) error type registryMap map[string]Plugin // Register registers a plugin with the cni func (registry registryMap) Register(name string, plugin Plugin) { registry[name] = plugin } // Has checks if it has a registry with the given name func (registry registryMap) Has(name string) bool { _, found := registry[name] return found } // Load loads a registry func (registry registryMap) Load(name string, cfg *config.KubicInitConfiguration, client clientset.Interface) error { if cfg.Network.MultipleCni { glog.V(1).Infoln("[kubic] MultipleCni is enabled, registring multus") registry["multus"](cfg, client) } if registry.Has(name) { return registry[name](cfg, client) } return fmt.Errorf("%s cni plugin is not supported", name) } // Registry is the Global Registry var Registry = registryMap{} <file_sep>/* * Copyright 2018 SUSE LINUX GmbH, Nuernberg, Germany.. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package multus import ( "encoding/json" "fmt" "github.com/golang/glog" "k8s.io/api/core/v1" rbac "k8s.io/api/rbac/v1" apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kuberuntime "k8s.io/apimachinery/pkg/runtime" clientset "k8s.io/client-go/kubernetes" clientsetscheme "k8s.io/client-go/kubernetes/scheme" kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util" "k8s.io/kubernetes/cmd/kubeadm/app/util/apiclient" kubicclient "github.com/kubic-project/kubic-init/pkg/client" "github.com/kubic-project/kubic-init/pkg/cni" "github.com/kubic-project/kubic-init/pkg/cni/cilium" "github.com/kubic-project/kubic-init/pkg/cni/flannel" "github.com/kubic-project/kubic-init/pkg/config" kubiccfg "github.com/kubic-project/kubic-init/pkg/config" "github.com/kubic-project/kubic-init/pkg/loader" "github.com/kubic-project/kubic-init/pkg/util" ) const ( // multusClusterRoleName sets the name for the multus ClusterRole multusClusterRoleName = "kubic:multus" // multusClusterRoleNamePSP the PSP cluster role multusClusterRoleNamePSP = "kubic:psp:multus" // multusServiceAccountName describes the name of the ServiceAccount for the multus addon multusServiceAccountName = "kubic-multus" // multusNetworkName describes the name of the cni config multusNetworkName = "multus-cni-network" ) var ( serviceAccount = v1.ServiceAccount{ ObjectMeta: metav1.ObjectMeta{ Name: multusServiceAccountName, Namespace: metav1.NamespaceSystem, }, } clusterRole = rbac.ClusterRole{ ObjectMeta: metav1.ObjectMeta{ Name: multusClusterRoleName, }, Rules: []rbac.PolicyRule{ { APIGroups: []string{"k8s.cni.cncf.io"}, Resources: []string{"*"}, Verbs: []string{"*"}, }, { APIGroups: []string{""}, Resources: []string{"pods", "pods/status"}, Verbs: []string{"get", "update"}, }, }, } clusterRoleBinding = rbac.ClusterRoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: multusClusterRoleName, }, RoleRef: rbac.RoleRef{ APIGroup: rbac.GroupName, Kind: "ClusterRole", Name: multusClusterRoleName, }, Subjects: []rbac.Subject{ { Kind: rbac.ServiceAccountKind, Name: multusServiceAccountName, Namespace: metav1.NamespaceSystem, }, }, } clusterRoleBindingPSP = rbac.ClusterRoleBinding{ ObjectMeta: metav1.ObjectMeta{ Name: multusClusterRoleNamePSP, }, RoleRef: rbac.RoleRef{ APIGroup: rbac.GroupName, Kind: "ClusterRole", Name: "suse:kubic:psp:privileged", }, Subjects: []rbac.Subject{ { Kind: rbac.ServiceAccountKind, Name: multusServiceAccountName, Namespace: metav1.NamespaceSystem, }, }, } customResourceDefinition = apiextensionsv1beta1.CustomResourceDefinition{ ObjectMeta: metav1.ObjectMeta{ Name: "network-attachment-definitions.k8s.cni.cncf.io", }, Spec: apiextensionsv1beta1.CustomResourceDefinitionSpec{ Group: "k8s.cni.cncf.io", Version: "v1", Scope: "Namespaced", Names: apiextensionsv1beta1.CustomResourceDefinitionNames{ Plural: "network-attachment-definitions", Singular: "network-attachment-definition", Kind: "NetworkAttachmentDefinition", ShortNames: []string{"net-attach-def"}, }, Validation: &apiextensionsv1beta1.CustomResourceValidation{ OpenAPIV3Schema: &apiextensionsv1beta1.JSONSchemaProps{ Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ "spec": apiextensionsv1beta1.JSONSchemaProps{ Properties: map[string]apiextensionsv1beta1.JSONSchemaProps{ "config": apiextensionsv1beta1.JSONSchemaProps{ Type: "string", }, }, }, }, }, }, }, } ) type multusCniStruct struct { Name string `json:"name,omitempty"` Type string `json:"type,omitempty"` Kubeconfig string `json:"kubeconfig"` Delegates []map[string]interface{} `json:"delegates"` } func init() { // self-register in the CNI plugins registry cni.Registry.Register("multus", EnsuremultusAddon) } // EnsuremultusAddon creates the multus addons func EnsuremultusAddon(cfg *config.KubicInitConfiguration, client clientset.Interface) error { if err := createServiceAccount(client); err != nil { return fmt.Errorf("error when creating multus service account: %v", err) } multusConfigMap := "" switch cfg.Network.Cni.Driver { case "cilium": multusConfigMap = cilium.CiliumCniConfigMap case "flannel": multusConfigMap = flannel.FlannelConfigMap19 } var multusConfigMapBytes []byte multusConfigMapBytes, err := kubeadmutil.ParseTemplate(multusConfigMap, struct { Network string Backend string KubeConfig string }{ cfg.Network.PodSubnet, "vxlan", // TODO: replace by some config arg kubiccfg.DefaultKubicKubeconfig, //TODO create kubeconfig for multus }) if err != nil { return fmt.Errorf("error when parsing multus configmap template: %v", err) } if err := createmultusAddon(multusConfigMapBytes, client, cfg.Network.Cni.Driver); err != nil { return fmt.Errorf("error when creating multus addons: %v", err) } if err := createRBACRules(client, cfg.Features.PSP); err != nil { return fmt.Errorf("error when creating multus RBAC rules: %v", err) } kubeconfig, err := kubicclient.GetConfig() if err != nil { return fmt.Errorf("failed to create kubic client: %v", err) } multusCRD := loader.CrdsSet{} multusCRD[util.NamespacedObjToString(&customResourceDefinition)] = &customResourceDefinition if err := loader.CreateCRDs(kubeconfig, multusCRD); err != nil { return fmt.Errorf("failed to create multus CRD: %v", err) } glog.V(1).Infof("[kubic] installed multus CNI driver") return nil } // CreateServiceAccount creates the necessary serviceaccounts that kubeadm uses/might use, if they don't already exist. func createServiceAccount(client clientset.Interface) error { return apiclient.CreateOrUpdateServiceAccount(client, &serviceAccount) } func createmultusAddon(configMapBytes []byte, client clientset.Interface, driver string) error { delegateConfigMap := &v1.ConfigMap{} if err := kuberuntime.DecodeInto(clientsetscheme.Codecs.UniversalDecoder(), configMapBytes, delegateConfigMap); err != nil { return fmt.Errorf("unable to decode multus configmap %v", err) } delegateCniJSON := []byte(delegateConfigMap.Data["cni-conf.json"]) var multusCniJSON map[string]interface{} json.Unmarshal(delegateCniJSON, &multusCniJSON) multusCniConfig := multusCniStruct{ Name: multusNetworkName, Type: "multus", Kubeconfig: kubiccfg.DefaultKubicKubeconfig, Delegates: []map[string]interface{}{multusCniJSON}, } marshaledCniJSON, _ := json.Marshal(multusCniConfig) multusConfigMap := &v1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: "cni-config", Namespace: metav1.NamespaceSystem, Labels: map[string]string{ "tier": "node", "app": "multus", }, }, Data: map[string]string{ "cni-conf.json": string(marshaledCniJSON), }, } if driver == "flannel" { multusConfigMap.Data["net-conf.json"] = delegateConfigMap.Data["net-conf.json"] } // Create the ConfigMap for multus or update it in case it already exists return apiclient.CreateOrUpdateConfigMap(client, multusConfigMap) } // CreateRBACRules creates the essential RBAC rules for a minimally set-up cluster func createRBACRules(client clientset.Interface, psp bool) error { var err error if err = apiclient.CreateOrUpdateClusterRole(client, &clusterRole); err != nil { return err } if err = apiclient.CreateOrUpdateClusterRoleBinding(client, &clusterRoleBinding); err != nil { return err } if psp { if err = apiclient.CreateOrUpdateClusterRoleBinding(client, &clusterRoleBindingPSP); err != nil { return err } } return nil } <file_sep>GO := GO111MODULE=on GO15VENDOREXPERIMENT=1 go GO_NOMOD := GO111MODULE=off go GO_VERSION := $(shell $(GO) version | sed -e 's/^[^0-9.]*\([0-9.]*\).*/\1/') GO_BIN := $(shell [ -n "${GOBIN}" ] && echo ${GOBIN} || (echo `echo ${GOPATH} | cut -f1 -d':'`/bin)) GO_VERSION_MAJ := $(shell echo $(GO_VERSION) | cut -f1 -d'.') GO_VERSION_MIN := $(shell echo $(GO_VERSION) | cut -f2 -d'.') SOURCES_DIRS = cmd pkg SOURCES_DIRS_GO = ./pkg/... ./cmd/... # go source files, ignore vendor directory KUBIC_INIT_SRCS = $(shell find $(SOURCES_DIRS) -type f -name '*.go' -not -path "*generated*") KUBIC_INIT_MAIN_SRCS = $(shell find $(SOURCES_DIRS) -type f -name '*.go' -not -path "*_test.go") KUBIC_INIT_GEN_SRCS = $(shell grep -l -r "//go:generate" $(SOURCES_DIRS)) DEEPCOPY_FILENAME := zz_generated.deepcopy.go # the list of all the deepcopy.go files we are going to generate DEEPCOPY_GENERATED_FILES := $(foreach file,$(KUBIC_INIT_GEN_SRCS),$(dir $(file))$(DEEPCOPY_FILENAME)) DEEPCOPY_GENERATOR := $(GO_BIN)/deepcopy-gen KUBIC_INIT_EXE = cmd/kubic-init/kubic-init KUBIC_INIT_MAIN = cmd/kubic-init/main.go .DEFAULT_GOAL: $(KUBIC_INIT_EXE) # These will be provided to the target KUBIC_INIT_VERSION := 1.0.0 KUBIC_INIT_BUILD := $(shell git rev-parse HEAD 2>/dev/null) KUBIC_INIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD 2> /dev/null || echo 'unknown') KUBIC_INIT_BUILD_DATE := $(shell date +%Y%m%d-%H:%M:%S) # Use linker flags to provide version/build settings to the target KUBIC_INIT_LDFLAGS = -ldflags "-X=main.Version=$(KUBIC_INIT_VERSION) \ -X=main.Build=$(KUBIC_INIT_BUILD) \ -X=main.BuildDate=$(KUBIC_INIT_BUILD_DATE) \ -X=main.Branch=$(KUBIC_INIT_BRANCH) \ -X=main.GoVersion=$(GO_VERSION)" ############################################################# # Build targets ############################################################# all: $(KUBIC_INIT_EXE) print-version: @echo "kubic-init version: $(KUBIC_INIT_VERSION)" @echo "kubic-init build: $(KUBIC_INIT_BUILD)" @echo "kubic-init branch: $(KUBIC_INIT_BRANCH)" @echo "kubic-init date: $(KUBIC_INIT_BUILD_DATE)" @echo "go: $(GO_VERSION)" # NOTE: deepcopy-gen doesn't support go1.11's modules, so we must 'go get' it $(DEEPCOPY_GENERATOR): @[ -n "${GOPATH}" ] || ( echo "FATAL: GOPATH not defined" ; exit 1 ; ) @echo ">>> Getting deepcopy-gen (for $(DEEPCOPY_GENERATOR))" -@$(GO_NOMOD) get -u k8s.io/code-generator/cmd/deepcopy-gen -@$(GO_NOMOD) get -d -u k8s.io/apimachinery define _CREATE_DEEPCOPY_TARGET $(1): $(DEEPCOPY_GENERATOR) $(shell grep -l "//go:generate" $(dir $1)/*) @echo ">>> Updating deepcopy files in $(dir $1)" @$(GO) generate -x $(dir $1)/* endef # Use macro to generate targets for all the DEEPCOPY_GENERATED_FILES files $(foreach file,$(DEEPCOPY_GENERATED_FILES),$(eval $(call _CREATE_DEEPCOPY_TARGET,$(file)))) clean-generated: rm -f $(DEEPCOPY_GENERATED_FILES) generate: $(DEEPCOPY_GENERATOR) $(DEEPCOPY_GENERATED_FILES) .PHONY: generate go-version-check: @[ $(GO_VERSION_MAJ) -ge 2 ] || \ [ $(GO_VERSION_MAJ) -eq 1 -a $(GO_VERSION_MIN) -ge 11 ] || (echo "FATAL: Go version:$(GO_VERSION) does not support modules" ; exit 1 ; ) $(KUBIC_INIT_EXE): $(KUBIC_INIT_MAIN_SRCS) $(DEEPCOPY_GENERATED_FILES) @make go-version-check @echo ">>> Building $(KUBIC_INIT_EXE)..." $(GO) build $(KUBIC_INIT_LDFLAGS) -o $(KUBIC_INIT_EXE) $(KUBIC_INIT_MAIN) .PHONY: fmt fmt: $(KUBIC_INIT_SRCS) @echo ">>> Reformatting code" @$(GO) fmt $(SOURCES_DIRS_GO) .PHONY: simplify simplify: @gofmt -s -l -w $(KUBIC_INIT_SRCS) # NOTE: deepcopy-gen doesn't support go1.11's modules, so we must 'go get' it $(GO_BIN)/golint: @echo ">>> Getting $(GO_BIN)/golint" @$(GO_NOMOD) get -u golang.org/x/lint/golint @echo ">>> $(GO_BIN)/golint successfully installed" # once golint is fixed add here option to golint: set_exit_status # see https://github.com/kubic-project/kubic-init/issues/69 .PHONY: check check: $(GO_BIN)/golint @test -z $(shell gofmt -l $(KUBIC_INIT_MAIN) | tee /dev/stderr) || echo "[WARN] Fix formatting issues with 'make fmt'" @for d in $$($(GO) list ./... | grep -v /vendor/); do $(GO_BIN)/golint -set_exit_status $${d}; done @$(GO) tool vet ${KUBIC_INIT_SRCS} terraform fmt lint: check check-config: $(KUBIC_INIT_EXE) @YAMLS=`find config -type f -print0 | \ xargs -0 egrep "kind: KubicInitConfiguration" | \ cut -d':' -f1` ; \ for f in $$YAMLS ; do \ echo "Checking $$f..." ; \ $(KUBIC_INIT_EXE) checkconfig --config $$f ; \ done .PHONY: test test: @$(GO) test -v ./pkg/... ./cmd/... -coverprofile cover.out .PHONY: check clean: rm -f $(KUBIC_INIT_EXE) rm -f config/rbac/*.yaml config/crds/*.yaml .PHONY: coverage coverage: $(GO_NOMOD) tool cover -html=cover.out include build/make/*.mk <file_sep>TF_LIBVIRT_FULL_DIR = deployments/tf-libvirt-full TF_LIBVIRT_NODES_DIR = deployments/tf-libvirt-nodes TF_ARGS_DEFAULT = -input=false -auto-approve \ -var 'kubic_init_image_tgz="$(IMAGE_TAR_GZ)"' \ -var 'kubic_init_extra_args="$(KUBIC_INIT_EXTRA_ARGS)"' SSH_ARGS := -o "StrictHostKeyChecking=no" SSH_VMS := $(shell command sshpass >/dev/null 2>&1 && echo "sshpass -p linux ssh $(SSH_ARGS)" || echo "ssh $(SSH_ARGS)") ############################################################# # Terraform deployments ############################################################# ### Terraform full deplyment tf-full-plan: cd $(TF_LIBVIRT_FULL_DIR) && terraform init && terraform plan # # Usage: # - create a only-one-seeder cluster: # $ make tf-full-run TF_ARGS="-var nodes_count=0" # - create cluster with Docker: # $ make tf-full-run TF_ARGS="-var kubic_init_runner=docker" \ # KUBIC_INIT_EXTRA_ARGS="--var Runtime.Engine=docker" # tf-full-run: tf-full-apply tf-full-apply: docker-image @echo ">>> Deploying a full cluster with Terraform..." cd $(TF_LIBVIRT_FULL_DIR) && terraform init && terraform apply $(TF_ARGS_DEFAULT) $(TF_ARGS) tf-full-reapply: cd $(TF_LIBVIRT_FULL_DIR) && terraform init && terraform apply $(TF_ARGS_DEFAULT) $(TF_ARGS) tf-full-destroy: cd $(TF_LIBVIRT_FULL_DIR) && terraform init && terraform destroy -force $(TF_ARGS_DEFAULT) $(TF_ARGS) tf-full-nuke: -make tf-full-destroy cd $(TF_LIBVIRT_FULL_DIR) && rm -f *.tfstate* ### Terraform only-seeder deployment (shortcut for `nodes_count=0`) tf-seeder-plan: -make tf-full-plan TF_ARGS="-var nodes_count=0 $(TF_ARGS)" # # Usage: # - create a seeder with a specific Token: # $ env TOKEN=XXXX make tf-seeder-run # tf-seeder-run: tf-seeder-apply tf-seeder-apply: @echo ">>> Deploying only-seeder with Terraform..." @make tf-full-apply TF_ARGS="-var nodes_count=0 $(TF_ARGS)" tf-seeder-reapply: @make tf-full-reapply TF_ARGS="-var nodes_count=0 $(TF_ARGS)" tf-seeder-destroy: @make tf-full-destroy TF_ARGS="-var nodes_count=0 $(TF_ARGS)" tf-seeder-nuke: tf-full-nuke ### Terraform only-nodes deployment tf-nodes-plan: cd $(TF_LIBVIRT_NODES_DIR) && terraform init && terraform plan # # Usage: # - create only one node (ie, for connecting to the seeder started locally with `make local-run`): # $ env TOKEN=XXXX make tf-nodes-run # tf-nodes-run: tf-nodes-apply tf-nodes-apply: docker-image @echo ">>> Deploying only-nodes with Terraform..." cd $(TF_LIBVIRT_NODES_DIR) && terraform init && terraform apply $(TF_ARGS_DEFAULT) $(TF_ARGS) tf-nodes-destroy: $(TF_LIBVIRT_NODES_DIR)/.terraform cd $(TF_LIBVIRT_NODES_DIR) && terraform init && terraform destroy -force $(TF_ARGS_DEFAULT) $(TF_ARGS) tf-nodes-nuke: -make tf-nodes-destroy cd $(TF_LIBVIRT_NODES_DIR) && rm -f *.tfstate* # # some ssh convenience targets # SEEDER := $(shell cd $(TF_LIBVIRT_FULL_DIR) && terraform output -json seeder 2>/dev/null | python -c 'import sys, json; print json.load(sys.stdin)["value"]' 2>/dev/null) tf-ssh-seeder: $(SSH_VMS) root@$(SEEDER) NODE0 := $(shell cd $(TF_LIBVIRT_FULL_DIR) && terraform output -json nodes 2>/dev/null | python -c 'import sys, json; print json.load(sys.stdin)["value"][0][0]' 2>/dev/null) tf-ssh-node-0: @$(SSH_VMS) root@$(NODE0) <file_sep> ## 0.0.3 Initial kubic-init - January 12 2019 ### Kubic-init - Add check if the kubic-init must reset or bootstrap before going forward (https://github.com/kubic-project/kubic-init/pull/149) - cni: make default cni config placement configurable - cni: add cilium cni plugin - cni: flannel initialization and make the CNI configuration and binaries dirs configurable - config: parse bind interface (https://github.com/kubic-project/kubic-init/pull/142) - cni: use flannel as the default CNI driver - Load the kubic-manager once the seeder has finished with the control-plane - When `autoApproval=false` in the config file, remove the RBAC rules used for approvinfg nodes automatically. - Use the etcd image from the registry.suse.de ### K8s & Kubeadm - Add a command for getting kubeadm's version and log it. - Upgrade to k8s 1.13.0 - Use the v1beta1 API - Use admin kubeconfig to deploy CRD's - Get rid of our own Init/Join code (https://github.com/kubic-project/kubic-init/pull/2) <file_sep>![alpha](https://img.shields.io/badge/stability%3F-beta-yellow.svg) [![Go Report Card](https://goreportcard.com/badge/github.com/kubic-project/kubic-init)](https://goreportcard.com/report/github.com/kubic-project/kubic-init) [![GoDoc](https://godoc.org/github.com/kubic-project/kubic-init?status.svg)](https://godoc.org/github.com/kubic-project/kubic-init) [![CircleCI](https://circleci.com/gh/kubic-project/kubic-init/tree/master.svg?style=svg)](https://circleci.com/gh/kubic-project/kubic-init/tree/master) # Kubic-init: The Kubic-init repository is a project geared at simplifying the process of creating and maintaining kubernetes clusters. Kubic-init is being actively developed/tested on top of the [Kubic project](https://en.opensuse.org/Portal:Kubic). - [User-Guide-documentation](docs/user-guide.md) - [Design And Architecture](docs/design.md) - [Devel](docs/devel.md) - [Roadmap](docs/roadmap.md) <file_sep>#!/bin/bash # NOTE: these variables will be replaced by Terraform IMAGE="${kubic_init_image_name}" IMAGE_FILENAME="${kubic_init_image_tgz}" RUNNER=${kubic_init_runner} EXTRA_ARGS="${kubic_init_extra_args}" ################################################################################### log() { echo ">>> $@" ; } set_var() { var="$1" value="$2" file="$3" if [ -f $file ] ; then log "Setting $var=$value in $file..." sed -i 's|^\('"$var"'\)\ *=.*|\1 = '"$value"'|' $file else log "Creating new file $file, with $var=$value..." echo "$var = $value" > $file fi # TODO: add a case for where the file exists but the var doesn't } print_file() { log "Contents of $1:" log "------------------------------------" cat $1 | awk '{ print ">>> " $0 }' log "------------------------------------" } log "Making sure kubic-init is not running..." systemctl stop kubic-init >/dev/null 2>&1 || /bin/true log "Setting runner as $RUNNER..." [ -x /usr/bin/$RUNNER ] || ( log "FATAL: /usr/bin/$RUNNER does not exist!!!" ; exit 1 ; ) set_var KUBIC_INIT_RUNNER /usr/bin/$RUNNER /etc/sysconfig/kubic-init log "Removing any previous kubic-init image..." /usr/bin/$RUNNER rmi kubic-init >/dev/null 2>&1 || /bin/true log "Setting up network..." echo br_netfilter > /etc/modules-load.d/br_netfilter.conf modprobe br_netfilter sysctl -w net.ipv4.ip_forward=1 log "Setting up crio..." set_var plugin_dir \"/var/lib/kubelet/cni/bin\" /etc/crio/crio.conf echo 'runtime-endpoint: unix:///var/run/crio/crio.sock' > /etc/crictl.yaml log "Setting up storage..." set_var driver \"btrfs\" /etc/containers/storage.conf [ "$RUNNER" = "podman" ] && IMAGE="localhost/$IMAGE" log "Setting image as $IMAGE" set_var KUBIC_INIT_IMAGE "\"$IMAGE\"" /etc/sysconfig/kubic-init if [ -n "$EXTRA_ARGS" ] ; then log "Setting kubic-init extra args = $EXTRA_ARGS" set_var KUBIC_INIT_EXTRA_ARGS "\"$EXTRA_ARGS\"" /etc/sysconfig/kubic-init fi print_file /etc/sysconfig/kubic-init print_file /etc/kubic/kubic-init.yaml [ -d /var/lib/etcd ] || ( log "Creating etcd staorage..." ; mkdir -p /var/lib/etcd ; ) log "Loading the kubic-init image with $RUNNER from /tmp/$IMAGE_FILENAME..." while ! /usr/bin/$RUNNER load -i /tmp/$IMAGE_FILENAME ; do log "(will try to load the kubic-init image again)" sleep 5 done log "Enabling the kubic-init service..." sysctl --system systemctl daemon-reload systemctl enable kubelet [ "$RUNNER" = "podman" ] && \ systemctl enable --now crio || \ systemctl enable --now docker systemctl enable --now kubic-init <file_sep>#! /bin/bash set -e if [[ -z "${SEEDER}" ]]; then # set SEEDER var from ARGs if env var is empty SEEDER=$1 # if ARG and ENV empty Error out [ -n "$SEEDER" ] || ( echo "FATAL: must provide SEEDER variable as ENV or Arg" ; exit 1 ; ) fi # this IP will be then read by golang using os.env export SEEDER ginkgo -r --randomizeAllSpecs --randomizeSuites --failFast --cover --trace --race --progress -v
14b65468151e40c8312fae9086ab0461c9d36300
[ "Markdown", "Makefile", "Python", "Go", "Shell" ]
23
Go
drpaneas/kubic-init
16ae56074c01fe9f9c66c163f2d609af21f911c4
d01db0cfc3a55e83ec3042b5adfc25b0debc13c4
refs/heads/master
<repo_name>rolandvs/Micropython-scheduler<file_sep>/README.md Micropython-scheduler ===================== V1.02 6th Sept 2014 Author: <NAME> A set of libraries for writing threaded code on the MicroPython board. Files ----- There are five libraries 1. usched.py The scheduler 2. switch.py Support for debounced switches. Uses usched. 3. pushbutton.py Pushbutton supports logical value, press, release, long and double click callbacks 4. lcdthread.py Support for LCD displays using the Hitachi HD44780 controller chip. Uses usched. 5. delay.py A simple retriggerable time delay class Test/demonstration programs 1. ledflash.py Flashes the onboard LED's asynchronously 2. roundrobin.py Demonstrates round-robin schedulting. 3. irqtest.py Demonstrates a thread which blocks on an interrupt. 4. subthread.py Illustrates dynamic creation and deletion of threads. 5. lcdtest.py Demonstrates output to an attached LCD display. 6. polltest.py A thread which blocks on a user defined polling function 7. instrument.py The scheduler's timing functions employed to instrument code 8. pushbuttontest.py Demo of pushbutton class Now uses the new pyb.micros() function rather than tie up a hardware timer. Hence requires a version of MicroPython dated on or after 28th Aug 2014. There is also a file minified.zip. This includes the above files but run through pyminifier to strip comments and unneccesary spaces. Cryptic. Only recommended if you're running on internal memory and are short of space. Please report any bugs against the standard version as the line numbers won't match otherwise! The scheduler uses generators and the yield statement to implement lightweight threads. When a thread submits control to the scheduler it yields an object which informs the scheduler of the circumstances in which the thread should resume execution. There are four options. 1. A timeout: the thread will be rescheduled after a given time has elapsed. 2. Round robin: it will be rescheduled as soon as possible subject to other pending threads getting run. 3. Pending a poll function: a user specified function is polled by the scheduler and can cause the thread to be scheduled. 4. Wait pending a pin interrupt: thread will reschedule after a pin interrupt has occurred. The last two options may include a timeout: a maximum time the thread will block pending the specified event. Overview -------- Documentation Most of this is in the code comments. Look at the example programs first, then at the libraries themselves for more detail. Timing The scheduler's timing is based on pyb.micros(). My use of microsecond timing shouldn't lead the user into hopeless optimism: if you want a delay of 1mS exactly don't issue yield from wait(0.001) and expect to get a one millisecond delay. It's a cooperative scheduler. Another thread will be running when the period elapses. Until that thread decides to yield your thread will have no chance of restarting. Even then a higher priority thread such as one blocked on an interrupt may, by then, be pending. So, while the minimum delay will be 1mS the maximum is dependent on the other code you have running. On the Micropython board don't be too surprised to see delays of many milliseconds. If you want precise timing, especially at millisecond level or better, you'll need to use one of the hardware timers. Avoid issuing short timeout values. A thread which does so will tend to hog the CPU at the expense of other threads. The well mannered way to yield control in the expectation of restarting soon is to yield a Roundrobin instance. In the absence of higher priority events, such a thread will resume when any other such threads have been scheduled. Communication In nontrivial applications threads need to communicate. A well behaved thread periodically yields control to the scheduler: the item yielded is an object which tells the scheduler the conditions under which the thread is to be re-sceduled. The item yielded is unsuitable for use for inter-thread communication which is best achieved by passing a shared mutable object as an argument to a thread on creation. At its simplest this can be a list, as in the example subthread.py. More flexibly a user defined mutable object may be used as in polltest.py. I'm ignoring the idea of globals here! Concurrency The more gory aspects of concurrency are largely averted in a simple cooperative scheduler such as this: at any one time one thread has complete control and a data item is not suddenly going to be changed by the activities of another thread. However the Micropython system does enable hardware interrupts, and their handlers pre-emptively take control and run in their own context. Appropriate precautions should be taken communicating between interrupt handlers and other code. Interrupts The way in which the scheduler supports pin interrupts is described in irqtest.py In essence the user supplies a callback function. When an interrupt occurs, the default callback runs which increments a counter and runs the user's callback. A thread blocked on this interrupt will be rescheduled by virtue of the scheduler checking this counter. It's important to be aware that the user's callback runs in the IRQ context and is therefore subject to the Micropython rules on interrupt handlers along with the concurrency issues mentioned above. Polling Some hardware such as the accelerometer doesn't support interrupts, and therefore needs to be polled. One option suitable for slow devices is to write a thread which polls the device periodically. A faster and more elegant way is to delegate this activity to the scheduler. The thread then suspends excution pending the result of a user supplied callback function, which is run by the scheduler. From the thread's point of view it blocks pending an event - with an optional timeout available. Return from yield The scheduler returns a 3-tuple to all yield statements. In many case this can be ignored but it contains information about why the thread was scheduled such as a count of interrupts which have occurred and whether the return was due to an event or a timeout. Elements are: 0. 0 unless thread returned a Pinblock and one or more interrupts have occured, when it holds a count of interrupts. 1. 0 unless thread returned a Poller and the latter has returned an integer, when it holds that value. 2. 0 unless thread was waiting on a timer* when it holds no. of uS it is late * In addition to Timeout instances this includes timeouts applied to Pinblock or Poller objects: this enables the thread to determine whether it was rescheduled because of the event or because of a timeout. If the thread yielded a Roundrobin instance the return tuple will be (0, 0, 0). There is little point in intercepting this. Initialisation A thread is created with code like objSched.add_thread(robin("Thread 1")) When this code runs a generator object is created and assigned to the scheduler. It's important to note that at this time the thread will run until the first yield statement. It will then suspend execution until the scheduler starts. This enables initialisation code to be run in a well defined order: the order in which the threads are created. <file_sep>/lib/usched.py # Microthreads for the micropython board. 6th Sep 2014 # Author: <NAME> # V1.02 6th Sep 2014 Uses pyb.micros() in place of timer 2. Implements wait generator # V1.01 25th Aug 2014 # 25th Aug microsUntil added for Delay class # 14th Aug unused pin argument removed from Waitfor constructor # 12th Aug: Waitfor.triggered returns a measure of priority, with scheduler scheduling the highest priority thread # and sending the result to the yield statement # New implementation. Uses microsecond counter more effectively. Supports waiting on interrupt. import pyb import micropython micropython.alloc_emergency_exception_buf(100) # *************************************************** TIMER ACCESS ************************************************** # Utility functions enable access to the counter which produce correct results if timer rolls over TIMERPERIOD = 0x7fffffff # 35.79 minutes 2148 secs MAXTIME = TIMERPERIOD//2 # 1073 seconds maximum timeout MAXSECS = MAXTIME//1000000 class TimerException(Exception) : pass def microsWhen(timediff): # Expected value of counter in a given no. of uS if timediff >= MAXTIME: raise TimerException() return (pyb.micros() + timediff) & TIMERPERIOD def microsSince(oldtime): # No of uS since timer held this value return (pyb.micros() - oldtime) & TIMERPERIOD def after(trigtime): # If current time is after the specified value return res = ((pyb.micros() - trigtime) & TIMERPERIOD) # the no. of uS after. Otherwise return zero if res >= MAXTIME: res = 0 return res def microsUntil(tim): # uS from now until a specified time (used in Delay class) return ((tim - pyb.micros()) & TIMERPERIOD) def seconds(S): # Utility functions to convert to integer microseconds return int(1000000*S) def millisecs(mS): return int(1000*mS) # *********************************** WAITFOR CLASS: TRIGGER FOR THREAD EXECUTION *********************************** # This is a base class. User threads should use only classes derived from this. # Threads submit control by yielding a Waitfor object. This conveys information to the scheduler as to when the thread # should be rescheduled. The scheduler stores this on the task list and polls its triggered method to determine if the # thread is ready to run. Can wait on a time, an interrupt, a poll function, or not at all: reschedule ASAP running # other such threads in round-robin fashion. A timeout may be applied when blocking on an interrupt or a poll. # A poll function will be called every time the scheduler determines which thread to run, so should execute quickly. # It should return None unless the thread is to run, in which case it should return an integer which will be passed # back to the thread # The triggered method returns a "priority" tuple of three integers indicating priority or None. The latter indicates # that the thread is not ready for execution. The value (0,0,0) indicates a round-robin reschedule. # The tuple holds: # (number of interrupts missed, pollfunc return value, uS after timeout or zero if it's a round-robin thread) # This design allows priorities to be sorted in natural order. The scheduler sends this tuple to the thread which # yielded the Waitfor object. # Time in uS must not exceed MAXTIME (536 secs) and an exception will be raised if a longer time is specified. Threads # can readily implement longer delays with successive yields in a loop. # If a thread wishes to run again ASAP it yields a Roundrobin instance. In the absence of timed-out or higher priority # threads, threads yielding these will run in round-robin fashion with minimal delay. class Waitfor(object): def __init__(self): self.uS = 0 # Current value of timeout in uS self.timeout = microsWhen(0) # End value of microsecond counter when TO has elapsed self.forever = False # "infinite" time delay flag self.irq = None # Interrupt vector no self.pollfunc = None # Function to be called if we're polling self.pollfunc_args = () # Arguments for the above self.customcallback = None # Optional custom interrupt handler self.interruptcount = 0 # Set by handler, tested by triggered() self.roundrobin = False # If true reschedule ASAP def triggered(self): # Polled by scheduler. Returns a priority tuple or None if not ready if self.irq: # Waiting on an interrupt self.irq.disable() # Potential concurrency issue here (????) numints = self.interruptcount # Number of missed interrupts if numints: # Waiting on an interrupt and it's occurred self.interruptcount = 0 # Clear down the counter self.irq.enable() if numints: return (numints, 0, 0) if self.pollfunc: # Optional function for the scheduler to poll res = self.pollfunc(*self.pollfunc_args) # something other than an interrupt if res is not None: return (0, res, 0) if not self.forever: # Check for timeout if self.roundrobin: return (0,0,0) # Priority value of round robin thread res = after(self.timeout) # uS after, or zero if not yet timed out in which case we return None if res: # Note: can never return (0,0,0) here! return (0, 0, res) # Nonzero means it's timed out return None # Not ready for execution def _ussetdelay(self,uS = None): # Reset the timer by default to its last value if uS: # If a value was passed, update it self.uS = uS self.timeout = microsWhen(self.uS) # Target timer value return self def setdelay(self, secs = None): # Method used by derived classes to alter timer values if secs is None: # Set to infinity self.forever = True return self else: # Update saved delay and calculate a new end time self.forever = False return self._ussetdelay(seconds(secs)) def __call__(self): # Convenience function allows user to yield an updated if self.uS: # waitfor object return self._ussetdelay() return self def intcallback(self, irqno): # Runs in interrupt's context. if self.customcallback: self.customcallback(irqno) self.interruptcount += 1 # Increments count to enable trigger to operate class Roundrobin(Waitfor): # Trivial subclasses of Waitfor. A thread yielding a Roundrobin def __init__(self): # will be rescheduled as soon as priority threads have been serviced super().__init__() self.roundrobin = True class Timeout(Waitfor): # A thread yielding a Timeout instance will pause for at least that period def __init__(self, tim): # Time is in seconds super().__init__() self.setdelay(tim) # A thread can relinquish control for a period in two ways: yielding a Timeout instance or issuing # yield from wait(time_in_seconds) # The latter imposes no restrictions on the duration whereas a Timeout will throw an exception if the time exceeds # MAXTIME def wait(secs): if secs <=0 : raise TimerException() count = secs // MAXSECS # number of 30 minute iterations tstart = secs - count*MAXSECS # remainder (divmod is a tad broken) yield Timeout(tstart) while count: yield Timeout(MAXSECS) count -= 1 # ************************************************ INTERRUPT HANDLING *********************************************** # The aim here is to enable a thread to block pending receipt of an interrupt. An optional timeout may be applied. # A thread wishing to do this must create a Pinblock instance with optional timeout and callback function # wf = Pinblock(mypin, pyb.ExtInt.IRQ_FALLING, pyb.Pin.PULL_NONE, mycallback) # The custom callback function (if provided) receives the irq number as its only argument class Pinblock(Waitfor): # Block on an interrupt from a pin subject to optional timeout def __init__(self, pin, mode, pull, customcallback = None, timeout = None): super().__init__() self.customcallback = customcallback if timeout is None: self.forever = True else: self.setdelay(timeout) self.irq = pyb.ExtInt(pin, mode, pull, self.intcallback) class Poller(Waitfor): def __init__(self, pollfunc, pollfunc_args = (), timeout = None): super().__init__() self.pollfunc = pollfunc self.pollfunc_args = pollfunc_args if timeout is None: self.forever = True else: self.setdelay(timeout) # ************************************************* SCHEDULER CLASS ************************************************* class Sched(object): def __init__(self): self.lstThread = [] # Entries contain [Waitfor object, function] self.bStop = False def stop(self): # Kill the run method self.bStop = True def add_thread(self, func): # Thread list contains [Waitfor object, generator] try: # Run thread to first yield to acquire a Waitfor instance self.lstThread.append([func.send(None), func]) # and put the resultant thread onto the threadlist except StopIteration: # Shouldn't happen on 1st call: implies thread lacks a yield statement print("Stop iteration error") # best to tell user. def run(self): # Run scheduler but trap ^C for testing try: self._runthreads() except OSError as v: # Doesn't recognise EnvironmentError or VCPInterrupt! print(v) print("Interrupted") def _runthreads(self): # Only returns if the stop method is used or all threads terminate while len(self.lstThread) and not self.bStop: # Run until last thread terminates or the scheduler is stopped self.lstThread = [thread for thread in self.lstThread if thread[1] is not None] # Remove threads flagged for deletion lstPriority = [] # List threads which are ready to run lstRoundRobin = [] # Low priority round robin threads for idx, thread in enumerate(self.lstThread): # Put each pending thread on priority or round robin list priority = thread[0].triggered() # (interrupt count, poll func value, uS overdue) or None if priority is not None: # Ignore threads waiting on events or time if priority == (0,0,0) : # (0,0,0) indicates round robin lstRoundRobin.append(idx) else: # Thread is ready to run lstPriority.append((priority, idx)) # List threads ready to run lstPriority.sort() # Lowest priority will be first in list while True: # Until there are no round robin threads left while len(lstPriority): # Execute high priority threads first priority, idx = lstPriority.pop(-1) # Get highest priority thread. Thread: thread = self.lstThread[idx] # thread[0] is the current waitfor instance, thread[1] is the code try: # Run thread, send (interrupt count, poll func value, uS overdue) thread[0] = thread[1].send(priority) # Thread yields a Waitfor object: store it for subsequent testing except StopIteration: # The thread has terminated: self.lstThread[idx][1] = None # Flag thread for removal if len(lstRoundRobin) == 0: # There are no round robins pending. Quit the loop to rebuild new break # lists of threads idx = lstRoundRobin.pop() # Run an arbitrary round robin thread and remove from pending list thread = self.lstThread[idx] try: # Run thread, send (0,0,0) because it's a round robin thread[0] = thread[1].send((0,0,0)) # Thread yields a Waitfor object: store it except StopIteration: # The thread has terminated: self.lstThread[idx][1] = None # Flag thread for removal # Rebuild priority list: time has elapsed and events may have occurred! for idx, thread in enumerate(self.lstThread): # check and handle priority threads priority = thread[0].triggered() # (interrupt count, poll func value, uS overdue) or None # Ignore pending threads, those scheduled for deletion and round robins if priority is not None and priority != (0,0,0) and thread[1] is not None: lstPriority.append((priority, idx)) # Just list threads wanting to run lstPriority.sort() <file_sep>/lib/delay.py # A time delay class for the micropython board. Based on the scheduler class. 24th Aug 2014 # Author: <NAME> # V1.0 25th Aug 2014 # Used by Pushbutton library. # This class implements the software equivalent of a retriggerable monostable. When first instantiated # a delay object does nothing until it trigger method is called. It then enters a running state until # the specified time elapses when it calls the optional callback function and stops running. # A running delay may be retriggered by calling its trigger function: its time to run is now specified # by the passed value. # The usual caveats re microsheduler time periods applies: if you need millisecond accuracy # (or better) use a hardware timer. Times can easily be -0 +20mS or more, depending on other threads from usched import Sched, microsWhen, seconds, after, microsUntil, Timeout class Delay(object): def __init__(self, objSched, callback = None, callback_args = ()): self.objSched = objSched self.callback = callback self.callback_args = callback_args self._running = False def stop(self): self._running = False def trigger(self, duration): self.tstop = microsWhen(seconds(duration)) # Update end time if not self._running: # Start a thread which stops the self.objSched.add_thread(self.killer()) # delay after its period has elapsed self._running = True def running(self): return self._running def killer(self): to = Timeout(1) # Initial value is arbitrary while not after(self.tstop): # Might have been retriggered yield to._ussetdelay(microsUntil(self.tstop)) if self._running and self.callback: self.callback(*self.callback_args) self._running = False <file_sep>/instrument.py # instrument.py Demo of instrumenting code via the usched module's timer functions # Author: <NAME> # V1.02 6 Sep 2014 now uses pyb.micros() and yield from wait # V1.0 21st Aug 2014 import pyb from usched import Sched, Roundrobin, wait, microsSince # Run on MicroPython board bare hardware # THREADS: def stop(fTim, objSch): # Stop the scheduler after fTim seconds yield from wait(fTim) objSch.stop() def thr_instrument(objSch, lstResult): yield Roundrobin() # Don't measure initialisation phase (README.md) while True: start = pyb.micros() # More typically we'd measure our own code yield Roundrobin() # but here we're measuring yield delays lstResult[0] = max(lstResult[0], microsSince(start)) lstResult[1] += 1 def robin(text): wf = Roundrobin() while True: print(text) yield wf() # USER TEST PROGRAM def test(duration = 0): objSched = Sched() objSched.add_thread(robin("Thread 1")) # Instantiate a few threads objSched.add_thread(robin("Thread 2")) objSched.add_thread(robin("Thread 3")) lstResult = [0, 0] objSched.add_thread(thr_instrument(objSched, lstResult)) if duration: objSched.add_thread(stop(duration, objSched)) # Run for a period then stop objSched.run() print("Maximum delay was {:6.1f}mS".format(lstResult[0]/1000.0)) print("Thread was executed {:3d} times in {:3d} seconds".format(lstResult[1], duration)) test(2)
c7f0f4a43a04ad53878c329139ac4321412d56a6
[ "Markdown", "Python" ]
4
Markdown
rolandvs/Micropython-scheduler
1252b057a8fa6396e0b1ed9e5610c80a4dfa02dd
6c1146d5992e05ea454bd1921ef50589b5b9b744