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 acolina.pdfutils.controller; import acolina.pdfutils.App; import acolina.pdfutils.util.PDFUtil; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.stage.DirectoryChooser; import javafx.stage.FileChooser; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.util.Objects; import java.util.ResourceBundle; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class MainController { private FileChooser fileChooser = new FileChooser(); private DirectoryChooser directoryChooser = new DirectoryChooser(); private App app; private File file; @FXML private TextField archivo; @FXML private CheckBox saveImg; @FXML private CheckBox useImgFinal; @FXML private Button startButton; @FXML private Spinner<Integer> porcentage; @FXML private RadioButton minus; @FXML private RadioButton plus; /** * Initializes the controller class. This method is automatically called * after the fxml file has been loaded. */ @FXML public void initialize() { porcentage.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 100)); ToggleGroup radioGroup = new ToggleGroup(); minus.setToggleGroup(radioGroup); plus.setToggleGroup(radioGroup); } @FXML private void handleFindFile(ActionEvent event) { file = fileChooser.showOpenDialog(null); if (Objects.nonNull(file)) archivo.setText(file.toString()); } @FXML private void handleStart(ActionEvent event) { final File f = directoryChooser.showDialog(null); new Thread(() -> { PDFUtil pdfUtil = new PDFUtil(); startButton.setDisable(true); if (saveImg.isSelected()) { File directory = null; try { Future<File> future = pdfUtil.toImg(new FileInputStream(file)); directory = future.get(); } catch (IOException | InterruptedException | ExecutionException e) { e.printStackTrace(); } if (Objects.nonNull(directory)) { if (useImgFinal.isSelected()) { pdfUtil.saveImgToPDF(directory, f,porcentage.getValue(),plus.isSelected()); directory.deleteOnExit(); Platform.runLater(() -> { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Information Dialog"); alert.setHeaderText(null); alert.setContentText("Documento Guardado con exito!"); alert.showAndWait(); }); } else { String pathName = file.getPath(); // ImageUtil.saveImg(images, pathName); } } } System.gc(); startButton.setDisable(false); }).start(); } /** * Is called by the main application to give a reference back to itself. * * @param mainApp */ public void setMainApp(App mainApp) { this.app = mainApp; } } <file_sep>package acolina.pdfutils.controller.parallel; import acolina.pdfutils.util.ImageUtil; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.RecursiveTask; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ImageIOToPDFRecursiveTask extends RecursiveTask<Map<Integer, PDPage>> { private static final int MAX_IMG = 3; private Pattern pattern = Pattern.compile("-[\\d]+-"); private PDDocument document; private List<File> files; private int porcentage; private boolean isPlus; public ImageIOToPDFRecursiveTask(PDDocument document, List<File> files, int porcentage, boolean isPlus) { this.document = document; this.files = files; this.porcentage = porcentage; this.isPlus = isPlus; } @Override protected Map<Integer, PDPage> compute() { if (files.size() <= ImageIOToPDFRecursiveTask.MAX_IMG) { try { Map<Integer, PDPage> pages = new HashMap<>(ImageIOToPDFRecursiveTask.MAX_IMG); for (File image : files) { InputStream temp = ImageUtil.reduceQuality(ImageIO.read(image)); int width = ImageUtil.getScalePorcentage(Math.round(PDRectangle.LETTER.getWidth()), porcentage, isPlus); int height = ImageUtil.getScalePorcentage(Math.round(PDRectangle.LETTER.getHeight()), porcentage, isPlus); BufferedImage tempImg = ImageUtil.resize(temp, width, height); PDPage page = new PDPage(new PDRectangle(width, height)); PDPageContentStream content = new PDPageContentStream(document, page); PDImageXObject ximage = JPEGFactory.createFromImage(document, tempImg); content.drawImage(ximage, 0, 0); content.close(); pages.put(getPageByName(image.getName()), page); } return pages; } catch (IOException e) { throw new RuntimeException(e); } } else { ImageIOToPDFRecursiveTask task1 = new ImageIOToPDFRecursiveTask(document, files.subList(0, ImageIOToPDFRecursiveTask.MAX_IMG), porcentage, isPlus); task1.fork(); ImageIOToPDFRecursiveTask task2 = new ImageIOToPDFRecursiveTask(document, files.subList(ImageIOToPDFRecursiveTask.MAX_IMG, files.size()), porcentage, isPlus); return combineList(task2.compute(), task1.join()); } } private <T> Map<Integer, T> combineList(Map<Integer, T> lst1, Map<Integer, T> lst2) { Map<Integer, T> lst = new HashMap<>(lst1); lst.putAll(lst2); return lst; } private Integer getPageByName(String name) { Matcher matcher = pattern.matcher(name); matcher.find(); String id = matcher.group().replaceAll("-", ""); return Integer.parseInt(id); } }
c342ff804215b0e8e821484ea76dede8e3f64b20
[ "Java" ]
2
Java
AColina/PDF-Utils
556ccf628e02c64784816d4b114099aac3deb79c
d93097035d96962cc31180e8a4df041e9c66e29e
refs/heads/master
<repo_name>exxxar/first-spring-project<file_sep>/target/classes/i18n/messages.properties page.login.title=Login page page.login.loginBtn=Log In page.login.regBtn=Registration page.login.forgot=Forgot a pass? page.login.label.username = Username page.login.label.password = <PASSWORD> page.login.name = My workShop local.en = English local.de = German messages.users.email = User's name is Empty! Change it messages.users.password = <PASSWORD>! messages.users.username = Bad username! MyEmpty.users.empty = This is empty field! <file_sep>/target/mavenproject6/resources/js/script.js $(document).ready(function(){ $('.get-userlist').click(function(){ $.get("../user/list",{},function(data){ $(".content-place").html(data); }); }); });<file_sep>/target/classes/i18n/messages_de.properties messages.users.email = User's name is Empty! Change itffffsssfdf messages.users.password = <PASSWORD>! messages.users.username = manamana MyEmpty.users.empty = This isfffff empty field! <file_sep>/src/main/java/com/web/mavenproject6/entities/Users.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.web.mavenproject6.entities; import com.mysql.jdbc.TimeUtil; import com.web.mavenproject6.validators.annotation.MyEmpty; import java.io.Serializable; import java.sql.Date; import java.util.Calendar; import javax.annotation.Resources; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Max; import javax.validation.constraints.NotNull; import javax.validation.groups.Default; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.validation.annotation.Validated; /** * * @author Aleks */ @Entity @Table(name="users") public class Users implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @NotEmpty @Length(max = 45) private String username; @MyEmpty @Length(max = 45) private String password; @NotNull private boolean enabled; private String email; private String name; private String address; private Date regDate; private Date lastOnlineDate; private Date deleteDate; public Users(long id, String username, String password, boolean enabled, String email, String name, String address, Date regDate, Date lastOnlineDate, Date deleteDate) { this.id = id; this.username = username; this.password = <PASSWORD>; this.enabled = enabled; this.email = email; this.name = name; this.address = address; this.regDate = regDate; this.lastOnlineDate = lastOnlineDate; this.deleteDate = deleteDate; } public Users() { this.username = ""; this.password = ""; this.enabled = true; this.email = ""; this.name = ""; this.address = ""; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getRegDate() { return regDate; } public void setRegDate(Date regDate) { this.regDate = regDate; } public Date getLastOnlineDate() { return lastOnlineDate; } public void setLastOnlineDate(Date lastOnlineDate) { this.lastOnlineDate = lastOnlineDate; } public Date getDeleteDate() { return deleteDate; } public void setDeleteDate(Date deleteDate) { this.deleteDate = deleteDate; } @Override public String toString() { return "Users{" + "id=" + id + ", username=" + username + ", password=" + <PASSWORD> + ", enabled=" + enabled + ", email=" + email + ", name=" + name + ", address=" + address + ", regDate=" + regDate + ", lastOnlineDate=" + lastOnlineDate + ", deleteDate=" + deleteDate + '}'; } }<file_sep>/src/main/resources/i18n/messages_en.properties messages.users.email = Ha ha ha lala loa messages.users.password = <PASSWORD> messages.users.username = trrr MyEmpty.users.empty = prrr <file_sep>/src/main/java/com/web/mavenproject6/controller/UserController.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.web.mavenproject6.controller; import com.web.mavenproject6.entities.Users; import com.web.mavenproject6.other.Mailer; import com.web.mavenproject6.service.UserServiceImp; import com.web.mavenproject6.validators.UsersValidator; import java.io.IOException; import java.util.Date; import java.util.Locale; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import javax.validation.Validator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.env.Environment; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.validation.ObjectError; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.util.List; /** * * @author Aleks */ @Controller public class UserController { @Autowired private Environment env; @Autowired UserServiceImp userServiceImp; @Autowired private UsersValidator usersValidator; @Autowired private Mailer mail; // @InitBinder // private void initBinder(WebDataBinder binder) { // binder.setValidator(usersValidator); // } @RequestMapping(value = "/signup") public ModelAndView signUpUser(HttpServletRequest request, HttpServletResponse response, Map<String, Object> model) { model.put("message", "Hello World"); model.put("title", "Hello Home"); model.put("date", new Date()); Users u = new Users(); u.setUsername("admin"); u.setPassword("<PASSWORD>"); userServiceImp.add(u); return new ModelAndView("thy/signup"); } @RequestMapping(value = "/admin/apanel", method = RequestMethod.GET) public String home(Map<String, Object> model, Locale locale) { model.put("users", userServiceImp.list()); model.put("user", new Users()); return "thy/adminPanel"; } @RequestMapping(value = "/redmine", method = RequestMethod.GET) public void redmine(Map<String, Object> model) { // String uri = "https://www.hostedredmine.com"; // String apiAccessKey = "<KEY>"; // String projectKey = "taskconnector-test"; // Integer queryId = null; // any // // RedmineManager mgr = RedmineManagerFactory.createWithApiKey(uri, apiAccessKey); // IssueManager issueManager = mgr.getIssueManager(); // List<Issue> issues = issueManager.getIssues(projectKey, queryId); // for (Issue issue : issues) { // System.out.println(issue.toString()); // } // // // Create issue // Issue issueToCreate = IssueFactory.createWithSubject("some subject"); // Issue createdIssue = issueManager.createIssue(projectKey, issueToCreate); // // // Get issue by ID: // Issue issue = issueManager.getIssueById(123); } @RequestMapping(value = "/mail", method = RequestMethod.GET) public String mail1(Map<String, Object> model, Locale locale) { mail.sendMail("<EMAIL>", "<EMAIL>", "Testing123", "Testing only \n\n Hello Spring Email Sender"); System.out.println("success send!"); return "thy/home"; } @RequestMapping(value = "/admin/apanel", method = RequestMethod.POST) public ModelAndView addUser(@ModelAttribute("user") @Valid Users user, BindingResult result, final RedirectAttributes redirectAttributes, Map<String, Object> model, Locale locale) { usersValidator.validate(user, result); if (result.hasErrors()) { model.put("users", userServiceImp.list()); return new ModelAndView("thy/adminPanel"); } ModelAndView mav = new ModelAndView(); userServiceImp.add(user); mav.setViewName("thy/adminPanel"); return mav; } @RequestMapping(value = "/user/del/{userId}") public void deleteUser(@PathVariable("userId") String id, HttpServletRequest request, HttpServletResponse response, ModelMap map) throws IOException { userServiceImp.delete((long) Integer.parseInt(id)); map.addAttribute("id", id); response.sendRedirect("/../admin/apanel"); // return "redirect:admin/apanel"; } }
5d9f7c35a559c6228f1179fa96cbc7fe32d90a2f
[ "JavaScript", "Java", "INI" ]
6
INI
exxxar/first-spring-project
894ac3af2ff642e4067daaea3012a8257f1f8d06
488282716f158485e9b08bf7e3528cec5dda8ec2
refs/heads/master
<repo_name>mallikarjungithub/jspractice<file_sep>/js/all.js var a = 3; var b = "3"; console.log(a == b); console.log(a === b); var a = 3 + 4 + "hai"; console.log(a); var b = "hai" + 3 + 4; console.log(b); var test = 3 + 5 + "hai" + 8; console.log(test); var time = new Date(); console.log(time.getTime()); var Year = new Date(); console.log(Year.getFullYear()); var task = new Date(); var month = ["jan", "feb", "mar", "apl", "may", "jun", "jly", "aug", "sep", "oct", "nov", "dec"]; console.log(month[task.getMonth("march")]); var d = new Date(); var d1 = ["1", "2", "3", "18"]; console.log(d1[d.getDate()]); var ab = 3; var cd = 5; console.log(ab + cd); console.log(ab - cd); console.log(ab * cd); console.log(ab/cd); console.log(ab%cd); for (i = 0; i < 101; i++) { console.log(i); } for (i = 0; i < 101; i++) { if (i % 2 == 0) { console.log("even" + i); } else { console.log("odd " + i); } } var x=3; var y=4; console.log(x**y); var m=4; var n=3; console.log(m-=n); var name=(" mallikarjun "); console.log(name.lenght); var result=name.trim(); console.log(result); console.log(result.lenght); var o=3; var p=4; console.log(o&&p); var employee=[{ name:"malli", age:"24", mail:"<EMAIL>", }, {name:"mahi", age:"24", mail:"<EMAIL>", } ] console.log(employee);
dca2180ed652b2d5b6a1a22062b41d6b60690a8c
[ "JavaScript" ]
1
JavaScript
mallikarjungithub/jspractice
89815644d6a02294e595908b854eaaf303225378
390bbe77dded4e624a5c2bedc5ac59947d778aea
refs/heads/master
<file_sep>package nazmul.materialsearchviewdemo; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.MatrixCursor; import android.provider.BaseColumns; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.CursorAdapter; import android.support.v4.widget.SimpleCursorAdapter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Toast; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private SimpleCursorAdapter myAdapter; SearchView searchView = null; private String[] strArrData = {"No Suggestions"}; ArrayList<String> dataList = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dataList.add("test"); dataList.add("toastt"); dataList.add("testing"); dataList.add("tested"); dataList.add("test"); strArrData = dataList.toArray(new String[dataList.size()]); final String[] from = new String[] {"fishName"}; final int[] to = new int[] {android.R.id.text1}; // setup SimpleCursorAdapter myAdapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.serach_menu, menu); // Get Search item from action bar and Get Search service MenuItem searchItem = menu.findItem(R.id.action_search); SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE); if (searchItem != null) { searchView = (SearchView) searchItem.getActionView(); } if (searchView != null) { searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName())); searchView.setSuggestionsAdapter(myAdapter); // Getting selected (clicked) item suggestion searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() { @Override public boolean onSuggestionClick(int position) { // Add clicked text to search box CursorAdapter ca = searchView.getSuggestionsAdapter(); Cursor cursor = ca.getCursor(); cursor.moveToPosition(position); searchView.setQuery(cursor.getString(cursor.getColumnIndex("fishName")),false); return true; } @Override public boolean onSuggestionSelect(int position) { return true; } }); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { return false; } @Override public boolean onQueryTextChange(String s) { // Filter data final MatrixCursor mc = new MatrixCursor(new String[]{ BaseColumns._ID, "fishName" }); for (int i=0; i<strArrData.length; i++) { if (strArrData[i].toLowerCase().startsWith(s.toLowerCase())) mc.addRow(new Object[] {i, strArrData[i]}); } myAdapter.changeCursor(mc); return false; } }); } return true; } @Override protected void onNewIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); if (searchView != null) { searchView.clearFocus(); } // User entered text and pressed search button. Perform task ex: fetching data from database and display } } }
486ead661dd1ac0c03026dd5804b4a16f09223c3
[ "Java" ]
1
Java
mdNazmulHasan/MaterialSearchViewDemo
ff559ccc4ba2a5bf191568148e1be29b301e021a
45df4a9dfe4589ef6ae54359f6dd71825d6f3e17
refs/heads/master
<repo_name>BigMike-Champ/Tech_Journal<file_sep>/SYS350/Milestone4/Menu.py import configparser import time import json from configparser import ConfigParser import ssl, getpass from pyVim.connect import SmartConnect, vim, Disconnect def menu(): print("[1] Read data from a file proof") print("[2] Data from current pyvmomi session") print("[3] Filter all VMs") print("[4] List All VM's") print("[5] List Vcenter Information") print("[7] Turn a VM [OFF]") print("[8] Turn a VM [ON]") print("[9] Make a snapshot") print("[10] Delete a VM") print("[11] Modify VM specs") print("[12] Rename a VM") print("[13] Exit the Program") def opt1(): with open('/home/champuser/Desktop/Tech_Journal/SYS350/Milestone4/config.json', 'r') as jsonfile: data = json.load(jsonfile) print(data) def opt2(): with open('/home/champuser/Desktop/Tech_Journal/SYS350/Milestone4/config.json', 'r') as jsonfile: data = json.load(jsonfile) passw = getpass.getpass() s=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) s.verify_mode=ssl.CERT_NONE vc = data["vcenter"] un = data["username"] si=SmartConnect(host=vc, user=un, pwd=passw, sslContext=s) for session in si.content.sessionManager.sessionList: if session.key == si.content.sessionManager.currentSession.key: print( "Current Domain and User={0.userName}, |" "IP Address={0.ipAddress} |".format(session), "Vcenter=", vc ) Disconnect(si) def opt3(): with open('/home/champuser/Desktop/Tech_Journal/SYS350/Milestone4/config.json', 'r') as jsonfile: data = json.load(jsonfile) passw = getpass.getpass() s=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) s.verify_mode=ssl.CERT_NONE vc = data["vcenter"] un = data["username"] si=SmartConnect(host=vc, user=un, pwd=<PASSWORD>, sslContext=s) si.RetrieveContent() datacenter = si.content.rootFolder.childEntity[0] vms = datacenter.vmFolder.childEntity vm_name=input("Enter a VM name: ") for i in vms: if vm_name in str(i.name): time.sleep(2) print(str(i.name) + "- It is there") print(i.guest.guestState + "- Powerstate") print(i.config.hardware.numCPU, "- CPUS") GB = (i.config.hardware.memoryMB/1024) print( GB , "- Memory in GB") print(i.summary.guest.ipAddress , "- IP") print("__________________") elif len(vm_name) == 0: opt4() Disconnect(si) def opt4(): with open('/home/champuser/Desktop/Tech_Journal/SYS350/Milestone4/config.json', 'r') as jsonfile: data = json.load(jsonfile) passw = <PASSWORD>() s=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) s.verify_mode=ssl.CERT_NONE vc = data["vcenter"] un = data["username"] si=SmartConnect(host=vc, user=un, pwd=<PASSWORD>, sslContext=s) si.RetrieveContent() datacenter = si.content.rootFolder.childEntity[0] vms = datacenter.vmFolder.childEntity for i in vms: time.sleep(5) print(str(i.name) + "- Name") print(i.guest.guestState + "- Powerstate") print(i.config.hardware.numCPU, "- CPUS") GB = (i.config.hardware.memoryMB/1024) print( GB , "- Memory in GB") print(i.summary.guest.ipAddress) print("__________________") Disconnect(si) def opt5(): with open('/home/champuser/Desktop/Tech_Journal/SYS350/Milestone4/config.json', 'r') as jsonfile: data = json.load(jsonfile) passw = getpass.getpass() s=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) s.verify_mode=ssl.CERT_NONE vc = data["vcenter"] un = data["username"] si=SmartConnect(host=vc, user=un, pwd=<PASSWORD>, sslContext=s) aboutInfo=si.content.about print("The Vcenter Info! from Milestone 2! ", aboutInfo) time.sleep(2) print(aboutInfo.osType) Disconnect(si) def opt7(): with open('/home/champuser/Desktop/Tech_Journal/SYS350/Milestone4/config.json', 'r') as jsonfile: data = json.load(jsonfile) passw = getpass.getpass() s=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) s.verify_mode=ssl.CERT_NONE vc = data["vcenter"] un = data["username"] si=SmartConnect(host=vc, user=un, pwd=<PASSWORD>, sslContext=s) si.RetrieveContent() datacenter = si.content.rootFolder.childEntity[0] vms = datacenter.vmFolder.childEntity vm_name=input("Enter a VM name: ") for i in vms: if vm_name == i.name: print("Turning the VM off!") i.PowerOff() time.sleep(5) Disconnect(si) def opt8(): #https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/vm_power_on.py with open('/home/champuser/Desktop/Tech_Journal/SYS350/Milestone4/config.json', 'r') as jsonfile: data = json.load(jsonfile) passw = getpass.getpass() s=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) s.verify_mode=ssl.CERT_NONE vc = data["vcenter"] un = data["username"] si=SmartConnect(host=vc, user=un, pwd=<PASSWORD>, sslContext=s) si.RetrieveContent() datacenter = si.content.rootFolder.childEntity[0] vms = datacenter.vmFolder.childEntity vm_name=input("Enter a VM name: ") for i in vms: if vm_name == i.name: print("Turning the VM on!") i.PowerOn() time.sleep(5) Disconnect(si) def opt9(): #https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/create_snapshot.py with open('/home/champuser/Desktop/Tech_Journal/SYS350/Milestone4/config.json', 'r') as jsonfile: data = json.load(jsonfile) passw = <PASSWORD>() s=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) s.verify_mode=ssl.CERT_NONE vc = data["vcenter"] un = data["username"] si=SmartConnect(host=vc, user=un, pwd=<PASSWORD>, sslContext=s) si.RetrieveContent() datacenter = si.content.rootFolder.childEntity[0] vms = datacenter.vmFolder.childEntity vm_name=input("Enter a VM name: ") s_Name=input("Enter what the snapshot should be named") descript=input("Please put in a description") for i in vms: if vm_name == i.name: i.CreateSnapshot_Task(name=s_Name, memory=True, quiesce=False) Disconnect(si) def opt10(): with open('/home/champuser/Desktop/Tech_Journal/SYS350/Milestone4/config.json', 'r') as jsonfile: data = json.load(jsonfile) passw = getpass.getpass() s=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) s.verify_mode=ssl.CERT_NONE vc = data["vcenter"] un = data["username"] si=SmartConnect(host=vc, user=un, pwd=<PASSWORD>, sslContext=s) si.RetrieveContent() datacenter = si.content.rootFolder.childEntity[0] vms = datacenter.vmFolder.childEntity #vm_name=input("Enter a VM name: ") name_c=input("Enter the name of the machine to be deleted: ") for i in vms: if name_c == i.name: i.PowerOff() time.sleep(10) print("Deleting the VM") i.Destroy_Task() time.sleep(10) Disconnect(si) 13 def opt11(): with open('/home/champuser/Desktop/Tech_Journal/SYS350/Milestone4/config.json', 'r') as jsonfile: data = json.load(jsonfile) passw = <PASSWORD>() s=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) s.verify_mode=ssl.CERT_NONE vc = data["vcenter"] un = data["username"] si=SmartConnect(host=vc, user=un, pwd=<PASSWORD>, sslContext=s) si.RetrieveContent() datacenter = si.content.rootFolder.childEntity[0] vms = datacenter.vmFolder.childEntity vm_name=input("Enter a VM name to reconfigure CPU for: ") for i in vms: if vm_name == i.name: print("You have chosen to reconfigure the CPU's. Powering the VM off.") i.PowerOff() print("Power is off Proceeding to reconfigure.") number = input("Input the number of CPU's you would like to set: ") time.sleep(2) core = input("Enter the number of Cores you would want: ") time.sleep(2) print("Configuring...") spec = vim.vm.ConfigSpec() spec.numCPUs=int(number) spec.numCoresPerSocket=int(core) i.Reconfigure(spec) print("VM CPU update complete") time.sleep(5) Disconnect(si) def opt12(): with open('/home/champuser/Desktop/Tech_Journal/SYS350/Milestone4/config.json', 'r') as jsonfile: data = json.load(jsonfile) passw = getpass.getpass() s=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) s.verify_mode=ssl.CERT_NONE vc = data["vcenter"] un = data["username"] si=SmartConnect(host=vc, user=un, pwd=passw, sslContext=s) si.RetrieveContent() datacenter = si.content.rootFolder.childEntity[0] vms = datacenter.vmFolder.childEntity vm_name=input("Enter a VM name: ") new_name=input("Please enter a name to change the VM name to: ") for i in vms: if vm_name == i.name: print("Renaming Now...") i.Rename(new_name) time.sleep(2) print("Name has been changed") time.sleep(2) Disconnect(si) menu() option = int(input("Enter your option: ")) while option !=0 : if option == 1: opt1() elif option == 2: opt2() elif option == 3: opt3() elif option == 4: opt4() elif option == 5: opt5() elif option == 6: menu2() elif option == 7: opt7() elif option == 8: opt8() elif option == 9: opt9() elif option == 10: opt10() elif option == 11: opt11() elif option == 12: opt12() elif option == 13: exit() else: print("Please input an option") menu() option = int(input("Enter your option: ")) <file_sep>/linux/centos7/secure-ssh.sh #secure-ssh.sh #author mike #creates a new ssh user using the $l parameter #adds a public key from the local repo or curled from the remote repo #removes roots ability to ssh in newuser=$1 useradd -m -d /home/$newuser -s /bin/bash $newuser sudo mkdir /home/$newuser/.ssh sudo cp /home/michaelu/Tech_Journal/linux/public-keys/id_rsa.pub /home/$newuser/.ssh/authorized_keys sudo chmod 700 /home/$newuser/.ssh sudo chmod 600 /home/$newuser/.ssh/authorized_keys sudo chown -R $newuser:$newuser /home/$newuser/.ssh
84db48213951aca6f8f2fdeb4d7e4f1135ff7052
[ "Python", "Shell" ]
2
Python
BigMike-Champ/Tech_Journal
33cedabbfae0970d20a543a81f0eb55355f6d591
5033f7dbaf44876e7a3c8a1d0e88aee2c294153a
refs/heads/main
<file_sep>#! /bin/bash # numbers.sh # <NAME> echo "Please Enter a Positive Integer:" read -r X N=1 while [ "$N" -le "$X" ] do if [ $(( N % 2 )) -eq 0 ]; then echo "The number $N is even." else echo "The number $N is odd." fi N=$((N+1)) done <file_sep>## Identifying Information: 1. Name: <NAME> 2. Student ID: 2379158 3. Email: <EMAIL> 4. Class: CPSC 298 - 03 5. Assignment: numbers ## Application Purpose A bash script named “numbers.sh” that will - prompt a user to type a positive integer - print all the numbers from 1 up to and including that number - print the word "odd" or "even" on the same line as each number ## Files 1. numbers.sh 2. numbers-input ## Known Errors ## References ## Instructions To run the script with input from the included numbers-input file: ./numbers.sh < numbers-input
4ca46a0e33185afd9284685dac5ba4ef4adbf924
[ "Markdown", "Shell" ]
2
Shell
ShanzehB/numbers
2040761958c964a91f21c2a19ed8d2221679d6ff
2ea6f0e8a94fd5ca1f43b927481e8e97449d25c0
refs/heads/main
<repo_name>Jaydenmay-040/Fibonacci<file_sep>/fibonacci.py # function using nth fibonacci def fibonacci(n): if n < 0: print("Incorrect input") # first fibonacci number is 0 elif n == 0: return 0 # second fibonacci is 1 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) for x in range(20): print(fibonacci(x), end = " ")
6c99c6600686fa716aaa2bc97a561118dca37ed1
[ "Python" ]
1
Python
Jaydenmay-040/Fibonacci
d96039856fe7e7cbd6928b8b2849f268417f56be
171e80c08e63ef11037a3a7cd91ec57a1b3ff58d
refs/heads/master
<file_sep># kubego [![GoDoc](https://godoc.org/github.com/autom8ter/kubego?status.svg)](https://godoc.org/github.com/autom8ter/kubego) a simple wrapper around the following kubernetes libraries: - kubernetes-client-go go get github.com/autom8ter/kubego/kube - istio-client-go go get github.com/autom8ter/kubego/istio - helm-client-go(v3) go get github.com/autom8ter/kubego/helm <file_sep>package helm_test import ( "github.com/autom8ter/kubego/helm" "testing" ) func TestHelm(t *testing.T) { h, err := helm.NewHelm() if err != nil { t.Fatal(err.Error()) } if err := h.AddRepo(helm.StableCharts); err != nil { t.Fatal(err) } results, err := h.AllCharts() if err != nil { t.Fatal(err.Error()) } if len(results) == 0 { t.Fatal("failed to load stable charts") } for _, r := range results { t.Log(r.Name) } releases, err := h.SearchReleases("hermes-admin", "", 5, 0) if err != nil { t.Fatal(err.Error()) } for _, r := range releases { t.Log(r.Name) } } <file_sep>module github.com/autom8ter/kubego go 1.15 require ( github.com/gophercloud/gophercloud v0.15.0 // indirect github.com/graphikDB/graphik v1.2.0 // indirect github.com/mitchellh/go-homedir v1.1.0 github.com/pkg/errors v0.9.1 helm.sh/helm/v3 v3.5.0 istio.io/client-go v0.0.0-20210115164403-c9e58f5c6252 k8s.io/api v0.20.1 k8s.io/client-go v0.20.1 k8s.io/klog v1.0.0 // indirect ) <file_sep>package kube import ( "context" "github.com/mitchellh/go-homedir" "github.com/pkg/errors" "io" corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" v1 "k8s.io/client-go/kubernetes/typed/apps/v1" v13 "k8s.io/client-go/kubernetes/typed/batch/v1" "k8s.io/client-go/kubernetes/typed/batch/v1beta1" v12 "k8s.io/client-go/kubernetes/typed/core/v1" v14 "k8s.io/client-go/kubernetes/typed/networking/v1" _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "path/filepath" ) // Kube is a kubernetes client type Kube struct { clientset *kubernetes.Clientset } // NewInClusterClient returns a client for use when inside the kubernetes cluster func NewInClusterKubeClient() (*Kube, error) { config, err := rest.InClusterConfig() if err != nil { return nil, errors.Wrap(err, "failed to get in cluster config") } clientset, err := kubernetes.NewForConfig(config) if err != nil { return nil, errors.Wrap(err, "failed to get in cluster k8s clientset") } return &Kube{ clientset: clientset, }, nil } // NewOutOfClusterClient returns a client for use when not inside the kubernetes cluster func NewOutOfClusterKubeClient() (*Kube, error) { dir, _ := homedir.Dir() kubeconfig := filepath.Join(dir, ".kube", "config") config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) if err != nil { return nil, errors.Wrap(err, "failed to get out of cluster config") } clientset, err := kubernetes.NewForConfig(config) if err != nil { return nil, errors.Wrap(err, "failed to get out of cluster k8s clientset") } return &Kube{ clientset: clientset, }, nil } // Pods returns an interface for managing k8s pods func (p *Kube) Pods(namespace string) v12.PodInterface { return p.clientset.CoreV1().Pods(namespace) } // Services returns an interface for managing k8s services func (p *Kube) Services(namespace string) v12.ServiceInterface { return p.clientset.CoreV1().Services(namespace) } // Namespaces returns an interface for managing k8s namespaces func (p *Kube) Namespaces() v12.NamespaceInterface { return p.clientset.CoreV1().Namespaces() } // ConfigMaps returns an interface for managing k8s config maps func (p *Kube) ConfigMaps(namespace string) v12.ConfigMapInterface { return p.clientset.CoreV1().ConfigMaps(namespace) } // Nodes returns an interface for managing k8s nodes func (p *Kube) Nodes() v12.NodeInterface { return p.clientset.CoreV1().Nodes() } // PersistentVolumeClaims returns an interface for managing k8s persistant volume claims func (p *Kube) PersistentVolumeClaims(namespace string) v12.PersistentVolumeClaimInterface { return p.clientset.CoreV1().PersistentVolumeClaims(namespace) } // PersistentVolumes returns an interface for managing k8s persistant volumes func (p *Kube) PersistentVolumes() v12.PersistentVolumeInterface { return p.clientset.CoreV1().PersistentVolumes() } // Secrets returns an interface for managing k8s secrets func (p *Kube) Secrets(namespace string) v12.SecretInterface { return p.clientset.CoreV1().Secrets(namespace) } // ServiceAccounts returns an interface for managing k8s service accounts func (p *Kube) ServiceAccounts(namespace string) v12.ServiceAccountInterface { return p.clientset.CoreV1().ServiceAccounts(namespace) } // Endpoints returns an interface for managing k8s endpoints func (p *Kube) Endpoints(namespace string) v12.EndpointsInterface { return p.clientset.CoreV1().Endpoints(namespace) } // Events returns an interface for managing k8s events func (p *Kube) Events(namespace string) v12.EventInterface { return p.clientset.CoreV1().Events(namespace) } // ResourceQuotas returns an interface for managing k8s resource quotas func (p *Kube) ResourceQuotas(namespace string) v12.ResourceQuotaInterface { return p.clientset.CoreV1().ResourceQuotas(namespace) } // StatefulSets returns an interface for managing k8s statefulsets func (p *Kube) StatefulSets(namespace string) v1.StatefulSetInterface { return p.clientset.AppsV1().StatefulSets(namespace) } // Deployments returns an interface for managing k8s deployments func (p *Kube) Deployments(namespace string) v1.DeploymentInterface { return p.clientset.AppsV1().Deployments(namespace) } // DaemonSets returns an interface for managing k8s daemonsets func (p *Kube) DaemonSets(namespace string) v1.DaemonSetInterface { return p.clientset.AppsV1().DaemonSets(namespace) } // ReplicaSets returns an interface for managing k8s replicasets func (p *Kube) ReplicaSets(namespace string) v1.ReplicaSetInterface { return p.clientset.AppsV1().ReplicaSets(namespace) } // Jobs returns an interface for managing k8s jobs func (p *Kube) Jobs(namespace string) v13.JobInterface { return p.clientset.BatchV1().Jobs(namespace) } // CronJobs returns an interface for managing k8s cronjobs func (p *Kube) CronJobs(namespace string) v1beta1.CronJobInterface { return p.clientset.BatchV1beta1().CronJobs(namespace) } // Ingresses returns an interface for managing k8s ingresses func (p *Kube) Ingresses(namespace string) v14.IngressInterface { return p.clientset.NetworkingV1().Ingresses(namespace) } // GetLogs returns a readerCloser that streams the pod's logs func (p *Kube) GetLogs(ctx context.Context, podName, namespace string, opts *corev1.PodLogOptions) (io.ReadCloser, error) { return p.Pods(namespace).GetLogs(podName, opts).Stream(ctx) } <file_sep>package helm import ( "fmt" "github.com/pkg/errors" "helm.sh/helm/v3/cmd/helm/search" "helm.sh/helm/v3/pkg/action" "helm.sh/helm/v3/pkg/chart" "helm.sh/helm/v3/pkg/chart/loader" "helm.sh/helm/v3/pkg/cli" "helm.sh/helm/v3/pkg/cli/values" "helm.sh/helm/v3/pkg/downloader" "helm.sh/helm/v3/pkg/getter" "helm.sh/helm/v3/pkg/helmpath" "helm.sh/helm/v3/pkg/release" "helm.sh/helm/v3/pkg/repo" "helm.sh/helm/v3/pkg/storage/driver" "os" "path/filepath" ) // StableCharts is a helm repo entry for the standard stable helm charts: https://charts.helm.sh/stable var StableCharts = &repo.Entry{ Name: "stable", URL: "https://charts.helm.sh/stable", } // Helm is a v3 helm client(wrapper) type Helm struct { env *cli.EnvSettings repo *repo.File logger func(format string, args ...interface{}) } // HelmOpt is an optional argument to modify the helm client type HelmOpt func(h *Helm) // WithLogger modifies default logger func WithLogger(logger func(format string, args ...interface{})) HelmOpt { return func(h *Helm) { h.logger = logger } } // WithEnvFunc modifies helm environmental settings func WithEnvFunc(fn func(settings *cli.EnvSettings)) HelmOpt { return func(h *Helm) { fn(h.env) } } // NewHelm creates a new v3 helm client(wrapper). func NewHelm(opts ...HelmOpt) (*Helm, error) { h := &Helm{ env: cli.New(), repo: &repo.File{}, logger: func(format string, args ...interface{}) { fmt.Printf(format, args...) }, } for _, o := range opts { o(h) } return h, nil } func (h *Helm) actionConfig(namespace string) (*action.Configuration, error) { actionConfig := new(action.Configuration) if namespace == "" { namespace = h.env.Namespace() } if err := actionConfig.Init(h.env.RESTClientGetter(), namespace, os.Getenv("HELM_DRIVER"), h.logger); err != nil { return nil, err } return actionConfig, nil } // Get gets a release by name func (h *Helm) Get(namespace string, name string) (*release.Release, error) { config, err := h.actionConfig(namespace) if err != nil { return nil, err } client := action.NewGet(config) return client.Run(name) } // Upgrade upgrades a chart in the cluster func (h *Helm) Upgrade(namespace string, chartName, releaseName string, recreate bool, configVals map[string]string) (*release.Release, error) { config, err := h.actionConfig(namespace) if err != nil { return nil, err } upgrade := action.NewUpgrade(config) if upgrade.Version == "" { upgrade.Version = ">0.0.0-0" } upgrade.Namespace = namespace upgrade.Recreate = recreate upgrade.Wait = true getters := getter.All(h.env) valueOpts := &values.Options{} vals, err := valueOpts.MergeValues(getters) if err != nil { return nil, err } for k, v := range configVals { vals[k] = v } chrt, _, err := h.getLocalChart(chartName, &upgrade.ChartPathOptions) if err != nil { return nil, err } if req := chrt.Metadata.Dependencies; req != nil { if err := action.CheckDependencies(chrt, req); err != nil { return nil, err } } return upgrade.Run(releaseName, chrt, vals) } // IsInstalled checks whether a release/chart is already installed on the cluster func (h *Helm) IsInstalled(namespace string, release string) (bool, error) { config, err := h.actionConfig(namespace) if err != nil { return false, err } histClient := action.NewHistory(config) histClient.Max = 1 if _, err := histClient.Run(release); err == driver.ErrReleaseNotFound { return false, nil } else if err != nil { return false, err } return true, nil } // Install a chart/release in the given namespace func (h *Helm) Install(namespace, chartName, releaseName string, createNamespace bool, configVals map[string]string) (*release.Release, error) { config, err := h.actionConfig(namespace) if err != nil { return nil, err } client := action.NewInstall(config) if client.Version == "" { client.Version = ">0.0.0-0" } client.Namespace = namespace client.CreateNamespace = createNamespace client.IncludeCRDs = true client.Wait = true client.ReleaseName = releaseName getters := getter.All(h.env) valueOpts := &values.Options{} vals, err := valueOpts.MergeValues(getters) if err != nil { return nil, err } for k, v := range configVals { vals[k] = v } chrt, cp, err := h.getLocalChart(chartName, &client.ChartPathOptions) if err != nil { return nil, err } if req := chrt.Metadata.Dependencies; req != nil { if err := action.CheckDependencies(chrt, req); err != nil { man := &downloader.Manager{ ChartPath: cp, Keyring: client.ChartPathOptions.Keyring, SkipUpdate: false, Getters: getters, RepositoryConfig: h.env.RepositoryConfig, RepositoryCache: h.env.RepositoryCache, } if err := man.Update(); err != nil { return nil, err } return nil, err } } return client.Run(chrt, vals) } // Uninstall uninstalls a release by name in the given namespace func (h *Helm) Uninstall(namespace, releaseName string) (*release.UninstallReleaseResponse, error) { config, err := h.actionConfig(namespace) if err != nil { return nil, err } client := action.NewUninstall(config) return client.Run(releaseName) } // History returns a history for the named release in the given namespace func (h *Helm) History(namespace string, release string, max int) ([]*release.Release, error) { config, err := h.actionConfig(namespace) if err != nil { return nil, err } histClient := action.NewHistory(config) histClient.Max = max return histClient.Run(release) } // Rollback rolls back the chart by name to the previous version func (h *Helm) Rollback(namespace string, release string) error { config, err := h.actionConfig(namespace) if err != nil { return err } client := action.NewRollback(config) client.Recreate = true return client.Run(release) } // Status executes 'helm status' against the given release. func (h *Helm) Status(namespace string, release string) (*release.Release, error) { config, err := h.actionConfig(namespace) if err != nil { return nil, err } client := action.NewStatus(config) client.ShowDescription = true return client.Run(release) } // SearchReleases searches for helm releases. If namespace is empty, all namespaces will be searched. func (h *Helm) SearchReleases(namespace, selector string, limit, offset int) ([]*release.Release, error) { config, err := h.actionConfig(namespace) if err != nil { return nil, err } client := action.NewList(config) client.StateMask = action.ListAll client.Limit = limit client.Selector = selector client.AllNamespaces = namespace == "" client.Offset = offset return client.Run() } // AddRepo adds or updates a helm repository func (h *Helm) AddRepo(entry *repo.Entry) error { r, err := repo.NewChartRepository(entry, getter.All(h.env)) if err != nil { return err } if _, err := r.DownloadIndexFile(); err != nil { return err } if h.repo.Has(entry.Name) { return nil } h.repo.Update(entry) return h.repo.WriteFile(h.env.RepositoryConfig, 0700) } // UpdateRepos updates all local helm repos func (h *Helm) UpdateRepos() error { repoFile := h.env.RepositoryConfig f, err := repo.LoadFile(repoFile) if err != nil { return err } for _, entry := range f.Repositories { r, err := repo.NewChartRepository(entry, getter.All(h.env)) if err != nil { return err } if _, err := r.DownloadIndexFile(); err != nil { return err } if h.repo.Has(entry.Name) { return nil } h.repo.Update(entry) } return h.repo.WriteFile(h.env.RepositoryConfig, 0700) } // SearchCharts searches for a cached helm chart. func (h *Helm) SearchCharts(term string, regex bool) ([]*search.Result, error) { repoFile := h.env.RepositoryConfig rf, err := repo.LoadFile(repoFile) if err != nil { return nil, err } i := search.NewIndex() for _, re := range rf.Repositories { f := filepath.Join(h.env.RepositoryCache, helmpath.CacheIndexFile(re.Name)) ind, err := repo.LoadIndexFile(f) if err != nil { if err := h.UpdateRepos(); err != nil { return nil, err } ind, _ = repo.LoadIndexFile(f) } if ind != nil { i.AddRepo(re.Name, ind, true) } } return i.Search(term, 25, regex) } // AllCharts returns all cached helm charts func (h *Helm) AllCharts() ([]*search.Result, error) { repoFile := h.env.RepositoryConfig rf, err := repo.LoadFile(repoFile) if err != nil { return nil, err } i := search.NewIndex() for _, re := range rf.Repositories { f := filepath.Join(h.env.RepositoryCache, helmpath.CacheIndexFile(re.Name)) ind, err := repo.LoadIndexFile(f) if err != nil { if err := h.UpdateRepos(); err != nil { return nil, err } ind, _ = repo.LoadIndexFile(f) } if ind != nil { i.AddRepo(re.Name, ind, true) } } return i.All(), nil } func (c *Helm) getLocalChart(chartName string, chartPathOptions *action.ChartPathOptions) (*chart.Chart, string, error) { chartPath, err := chartPathOptions.LocateChart(chartName, c.env) if err != nil { return nil, "", err } helmChart, err := loader.Load(chartPath) if err != nil { return nil, "", err } if helmChart.Metadata.Deprecated { return nil, "", errors.New("deprecated chart") } return helmChart, chartPath, err } <file_sep>package istio import ( "github.com/mitchellh/go-homedir" "github.com/pkg/errors" istio "istio.io/client-go/pkg/clientset/versioned" "istio.io/client-go/pkg/clientset/versioned/typed/networking/v1alpha3" "istio.io/client-go/pkg/clientset/versioned/typed/security/v1beta1" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "path/filepath" ) // Istio is an istio client type Istio struct { clientset *istio.Clientset } // NewInClusterClient returns a client for use when inside the kubernetes cluster func NewInClusterIstioClient() (*Istio, error) { config, err := rest.InClusterConfig() if err != nil { return nil, errors.Wrap(err, "failed to get in cluster config") } ic, err := istio.NewForConfig(config) if err != nil { return nil, errors.Wrap(err, "failed to get in cluster istio clientset") } return &Istio{ clientset: ic, }, nil } // NewOutOfClusterIstioClient returns an istio client for use when not inside the kubernetes cluster func NewOutOfClusterIstioClient() (*Istio, error) { dir, _ := homedir.Dir() kubeconfig := filepath.Join(dir, ".kube", "config") config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) if err != nil { return nil, errors.Wrap(err, "failed to get out of cluster config") } ic, err := istio.NewForConfig(config) if err != nil { return nil, errors.Wrap(err, "failed to get out of cluster istio clientset") } return &Istio{ clientset: ic, }, nil } // VirtualServices is a VirtualServices client. ref: https://istio.io/latest/docs/reference/config/networking/virtual-service/ func (c *Istio) VirtualServices(namespace string) v1alpha3.VirtualServiceInterface { return c.clientset.NetworkingV1alpha3().VirtualServices(namespace) } // Gateways is a Istio Gateways client. ref: https://istio.io/latest/docs/reference/config/networking/gateway/ func (c *Istio) Gateways(namespace string) v1alpha3.GatewayInterface { return c.clientset.NetworkingV1alpha3().Gateways(namespace) } // Istio WorkloadEntries client. ref: https://istio.io/latest/docs/reference/config/networking/workload-entry/ func (c *Istio) WorkloadEntries(namespace string) v1alpha3.WorkloadEntryInterface { return c.clientset.NetworkingV1alpha3().WorkloadEntries(namespace) } // Istio WorkloadGroups client. ref: https://istio.io/latest/docs/reference/config/networking/workload-group/ func (c *Istio) WorkloadGroups(namespace string) v1alpha3.WorkloadGroupInterface { return c.clientset.NetworkingV1alpha3().WorkloadGroups(namespace) } // Istio DestinationRules client. ref: https://istio.io/latest/docs/reference/config/networking/destination-rule/ func (c *Istio) DestinationRules(namespace string) v1alpha3.DestinationRuleInterface { return c.clientset.NetworkingV1alpha3().DestinationRules(namespace) } // Istio Sidecars client. ref: https://istio.io/latest/docs/reference/config/networking/sidecar/ func (c *Istio) Sidecars(namespace string) v1alpha3.SidecarInterface { return c.clientset.NetworkingV1alpha3().Sidecars(namespace) } // Istio EnvoyFilters client. ref: https://istio.io/latest/docs/reference/config/networking/envoy-filter/ func (c *Istio) EnvoyFilters(namespace string) v1alpha3.EnvoyFilterInterface { return c.clientset.NetworkingV1alpha3().EnvoyFilters(namespace) } // Istio Request Authentication client. ref: https://istio.io/latest/docs/reference/config/networking/service-entry/ func (c *Istio) ServiceEntries(namespace string) v1alpha3.ServiceEntryInterface { return c.clientset.NetworkingV1alpha3().ServiceEntries(namespace) } // Istio AuthorizationPolicies client. ref: https://istio.io/latest/docs/reference/config/security/authorization-policy/ func (c *Istio) AuthorizationPolicies(namespace string) v1beta1.AuthorizationPolicyInterface { return c.clientset.SecurityV1beta1().AuthorizationPolicies(namespace) } // Istio PeerAuthentications client. ref: https://istio.io/latest/docs/reference/config/security/peer_authentication/ func (c *Istio) PeerAuthentications(namespace string) v1beta1.PeerAuthenticationInterface { return c.clientset.SecurityV1beta1().PeerAuthentications(namespace) } // Istio Request Authentication client. ref: https://istio.io/latest/docs/reference/config/security/request_authentication/ func (c *Istio) RequestAuthentications(namespace string) v1beta1.RequestAuthenticationInterface { return c.clientset.SecurityV1beta1().RequestAuthentications(namespace) }
d850aca8311759b84c60a918f442a2535f8ca7c8
[ "Markdown", "Go Module", "Go" ]
6
Markdown
gitlayzer/kubego
4e765ca454332ef7ddfa0f9c3a8402e408345d25
6165c5e2add6eafeb862b7cb465664616993196c
refs/heads/master
<repo_name>010011100010/ll3305_CodeLab1_WK5HW<file_sep>/WK5HW/Assets/Script/LevelBuilder.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; using UnityEngine.SceneManagement; public class LevelBuilder : MonoBehaviour { public string[] fileNames; public static int levelNum = 0; public float offsetZ = -30; public float heightOffset = 30; public int offsetX = -50; //public float offsetY = 0; // Use this for initialization void Start () { } // Update is called once per frame void Update () { string fileName = fileNames[levelNum]; string filePath = Application.dataPath + "/" + fileName; int yPos = 0; int zPos = 0; if(Input.GetKeyDown(KeyCode.P)){ StreamReader sr = new StreamReader(filePath); GameObject levelHolder = new GameObject("Level Holder"); levelNum++; zPos++; //SceneManager.LoadScene("Scene1"); while (!sr.EndOfStream) { string line = sr.ReadLine (); for (int xPos = 0; xPos < line.Length; xPos++) { if (line [xPos] == 'x') { //GameObject cube = GameObject.CreatePrimitive (PrimitiveType.Cube); GameObject cube = Instantiate(Resources.Load("orangeCube") as GameObject); cube.transform.parent = levelHolder.transform; cube.transform.position = new Vector3 (xPos+offsetX, heightOffset, yPos+offsetZ); } } yPos--; } sr.Close (); } } }
6db135ce65d4f171b7bc15a20fc9400bbb0888b0
[ "C#" ]
1
C#
010011100010/ll3305_CodeLab1_WK5HW
95c43ff65bae165ab04cc1c4de4252026e3be00c
cd5718e5e85623c35f56f7506c6cc8339b157bae
refs/heads/master
<repo_name>irvinap/rails-app<file_sep>/app/models/blogpost.rb class Blogpost < ApplicationRecord belongs_to :user #can't create blogpost without logged in and title validates :user_id, presence: true validates :title, presence: true end
1a82db7c8dc888f976f48136993b364f52b5746c
[ "Ruby" ]
1
Ruby
irvinap/rails-app
5f1fb74ebe34bba713fb7777d9fabd047e69ef9c
851c577c473b8a0d0fa0bf375880a17681b421a3
refs/heads/master
<repo_name>veffhz/library-web-app<file_sep>/library-app/src/main/resources/static/js/components/authors/AuthorTr.js import { showAlert } from '../Utils.js' export default { name: 'AuthorTr', props: ['author', 'editAuthor'], template: ` <tr> <td>{{ author.id }}</td> <td>{{ author.fullName }}</td> <td> <input type="button" value="edit" @click="edit"> <input type="button" value="x" @click="del"/> </td> </tr> `, methods: { ...Vuex.mapActions('authorModule',['removeAuthor']), edit() { this.editAuthor(this.author); }, del() { this.removeAuthor(this.author) .then(result => { if (result.ok) { showAlert('#authorSuccess', '#authorAction', 'deleted'); }}, error => showAlert('#authorError', '#authorToAction', 'delete')); } } };<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/dao/CommentRepository.java package ru.otus.librarywebapp.dao; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import reactor.core.publisher.Flux; import ru.otus.domain.Comment; public interface CommentRepository extends ReactiveMongoRepository<Comment, String>, PageableFindAll<Comment> { Flux<Comment> findByBookId(String bookId); Flux<Comment> deleteByBookId(String bookId); } <file_sep>/library-app/src/main/resources/static/js/store/Store.js Vue.use(Vuex) import { authorModule } from './modules/Author.js' import { bookModule } from './modules/Book.js' import { commentModule } from './modules/Comment.js' import { genreModule } from './modules/Genre.js' export default new Vuex.Store({ state: {}, mutations: {}, actions: {}, modules: { authorModule, bookModule, commentModule, genreModule } })<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/dao/BookRepository.java package ru.otus.librarywebapp.dao; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import reactor.core.publisher.Flux; import ru.otus.domain.Book; public interface BookRepository extends ReactiveMongoRepository<Book, String>, PageableFindAll<Book> { Flux<Book> findByBookName(String bookName); Flux<Book> findByBookNameContaining(String bookName); Flux<Book> findByAuthorId(String authorId); Flux<Book> findByGenreId(String genreId); Flux<Book> deleteByAuthorId(String authorId); //TODO test Flux<Book> deleteByGenreId(String genreId); //TODO test } <file_sep>/library-app/src/main/resources/static/js/components/comments/CommentTable.js import CommentTr from './CommentTr.js' import CommentForm from './CommentForm.js' export default { name: 'CommentTable', computed: Vuex.mapState('commentModule', ['comments']), components: { CommentTr, CommentForm }, data: function() { return { comment: null } }, template: ` <div> <h1>Comments:</h1> <table class="items"> <thead> <tr> <th>id</th> <th>author</th> <th>date</th> <th>content</th> <th>book</th> <th></th> </tr> </thead> <tbody> <comment-tr v-for="comment in comments" :key="comment.id" :comment="comment" :editComment="editComment" /> </tbody> </table> <div class="gap-30"></div> <p>Edit:</p> <comment-form :commentAttr="comment" /> <div class="gap-30"></div> <div class="alert alert-danger" id="commentError" style="display:none;"> <strong>Error!</strong> Access Denied! You not have permission to <span id="commentToAction"></span> comment! </div> <div class="alert alert-success" id="commentSuccess" style="display:none;"> <strong>Success!</strong> Comment <span id="commentAction"></span> successfully. </div> </div> `, methods: { editComment(comment) { this.comment = comment; } } };<file_sep>/library-model/src/main/java/ru/otus/domain/Comment.java package ru.otus.domain; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; import javax.persistence.*; import javax.validation.constraints.NotBlank; import java.time.LocalDateTime; @Data @NoArgsConstructor @ToString(exclude = "book") @Document(collection = "comments") @Entity @Table(name = "comments") public class Comment { @Id @javax.persistence.Id @GeneratedValue(strategy = GenerationType.IDENTITY) private String id; @DBRef @ManyToOne @JoinColumn(name = "book_id") private Book book; @NotBlank private String author; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm") @CreatedDate private LocalDateTime date; @NotBlank private String content; public Comment(String author, LocalDateTime date, String content) { this.author = author; this.date = date; this.content = content; } } <file_sep>/library-batch/src/main/java/ru/otus/dao/jpa/BookJpaRepository.java package ru.otus.dao.jpa; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import ru.otus.domain.Book; import java.util.List; public interface BookJpaRepository extends JpaRepository<Book, String>, FindAllSupport { @EntityGraph("bookGraph") List<Book> findAll(); } <file_sep>/library-app/src/test/java/ru/otus/librarywebapp/rest/BookControllerTest.java package ru.otus.librarywebapp.rest; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.BodyInserters; import reactor.core.publisher.Mono; import ru.otus.domain.Author; import ru.otus.domain.Book; import ru.otus.domain.Genre; import ru.otus.dto.BookDto; import ru.otus.librarywebapp.service.BookService; import java.util.Collections; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; @DisplayName("Test for book api") @WebFluxTest(controllers = BookApi.class) @Import(BookApi.class) class BookControllerTest extends BaseTest { @MockBean private BookService bookService; @Test @DisplayName("Test get all books on /api/book") void shouldGetAllBooks() { given(this.bookService.getAll(BookApi.BOOK_PAGE_REQUEST)) .willReturn(Mono.just(new BookDto(Collections.singletonList(book()), 0, 1L))); String responseBody = "{\"books\":[{\"id\":null,\"author\":{\"id\":null,\"firstName\":null,\"birthDate\":null," + "\"lastName\":null,\"fullName\":\" \"},\"genre\":{\"id\":null,\"genreName\":null},\"bookName\":\"Best\"," + "\"publishDate\":\"2019-04-27\",\"language\":\"russian\",\"publishingHouse\":\"Test\",\"city\":\"Test\"," + "\"isbn\":\"555-555\"}],\"currentPage\":0,\"totalPages\":1}"; this.webClient.get().uri(uriBuilder -> uriBuilder .path("/api/book") .queryParam("page", 0) .build()) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo(responseBody); } @Test @DisplayName("Test get book on /api/book/{123}") void shouldGetBook() { given(this.bookService.getById("123")).willReturn(Mono.just(book())); String responseBody = "{\"id\":null,\"author\":{\"id\":null,\"firstName\":null,\"birthDate\":null,\"lastName\":null,\"fullName\":\" \"}," + "\"genre\":{\"id\":null,\"genreName\":null},\"bookName\":\"Best\",\"publishDate\":\"2019-04-27\",\"language\":\"russian\"," + "\"publishingHouse\":\"Test\",\"city\":\"Test\",\"isbn\":\"555-555\"}"; this.webClient.get().uri("/api/book/123") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo(responseBody); } @Test @DisplayName("Test update book on /api/book") void shouldUpdateBook() { Book book = book(); given(this.bookService.update(book)).willReturn(Mono.just(book())); String responseBody = "{\"id\":null,\"author\":{\"id\":null,\"firstName\":null,\"birthDate\":null,\"lastName\":null,\"fullName\":\" \"}," + "\"genre\":{\"id\":null,\"genreName\":null},\"bookName\":\"Best\",\"publishDate\":\"2019-04-27\",\"language\":\"russian\"," + "\"publishingHouse\":\"Test\",\"city\":\"Test\",\"isbn\":\"555-555\"}"; this.webClient .mutateWith(csrf()) .put().uri("/api/book") .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromObject(book)) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo(responseBody); verify(this.bookService, times(1)).update(any(Book.class)); } @Test @DisplayName("Test create book on post /api/book") void shouldCreateBook() { Book book = book(); given(this.bookService.insert(book)).willReturn(Mono.just(book)); String responseBody = "{\"id\":null,\"author\":{\"id\":null,\"firstName\":null,\"birthDate\":null,\"lastName\":null,\"fullName\":\" \"}," + "\"genre\":{\"id\":null,\"genreName\":null},\"bookName\":\"Best\",\"publishDate\":\"2019-04-27\",\"language\":\"russian\"," + "\"publishingHouse\":\"Test\",\"city\":\"Test\",\"isbn\":\"555-555\"}"; this.webClient .mutateWith(csrf()) .post().uri("/api/book") .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromObject(book)) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isCreated() .expectBody(String.class).isEqualTo(responseBody); verify(this.bookService, times(1)).insert(any(Book.class)); } @Test @DisplayName("Test delete book on /api/book/{id}") void shouldDeleteBookById() { given(this.bookService.deleteById("123")).willReturn(Mono.empty()); this.webClient .mutateWith(csrf()) .delete().uri("/api/book/123") .exchange() .expectStatus().isNoContent(); verify(this.bookService, times(1)).deleteById("123"); } private Book book() { return new Book(new Author(), new Genre(), "Best", date(), "russian", "Test", "Test", "555-555"); } }<file_sep>/library-batch/src/main/java/ru/otus/dao/jpa/GenreJpaRepository.java package ru.otus.dao.jpa; import org.springframework.data.jpa.repository.JpaRepository; import ru.otus.domain.Genre; import java.util.List; import java.util.Optional; public interface GenreJpaRepository extends JpaRepository<Genre, String>, FindAllSupport { List<Genre> findAll(); Optional<Genre> findOneByGenreName(String genreName); } <file_sep>/library-batch/src/main/java/ru/otus/config/mongo/entity/AuthorBatchConfig.java package ru.otus.config.mongo.entity; import lombok.extern.slf4j.Slf4j; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.data.MongoItemWriter; import org.springframework.batch.item.data.RepositoryItemReader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import ru.otus.dao.jpa.AuthorJpaRepository; import ru.otus.domain.Author; import java.util.Collections; @Slf4j @Configuration public class AuthorBatchConfig { private final StepBuilderFactory stepBuilderFactory; private final AuthorJpaRepository authorRepository; @Autowired public AuthorBatchConfig(StepBuilderFactory stepBuilderFactory, AuthorJpaRepository authorRepository) { this.stepBuilderFactory = stepBuilderFactory; this.authorRepository = authorRepository; } @Bean(name = "authorReader") public RepositoryItemReader<Author> authorReader() { RepositoryItemReader<Author> reader = new RepositoryItemReader<>(); reader.setRepository(authorRepository); reader.setMethodName(authorRepository.FIND_ALL_METHOD); reader.setSort(Collections.singletonMap("id", Sort.Direction.ASC)); reader.setPageSize(10000); return reader; } @Bean(name = "authorWriter") public MongoItemWriter<Author> authorWriter(MongoTemplate mongoTemplate) { MongoItemWriter<Author> writer = new MongoItemWriter<>(); writer.setTemplate(mongoTemplate); writer.setCollection("authors"); return writer; } @Bean(name = "authorProcessor") public ItemProcessor<Author, Author> authorProcessor() { return author -> { log.info("Migrate {}", author); return new Author(author.getFirstName(), author.getBirthDate(), author.getLastName()); }; } @Bean public Step authorJpaToMongoStep(MongoTemplate mongoTemplate) { return stepBuilderFactory.get("authorJpaToMongoStep") .<Author, Author> chunk(10) .reader(authorReader()) .processor(authorProcessor()) .writer(authorWriter(mongoTemplate)) .build(); } } <file_sep>/library-batch/src/main/resources/data.sql insert into authors (id, first_name, birth_date, last_name) values (1, 'n/a', '1900-01-01', 'n/a'); <file_sep>/library-app/src/test/java/ru/otus/librarywebapp/impl/GenreServiceImplTest.java package ru.otus.librarywebapp.impl; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import ru.otus.domain.Author; import ru.otus.domain.Book; import ru.otus.domain.Genre; import ru.otus.librarywebapp.dao.GenreRepository; import ru.otus.librarywebapp.service.BookService; import ru.otus.librarywebapp.service.impl.GenreServiceImpl; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; @DisplayName("Test for Genre Service") @ExtendWith(SpringExtension.class) class GenreServiceImplTest { @SpyBean private GenreServiceImpl genreService; @MockBean private GenreRepository genreRepository; @MockBean private BookService bookService; @Test @DisplayName("Test invoke get genre by id") void shouldGetGenreById() { Mono<Genre> genreMock = Mono.just(new Genre("test")); when(genreRepository.findById(any(String.class))).thenReturn(genreMock); Mono<Genre> genre = genreService.getById("000"); verify(genreRepository, times(1)).findById("000"); assertEquals(genreMock, genre); } @Test @DisplayName("Test invoke get all genres") void shouldGetAllGenres() { genreService.getAll(); verify(genreRepository, times(1)).findAll(); } @Test @DisplayName("Test invoke delete genre by id") void shouldDeleteGenreById() { Book book = new Book(new Author("", null, ""), new Genre(""), "Book", LocalDate.now(), "russian", "Test", "Test", "555-555"); when(bookService.deleteByGenreId(any(String.class))).thenReturn(Flux.just(book)); when(genreRepository.deleteById(any(String.class))).thenReturn(Mono.empty()); genreService.deleteById("000"); verify(genreRepository, times(1)).deleteById("000"); verify(bookService, times(1)).deleteByGenreId(any(String.class)); } @Test @DisplayName("Test invoke insert new genre") void shouldInsertNewGenre() { Genre genre = new Genre("test"); genreService.insert(genre); verify(genreRepository, times(1)).insert(genre); } }<file_sep>/library-model/src/main/java/ru/otus/dto/GenreDto.java package ru.otus.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import ru.otus.domain.Genre; import java.util.List; @Getter @Setter @AllArgsConstructor public class GenreDto { private List<Genre> genres; } <file_sep>/library-app/src/main/resources/static/js/store/modules/Genre.js Vue.use(Vuex) export const genreModule = { namespaced: true, state: { ...frontendData.genreDto }, mutations: { addGenreMutation(state, genre) { state.genres = [...state.genres, genre] }, updateGenreMutation(state, genre) { var indexUpdated = state.genres.findIndex(item => item.id === genre.id); state.genres = [ ...state.genres.slice(0, indexUpdated), genre, ...state.genres.slice(indexUpdated + 1) ] }, removeGenreMutation(state, genre) { var indexDeleted = state.genres.findIndex(item => item.id === genre.id); if (indexDeleted > -1) { state.genres = [ ...state.genres.slice(0, indexDeleted), ...state.genres.slice(indexDeleted + 1) ] } } }, actions: { async addGenre({commit, state}, genre) { const result = await Vue.resource('/api/genre{/id}').save({}, genre); const data = await result.json(); if (result.ok) { commit('addGenreMutation', data); } return result; }, async updateGenre({commit}, genre) { const result = await Vue.resource('/api/genre{/id}').update({}, genre) const data = await result.json() if (result.ok) { commit('updateGenreMutation', data); } return result; }, async removeGenre({dispatch, commit}, genre) { const result = await Vue.resource('/api/genre{/id}').remove({id: genre.id}) if (result.ok) { commit('removeGenreMutation', genre); dispatch('bookModule/removeBookByGenreId', genre.id, { root: true }); } return result; }, } }<file_sep>/library-app/src/test/java/ru/otus/librarywebapp/rest/BaseTest.java package ru.otus.librarywebapp.rest; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.WebTestClient; import ru.otus.librarywebapp.utils.Helper; import java.time.LocalDate; import java.time.LocalDateTime; @WithMockUser(username = "usr", authorities = "ROLE_USER") class BaseTest { private static final String DATE = "2019-04-27"; @Autowired WebTestClient webClient; @Autowired private ObjectMapper mapper; LocalDate date() { return mapper.convertValue(DATE, LocalDate.class); } LocalDateTime dateTime() { return Helper.toLocalDateTime(DATE); } } <file_sep>/library-app/src/main/resources/static/js/components/authors/AuthorTable.js import AuthorTr from './AuthorTr.js' import AuthorForm from './AuthorForm.js' export default { name: 'AuthorTable', computed: Vuex.mapState('authorModule', ['authors']), components: { AuthorTr, AuthorForm }, data: function() { return { author: null } }, template: ` <div> <h1>Authors:</h1> <table class="items"> <thead> <tr> <th>Id</th> <th>fullName</th> <th></th> </tr> </thead> <tbody> <author-tr v-for="author in authors" :key="author.id" :author="author" :editAuthor="editAuthor" /> </tbody> </table> <div class="gap-30"></div> <p>Edit:</p> <author-form :authorAttr="author" /> <div class="gap-30"></div> <div class="alert alert-danger" id="authorError" style="display:none;"> <strong>Error!</strong> Access Denied! You not have permission to <span id="authorToAction"></span> author! </div> <div class="alert alert-success" id="authorSuccess" style="display:none;"> <strong>Success!</strong> Author <span id="authorAction"></span> successfully. </div> </div> `, methods: { editAuthor(author) { this.author = author; } } };<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/integration/IntegrationService.java package ru.otus.librarywebapp.integration; import org.springframework.integration.annotation.Gateway; import org.springframework.integration.annotation.MessagingGateway; import ru.otus.domain.Book; import java.util.List; @MessagingGateway public interface IntegrationService { @Gateway(requestChannel = "bookInChannel", replyChannel = "storeChannel") void process(List<Book> book); } <file_sep>/library-app/src/main/resources/static/js/pages/Comment.js import CommentTable from '../components/comments/CommentTable.js' export default { name: 'Comment', components: { CommentTable }, template: '<comment-table />' };<file_sep>/library-app/src/test/java/ru/otus/librarywebapp/domain/GenreTest.java package ru.otus.librarywebapp.domain; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.test.context.junit.jupiter.SpringExtension; import ru.otus.domain.Genre; import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(SpringExtension.class) @DataMongoTest class GenreTest { @Autowired private MongoTemplate mongoTemplate; @Test public void saveAndGet() { Genre genre = new Genre("Genre"); mongoTemplate.insert(genre, "genres"); Genre genreFromDb = mongoTemplate.findById(genre.getId(), Genre.class,"genres"); assertEquals(genre, genreFromDb); } }<file_sep>/library-app/src/main/resources/static/js/components/Utils.js export function showAlert(divId, spanId, spanText) { $(spanId).text(spanText); $(divId).fadeIn(1000); setTimeout(function() { $(divId).fadeOut(1000); }, 2000); }<file_sep>/library-app/src/main/resources/static/js/components/authors/AuthorForm.js import { showAlert } from '../Utils.js' export default { name: 'AuthorForm', props: ['authorAttr'], data: function() { return { firstName: '', lastName: '', birthDate: '', id: null } }, watch: { authorAttr: function(newVal, oldVal) { this.firstName = newVal.firstName; this.birthDate = newVal.birthDate; this.lastName = newVal.lastName; this.id = newVal.id; } }, template: ` <div class="block"> <form onsubmit="return false"> <input type="text" placeholder="<NAME>" v-model="firstName" required="required"> <p/> <input type="date" v-model="birthDate" required="required"> <p/> <input type="text" placeholder="<NAME>" v-model="lastName" required="required"> <p/> <input type="reset" value="Clean"> <input type="submit" value="Save" @click="save"> </form> </div> `, methods: { ...Vuex.mapActions('authorModule', ['addAuthor', 'updateAuthor']), save: function() { var inputs = document.getElementsByTagName('input'); for (var index = 0; index < inputs.length; ++index) { if (!inputs[index].checkValidity()) { return; } } var author = { id: this.id, firstName: this.firstName, birthDate: this.birthDate, lastName: this.lastName }; if (this.id) { this.updateAuthor(author).then(result => { if (result.ok) { showAlert('#authorSuccess', '#authorAction', 'updated'); }}, error => showAlert('#authorError', '#authorToAction', 'update')); } else { this.addAuthor(author).then(result => { if (result.ok) { showAlert('#authorSuccess', '#authorAction', 'created'); }}, error => showAlert('#authorError', '#authorToAction', 'create')); } this.firstName = ''; this.birthDate = ''; this.lastName = ''; this.id = null; } } };<file_sep>/library-app/src/test/java/ru/otus/librarywebapp/dao/GenreRepositoryTest.java package ru.otus.librarywebapp.dao; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; import org.springframework.context.annotation.ComponentScan; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import ru.otus.domain.Genre; import java.util.Objects; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @DisplayName("Test for GenreRepository") @DataMongoTest @ComponentScan({"ru.otus.librarywebapp.dao", "ru.otus.librarywebapp.testconfig"}) class GenreRepositoryTest { @Autowired private GenreRepository genreRepository; @Test @DisplayName("Test return count genres") void shouldReturnCorrectCount() { Mono<Long> count = genreRepository.count(); StepVerifier .create(count) .assertNext(c -> assertEquals(c.longValue(), 2)) .expectComplete() .verify(); } @Test @DisplayName("Test insert new genre") void shouldInsertNewGenre() { Genre genre = new Genre("test"); StepVerifier .create(genreRepository.save(genre)) .assertNext(g -> assertNotNull(g.getId())) .expectComplete() .verify(); } @Test @DisplayName("Test get genre by id") void shouldGetGenreById() { Mono<Genre> genre = genreRepository.findAll().elementAt(0); StepVerifier .create(genre) .assertNext(g -> assertEquals(g.getGenreName(), "Genre")) .expectComplete() .verify(); } @Test @DisplayName("Test get all genre") void shouldGetAllGenres() { Flux<Genre> genres = genreRepository.findAll(); StepVerifier .create(genres) .assertNext(g -> assertEquals(g.getGenreName(), "Genre7")) .assertNext(g -> assertEquals(g.getGenreName(), "Genre9")) .expectComplete() .verify(); } @Test @DisplayName("Test delete genre by id") void shouldDeleteGenreById() { Genre genre = genreRepository.findAll().blockFirst(); Objects.requireNonNull(genre); StepVerifier.create(genreRepository.deleteById(genre.getId())) .verifyComplete(); } @Test @DisplayName("Test delete genre") void shouldDeleteGenre() { Genre genre = genreRepository.findAll().blockFirst(); Objects.requireNonNull(genre); StepVerifier.create(genreRepository.delete(genre)) .verifyComplete(); } }<file_sep>/library-model/src/main/java/ru/otus/domain/User.java package ru.otus.domain; import lombok.Data; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import javax.validation.constraints.NotBlank; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; @Data @Document(collection = "users") public class User implements UserDetails { @Id private String id; @NotBlank private String username; @NotBlank private String password; private boolean active; @DBRef private List<Role> roles; @CreatedDate private LocalDateTime createdDate; @LastModifiedDate private LocalDateTime modifiedDate; public User() { this.roles = new ArrayList<>(); this.createdDate = LocalDateTime.now(); } @Override public boolean isAccountNonExpired() { return active; } @Override public boolean isAccountNonLocked() { return active; } @Override public boolean isCredentialsNonExpired() { return active; } @Override public boolean isEnabled() { return active; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return this.roles.stream() .map(authority -> new SimpleGrantedAuthority(authority.getRoleName())) .collect(Collectors.toList()); } } <file_sep>/library-app/src/main/java/ru/otus/librarywebapp/dao/AuthorRepository.java package ru.otus.librarywebapp.dao; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import reactor.core.publisher.Flux; import ru.otus.domain.Author; public interface AuthorRepository extends ReactiveMongoRepository<Author, String>, PageableFindAll<Author> { Flux<Author> findByLastName(String lastName); } <file_sep>/library-app/src/test/java/ru/otus/librarywebapp/rest/Application.java package ru.otus.librarywebapp.rest; import org.springframework.boot.SpringBootConfiguration; @SpringBootConfiguration public class Application { } <file_sep>/library-app/src/test/java/ru/otus/librarywebapp/rest/GenreControllerTest.java package ru.otus.librarywebapp.rest; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.BodyInserters; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import ru.otus.domain.Genre; import ru.otus.librarywebapp.service.GenreService; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; @DisplayName("Test for genre api") @WebFluxTest(controllers = GenreApi.class) @Import(GenreApi.class) class GenreControllerTest extends BaseTest { @MockBean private GenreService genreService; @Test @DisplayName("Test get genres on /api/genre") void shouldGetAllGenres() { given(this.genreService.getAll()).willReturn(Flux.just(genre(), genre())); String responseBody = "[{\"id\":null,\"genreName\":\"test\"},{\"id\":null,\"genreName\":\"test\"}]"; this.webClient.get().uri("/api/genre") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo(responseBody); } @Test @DisplayName("Test get genre on /api/genre/{id}") void shouldGetGenre() { given(this.genreService.getById("123")).willReturn(Mono.just(genre())); String responseBody = "{\"id\":null,\"genreName\":\"test\"}"; this.webClient.get().uri("/api/genre/123") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo(responseBody); } @Test @DisplayName("Test update genre on /api/genre") void shouldUpdateGenre() { Genre genre = genre(); given(this.genreService.update(genre)).willReturn(Mono.just(genre())); String responseBody = "{\"id\":null,\"genreName\":\"test\"}"; this.webClient .mutateWith(csrf()) .put().uri("/api/genre") .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromObject(genre)) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo(responseBody); verify(this.genreService, times(1)).update(any(Genre.class)); } @Test @DisplayName("Test create genre on post /api/genre") void shouldCreateGenre() { Genre genre = genre(); given(this.genreService.insert(genre)).willReturn(Mono.just(genre())); String responseBody = "{\"id\":null,\"genreName\":\"test\"}"; this.webClient .mutateWith(csrf()) .post().uri("/api/genre") .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromObject(genre)) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isCreated() .expectBody(String.class).isEqualTo(responseBody); verify(this.genreService, times(1)).insert(any(Genre.class)); } @Test @DisplayName("Test delete genre on /api/genre/{id}") void shouldDeleteGenreById() { given(this.genreService.deleteById("123")).willReturn(Mono.empty()); this.webClient .mutateWith(csrf()) .delete().uri("/api/genre/123") .exchange() .expectStatus().isNoContent(); verify(this.genreService, times(1)).deleteById("123"); } private Genre genre() { return new Genre("test"); } }<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/endpoints/Link.java package ru.otus.librarywebapp.endpoints; import lombok.Getter; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public class Link { @Getter private final String href; @Getter private boolean templated; } <file_sep>/library-app/src/main/resources/static/js/store/modules/Comment.js Vue.use(Vuex) export const commentModule = { namespaced: true, state: { ...frontendData.commentDto }, mutations: { addCommentMutation(state, comment) { state.comments = [...state.comments, comment] }, updateCommentMutation(state, comment) { var indexUpdated = state.comments.findIndex(item => item.id === comment.id); state.comments = [ ...state.comments.slice(0, indexUpdated), comment, ...state.comments.slice(indexUpdated + 1) ] }, removeCommentMutation(state, comment) { var indexDeleted = state.comments.findIndex(item => item.id === comment.id); if (indexDeleted > -1) { state.comments = [ ...state.comments.slice(0, indexDeleted), ...state.comments.slice(indexDeleted + 1) ] } }, removeCommentByBookIdMutation(state, bookId) { if (bookId) { var comments = state.comments.filter(comment => bookId != comment.book.id); state.comments = comments; } } }, actions: { async addComment({commit, state}, comment) { const result = await Vue.resource('/api/comment{/id}').save({}, comment); const data = await result.json(); if (result.ok) { commit('addCommentMutation', data); } return result; }, async updateComment({commit}, comment) { const result = await Vue.resource('/api/comment{/id}').update({}, comment) const data = await result.json() if (result.ok) { commit('updateCommentMutation', data); } return result; }, async removeComment({commit}, comment) { const result = await Vue.resource('/api/comment{/id}').remove({id: comment.id}) if (result.ok) { commit('removeCommentMutation', comment); } return result; }, } }<file_sep>/library-model/src/main/java/ru/otus/dto/LibraryDto.java package ru.otus.dto; import lombok.*; @Data @NoArgsConstructor @AllArgsConstructor public class LibraryDto { private String bookName; private String author; private String year; private String genre; private String isbn; } <file_sep>/library-model/src/main/java/ru/otus/dto/LibraryItem.java package ru.otus.dto; import lombok.Data; import lombok.NoArgsConstructor; import ru.otus.domain.Author; import ru.otus.domain.Book; import ru.otus.domain.Genre; @Data @NoArgsConstructor public class LibraryItem { private Author author; private Genre genre; private Book book; public LibraryItem withAuthor(Author author) { this.author = author; return this; } public LibraryItem withGenre(Genre genre) { this.genre = genre; return this; } public LibraryItem withBook(Book book) { this.book = book; return this; } } <file_sep>/library-app/pom.xml <?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>library-web-app</artifactId> <groupId>ru.otus</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>library-app</artifactId> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-integration</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> <version>5.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mongodb</artifactId> <version>5.1.6.RELEASE</version> </dependency> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.12.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>ru.otus</groupId> <artifactId>library-model</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-junit-jupiter</artifactId> <version>${mockito.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>io.projectreactor</groupId> <artifactId>reactor-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>de.flapdoodle.embed</groupId> <artifactId>de.flapdoodle.embed.mongo</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.github.mongobee</groupId> <artifactId>mongobee</artifactId> <version>${mongobee.version}</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>vue</artifactId> <version>${vue.version}</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>bootstrap</artifactId> <version>3.3.6</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>vue-resource</artifactId> <version>0.9.3</version> </dependency> <dependency> <groupId>org.webjars.bower</groupId> <artifactId>vue-router</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.webjars.npm</groupId> <artifactId>vuex</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>1.12.4</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-locator</artifactId> <version>0.32</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>3.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>3.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-spring-webflux</artifactId> <version>3.0.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <finalName>${artifactId}</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <skip>false</skip> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>jcenter-snapshots</id> <name>jcenter</name> <url>http://oss.jfrog.org/artifactory/oss-snapshot-local/</url> </repository> </repositories> </project><file_sep>/library-app/src/main/resources/static/js/components/books/BookTr.js import { showAlert } from '../Utils.js' export default { name: 'BookTr', props: ['book', 'editBook'], template: ` <tr> <td>{{ book.id }}</td> <td>{{ book.bookName }}</td> <td>{{ book.publishDate }}</td> <td>{{ book.language }}</td> <td>{{ book.publishingHouse }}</td> <td>{{ book.city }}</td> <td>{{ book.isbn }}</td> <td v-if="book.author != null">{{ book.author.fullName }}</td> <td class="gray" v-else>Not found!</td> <td v-if="book.genre != null">{{ book.genre.genreName }}</td> <td class="gray" v-else>Not found!</td> <td> <input type="button" value="edit" @click="edit"> <input type="button" value="x" @click="del"/> </td> </tr> `, methods: { ...Vuex.mapActions('bookModule',['removeBook']), edit() { this.editBook(this.book); }, del() { this.removeBook(this.book) .then(result => { if (result.ok) { showAlert('#bookSuccess', '#bookAction', 'deleted'); }}, error => showAlert('#bookError', '#bookToAction', 'delete')); } } };<file_sep>/library-app/src/main/resources/static/js/components/comments/CommentForm.js import { showAlert } from '../Utils.js' export default { name: 'CommentForm', computed: Vuex.mapState('bookModule', ['books']), props: ['commentAttr'], data: function() { return { author: '', content: '', book: '', id: null } }, watch: { commentAttr: function(newVal, oldVal) { this.author = newVal.author; this.date = newVal.date; this.content = newVal.content; this.book = newVal.book; this.id = newVal.id; } }, template: ` <div class="block"> <form onsubmit="return false"> <input type="text" placeholder="Author" v-model="author" required="required"> <p/> <input type="text" placeholder="Content" v-model="content" required="required"> <p/> <select v-model="book" required="required"> <option disabled value="">---</option> <option v-for="book in books" v-bind:value="book">{{ book.bookName }}</option> </select> <p/> <input type="reset" value="Clean"> <input type="submit" value="Save" @click="save"> </form> </div> `, methods: { ...Vuex.mapActions('commentModule', ['addComment', 'updateComment']), save: function() { var inputs = document.getElementsByTagName('input'); for (var index = 0; index < inputs.length; ++index) { if (!inputs[index].checkValidity()) { return; } } var comment = { id: this.id, author: this.author, date: this.date, content: this.content, book: this.book }; if (this.id) { this.updateComment(comment).then(result => { if (result.ok) { showAlert('#commentSuccess', '#commentAction', 'updated'); }}, error => showAlert('#commentError', '#commentToAction', 'update')); } else { this.addComment(comment).then(result => { if (result.ok) { showAlert('#commentSuccess', '#commentAction', 'created'); }}, error => showAlert('#commentError', '#commentToAction', 'create')); } this.author = ''; this.content = ''; this.book = ''; this.id = null; } } };<file_sep>/library-app/src/test/java/ru/otus/librarywebapp/rest/UserControllerTest.java package ru.otus.librarywebapp.rest; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.BodyInserters; import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; @DisplayName("Test for user api") @WebFluxTest(controllers = UserApi.class) @Import(UserApi.class) class UserControllerTest extends BaseTest { @Test @DisplayName("Test get on /api/user") void shouldGetUser() { String responseBody = "[\"usr\",null,{\"password\":\"<PASSWORD>\",\"username\":\"usr\"," + "\"authorities\":[{\"authority\":\"ROLE_USER\"}],\"accountNonExpired\":true,\"accountNonLocked\":true," + "\"credentialsNonExpired\":true,\"enabled\":true},[{\"authority\":\"ROLE_USER\"}]]"; this.webClient.get().uri("/api/user") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo(responseBody); } @Test @DisplayName("Test post on /api/user") void shouldPostUser() { String responseBody = "[\"usr\",[{\"authority\":\"ROLE_USER\"}],\"Test\"]"; this.webClient .mutateWith(csrf()) .post().uri("/api/user") .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromObject("Test")) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isCreated() .expectBody(String.class).isEqualTo(responseBody); } }<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/service/GenreService.java package ru.otus.librarywebapp.service; import org.springframework.data.domain.Pageable; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import ru.otus.domain.Genre; import ru.otus.dto.GenreDto; public interface GenreService { Mono<Long> count(); Mono<Genre> getById(String id); Flux<Genre> getByGenreName(String genreName); Flux<Genre> getAll(); Mono<GenreDto> getAll(Pageable pageable); Mono<Void> deleteById(String id); Mono<Genre> insert(Genre genre); Mono<Genre> update(Genre genre); } <file_sep>/library-app/src/main/resources/static/js/pages/Home.js export default { name: 'Home', computed: { ...Vuex.mapState('authorModule', ['authors']), ...Vuex.mapState('bookModule', ['books']), ...Vuex.mapState('commentModule', ['comments']), ...Vuex.mapState('genreModule', ['genres']) }, template: ` <div> <h1>Info</h1> <p>Now we have:</p> <table class="items"> <thead> <tr> <th>#</th> <th>what</th> <th>count</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Authors</td> <td>{{ authors.length }}</td> </tr> <tr> <td>2</td> <td>Genres</td> <td>{{ genres.length }}</td> </tr> <tr> <td>3</td> <td>Books</td> <td>{{ books.length }}</td> </tr> <tr> <td>4</td> <td>Comments</td> <td>{{ comments.length }}</td> </tr> </tbody> </table> </div>` };<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/rest/ErrorHandler.java package ru.otus.librarywebapp.rest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import ru.otus.librarywebapp.exception.AuthorNotFoundException; import ru.otus.librarywebapp.exception.BookNotFoundException; import ru.otus.librarywebapp.exception.CommentNotFoundException; import ru.otus.librarywebapp.exception.GenreNotFoundException; @RestControllerAdvice public class ErrorHandler { @ExceptionHandler(value = {AuthorNotFoundException.class, BookNotFoundException.class, CommentNotFoundException.class, GenreNotFoundException.class}) public ResponseEntity<String> handle(RuntimeException ex) { return new ResponseEntity<>("Error: " + ex.getMessage(), HttpStatus.NOT_FOUND); } } <file_sep>/library-app/src/main/java/ru/otus/librarywebapp/security/CustomReactiveUserDetailsService.java package ru.otus.librarywebapp.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.ReactiveUserDetailsService; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; import ru.otus.librarywebapp.dao.UserRepository; @Service public class CustomReactiveUserDetailsService implements ReactiveUserDetailsService { private final UserRepository userRepository; @Autowired public CustomReactiveUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public Mono<UserDetails> findByUsername(String name) { return userRepository.findByUsername(name); } } <file_sep>/library-model/src/main/java/ru/otus/dto/AuthorDto.java package ru.otus.dto; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import ru.otus.domain.Author; import java.util.List; @Getter @Setter @AllArgsConstructor public class AuthorDto { private List<Author> authors; } <file_sep>/library-app/src/test/java/ru/otus/librarywebapp/rest/HomeControllerTest.java package ru.otus.librarywebapp.rest; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.WebTestClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import ru.otus.domain.Author; import ru.otus.domain.Genre; import ru.otus.dto.BookDto; import ru.otus.dto.CommentDto; import ru.otus.librarywebapp.controller.HomeController; import ru.otus.librarywebapp.service.AuthorService; import ru.otus.librarywebapp.service.BookService; import ru.otus.librarywebapp.service.CommentService; import ru.otus.librarywebapp.service.GenreService; import java.util.Collections; import static org.mockito.BDDMockito.given; @DisplayName("Test for Home Controller") @WebFluxTest(controllers = HomeController.class) @Import(HomeController.class) class HomeControllerTest { @Autowired private WebTestClient webClient; @MockBean private BookService bookService; @MockBean private AuthorService authorService; @MockBean private GenreService genreService; @MockBean private CommentService commentService; @Test @DisplayName("Test redirect on / ") void shouldRedirectToLogin() { this.webClient.get() .uri("/") .exchange() .expectStatus().isUnauthorized(); } @Test @DisplayName("Test get info page on / ") @WithMockUser void shouldGetInfoPage() { given(this.authorService.getAll()).willReturn(Flux.just(new Author())); given(this.genreService.getAll()).willReturn(Flux.just(new Genre())); given(this.bookService.getAll(BookApi.BOOK_PAGE_REQUEST)) .willReturn(Mono.just(new BookDto(Collections.emptyList(), 0, 0L))); given(this.commentService.getAll(CommentApi.COMMENTS_PAGE_REQUEST)) .willReturn(Mono.just(new CommentDto(Collections.emptyList(), 0, 0L))); this.webClient.get().uri("/") .accept(MediaType.TEXT_HTML) .exchange() .expectStatus().isOk() .expectBody(String.class).consumeWith( response -> Assertions.assertThat(response.getResponseBody()).contains("frontendData") ); } }<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/dao/AdditionalDataRepository.java package ru.otus.librarywebapp.dao; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import reactor.core.publisher.Flux; import ru.otus.domain.AdditionalData; public interface AdditionalDataRepository extends ReactiveMongoRepository<AdditionalData, String>, PageableFindAll<AdditionalData> { Flux<AdditionalData> findByBookId(String bookId); Flux<AdditionalData> deleteByBookId(String bookId); } <file_sep>/library-app/src/test/java/ru/otus/librarywebapp/rest/CommentControllerTest.java package ru.otus.librarywebapp.rest; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.BodyInserters; import reactor.core.publisher.Mono; import ru.otus.domain.Comment; import ru.otus.dto.CommentDto; import ru.otus.librarywebapp.service.CommentService; import java.util.Collections; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; @DisplayName("Test for comment api") @WebFluxTest(controllers = CommentApi.class) @Import(CommentApi.class) class CommentControllerTest extends BaseTest { @MockBean private CommentService commentService; @Test @DisplayName("Test get all comments on /api/comment") void shouldGetAllComments() { given(this.commentService.getAll(CommentApi.COMMENTS_PAGE_REQUEST)) .willReturn(Mono.just(new CommentDto(Collections.singletonList(comment()), 0, 1L))); String responseBody = "{\"comments\":[{\"id\":null,\"book\":null,\"author\":\"test\"," + "\"date\":\"2019-04-27 00:00\",\"content\":\"test\"}],\"currentPage\":0,\"totalPages\":1}"; this.webClient.get().uri(uriBuilder -> uriBuilder .path("/api/comment") .queryParam("page", 0) .build()) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo(responseBody); } @Test @DisplayName("Test get comment on /api/comment{id}") void shouldGetComment() { given(this.commentService.getById("123")).willReturn(Mono.just(comment())); String responseBody = "{\"id\":null,\"book\":null,\"author\":\"test\",\"date\":\"2019-04-27 00:00\",\"content\":\"test\"}"; this.webClient.get().uri("/api/comment/123") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo(responseBody); } @Test @DisplayName("Test update comment page on /api/comment") void shouldUpdateComment() { Comment comment = comment(); given(this.commentService.update(any(Comment.class))).willReturn(Mono.just(comment)); String responseBody = "{\"id\":null,\"book\":null,\"author\":\"test\",\"date\":\"2019-04-27 00:00\",\"content\":\"test\"}"; this.webClient .mutateWith(csrf()) .put().uri("/api/comment") .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromObject(comment)) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo(responseBody); verify(this.commentService, times(1)).update(comment); } @Test @DisplayName("Test create comment on post /api/comment") void shouldCreateComment() { Comment comment = new Comment("test", null, "test"); Comment savedComment = comment(); given(this.commentService.insert(any(Comment.class))).willReturn(Mono.just(savedComment)); String responseBody = "{\"id\":null,\"book\":null,\"author\":\"test\",\"date\":\"2019-04-27 00:00\",\"content\":\"test\"}"; this.webClient .mutateWith(csrf()) .post().uri("/api/comment") .contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromObject(comment)) .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isCreated() .expectBody(String.class).isEqualTo(responseBody); verify(this.commentService, times(1)).insert(any(Comment.class)); } @Test @DisplayName("Test delete comment on /api/comment/{id}") void shouldDeleteCommentById() { given(this.commentService.deleteById("123")).willReturn(Mono.empty()); this.webClient .mutateWith(csrf()) .delete().uri("/api/comment/123") .exchange() .expectStatus().isNoContent(); verify(this.commentService, times(1)).deleteById("123"); } private Comment comment() { return new Comment("test", dateTime(), "test"); } }<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/rest/BookApi.java package ru.otus.librarywebapp.rest; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; import ru.otus.domain.Book; import ru.otus.dto.BookDto; import ru.otus.librarywebapp.exception.BookNotFoundException; import ru.otus.librarywebapp.service.BookService; import javax.validation.Valid; @Slf4j @RestController public class BookApi { private static final String BOOKS_SORT_FIELD = "bookName"; private static final Sort BOOK_SORT = Sort.by(Sort.Direction.ASC, BOOKS_SORT_FIELD); public static final int BOOKS_PER_PAGE = 15; public static final PageRequest BOOK_PAGE_REQUEST = PageRequest.of(0, BOOKS_PER_PAGE, BOOK_SORT); private final BookService bookService; @Autowired public BookApi(BookService bookService) { this.bookService = bookService; } @GetMapping("/api/book") public Mono<BookDto> getAll(@RequestParam("page") int page) { log.info("get all books, page {}", page); return bookService.getAll(PageRequest.of(page, BOOKS_PER_PAGE, BOOK_SORT)); } @GetMapping("/api/book/{id}") public Mono<Book> getById(@PathVariable String id) { log.info("get books by id {}", id); return bookService.getById(id) .switchIfEmpty(Mono.error(BookNotFoundException::new)); } @ResponseStatus(HttpStatus.OK) @PutMapping("/api/book") public Mono<Book> update(@Valid @RequestBody Book book) { log.info("update book {} by id {}", book, book.getId()); return bookService.update(book); } @ResponseStatus(HttpStatus.CREATED) @PostMapping("/api/book") public Mono<Book> create(@Valid @RequestBody Book book) { log.info("create book {}", book); return bookService.insert(book); } @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping("/api/book/{id}") public Mono<Void> delete(@PathVariable String id) { log.info("delete book by id {}", id); return bookService.deleteById(id); } } <file_sep>/README.md # library-web-app Simple CRUD application with Spring Boot, WebFlux, Spring Security and Vue.js. ##### prerequisites: Java 8, MongoDB ##### start: ```bash mvnw spring-boot:run -pl library-app -am``` or ```mvn spring-boot:run -pl library-app -am``` ##### batch tool: ```bash mvnw spring-boot:run -pl library-batch -am``` or ```mvn spring-boot:run -pl library-batch -am```<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/service/impl/CommentServiceImpl.java package ru.otus.librarywebapp.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import ru.otus.domain.Comment; import ru.otus.dto.CommentDto; import ru.otus.librarywebapp.dao.CommentRepository; import ru.otus.librarywebapp.rest.CommentApi; import ru.otus.librarywebapp.service.CommentService; @Service public class CommentServiceImpl implements CommentService { private final CommentRepository repository; @Autowired public CommentServiceImpl(CommentRepository repository) { this.repository = repository; } @Override public Mono<Long> count() { return repository.count(); } @Override public Mono<Comment> getById(String id) { return repository.findById(id); } @Override public Flux<Comment> getByBookId(String bookId) { return repository.findByBookId(bookId); } @Override public Flux<Comment> getAll() { return repository.findAll(); } @Override public Mono<CommentDto> getAll(Pageable pageable) { return repository.findAll(pageable).collectList().zipWith(repository.count()) .map(data -> new CommentDto(data.getT1(), pageable.getPageNumber(), data.getT2() / CommentApi.COMMENTS_PER_PAGE)); } @Override public Mono<Void> deleteById(String id) { return repository.deleteById(id); } @Override @Transactional public Flux<Comment> deleteByBookId(String bookId) { return repository.deleteByBookId(bookId); } @Override public Mono<Comment> insert(Comment comment) { return repository.insert(comment); } @Override public Mono<Comment> update(Comment comment) { return repository.save(comment); } } <file_sep>/Dockerfile FROM maven:3.6.1-jdk-8-alpine AS MAVEN_IMAGE ENV BUILD_DIR=/tmp/project RUN mkdir -p $BUILD_DIR WORKDIR $BUILD_DIR COPY ./pom.xml $BUILD_DIR/ COPY ./library-model $BUILD_DIR/library-model COPY ./library-app $BUILD_DIR/library-app COPY ./library-batch $BUILD_DIR/library-batch RUN mvn package -pl library-app -am FROM openjdk:8-alpine ENV SPRING_DATA_MONGODB_URI=mongodb://mongo:27017 ENV PROJECT_DIR=/opt/project RUN mkdir -p $PROJECT_DIR WORKDIR $PROJECT_DIR COPY --from=MAVEN_IMAGE /tmp/project/library-app/target/library-app.jar $PROJECT_DIR/library-app.jar EXPOSE 8080 CMD ["java", "-jar", "library-app.jar"] <file_sep>/library-app/src/main/java/ru/otus/librarywebapp/integration/IntegrationConfig.java package ru.otus.librarywebapp.integration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.expression.common.LiteralExpression; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.integration.dsl.MessageChannels; import org.springframework.integration.dsl.Pollers; import org.springframework.integration.mongodb.outbound.MongoDbStoringMessageHandler; import org.springframework.integration.scheduling.PollerMetadata; import org.springframework.messaging.MessageHandler; import ru.otus.domain.AdditionalData; import ru.otus.domain.Book; import ru.otus.librarywebapp.service.BookValidateService; import java.util.concurrent.Executors; @Configuration public class IntegrationConfig { @Bean public QueueChannel bookInChannel() { return MessageChannels.queue(10).get(); } @Bean (name = PollerMetadata.DEFAULT_POLLER) public PollerMetadata poller () { return Pollers.fixedRate(100).maxMessagesPerPoll(10).get() ; } @Bean @ServiceActivator(inputChannel = "storeChannel") public MessageHandler mongoOutboundAdapter(MongoTemplate mongoTemplate) { MongoDbStoringMessageHandler adapter = new MongoDbStoringMessageHandler(mongoTemplate); adapter.setCollectionNameExpression(new LiteralExpression("additionalData")); return adapter; } @Bean public IntegrationFlow flow(BookValidateService bookValidateService) { return IntegrationFlows.from("bookInChannel") .log() .split() .channel(c -> c.executor(Executors.newCachedThreadPool())) .filter((Book book) -> book.getAuthor().isAvailable()) .transform(Book.class, bookValidateService::validate) .filter(AdditionalData::isNotEmpty) .log() .channel("storeChannel") .get(); } } <file_sep>/library-app/src/main/java/ru/otus/librarywebapp/service/impl/BookServiceImpl.java package ru.otus.librarywebapp.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import ru.otus.dto.BookDto; import ru.otus.librarywebapp.dao.BookRepository; import ru.otus.librarywebapp.dao.CommentRepository; import ru.otus.domain.Book; import ru.otus.librarywebapp.rest.BookApi; import ru.otus.librarywebapp.service.BookService; @Service public class BookServiceImpl implements BookService { private final BookRepository repository; private final CommentRepository commentRepository; @Autowired public BookServiceImpl(BookRepository repository, CommentRepository commentRepository) { this.repository = repository; this.commentRepository = commentRepository; } @Override public Mono<Long> count() { return repository.count(); } public Mono<Book> getById(String id) { return repository.findById(id); } @Override public Flux<Book> getByBookName(String bookName) { return repository.findByBookName(bookName); } @Override public Flux<Book> getByBookPartName(String bookName) { return repository.findByBookNameContaining(bookName); } @Override public Flux<Book> getAll() { return repository.findAll(); } @Override public Mono<BookDto> getAll(Pageable pageable) { return repository.findAll(pageable).collectList().zipWith(repository.count()) .map(data -> new BookDto(data.getT1(), pageable.getPageNumber(), data.getT2() / BookApi.BOOKS_PER_PAGE)); } @Override public Flux<Book> deleteByAuthorId(String authorId) { return repository.findByAuthorId(authorId) .flatMap(book -> commentRepository.deleteByBookId(book.getId())) .thenMany(repository.deleteByAuthorId(authorId)); } @Override public Flux<Book> deleteByGenreId(String genreId) { return repository.findByGenreId(genreId) .flatMap(book -> commentRepository.deleteByBookId(book.getId())) .thenMany(repository.deleteByGenreId(genreId)); } @Override public Mono<Void> deleteById(String id) { return commentRepository.deleteByBookId(id).then(repository.deleteById(id)); } @Override public Mono<Book> insert(Book book) { return repository.insert(book); } @Override public Mono<Book> update(Book book) { return repository.save(book); } } <file_sep>/library-app/src/main/resources/static/js/store/modules/Author.js Vue.use(Vuex) export const authorModule = { namespaced: true, state: { ...frontendData.authorDto }, mutations: { addAuthorMutation(state, author) { state.authors = [...state.authors, author] }, updateAuthorMutation(state, author) { var indexUpdated = state.authors.findIndex(item => item.id === author.id); state.authors = [ ...state.authors.slice(0, indexUpdated), author, ...state.authors.slice(indexUpdated + 1) ] }, removeAuthorMutation(state, author) { var indexDeleted = state.authors.findIndex(item => item.id === author.id); if (indexDeleted > -1) { state.authors = [ ...state.authors.slice(0, indexDeleted), ...state.authors.slice(indexDeleted + 1) ] } } }, actions: { async addAuthor({commit, state}, author) { const result = await Vue.resource('/api/author{/id}').save({}, author); const data = await result.json(); if (result.ok) { commit('addAuthorMutation', data); } return result; }, async updateAuthor({commit}, author) { const result = await Vue.resource('/api/author{/id}').update({}, author) const data = await result.json() if (result.ok) { commit('updateAuthorMutation', data); } return result; }, async removeAuthor({dispatch, commit}, author) { const result = await Vue.resource('/api/author{/id}').remove({id: author.id}) if (result.ok) { commit('removeAuthorMutation', author); dispatch('bookModule/removeBookByAuthorId', author.id, { root: true }); } return result; }, } }<file_sep>/library-app/src/main/resources/static/js/components/books/BookTable.js import BookTr from './BookTr.js' import BookForm from './BookForm.js' import LazyLoader from '../LazyLoader.js' export default { name: 'BookTable', computed: Vuex.mapState('bookModule', ['books']), components: { BookTr, BookForm, LazyLoader }, data: function() { return { book: null } }, template: ` <div> <h1>Books:</h1> <table class="items"> <thead> <tr> <th>id</th> <th>bookName</th> <th>publishDate</th> <th>language</th> <th>publishingHouse</th> <th>city</th> <th>isbn</th> <th>author</th> <th>genre</th> <th></th> </tr> </thead> <tbody> <book-tr v-for="book in books" :key="book.id" :book="book" :editBook="editBook" /> <lazy-loader></lazy-loader> </tbody> </table> <div class="gap-30"></div> <p>Edit:</p> <book-form :bookAttr="book" /> <div class="gap-30"></div> <div class="alert alert-danger" id="bookError" style="display:none;"> <strong>Error!</strong> Access Denied! You not have permission to <span id="bookToAction"></span> book! </div> <div class="alert alert-success" id="bookSuccess" style="display:none;"> <strong>Success!</strong> Book <span id="bookAction"></span> successfully. </div> </div> `, methods: { editBook(book) { this.book = book; } } };<file_sep>/library-app/src/main/resources/static/js/components/books/BookForm.js import { showAlert } from '../Utils.js' export default { name: 'BookForm', computed: { ...Vuex.mapState('authorModule', ['authors']), ...Vuex.mapState('genreModule', ['genres']) }, props: ['bookAttr'], data: function() { return { bookName: '', publishDate: '', language: '', publishingHouse: '', city: '', isbn: '', author: '', genre: '', id: null } }, watch: { bookAttr: function(newVal, oldVal) { this.bookName = newVal.bookName; this.publishDate = newVal.publishDate; this.language = newVal.language; this.publishingHouse = newVal.publishingHouse; this.city = newVal.city; this.isbn = newVal.isbn; this.author = newVal.author; this.genre = newVal.genre; this.id = newVal.id; } }, template: ` <div class="block"> <form onsubmit="return false"> <input type="text" placeholder="Book Name" v-model="bookName" required="required"> <p/> <input type="date" v-model="publishDate" required="required"> <p/> <input type="text" placeholder="Language" v-model="language" required="required"> <p/> <input type="text" placeholder="Publishing House" v-model="publishingHouse" required="required"> <p/> <input type="text" placeholder="City" v-model="city" required="required"> <p/> <input type="text" placeholder="Isbn" v-model="isbn" required="required"> <p/> <select v-model="author" required="required"> <option disabled value="">---</option> <option v-for="author in authors" v-bind:value="author">{{ author.fullName }}</option> </select> <p/> <select v-model="genre" required="required"> <option disabled value="">---</option> <option v-for="genre in genres" v-bind:value="genre">{{ genre.genreName }}</option> </select> <p/> <input type="reset" value="Clean"> <input type="submit" value="Save" @click="save"> </form> </div> `, methods: { ...Vuex.mapActions('bookModule', ['addBook', 'updateBook']), save: function() { var inputs = document.getElementsByTagName('input'); for (var index = 0; index < inputs.length; ++index) { if (!inputs[index].checkValidity()) { return; } } var book = { id: this.id, bookName: this.bookName, publishDate: this.publishDate, language: this.language, publishingHouse: this.publishingHouse, city: this.city, isbn: this.isbn, author: this.author, genre: this.genre }; if (this.id) { this.updateBook(book).then(result => { if (result.ok) { showAlert('#bookSuccess', '#bookAction', 'updated'); }}, error => showAlert('#bookError', '#bookToAction', 'update')); } else { this.addBook(book).then(result => { if (result.ok) { showAlert('#bookSuccess', '#bookAction', 'created'); }}, error => showAlert('#bookError', '#bookToAction', 'create')); } this.bookName = ''; this.publishDate = ''; this.language = ''; this.publishingHouse = ''; this.city = ''; this.isbn = ''; this.author = ''; this.genre = ''; this.id = null; } } };<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/LibraryWebAppApplication.java package ru.otus.librarywebapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.data.mongodb.config.EnableMongoAuditing; import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories; import org.springframework.integration.annotation.IntegrationComponentScan; import org.springframework.integration.config.EnableIntegration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.web.client.RestTemplate; import ru.otus.librarywebapp.dao.BookRepository; import ru.otus.librarywebapp.integration.IntegrationService; import ru.otus.librarywebapp.integration.ValidateTask; import java.time.Duration; @SpringBootApplication @EnableMongoAuditing @EnableScheduling @EnableReactiveMongoRepositories @EnableIntegration @IntegrationComponentScan public class LibraryWebAppApplication { @Bean @ConditionalOnProperty(prefix = "validate-service", value = "enabled", havingValue = "true") public ValidateTask validateTask(IntegrationService integrationService, BookRepository bookRepository) { return new ValidateTask(integrationService, bookRepository); } @Bean public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) { return restTemplateBuilder .setConnectTimeout(Duration.ofSeconds(5)) .setReadTimeout(Duration.ofSeconds(5)) .build(); } public static void main(String[] args) { SpringApplication.run(LibraryWebAppApplication.class, args); } } <file_sep>/library-batch/src/main/resources/schema.sql DROP TABLE IF EXISTS AUTHORS; CREATE TABLE AUTHORS(ID BIGINT IDENTITY PRIMARY KEY, FIRST_NAME VARCHAR(255), BIRTH_DATE DATE, LAST_NAME VARCHAR(255)); DROP TABLE IF EXISTS GENRES; CREATE TABLE GENRES(ID BIGINT IDENTITY PRIMARY KEY, GENRE_NAME VARCHAR(255) UNIQUE); DROP TABLE IF EXISTS BOOKS; CREATE TABLE BOOKS(ID BIGINT IDENTITY PRIMARY KEY, AUTHOR_ID BIGINT NOT NULL, GENRE_ID BIGINT NOT NULL, BOOK_NAME VARCHAR(255), PUBLISH_DATE DATE, LANGUAGE VARCHAR(255), PUBLISHING_HOUSE VARCHAR(255), CITY VARCHAR(255), ISBN VARCHAR(255), FOREIGN KEY(AUTHOR_ID) REFERENCES AUTHORS(ID), FOREIGN KEY(GENRE_ID) REFERENCES GENRES(ID)); DROP TABLE IF EXISTS COMMENTS; CREATE TABLE COMMENTS(ID BIGINT IDENTITY PRIMARY KEY, AUTHOR VARCHAR(255), BOOK_ID BIGINT NOT NULL, `DATE` DATE, CONTENT VARCHAR(255), FOREIGN KEY(BOOK_ID) REFERENCES BOOKS(ID));<file_sep>/library-app/src/test/java/ru/otus/librarywebapp/rest/TaskControllerTest.java package ru.otus.librarywebapp.rest; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.context.annotation.Import; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.reactive.server.WebTestClient; import ru.otus.librarywebapp.controller.TaskController; import ru.otus.librarywebapp.integration.ValidateTask; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.csrf; @DisplayName("Test for Task Controller") @WebFluxTest(controllers = TaskController.class) @Import(TaskController.class) class TaskControllerTest { @Autowired private WebTestClient webClient; @MockBean private ValidateTask validateTask; @SpyBean private ScheduledAnnotationBeanPostProcessor scheduledAnnotationBeanPostProcessor; @Test @DisplayName("Test task forbidden /task/** ") void shouldTaskForbidden() { this.webClient.put() .uri("/task/start") .exchange() .expectStatus().isForbidden(); this.webClient.put() .uri("/task/stop") .exchange() .expectStatus().isForbidden(); } @Test @DisplayName("Test task start on /task/start ") @WithMockUser void shouldTaskStart() { this.webClient.mutateWith(csrf()) .put() .uri("/task/start") .exchange() .expectStatus().isOk(); verify(this.scheduledAnnotationBeanPostProcessor, times(1)).postProcessAfterInitialization(any(ValidateTask.class), anyString()); } @Test @DisplayName("Test task stop on /task/stop ") @WithMockUser void shouldTaskStop() { this.webClient.mutateWith(csrf()) .put() .uri("/task/stop") .exchange() .expectStatus().isOk(); verify(this.scheduledAnnotationBeanPostProcessor, times(1)).postProcessBeforeDestruction(any(ValidateTask.class), anyString()); } }<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/actuators/CustomHealthIndicator.java package ru.otus.librarywebapp.actuators; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.ReactiveHealthIndicator; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; import java.time.Duration; import java.time.LocalDateTime; @Component public class CustomHealthIndicator implements ReactiveHealthIndicator { private final LocalDateTime localDateTime = LocalDateTime.now(); @Override public Mono<Health> health() { return checkUptimeServiceHealth().onErrorResume( ex -> Mono.just(new Health.Builder().down(ex).build()) ); } private Mono<Health> checkUptimeServiceHealth() { return Mono.just(new Health.Builder().up().withDetail("uptime", Duration.between(localDateTime, LocalDateTime.now()).getSeconds()).build()); } } <file_sep>/library-app/src/main/resources/static/js/components/genres/GenreTr.js import { showAlert } from '../Utils.js' export default { name: 'GenreTr', props: ['genre', 'editGenre'], template: ` <tr> <td>{{ genre.id }}</td> <td>{{ genre.genreName }}</td> <td> <input type="button" value="edit" @click="edit"> <input type="button" value="x" @click="del"/> </td> </tr> `, methods: { ...Vuex.mapActions('genreModule',['removeGenre']), edit() { this.editGenre(this.genre); }, del() { this.removeGenre(this.genre).then(result => { if (result.ok) { showAlert('#genreSuccess', '#genreAction', 'deleted'); }}, error => showAlert('#genreError', '#genreToAction', 'delete')); } } };<file_sep>/library-model/src/main/java/ru/otus/domain/Book.java package ru.otus.domain; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.time.LocalDate; @Data @NoArgsConstructor @Document(collection = "books") @Entity @Table(name = "books") public class Book { @Id @javax.persistence.Id @GeneratedValue(strategy = GenerationType.IDENTITY) private String id; @DBRef @ManyToOne @JoinColumn(name = "author_id") private Author author; @DBRef @ManyToOne @JoinColumn(name = "genre_id") private Genre genre; @NotBlank @Indexed private String bookName; @NotNull @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") private LocalDate publishDate; @NotBlank private String language; @NotBlank private String publishingHouse; @NotBlank private String city; @NotBlank private String isbn; public Book(Author author, Genre genre, String bookName, LocalDate publishDate, String language, String publishingHouse, String city, String isbn) { this.author = author; this.genre = genre; this.bookName = bookName; this.publishDate = publishDate; this.language = language; this.publishingHouse = publishingHouse; this.city = city; this.isbn = isbn; } } <file_sep>/library-app/src/main/java/ru/otus/librarywebapp/dao/GenreRepository.java package ru.otus.librarywebapp.dao; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import reactor.core.publisher.Flux; import ru.otus.domain.Genre; public interface GenreRepository extends ReactiveMongoRepository<Genre, String>, PageableFindAll<Genre> { Flux<Genre> findByGenreName(String genreName); } <file_sep>/library-app/src/main/resources/static/js/Router.js import Home from './pages/Home.js' import Author from './pages/Author.js' import Genre from './pages/Genre.js' import Book from './pages/Book.js' import Comment from './pages/Comment.js' Vue.use(VueRouter) export default new VueRouter({ routes: [ { path: '/', name: 'home', component: Home }, { path: '/author', name: 'author', component: Author }, { path: '/genre', name: 'genre', component: Genre }, { path: '/book', name: 'book', component: Book }, { path: '/comment', name: 'comment', component: Comment } ] })<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/controller/TaskController.java package ru.otus.librarywebapp.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.lang.Nullable; import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.ResponseBody; import ru.otus.librarywebapp.integration.ValidateTask; import java.util.Objects; @Slf4j @Controller public class TaskController { private static final String SCHEDULED_TASKS = "validateTask"; private final ScheduledAnnotationBeanPostProcessor postProcessor; private final ValidateTask scheduledTask; @Autowired public TaskController(ScheduledAnnotationBeanPostProcessor postProcessor, @Nullable ValidateTask scheduledTask) { this.postProcessor = postProcessor; this.scheduledTask = scheduledTask; } @PutMapping(value = "/task/stop") @ResponseBody public ResponseEntity<String> stopSchedule(){ if (Objects.isNull(scheduledTask)) { log.warn("Task disabled!"); return ResponseEntity.badRequest().body("Task disabled!"); } log.info("Task stop."); postProcessor.postProcessBeforeDestruction(scheduledTask, SCHEDULED_TASKS); return ResponseEntity.ok("OK"); } @PutMapping(value = "/task/start") @ResponseBody public ResponseEntity<String> startSchedule(){ if (Objects.isNull(scheduledTask)) { log.warn("Task disabled!"); return ResponseEntity.badRequest().body("Task disabled!"); } log.info("Task start."); postProcessor.postProcessAfterInitialization(scheduledTask, SCHEDULED_TASKS); return ResponseEntity.ok("OK"); } } <file_sep>/library-model/src/main/java/ru/otus/domain/Author.java package ru.otus.domain; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Table; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.time.LocalDate; import java.util.Objects; @Data @NoArgsConstructor @Document(collection = "authors") @Entity @Table(name = "authors") public class Author { public static final String N_A = "n/a"; @Id @javax.persistence.Id @GeneratedValue(strategy = GenerationType.IDENTITY) private String id; @NotBlank private String firstName; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd") @NotNull private LocalDate birthDate; @Indexed @NotBlank private String lastName; public Author(String firstName, LocalDate birthDate, String lastName) { this.firstName = firstName; this.birthDate = birthDate; this.lastName = lastName; } public String getFullName() { if (isAvailable()) { return String.format("%s %s", Objects.toString(firstName, ""), Objects.toString(lastName, "")); } else { return lastName; } } @JsonIgnore public boolean isAvailable() { return !N_A.equals(lastName); } } <file_sep>/library-app/src/main/java/ru/otus/librarywebapp/exception/BookDateParseException.java package ru.otus.librarywebapp.exception; public class BookDateParseException extends RuntimeException { private static final String MESSAGE = "Date parsing error!"; public BookDateParseException() { super(MESSAGE); } public BookDateParseException(String message, Throwable cause) { super(message, cause); } public BookDateParseException(Throwable cause) { super(MESSAGE, cause); } } <file_sep>/library-app/src/main/resources/static/js/pages/Author.js import AuthorTable from '../components/authors/AuthorTable.js' export default { name: 'Author', components: { AuthorTable }, template: '<author-table />' };<file_sep>/library-app/src/main/resources/static/js/store/modules/Book.js Vue.use(Vuex) export const bookModule = { namespaced: true, state: { ...frontendData.bookDto }, mutations: { addBookMutation(state, book) { state.books = [...state.books, book] }, updateBookMutation(state, book) { var indexUpdated = state.books.findIndex(item => item.id === book.id); state.books = [ ...state.books.slice(0, indexUpdated), book, ...state.books.slice(indexUpdated + 1) ] }, removeBookMutation(state, book) { var indexDeleted = state.books.findIndex(item => item.id === book.id); if (indexDeleted > -1) { state.books = [ ...state.books.slice(0, indexDeleted), ...state.books.slice(indexDeleted + 1) ] } }, addBookPageMutation(state, books) { const targetBooks = state.books .concat(books) .reduce((result, value) => { result[value.id] = value return result; }, {}) state.books = Object.values(targetBooks) }, updateTotalPagesMutation(state, totalPages) { state.totalPages = totalPages }, updateCurrentPageMutation(state, currentPage) { state.currentPage = currentPage } }, actions: { async addBook({commit, state}, book) { const result = await Vue.resource('/api/book{/id}').save({}, book); const data = await result.json(); if (result.ok) { commit('addBookMutation', data); } return result; }, async updateBook({commit}, book) { const result = await Vue.resource('/api/book{/id}').update({}, book) const data = await result.json() if (result.ok) { commit('updateBookMutation', data); } return result; }, async removeBook({commit}, book) { const result = await Vue.resource('/api/book{/id}').remove({id: book.id}) if (result.ok) { commit('removeBookMutation', book); commit('commentModule/removeCommentByBookIdMutation', book.id, { root: true }); } return result; }, async removeBookByAuthorId({commit, state}, authorId) { var booksToBeDeleted = state.books.filter(book => authorId === book.author.id); booksToBeDeleted.forEach(function(book) { commit('removeBookMutation', book); commit('commentModule/removeCommentByBookIdMutation', book.id, { root: true }); }); }, async removeBookByGenreId({commit, state}, genreId) { var booksToBeDeleted = state.books.filter(book => genreId === book.genre.id); booksToBeDeleted.forEach(function(book) { commit('removeBookMutation', book); commit('commentModule/removeCommentByBookIdMutation', book.id, { root: true }); }); }, async loadPageAction({commit, state}) { const response = await Vue.http.get('/api/book', {params: { page: state.currentPage + 1 }}) const data = await response.json() commit('addBookPageMutation', data.books) commit('updateTotalPagesMutation', data.totalPages) commit('updateCurrentPageMutation', Math.min(data.currentPage, data.totalPages - 1)) } } }<file_sep>/library-model/src/main/java/ru/otus/domain/AdditionalData.java package ru.otus.domain; import lombok.Data; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; import java.util.ArrayList; import java.util.List; @Data @Document(collection = "additionalData") public class AdditionalData { private final List<String> items; @DBRef private Book book; public AdditionalData() { this.items = new ArrayList<>(); } public boolean isNotEmpty() { return !items.isEmpty(); } } <file_sep>/library-app/src/main/resources/static/js/components/comments/CommentTr.js import { showAlert } from '../Utils.js' export default { name: 'CommentTr', props: ['comment', 'editComment', 'deleteComment'], template: ` <tr> <td>{{ comment.id }}</td> <td>{{ comment.author }}</td> <td>{{ comment.date }}</td> <td>{{ comment.content }}</td> <td v-if="comment.book != null">{{ comment.book.bookName }}</td> <td class="gray" v-else>Not found!</td> <td> <input type="button" value="edit" @click="edit"> <input type="button" value="x" @click="del"/> </td> </tr> `, methods: { ...Vuex.mapActions('commentModule',['removeComment']), edit() { this.editComment(this.comment); }, del() { this.removeComment(this.comment) .then(result => { if (result.ok) { showAlert('#commentSuccess', '#commentAction', 'deleted'); }}, error => showAlert('#commentError', '#commentToAction', 'delete')); } } };<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/exception/AuthorNotFoundException.java package ru.otus.librarywebapp.exception; public class AuthorNotFoundException extends RuntimeException { private static final String MESSAGE = "Author not found!"; public AuthorNotFoundException() { super(MESSAGE); } public AuthorNotFoundException(String message, Throwable cause) { super(message, cause); } public AuthorNotFoundException(Throwable cause) { super(MESSAGE, cause); } } <file_sep>/library-batch/src/main/java/ru/otus/config/csv/LibraryItemProcessor.java package ru.otus.config.csv; import lombok.extern.slf4j.Slf4j; import org.springframework.batch.item.ItemProcessor; import org.springframework.util.StringUtils; import ru.otus.domain.*; import ru.otus.dto.LibraryDto; import ru.otus.dto.LibraryItem; import java.time.LocalDate; @Slf4j public class LibraryItemProcessor implements ItemProcessor<LibraryDto, LibraryItem> { private LocalDate LocalDateMIN = LocalDate.of(1900, 1, 1); @Override public LibraryItem process(final LibraryDto libraryDto) { String bookName = libraryDto.getBookName(); String strAuthor = libraryDto.getAuthor(); String year = libraryDto.getYear(); String strGenre = libraryDto.getGenre(); String isbn = libraryDto.getIsbn(); Author author = parseAuthor(strAuthor); Genre genre = parseGenre(strGenre); LibraryItem transformedDto = new LibraryItem() .withAuthor(author) .withGenre(genre) .withBook(parseBook(bookName, year, isbn, author, genre)); if (log.isDebugEnabled()) { log.debug("Converting [{}] into [{}]", libraryDto, transformedDto); } return transformedDto; } private Author parseAuthor(String strAuthor) { String author = strAuthor.trim(); if (StringUtils.isEmpty(author)) { return null; } String[] fio = author.split("\\s"); if (fio.length > 1) { return new Author(fio[1].trim(), LocalDateMIN, fio[0].trim()); } else { return new Author(Author.N_A, LocalDateMIN, fio[0].trim()); } } private Genre parseGenre(String strGenre) { String genre = strGenre.trim(); return new Genre(StringUtils.capitalize(genre.toLowerCase())); } private Book parseBook(String strBookName, String year, String isbn, Author author, Genre genre) { String bookName = strBookName.trim(); LocalDate date = LocalDate.of(Integer.parseInt(year), 1, 1); return new Book(author, genre, bookName, date, "RU", Author.N_A, Genre.N_A, isbn); } }<file_sep>/pom.xml <?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"> <modelVersion>4.0.0</modelVersion> <packaging>pom</packaging> <modules> <module>library-model</module> <module>library-app</module> <module>library-batch</module> </modules> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> </parent> <groupId>ru.otus</groupId> <artifactId>library-web-app</artifactId> <version>0.0.1-SNAPSHOT</version> <name>library-web-app</name> <description>Library web project for Spring Boot</description> <properties> <java.version>1.8</java.version> <mockito.version>2.23.4</mockito.version> <mongobee.version>0.13</mongobee.version> <vue.version>2.5.16</vue.version> <swagger.version>3.0.0-SNAPSHOT</swagger.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </build> </project> <file_sep>/library-app/src/test/java/ru/otus/librarywebapp/dao/AuthorRepositoryTest.java package ru.otus.librarywebapp.dao; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; import org.springframework.context.annotation.ComponentScan; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import ru.otus.domain.Author; import java.time.LocalDate; import java.util.Objects; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @DisplayName("Test for AuthorRepository") @DataMongoTest @ComponentScan({"ru.otus.librarywebapp.dao", "ru.otus.librarywebapp.testconfig"}) class AuthorRepositoryTest { @Autowired private AuthorRepository authorRepository; @Test @DisplayName("Test return count authors") void shouldReturnCorrectCount() { Mono<Long> count = authorRepository.count(); StepVerifier .create(count) .assertNext(c -> assertEquals(c.longValue(), 2)) .expectComplete() .verify(); } @Test @DisplayName("Test insert new author") void shouldInsertNewAuthor() { Author author = new Author("test", LocalDate.now(), "test"); StepVerifier .create(authorRepository.save(author)) .assertNext(a -> assertNotNull(a.getId())) .expectComplete() .verify(); } @Test @DisplayName("Test get author by id") void shouldGetAuthorById() { Mono<Author> author = authorRepository.findById("5"); StepVerifier .create(author) .assertNext(a -> assertEquals(a.getFirstName(), "FirstName")) .expectComplete() .verify(); } @Test @DisplayName("Test get author by last name") void shouldGetAuthorsByLastName() { Flux<Author> authors = authorRepository.findByLastName("LastName"); StepVerifier .create(authors) .assertNext(b -> assertEquals(b.getFirstName(), "FirstName")) .expectComplete() .verify(); } @Test @DisplayName("Test get all authors") void shouldGetAllAuthors() { Flux<Author> authors = authorRepository.findAll(); StepVerifier .create(authors) .assertNext(b -> assertEquals(b.getFirstName(), "FirstName")) .assertNext(b -> assertEquals(b.getFirstName(), "FirstName7")) .expectComplete() .verify(); } @Test @DisplayName("Test delete author by id") void shouldDeleteAuthorById() { StepVerifier.create(authorRepository.deleteById("9")) .verifyComplete(); } @Test @DisplayName("Test delete author") void shouldDeleteAuthor() { Author author = authorRepository.findById("7").block(); Objects.requireNonNull(author); StepVerifier.create(authorRepository.delete(author)) .verifyComplete(); } }<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/service/CommentService.java package ru.otus.librarywebapp.service; import org.springframework.data.domain.Pageable; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import ru.otus.domain.Comment; import ru.otus.dto.CommentDto; public interface CommentService { Mono<Long> count(); Mono<Comment> getById(String id); Flux<Comment> getByBookId(String bookId); Flux<Comment> getAll(); Mono<CommentDto> getAll(Pageable pageable); Mono<Void> deleteById(String id); Flux<Comment> deleteByBookId(String bookId); Mono<Comment> update(Comment comment); Mono<Comment> insert(Comment comment); } <file_sep>/library-app/src/main/resources/static/js/components/LazyLoader.js export default { name: 'LazyLoader', template: `<span></span>`, methods: {...Vuex.mapActions('bookModule', ['loadPageAction'])}, mounted() { window.onscroll = () => { const el = document.documentElement const isBottomOfScreen = el.scrollTop + window.innerHeight === el.offsetHeight if (isBottomOfScreen) { this.loadPageAction() } } }, beforeDestroy() { window.onscroll = null } }<file_sep>/library-app/src/main/java/ru/otus/librarywebapp/dao/PageableFindAll.java package ru.otus.librarywebapp.dao; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.Query; import reactor.core.publisher.Flux; public interface PageableFindAll<T> { @Query("{ id: { $exists: true }}") Flux<T> findAll(Pageable pageable); } <file_sep>/library-batch/src/main/java/ru/otus/shell/BatchCommands.java package ru.otus.shell; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.JobParametersInvalidException; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; import org.springframework.batch.core.repository.JobRestartException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; @ShellComponent public class BatchCommands { private final JobLauncher jobLauncher; private final Job csvFileToDatabaseJob; private final Job jpaEntitiesToMongoJob; @Autowired public BatchCommands(JobLauncher jobLauncher, Job csvFileToDatabaseJob, Job jpaEntitiesToMongoJob) { this.jobLauncher = jobLauncher; this.csvFileToDatabaseJob = csvFileToDatabaseJob; this.jpaEntitiesToMongoJob = jpaEntitiesToMongoJob; } @ShellMethod(value = "Run import csv.", key = "import") public String importCsv() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException { jobLauncher.run(csvFileToDatabaseJob, new JobParametersBuilder() .addLong("uniqueness", System.nanoTime()).toJobParameters()); return "Done!"; } @ShellMethod(value = "Run migrate jpa.", key = "migrate") public String migrateJpa() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException { jobLauncher.run(jpaEntitiesToMongoJob, new JobParametersBuilder() .addLong("uniqueness", System.nanoTime()).toJobParameters()); return "Done!"; } }
a0c40705bf9ba2d3acdace56ae445312cf3b2a6e
[ "SQL", "JavaScript", "Markdown", "Maven POM", "Java", "Dockerfile" ]
74
JavaScript
veffhz/library-web-app
f223e7fde46987b257b17230f4cd3c38d3e2d107
78639d4c2cb44f9b388145be8d628001a513af79
refs/heads/master
<repo_name>kevinmcalear/react-pokemon-searcher-dumbo-web-051319<file_sep>/src/components/PokemonIndex.js import React from 'react' import PokemonCollection from './PokemonCollection' import MyTeamCollection from './MyTeamCollection' import PokemonForm from './PokemonForm' class PokemonIndex extends React.Component { state = { pokemon: [], searchTerm: '', myTeam: [] } handleChange = (e) => { this.setState({ searchTerm: e.target.value }) } handleAddPokemonToTeam = (pokemon) => { this.setState({myTeam: [...this.state.myTeam, pokemon]}) } componentDidMount() { fetch('http://localhost:3000/pokemon') .then(res => res.json()) .then((pokeData) => { this.setState({ pokemon: pokeData }) }) } // getFilteredPokemon = () => { // return this.state.pokemon.filter(pokemaan => pokemaan.name.includes(this.state.searchTerm)) // } handleNewPokemonSubmit = (newPokemon) => { const pokemon = { name: newPokemon.name, stats: [ { value: newPokemon.hp, name: "hp" } ], sprites: { front: newPokemon.frontUrl, back: newPokemon.backUrl } } console.log(newPokemon) fetch('http://localhost:3000/pokemon', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify(pokemon) }) .then(res => res.json()) .then(ourNewPokemon => { this.setState({pokemon: [...this.state.pokemon, ourNewPokemon]}) }) } render() { const filteredPokemon = this.state.pokemon .filter(pokemaan => pokemaan.name.toLowerCase().includes(this.state.searchTerm.toLowerCase())) return ( <div> <h1>Pokemon Searcher</h1> <br /> <input value={this.state.searchTerm} onChange={this.handleChange} type="search" /> <br /> <br /> <br /> <MyTeamCollection pokemon={this.state.myTeam}/> <br /> <hr /> <br /> <PokemonCollection onAddPokemonToTeam={this.handleAddPokemonToTeam} pokemon={filteredPokemon}/> <br /> <PokemonForm onNewPokemonSubmit={this.handleNewPokemonSubmit}/> </div> ) } } export default PokemonIndex
cbbd900f39eb7ab188a35d16b505b73c0f834618
[ "JavaScript" ]
1
JavaScript
kevinmcalear/react-pokemon-searcher-dumbo-web-051319
185c59c10263e4eaa18046f8e4ee62927ed493fd
0dacad20a79038be0163789d4cd6e17ff924e89b
refs/heads/master
<file_sep>use fluent::ContinuationAdderTrait; use fluent::EndScheduleMultipleTaskBoxesMultipleContinuationBoxes; use fluent::EndScheduleTrait; use SchedulerTrait; use Task; use TaskBox; use TaskBoxIntoIterator; pub struct ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, continuation_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, } impl <'a, TScheduler> ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TScheduler: SchedulerTrait { pub fn new(scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, continuation_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>) -> ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> { ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes { scheduler: scheduler, task_boxes: task_boxes, continuation_boxes: continuation_boxes } } fn convert_to_end_schedule_multiple_task_boxes_multiple_continuation_boxes(self) -> EndScheduleMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> { EndScheduleMultipleTaskBoxesMultipleContinuationBoxes::new(self.scheduler, self.task_boxes, self.continuation_boxes) } } impl <'a, TScheduler> ContinuationAdderTrait<TScheduler, ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler>> for ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TScheduler: SchedulerTrait { fn add_continuation<TTask>(self, continuation: TTask) -> ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TTask: 'static + Task<TScheduler::TTaskBoxParam> { let continuation_box = Box::new(continuation); self.add_continuation_box(continuation_box) } fn add_continuation_box(self, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> { let mut mut_self = self; mut_self.continuation_boxes.push(continuation_box); mut_self } fn add_continuation_boxes<TTaskBoxIntoIterator>(self, continuation_boxes: TTaskBoxIntoIterator) -> ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TTaskBoxIntoIterator: TaskBoxIntoIterator<TScheduler::TTaskBoxParam> { let mut mut_self = self; for continuation_box in continuation_boxes { mut_self.continuation_boxes.push(continuation_box); } mut_self } } impl <'a, TScheduler> EndScheduleTrait for ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TScheduler: SchedulerTrait { type TEndScheduleReturn = TScheduler::TScheduleMultipleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn { self.convert_to_end_schedule_multiple_task_boxes_multiple_continuation_boxes() .end_schedule() } } <file_sep>use fluent::ContinuationAdderOneTaskBoxMultipleContinuationBoxes; use fluent::ContinuationAdderTrait; use fluent::EndScheduleOneTaskBoxOneContinuationBox; use fluent::EndScheduleTrait; use SchedulerTrait; use Task; use TaskBox; use TaskBoxIntoIterator; pub struct ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, task_box: TaskBox<TScheduler::TTaskBoxParam>, continuation_box: TaskBox<TScheduler::TTaskBoxParam>, } impl <'a, TScheduler> ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler> where TScheduler: SchedulerTrait { pub fn new(scheduler: &'a TScheduler, task_box: TaskBox<TScheduler::TTaskBoxParam>, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler> { ContinuationAdderOneTaskBoxOneContinuationBox { scheduler: scheduler, task_box: task_box, continuation_box: continuation_box } } fn convert_to_continuation_adder_one_task_multiple_continuations(self) -> ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler> { ContinuationAdderOneTaskBoxMultipleContinuationBoxes::new(self.scheduler, self.task_box, Vec::new()) } fn convert_to_end_schedule_one_task_box_one_continuation_box(self) -> EndScheduleOneTaskBoxOneContinuationBox<'a, TScheduler> { EndScheduleOneTaskBoxOneContinuationBox::new(self.scheduler, self.task_box, self.continuation_box) } } impl <'a, TScheduler> ContinuationAdderTrait<TScheduler, ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler>> for ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler> where TScheduler: SchedulerTrait { fn add_continuation<TTask>(self, continuation: TTask) -> ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler> where TTask: 'static + Task<TScheduler::TTaskBoxParam> { let continuation_box = Box::new(continuation); self.add_continuation_box(continuation_box) } fn add_continuation_box(self, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler> { self.convert_to_continuation_adder_one_task_multiple_continuations() .add_continuation_box(continuation_box) } fn add_continuation_boxes<TTaskBoxIntoIterator>(self, continuation_boxes: TTaskBoxIntoIterator) -> ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler> where TTaskBoxIntoIterator: TaskBoxIntoIterator<TScheduler::TTaskBoxParam> { self.convert_to_continuation_adder_one_task_multiple_continuations() .add_continuation_boxes(continuation_boxes) } } impl <'a, TScheduler> EndScheduleTrait for ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler> where TScheduler: SchedulerTrait { type TEndScheduleReturn = TScheduler::TScheduleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn { self.convert_to_end_schedule_one_task_box_one_continuation_box() .end_schedule() } } <file_sep>use Task; pub type TaskBox<TScheduler> = Box<Task<TScheduler, Output = ()>>; <file_sep>use deque::{ BufferPool, Stealer, Stolen, Worker }; use rand::Rng; use rand::StdRng; use SchedulerTrait; use TaskBox; use TaskBoxIntoIterator; pub struct Scheduler<TRng> where TRng: Rng + Send { worker: Worker<TaskBox<Scheduler<TRng>>>, stealers: Vec<Stealer<TaskBox<Scheduler<TRng>>>>, rng: TRng, } impl <TRng> Scheduler<TRng> where TRng: Rng + Send { pub fn new<TStealerIterator>(worker: Worker<TaskBox<Scheduler<TRng>>>, stealers: TStealerIterator, rng: TRng) -> Scheduler<TRng> where TStealerIterator: IntoIterator<Item = Stealer<TaskBox<Scheduler<TRng>>>> { Scheduler { worker: worker, stealers: stealers.into_iter().collect(), rng: rng } } pub fn new_batch_from_rngs<TRangeIntoIterator>(rngs: TRangeIntoIterator) -> Vec<Scheduler<TRng>> where TRangeIntoIterator: IntoIterator<Item = TRng> { let buffer_pool = BufferPool::<TaskBox<Scheduler<TRng>>>::new(); let (rng_and_worker_vec, stealers): (Vec<(TRng, Worker<TaskBox<Scheduler<TRng>>>)>, Vec<Stealer<TaskBox<Scheduler<TRng>>>>) = { rngs.into_iter() .map( |rng| { let (worker, stealer) = buffer_pool.deque(); ((rng, worker), stealer) } ).unzip() }; let schedulers = rng_and_worker_vec.into_iter() .map(|(rng, worker)| Scheduler::new(worker, stealers.clone(), rng)) .collect(); schedulers } pub fn run(&mut self) { while { while self.try_run_worker() { } self.try_run_stealers() } { } } fn try_run_worker(&mut self) -> bool { match self.worker.pop() { Some(task_box) => { task_box.call_box((&self,)); true }, None => { false }, } } fn try_run_stealers(&mut self) -> bool { let num_stealers = self.stealers.len(); let start_index = self.rng.gen_range(0, num_stealers); self.stealers.iter() .cycle() .skip(start_index) .take(num_stealers) .any(|stealer| self.try_run_stealer(stealer)) } fn try_run_stealer(&self, stealer: &Stealer<TaskBox<Scheduler<TRng>>>) -> bool { while { match stealer.steal() { Stolen::Empty => { // No tasks to steal. Stop trying for this stealer. false }, Stolen::Abort => { // Thread contention. Keep trying until the other thread yields. true }, Stolen::Data(data) => { // Successful steal. Run task and stop trying. data.call_box((&self,)); return true; }, } } { } false } } impl Scheduler<StdRng> { pub fn new_batch(num_schedulers: usize) -> Vec<Scheduler<StdRng>> { let rngs = (0..num_schedulers) .map( |_| { StdRng::new().unwrap() } ); Self::new_batch_from_rngs(rngs) } } impl <TRng> SchedulerTrait for Scheduler<TRng> where TRng: 'static + Rng + Send { type TTaskBoxParam = Scheduler<TRng>; type TScheduleReturn = (); type TScheduleMultipleReturn = (); fn schedule(&self, task_box: TaskBox<Self::TTaskBoxParam>) -> Self::TScheduleReturn { self.worker.push(task_box) } fn schedule_multiple<TTaskBoxIntoIterator>(&self, task_boxes: TTaskBoxIntoIterator) -> Self::TScheduleMultipleReturn where TTaskBoxIntoIterator: TaskBoxIntoIterator<Self::TTaskBoxParam> { for task_box in task_boxes { self.worker.push(task_box) } } } <file_sep>use fluent::EndScheduleTrait; use SchedulerTrait; use TaskBox; pub struct EndScheduleOneTaskBoxMultipleContinuationBoxes<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, task_box: TaskBox<TScheduler::TTaskBoxParam>, continuation_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, } impl <'a, TScheduler> EndScheduleOneTaskBoxMultipleContinuationBoxes<'a, TScheduler> where TScheduler: SchedulerTrait { pub fn new(scheduler: &'a TScheduler, task_box: TaskBox<TScheduler::TTaskBoxParam>, continuation_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>) -> EndScheduleOneTaskBoxMultipleContinuationBoxes<'a, TScheduler> { EndScheduleOneTaskBoxMultipleContinuationBoxes { scheduler: scheduler, task_box: task_box, continuation_boxes: continuation_boxes } } } impl <'a, TScheduler> EndScheduleTrait for EndScheduleOneTaskBoxMultipleContinuationBoxes<'a, TScheduler> where TScheduler: SchedulerTrait { type TEndScheduleReturn = TScheduler::TScheduleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn { let task_box = self.task_box; let continuation_boxes = self.continuation_boxes; let result_task = move |scheduler: &TScheduler::TTaskBoxParam| { task_box.call_box((&scheduler,)); scheduler.schedule_multiple(continuation_boxes); }; let result_task_box = Box::new(result_task); self.scheduler.schedule(result_task_box) } } <file_sep>use alloc::heap::deallocate; use std::mem::{ align_of_val, size_of_val }; use std::ptr::{ read, Shared }; use std::sync::atomic::{ AtomicUsize, Ordering }; pub struct DecayPtr<T> { _ptr: Shared<DecayInner<T>>, has_decayed: bool, } struct DecayInner<T> { decay_count: AtomicUsize, data: T, } unsafe impl<T: Send> Send for DecayPtr<T> { } unsafe impl<T: Send> Send for DecayInner<T> { } impl<T> DecayPtr<T> { pub fn new(data: T) -> DecayPtr<T> { let inner = Box::new( DecayInner { decay_count: AtomicUsize::new(1), data: data, } ); DecayPtr { _ptr: unsafe { Shared::new(Box::into_raw(inner)) }, has_decayed: false, } } pub fn decay(mut self) -> Option<T> { assert!(!self.has_decayed, "A decay pointer cannot decay twice."); self.has_decayed = true; let should_release = self.decay_decrement() == 0; if should_release { Some(self.decay_release()) } else { None } } fn decay_decrement(&self) -> usize { let inner = self.inner_ref(); inner.decay_count.fetch_sub(1, Ordering::Acquire) } fn decay_release(self) -> T { let inner = self.inner_raw(); let result = unsafe { read(inner) }; unsafe { deallocate(inner as *mut u8, size_of_val(&*inner), align_of_val(&*inner)) }; result.data } } impl<T> DecayPtr<T> { fn inner_ref(&self) -> &DecayInner<T> { unsafe { &**self._ptr } } fn inner_raw(self) -> *mut DecayInner<T> { *self._ptr } pub fn clone(&self) ->DecayPtr<T> { assert!(!self.has_decayed, "A decay pointer cannot be cloned if it has decayed."); self.inner_ref().decay_count.fetch_add(1, Ordering::Relaxed); DecayPtr { _ptr: self._ptr, has_decayed: false, } } } impl<T> Drop for DecayPtr<T> { fn drop(&mut self) { assert!(self.has_decayed, "A decay pointer must always decay before it is dropped."); } } <file_sep>use utilities::DecayPtr; use fluent::EndScheduleTrait; use SchedulerTrait; use TaskBox; pub struct EndScheduleMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, continuation_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, } impl <'a, TScheduler> EndScheduleMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TScheduler: SchedulerTrait { pub fn new(scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, continuation_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>) -> EndScheduleMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> { EndScheduleMultipleTaskBoxesMultipleContinuationBoxes { scheduler: scheduler, task_boxes: task_boxes, continuation_boxes: continuation_boxes } } } impl <'a, TScheduler> EndScheduleTrait for EndScheduleMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TScheduler: SchedulerTrait { type TEndScheduleReturn = TScheduler::TScheduleMultipleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn { let task_boxes = self.task_boxes; let continuation_boxes = self.continuation_boxes; let decaying_continuation_boxes = DecayPtr::new(continuation_boxes); let result_tasks: Vec<_> = task_boxes .into_iter() .map( |task_box: TaskBox<TScheduler::TTaskBoxParam>| -> TaskBox<TScheduler::TTaskBoxParam> { let decaying_continuation_boxes_clone = decaying_continuation_boxes.clone(); Box::new( move |scheduler: &TScheduler::TTaskBoxParam| { task_box.call_box((&scheduler,)); if let Some(continuation_boxes) = decaying_continuation_boxes_clone.decay() { scheduler.schedule_multiple(continuation_boxes); } } ) } ).collect(); decaying_continuation_boxes.decay(); self.scheduler.schedule_multiple(result_tasks) } } <file_sep>use fluent::BeginScheduleTrait; use fluent::EmptyTaskAdderTrait; use fluent::EndScheduleTrait; use LooseContinuation; use rand::StdRng; use Scheduler; use SchedulerTrait; use std::sync::Arc; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::thread; mod fluent_tests; #[test] fn it_works() { let num_threads = 8; let num_tasks_per_thread = 500000; let schedulers = Scheduler::<StdRng>::new_batch(num_threads); let shared = Arc::new(AtomicUsize::new(0)); for scheduler in &schedulers { for _ in 0..num_tasks_per_thread { let clone = shared.clone(); let loose_continuation = LooseContinuation::<Scheduler<_>>::new() .begin_schedule() .add_task( move |_: &Scheduler<StdRng>| { clone.fetch_add(1, Ordering::Relaxed); let mut _value = 0; for i in 0..1000 { _value = i + 5; } } ) .end_schedule(); scheduler.schedule(loose_continuation); } break; } let join_handles: Vec<_> = schedulers .into_iter() .map( |mut scheduler| { thread::spawn( move || { scheduler.run(); } ) } ).collect(); for join_handle in join_handles { join_handle.join().unwrap(); } let shared_as_usize: usize = shared.load(Ordering::Relaxed); println!("{0}", shared_as_usize); } <file_sep>use fluent::EndScheduleTrait; use SchedulerTrait; use TaskBox; pub struct EndScheduleOneTaskBoxNoContinuations<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, task_box: TaskBox<TScheduler::TTaskBoxParam>, } impl <'a, TScheduler> EndScheduleOneTaskBoxNoContinuations<'a, TScheduler> where TScheduler: SchedulerTrait { pub fn new(scheduler: &'a TScheduler, task_box: TaskBox<TScheduler::TTaskBoxParam>) -> EndScheduleOneTaskBoxNoContinuations<'a, TScheduler> { EndScheduleOneTaskBoxNoContinuations { scheduler: scheduler, task_box: task_box } } } impl <'a, TScheduler> EndScheduleTrait for EndScheduleOneTaskBoxNoContinuations<'a, TScheduler> where TScheduler: SchedulerTrait { type TEndScheduleReturn = TScheduler::TScheduleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn { let task_box = self.task_box; self.scheduler.schedule(task_box) } } <file_sep># taskify An efficient scheduler written in rust. ## Summary This scheduler has a few fundamental goals: * It is general purpose. * It does not use any locks. * It is efficient. <file_sep>use fluent::ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes; use fluent::ContinuationAdderMultipleTaskBoxesOneContinuationBox; use fluent::ContinuationAdderOneTaskBoxMultipleContinuationBoxes; use fluent::ContinuationAdderOneTaskBoxOneContinuationBox; use fluent::EmptyTaskAdderTrait; use SchedulerTrait; use Task; use fluent::TaskAdderMultipleTaskBoxes; use fluent::TaskAdderOneTaskBox; use fluent::TaskAdderTrait; use TaskBox; use TaskBoxIntoIterator; pub struct EmptyTaskAdder<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, } impl <'a, TScheduler> EmptyTaskAdder<'a, TScheduler> where TScheduler: SchedulerTrait { pub fn new(scheduler: &'a TScheduler) -> EmptyTaskAdder<'a, TScheduler> { EmptyTaskAdder { scheduler: scheduler } } fn convert_to_task_adder_multiple_task_boxes(self) -> TaskAdderMultipleTaskBoxes<'a, TScheduler> { TaskAdderMultipleTaskBoxes::new(self.scheduler, Vec::new()) } fn convert_to_task_adder_one_task_box(self, task_box: TaskBox<TScheduler::TTaskBoxParam>) -> TaskAdderOneTaskBox<'a, TScheduler> { TaskAdderOneTaskBox::new(self.scheduler, task_box) } } impl <'a, TScheduler> EmptyTaskAdderTrait<TScheduler, ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler>, ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler>, TaskAdderMultipleTaskBoxes<'a, TScheduler>, TaskAdderOneTaskBox<'a, TScheduler>> for EmptyTaskAdder<'a, TScheduler> where TScheduler: SchedulerTrait { fn add_task<TTask>(self, task: TTask) -> TaskAdderOneTaskBox<'a, TScheduler> where TTask: 'static + Task<TScheduler::TTaskBoxParam> { let task_box = Box::new(task); self.add_task_box(task_box) } fn add_task_box(self, task_box: TaskBox<TScheduler::TTaskBoxParam>) -> TaskAdderOneTaskBox<'a, TScheduler> { self.convert_to_task_adder_one_task_box(task_box) } fn add_task_boxes<TTaskBoxIntoIterator>(self, task_boxes: TTaskBoxIntoIterator) -> TaskAdderMultipleTaskBoxes<'a, TScheduler> where TTaskBoxIntoIterator: TaskBoxIntoIterator<TScheduler::TTaskBoxParam> { self.convert_to_task_adder_multiple_task_boxes() .add_task_boxes(task_boxes) } } <file_sep>use fluent::ContinuationAdderTrait; use SchedulerTrait; use Task; use fluent::TaskAdderTrait; use TaskBox; use TaskBoxIntoIterator; pub trait EmptyTaskAdderTrait<TScheduler, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes, TContinuationAdderMultipleTaskBoxesOneContinuationBox, TContinuationAdderOneTaskBoxMultipleContinuationBoxes, TContinuationAdderOneTaskBoxOneContinuationBox, TTaskAdderMultipleTaskBoxes, TTaskAdderOneTaskBox> where TScheduler: SchedulerTrait, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes: ContinuationAdderTrait<TScheduler, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes>, TContinuationAdderMultipleTaskBoxesOneContinuationBox: ContinuationAdderTrait<TScheduler, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes>, TContinuationAdderOneTaskBoxMultipleContinuationBoxes: ContinuationAdderTrait<TScheduler, TContinuationAdderOneTaskBoxMultipleContinuationBoxes, TContinuationAdderOneTaskBoxMultipleContinuationBoxes>, TContinuationAdderOneTaskBoxOneContinuationBox: ContinuationAdderTrait<TScheduler, TContinuationAdderOneTaskBoxMultipleContinuationBoxes, TContinuationAdderOneTaskBoxMultipleContinuationBoxes>, TTaskAdderMultipleTaskBoxes: TaskAdderTrait<TScheduler, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes, TContinuationAdderMultipleTaskBoxesOneContinuationBox, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes, TContinuationAdderMultipleTaskBoxesOneContinuationBox, TTaskAdderMultipleTaskBoxes>, TTaskAdderOneTaskBox: TaskAdderTrait<TScheduler, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes, TContinuationAdderMultipleTaskBoxesOneContinuationBox, TContinuationAdderOneTaskBoxMultipleContinuationBoxes, TContinuationAdderOneTaskBoxOneContinuationBox, TTaskAdderMultipleTaskBoxes> { fn add_task<TTask>(self, task: TTask) -> TTaskAdderOneTaskBox where TTask: 'static + Task<TScheduler::TTaskBoxParam>; fn add_task_box(self, task_box: TaskBox<TScheduler::TTaskBoxParam>) -> TTaskAdderOneTaskBox; fn add_task_boxes<TTaskBoxIntoIterator>(self, task_boxes: TTaskBoxIntoIterator) -> TTaskAdderMultipleTaskBoxes where TTaskBoxIntoIterator: TaskBoxIntoIterator<TScheduler::TTaskBoxParam>; } <file_sep>use fluent::ContinuationAdderTrait; use fluent::EmptyTaskAdderTrait; use SchedulerTrait; use fluent::TaskAdderTrait; pub trait BeginScheduleTrait<'a, TScheduler, TContinuationAdderMultipleTasksMultipleContinuations, TContinuationAdderMultipleTasksOneContinuation, TContinuationAdderOneTaskMultipleContinuations, TContinuationAdderOneTaskOneContinuation, TEmptyTaskAdder, TTaskAdderMultipleTasks, TTaskAdderOneTask> where TScheduler: SchedulerTrait, TContinuationAdderMultipleTasksMultipleContinuations: ContinuationAdderTrait<TScheduler, TContinuationAdderMultipleTasksMultipleContinuations, TContinuationAdderMultipleTasksMultipleContinuations>, TContinuationAdderMultipleTasksOneContinuation: ContinuationAdderTrait<TScheduler, TContinuationAdderMultipleTasksMultipleContinuations, TContinuationAdderMultipleTasksMultipleContinuations>, TContinuationAdderOneTaskMultipleContinuations: ContinuationAdderTrait<TScheduler, TContinuationAdderOneTaskMultipleContinuations, TContinuationAdderOneTaskMultipleContinuations>, TContinuationAdderOneTaskOneContinuation: ContinuationAdderTrait<TScheduler, TContinuationAdderOneTaskMultipleContinuations, TContinuationAdderOneTaskMultipleContinuations>, TEmptyTaskAdder: EmptyTaskAdderTrait<TScheduler, TContinuationAdderMultipleTasksMultipleContinuations, TContinuationAdderMultipleTasksOneContinuation, TContinuationAdderOneTaskMultipleContinuations, TContinuationAdderOneTaskOneContinuation, TTaskAdderMultipleTasks, TTaskAdderOneTask>, TTaskAdderMultipleTasks: TaskAdderTrait<TScheduler, TContinuationAdderMultipleTasksMultipleContinuations, TContinuationAdderMultipleTasksOneContinuation, TContinuationAdderMultipleTasksMultipleContinuations, TContinuationAdderMultipleTasksOneContinuation, TTaskAdderMultipleTasks>, TTaskAdderOneTask: TaskAdderTrait<TScheduler, TContinuationAdderMultipleTasksMultipleContinuations, TContinuationAdderMultipleTasksOneContinuation, TContinuationAdderOneTaskMultipleContinuations, TContinuationAdderOneTaskOneContinuation, TTaskAdderMultipleTasks> { fn begin_schedule(&'a self) -> TEmptyTaskAdder; } <file_sep>#![feature(alloc)] #![feature(fnbox)] #![feature(heap_api)] #![feature(shared)] extern crate alloc; extern crate deque; extern crate rand; pub mod fluent; // An error with the compiler requires all these modules be public now. pub mod loose_continuation; pub mod scheduler; pub mod scheduler_trait; pub mod task; pub mod task_box; pub mod task_box_into_iterator; pub mod utilities; pub use loose_continuation::LooseContinuation; pub use scheduler::Scheduler; pub use scheduler_trait::SchedulerTrait; pub use task::Task; pub use task_box::TaskBox; pub use task_box_into_iterator::TaskBoxIntoIterator; #[cfg(test)] mod tests; <file_sep>use SchedulerTrait; use std::marker::PhantomData; use TaskBox; use TaskBoxIntoIterator; pub struct LooseContinuation<TScheduler> where TScheduler: SchedulerTrait { _scheduler: PhantomData<TScheduler>, } impl <TScheduler> LooseContinuation<TScheduler> where TScheduler: SchedulerTrait { pub fn new() -> LooseContinuation<TScheduler> { LooseContinuation::<TScheduler>{ _scheduler: PhantomData, } } } impl <TScheduler> SchedulerTrait for LooseContinuation<TScheduler> where TScheduler: SchedulerTrait { type TTaskBoxParam = TScheduler::TTaskBoxParam; type TScheduleReturn = TaskBox<Self::TTaskBoxParam>; type TScheduleMultipleReturn = TaskBox<Self::TTaskBoxParam>; fn schedule(&self, task_box: TaskBox<Self::TTaskBoxParam>) -> Self::TScheduleReturn { task_box } fn schedule_multiple<TTaskBoxIntoIterator>(&self, task_boxes: TTaskBoxIntoIterator) -> Self::TScheduleMultipleReturn where TTaskBoxIntoIterator: 'static + TaskBoxIntoIterator<Self::TTaskBoxParam> { Box::new( move |scheduler: &Self::TTaskBoxParam| { scheduler.schedule_multiple(task_boxes); } ) } } <file_sep>pub trait EndScheduleTrait { type TEndScheduleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn; } <file_sep>use fluent::ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes; use fluent::ContinuationAdderMultipleTaskBoxesOneContinuationBox; use fluent::ContinuationAdderOneTaskBoxMultipleContinuationBoxes; use fluent::ContinuationAdderOneTaskBoxOneContinuationBox; use fluent::ContinuationAdderTrait; use fluent::EndScheduleOneTaskBoxNoContinuations; use fluent::EndScheduleTrait; use SchedulerTrait; use Task; use fluent::TaskAdderTrait; use fluent::TaskAdderMultipleTaskBoxes; use TaskBox; use TaskBoxIntoIterator; pub struct TaskAdderOneTaskBox<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, task_box: TaskBox<TScheduler::TTaskBoxParam>, } impl <'a, TScheduler> TaskAdderOneTaskBox<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { pub fn new(scheduler: &'a TScheduler, task_box: TaskBox<TScheduler::TTaskBoxParam>) -> TaskAdderOneTaskBox<'a, TScheduler> { TaskAdderOneTaskBox { scheduler: scheduler, task_box: task_box } } fn convert_to_task_adder_multiple_tasks(self) -> TaskAdderMultipleTaskBoxes<'a, TScheduler> { let task_boxes = vec![self.task_box]; TaskAdderMultipleTaskBoxes::new(self.scheduler, task_boxes) } fn convert_to_continuation_adder_one_task_multiple_continuations(self) -> ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler> { ContinuationAdderOneTaskBoxMultipleContinuationBoxes::new(self.scheduler, self.task_box, Vec::new()) } fn convert_to_continuation_adder_one_task_one_continuation(self, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler> { ContinuationAdderOneTaskBoxOneContinuationBox::new(self.scheduler, self.task_box, continuation_box) } fn convert_to_end_schedule_one_task_box_no_continuation_boxes(self) -> EndScheduleOneTaskBoxNoContinuations<'a, TScheduler> { EndScheduleOneTaskBoxNoContinuations::new(self.scheduler, self.task_box) } } impl <'a, TScheduler> TaskAdderTrait<TScheduler, ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler>, ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler>, TaskAdderMultipleTaskBoxes<'a, TScheduler>> for TaskAdderOneTaskBox<'a, TScheduler> where TScheduler: SchedulerTrait { fn add_task<TTask>(self, task: TTask) -> TaskAdderMultipleTaskBoxes<'a, TScheduler> where TTask: 'static + Task<TScheduler::TTaskBoxParam> { let task_box = Box::new(task); self.add_task_box(task_box) } fn add_task_box(self, task_box: TaskBox<TScheduler::TTaskBoxParam>) -> TaskAdderMultipleTaskBoxes<'a, TScheduler> { self.convert_to_task_adder_multiple_tasks() .add_task_box(task_box) } fn add_task_boxes<TTaskBoxIntoIterator>(self, task_boxes: TTaskBoxIntoIterator) -> TaskAdderMultipleTaskBoxes<'a, TScheduler> where TTaskBoxIntoIterator: TaskBoxIntoIterator<TScheduler::TTaskBoxParam> { self.convert_to_task_adder_multiple_tasks() .add_task_boxes(task_boxes) } } impl <'a, TScheduler> ContinuationAdderTrait<TScheduler, ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler>> for TaskAdderOneTaskBox<'a, TScheduler> where TScheduler: SchedulerTrait { fn add_continuation<TTask>(self, continuation: TTask) -> ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler> where TTask: 'static + Task<TScheduler::TTaskBoxParam> { let continuation_box = Box::new(continuation); self.add_continuation_box(continuation_box) } fn add_continuation_box(self, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler> { self.convert_to_continuation_adder_one_task_one_continuation(continuation_box) } fn add_continuation_boxes<TTaskBoxIntoIterator>(self, continuation_boxes: TTaskBoxIntoIterator) -> ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler> where TTaskBoxIntoIterator: TaskBoxIntoIterator<TScheduler::TTaskBoxParam> { self.convert_to_continuation_adder_one_task_multiple_continuations() .add_continuation_boxes(continuation_boxes) } } impl <'a, TScheduler> EndScheduleTrait for TaskAdderOneTaskBox<'a, TScheduler> where TScheduler: SchedulerTrait { type TEndScheduleReturn = TScheduler::TScheduleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn { self.convert_to_end_schedule_one_task_box_no_continuation_boxes() .end_schedule() } } <file_sep>use fluent::*; use Scheduler; use rand::StdRng; #[test] fn schedule_one() { let num_threads = 8; let schedulers = Scheduler::<StdRng>::new_batch(num_threads); for scheduler in &schedulers { scheduler .begin_schedule() .add_task( |_: &Scheduler<StdRng>| { } ) .end_schedule(); } } <file_sep>use fluent::BeginScheduleTrait; use fluent::ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes; use fluent::ContinuationAdderMultipleTaskBoxesOneContinuationBox; use fluent::ContinuationAdderOneTaskBoxMultipleContinuationBoxes; use fluent::ContinuationAdderOneTaskBoxOneContinuationBox; use fluent::EmptyTaskAdder; use SchedulerTrait; use fluent::TaskAdderMultipleTaskBoxes; use fluent::TaskAdderOneTaskBox; pub trait SimpleBeginScheduleTrait<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { } impl <'a, TScheduler> BeginScheduleTrait<'a, TScheduler, ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler>, ContinuationAdderOneTaskBoxMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderOneTaskBoxOneContinuationBox<'a, TScheduler>, EmptyTaskAdder<'a, TScheduler>, TaskAdderMultipleTaskBoxes<'a, TScheduler>, TaskAdderOneTaskBox<'a, TScheduler>> for TScheduler where TScheduler: SimpleBeginScheduleTrait<'a, TScheduler> + SchedulerTrait { fn begin_schedule(&'a self) -> EmptyTaskAdder<'a, TScheduler> { EmptyTaskAdder::new(self) } } <file_sep>use std::boxed::FnBox; use SchedulerTrait; pub trait Task<TScheduler>: FnBox(&TScheduler) + Send where TScheduler: SchedulerTrait { } impl <TScheduler, T> Task<TScheduler> for T where TScheduler: SchedulerTrait, T: FnBox(&TScheduler) + Send { } <file_sep>use fluent::SimpleBeginScheduleTrait; use TaskBox; use TaskBoxIntoIterator; pub trait SchedulerTrait { type TTaskBoxParam: 'static + SchedulerTrait<TTaskBoxParam = Self::TTaskBoxParam>; type TScheduleReturn; type TScheduleMultipleReturn; fn schedule(&self, task_box: TaskBox<Self::TTaskBoxParam>) -> Self::TScheduleReturn; fn schedule_multiple<TTaskBoxIntoIterator>(&self, task_boxes: TTaskBoxIntoIterator) -> Self::TScheduleMultipleReturn where TTaskBoxIntoIterator: TaskBoxIntoIterator<Self::TTaskBoxParam>; } impl <'a, TScheduler, T> SimpleBeginScheduleTrait<'a, TScheduler> for T where TScheduler: 'a + SchedulerTrait, T: SchedulerTrait { } <file_sep>use fluent::ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes; use fluent::ContinuationAdderMultipleTaskBoxesOneContinuationBox; use fluent::ContinuationAdderTrait; use fluent::EndScheduleMultipleTaskBoxesNoContinuations; use fluent::EndScheduleTrait; use SchedulerTrait; use Task; use fluent::TaskAdderTrait; use TaskBox; use TaskBoxIntoIterator; pub struct TaskAdderMultipleTaskBoxes<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, } impl <'a, TScheduler> TaskAdderMultipleTaskBoxes<'a, TScheduler> where TScheduler: SchedulerTrait { pub fn new(scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>) -> TaskAdderMultipleTaskBoxes<'a, TScheduler> { TaskAdderMultipleTaskBoxes { scheduler: scheduler, task_boxes: task_boxes } } fn convert_to_continuation_adder_multiple_tasks_multiple_continuations(self) -> ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> { ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes::new(self.scheduler, self.task_boxes, Vec::new()) } fn convert_to_continuation_adder_multiple_tasks_one_continuation(self, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler> { ContinuationAdderMultipleTaskBoxesOneContinuationBox::new(self.scheduler, self.task_boxes, continuation_box) } fn convert_to_end_schedule_multiple_task_boxes_no_continuation_boxes(self) -> EndScheduleMultipleTaskBoxesNoContinuations<'a, TScheduler> { EndScheduleMultipleTaskBoxesNoContinuations::new(self.scheduler, self.task_boxes) } } impl <'a, TScheduler> TaskAdderTrait<TScheduler, ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler>, ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler>, TaskAdderMultipleTaskBoxes<'a, TScheduler>> for TaskAdderMultipleTaskBoxes<'a, TScheduler> where TScheduler: SchedulerTrait { fn add_task<TTask>(self, task: TTask) -> TaskAdderMultipleTaskBoxes<'a, TScheduler> where TTask: 'static + Task<TScheduler::TTaskBoxParam> { let task_box = Box::new(task); self.add_task_box(task_box) } fn add_task_box(self, task_box: TaskBox<TScheduler::TTaskBoxParam>) -> TaskAdderMultipleTaskBoxes<'a, TScheduler> { let mut mut_self = self; mut_self.task_boxes.push(task_box); mut_self } fn add_task_boxes<TTaskBoxIntoIterator>(self, task_boxes: TTaskBoxIntoIterator) -> TaskAdderMultipleTaskBoxes<'a, TScheduler> where TTaskBoxIntoIterator: TaskBoxIntoIterator<TScheduler::TTaskBoxParam> { let mut mut_self = self; for task_box in task_boxes { mut_self.task_boxes.push(task_box); } mut_self } } impl <'a, TScheduler> ContinuationAdderTrait<TScheduler, ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler>> for TaskAdderMultipleTaskBoxes<'a, TScheduler> where TScheduler: SchedulerTrait { fn add_continuation<TTask>(self, continuation: TTask) -> ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler> where TTask: 'static + Task<TScheduler::TTaskBoxParam> { let continuation_box = Box::new(continuation); self.add_continuation_box(continuation_box) } fn add_continuation_box(self, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler> { self.convert_to_continuation_adder_multiple_tasks_one_continuation(continuation_box) } fn add_continuation_boxes<TTaskBoxIntoIterator>(self, continuation_boxes: TTaskBoxIntoIterator) -> ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TTaskBoxIntoIterator: 'static + TaskBoxIntoIterator<TScheduler::TTaskBoxParam> { self.convert_to_continuation_adder_multiple_tasks_multiple_continuations() .add_continuation_boxes(continuation_boxes) } } impl <'a, TScheduler> EndScheduleTrait for TaskAdderMultipleTaskBoxes<'a, TScheduler> where TScheduler: SchedulerTrait { type TEndScheduleReturn = TScheduler::TScheduleMultipleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn { self.convert_to_end_schedule_multiple_task_boxes_no_continuation_boxes() .end_schedule() } } <file_sep>// An error with the compiler requires all these modules be public now. pub mod begin_schedule_trait; pub mod continuation_adder_multiple_task_boxes_multiple_continuation_boxes; pub mod continuation_adder_multiple_task_boxes_one_continuation_box; pub mod continuation_adder_one_task_box_multiple_continuation_boxes; pub mod continuation_adder_one_task_box_one_continuation_box; pub mod continuation_adder_trait; pub mod empty_task_adder; pub mod empty_task_adder_trait; pub mod end_schedule_multiple_task_boxes_multiple_continuation_boxes; pub mod end_schedule_multiple_task_boxes_no_continuations; pub mod end_schedule_multiple_task_boxes_one_continuation_box; pub mod end_schedule_one_task_box_multiple_continuation_boxes; pub mod end_schedule_one_task_box_no_continuations; pub mod end_schedule_one_task_box_one_continuation_box; pub mod end_schedule_trait; pub mod simple_begin_schedule_trait; pub mod task_adder_trait; pub mod task_adder_multiple_task_boxes; pub mod task_adder_one_task_box; pub use fluent::begin_schedule_trait::BeginScheduleTrait; pub use fluent::continuation_adder_multiple_task_boxes_multiple_continuation_boxes::ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes; pub use fluent::continuation_adder_multiple_task_boxes_one_continuation_box::ContinuationAdderMultipleTaskBoxesOneContinuationBox; pub use fluent::continuation_adder_one_task_box_multiple_continuation_boxes::ContinuationAdderOneTaskBoxMultipleContinuationBoxes; pub use fluent::continuation_adder_one_task_box_one_continuation_box::ContinuationAdderOneTaskBoxOneContinuationBox; pub use fluent::continuation_adder_trait::ContinuationAdderTrait; pub use fluent::empty_task_adder::EmptyTaskAdder; pub use fluent::empty_task_adder_trait::EmptyTaskAdderTrait; pub use fluent::end_schedule_multiple_task_boxes_multiple_continuation_boxes::EndScheduleMultipleTaskBoxesMultipleContinuationBoxes; pub use fluent::end_schedule_multiple_task_boxes_no_continuations::EndScheduleMultipleTaskBoxesNoContinuations; pub use fluent::end_schedule_multiple_task_boxes_one_continuation_box::EndScheduleMultipleTaskBoxesOneContinuationBox; pub use fluent::end_schedule_one_task_box_multiple_continuation_boxes::EndScheduleOneTaskBoxMultipleContinuationBoxes; pub use fluent::end_schedule_one_task_box_no_continuations::EndScheduleOneTaskBoxNoContinuations; pub use fluent::end_schedule_one_task_box_one_continuation_box::EndScheduleOneTaskBoxOneContinuationBox; pub use fluent::end_schedule_trait::EndScheduleTrait; pub use fluent::simple_begin_schedule_trait::SimpleBeginScheduleTrait; pub use fluent::task_adder_trait::TaskAdderTrait; pub use fluent::task_adder_multiple_task_boxes::TaskAdderMultipleTaskBoxes; pub use fluent::task_adder_one_task_box::TaskAdderOneTaskBox; <file_sep>use SchedulerTrait; use TaskBox; pub trait TaskBoxIntoIterator<TScheduler>: IntoIterator<Item = TaskBox<TScheduler>> + Send where TScheduler: SchedulerTrait { } impl <TScheduler, T> TaskBoxIntoIterator<TScheduler> for T where TScheduler: SchedulerTrait, T: IntoIterator<Item = TaskBox<TScheduler>> + Send { } <file_sep>use fluent::EndScheduleTrait; use SchedulerTrait; use TaskBox; pub struct EndScheduleOneTaskBoxOneContinuationBox<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, task_box: TaskBox<TScheduler::TTaskBoxParam>, continuation_box: TaskBox<TScheduler::TTaskBoxParam>, } impl <'a, TScheduler> EndScheduleOneTaskBoxOneContinuationBox<'a, TScheduler> where TScheduler: SchedulerTrait { pub fn new(scheduler: &'a TScheduler, task_box: TaskBox<TScheduler::TTaskBoxParam>, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> EndScheduleOneTaskBoxOneContinuationBox<'a, TScheduler> { EndScheduleOneTaskBoxOneContinuationBox { scheduler: scheduler, task_box: task_box, continuation_box: continuation_box } } } impl <'a, TScheduler> EndScheduleTrait for EndScheduleOneTaskBoxOneContinuationBox<'a, TScheduler> where TScheduler: SchedulerTrait { type TEndScheduleReturn = TScheduler::TScheduleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn { let task_box = self.task_box; let continuation_box = self.continuation_box; let complete_task = move |scheduler: &TScheduler::TTaskBoxParam| { task_box.call_box((&scheduler,)); continuation_box.call_box((&scheduler,)); }; let complete_task_box = Box::new(complete_task); self.scheduler.schedule(complete_task_box) } } <file_sep>mod decay_ptr; pub use utilities::decay_ptr::DecayPtr; <file_sep>use fluent::ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes; use fluent::ContinuationAdderTrait; use fluent::EndScheduleMultipleTaskBoxesOneContinuationBox; use fluent::EndScheduleTrait; use SchedulerTrait; use Task; use TaskBox; use TaskBoxIntoIterator; pub struct ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, continuation_box: TaskBox<TScheduler::TTaskBoxParam>, } impl <'a, TScheduler> ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler> where TScheduler: SchedulerTrait { pub fn new(scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler> { ContinuationAdderMultipleTaskBoxesOneContinuationBox { scheduler: scheduler, task_boxes: task_boxes, continuation_box: continuation_box } } fn convert_to_continuation_adder_multiple_tasks_multiple_continuations(self) -> ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> { let continuation_boxes = vec![self.continuation_box]; ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes::new(self.scheduler, self.task_boxes, continuation_boxes) } fn convert_to_end_schedule_multiple_task_boxes_one_continuation_box(self) -> EndScheduleMultipleTaskBoxesOneContinuationBox<'a, TScheduler> { EndScheduleMultipleTaskBoxesOneContinuationBox::new(self.scheduler, self.task_boxes, self.continuation_box) } } impl <'a, TScheduler> ContinuationAdderTrait<TScheduler, ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler>, ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler>> for ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler> where TScheduler: SchedulerTrait { fn add_continuation<TTask>(self, continuation: TTask) -> ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TTask: 'static + Task<TScheduler::TTaskBoxParam> { let continuation_box = Box::new(continuation); self.add_continuation_box(continuation_box) } fn add_continuation_box(self, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> { self.convert_to_continuation_adder_multiple_tasks_multiple_continuations() .add_continuation_box(continuation_box) } fn add_continuation_boxes<TTaskBoxIntoIterator>(self, continuation_boxes: TTaskBoxIntoIterator) -> ContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes<'a, TScheduler> where TTaskBoxIntoIterator: TaskBoxIntoIterator<TScheduler::TTaskBoxParam> { self.convert_to_continuation_adder_multiple_tasks_multiple_continuations() .add_continuation_boxes(continuation_boxes) } } impl <'a, TScheduler> EndScheduleTrait for ContinuationAdderMultipleTaskBoxesOneContinuationBox<'a, TScheduler> where TScheduler: SchedulerTrait { type TEndScheduleReturn = TScheduler::TScheduleMultipleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn { self.convert_to_end_schedule_multiple_task_boxes_one_continuation_box() .end_schedule() } } <file_sep>use fluent::EndScheduleTrait; use SchedulerTrait; use Task; use TaskBox; use TaskBoxIntoIterator; pub trait ContinuationAdderTrait<TScheduler, TContinuationAdderMultipleContinuationBoxes, TContinuationAdderOneContinuationBox>: EndScheduleTrait where TScheduler: SchedulerTrait, TContinuationAdderMultipleContinuationBoxes: ContinuationAdderTrait<TScheduler, TContinuationAdderMultipleContinuationBoxes, TContinuationAdderMultipleContinuationBoxes>, TContinuationAdderOneContinuationBox: ContinuationAdderTrait<TScheduler, TContinuationAdderMultipleContinuationBoxes, TContinuationAdderMultipleContinuationBoxes> { fn add_continuation<TTask>(self, continuation: TTask) -> TContinuationAdderOneContinuationBox where TTask: 'static + Task<TScheduler::TTaskBoxParam>; fn add_continuation_box(self, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> TContinuationAdderOneContinuationBox; fn add_continuation_boxes<TTaskBoxIntoIterator>(self, continuation_boxes: TTaskBoxIntoIterator) -> TContinuationAdderMultipleContinuationBoxes where TTaskBoxIntoIterator: TaskBoxIntoIterator<TScheduler::TTaskBoxParam>; } <file_sep>use fluent::EndScheduleTrait; use SchedulerTrait; use TaskBox; pub struct EndScheduleMultipleTaskBoxesNoContinuations<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, } impl <'a, TScheduler> EndScheduleMultipleTaskBoxesNoContinuations<'a, TScheduler> where TScheduler: SchedulerTrait { pub fn new(scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>) -> EndScheduleMultipleTaskBoxesNoContinuations<'a, TScheduler> { EndScheduleMultipleTaskBoxesNoContinuations { scheduler: scheduler, task_boxes: task_boxes } } } impl <'a, TScheduler> EndScheduleTrait for EndScheduleMultipleTaskBoxesNoContinuations<'a, TScheduler> where TScheduler: SchedulerTrait { type TEndScheduleReturn = TScheduler::TScheduleMultipleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn { let task_boxes = self.task_boxes; self.scheduler.schedule_multiple(task_boxes) } } <file_sep>use fluent::ContinuationAdderTrait; use fluent::EndScheduleTrait; use SchedulerTrait; use Task; use TaskBox; use TaskBoxIntoIterator; pub trait TaskAdderTrait<TScheduler, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes, TContinuationAdderMultipleTaskBoxesOneContinuationBox, TContinuationAdderOneTaskBoxMultipleContinuationBoxes, TContinuationAdderOneTaskBoxOneContinuationBox, TTaskAdderMultipleTaskBoxes>: ContinuationAdderTrait<TScheduler, TContinuationAdderOneTaskBoxMultipleContinuationBoxes, TContinuationAdderOneTaskBoxOneContinuationBox> + EndScheduleTrait where TScheduler: SchedulerTrait, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes: ContinuationAdderTrait<TScheduler, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes>, TContinuationAdderMultipleTaskBoxesOneContinuationBox: ContinuationAdderTrait<TScheduler, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes>, TContinuationAdderOneTaskBoxMultipleContinuationBoxes: ContinuationAdderTrait<TScheduler, TContinuationAdderOneTaskBoxMultipleContinuationBoxes, TContinuationAdderOneTaskBoxMultipleContinuationBoxes>, TContinuationAdderOneTaskBoxOneContinuationBox: ContinuationAdderTrait<TScheduler, TContinuationAdderOneTaskBoxMultipleContinuationBoxes, TContinuationAdderOneTaskBoxMultipleContinuationBoxes>, TTaskAdderMultipleTaskBoxes: TaskAdderTrait<TScheduler, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes, TContinuationAdderMultipleTaskBoxesOneContinuationBox, TContinuationAdderMultipleTaskBoxesMultipleContinuationBoxes, TContinuationAdderMultipleTaskBoxesOneContinuationBox, TTaskAdderMultipleTaskBoxes> { fn add_task<TTask>(self, task: TTask) -> TTaskAdderMultipleTaskBoxes where TTask: 'static + Task<TScheduler::TTaskBoxParam>; fn add_task_box(self, task_box: TaskBox<TScheduler::TTaskBoxParam>) -> TTaskAdderMultipleTaskBoxes; fn add_task_boxes<TTaskBoxIntoIterator>(self, task_boxes: TTaskBoxIntoIterator) -> TTaskAdderMultipleTaskBoxes where TTaskBoxIntoIterator: TaskBoxIntoIterator<TScheduler::TTaskBoxParam>; } <file_sep>use utilities::DecayPtr; use fluent::EndScheduleTrait; use SchedulerTrait; use TaskBox; pub struct EndScheduleMultipleTaskBoxesOneContinuationBox<'a, TScheduler> where TScheduler: 'a + SchedulerTrait { scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, continuation_box: TaskBox<TScheduler::TTaskBoxParam>, } impl <'a, TScheduler> EndScheduleMultipleTaskBoxesOneContinuationBox<'a, TScheduler> where TScheduler: SchedulerTrait { pub fn new(scheduler: &'a TScheduler, task_boxes: Vec<TaskBox<TScheduler::TTaskBoxParam>>, continuation_box: TaskBox<TScheduler::TTaskBoxParam>) -> EndScheduleMultipleTaskBoxesOneContinuationBox<'a, TScheduler> { EndScheduleMultipleTaskBoxesOneContinuationBox { scheduler: scheduler, task_boxes: task_boxes, continuation_box: continuation_box } } } impl <'a, TScheduler> EndScheduleTrait for EndScheduleMultipleTaskBoxesOneContinuationBox<'a, TScheduler> where TScheduler: SchedulerTrait { type TEndScheduleReturn = TScheduler::TScheduleMultipleReturn; fn end_schedule(self) -> Self::TEndScheduleReturn { let task_boxes = self.task_boxes; let continuation_box = self.continuation_box; let decaying_continuation_box = DecayPtr::new(continuation_box); let result_tasks: Vec<_> = task_boxes .into_iter() .map( |task_box: TaskBox<TScheduler::TTaskBoxParam>| -> TaskBox<TScheduler::TTaskBoxParam> { let decaying_continuation_box_clone = decaying_continuation_box.clone(); Box::new( move |scheduler: &TScheduler::TTaskBoxParam| { task_box.call_box((&scheduler,)); if let Some(continuation_box) = decaying_continuation_box_clone.decay() { scheduler.schedule(continuation_box); } } ) } ).collect(); decaying_continuation_box.decay(); self.scheduler.schedule_multiple(result_tasks) } } <file_sep>[package] name = "taskify" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] [dependencies] deque = "0.2.3" rand = "0.3.11"
a515bd525430b3d0b07a16665b51f87adb06b56c
[ "Markdown", "Rust", "TOML" ]
32
Rust
Tyleo/taskify
a6940ab7928d29c0280125ff8f2eb0a5440dca01
6db6d5cc85581e6c3ea0f794b0351f49034414f8
refs/heads/master
<repo_name>npke/proxy-server<file_sep>/index.js let http = require('http'); let request = require('request'); let url = require('url'); let path = require('path'); let fs = require('fs'); let argv = require('yargs') .usage('Usage: node $0 [options]') .default('host', '127.0.0.1:8000') .alias('p', 'port') .describe('p', 'Specify a forwarding port') .alias('x', 'host') .describe('x', 'Specify a forwarding host') .alias('e', 'exec') .describe('e', 'Specify a process to proxy instead') .alias('l', 'log') .describe('l', 'Specify a output log file') .help('h') .alias('h', 'help') .describe('h', 'Show help') .example('$0 -p 8001 -h google.com') .epilog('copyright 2016') .argv; let exec = require('child_process').exec; let port = argv.port || (argv.host === '127.0.0.1' ? 8000 : 80); let destinationUrl = url.format({ protocol: 'http', host: argv.host, port: port }); let execCommand = argv.exec; if (execCommand) { execCommand = `${argv.exec} ${argv._.join(' ')}`; exec(execCommand, (err, stdout) => { if (err) { console.log ('Oops! Something went wrong!'); return; } console.log(stdout); }) return; } if (argv.url) destinationUrl = 'http://' + argv.url; let logPath = argv.log && path.join(__dirname, argv.log); let logStream = logPath ? fs.createWriteStream(logPath) : process.stdout; // Echo server let echoServer = http.createServer((req, res) => { console.log('\n\n---Echo server---'); process.stdout.write('\nRequest Header: \n' + JSON.stringify(req.headers)); for (let header in req.headers) { res.setHeader(header, req.headers[header]); } req.pipe(res); }); echoServer.listen(8000, () => { console.log('\n->Echo server running at http://localhost:8000 (http://127.0.0.1:8000)\n'); }); // Proxy server let proxyServer = http.createServer((req, res) => { let url = destinationUrl; if (req.headers['x-destination-url']) { url = 'http://' + req.headers['x-destination-url']; } console.log('\n\n---Proxy Server---'); console.log(`Proxying request to: ${url + req.url}`); let options = { headers: req.headers, url: `${url}${req.url}` } options.method = req.method; let outboundResponse = request(options); req.pipe(outboundResponse); outboundResponse.pipe(res); logStream.write('\nRequest Header: \n' + JSON.stringify(req.headers)); logStream.write(JSON.stringify(outboundResponse.headers)); logStream.write('\n\nResponse: \n'); outboundResponse.pipe(logStream, {end: false}); }); proxyServer.listen(8001, () => { console.log('->Proxy server running at http://localhost:8001 (http://127.0.0.1:8001)'); console.log('-->Default destination: ' + destinationUrl); console.log('-->Default log stream: ' + (logPath ? logPath : 'stdout')); });
fe068032eb0c1279b37acc11341cfcc4bf4fec9a
[ "JavaScript" ]
1
JavaScript
npke/proxy-server
571f30105cbaaabd8ed3c6e6af0c6f6ff9d2f6bf
bfc464e93208aafb6d97f694b64e3c32d884a93b
refs/heads/master
<repo_name>Doldge/crypto-pals-answers<file_sep>/challenge_set_1/answers.py #! /usr/bin/python # Challenge 2+ & conversion of bytes import struct # Challenge 3 import string def find_ngrams(input_list, n): return zip(*[input_list[i:] for i in range(n)]) def xor(a_byte, b_byte): return struct.pack('B', (ord(a_byte) ^ ord(b_byte))) def character_frequency(input_str): """ Takes an input string and determines the chi^2 value for it's contents. The chi^2 value is a kind of 'score' of the character frequency for the contents of a string. higher-scores mean the string is more likely english. """ expected_character_frequency = { 'a': 8.167, 'b': 1.492, 'c': 2.782, 'd': 4.253, 'e': 12.702, 'f': 2.228, 'g': 2.015, 'h': 6.094, 'i': 6.966, 'j': 0.153, 'k': 0.772, 'l': 4.025, 'm': 2.406, 'n': 6.749, 'o': 7.507, 'p': 1.929, 'q': 0.095, 'r': 5.987, 's': 6.327, 't': 9.056, 'u': 2.758, 'v': 0.978, 'w': 2.360, 'x': 0.150, 'y': 1.974, 'z': 0.074, # FIXME for challenge 4 I've had to fudge this list by including the # below space character in order to ensure the score alg chose the # correct sentance. The current value (5.00) is probably a tad high. ' ': 5.00 } occurance_count = {char: 0 for char in string.ascii_lowercase+' '} ignored = 0 for character in input_str: if character in string.ascii_letters + ' ': occurance_count[character.lower()] += 1 else: ignored += 1 chi_squared = 0 length_of_input = len(input_str) if ignored == length_of_input: return 0 for char, occurance in occurance_count.items(): expected = ( float(length_of_input - ignored) * expected_character_frequency[char] ) if not expected: # Sometimes the expected value is zero. print(( length_of_input, ignored, expected_character_frequency[char] )) continue difference = occurance - expected chi_squared += difference * difference / expected return chi_squared def challenge_1(): print('\nChallenge 1') expected_output = \ 'SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t' hex_input = \ '49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736\ f6e6f7573206d757368726f6f6d' base64_output = hex_input.decode('hex').encode('base64') # Theres a new line character at the end of the string that doesn't appear # to be in the expected output string. just strip it. base64_output = base64_output.strip() print('OUTPUT: {}'.format(base64_output)) print('EXPECTED: {}'.format(expected_output)) print('PASS [{}]'.format(base64_output == expected_output)) def challenge_2(): print('\nChallenge 2') expected_output = '746865206b696420646f6e277420706c6179' hex_input1 = '1c0111001f010100061a024b53535009181c' hex_input2 = '686974207468652062756c6c277320657965' def xor(a_list, b_list): obuf = b'' for a_byte, b_byte in zip(a_list, b_list): obuf += struct.pack('B', (ord(a_byte) ^ ord(b_byte))) return obuf.encode('hex') answer = xor(hex_input1.decode('hex'), hex_input2.decode('hex')) print('OUTPUT: {}'.format(answer.decode('hex'))) print('EXPECTED: {}'.format(expected_output.decode('hex'))) print('PASS [{}]'.format(answer == expected_output)) def challenge_3(): print('\nChallenge 3') hex_input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a3\ 93b3736' def xor(a_byte, b_list): obuf = b'' for b_byte in b_list: obuf += struct.pack('B', (ord(a_byte) ^ ord(b_byte))) return obuf start_byte = b'\x00' results = [] while start_byte != b'\xff': output = xor(start_byte, hex_input.decode('hex')) score = character_frequency(output) results.append((score, output)) start_byte = struct.pack('B', ord(start_byte) + 1) results.sort(key=lambda x: x[0], reverse=True) print('OUTPUT: {}'.format(results[0][1])) def challenge_4(): print('\nChallenge 4') def xor(a_byte, b_list): obuf = b'' for b_byte in b_list: obuf += struct.pack('B', (ord(a_byte) ^ ord(b_byte))) return obuf scored_output = [] raw_ = '' with open('4.txt', 'r') as f: raw_ = f.read() for line in raw_.split(): buf = line.decode('hex') start_byte = b'\x00' count = (16 * 16) - 1 while count: output = xor(start_byte, buf) score = character_frequency(output) scored_output.append((score, output)) start_byte = struct.pack('B', ord(start_byte) + 1) count -= 1 scored_output.sort(key=lambda x: x[0], reverse=True) print(scored_output[0][1]) def challenge_5(): print('\nChallenge 5') expected_output = '0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343\ c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b202831652\ 86326302e27282f' input_str = """Burning 'em, if you ain't quick and nimble I go crazy when I hear a cymbal""" KEY = 'ICE' pointer = 0 obuf = b'' for char in input_str: obuf += xor(KEY[pointer % 3], char) pointer += 1 print('PASS [{}]'.format(obuf.encode('hex') == expected_output)) def str2bits(s=''): return [bin(ord(x))[2:].zfill(8) for x in s] def hamming_distance(a_bits, b_bits): count = 0 _a = ''.join(a_bits) _b = ''.join(b_bits) for i, j in zip(_a, _b): if i != j: count += 1 return count def challenge_6(): print('\nChallenge 6') # Test our hamming code works test_str1 = 'this is a test' test_str2 = 'wokka wokka!!!' test_res = hamming_distance(str2bits(test_str1), str2bits(test_str2)) print('HAMMING TEST PASS [{}]'.format(test_res == 37)) # read the input file input_data = '' with open('6.txt', 'r') as f: input_data = f.read() input_data = input_data.decode('base64') input_data_bin = str2bits(input_data) # find a key_size key_list = [] for key_size in range(2, 40): block_1 = input_data_bin[:key_size] block_2 = input_data_bin[key_size:key_size*2] distance = float(hamming_distance(block_1, block_2)) normalized = distance / key_size key_list.append((normalized, key_size)) key_list.sort(key=lambda x: x[0]) print(key_list) key_size = key_list[1] # break the input into blocks of key_size blocks = [] last_i = 0 for i, byte in enumerate(input_data_bin): if i != 0 and i % key_size == 0: blocks.append(input_data_bin[last_i:i]) last_i = i # transpose the blocks transposed_blocks = [] i = 0 while i <= key_size: t_block = [] for block in blocks: t_block.append(block[i]) transposed_blocks.append(t_block) i += 1 # solve each block as if it were an xor. if __name__ == '__main__': challenge_1() challenge_2() challenge_3() challenge_4() challenge_5() challenge_6()
245ff2244bae6d354557df9501974c0ad6e400c1
[ "Python" ]
1
Python
Doldge/crypto-pals-answers
3ef67b5560b2a61b48f93adc7de372510cfb398f
b8add293c9c5614be0d99981df84df64041f9d59
refs/heads/master
<repo_name>Abhishek-Nagarkoti/aws-sdk-go<file_sep>/private/model/api/shape_marshal.go // +build codegen package api import ( "bytes" "fmt" "strings" "text/template" ) // MarshalShapeGoCode renders the shape's MarshalFields method with marshalers // for each field within the shape. A string is returned of the rendered Go code. // // Will panic if error. func MarshalShapeGoCode(s *Shape) string { w := &bytes.Buffer{} if err := marshalShapeTmpl.Execute(w, s); err != nil { panic(fmt.Sprintf("failed to render shape's fields marshaler, %v", err)) } return w.String() } // MarshalShapeRefGoCode renders protocol encode for the shape ref's type. // // Will panic if error. func MarshalShapeRefGoCode(refName string, ref *ShapeRef, context *Shape) string { if ref.XMLAttribute { return "// Skipping " + refName + " XML Attribute." } if context.IsRefPayloadReader(refName, ref) { if strings.HasSuffix(context.ShapeName, "Output") { return "// Skipping " + refName + " Output type's body not valid." } } mRef := marshalShapeRef{ Name: refName, Ref: ref, Context: context, } switch mRef.Location() { case "StatusCode": return "// ignoring invalid encode state, StatusCode. " + refName } w := &bytes.Buffer{} if err := marshalShapeRefTmpl.ExecuteTemplate(w, "encode field", mRef); err != nil { panic(fmt.Sprintf("failed to marshal shape ref, %s, %v", ref.Shape.Type, err)) } return w.String() } var marshalShapeTmpl = template.Must(template.New("marshalShapeTmpl").Funcs( map[string]interface{}{ "MarshalShapeRefGoCode": MarshalShapeRefGoCode, }, ).Parse(` {{ $shapeName := $.ShapeName -}} // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s *{{ $shapeName }}) MarshalFields(e protocol.FieldEncoder) error { {{ range $name, $ref := $.MemberRefs -}} {{ MarshalShapeRefGoCode $name $ref $ }} {{ end }} return nil } {{ if $.UsedInList -}} func encode{{ $shapeName }}List(vs []*{{ $shapeName }}) func(protocol.ListEncoder) { return func(le protocol.ListEncoder) { for _, v := range vs { le.ListAddFields(v) } } } {{- end }} {{ if $.UsedInMap -}} func encode{{ $shapeName }}Map(vs map[string]*{{ $shapeName }}) func(protocol.MapEncoder) { return func(me protocol.MapEncoder) { for k, v := range vs { me.MapSetFields(k, v) } } } {{- end }} `)) var marshalShapeRefTmpl = template.Must(template.New("marshalShapeRefTmpl").Parse(` {{ define "encode field" -}} {{ if $.IsIdempotencyToken -}} {{ template "idempotency token" $ }} { v := {{ $.Name }} {{ else -}} if {{ template "is ref set" $ }} { v := {{ template "ref value" $ }} {{- end }} {{ if $.HasAttributes -}} {{ template "attributes" $ }} {{- end }} e.Set{{ $.MarshalerType }}(protocol.{{ $.Location }}Target, "{{ $.LocationName }}", {{ template "marshaler" $ }}, {{ template "metadata" $ }}) } {{- end }} {{ define "marshaler" -}} {{- if $.IsShapeType "list" -}} {{- $helperName := $.EncodeHelperName "list" -}} {{- if $helperName -}} {{ $helperName }} {{- else -}} func(le protocol.ListEncoder) { {{ $memberRef := $.ListMemberRef -}} for _, item := range v { v := {{ if $memberRef.Ref.UseIndirection }}*{{ end }}item le.ListAdd{{ $memberRef.MarshalerType }}({{ template "marshaler" $memberRef }}) } } {{- end -}} {{- else if $.IsShapeType "map" -}} {{- $helperName := $.EncodeHelperName "map" -}} {{- if $helperName -}} {{ $helperName }} {{- else -}} func(me protocol.MapEncoder) { {{ $valueRef := $.MapValueRef -}} for k, item := range v { v := {{ if $valueRef.Ref.UseIndirection }}*{{ end }}item me.MapSet{{ $valueRef.MarshalerType }}(k, {{ template "marshaler" $valueRef }}) } } {{- end -}} {{- else if $.IsShapeType "structure" -}} v {{- else if $.IsShapeType "timestamp" -}} protocol.TimeValue{V: v, Format: {{ $.TimeFormat }} } {{- else if $.IsShapeType "jsonvalue" -}} protocol.JSONValue{V: v {{ if eq $.Location "Header" }}, Base64: true{{ end }} } {{- else if $.IsPayloadStream -}} protocol.{{ $.GoType }}{{ $.MarshalerType }}{V:v} {{- else -}} protocol.{{ $.GoType }}{{ $.MarshalerType }}(v) {{- end -}} {{- end }} {{ define "metadata" -}} protocol.Metadata{ {{- if $.IsFlattened -}} Flatten: true, {{- end -}} {{- if $.HasAttributes -}} Attributes: attrs, {{- end -}} {{- if $.XMLNamespacePrefix -}} XMLNamespacePrefix: "{{ $.XMLNamespacePrefix }}", {{- end -}} {{- if $.XMLNamespaceURI -}} XMLNamespaceURI: "{{ $.XMLNamespaceURI }}", {{- end -}} {{- if $.ListLocationName -}} ListLocationName: "{{ $.ListLocationName }}", {{- end -}} {{- if $.MapLocationNameKey -}} MapLocationNameKey: "{{ $.MapLocationNameKey }}", {{- end -}} {{- if $.MapLocationNameValue -}} MapLocationNameValue: "{{ $.MapLocationNameValue }}", {{- end -}} } {{- end }} {{ define "ref value" -}} {{ if $.Ref.UseIndirection }}*{{ end }}s.{{ $.Name }} {{- end}} {{ define "is ref set" -}} {{ $isList := $.IsShapeType "list" -}} {{ $isMap := $.IsShapeType "map" -}} {{- if or $isList $isMap -}} len(s.{{ $.Name }}) > 0 {{- else -}} s.{{ $.Name }} != nil {{- end -}} {{- end }} {{ define "attributes" -}} attrs := make([]protocol.Attribute, 0, {{ $.NumAttributes }}) {{ range $name, $child := $.ChildrenRefs -}} {{ if $child.Ref.XMLAttribute -}} if s.{{ $.Name }}.{{ $name }} != nil { v := {{ if $child.Ref.UseIndirection }}*{{ end }}s.{{ $.Name }}.{{ $name }} attrs = append(attrs, protocol.Attribute{Name: "{{ $child.LocationName }}", Value: {{ template "marshaler" $child }}, Meta: {{ template "metadata" $child }}}) } {{- end }} {{- end }} {{- end }} {{ define "idempotency token" -}} var {{ $.Name }} string if {{ template "is ref set" $ }} { {{ $.Name }} = {{ template "ref value" $ }} } else { {{ $.Name }} = protocol.GetIdempotencyToken() } {{- end }} `)) type marshalShapeRef struct { Name string Ref *ShapeRef Context *Shape } func (r marshalShapeRef) ListMemberRef() marshalShapeRef { return marshalShapeRef{ Name: r.Name + "ListMember", Ref: &r.Ref.Shape.MemberRef, Context: r.Ref.Shape, } } func (r marshalShapeRef) MapValueRef() marshalShapeRef { return marshalShapeRef{ Name: r.Name + "MapValue", Ref: &r.Ref.Shape.ValueRef, Context: r.Ref.Shape, } } func (r marshalShapeRef) ChildrenRefs() map[string]marshalShapeRef { children := map[string]marshalShapeRef{} for name, ref := range r.Ref.Shape.MemberRefs { children[name] = marshalShapeRef{ Name: name, Ref: ref, Context: r.Ref.Shape, } } return children } func (r marshalShapeRef) IsShapeType(typ string) bool { return r.Ref.Shape.Type == typ } func (r marshalShapeRef) IsPayloadStream() bool { return r.Context.IsRefPayloadReader(r.Name, r.Ref) } func (r marshalShapeRef) MarshalerType() string { switch r.Ref.Shape.Type { case "list": return "List" case "map": return "Map" case "structure": return "Fields" default: // Streams have a special case if r.Context.IsRefPayload(r.Name) { return "Stream" } return "Value" } } func (r marshalShapeRef) EncodeHelperName(typ string) string { if r.Ref.Shape.Type != typ { return "" } var memberRef marshalShapeRef switch r.Ref.Shape.Type { case "map": memberRef = r.MapValueRef() case "list": memberRef = r.ListMemberRef() default: return "" } switch memberRef.Ref.Shape.Type { case "list", "map": return "" case "structure": shapeName := memberRef.Ref.Shape.ShapeName return "encode" + shapeName + strings.Title(typ) + "(v)" default: return "protocol.Encode" + memberRef.GoType() + strings.Title(typ) + "(v)" } } func (r marshalShapeRef) GoType() string { switch r.Ref.Shape.Type { case "boolean": return "Bool" case "string", "character": return "String" case "integer", "long": return "Int64" case "float", "double": return "Float64" case "timestamp": return "Time" case "jsonvalue": return "JSONValue" case "blob": if r.Context.IsRefPayloadReader(r.Name, r.Ref) { if strings.HasSuffix(r.Context.ShapeName, "Output") { return "ReadCloser" } return "ReadSeeker" } return "Bytes" default: panic(fmt.Sprintf("unknown marshal shape ref type, %s", r.Ref.Shape.Type)) } } func (r marshalShapeRef) Location() string { var loc string if l := r.Ref.Location; len(l) > 0 { loc = l } else if l := r.Ref.Shape.Location; len(l) > 0 { loc = l } switch loc { case "querystring": return "Query" case "header": return "Header" case "headers": // headers means key is header prefix return "Headers" case "uri": return "Path" case "statusCode": return "StatusCode" default: if len(loc) != 0 { panic(fmt.Sprintf("unknown marshal shape ref location, %s", loc)) } if r.Context.IsRefPayload(r.Name) { return "Payload" } return "Body" } } func (r marshalShapeRef) LocationName() string { if l := r.Ref.QueryName; len(l) > 0 { // Special case for EC2 query return l } locName := r.Name if l := r.Ref.LocationName; len(l) > 0 { locName = l } else if l := r.Ref.Shape.LocationName; len(l) > 0 { locName = l } return locName } func (r marshalShapeRef) IsFlattened() bool { return r.Ref.Flattened || r.Ref.Shape.Flattened } func (r marshalShapeRef) XMLNamespacePrefix() string { if v := r.Ref.XMLNamespace.Prefix; len(v) != 0 { return v } return r.Ref.Shape.XMLNamespace.Prefix } func (r marshalShapeRef) XMLNamespaceURI() string { if v := r.Ref.XMLNamespace.URI; len(v) != 0 { return v } return r.Ref.Shape.XMLNamespace.URI } func (r marshalShapeRef) ListLocationName() string { if v := r.Ref.Shape.MemberRef.LocationName; len(v) > 0 { if !(r.Ref.Shape.Flattened || r.Ref.Flattened) { return v } } return "" } func (r marshalShapeRef) MapLocationNameKey() string { return r.Ref.Shape.KeyRef.LocationName } func (r marshalShapeRef) MapLocationNameValue() string { return r.Ref.Shape.ValueRef.LocationName } func (r marshalShapeRef) HasAttributes() bool { for _, ref := range r.Ref.Shape.MemberRefs { if ref.XMLAttribute { return true } } return false } func (r marshalShapeRef) NumAttributes() (n int) { for _, ref := range r.Ref.Shape.MemberRefs { if ref.XMLAttribute { n++ } } return n } func (r marshalShapeRef) IsIdempotencyToken() bool { return r.Ref.IdempotencyToken || r.Ref.Shape.IdempotencyToken } func (r marshalShapeRef) TimeFormat() string { switch r.Location() { case "Header", "Headers": return "protocol.RFC822TimeFromat" default: switch r.Context.API.Metadata.Protocol { case "json", "rest-json": return "protocol.UnixTimeFormat" case "rest-xml", "ec2", "query": return "protocol.ISO8601TimeFormat" default: panic(fmt.Sprintf("unable to determine time format for %s ref", r.Name)) } } } // UnmarshalShapeGoCode renders the shape's UnmarshalAWS method with unmarshalers // for each field within the shape. A string is returned of the rendered Go code. // // Will panic if error. func UnmarshalShapeGoCode(s *Shape) string { w := &bytes.Buffer{} if err := unmarshalShapeTmpl.Execute(w, s); err != nil { panic(fmt.Sprintf("failed to render shape's fields unmarshaler, %v", err)) } return w.String() } var unmarshalShapeTmpl = template.Must(template.New("unmarshalShapeTmpl").Funcs( template.FuncMap{ "UnmarshalShapeRefGoCode": UnmarshalShapeRefGoCode, }, ).Parse(` {{ $shapeName := $.ShapeName -}} // UnmarshalAWS decodes the AWS API shape using the passed in protocol decoder. func (s *{{ $shapeName }}) UnmarshalAWS(d protocol.FieldDecoder) { {{ range $name, $ref := $.MemberRefs -}} {{ UnmarshalShapeRefGoCode $name $ref $ }} {{ end }} } {{ if $.UsedInList -}} func decode{{ $shapeName }}List(vsp *[]*{{ $shapeName }}) func(int, protocol.ListDecoder) { return func(n int, ld protocol.ListDecoder) { vs := make([]{{ $shapeName }}, n) *vsp = make([]*{{ $shapeName }}, n) for i := 0; i < n; i++ { ld.ListGetUnmarshaler(&vs[i]) (*vsp)[i] = &vs[i] } } } {{- end }} {{ if $.UsedInMap -}} func decode{{ $shapeName }}Map(vsp *map[string]*{{ $shapeName }}) func([]string, protocol.MapDecoder) { return func(ks []string, md protocol.MapDecoder) { vs := make(map[string]*{{ $shapeName }}, n) for _, k range ks { v := &{{ $shapeName }}{} md.MapGetUnmarshaler(k, v) vs[k] = v } } } {{- end }} `)) // UnmarshalShapeRefGoCode generates the Go code to unmarshal an API shape. func UnmarshalShapeRefGoCode(refName string, ref *ShapeRef, context *Shape) string { if ref.XMLAttribute { return "// Skipping " + refName + " XML Attribute." } mRef := marshalShapeRef{ Name: refName, Ref: ref, Context: context, } switch mRef.Location() { case "Path": return "// ignoring invalid decode state, Path. " + refName case "Query": return "// ignoring invalid decode state, Query. " + refName } w := &bytes.Buffer{} if err := unmarshalShapeRefTmpl.ExecuteTemplate(w, "decode", mRef); err != nil { panic(fmt.Sprintf("failed to decode shape ref, %s, %v", ref.Shape.Type, err)) } return w.String() } var unmarshalShapeRefTmpl = template.Must(template.New("unmarshalShapeRefTmpl").Parse(` // Decode {{ $.Name }} {{ $.GoType }} {{ $.MarshalerType }} to {{ $.Location }} at {{ $.LocationName }} `)) <file_sep>/CHANGELOG_PENDING.md ### SDK Features * Add dep Go dependency management metadata files (#1544) * Adds the Go `dep` dependency management metadata files to the SDK. * Fixes [#1451](https://github.com/aws/aws-sdk-go/issues/1451) * Fixes [#634](https://github.com/aws/aws-sdk-go/issues/634) * `service/dynamodb/expression`: Add expression building utility for DynamoDB ([#1527](https://github.com/aws/aws-sdk-go/pull/1527)) * Adds a new package, expression, to the SDK providing builder utilities to create DynamoDB expressions safely taking advantage of type safety. * `API Marshaler`: Add generated marshalers for RESTXML protocol ([#1409](https://github.com/aws/aws-sdk-go/pull/1409)) * Updates the RESTXML protocol marshaler to use generated code instead of reflection for REST XML based services. * `API Marshaler`: Add generated marshalers for RESTJSON protocol ([#1547](https://github.com/aws/aws-sdk-go/pull/1547)) * Updates the RESTJSON protocol marshaler to use generated code instead of reflection for REST JSON based services. ### SDK Enhancements * `private/protocol`: Update format of REST JSON and XMl benchmarks ([#1546](https://github.com/aws/aws-sdk-go/pull/1546)) * Updates the format of the REST JSON and XML benchmarks to be readable. RESTJSON benchmarks were updated to more accurately bench building of the protocol. ### SDK Bugs
ab72772217013ba979d1f3cff64957c06ebed30b
[ "Markdown", "Go" ]
2
Go
Abhishek-Nagarkoti/aws-sdk-go
f93b927be230712e3587ed606bba8f43e340c4ca
7351b8ec5b2d50335744e6dba74dcc6d11d15061
refs/heads/master
<file_sep>print("\nNow when Laertes and the two men raised their hands upon your undertaking.\n\ Alas!\n\ Winds from East, South, North, East, and West have breathed upon it in his boyhood.\n\ Let us see what he has many suitors, who eat them up at the well, do not think he will, set your\n\ Now, therefore, do you sit like that of my son, that I am afraid of such sovereign power and virtue\n")<file_sep># Homer MarkovText Text Generation through Markov Chains This is a custom Markov chain text engine that generates passages like Homer! <H1> Training Data </H1> There are some data sets that have been provided in there which have been scoured from the web. What's included: 1. Homer's Illiad 2. Homer's Oddysey <H1> Generating a Dictionary </H1> To generate a dictionary file, you'll need to run the genMarkovDict.py script as follows: <BR><code>python genMarkovDict.py -k (the order of the markov chain; i.e. do you generate one word at a time or pairs of words) -i (input file with wild card) -d (output dictionary file) </code> For example, the following generates a dictionary of order 2 where the text was generated using two words at a time: <BR><code>python genMarkovDict.py -k 2 -i "Data - Oddysey\*.*" -d homerdict.txt </code> <H1> Generating Text </H1> To generate the actual text, you'll need to run the genMarkovText.py script as follows: <code>python genMarkovText.py -w (maximum number of words in sentence) -n (number of sentences to generate) -d (source dictionary file) </code> For example, the following creates 5 generated text sentences with each one having a maximum of 20 words (if the end of sentence is found, then it will only go up to that last word) <BR><code>python genMarkovText.py -w 20 -n 5 -d homerdict.txt </code> <H1> Credits </H1> Special thanks to <NAME> for open sourcing their code and making this as easy as possible! Also thank you to MIT for having an online resource with the entire Homer series that required only specific preprocessing. <file_sep>import sys old_file = open(sys.argv[1], 'r') new_file = open(sys.argv[2], 'w+') print("processing") for line in old_file: if "----------------------------------------------------------------------" in line: continue else: new_file.write(line) new_file.close()
e3ce3503211f72f575a1972ff70ad1bd44b5c275
[ "Markdown", "Python" ]
3
Python
VictorButoi/MarkovText
de491a8c6b5cd7317caeccaf0af521454a18a122
415e814e420198e4d03484f1b60f98a17089860c
refs/heads/master
<repo_name>msheke101/mvc<file_sep>/WebApplication3/Controllers/CompanyNamesController.cs using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using WebApplication3.Models; namespace WebApplication3.Controllers { public class CompanyNamesController : Controller { private SubsidiariesEntities db = new SubsidiariesEntities(); // GET: CompanyNames public ActionResult Index() { var companyNames = db.CompanyNames.Include(c => c.Exchange).Include(c => c.CompanyType); return View(companyNames.ToList()); } // search //public ActionResult Index(string searchString) //{ // var companyNames = from m in db.CompanyNames // select m; // if (!String.IsNullOrEmpty(searchString)) // { // companyNames = companyNames.Where(s => s.CompanyName1.Contains(searchString)); // } // return View(companyNames.Where(s => s.CompanyName1.Contains(searchString))); // } //public ActionResult Index(string CompanyTypeID,string ExchangeCode, string searchString) // { // var GenreLst = new List<string>(); // var GenreQry = from d in db.CompanyNames // orderby d.ExchangeCode // select d.ExchangeCode; // // GenreLst.AddRange(GenreQry.Distinct()); // ViewBag.ExchangeCode = new SelectList(db.Exchanges, "ExchangeCode", "ExchangeName"); // var TypLst = new List<string>(); // var TypQry = from d in db.CompanyNames // orderby d.CompanyTypeID // select d.CompanyTypeID; // // TypLst.AddRange(TypQry.Distinct()); // ViewBag.CompanyTypeID = new SelectList(db.CompanyTypes, "CompanyTypeID", "CompanyTypeDesc"); // var companyNames = from m in db.CompanyNames // select m; // if (!String.IsNullOrEmpty(searchString)) // { // companyNames = companyNames.Where(s => s.CompanyName1.Contains(searchString)); // } // if (!string.IsNullOrEmpty(ExchangeCode)) // { // companyNames = companyNames.Where(x => x.ExchangeCode == ExchangeCode); // } // if (!string.IsNullOrEmpty(CompanyTypeID)) // { // companyNames = companyNames.Where(x => x.CompanyTypeID == CompanyTypeID); // } // return View(companyNames); // } // GET: CompanyNames/Details/5 public ActionResult Details(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } CompanyName companyName = db.CompanyNames.Find(id); if (companyName == null) { return HttpNotFound(); } return View(companyName); } // GET: CompanyNames/Create public ActionResult Create() { ViewBag.ExchangeCode = new SelectList(db.Exchanges, "ExchangeCode", "ExchangeName"); ViewBag.CompanyTypeID = new SelectList(db.CompanyTypes, "CompanyTypeID", "CompanyTypeDesc"); return View(); } // POST: CompanyNames/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "CompanyID,ExchangeCode,CompanyName1,ShortCode,CountryID,BusinessSectorID,CompanyTypeID,UpdateDate")] CompanyName companyName) { if (ModelState.IsValid) { db.CompanyNames.Add(companyName); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.ExchangeCode = new SelectList(db.Exchanges, "ExchangeCode", "ExchangeName", companyName.ExchangeCode); ViewBag.CompanyTypeID = new SelectList(db.CompanyTypes, "CompanyTypeID", "CompanyTypeDesc", companyName.CompanyTypeID); return View(companyName); } // GET: CompanyNames/Edit/5 public ActionResult Edit(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } CompanyName companyName = db.CompanyNames.Find(id); if (companyName == null) { return HttpNotFound(); } ViewBag.ExchangeCode = new SelectList(db.Exchanges, "ExchangeCode", "ExchangeName", companyName.ExchangeCode); ViewBag.CompanyTypeID = new SelectList(db.CompanyTypes, "CompanyTypeID", "CompanyTypeDesc", companyName.CompanyTypeID); return View(companyName); } // POST: CompanyNames/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "CompanyID,ExchangeCode,CompanyName1,ShortCode,CountryID,BusinessSectorID,CompanyTypeID,UpdateDate")] CompanyName companyName) { if (ModelState.IsValid) { db.Entry(companyName).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.ExchangeCode = new SelectList(db.Exchanges, "ExchangeCode", "ExchangeName", companyName.ExchangeCode); ViewBag.CompanyTypeID = new SelectList(db.CompanyTypes, "CompanyTypeID", "CompanyTypeDesc", companyName.CompanyTypeID); return View(companyName); } // GET: CompanyNames/Delete/5 public ActionResult Delete(string id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } CompanyName companyName = db.CompanyNames.Find(id); if (companyName == null) { return HttpNotFound(); } return View(companyName); } // POST: CompanyNames/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(string id) { CompanyName companyName = db.CompanyNames.Find(id); db.CompanyNames.Remove(companyName); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } } <file_sep>/WebApplication3/Views/CompanyNames/ola.php <html> <title>welcome<title/> <head> welcome home jimmy <head/> <?php echo "we alive and kicking"; ?> <body> jimmy is a cool boy <body/> <h1>jimmy is for years only<h1/> <html/>
2d003c6f126eb093880fe6b27f6c5c286b32eb5c
[ "C#", "PHP" ]
2
C#
msheke101/mvc
b42c64e6d9ab8798edbbdac0a2701324034621d6
e4c7b0a754a1c1f087aa18f44532637ca007a52e
refs/heads/master
<repo_name>iarlenaquiles/TreinamentoNode<file_sep>/day3/index.js var express = require('express'); var app = express(); var myFunction = require('./myFunction'); var bodyParser = require('body-parser'); var request = require('request'); app.set("views", __dirname + "/views"); app.set("view engine", "ejs"); app.use(bodyParser.urlencoded({ extended: true })); app.get('/form', function (req, resp) { resp.render('form'); }); app.get('/register', function (req, resp) { resp.render('register'); }); app.get('/user/:id', function (req, resp) { let id = req.params.id; request('https://reqres.in/api/users/' + id, function (error, response, body) { if (response.statusCode == 200) { resp.render('user', { user: body }); } else if (response.statusCode == 404) { resp.render('user', { user: "User not found" }); } }); }); app.get('/resource', function (req, resp) { request('https://reqres.in/api/unknown', function (error, response, body) { if (response.statusCode == 200) { resp.render('resource', { resource: body }); } else if (response.statusCode == 404) { resp.render('resource', { resource: "Resource not found" }); } }); }); app.get('/resource/:id', function (req, resp) { let id = req.params.id; request('https://reqres.in/api/unknown/' + id, function (error, response, body) { if (response.statusCode == 200) { resp.render('resource', { resource: body }); } else if (response.statusCode == 404) { resp.render('resource', { user: "Resource not found" }); } }); }); app.post('/create', function (req, resp) { console.log(req); var postData = req.body; request.post({ url: 'https://reqres.in/api/users', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: require('querystring').stringify(postData) }, function (err, response, body) { resp.render('create', { create: body }); }); }); app.post('/register', function (req, resp) { console.log(req); var postData = req.body; request.post({ url: 'https://reqres.in/api/register', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: require('querystring').stringify(postData) }, function (err, response, body) { resp.render('create', { create: response }); }); }); app.put('/update', function (req, resp) { var putData = { "name": "<NAME>", "job": "leader" }; request.put({ url: 'https://reqres.in/api/users/2', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: require('querystring').stringify(putData) }, function (err, response, body) { resp.render('create', { create: body }); }); }); app.listen(3050, function () { console.log('Example app listening on port 3050'); }); <file_sep>/exercicio/index.js var express = require('express'); var app = express(); var myFunction = require('./myFunction'); var bodyParser = require('body-parser'); app.set("views", __dirname + "/views"); app.set("view engine", "ejs"); app.use(bodyParser.urlencoded({ extended: true })); app.get('/oddeven/:value', function (req, resp) { let value = req.params.value; resp.send("The number is " + myFunction.oddOrEven(value)); }); app.get('/random', function (req, resp) { resp.render('random', { number: myFunction.random() }); }); app.get('/number/:number', function (req, resp) { let number = req.params.number; if (number < 5) { resp.render('random', { number }); } else { resp.send(number); } }); app.get('/array', function(req, resp) { resp.render('array', { array: myFunction.array()}) }); app.listen(3050, function () { console.log('Example app listening on port 3050'); }); <file_sep>/day2Exercicio/index.js var express = require('express'); var app = express(); var myFunction = require('./myFunction'); var bodyParser = require('body-parser'); app.set("views", __dirname + "/views"); app.set("view engine", "ejs"); app.use(bodyParser.urlencoded({ extended: true })); app.get('/oddeven/:value', function (req, resp) { let value = req.params.value; resp.send("The number is " + myFunction.oddOrEven(value)); }); app.get('/oddeven', function (req, resp) { resp.render('home', { item: "Lorem Ipsum" }); }); app.get('/osf', function (req, resp) { resp.send("Bem-vindo ao treinamento"); }); app.get('/call', function (req, resp) { resp.send(myFunction.call()); }); app.get('/square/:value', function (req, resp) { let value = req.params.value; resp.send("Square: " + myFunction.square(value)); }); app.listen(3050, function () { console.log('Example app listening on port 3050'); });
6fb02d85c7801c24f6c3a5ecf6fb39171c48bce5
[ "JavaScript" ]
3
JavaScript
iarlenaquiles/TreinamentoNode
cbb735372730b5c6e6f7b693f784603b35ef7089
93046e80ce8afc837cf1f42a5ae37f7e99b9e9fb
refs/heads/master
<file_sep>// -*- C++ -*- // // Package: Demo/QGAnalyzer // Class: QGAnalyzer // /**\class QGAnalyzer QGAnalyzer.cc Demo/QGAnalyzer/plugins/QGAnalyzer.cc Description: [one line class summary] Implementation: [Notes on implementation] */ // // Original Author: <NAME> // Created: Fri, 25 Mar 2016 17:54:55 GMT // // // system include files #include <memory> // user include files //#include "FWCore/Framework/interface/Frameworkfwd.h" //COMMENTED OUT 4-19-2016 #include "FWCore/Framework/interface/EDAnalyzer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" //Histogram Headers #include "FWCore/ServiceRegistry/interface/Service.h" #include "CommonTools/UtilAlgos/interface/TFileService.h" #include "TH1.h" #include "TH2.h" //Jet Headers #include "DataFormats/JetReco/interface/PFJet.h" #include "DataFormats/JetReco/interface/PFJetCollection.h" #include "DataFormats/ParticleFlowCandidate/interface/PFCandidateFwd.h" #include "DataFormats/Common/interface/ValueMap.h" // // class declaration // class QGAnalyzer : public edm::EDAnalyzer { public: explicit QGAnalyzer(const edm::ParameterSet&); ~QGAnalyzer(); static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: virtual void beginJob() override; virtual void analyze(const edm::Event&, const edm::EventSetup&) override; virtual void endJob() override; //virtual void beginRun(edm::Run const&, edm::EventSetup const&) override; //virtual void endRun(edm::Run const&, edm::EventSetup const&) override; //virtual void beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; //virtual void endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) override; // ----------member data --------------------------- edm::EDGetTokenT<reco::PFJetCollection> jetsToken; edm::EDGetTokenT<edm::ValueMap<float>> qgToken; edm::InputTag jetsInputTag; TH1D *qgplot; }; // // constants, enums and typedefs // // // static data member definitions // //edm::InputTag jetsInputTag; // // constructors and destructor // QGAnalyzer::QGAnalyzer(const edm::ParameterSet& iConfig) : jetsToken(consumes<reco::PFJetCollection>( iConfig.getParameter<edm::InputTag>("jetsInputTag"))) { qgToken = consumes<edm::ValueMap<float>>(edm::InputTag("QGTagger", "qgLikelihood")); edm::Service<TFileService> fs; qgplot = fs->make<TH1D>("qgplot","QG Likelihood",50,0,50); } QGAnalyzer::~QGAnalyzer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) } // // member functions // // ------------ method called for each event ------------ void QGAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup) { using namespace edm; edm::Handle<reco::PFJetCollection> jets; iEvent.getByToken(jetsToken, jets); edm::Handle<edm::ValueMap<float>> qgHandle; iEvent.getByToken(qgToken, qgHandle); for(auto jet = jets->begin(); jet != jets->end(); ++jet){ edm::RefToBase<reco::Jet> jetRef(edm::Ref<reco::PFJetCollection>(jets, jet - jets->begin())); //float qgLikelihood = (*qgHandle)[jetRef]; //qgplot->Fill(qgLikelihood); } #ifdef THIS_IS_AN_EVENT_EXAMPLE Handle<ExampleData> pIn; iEvent.getByLabel("example",pIn); #endif #ifdef THIS_IS_AN_EVENTSETUP_EXAMPLE ESHandle<SetupData> pSetup; iSetup.get<SetupRecord>().get(pSetup); #endif } // ------------ method called once each job just before starting event loop ------------ void QGAnalyzer::beginJob() { } // ------------ method called once each job just after ending the event loop ------------ void QGAnalyzer::endJob() { } // ------------ method called when starting to processes a run ------------ /* void QGAnalyzer::beginRun(edm::Run const&, edm::EventSetup const&) { } */ // ------------ method called when ending the processing of a run ------------ /* void QGAnalyzer::endRun(edm::Run const&, edm::EventSetup const&) { } */ // ------------ method called when starting to processes a luminosity block ------------ /* void QGAnalyzer::beginLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) { } */ // ------------ method called when ending the processing of a luminosity block ------------ /* void QGAnalyzer::endLuminosityBlock(edm::LuminosityBlock const&, edm::EventSetup const&) { } */ // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ void QGAnalyzer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { //The following says we do not know what parameters are allowed so do no validation // Please change this to state exactly what you do use, even if it is no parameters edm::ParameterSetDescription desc; desc.setUnknown(); descriptions.addDefault(desc); } //define this as a plug-in DEFINE_FWK_MODULE(QGAnalyzer); <file_sep>import FWCore.ParameterSet.Config as cms demo = cms.EDAnalyzer('QGAnalyzer' ) <file_sep>#Automatically created by SCRAM import os __path__.append(os.path.dirname(os.path.abspath(__file__).rsplit('/Demo/QGAnalyzer/',1)[0])+'/cfipython/slc6_amd64_gcc491/Demo/QGAnalyzer') <file_sep>import FWCore.ParameterSet.Config as cms process = cms.Process("Demo") process.load("FWCore.MessageService.MessageLogger_cfi") process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff") process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff") process.load("CondCore.DBCommon.CondDBSetup_cfi") process.load('Configuration/StandardSequences/Reconstruction_cff') process.load('Configuration/StandardSequences/MagneticField_AutoFromDBCurrent_cff') process.MessageLogger.cerr.threshold = 'INFO' process.MessageLogger.categories.append('Demo') process.MessageLogger.cerr.INFO = cms.untracked.PSet( limit = cms.untracked.int32(-1) ) process.load('RecoJets.JetProducers.QGTagger_cfi') process.QGTagger.srcJets = cms.InputTag('reco::PFJetCollection') # Could be reco::PFJetCollection or pat::JetCollection (both AOD and miniAOD) process.QGTagger.jetsLabel = cms.string('QGL_AK4PFchs') # Other options: see https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion process.options = cms.untracked.PSet( SkipEvent = cms.untracked.vstring('ProductNotFound') ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) from Configuration.AlCa.GlobalTag_condDBv2 import GlobalTag #process.GlobalTag = GlobalTag(process.GlobalTag, '74X_dataRun2_Prompt_v2', '') #process.GlobalTag.globaltag = 'GR_R_44_V12::All' process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_data', '') ####################### # Quark gluon tagging # # (added manually) # ####################### qgDatabaseVersion = 'v1' # check https://twiki.cern.ch/twiki/bin/viewauth/CMS/QGDataBaseVersion from CondCore.DBCommon.CondDBSetup_cfi import * QGPoolDBESSource = cms.ESSource("PoolDBESSource", CondDBSetup, toGet = cms.VPSet(), connect = cms.string('frontier://FrontierProd/CMS_COND_PAT_000'), ) for type in ['AK4PF','AK4PFchs_antib']: QGPoolDBESSource.toGet.extend(cms.VPSet(cms.PSet( record = cms.string('QGLikelihoodRcd'), tag = cms.string('QGLikelihoodObject_'+qgDatabaseVersion+'_'+type), label = cms.untracked.string('QGL_'+type) ))) ########### # Input # ########### process.source = cms.Source("PoolSource", # replace 'myfile.root' with the source file you want to use fileNames = cms.untracked.vstring( #'file:/afs/cern.ch/cms/Tutorials/TWIKI_DATA/TTJets_8TeV_53X.root' 'root://cmsxrootd.fnal.gov///store/mc/RunIISpring15DR74/MinBias_TuneCUETP8M1_13TeV-pythia8/GEN-SIM-RECODEBUG/NoPURealisticRecodebug_741_p1_mcRun2_Realistic_50ns_v0-v1/00000/06967C3F-4A53-E511-91B8-0025904C7DF6.root' ), ) ############ # Output # ############ process.TFileService = cms.Service("TFileService", fileName = cms.string('histodemo.root') ) process.demo = cms.EDAnalyzer('QGAnalyzer', jetsInputTag = cms.InputTag("ak4PFJets") #added from http://uaf-2.t2.ucsd.edu/~ibloch/CMS2/NtupleMaker/python/jetMaker_cfi.py through comparison. It doesn't work though, so that's an issue. ) process.p = cms.Path(process.demo)
0967dfd92883d645cdda8a84a4d7666d59e9441b
[ "Python", "C++" ]
4
C++
obaron/QGAnalyzer
7a098d2201aab5f74878dba6dce7f78e8fe6a13c
72c528beafc39a97aabbf9441393f4a284879c61
refs/heads/master
<file_sep>Projet du groupe **Atari** pour la semaine intensive de JavaScript. *@HETIC* **W1P2021** <file_sep>/* * Project : JS * Date : 17/12/2018 * */ /* * * TODO: remettre les variables etc * */ oxo.screens.loadScreen('home', function() { let rules = document.getElementById(`rules`); let info = document.getElementById(`info`); let rules_show = document.getElementById(`rules_show`); let info_show = document.getElementById(`info_show`); rules.addEventListener('click', function() { rules_show.classList.toggle('infoBox--active'); }); info.addEventListener('click', function() { info_show.classList.toggle('infoBox--active'); }); }); /* * Variable */ let initial; // Value Initial Game let position; // Actual Position Gift let position_minimum = 400; //400; // Initial Position let position_maximun = 600;//500; // Maximun position let position_final = 700; // Finak Position let position_status; let countdown_start; let gift_color_array = ['red', 'yellow', 'green', 'black']; let gift_color_select; let gift_statut = ['present--good good', 'present--bad bad']; // Define if the gift is good or bad let gift_array = [`gift_0 ${gift_statut[0]}`, `gift_1 ${gift_statut[0]}`, `gift_2 ${gift_statut[0]}`, `gift_3 ${gift_statut[1]}`]; // Array Gifts and add their statuts let fireplace_array = [`fireplace_0`, `fireplace_2`, `fireplace_3`, `fireplace_4`]; // Array Spawns let bonus; // Add a bonus //let gift_check; // Check gift statue let spawners_select; // Select the spawner let NbGifts = 0; // Total of gifts let character; // Define the active gift let move; let fireplace_select; //Choose the fireplace let laser; // Define the laser ID let health = 3; // Nb of life let health_array = [`health_0`, `health_1`, `health_2`] let health_select; let snow_life; let wrapper_select; let speed = 1000; // Speed spawn gifts let timer = 90; //Game Timer let speed_gift = null; //Game stop let speed_timer = null; //Game stop let timer_laser = 1000; // Timer Laser let position_refresh = 10; let refresh; let refresh_timer; let audio_background; // Variable Background Song let audio_laser; // Laser soundù let gift; //let end_id; // Choose the end let end_status = true; let end_id; let try_again; let frame_status; // /* * Load the game when enter is press */ oxo.inputs.listenKey('enter', function() { // do something if (oxo.screens.getCurrentScreen !== 'game') { oxo.screens.loadScreen(`game`, function() { // game.html is loaded, do something //Select countdown_start countdown_start = document.getElementById(`countdown_start`); wrapper_select = document.getElementById(`game__area_snow`); // Show countdown when the party starts let timeleft = 3; let time_start_interval = setInterval(function(){ let time_start = [`GO`, `1`,`2`,`3`]; countdown_start.innerHTML = `${time_start[timeleft]}` timeleft--; if(timeleft < 0) clearInterval(time_start_interval); },1000); //Select spawners spawners_select = document.querySelectorAll(`.game__area .spawner .spawner__position`); //Select health health_select = document.querySelectorAll(`.health`); //Select laser laser = document.getElementById(`deer_arm`); //Select snow div snow_life = document.querySelectorAll(`.snow_life`); //Select audio audio_background = document.getElementById('song_background'); audio_laser = document.getElementById('song_laser'); /////////////////////////////////////////////////////////////////////////////////////////////// //console.log(health_select); //console.log('spawners_select '+ spawners_select); /////////////////////////////////////////////////////////////////////////////////////////////// //Load start Function setTimeout(function() { // Anime the deer laser.classList.remove(`deer__arm--start`); laser.classList.remove(`deer__arm--shoot`); laser.classList.add(`deer__arm--up`); start(); }, 4500); }); } }); // /* * Define Game Timer */ function start(){ //musique audio_background.play(); speed_timer = setInterval(count, 1000); } function count() { level(); timer--; if(timer == 0){ finish(); } else { // WHile time != 0 do : NbGifts = NbGifts + 1; /////////////////////////////////////////////////////////////////////////////////////////////// //console.log( timer + " secondes restantes"); /////////////////////////////////////////////////////////////////////////////////////////////// } } function finish() { // Load End game oxo.screens.loadScreen('end', function() { end_id = document.getElementById(`end_type`); console.log(end_id); //Title frame_status = document.getElementById('frame_status'); // Choose the end if(end_status === true) { end_id.classList.add(`goodScore`); } else { // Show the bad title if you loose //frame_status.parentNode.removeChild(frame_status); //frame_status.innerHTML = `<img id="frame_status" src="../img/SVG/gameOver.svg">` end_id.classList.add(`badScore`); } let test = document.getElementById('top_bottom'); try_again = document.getElementById('try_again'); oxo.inputs.listenKeys([ `enter`], function(key) { oxo.screens.loadScreen('home', function() { window.location.href = "https://christmas-hero.netlify.com/"; //http://localhost:1234/index.html }); }); setTimeout(function() { document.getElementById('top_bottom').click(); //console.log('smooth'); }, 1000); }); clearInterval(speed_timer); clearInterval(refresh); clearInterval(refresh_timer); clearInterval(speed_gift); } /* * Define Level */ function level(){ //Incrase level speed = speed- 30; spawn(); /////////////////////////////////////////////////////////////////////////////////////////////// //console.log( speed + " speed"); //console.log( speed_gift + " level"); /////////////////////////////////////////////////////////////////////////////////////////////// } /* * Select and Create Gifts */ function spawn() { // Get the a random color gift_color_select = oxo.utils.getRandomNumber(0, 3); // Choose a random spawner fireplace_select = oxo.utils.getRandomNumber(0, 3); //console.log('fireplace_select ' +fireplace_select); //Remove all classes spawners_select[fireplace_select].classList.remove(`spawner__position`, `gift_0`, `gift_1`, `gift_2`, `gift_3`); // Add a random gift and define 1 ID for each //console.log(NbGifts); spawners_select[fireplace_select].innerHTML = `<div id="gift_moving_${NbGifts}" class="${gift_array[oxo.utils.getRandomNumber(0, gift_array.length - 1)]} gifts present "><div class="present__image present--${gift_color_array[gift_color_select]}"></div><div class="present__value present__value--coint"><img src=""></div></div>`; gift = document.getElementById(`gift_moving_${NbGifts}`); var giftInterval = setInterval(function() { oxo.animation.move(gift, 'down', 10); //console.log(oxo.animation.getPosition(gift).y); }, 20); // When the gift go out of the screen oxo.elements.onLeaveScreenOnce(gift, function() { //console.log('OUT'); gift.remove(); clearInterval(giftInterval); }); // Select the last id was created character = document.getElementById(`gift_moving_${NbGifts}`); //Check position gift //gift_move(); /////////////////////////////////////////////////////////////////////////////////////////////// //console.log( spawners_select[fireplace_select]); //console.log(character.className === `bad`); //console.log(character); //console.log(position = oxo.animation.getPosition(character)); //console.log(position.x); /////////////////////////////////////////////////////////////////////////////////////////////// } // /* * Keys write * q : fireplace_0 * s : fireplace_1 * d : fireplace_2 * f : fireplace_3 */ oxo.inputs.listenKeys([ `f`], function(key) { //console.log(oxo.animation.getPosition(gift)); //console.log(oxo.animation.getPosition(gift).y); clearInterval(refresh_timer); laser_effect(); // Compare the tower was selected if(spawners_select[0] === spawners_select[fireplace_select]) { console.log('f'); //console.log(oxo.animation.getPosition(gift)); score(); } }); oxo.inputs.listenKeys([ `g`], function(key) { clearInterval(refresh_timer); laser_effect(); // Compare the tower was selected if(spawners_select[1] === spawners_select[fireplace_select]) { console.log('g'); score(); } }); oxo.inputs.listenKeys([ `h`], function(key) { clearInterval(refresh_timer); laser_effect(); // Compare the tower was selected if(spawners_select[2] === spawners_select[fireplace_select]) { console.log('h'); score(); } }); oxo.inputs.listenKeys([ `j`], function(key) { clearInterval(refresh_timer); laser_effect(); // Compare the tower was selected if(spawners_select[3] === spawners_select[fireplace_select]) { console.log('j'); score(); } }); /* * Add score or end game */ function score(){ console.log('%c coucou', 'background-color: green; padding: 5px'); // Compare position let marchestpfrr = oxo.animation.getPosition(gift).y; if (position_minimum <= marchestpfrr && marchestpfrr <= position_maximun) { // Check spawners_select[fireplace_select].classList.add(`check`); //console.log(spawners_select[fireplace_select]); if (character.classList.contains(`bad`)){ health_counter(); } else { //spawners_select[fireplace_select].classList.add(`present--noAccept`); // Add to score oxo.player.addToScore(5); speed = speed- 30; // One time for each gift position = 0; } } } // /* * Effect laser */ function laser_effect() { // Visual Effect audio_background.play(); laser.classList.add(`deer__arm--shoot`); // Disapear laser after a delay setTimeout(function() { laser.classList.remove(`deer__arm--shoot`); //console.log(laser); }, timer_laser); } // /* * Health Counter Function */ function health_counter(){ health--; health_select[health].classList.remove(`health`); speed = speed- 15; wrapper_select.classList.remove(`wrapper`); snow_life[health].classList.add(`disturber--snow`); //Arrête la partie if(health === 0){ // Set the bad game end_status = false; finish(); } } //
03781d81b255bbc414824da34cc664cb4b24cbf8
[ "Markdown", "JavaScript" ]
2
Markdown
kentoje/hetic-w1p2021-01-atari
b6330e56607a9a62b779d2f033c0ea28cb992717
dd525ffa3f32ef7f5c680a1f750f752359413725
refs/heads/master
<repo_name>alcir-junior-caju/study-js-reactjs-gostack-redux-sagas<file_sep>/src/store/modules/rootSaga.ts import { all } from 'redux-saga/effects'; import cart from '@store/modules/cart/sagas'; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types export default function* rootSaga() { return yield all([cart]); } <file_sep>/src/components/Cart/styles.ts import styled from 'styled-components'; export const Container = styled.div` border-top: 1px solid #ccc; margin-top: 40px; padding-top: 10px; h4 { margin: 10px 0; } table { margin-top: 20px; thead tr th { padding-bottom: 20px; } } `; <file_sep>/src/store/modules/rootReducers.ts import { combineReducers } from 'redux'; import cart from '@store/modules/cart/reducer'; export default combineReducers({ cart }); <file_sep>/src/store/modules/cart/actions.ts /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ import { ActionTypes, IProduct } from '@store/modules/cart/types'; // interface IAction { // type: string; // payload: object; // } export function addItemsToCartRequest(product: IProduct) { return { type: ActionTypes.addItemsToCartRequest, payload: { product } }; } export function addProductToCartRequest(product: IProduct) { return { type: ActionTypes.addProductToCartRequest, payload: { product } }; } export function addProductToCartSuccess(product: IProduct) { return { type: ActionTypes.addProductToCartSucess, payload: { product } }; } export function addProductToCartFailure(productId: number) { return { type: ActionTypes.addProductToCartFailure, payload: { productId } }; } <file_sep>/src/components/CatalogItem/styles.ts import styled from 'styled-components'; export const Container = styled.article` align-items: center; display: flex; justify-content: space-between; padding: 10px 0; `; export const MessageError = styled.span` background: transparent; color: red; `; <file_sep>/README.md <!-- Info Header --> <table> <tr> <td> <img alt="Caju" src="https://www.cajucomunica.com.br/logo-caju.png" width="250px" /> </td> <td> <h3> Estudo sobre Redux e Sagas. </h3> <p> <a href="https://cajucomunica.com.br"> <img alt="Criado por Alcir Junior [Caju]" src="https://img.shields.io/badge/criado%20por-Alcir Junior [Caju]-%23f08700"> </a> <img alt="License" src="https://img.shields.io/badge/license-MIT-%23f08700"> </p> <p"> <a href="#telas-do-sistema">Tela da aplicação:</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#descrição">Descrição</a> </p> </td> </tr> </table> #### Telas do Sistema <p align="center"> <img alt="Tela" src="_images/tela.png" width="75%" style="margin: 15px 0" /> </p> --- #### Visualizar o projeto na IDE: Para quem quiser visualizar o projeto na IDE esse recurso do GitHub é bem bacana: https://github1s.com/alcir-junior-caju/study-js-reactjs-gostack-redux-sagas --- #### Descrição Estudo sobre Redux e Sagas.
eb92055649d4f4405e4b86bfd51c461aceedd579
[ "Markdown", "TypeScript" ]
6
TypeScript
alcir-junior-caju/study-js-reactjs-gostack-redux-sagas
62d1a76b8c7da1b166dd37921977a5a7cc1028de
7334cfdc89599f286c0fab1710c4844f6522df5a
refs/heads/master
<file_sep>require('rspec') require('scrabble_score') describe('String#scrabble_score') do it('provides score for a letter') do expect(('a').scrabble_score()).to(eq(1)) end it('provides the score for a word') do expect(('aei').scrabble_score()).to(eq(3)) end end
0e27348c7cfa315325c3ade8e570760f91b781b0
[ "Ruby" ]
1
Ruby
tryangul/scrabble_score_sinatra
b77be451ab6eb132dd6d52e026b1b2fa892424b4
5c2012aa2b37d022ac3656b02811a4971f686519
refs/heads/master
<file_sep>using System.Linq; using System.Threading.Tasks; using Core.Entity.identity; using Microsoft.AspNetCore.Identity; namespace Infrastructure.identity { public class AppIdentityDbContextSeed { public static async Task SeedUserAsync(UserManager<AppUser> userManager) { if (!userManager.Users.Any()) { var user = new AppUser { DisplayName = "jeeva", Email = "<EMAIL>", UserName = "jeeva", Address = new Address { FirstName = "jeeva", LastName = "rishi", Street = "3 cross street", City = "Kanchipuram", State = "Tamilnadu", Zipcode = "631551" } }; await userManager.CreateAsync(user, "Pa$$w0rd"); } } } }<file_sep>export interface IProduct{ id:number; name:string; description:string; price:number; pictureUrl:string; productType:string; productBrand:string; }<file_sep>import {v4 as uuidv4} from 'uuid'; export interface IBasket{ id:string; items:IBasketItem[]; } export interface IBasketItem{ id:number; productName:string; price:number; quantity:number; pictureUrl:string; brand:string; type:string; } export class Basket implements IBasket{ id = uuidv4(); items: IBasketItem[]=[]; } export interface IBasketTotals{ shipping:number; subtotal:number; total:number; }<file_sep>namespace Core.Entity { public class ProductBrand :BaseEntity { public string Name { get; set; } } }
7707fa0d5a9b6783f6780a6b58efbc1e6ba3a62d
[ "C#", "TypeScript" ]
4
C#
rishiVickey/Project
ab3c6c70417565193f095689593e377c6d86d7d0
be7058f0bf6f9add815f24db812eaf3ae476b873
refs/heads/master
<file_sep>import csv import arcpy import xlrd import os asfrLookup = "C://Google Drive//BirthsandPregnanciesMapping//ASFR//asfr_lookup_1990.csv" asfrDir = "C://Google Drive//BirthsandPregnanciesMapping//ASFR//1990" asfrGdb = "C://Google Drive//BirthsandPregnanciesMapping//asfr_1990.gdb" # Loop through ASFR lookup asfr lookup table with open(asfrLookup) as csvFile: reader = csv.reader(csvFile, delimiter=",") next(reader, None) # Skip header row for row in reader: iso2, fileName, levelRank = row # Open excel spreadsheet xlsxPath = os.path.join(asfrDir, fileName) wb = xlrd.open_workbook(xlsxPath) for i in ("URBAN", "RURAL"): # Add data to table with insert cursor c = arcpy.da.InsertCursor("%s//asfr%s" % (asfrGdb, i), ("iso", "region", "levelRank", "a1520", "a2025", "a2530", "a3035", "a3540", "a4045", "a4550", "sourceFile")) for col in range(1, wb.sheet_by_name(i).ncols): region, a1520, a2025, a2530, a3035, a3540, a4045, a4550 = wb.sheet_by_name(i).col_values(col, 0, 8) rowData = [iso2, region, levelRank, a1520, a2025, a2530, a3035, a3540, a4045, a4550, fileName] c.insertRow(rowData) del c<file_sep>from __future__ import division import csv import arcpy import xlrd import os from collections import Counter iPumsXls = "C:\\Google Drive\\BirthsandPregnanciesMapping\\Africa_SubNational_ageStructures\\iPums\\EA\\TZA_ipums.csv" #Raw iPums data outDir = "C:\\Google Drive\\BirthsandPregnanciesMapping\\Africa_SubNational_ageStructures\\iPums" outIso = "TZA.csv" age_dict = {} #Set age dictionary with open(iPumsXls) as csvFile: for line in csvFile: #Go through each observation in iPums data age_str = line.split(",") ISO = age_str[0] adm = age_str[4] age_class = age_str[7] if adm not in age_dict: #If Python encounters new admin unit/age class, add to dictionary age_dict[adm] = {} if age_class not in age_dict[adm]: age_dict[adm][age_class] = 0 age_dict[adm][age_class] = age_dict[adm][age_class] + 1 #Output subnational age structures orderedagecl=["1","2","3","4","8","9","10","11","12","13","14","15","16","17","18","19","20","98"] #Order age class out_file = open(os.path.join(outDir,outIso), 'w') out_file.write("admin2, a0005, a0510, a1015, a1520, a2025, a2530, a3035, a3540, a4045, a4550, a5055, a5560, a6065, a6570, a7075, a7580, a80plus, aUnknown, ISO\n") for adm in age_dict: #Write admin unit out_file.write("{}".format(adm)) for age_class in orderedagecl: #Loop through age class for each admin unit if age_class in age_dict[adm]: age_prop = ((age_dict[adm][age_class])/(sum(Counter(age_dict[adm].values())))) #Create proportions of total population in each age structure per admin unit out_file.write(",{}".format(age_prop)) else: out_file.write(",") out_file.write(",%s\n" % ISO) #Write ISO for each line out_file.close() <file_sep>import logging import mapnik import xml.etree.ElementTree as ET import os import subprocess import tempfile # Set up logging logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s", level=logging.INFO) # Parameters countryListXml = "C:/Projects/BirthsAndPregnanciesMapping/code/country_list.xml" dbPath = "C:/Projects/BirthsAndPregnanciesMapping/data/2014-05-23/adminBoundaries.sqlite" epsDir = "C:/Projects/BirthsAndPregnanciesMapping/results/eps" max_img_size = 1000 # Max width or height of output image # Create style stroke = mapnik.Stroke() stroke.color = mapnik.Color(0,0,0) stroke.width = 1.0 symbolizer = mapnik.LineSymbolizer(stroke) rule = mapnik.Rule() rule.symbols.append(symbolizer) style = mapnik.Style() style.rules.append(rule) # Loop through countries in xml countryList = ET.parse(countryListXml).getroot() for country in countryList.findall("country"): name = country.find("name").text iso3 = country.find("iso3").text logging.info("Processing %s" % name) # Create Datasource query = '(SELECT * FROM GAUL_2010_2 WHERE ISO3 = "%s")' % iso3 datasource = mapnik.SQLite(file=dbPath, table=query, geometry_field="Geometry", key_field="PK_UID", use_spatial_index=False) # Create layer layer = mapnik.Layer("boundaries") layer.datasource = datasource layer.styles.append("boundariesStyle") # Calculate image output size envelope = datasource.envelope() dLong = envelope.maxx - envelope.minx dLat = envelope.maxy - envelope.miny aspectRatio = dLong / dLat if dLong > dLat: width = max_img_size height = int(width / aspectRatio) elif dLat > dLong: height = max_img_size width = int(aspectRatio * height) else: width = max_img_size height = max_img_size # Create map map = mapnik.Map(width, height) map.append_style("boundariesStyle", style) map.layers.append(layer) map.zoom_all() # Output to temporary postscript file outPsPath = os.path.join(tempfile.gettempdir(), "%sadminBoundaries.ps" % iso3) mapnik.render_to_file(map, outPsPath) # Convert postscript to EPS file using ghostscript outEpsPath = os.path.join(epsDir, "%sadminBoundaries.eps" % iso3) subprocess.call(["C:/Program Files/gs/gs9.14/bin/gswin64c", "-dDEVICEWIDTHPOINTS=%s" % width, "-dDEVICEHEIGHTPOINTS=%s" % height, "-sDEVICE=eps2write", "-o", outEpsPath, outPsPath]) # Delete temporary file os.remove(outPsPath) <file_sep>import logging import mapnik import xml.etree.ElementTree as ET import os import subprocess import tempfile # Set up logging logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s", level=logging.INFO) # Parameters shpPath = "C:/Projects/BirthsAndPregnanciesMapping/data/2014-04-24/Zanzibar/Zanzibar.shp" epsDir = "C:/Projects/BirthsAndPregnanciesMapping/results/eps" max_img_size = 1000 # Max width or height of output image # Create style stroke = mapnik.Stroke() stroke.color = mapnik.Color(0,0,0) stroke.width = 1.0 symbolizer = mapnik.LineSymbolizer(stroke) rule = mapnik.Rule() rule.symbols.append(symbolizer) style = mapnik.Style() style.rules.append(rule) # Create Datasource datasource = mapnik.Shapefile(file=shpPath) # Create layer layer = mapnik.Layer("boundaries") layer.datasource = datasource layer.styles.append("boundariesStyle") # Calculate image output size envelope = datasource.envelope() dLong = envelope.maxx - envelope.minx dLat = envelope.maxy - envelope.miny aspectRatio = dLong / dLat if dLong > dLat: width = max_img_size height = int(width / aspectRatio) elif dLat > dLong: height = max_img_size width = int(aspectRatio * height) else: width = max_img_size height = max_img_size # Create map map = mapnik.Map(width, height) map.append_style("boundariesStyle", style) map.layers.append(layer) map.zoom_all() # Output to temporary postscript file outPsPath = os.path.join(tempfile.gettempdir(), "ZanzibarAdminBoundaries.ps") mapnik.render_to_file(map, outPsPath) # Convert postscript to EPS file using ghostscript outEpsPath = os.path.join(epsDir, "ZanzibarAdminBoundaries.eps") subprocess.call(["C:/Program Files/gs/gs9.14/bin/gswin64c", "-dDEVICEWIDTHPOINTS=%s" % width, "-dDEVICEHEIGHTPOINTS=%s" % height, "-sDEVICE=eps2write", "-o", outEpsPath, outPsPath]) # Delete temporary file os.remove(outPsPath) <file_sep>import os import fnmatch import arcpy inDir = "C:/BirthsandPregnancies/WorldPop/" outDir = "C:/BirthsandPregnancies/WorldPop/POP_compressed/" matches = [] for root, dirnames, filenames in os.walk(inDir): for filename in fnmatch.filter(filenames, '*.tif'): matches.append(os.path.join(root[len(inDir):], filename)) for match in matches: inRast = os.path.normpath(os.path.join(inDir, match)) outRast = os.path.normpath(os.path.join(outDir, match)) newDir = os.path.dirname(outRast) if not os.path.exists(newDir): os.makedirs(newDir) print "Compressing " + inRast arcpy.CopyRaster_management(inRast, outRast)<file_sep>import mapnik import os import fnmatch import logging # Set up logging logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s", level=logging.INFO) # Parameters rastDir = r"C:\BirthsandPregnancies\results\raster" outPngDir = r"C:\BirthsandPregnancies\results\png" max_img_size = 5000 # Max width or height of output image # Define raster color scheme c = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color(54,97,255)) c.add_stop(0, mapnik.COLORIZER_EXACT, mapnik.Color(87,36,255)) c.add_stop(0) # Uses default colour value c.add_stop(0.1, mapnik.Color(79,159,227)) c.add_stop(0.2, mapnik.Color(0,255,255)) c.add_stop(0.5, mapnik.Color(102,255,77)) c.add_stop(1, mapnik.Color(209,255,105)) c.add_stop(1.5, mapnik.Color(230,230,0)) c.add_stop(2, mapnik.Color(230,153,0)) c.add_stop(2.5, mapnik.Color(255,64,0)) c.add_stop(10, mapnik.Color(168,0,0)) # Create style style = mapnik.Style() rule = mapnik.Rule() symbolizer = mapnik.RasterSymbolizer() symbolizer.colorizer = c rule.symbols.append(symbolizer) style.rules.append(rule) # Get list of raster paths rasterPaths = [] for root, dirnames, filenames in os.walk(rastDir): for filename in fnmatch.filter(filenames, '*2012pregnancies.tif'): rasterPaths.append(os.path.join(root,filename)) # Loop through rasters, generate PNG outputs for rasterPath in rasterPaths: outPngPath = os.path.join(outPngDir, os.path.splitext(os.path.basename(rasterPath))[0] + ".png") # Create layer datasource = mapnik.Gdal(file=rasterPath, band=1) layer = mapnik.Layer("pregnancies") layer.datasource = datasource layer.styles.append("pregnanciesStyle") # Calculate image output size envelope = datasource.envelope() dLong = envelope.maxx - envelope.minx dLat = envelope.maxy - envelope.miny aspectRatio = dLong / dLat if dLong > dLat: width = max_img_size height = int(width / aspectRatio) elif dLat > dLong: height = max_img_size width = int(aspectRatio * height) else: width = max_img_size height = max_img_size # Create map object map = mapnik.Map(width, height) map.append_style("pregnanciesStyle", style) map.layers.append(layer) map.zoom_all() # Output to file logging.info("Creating %s" % outPngPath) mapnik.render_to_file(map, outPngPath) <file_sep>import arcpy import xlrd import tempfile import os import csv import logging import fnmatch import xlsxwriter import math import itertools import xml.etree.ElementTree as ET def dhsAsfrJoin(urbanAsfrFc, ruralAsfrFc, iso2, dhsRegionsFc, urbanAreasShp, iso3, outGDB): global asfrPresent try: # Extract ASFR data for selected country arcpy.TableToTable_conversion(urbanAsfrFc, "in_memory", "urbanAsfrExtract", """ iso = '%s' """ % iso2) arcpy.TableToTable_conversion(ruralAsfrFc, "in_memory", "ruralAsfrExtract", """ iso = '%s' """ % iso2) # Check ASFR data exists for selected country if int(arcpy.GetCount_management("in_memory/urbanAsfrExtract").getOutput(0)) == 0 and int(arcpy.GetCount_management("in_memory/ruralAsfrExtract").getOutput(0)) == 0: asfrPresent = False logging.warning("No Age Specific Fertity Rate data available") else: asfrPresent = True # Extract DHS regions and urban polygons for selected country arcpy.FeatureClassToFeatureClass_conversion(dhsRegionsFc, "in_memory", "dhs_extract", """ ISO = '%s' """ % iso2) arcpy.FeatureClassToFeatureClass_conversion(urbanAreasShp, "in_memory", "urban_extract", """ ISO3 = '%s' """ % iso3) # Union of urban and dhs polygons arcpy.Union_analysis(["in_memory/dhs_extract", "in_memory/urban_extract"], "in_memory/dhsUrbanRural") # Separate urban and rural polygons arcpy.FeatureClassToFeatureClass_conversion("in_memory/dhsUrbanRural", "in_memory", "dhsUrban", """ ONES = 1 """) arcpy.FeatureClassToFeatureClass_conversion("in_memory/dhsUrbanRural", "in_memory", "dhsRural", """ ONES = 0 """) # Join DHS polygons to ASFR tables arcpy.JoinField_management("in_memory/dhsUrban", "REG_ID", "in_memory/urbanAsfrExtract", "REG_ID", ["a1520", "a2025", "a2530", "a3035", "a3540", "a4045", "a4550"]) arcpy.JoinField_management("in_memory/dhsRural", "REG_ID", "in_memory/ruralAsfrExtract", "REG_ID", ["a1520", "a2025", "a2530", "a3035", "a3540", "a4045", "a4550"]) # Merge rural and urban polygons arcpy.Merge_management(["in_memory/dhsUrban", "in_memory/dhsRural"], r"C:\Google Drive\BirthsandPregnanciesMapping\results\test\result.gdb\dhsAsfr%s" % iso3) #outGDB + "/dhsAsfr%s" % iso3) finally: arcpy.Delete_management("in_memory") def findPopRast(popRastDir, iso3, grumpPopRast, countryBoundaries, outDir): # Look for tif files matches = [] for root, dirnames, filenames in os.walk(popRastDir + "\\" + iso3): for filename in fnmatch.filter(filenames, '*.tif'): matches.append(os.path.join(root, filename)) # If match found return path if len(matches) == 1: return matches[0] # If no matches, clip grump population raster and resample to 100m resolution elif len(matches) == 0: logging.warning("No WorldPop raster available. Using GRUMP raster instead.") arcpy.CheckOutExtension("Spatial") old_workspace = arcpy.env.workspace old_scratchWorkspace = arcpy.env.scratchWorkspace tmpdir = tempfile.mkdtemp() arcpy.env.workspace = tmpdir arcpy.env.scratchWorkspace = tmpdir defaultCellSize = arcpy.env.cellSize try: arcpy.FeatureClassToFeatureClass_conversion(countryBoundaries, "in_memory", "countryBoundary", """ iso_alpha3 = '%s' """ % (iso3,)) grumpPopClip = arcpy.sa.ExtractByMask(grumpPopRast, "in_memory/countryBoundary") currentCellSize = (grumpPopClip.meanCellHeight + grumpPopClip.meanCellWidth) / float(2) newCellSize = currentCellSize / float(10) arcpy.env.cellSize = newCellSize grumpPop100m = grumpPopClip / float(100) arcpy.CopyRaster_management(grumpPop100m, os.path.join(outDir, "pop1995%s.tif" % iso3)) return os.path.join(outDir, "pop1995%s.tif" % iso3) finally: arcpy.env.cellSize = defaultCellSize arcpy.Delete_management("in_memory") arcpy.Delete_management(tmpdir) arcpy.env.workspace = old_workspace arcpy.env.scratchWorkspace = old_scratchWorkspace arcpy.CheckInExtension("Spatial") else: logging.error("Multiple population rasters found") def unajustedBirthsEstimates(ageFc, iso3, ageXls, isoNum, popRastPath, asfrPresent, unBirthsXls, outputGdb, outputDir): arcpy.CheckOutExtension("Spatial") old_workspace = arcpy.env.workspace old_scratchWorkspace = arcpy.env.scratchWorkspace tmpdir = tempfile.mkdtemp() arcpy.env.workspace = tmpdir arcpy.env.scratchWorkspace = tmpdir try: # Get raster cell size popRast = arcpy.Raster(popRastPath) cellSize = (popRast.meanCellHeight + popRast.meanCellWidth) / float(2) # Extract subnational age breakdowns for selected country arcpy.FeatureClassToFeatureClass_conversion(ageFc, "in_memory", "age_extract", """ ISO = '%s' """ % (iso3,)) # If no features found, use national data from spreadsheet if int(arcpy.GetCount_management("in_memory/age_extract").getOutput(0)) == 0: logging.warning("No sub-national age bands, using national data") subNationalData = False # Calculate total population from raster popRastMask = popRast * 0 arcpy.CopyRaster_management(popRastMask, "popRastMask.tif", pixel_type="1_BIT") arcpy.BuildRasterAttributeTable_management("popRastMask.tif", "Overwrite") arcpy.sa.ZonalStatisticsAsTable("popRastMask.tif", "VALUE", popRast, "in_memory/popRastZonalStats", "DATA", "SUM") with arcpy.da.SearchCursor("in_memory/popRastZonalStats", "SUM") as c: for row in c: totalPop = row[0] # Get female populations by age from spreadsheet, calculate ratios wb = xlrd.open_workbook(ageXls) ws = wb.sheet_by_name("1995") for row in range(1, ws.nrows): if int(ws.cell_value(row, 4)) == int(isoNum): ageRatioFemale = { k : ((v * 1000) / totalPop) for k, v in zip(("a1520", "a2025", "a2530", "a3035", "a3540", "a4045", "a4550"), ws.row_values(row, 6, 13)) } else: subNationalData = True # Calculate number of women of child bearing age wocbaRasters = {} for ageField in ("a1520", "a2025", "a2530", "a3035", "a3540", "a4045", "a4550"): if subNationalData == True: ageRast = "age_%s.tif" % ageField arcpy.PolygonToRaster_conversion("in_memory/age_extract", ageField, ageRast, cell_assignment="MAXIMUM_AREA", cellsize=cellSize) wocbaRasters[ageField] = (ageRast * popRast * 0.5) else: wocbaRasters[ageField] = (ageRatioFemale[ageField] * popRast) if asfrPresent == False: # Calculate total women of child bearing age wocbaSum = arcpy.sa.CellStatistics(wocbaRasters.values(), "SUM", "DATA") wocbaSumRastMask = wocbaSum * 0 arcpy.CopyRaster_management(wocbaSumRastMask, "wocbaSumRastMask.tif", pixel_type="1_BIT") arcpy.BuildRasterAttributeTable_management("wocbaSumRastMask.tif", "Overwrite") arcpy.sa.ZonalStatisticsAsTable("wocbaSumRastMask.tif", "VALUE", wocbaSum, "in_memory/wocbaSumZonalStats", "DATA", "SUM") with arcpy.da.SearchCursor("in_memory/wocbaSumZonalStats", "SUM") as c: for row in c: totalWocba = row[0] # Retrieve UN total births from spreadsheet wb = xlrd.open_workbook(unBirthsXls) ws = wb.sheet_by_name("ESTIMATES") for row in range(1, ws.nrows): if ws.cell_value(row, 4) == iso3 and int(ws.cell_value(row, 2)) == 1995: unTotal = ws.cell_value(row, 3) * 1000 # Calculate fertility rate fertilityRate = float(unTotal) / float(totalWocba) # Multiply wocba and asfr rasters and sum outputs birthsRasters = [] for ageField in ("a1520", "a2025", "a2530", "a3035", "a3540", "a4045", "a4550"): if asfrPresent == True: asfrRast = "asfr_%s.tif" % ageField arcpy.PolygonToRaster_conversion(outputGdb + "/dhsAsfr%s" % iso3, ageField, asfrRast, cell_assignment="MAXIMUM_AREA", cellsize=cellSize) birthsRasters.append(wocbaRasters[ageField] * asfrRast) else: birthsRasters.append(wocbaRasters[ageField] * fertilityRate) births = arcpy.sa.CellStatistics(birthsRasters, "SUM", "DATA") arcpy.CopyRaster_management(births, os.path.join(outputDir, "%s1995unadjustedBirths.tif" % iso3), pixel_type="32_BIT_FLOAT") finally: # Tidy up arcpy.CheckInExtension("Spatial") arcpy.Delete_management("in_memory") arcpy.Delete_management(tmpdir) arcpy.env.workspace = old_workspace arcpy.env.scratchWorkspace = old_scratchWorkspace def adjustedBirthsEstimates(unBirthsXls, iso3, year, outputDir): arcpy.CheckOutExtension("Spatial") old_workspace = arcpy.env.workspace old_scratchWorkspace = arcpy.env.scratchWorkspace tmpdir = tempfile.mkdtemp() arcpy.env.workspace = tmpdir arcpy.env.scratchWorkspace = tmpdir try: unadjustedBirthsRast = os.path.join(outputDir, "%s%sunadjustedBirths.tif" % (iso3, year)) # Calculate total births rasterMask = arcpy.Raster(unadjustedBirthsRast) * 0 arcpy.CopyRaster_management(rasterMask, "rasterMask.tif", pixel_type="1_BIT") arcpy.BuildRasterAttributeTable_management("rasterMask.tif", "Overwrite") arcpy.sa.ZonalStatisticsAsTable("rasterMask.tif", "VALUE", unadjustedBirthsRast, "in_memory/zonalStats", "DATA", "SUM") with arcpy.da.SearchCursor("in_memory/zonalStats", "SUM") as c: for row in c: unadjustedTotal = row[0] # Retrieve UN total from spreadsheet wb = xlrd.open_workbook(unBirthsXls) ws = wb.sheet_by_name("ESTIMATES") for row in range(1, ws.nrows): if ws.cell_value(row, 4) == iso3 and int(ws.cell_value(row, 2)) == year: unTotal = ws.cell_value(row, 3) * 1000 # Calculate adjusted births raster adjustmentFactor = unTotal / unadjustedTotal adjustedBirths = arcpy.sa.Times(unadjustedBirthsRast, adjustmentFactor) arcpy.CopyRaster_management(adjustedBirths, os.path.join(outputDir, "%s%sadjustedBirths.tif" % (iso3, year)), pixel_type="32_BIT_FLOAT") finally: arcpy.Delete_management("in_memory") arcpy.Delete_management(tmpdir) arcpy.env.workspace = old_workspace arcpy.env.scratchWorkspace = old_scratchWorkspace # def growthRatesJoin(urbanGrowthFc, ruralGrowthFc, countryBoundaries, urbanAreasShp, iso3, outputGdb): # try: # # Extract polygons by country iso # arcpy.FeatureClassToFeatureClass_conversion(countryBoundaries, # "in_memory", # "countryBoundary", # """ iso_alpha3 = '%s' """ % (iso3,)) # arcpy.FeatureClassToFeatureClass_conversion(urbanAreasShp, # "in_memory", # "urban_extract", # """ ISO3 = '%s' """ % (iso3,)) # # Union of urban and boundary polygons # arcpy.Union_analysis(["in_memory/countryBoundary", "in_memory/urban_extract"], # "in_memory/countryUrbanRural") # # Separate urban and rural polygons # arcpy.FeatureClassToFeatureClass_conversion("in_memory/countryUrbanRural", # "in_memory", # "countryUrban", # """ ONES = 1 """) # arcpy.FeatureClassToFeatureClass_conversion("in_memory/countryUrbanRural", # "in_memory", # "countryRural", # """ ONES = 0 """) # # Join growth rates data # arcpy.JoinField_management("in_memory/countryUrban", "iso_alpha2", urbanGrowthFc, "ISO2", ["Growth20102015", "Growth20152020", "Growth20202025", "Growth20252030"]) # arcpy.JoinField_management("in_memory/countryRural", "iso_alpha2", ruralGrowthFc, "ISO2", ["Growth20102015", "Growth20152020", "Growth20202025", "Growth20252030"]) # # Merge urban and rural data back together # arcpy.Merge_management(["in_memory/countryUrban", "in_memory/countryRural"], outputGdb + "/growthRates%s" % iso3) # finally: # # Tidy up # arcpy.Delete_management("in_memory") # def futureBirthsEstimates(growthRatesXls, iso3, isoNum, outputGDB, outputDir): # arcpy.CheckOutExtension("Spatial") # old_workspace = arcpy.env.workspace # old_scratchWorkspace = arcpy.env.scratchWorkspace # tmpdir = tempfile.mkdtemp() # arcpy.env.workspace = tmpdir # arcpy.env.scratchWorkspace = tmpdir # try: # # Estimate births for 2015, 2020, 2025, and 2030 # for growthField in ("Growth20102015", "Growth20152020", "Growth20202025", "Growth20252030"): # fromYear = growthField[-8:-4] # Year growth is calculated from # toYear = growthField[-4:] # Year growth is calculated to # # Retrieve adjusted births raster and raster cell size # adjustedBirthsRast = arcpy.Raster(os.path.join(outputDir, "%s%sadjustedBirths.tif" % (iso3, fromYear))) # cellSize = (adjustedBirthsRast.meanCellHeight + adjustedBirthsRast.meanCellWidth) / float(2) # # Create raster of growth rates from feature class # growthRast = "%s.tif" % growthField # arcpy.PolygonToRaster_conversion(outputGDB + "/growthRates%s" % iso3, # growthField, # growthRast, # cell_assignment="MAXIMUM_AREA", # cellsize=cellSize) # # Calculate unadjusted births and create output raster # unadjustedBirths = adjustedBirthsRast * arcpy.sa.Exp(arcpy.Raster(growthRast) / 100 * 5) # arcpy.CopyRaster_management(unadjustedBirths, os.path.join(outputDir, "%s%sunadjustedBirths.tif" % (iso3, toYear)), pixel_type="32_BIT_FLOAT") # # Calculate adjusted births # adjustedBirthsEstimates(unBirthsXls, iso3, int(toYear), outputDir) # # Estimate births for 2012 # # Retrieve 2010 adjusted births raster # adjustedBirthsRast = arcpy.Raster(os.path.join(outputDir, "%s2010adjustedBirths.tif" % iso3)) # # Calculate unadjusted births and create output raster # growthRast = "Growth20102015.tif" # unadjustedBirths = adjustedBirthsRast * arcpy.sa.Exp(arcpy.Raster(growthRast) / 100 * 2) # arcpy.CopyRaster_management(unadjustedBirths, os.path.join(outputDir, "%s2012unadjustedBirths.tif" % iso3), pixel_type="32_BIT_FLOAT") # # Calculate adjusted births # adjustedBirthsEstimates(unBirthsXls, iso3, 2012, outputDir) # # 2035 estimates are calculated separately, as only national growth rates are available # # Retrieve adjusted births raster # adjustedBirthsRast = arcpy.Raster(os.path.join(outputDir, "%s2030adjustedBirths.tif" % iso3)) # # Retrieve growth rate from spreadsheet # wb = xlrd.open_workbook(growthRatesXls) # ws = wb.sheet_by_name("MEDIUM FERTILITY") # for row in range(17, ws.nrows): # if int(ws.cell_value(row, 4)) == int(isoNum): # growthRate = ws.cell_value(row, 9) # # Calculate unadjusted births and create output raster # unadjustedBirths = adjustedBirthsRast * math.exp(growthRate / 100 * 5) # arcpy.CopyRaster_management(unadjustedBirths, os.path.join(outputDir, "%s2035unadjustedBirths.tif" % iso3), pixel_type="32_BIT_FLOAT") # # Calculate adjusted births # adjustedBirthsEstimates(unBirthsXls, iso3, 2035, outputDir) # finally: # # Tidy up # arcpy.CheckInExtension("Spatial") # arcpy.Delete_management(tmpdir) # arcpy.env.workspace = old_workspace # arcpy.env.scratchWorkspace = old_scratchWorkspace def pregnanciesEstimates(birthPregMultiXlsx, iso3, outputDir): arcpy.CheckOutExtension("Spatial") try: # Retrieve multiplier from spreadsheet wb = xlrd.open_workbook(birthPregMultiXlsx) ws = wb.sheet_by_name("2012") for row in range(1, ws.nrows): if ws.cell_value(row, 2) == iso3: birthPregMulti = ws.cell_value(row, 1) # Multiply births estimates for each year by multiplier year = 1995 #for year in ("1995"): rastPath = os.path.join(outputDir, "%s%sadjustedBirths.tif" % (iso3, year)) birthsRast = arcpy.Raster(rastPath) pregnancies = birthsRast * birthPregMulti outRast = os.path.join(outputDir, "%s%spregnancies.tif" % (iso3, year)) arcpy.CopyRaster_management(pregnancies, outRast, pixel_type="32_BIT_FLOAT") finally: arcpy.CheckInExtension("Spatial") def adminLevel2Estimates(adminBoundaryFc, iso3, urbanAreasShp, rastDir, outGdb): arcpy.CheckOutExtension("Spatial") try: # Extract polygons for selected country arcpy.FeatureClassToFeatureClass_conversion(adminBoundaryFc, "in_memory", "adminBoundsExtract", """ ISO3 = '%s' """ % (iso3,)) arcpy.FeatureClassToFeatureClass_conversion(urbanAreasShp, "in_memory", "urban_extract", """ ISO3 = '%s' """ % (iso3,)) # Identity of urban and admin boundary polygons arcpy.Identity_analysis("in_memory/adminBoundsExtract", "in_memory/urban_extract", "in_memory/adminUrbanRural", "NO_FID") # Define output feature class outputFc = os.path.join(outGdb, "birthsAndPregnancies%s" % iso3) # Aggregate polygons arcpy.Dissolve_management("in_memory/adminUrbanRural", outputFc, ["ADM2_CODE", "ADM2_NAME", "ONES"]) # Create new fields for zonal statistics arcpy.AddField_management(outputFc, "urbanOrRural", "TEXT") arcpy.AddField_management(outputFc, "ZONES", "TEXT") with arcpy.da.UpdateCursor(outputFc, ["ADM2_CODE", "ONES", "urbanOrRural", "ZONES"]) as upCur: for row in upCur: if row[1] == 1: row[2] = "URBAN" else: row[2] = "RURAL" row[3] = str(row[0]) + str(row[2]) upCur.updateRow(row) # Remove "ONES" field as no longer needed arcpy.DeleteField_management(outputFc, "ONES") year = "1995" # Calculate zonal statistics SUM for each raster #for year, desc in itertools.product(("1995"), ("adjustedBirths", "pregnancies")): for desc in ("adjustedBirths", "pregnancies"): raster = os.path.join(rastDir, "%s%s%s.tif" % (iso3, year, desc)) arcpy.sa.ZonalStatisticsAsTable(outputFc, "ZONES", raster, "in_memory/%s%sSUM" % (desc, year), "DATA", "SUM") # ArcGIS does not allow field renaming, so create new field and copy data across arcpy.AddField_management("in_memory/%s%sSUM" % (desc, year), "%s%s" % (desc, year), "DOUBLE") arcpy.CalculateField_management("in_memory/%s%sSUM" % (desc, year), "%s%s" % (desc, year), "!SUM!", "PYTHON_9.3") # Join stats table to output feature class arcpy.JoinField_management(outputFc, "ZONES", "in_memory/%s%sSUM" % (desc, year), "ZONES", ["%s%s" % (desc, year)]) # Remove "ONES" field as no longer needed arcpy.DeleteField_management(outputFc, "ZONES") finally: arcpy.Delete_management("in_memory") arcpy.CheckInExtension("Spatial") def outputToExcel(outGdb, iso3, outXlsxDir): year = "1995" # Input feature class outputFc = os.path.join(outGdb, "birthsAndPregnancies%s" % iso3) # Fieldnames fields = ("ADM2_CODE", "ADM2_NAME", "urbanOrRural", "adjustedBirths1995", "pregnancies1995") # "pregnancies2010", "adjustedBirths2012", "pregnancies2012", # "adjustedBirths2015", "pregnancies2015", "adjustedBirths2020", # "pregnancies2020", "adjustedBirths2025", "pregnancies2025", # "adjustedBirths2030", "pregnancies2030", "adjustedBirths2035", # "pregnancies2035") # Create output spreadsheet outXlsx = os.path.join(outXlsxDir, "birthsAndPregnancies%s%s.xlsx" % (iso3, year)) wb = xlsxwriter.Workbook(outXlsx) ws = wb.add_worksheet() # Row counter outRow = 0 # Add headers to first row fmt = wb.add_format( {'bold': True} ) for i in xrange(len(fields)): ws.write(outRow, i, fields[i], fmt) ws.set_column(i, i, len(fields[i])) # Move down to second row outRow = 1 # Use search cursor to loop through feature class rows with arcpy.da.SearchCursor(outputFc, fields) as cur: for inRow in cur: # Write data to spreadsheet for i in xrange(len(fields)): ws.write(outRow, i, inRow[i]) # Move down one row outRow += 1 # Save and close output spreadsheet wb.close() if __name__ == "__main__": # Input paths countryListXml = "C:\\Google Drive\\BirthsandPregnanciesMapping\\country_list.xml" # List of countries to process urbanAsfrFc = "C:\\Google Drive\\BirthsandPregnanciesMapping\\asfr_1995.gdb\\asfrURBAN" # Urban ASFR data ruralAsfrFc = "C:\\Google Drive\\BirthsandPregnanciesMapping\\asfr_1995.gdb\\asfrRURAL" # Rural ASFR data dhsRegionsFc = "C:\\Google Drive\\BirthsandPregnanciesMapping\\dhsBoundaries\\1995\\dhsBoundaries.gdb\\subnational_boundaries" # DHS boundaries urbanAreasShp = "C:\\BirthsandPregnancies\\GRUMP\\af_as_lac_urban_EA.shp" # Urban area extents ageFc = "C:\\Google Drive\\BirthsandPregnanciesMapping\\Africa_SubNational_ageStructures\\iPums\\EA.shp" # Asia\Africa Sub-national breakdown of population by age ageXls = "C:\\Google Drive\\BirthsandPregnanciesMapping\\POPULATION_BY_AGE_FEMALE_EA.xls" # UN national breakdown of female population by age popRastDir = "C:\\BirthsandPregnancies\\WorldPop1995" # Population raster directory grumpPopRast = "C:\\BirthsandPregnancies\\GRUMP\\grump_pop_1995.tif" # GRUMP 1995 population raster unBirthsXls = "C:\\Google Drive\\BirthsandPregnanciesMapping\\births-by-year_1990_ea.xls" # UN estimates of births birthPregMultiXlsx = "C:\\Google Drive\\BirthsandPregnanciesMapping\\Births-to-pregnancies-multipliers.xlsx" # Births to pregnancy multipliers countryBoundaries = "C:\\Google Drive\\BirthsandPregnanciesMapping\\LSIB-WSV\\lsib-wsv.gdb\\detailed_world_polygons" # Country boundary polygons #urbanGrowthFc = "C:\\Google Drive\\BirthsandPregnanciesMapping\\Growth Rates\\GrowthRates.gdb\\Urban" # Urban growth rates #ruralGrowthFc = "C:\\Google Drive\\BirthsandPregnanciesMapping\\Growth Rates\\GrowthRates.gdb\\Rural" # Rural growth rates adminBoundaryFc = "C:\\Google Drive\\BirthsandPregnanciesMapping\\adminBoundaries\\adminBoundaries.gdb\\g2014_2010_2_EA" # Admin level 2 boundaries #growthRatesXls = "C:\\Google Drive\\BirthsandPregnanciesMapping\\WPP2012_POP_F02_POPULATION_GROWTH_RATE.XLS" # UN National Growth Rates # Output paths outDir = "C:\\BirthsandPregnancies\\results\\raster" # Raster output directory outGDB = "C:\\Google Drive\\BirthsandPregnanciesMapping\\results\\test\\result.gdb" # Vector output geodatabase outXlsxDir = "C:\\BirthsandPregnancies\\results\\excel" # Excel output directory # Set up logging logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s", level=logging.INFO) # Allow files to be overwritten arcpy.env.overwriteOutput = True # Loop through countries listed within xml file countryList = ET.parse(countryListXml).getroot() for country in countryList.findall("country"): countryName = country.find("name").text iso2 = country.find("iso2").text iso3 = country.find("iso3").text isoNum = country.find("isoNum").text logging.info("Processing %s" % countryName) # Join ASFRs (if they exist) to DHS polygons logging.info("Joining ASRFs to DHS polygons") dhsAsfrJoin(urbanAsfrFc, ruralAsfrFc, iso2, dhsRegionsFc, urbanAreasShp, iso3, outGDB) # Find population raster logging.info("Retrieving population raster") popRastPath = findPopRast(popRastDir, iso3, grumpPopRast, countryBoundaries, outDir) # Calculate estimated number of births logging.info("Calculating estimated number of births") unajustedBirthsEstimates(ageFc, iso3, ageXls, isoNum, popRastPath, asfrPresent, unBirthsXls, outGDB, outDir) # Adjust births raster to match UN estimates logging.info("Adjusting births raster to match UN estimates") adjustedBirthsEstimates(unBirthsXls, iso3, 1995, outDir) # Join growth rates to country boundaries # logging.info("Joining growth rates to country boundaries") # growthRatesJoin(urbanGrowthFc, ruralGrowthFc, countryBoundaries, urbanAreasShp, iso3, outGDB) # Estimate future births # logging.info("Estimating future births") # futureBirthsEstimates(growthRatesXls, iso3, isoNum, outGDB, outDir) # Estimate pregnancies logging.info("Estimating pregnancies") pregnanciesEstimates(birthPregMultiXlsx, iso3, outDir) # Zonal statistics by admin region logging.info("Calculating zonal statistics by admin regions") adminLevel2Estimates(adminBoundaryFc, iso3, urbanAreasShp, outDir, outGDB) # Create excel spreadsheet output logging.info("Creating Excel spreadsheet output") outputToExcel(outGDB, iso3, outXlsxDir)<file_sep>births_and_pregnancies.py - This is the main script - Generates the estimates of future births and pregnancies for each country - Outputs in raster, vector and excel format compress_output_rasters.py - for each country, collects the raster outputs into tarballs for births and pregnancies - tarballs are then compressed with gzip compress_tiffs.py - applies LZW compression the the WorldPop rasters country_list.xml - list of all countries to be processed - includes name and iso codes - entries can be commented out, so you can select which countries to process create_boundary_maps.py - creates eps files of country and admin area boundaries - reads data from sqlite database - uses mapnik to apply style and generate postscript file - ghostscript then converts postscript to eps file create_pregnancy_maps.py - uses mapnik to create png maps from 2012 pregnancy rasters create_zanzibar_boundary_map.py - creates boundary map of Zanzibar from shapefile import_asfr_data.py - imports ASFR data from Excel spreadsheets into file geodatabase table pop_and_wra_2012.py - calculates urban and rural population and women of reproductive age for each country - outputs to csv<file_sep>import os import tarfile import logging import xml.etree.ElementTree as ET years = (2010, 2012, 2015, 2020, 2025, 2030, 2035) datasets = ("adjustedBirths", "pregnancies") rasterDir = "C:/Projects/BirthsAndPregnanciesMapping/results/raster" countryListXml = "C:/Projects/BirthsAndPregnanciesMapping/code/country_list.xml" outputDir = "C:/Projects/BirthsAndPregnanciesMapping/results/compressed_rasters" # Set up logging logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s", level=logging.INFO) # Loop through countries listed within xml file countryList = ET.parse(countryListXml).getroot() for country in countryList.findall("country"): iso3 = country.find("iso3").text # Create tar.gz archive for each country and dataset for dataset in datasets: logging.info("Compressing %s - %s" % (iso3, dataset)) tgz = tarfile.open(os.path.join(outputDir, "%s-%s.tar.gz" % (iso3, dataset)), "w:gz") for year in years: tiff = os.path.join(rasterDir, "%s%s%s.tif" % (iso3, year, dataset)) tfw = os.path.join(rasterDir, "%s%s%s.tfw" % (iso3, year, dataset)) tgz.add(tiff, os.path.basename(tiff)) tgz.add(tfw, os.path.basename(tfw)) tgz.close()<file_sep>import arcpy import os import fnmatch import logging import tempfile import csv import xml.etree.ElementTree as ET def findPopRast(popRastDir, iso3, grumpPopRast, countryBoundaries, outDir): # Look for tif files matches = [] for root, dirnames, filenames in os.walk(popRastDir + "\\" + iso3): for filename in fnmatch.filter(filenames, '*.tif'): matches.append(os.path.join(root, filename)) # If match found return path if len(matches) == 1: return matches[0] # If no matches, clip grump population raster elif len(matches) == 0: logging.warning("No WorldPop raster available. Using GRUMP raster instead.") arcpy.CheckOutExtension("Spatial") old_workspace = arcpy.env.workspace old_scratchWorkspace = arcpy.env.scratchWorkspace tmpdir = tempfile.mkdtemp() arcpy.env.workspace = tmpdir arcpy.env.scratchWorkspace = tmpdir defaultCellSize = arcpy.env.cellSize try: arcpy.FeatureClassToFeatureClass_conversion(countryBoundaries, "in_memory", "countryBoundary", """ iso_alpha3 = '%s' """ % (iso3,)) grumpPopClip = arcpy.sa.ExtractByMask(grumpPopRast, "in_memory/countryBoundary") currentCellSize = (grumpPopClip.meanCellHeight + grumpPopClip.meanCellWidth) / float(2) newCellSize = currentCellSize / float(10) arcpy.env.cellSize = newCellSize grumpPop100m = grumpPopClip / float(100) arcpy.CopyRaster_management(grumpPop100m, os.path.join(outDir, "pop2010%s.tif" % iso3)) return os.path.join(outDir, "pop2010%s.tif" % iso3) finally: arcpy.env.cellSize = defaultCellSize arcpy.Delete_management("in_memory") arcpy.Delete_management(tmpdir) arcpy.env.workspace = old_workspace arcpy.env.scratchWorkspace = old_scratchWorkspace arcpy.CheckInExtension("Spatial") else: logging.error("Multiple population rasters found") def growthRatesJoin(urbanGrowthFc, ruralGrowthFc, countryBoundaries, urbanAreasShp, iso3, outGDB): try: # Extract polygons by country iso arcpy.FeatureClassToFeatureClass_conversion(countryBoundaries, "in_memory", "countryBoundary", """ iso_alpha3 = '%s' """ % (iso3,)) arcpy.FeatureClassToFeatureClass_conversion(urbanAreasShp, "in_memory", "urban_extract", """ ISO3 = '%s' """ % (iso3,)) # Union of urban and boundary polygons arcpy.Union_analysis(["in_memory/countryBoundary", "in_memory/urban_extract"], "in_memory/countryUrbanRural") # Separate urban and rural polygons arcpy.FeatureClassToFeatureClass_conversion("in_memory/countryUrbanRural", "in_memory", "countryUrban", """ ONES = 1 """) arcpy.FeatureClassToFeatureClass_conversion("in_memory/countryUrbanRural", "in_memory", "countryRural", """ ONES = 0 """) # Join growth rates data arcpy.JoinField_management("in_memory/countryUrban", "iso_alpha2", urbanGrowthFc, "ISO2", ["Growth20102015"]) arcpy.JoinField_management("in_memory/countryRural", "iso_alpha2", ruralGrowthFc, "ISO2", ["Growth20102015"]) # Merge urban and rural data back together arcpy.Merge_management(["in_memory/countryUrban", "in_memory/countryRural"], outGDB + "/growthRates%s" % iso3) finally: # Tidy up arcpy.Delete_management("in_memory") def estimate2012pop(popRast2010Path, outGDB, outDir, iso3): arcpy.CheckOutExtension("Spatial") old_workspace = arcpy.env.workspace old_scratchWorkspace = arcpy.env.scratchWorkspace tmpdir = tempfile.mkdtemp() arcpy.env.workspace = tmpdir arcpy.env.scratchWorkspace = tmpdir try: # Get raster cell size popRast2010 = arcpy.Raster(popRast2010Path) cellSize = (popRast2010.meanCellHeight + popRast2010.meanCellWidth) / float(2) # Create raster of growth rates from feature class arcpy.PolygonToRaster_conversion(outGDB + "/growthRates%s" % iso3, "Growth20102015", "growth20102015.tif", cell_assignment="MAXIMUM_AREA", cellsize=cellSize) pop2012 = popRast2010 * arcpy.sa.Exp(arcpy.Raster("growth20102015.tif") / 100 * 2) arcpy.CopyRaster_management(pop2012, os.path.join(outDir, "%s2012unadjustedPop.tif" % iso3), pixel_type="32_BIT_FLOAT") finally: arcpy.Delete_management("in_memory") arcpy.Delete_management(tmpdir) arcpy.env.workspace = old_workspace arcpy.env.scratchWorkspace = old_scratchWorkspace arcpy.CheckInExtension("Spatial") def getUnPopEst(unPopEstCsv, isoNum): # Retrieve UN estimate of population from csv with open(unPopEstCsv, 'rb') as csvFile: reader = csv.reader(csvFile) for row in reader: if row[0] == isoNum and row[3] == "Medium" and row[4] == "2012": unPop = float(row[8]) * 1000 return unPop def getUnWraEst(unPopBySexCsv, isoNum): # Retrieve UN estimate of women of reproductive age from csv with open(unPopBySexCsv, 'rb') as csvFile: reader = csv.reader(csvFile) wra = 0 agebands = ("15-19", "20-24", "25-29", "30-34", "35-39", "40-44", "45-49") for row in reader: if row[0] == isoNum and row[3] == "Medium" and row[4] == "2012" and row[6] in agebands: wra += float(row[10]) * 1000 return wra def adjust2012pop(outDir, unPop2012, iso3): arcpy.CheckOutExtension("Spatial") old_workspace = arcpy.env.workspace old_scratchWorkspace = arcpy.env.scratchWorkspace tmpdir = tempfile.mkdtemp() arcpy.env.workspace = tmpdir arcpy.env.scratchWorkspace = tmpdir try: unadjustedPopRast = os.path.join(outDir, "%s2012unadjustedPop.tif" % iso3) # Calculate total pop rasterMask = arcpy.Raster(unadjustedPopRast) * 0 arcpy.CopyRaster_management(rasterMask, "rasterMask.tif", pixel_type="1_BIT") arcpy.BuildRasterAttributeTable_management("rasterMask.tif", "Overwrite") arcpy.sa.ZonalStatisticsAsTable("rasterMask.tif", "VALUE", unadjustedPopRast, "in_memory/zonalStats", "DATA", "SUM") with arcpy.da.SearchCursor("in_memory/zonalStats", "SUM") as c: for row in c: unadjustedTotal = row[0] # Calculate adjusted population raster adjustmentFactor = unPop2012 / unadjustedTotal adjustedPop = arcpy.sa.Times(unadjustedPopRast, adjustmentFactor) arcpy.CopyRaster_management(adjustedPop, os.path.join(outDir, "%s2012adjustedPop.tif" % iso3), pixel_type="32_BIT_FLOAT") finally: arcpy.Delete_management("in_memory") arcpy.Delete_management(tmpdir) arcpy.env.workspace = old_workspace arcpy.env.scratchWorkspace = old_scratchWorkspace arcpy.CheckInExtension("Spatial") def estimateWra2012(outDir, ageFc, iso3, unWra2012, unPop2012): arcpy.CheckOutExtension("Spatial") old_workspace = arcpy.env.workspace old_scratchWorkspace = arcpy.env.scratchWorkspace tmpdir = tempfile.mkdtemp() arcpy.env.workspace = tmpdir arcpy.env.scratchWorkspace = tmpdir try: # Get raster cell size popRast = arcpy.Raster(os.path.join(outDir, "%s2012adjustedPop.tif" % iso3)) cellSize = (popRast.meanCellHeight + popRast.meanCellWidth) / float(2) # Extract subnational age breakdowns for selected country arcpy.FeatureClassToFeatureClass_conversion(ageFc, "in_memory", "age_extract", """ ISO = '%s' """ % (iso3,)) # If no features found, use national data from spreadsheet if int(arcpy.GetCount_management("in_memory/age_extract").getOutput(0)) == 0: logging.warning("No sub-national age bands, using national data") wocba = float(unWra2012) / float(unPop2012) wra2012 = wocba * popRast else: arcpy.PolygonToRaster_conversion("in_memory/age_extract", "WOCBA", "wocba.tif", cell_assignment="MAXIMUM_AREA", cellsize=cellSize) wra2012 = arcpy.Raster("wocba.tif") * popRast arcpy.CopyRaster_management(wra2012, os.path.join(outDir, "%s2012unadjustedWRA.tif" % iso3), pixel_type="32_BIT_FLOAT") finally: arcpy.Delete_management("in_memory") arcpy.Delete_management(tmpdir) arcpy.env.workspace = old_workspace arcpy.env.scratchWorkspace = old_scratchWorkspace arcpy.CheckInExtension("Spatial") def adjust2012wra(outDir, unWra2012, iso3): arcpy.CheckOutExtension("Spatial") old_workspace = arcpy.env.workspace old_scratchWorkspace = arcpy.env.scratchWorkspace tmpdir = tempfile.mkdtemp() arcpy.env.workspace = tmpdir arcpy.env.scratchWorkspace = tmpdir try: unadjustedWraRast = os.path.join(outDir, "%s2012unadjustedWRA.tif" % iso3) # Calculate total wra rasterMask = arcpy.Raster(unadjustedWraRast) * 0 arcpy.CopyRaster_management(rasterMask, "rasterMask.tif", pixel_type="1_BIT") arcpy.BuildRasterAttributeTable_management("rasterMask.tif", "Overwrite") arcpy.sa.ZonalStatisticsAsTable("rasterMask.tif", "VALUE", unadjustedWraRast, "in_memory/zonalStats", "DATA", "SUM") with arcpy.da.SearchCursor("in_memory/zonalStats", "SUM") as c: for row in c: unadjustedTotal = row[0] # Calculate adjusted WRA raster adjustmentFactor = unWra2012 / unadjustedTotal adjustedWra = arcpy.sa.Times(unadjustedWraRast, adjustmentFactor) arcpy.CopyRaster_management(adjustedWra, os.path.join(outDir, "%s2012adjustedWRA.tif" % iso3), pixel_type="32_BIT_FLOAT") finally: arcpy.Delete_management("in_memory") arcpy.Delete_management(tmpdir) arcpy.env.workspace = old_workspace arcpy.env.scratchWorkspace = old_scratchWorkspace arcpy.CheckInExtension("Spatial") def urbanAndRuralPopAndWra(outDir, countryBoundaries, urbanAreasShp, iso3): arcpy.CheckOutExtension("Spatial") try: # Extract polygons for selected country arcpy.FeatureClassToFeatureClass_conversion(countryBoundaries, "in_memory", "countryExtract", """ iso_alpha3 = '%s' """ % iso3) arcpy.FeatureClassToFeatureClass_conversion(urbanAreasShp, "in_memory", "urban_extract", """ ISO3 = '%s' """ % iso3) # Identity of urban and admin boundary polygons arcpy.Identity_analysis(countryBoundaries, "in_memory/urban_extract", "in_memory/countryUrbanRural", "NO_FID") # Aggregate polygons arcpy.Dissolve_management("in_memory/countryUrbanRural", "in_memory/zones", ["ONES"]) # Create urbanOrRural field for zonal statistics arcpy.AddField_management("in_memory/zones", "urbanOrRural", "TEXT") with arcpy.da.UpdateCursor("in_memory/zones", ["ONES", "urbanOrRural"]) as upCur: for row in upCur: if row[0] == 1: row[1] = "URBAN" else: row[1] = "RURAL" upCur.updateRow(row) # Remove "ONES" field as no longer needed arcpy.DeleteField_management("in_memory/zones", "ONES") # Calculate total urban and rural populations arcpy.sa.ZonalStatisticsAsTable("in_memory/zones", "urbanOrRural", os.path.join(outDir, "%s2012adjustedPop.tif" % iso3), "in_memory/zonalStatsPop", "DATA", "SUM") urbanPop = 0 ruralPop = 0 with arcpy.da.SearchCursor("in_memory/zonalStatsPop", ["urbanOrRural", "SUM"]) as c: for row in c: if row[0] == "URBAN": urbanPop += row[1] elif row[0] == "RURAL": ruralPop += row[1] # Calculate total urban and rural women of reproducive age arcpy.sa.ZonalStatisticsAsTable("in_memory/zones", "urbanOrRural", os.path.join(outDir, "%s2012adjustedWRA.tif" % iso3), "in_memory/zonalStatsWra", "DATA", "SUM") urbanWra = 0 ruralWra = 0 with arcpy.da.SearchCursor("in_memory/zonalStatsWra", ["urbanOrRural", "SUM"]) as c: for row in c: if row[0] == "URBAN": urbanWra += row[1] elif row[0] == "RURAL": ruralWra += row[1] return (urbanPop, ruralPop, urbanWra, ruralWra) finally: arcpy.Delete_management("in_memory") arcpy.CheckInExtension("Spatial") if __name__ == "__main__": # Input paths countryListXml = "C:/Users/cr2m14/Google Drive/BirthsandPregnanciesMapping/country_list.xml" # List of countries to process popRastDir = "C:\\BirthsandPregnancies\\WorldPop" # Population raster directory grumpPopRast = "C:/BirthsandPregnancies/WorldPop/AfriPop_demo_2015_1km/ap15v4_TOTAL_adj.tif" # GRUMP population raster countryBoundaries = "C:/Users/cr2m14/Google Drive/BirthsandPregnanciesMapping/LSIB-WSV/lsib-wsv.gdb/detailed_world_polygons" # Country boundary polygons urbanGrowthFc = "C:/Users/cr2m14/Google Drive/BirthsandPregnanciesMapping/Growth Rates/GrowthRates.gdb/Urban" # Urban growth rates ruralGrowthFc = "C:/Users/cr2m14/Google Drive/BirthsandPregnanciesMapping/Growth Rates/GrowthRates.gdb/Rural" # Rural growth rates urbanAreasShp = "C:/Users/cr2m14/Google Drive/BirthsandPregnanciesMapping/GRUMP/af_as_lac_urban_Mano.shp" # Urban area extents unPopEstCsv = "C:/Users/cr2m14/Google Drive/BirthsandPregnanciesMapping/WPP2012_DB02_POPULATIONS_ANNUAL.CSV" # UN Population Estimates unPopBySexCsv = "C:/Users/cr2m14/Google Drive/BirthsandPregnanciesMapping/WPP2012_DB04_POPULATION_BY_SEX_ANNUAL.CSV" # UN Population estimates by age and sex ageFc = "C:/Users/cr2m14/Google Drive/BirthsandPregnanciesMapping/popByAgeGroup.gdb/asia_africa" # Asia/Africa Sub-national breakdown of population by age # Output paths outDir = "C:/BirthsandPregnancies/results/raster" # Raster output directory outGDB = "C:/Users/cr2m14/Google Drive/BirthsandPregnanciesMapping/results/test/result.gdb" # Vector output geodatabase outCsvFile = r"C:\BirthsandPregnancies\results\csv\popAndWra2012.csv" # Output CSV file # Set up logging logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s", level=logging.INFO) # Allow files to be overwritten arcpy.env.overwriteOutput = True # Loop through countries listed within xml file countryList = ET.parse(countryListXml).getroot() # Create CSV writer for output data with open(outCsvFile, 'ab') as csvFile: csvWriter = csv.writer(csvFile) for country in countryList.findall("country"): countryName = country.find("name").text iso2 = country.find("iso2").text iso3 = country.find("iso3").text isoNum = country.find("isoNum").text logging.info("Processing %s" % countryName) # Find population raster logging.info("Retrieving population raster") popRast2010Path = findPopRast(popRastDir, iso3, grumpPopRast, countryBoundaries, outDir) # Join growth rates to country boundaries logging.info("Joining growth rates to country boundaries") growthRatesJoin(urbanGrowthFc, ruralGrowthFc, countryBoundaries, urbanAreasShp, iso3, outGDB) # Estimate population for 2012 logging.info("Estimating population for 2012") estimate2012pop(popRast2010Path, outGDB, outDir, iso3) # Get UN estimate of population logging.info("Retrieving UN population estimate from csv file") unPop2012 = getUnPopEst(unPopEstCsv, isoNum) # Get UN estimate of women of reproductive age logging.info("Retrieving UN estimate of women of reproductive age from csv file") unWra2012 = getUnWraEst(unPopBySexCsv, isoNum) # Adjust population estimates to match UN figures logging.info("Adjusting population estimate to match UN figures") adjust2012pop(outDir, unPop2012, iso3) # Estimate women of reproductive age logging.info("Estimating number of women of reproductive age") estimateWra2012(outDir, ageFc, iso3, unWra2012, unPop2012) # Adjust women of reproductive age total to match UN figures logging.info("Adjusting estimate of women of reproductive age to match UN figures") adjust2012wra(outDir, unWra2012, iso3) # Calculate total urban and rural population and women of reproductive age logging.info("Calculating total urban and rural population and women of reproductive age") urbanPop, ruralPop, urbanWra, ruralWra = urbanAndRuralPopAndWra(outDir, countryBoundaries, urbanAreasShp, iso3) # Write outputs to csv logging.info("Writing output data to csv file") csvWriter.writerow([iso3, countryName, urbanPop, ruralPop, urbanWra, ruralWra])
07eac1d6ba842346fcebc32e6843c7164a8b24a1
[ "Python", "Text" ]
10
Python
cewarren6/BirthsandPregnanciesMapping
da4921378ccf7b17a820947f8ff22ed814a3bbb1
13253b3c438916c17359f9f21051a2e9dc5d1b76
refs/heads/master
<file_sep><?php class Stand{ // database connection and table name private $conn; private $table_name = "standen"; // object properties public $id; public $naam; public $gespeeld; public $gewonnen; public $gelijk; public $verloren; public $punten; public $dpv; public $dpt; public $saldo; // constructor with $db as database connection public function __construct($db){ $this->conn = $db; } // read products function read(){ // select all query $query = "SELECT teams.idComp AS id, teams.naam AS naam, gewonnen, gelijk, verloren, dpv, dpt FROM " . $this->table_name . " LEFT JOIN teams ON standen.idTeam = teams.id"; // prepare query statement $stmt = $this->conn->prepare($query); // execute query $stmt->execute(); return $stmt; } } <file_sep><?php class Sporthal{ // database connection and table name private $conn; private $table_name = "sporthallen"; // object properties public $id; public $naam; public $adres; public $postcode; public $woonplaats; public $telefoon; // constructor with $db as database connection public function __construct($db){ $this->conn = $db; } // read products function read(){ // select all query $query = "SELECT id, naam, adres, postcode, woonplaats, telefoon FROM " . $this->table_name . " ORDER BY id DESC"; // prepare query statement $stmt = $this->conn->prepare($query); // execute query $stmt->execute(); return $stmt; } // create team function create(){ // query to insert record $query = "INSERT INTO " . $this->table_name . " SET naam=:naam, adres=:adres, postcode=:postcode, woonplaats=:woonplaats, telefoon=:telefoon"; // prepare query $stmt = $this->conn->prepare($query); // sanitize $this->naam=htmlspecialchars(strip_tags($this->naam)); $this->adres=htmlspecialchars(strip_tags($this->adres)); $this->postcode=htmlspecialchars(strip_tags($this->postcode)); $this->woonplaats=htmlspecialchars(strip_tags($this->woonplaats)); $this->telefoon=htmlspecialchars(strip_tags($this->telefoon)); // bind values $stmt->bindParam(":naam", $this->naam); $stmt->bindParam(":adres", $this->adres); $stmt->bindParam(":postcode", $this->postcode); $stmt->bindParam(":woonplaats", $this->woonplaats); $stmt->bindParam(":telefoon", $this->telefoon); // execute query if($stmt->execute()){ return true; } return false; } }<file_sep><?php class Team{ // database connection and table name private $conn; private $table_name = "teams"; // object properties public $id; public $kleding; public $comp; public $naam; // constructor with $db as database connection public function __construct($db){ $this->conn = $db; } // read products function read(){ // select all query $query = "SELECT id, idKleding, idComp, naam FROM " . $this->table_name . " ORDER BY idComp DESC"; // prepare query statement $stmt = $this->conn->prepare($query); // execute query $stmt->execute(); return $stmt; } // create team function create(){ // query to insert record $query = "INSERT INTO " . $this->table_name . " SET idKleding=:kleding, idComp=:comp, naam=:naam"; // prepare query $stmt = $this->conn->prepare($query); // sanitize $this->kleding=htmlspecialchars(strip_tags($this->kleding)); $this->comp=htmlspecialchars(strip_tags($this->comp)); $this->naam=htmlspecialchars(strip_tags($this->naam)); // bind values $stmt->bindParam(":kleding", $this->kleding); $stmt->bindParam(":comp", $this->comp); $stmt->bindParam(":naam", $this->naam); // execute query if($stmt->execute()){ return true; } return false; } }
d17347cb9b9315f2589ccfc2fe8e78381e2ceff5
[ "PHP" ]
3
PHP
TeamEurekaGaming/api
beb67d43bc9c0599f6b8b0c4cbc6e16370d9fcea
92f55186482f43ddbac8133a0ebe22c85d14a23c
refs/heads/master
<repo_name>Hugo-janasik/Formulaire-PHP-HTML<file_sep>/description.php <!DOCTYPE html> <html> <head> <title>Description</title> <form method="post" action="index.php"> <p>Description</p> <br> <!-- Display our Data --> <!-- Customer_Name --> Customer_name: <?php echo $_POST["customer_name"]; ?> <input type="hidden" name="customer_name" value="<?php echo $_POST['customer_name'] ?>"> <br> <!-- Customer_Contact_Name --> Customer_Contact_name: <?php echo $_POST["customer_contact_name"]; ?> <input type="hidden" name="customer_contact_name" value="<?php echo $_POST['customer_contact_name'] ?>"> <br> <!-- Customer_Contact_Job --> Customer_Contact_job: <?php echo $_POST["customer_contact_job"]; ?> <input type="hidden" name="customer_contact_job" value="<?php echo $_POST['customer_contact_job'] ?>"> <br> <!-- SFDC_Opp_ID --> SFDC_Opp_Id: <?php echo $_POST["sfdc_opp_id"]; ?> <input type="hidden" name="sfdc_opp_id" value="<?php echo $_POST['sfdc_opp_id'] ?>"> <br> <!-- Expected Revenue --> <input type="hidden" name="revenue" value="<?php echo $_POST['revenue'] ?>"> <br> PoC Startign Date: <?php echo $_POST["date_poc_starting_date"]?> <br> <input type="hidden" name="date_poc_starting_date" value="<?php echo $_POST["date_poc_starting_date"] ?>"> <br> Expected Decision Date: <?php echo $_POST["date_expected_decision"] ?> <input type="hidden" name="date_expected_decision" value="<?php echo $_POST["date_expected_decision"] ?>"> <br> Usage Scenario & Workloads: <br> <textarea readonly="" rows="8" cols="45"><?php echo $_POST["comment"]?></textarea> <br> <input type="hidden" name="comment" value="<?php echo $_POST["comment"] ?>"> <?php if ($_POST["vsanProduct"] != "None") { echo "vSAN:"; echo " "; echo $_POST["vsanProduct"]; echo "<br>"; } ?> <input type="hidden" name="vsanProduct" value="<?php echo $_POST["vsanProduct"]?>"> <?php if ($_POST["nsxProduct"] != "None") { echo "NSX:"; echo " "; echo $_POST["nsxProduct"]; echo "<br>"; } ?> <input type="hidden" name="nsxProduct" value="<?php echo $_POST["nsxProduct"]?>"> <?php if ($_POST["vsphereProduct"] != "None") { echo "vSphere:"; echo " "; echo $_POST["vsphereProduct"]; echo "<br>"; } ?> <input type="hidden" name="vsphereProduct" value="<?php echo $_POST["vsphereProduct"]?>"> <?php if ($_POST["vraProduct"] != "None") { echo "vRA"; echo " "; echo $_POST["vraProduct"]; echo "<br>"; } ?> <input type="hidden" name="vraProduct" value="<?php echo $_POST["vraProduct"]?>"> VMware Pre-Sales : <?php echo $_POST["seName"] ?> <input type="hidden" name="seName" value="<?php echo $_POST["seName"]?>"> <br> VMware Sales : <?php echo $_POST["salesName"]?> <input type="hidden" name="salesName" value="<?php echo $_POST["salesName"]?>"> <br> <!-- Save the Partner Involved area--> <input type="hidden" name="commentary" value="<?php echo $_POST["commentary"]?>"> Demo Description: <br> <textarea readonly="" rows="10" cols="70"><?php echo $_POST["description"]?></textarea> <br> <input type="hidden" name="description" value="<?php echo $_POST["description"] ?>"> <!-- Save the Others Comments Area--> <input type="hidden" name="other" value="<?php echo $_POST["other"]?>"> <input type="submit" value="Return"> </form> <input type="submit" name="Send"> </body> </html><file_sep>/index.php <!DOCTYPE html> <html> <head> <title>First</title> </head> <body> <p>Bonjour Bienvenue sur la page Web dédier au Formulaire pour la config Intel.</p> <p>Pour pouvoir utiliser les machines Intel, Veuillez remplir le formulaire ci-dessous (via Chrome si possible)</p> <form method="post" action="description.php"> <!-- Customer Name--> <p>Customer Name: <?php if (isset($_POST["customer_name"])) { ?> <input type="text" name="customer_name" placeholder="Ex: ACME Corp" id="customer_name" value="<?php echo $_POST["customer_name"] ?>"> <?php } else { ?> <input type="text" name="customer_name" placeholder="Ex: ACME Corp" id="customer_name"> <?php } ?> </p> <!-- Customer Contact Name--> <p>Customer Contact Name: <?php if (isset($_POST["customer_contact_name"])) { ?> <input type="text" name="customer_contact_name" placeholder="Ex: <NAME>" id="customer_contact_name" value="<?php echo $_POST["customer_contact_name"]?>"> <?php } else { ?> <input type="text" name="customer_contact_name" placeholder="Ex: <NAME>" id="customer_contact_name"> <?php } ?> </p> <!-- Custome Contact Job--> <p>Customer Contact Job: <?php if (isset($_POST["customer_contact_job"])) { ?> <input type="text" name="customer_contact_job" placeholder="Ex: Infra Director" id="customer_contact_job" value="<?php echo $_POST["customer_contact_job"] ?>"> <?php } else { ?> <input type="text" name="customer_contact_job" placeholder="Ex: Infra Director" id="customer_contact_job"> <?php } ?> </p> <!-- SFDC Opp ID--> <p>SFDC Opp ID: <?php if (isset($_POST["sfdc_opp_id"])) { ?> <input type="text" name="sfdc_opp_id" placeholder="Ex: 1234567" id="sfdc_opp_id" value="<?php echo $_POST["sfdc_opp_id"] ?>"> <?php } else { ?> <input type="text" name="sfdc_opp_id" placeholder="Ex: 1234567" id="sfdc_opp_id"> <?php } ?> </p> <!-- Expected Revenue--> <p>Expected Revenue ($): <?php if (isset($_POST['revenue'])) { ?> <input type="text" name="revenue" placeholder="Ex: 300 000$" id="revenue" value="<?php echo $_POST['revenue'] ?>"> <?php } else { ?> <input type="text" name="revenue" placeholder="Ex: 300 000$" id="revenue"> <?php } ?> </p> <!-- POC Starting Date--> <p>POC Starting Date: <?php if (isset($_POST["date_poc_starting_date"])) { ?> <input type="date" name="date_poc_starting_date" value="<?php echo $_POST["date_poc_starting_date"] ?>"> <?php } else { ?> <?php $date_poc = date('Y-m-d'); ?> <input type="date" name="date_poc_starting_date" value="<?php echo $date_poc; ?>"> <?php } ?> </p> <!-- Expected Decision Date --> <p>Expected Decision Date: <?php if (isset($_POST["date_expected_decision"])) { ?> <input type="date" name="date_expected_decision" value="<?php echo $_POST["date_expected_decision"] ?>"> <?php } else { ?> <?php $decision_date = date('Y-m-d'); ?> <input type="date" name="date_expected_decision" value="<?php echo($decision_date); ?>"> <?php } ?> </p> <!-- Usage Scenario & Workloads--> <p>Usage Scenario & Workloads:</p> <?php if (isset($_POST["comment"])) { ?> <textarea name="comment" rows="8" cols="45"><?php echo $_POST["comment"]?></textarea> <?php } else { ?> <textarea name="comment" rows="8" cols="45" placeholder="Scenario & Workloads"></textarea><br> <?php } ?> <!-- VMware Product Test--> <p>VMware Product Test</p> VSAN : <select name="vsanProduct"> <option value="None">None</option> <option value="1.0-vsan">vSAN 1.0</option> <option value="1.1-vsan">vSAN 1.1</option> <option value="1.2-vsan">vSAN 1.2</option> <option value="1.3-vsan">vSAN 1.3</option> </select> <br> NSX: <select name="nsxProduct"> <option value="None">None</option> <option value="1.0-nsx">NSX 1.0</option> <option value="1.1-nsx">NSX 1.1</option> <option value="1.2-nsx">NSX 1.2</option> <option value="1.3-nsx">NSX 1.3</option> </select> <br> vSphere : <select name="vsphereProduct"> <option value="None">None</option> <option value="1.0-vsphere">vSphere 1.0</option> <option value="1.1-vsphere">vSphere 1.1</option> <option value="1.2-vsphere">vSphere 1.2</option> <option value="1.3-vsphere">vSphere 1.3</option> </select> <br> vRA : <select name="vraProduct"> <option value="None">None</option> <option value="1.0-vra">vRA 1.0</option> <option value="1.1-vra">vRA 1.1</option> <option value="1.2-vra">vRA 1.2</option> <option value="1.3-vra">vRA 1.3</option> </select> <br> <!-- SE 'list'--> <p>VMware Pre-Sales : <?php if (isset($_POST["seName"])) { ?> <input type="text" name="seName" value="<?php echo $_POST["seName"]?>"> <?php } else { ?> <input type="text" name="seName" placeholder="<NAME>"></p> <?php } ?> <!-- Sales 'list'--> <p>VMware Sales : <?php if (isset($_POST["salesName"])) { ?> <input type="text" name="salesName" value="<?php echo $_POST["salesName"] ?>"> <?php } else { ?> <input type="text" name="salesName" placeholder="<NAME>"></p> <?php } ?> <!-- VMware PArtner Invloved--> <p>VMware Partner Involved</p> <?php if (isset($_POST["commentary"])) { ?> <textarea name="commentary" rows="8" cols="45"><?php echo $_POST["commentary"]?></textarea> <?php } else { ?> <textarea name="commentary" rows="8" cols="45" placeholder="Axians"></textarea> <?php }?> <!-- Demo Description--> <p>Demo Description</p> <?php if (isset($_POST["description"])) { ?> <textarea name="description" rows="8" cols="45"><?php echo $_POST["description"]?></textarea> <?php } else { ?> <textarea name="description" rows="10" cols="70" placeholder="Demo Description"></textarea> <br> <?php } ?> <!-- Other Comments--> <p>Other comments</p> <?php if (isset($_POST["other"])) { ?> <textarea name="other" rows="8" cols="50"><?php echo $_POST["other"]?></textarea> <?php } else { ?> <textarea name="other" rows="8" cols="50" placeholder="Comments"></textarea> <?php } ?> <!-- Submit Button--> <p>Thank you <br>Click on submit to submit</p> <input type="submit" value="Submit"> </form> </body> </html><file_sep>/README.md # Formulaire-PHP-HTML
fa96bd413617475aea321c56538f7dc42eaa94ab
[ "Markdown", "PHP" ]
3
PHP
Hugo-janasik/Formulaire-PHP-HTML
126b088e83542fbef3e35f57ae296d80dc278695
63ee3fd05d1e970c8df8696924061573773beb99
refs/heads/master
<repo_name>zachalbert/nthnth<file_sep>/src/js/app.js import 'mediaelement' import './modules' import './modules/prism' import './modules/site' import './modules/svg' import './modules/ambient-light' import './modules/smooth-scroll' import './modules/scroll-magic' import './modules/sidebar' import './modules/lazy' import './modules/main-nav' <file_sep>/src/html/colorGen.html {% extends 'layouts/application.njk' %} {% block title %}Home{% endblock %} {% block content %} <br><br><p class="text-muted text-center">In development, go <a href="/">home</a></p> {% endblock %} <file_sep>/src/js/modules/scroll-magic.js import ScrollMagic from 'scrollmagic'; // init controller var controller = new ScrollMagic.Controller(); var trigger = $('.fixed-scroll-offset'); if( trigger.length ) { var sidebarTrigger = trigger.offset().top - $('.nav--top').outerHeight(); } if( sidebarTrigger ) { var fixSidebar = new ScrollMagic.Scene({ offset: sidebarTrigger // start this scene once sidebarTrigger has been reached }) .setPin(".sidebar--fixed", { pushFollowers: false }); // pins the element for the the scene's duration // Add one or more scenes to the controller controller.addScene([ fixSidebar ]); } <file_sep>/gulpfile.js/tasks/delayRefresh.js var config = require('config') var gulp = require('gulp') var delay = function(cb) { setTimeout(function() { cb() }, config.get('contentful.refreshDelay') * 1000) } gulp.task('delayRefresh', [], delay) module.exports = delay <file_sep>/src/content/sample.md --- sample: data title: "Sample" date: 12-12-2012 --- # Sample Data Use markdown files in the /content folder for quick, one-off additions to a site that are specific to a single client and unlikely to reoccur. Avoid changing the content model in contentful unless it makes sense to change for all clients. Data in this file is accessible alongside the data from contentful in the templates. Contentful content is accessed via `{{ contentful.title }}`, whereas data in this file is accessed via `{{ FILE_NAME.title }}` (which refers to the "title:" key in the front matter). <file_sep>/src/js/modules/sidebar.js /** * If the initial state is on a larger screen, remove the collapsed class from div.flexible-container **/ if( document.documentElement.clientWidth >= 992 ) { toggleSidebar(); } $('.sidebar__closer__trigger').click( function() { toggleSidebar(); }); function toggleSidebar() { $('.sidebar__closer__trigger > .icon').toggleClass('icon--flipped'); $('.flexible-container').toggleClass('flexible-container--collapsed flexible-container--expanded'); } (function($) { var resizeTimer; // Set resizeTimer to empty so it resets on page load function resizeFunction() { if( (document.documentElement.clientWidth <= 768) && $(".flexible-container").hasClass("flexible-container--expanded") ) { toggleSidebar(); } }; // On resize, run the function and reset the timeout // 250 is the delay in milliseconds. Change as you see fit. $(window).resize(function() { clearTimeout(resizeTimer); resizeTimer = setTimeout(resizeFunction, 250); }); })(jQuery); <file_sep>/src/js/modules/smooth-scroll.js import smoothScroll from 'smooth-scroll'; smoothScroll.init(); <file_sep>/src/js/modules/main-nav.js /** * Main top navigation. Covers hamburger menu. **/ $('.nav__menu-toggle').click(function() { toggleMenu(); }); $('.nav__overlay').click(function() { toggleMenu(); }); $(document).keyup(function(e) { if (e.keyCode === 27) toggleMenu(); // esc }); function toggleMenu() { $('.nav--top').toggleClass('is-visible'); } <file_sep>/src/js/modules/lazy.js /** * * Lazy loading via layzr.js * **/ import Layzr from 'layzr.js' const instance = Layzr({ threshold: 100 // Load images that are 100% of the screen height away from the bottom of the viewport }) document.addEventListener('DOMContentLoaded', function(event) { instance .update() // track initial elements .check() // check initial elements .handlers(true) // bind scroll and resize handlers }); <file_sep>/src/content/pricing.md --- - name: Personal price: 18 features: - Memory: "256 MB" - SSD Space: "10 GB" - Bandwidth: "Unmetered" - name: Professional featured: true price: 24 features: - Memory: "512 MB" - SSD Space: "30 GB" - Bandwidth: "Unmetered" - name: Corporate price: 38 features: - Memory: "1024 MB" - SSD Space: "60 GB" - Bandwidth: "Unmetered" --- <file_sep>/gulpfile.js/tasks/html.js var config = require('../config') if(!config.tasks.html) return var browserSync = require('browser-sync') var theConfig = require('config') var contentfulSync = require("../lib/contentfulSync") var contentfulPages = require("../lib/contentfulPages") var data = require('gulp-data') var faker = require('gulp-faker'); var fs = require('fs') var gulp = require('gulp') var gulpif = require('gulp-if') var handleErrors = require('../lib/handleErrors') var prettify = require('gulp-jsbeautifier') var path = require('path') var render = require('gulp-nunjucks-render') var exclude = path.normalize('!**/{' + config.tasks.html.excludeFolders.join(',') + '}/**') var paths = { src: [ path.join( config.root.src, config.tasks.html.src, '/**/*.{' + config.tasks.html.extensions + '}' ), exclude ], dest: path.join(config.root.dest, config.tasks.html.dest), } var getData = function(file) { var dataPath = path.resolve(config.root.src, config.tasks.html.src, config.tasks.html.dataFile) return JSON.parse(fs.readFileSync(dataPath, 'utf8')) } var htmlTask = function() { return gulp.src(paths.src) .pipe(contentfulPages()) .pipe(data(contentfulSync)) .pipe(data(getData)) .pipe(data(function(file) { return { path: file.relative } })) .pipe(faker()) .on('error', handleErrors) .pipe(render({ path: [path.join(config.root.src, config.tasks.html.src)], envOptions: { watch: false, autoescape: false }, manageEnv: function(environment) { environment.addGlobal('getContext', function(name) { return (name) ? this.ctx[name] : this.ctx; }); environment.addGlobal('getCanonicalLink', function(site, path) { return `//${ site.canonicalLink }/${ path }` }); environment.addGlobal('config', theConfig); environment.addGlobal('getIframeSrc', function(src) { // Strip default style parameters on Gcal's embed, and replace them with params that suck less let url = src.split(';src=')[1]; let baseUrl = 'https://calendar.google.com/calendar/embed?'; let styleArgs = 'showTitle=0&amp;showNav=0&amp;showPrint=0&amp;showCalendars=0&amp;height=600&amp;wkst=1&amp;bgcolor=%23FFFFFF&amp;'; let iframeSrc = baseUrl + styleArgs + url; return iframeSrc; }) } })) .on('error', handleErrors) .pipe(prettify({ "indent_size": 2, "preserve_newlines": true, "max_preserve_newlines": 0 })) .pipe(gulp.dest(paths.dest)) .on('end', browserSync.reload) } gulp.task('html', htmlTask) module.exports = htmlTask <file_sep>/src/js/modules/site.js /** * Prevent default for any link without a proper href **/ $('a[href="#"]').click( function(e) { e.preventDefault(); }) <file_sep>/README.md # Getting started - Get the keys from: - `APIs -> Content delivery / preview keys -> Website key` - [Management Key](https://www.contentful.com/developers/docs/references/authentication/#the-content-management-api) -> Getting OAuth Token ```bash cp config/default.json config/development.json # Edit and add contentful keys npm install npm start ``` # Debugging ## How do I see what variables are in the templates? - When in development mode, you can access `__config__` from the console to see all defined variables at the top level. - Are you in a macro or partial? Use `{{ this | dump }}` to see it on the page. # Contentful ## Data Model - site - title - description - styleClasses - added to `<body></body>` - canonicalLink - should be the hostname, used to construct a link for every page (based off path) - twitterUsername - username of the page (or site's) author - favicon - upload of the favicon - pages - the top level pages for the site ## Navigation The navigation is constructed via. links from the root site object and goes down via. children. site -> pages -> children(pages) ## Integration with Netlify - Create a webhook in Netlify, copy the url - Go to `Settings -> Webhooks` in Contentful, paste the url # Overview Forked from [Gulp Starter](https://github.com/vigetlabs/gulp-starter.git), then stuff was changed and added: - Nunjucks for templating, located in `src/html` - Content editing is done in markdown on prose.io - Gulp will process all `*.md` docs in `src/content/*` - Continuous deployment is set up through host netlify, which is watching the repo for commits to `master`. `https://resolutebuilders.netlify.com/` - As such, all dev should be done on branches and PR'ed into master. For now, let's use the main `dev` branch. ## TODO [ ] More robust image overlays that do color grading and correction [ ] Go over H5BP optimizations [ ] Sidebar scroller bug: Open dev tools (bottom aligned), then scroll to the bottom of a page with a collapsible sidebar, then close dev tools. The sidebar links will stay pinned to the bottom of the page. ## Components [x] Section [x] Content blocks [ ] Form builder; port forms from the base project to start What follows is stuff from the original readme. -- Features | Tools Used ------ | ----- **CSS** | [Sass](http://sass-lang.com/) ([Libsass](http://sass-lang.com/libsass) via [node-sass](https://github.com/sass/node-sass)), [Autoprefixer](https://github.com/postcss/autoprefixer), [CSSNano](https://github.com/ben-eb/cssnano), Source Maps **JavaScript** | [Babel](http://babeljs.io/), [Webpack](http://webpack.github.io/) **HTML** | [Nunjucks](https://mozilla.github.io/nunjucks/), [gulp-data](https://github.com/colynb/gulp-data), or bring your own **Images** | Compression with [imagemin](https://www.npmjs.com/package/gulp-imagemin) **Icons** | Auto-generated [SVG Sprites](https://github.com/w0rm/gulp-svgstore) and/or [Icon Fonts](https://www.npmjs.com/package/gulp-iconfont) **Fonts** | Folder and `.sass` mixin for including WebFonts **Live Updating** | [BrowserSync](http://www.browsersync.io/), [Webpack Dev Middleware](https://github.com/webpack/webpack-dev-middleware), [Webpack Hot Middleware](https://github.com/glenjamin/webpack-hot-middleware) **Production Builds** | JS and CSS are [uglified](https://github.com/terinjokes/gulp-uglify) and [minified](http://cssnano.co/), [filename md5 hashing (reving)](https://github.com/sindresorhus/gulp-rev), [file size reporting](https://github.com/jaysalvat/gulp-sizereport), local production [Express](http://expressjs.com/) server for testing builds. **JS Testing** | [Karma](http://karma-runner.github.io/0.12/index.html), [Mocha](http://mochajs.org/), [Chai](http://chaijs.com/), and [Sinon](http://sinonjs.org/), Example [Travis CI](https://travis-ci.org/) integration **Deployment** | Quickly deploy `public` folder to gh-pages with [`gulp-gh-pages`](https://github.com/shinnn/gulp-gh-pages) ## Usage Make sure Node installed. I recommend using [NVM](https://github.com/creationix/nvm) to manage versions. This has been tested on Node `0.12.x` - `5.9.0`, and should work on newer versions as well. [File an issue](https://github.com/vigetlabs/gulp-starter/issues) if it doesn't! #### Install Dependencies ```bash npm install ``` #### Run development tasks: ``` npm start ``` Aliases: `npm run gulp`, `npm run development` This is where the magic happens. The perfect front-end workflow. This runs the default gulp task, which starts compiling, watching, and live updating all our files as we change them. BrowserSync will start a server on port 3000, or do whatever you've configured it to do. You'll be able to see live changes in all connected browsers. Don't forget about the additional BrowserSync tools available on port 3001! Why run this as an npm script? NPM scripts add ./node_modules/bin to the path when run, using the packages version installed with this project, rather than a globally installed ones. Never `npm install -g` and get into mis-matched version issues again. These scripts are defined in the `scripts` property of `package.json`. #### Run in tests in watch mode: ```bash npm run test:watch ``` #### Run tests once: ```bash npm run test ``` #### Build production files: ```bash npm run production ``` ### Start compiling, serving, and watching files ``` npm run gulp ``` (or `npm run development`) This runs `gulp` from `./node_modules/bin`, using the version installed with this project, rather than a globally installed instance. All commands in the package.json `scripts` work this way. The `gulp` command runs the `default` task, defined in `gulpfile.js/tasks/default.js`. All files will compile in development mode (uncompressed with source maps). [BrowserSync](http://www.browsersync.io/) will serve up files to `localhost:3000` and will stream live changes to the code and assets to all connected browsers. Don't forget about the additional BrowserSync tools available on `localhost:3001`! To run any other existing task, simply add the task name after the `gulp` command. Example: ```bash npm run gulp production ``` ## Additional Task Details ### Build production-ready files ``` npm run production ``` This will compile revisioned and compressed files to `./public`. To build production files and preview them locally, run ``` npm run demo ``` This will start a static server that serves your production files to http://localhost:5000. This is primarily meant as a way to preview your production build locally, not necessarily for use as a live production server. ### Deploy to gh-pages ``` npm run deploy ``` This task compiles production code and then uses [gulp-gh-pages](https://github.com/shinnn/gulp-gh-pages) to push the contents of your `dest.root` to a `gh-pages` (or other specified) branch, viewable at http://[your-username].github.io/[your-repo-name]. Be sure to update the `homepage` property in your `package.json`. GitHub Pages isn't the most robust of hosting solutions (you'll eventually run into relative path issues), but it's a great place to quickly share in-progress work, and you get it for free. [Surge.sh](http://surge.sh/) might be a good alternative for production-ready static hosting to check out, and is just as easy to deploy to. Where ever you're deploying to, all you need to do is `npm run gulp production` and transfer the contents of the `public` folder to your server however you see fit. For non-static sites (Rails, Craft, etc.), make sure the `production` task runs as part of your deploy process. <file_sep>/gulpfile.js/lib/contentfulPages.js var Promise = require('bluebird'); var _ = require('lodash'); var Buffer = require('buffer').Buffer; var config = require('../config') var contentfulSync = require('./contentfulSync'); var File = require('gulp-util').File; var path = require('path'); var readFile = Promise.promisify(require("fs").readFile); var through = require('through2'); var createFile = function(data) { var fpath = path.join( __dirname, "../../", config.root.src, config.tasks.html.src, ( data.layout ? `pages/${data.layout}.njk` : `pages/default.njk` )) return readFile(fpath, "utf8").then(function(content) { return new File({ path: data.name, contents: new Buffer(content) }) }) } var addPages = function() { var noop = function(chunk, enc, cb) { cb(null, chunk) } var flush = function(cb) { var _this = this; contentfulSync(null, function(err, data) { Promise.each(data.contentful.page, function(page) { return createFile(page).then(function(fobj) { fobj.data = { page: page } _this.emit('data', fobj) }) }).then(function() { cb() }) }) } return through.obj(noop, flush) } module.exports = addPages <file_sep>/gulpfile.js/tasks/markdown.js var config = require('../config') if(!config.tasks.markdown) return var browserSync = require('browser-sync') var data = require('gulp-data') var gulp = require('gulp') var markdown = require('gulp-markdown') var marked = require('marked') var handleErrors = require('../lib/handleErrors') var prettyURL = require('gulp-pretty-url') var path = require('path') var exclude = path.normalize('!**/{' + config.tasks.markdown.excludeFiles.join(',') + '}') var paths = { src: [path.join(config.root.src, config.tasks.markdown.src, '/**/*.{' + config.tasks.markdown.extensions + '}'), exclude], dest: path.join(config.root.dest, config.tasks.markdown.dest), } marked.setOptions({ gfm: true, // Github flavored markdown smartypants: true // Smart quotes }); var markdownTask = function() { return gulp.src(paths.src) .on('error', handleErrors) .pipe(markdown()) .pipe(prettyURL()) .pipe(gulp.dest(paths.dest)) .on('end', browserSync.reload) } gulp.task('markdown', markdownTask) module.exports = markdownTask <file_sep>/gulpfile.js/tasks/markdownToJSON.js var config = require('../config') if(!config.tasks.markdownToJSON) return var browserSync = require('browser-sync') var gulp = require('gulp') var gutil = require('gulp-util') var marked = require('marked') var markdownToJSON = require('gulp-markdown-to-json') var handleErrors = require('../lib/handleErrors') var path = require('path') var paths = { src: [path.join(config.root.src, config.tasks.markdownToJSON.src, '/**/*.{' + config.tasks.markdownToJSON.extensions + '}')], dest: path.join(config.root.dest, config.tasks.markdownToJSON.dest), } marked.setOptions({ gfm: true, // Github flavored markdown smartypants: true // Smart quotes }); var markdownToJSONTask = function() { return gulp.src(paths.src) .on('error', handleErrors) .pipe(gutil.buffer()) .pipe(markdownToJSON(marked, config.tasks.markdownToJSON.output)) .pipe(gulp.dest('./src/html/data')) .on('end', browserSync.reload) } gulp.task('markdownToJSON', markdownToJSONTask) module.exports = markdownToJSONTask <file_sep>/gulpfile.js/tasks/contentfulReload.js var _ = require("lodash") var config = require('config') var gulp = require('gulp') var tunnel = require('contentful-webhook-tunnel') var reloadTask = function() { // This is a stupid hack because of the crappy library. process.env.CONTENTFUL_MANAGEMENT_ACCESS_TOKEN = config.get( "contentful.manageToken") var server = tunnel.createServer({ "spaces": [ config.get("contentful.space") ] }); var handle = _.debounce(function () { console.log("Triggered refresh...") setTimeout(function() { gulp.run('html') }, config.get('contentful.refreshDelay') * 1000) }, config.get('contentful.refreshDelay') * 1000, { 'leading': true, 'trailing': false }); server.on("publish", handle) server.on("unpublish", handle) server.listen(); } gulp.task('contentfulReload', [], reloadTask) module.exports = reloadTask
5133a50625b368c4b703582fd34dcd9deda941d9
[ "JavaScript", "HTML", "Markdown" ]
17
JavaScript
zachalbert/nthnth
55b195959964063f75c2c09249b53d5aea19fc0b
a53bb89cd92ec80dfa7224b7834c88ca08e22610
refs/heads/master
<file_sep>let textWrapper = document.querySelector('.title-1') textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>"); let textWrapper2 = document.querySelector('.title-2') textWrapper2.innerHTML = textWrapper2.textContent.replace(/\S/g, "<span class='letter'>$&</span>"); let textWrapper3 = document.querySelector('.title-3') textWrapper3.innerHTML = textWrapper3.textContent.replace(/\S/g, "<span class='letter'>$&</span>"); let tl = gsap.timeline(); tl.to('.title-1 .letter', { opacity: 1, y: '0', clipPath: 'polygon(0 0, 100% 0, 100% 100%, 0 100%)', stagger: '.03' }) tl.to('.title-2 .letter', { opacity: 1, y: '0', clipPath: 'polygon(0 0, 100% 0, 100% 100%, 0 100%)', stagger: '.03' }, "-=.7") tl.to('.title-3 .letter', { opacity: 1, y: '0', clipPath: 'polygon(0 0, 100% 0, 100% 100%, 0 100%)', stagger: '.03' }, "-=.7") tl.from('p', { opacity: 0, y: '-50px' }, "-=.7") tl.to('.img', { clipPath: 'polygon(0 0, 100% 0, 100% 100%, 0 100%)', ease: Back.easeOut.config(1.7), duration: .75 }, "-=.5") var myAnimation = new hoverEffect({ parent: document.querySelector('.img'), intensity: 0.3, image1: 'https://assets.codepen.io/2621168/abstract1.jpg', image2: 'https://assets.codepen.io/2621168/abstract2.jpg', displacementImage: 'https://assets.codepen.io/2621168/dis.png' }); let title = document.querySelector('.container'); let img = document.querySelector('.img'); let cursorCircle = document.querySelector('.cursor'); let cursor = { x: 0, y: 0 } document.addEventListener('mousemove', (e) => { cursor.x = -e.clientX * .1; cursor.y = -e.clientY * .1; img.style.transform = `translate(${cursor.x}px, ${cursor.y}px)`; cursorCircle.style.transform = `translate(${e.clientX}px, ${e.clientY}px)` }) <file_sep># UI-Hovering-Page
9923596200a3ad7fde192af7ade73635994badbf
[ "JavaScript", "Markdown" ]
2
JavaScript
afzal442/UI-Hovering-Page
9312be28551c1c3a4e7d1533cc71a0d1401ae29a
8bc51e3d217ad90d94377077db9f55e527629852
refs/heads/master
<repo_name>Rowhaagan/futsalphp<file_sep>/config/connection.php </<?php // Database connection $conn = mysqli_connect('localhost', 'rowhaagan', 'password', '<PASSWORD>') OR die('Could not connect because: '. mysqli_connect_error()); ?><file_sep>/admin/ajax/pages.php <?php include("../../config/connection.php"); $id = $_GET['id']; //echo $id; $query = "DELETE FROM pages WHERE page_id = $id"; $result = mysqli_query($conn, $query); if($result){ echo "Page has been Deleted."; } else{ echo "Page couldnot be deleted.<br/>"; echo $query.'<br/>'; echo mysqli_error($conn); } ?><file_sep>/README.md # futsalphp College Incomplete Project <file_sep>/template/navigation.php <nav class="fh5co-nav-style-1" role="navigation" data-offcanvass-position="fh5co-offcanvass-left"> <?php if($debug == 1) { ?> <button id="btn-debug" class="btn btn-default"><i class="fa fa-bug"></i></button> <?php } ?> <div class="container"> <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 fh5co-logo"> <a href="#" class="js-fh5co-mobile-toggle fh5co-nav-toggle"><i></i></a> <a href="#">Manfootster</a> </div> <div class="col-lg-6 col-md-5 col-sm-5 text-center fh5co-link-wrap"> <ul data-offcanvass="yes"> <?php nav_main($conn, $path); ?> </ul> </div> <div class="col-lg-3 col-md-4 col-sm-4 text-right fh5co-link-wrap"> <ul class="fh5co-special" data-offcanvass="yes"> <li><a href="#">Login</a></li> <li><a href="#" class="call-to-action">Get Started</a></li> </ul> </div> </div> </nav><file_sep>/admin/config/setup.php <?php // setup files: error_reporting(0); #Dtatabase connection include('../config/connection.php'); // Constants DEFINE('D_TEMPLATE', 'template'); // function include('functions/data.php'); include('functions/template.php'); include('functions/sandbox.php'); // site setup $debug = data_setting_value($conn, 'debug-status'); if(isset($_GET['page'])){ $page = $_GET['page']; //set $pageid to equal the value given the url } else { $page = 'dashboard'; //set $pageid equal to 1 or to the home page } // Page Setup include('config/queries.php'); #user setup $user = data_user($conn, $_SESSION[username]); ?><file_sep>/admin/views/pages.php <div class="container" style="padding-top:100px;"> <h4>Page Manager</h4> <div class="row"> <div class="col-sm-5 col-md-3"> <div class="list-group"> <a class="list-group-item" href="?page=pages"> <i class="fa fa-plus"></i>Add New Page </a> <?php $query="SELECT * FROM pages ORDER BY page_name ASC"; $result=mysqli_query($conn, $query); while($list = mysqli_fetch_assoc($result)){ $blurb = substr(strip_tags($list['page_banner_des']), 0, 60); ?> <div id="page_<?php echo $list['page_id']; ?>" class="list-group-item <?php selected($list['page_id'], $opened['page_id'], 'active'); ?>"> <h4 class="list-group-item-heading"><?php echo $list['page_name'];?> <span class="pull-right"> <a href="index.php?page=pages&id=<?php echo $list['page_id']?>" class="btn btn-warning"><i class="fa fa-chevron-right"></i></a> <a href="#" id="del_<?php echo $list['page_id']; ?>" class="btn btn-danger btn-delete"><i class="fa fa-trash-o"></i></a> </span> </h4> <p class="list-group-item-text"><?php echo $blurb;?></p> </div> <?php } ?> </div> </div> <div class="col-sm-7 col-md-9"> <?php if(isset($message)){ echo $message; } ?> <form action="index.php?page=pages&id=<?php echo $opened['page_id']; ?>" method="post" role="form"> <!-- cancel if you want to --> <div class="form-group"> <label for="user">User's Name:</label> <select name="user" id="user" class="form-control"> <option value="0">No User</option> <?php $query="SELECT user_id FROM users ORDER BY user_first_name ASC"; $result=mysqli_query($conn, $query); while($user_list = mysqli_fetch_assoc($result)){ $user_data = data_user($conn, $user_list['user_id']); ?> <option value="<?php echo $user_data['user_id']; ?>" <?php if(isset($_GET['id'])){ selected($user_data['user_id'], $opened['user_id'], 'selected'); } else { selected($user_data['user_id'], $user['user_id'], 'selected'); // here $user['user_id'] is logged in user's id or name } ?> > <?php echo $user_data['fullname']; ?> </option> <!--here $user_data['user_id'] is user_id field from users table and $opened['user_id'] is user_id field from pages table --> <?php } ?> </select> </div> <div class="form-group"> <label for="name">Page Name:</label> <input type="text" name="name" id="name" class="form-control" value="<?php echo $opened['page_name']; ?>" placeholder="Page Name" autocomplete="off"> </div> <div class="form-group"> <label for="slug">Page Slug:</label> <input type="text" name="slug" id="slug" class="form-control" value="<?php echo $opened['page_slug']; ?>" placeholder="Page Slug" autocomplete="off"> </div> <div class="form-group"> <label for="title">Page Title:</label> <input type="text" name="title" id="title" class="form-control" value="<?php echo $opened['page_title']; ?>" placeholder="Page Title" autocomplete="off"> </div> <div class="form-group"> <label for="banner_text">Page Banner Text:</label> <input type="text" name="banner_text" id="banner_text" class="form-control" value="<?php echo $opened['page_banner_title']; ?>" placeholder="Banner Text" autocomplete="off"> </div> <div class="form-group"> <label for="banner_des">Page Banner Description:</label> <textarea name="banner_des" id="banner_des" class="form-control" rows="8" placeholder="Banner Description"><?php echo $opened['page_banner_des']; ?></textarea> </div> <div class="form-group"> <label for="banner_btn_text">Page Banner Button Text:</label> <input type="text" name="banner_btn_text" id="banner_btn_text" class="form-control" value="<?php echo $opened['page_banner_btn_text']; ?>" placeholder="Banner Button Text" autocomplete="off"> </div> <button type="submit" class="btn btn-default">Save</button> <input type="hidden" name="submitted" value="1"> <?php if(isset($opened['page_id'])) { ?> <input type="text" name="id" value="<?php echo $opened['page_id']; ?>"> <?php } ?> </form> </div> </div> </div> <file_sep>/admin/login.php <?php #start session session_start(); #Dtatabase connection include('../config/connection.php'); if($_POST){ $query="SELECT * FROM users WHERE user_email = '$_POST[email]' AND user_password =SHA1('$_POST[password]')"; $result=mysqli_query($conn, $query); if(mysqli_num_rows($result)==1){ $_SESSION['username'] = $_POST['email']; header('Location: index.php'); } } ?> <!DOCTYPE html> <head> <title>Manfootster | Admin Login</title> <?php include('config/css.php'); ?> </head> <body class=pagelogin> <div class="login-page"> <div class="form"> <?php if($_POST){ echo $_POST['email']; echo '<br/>'; echo $_POST['password']; } ?> <form class="login-form" role="form" action="login.php" method="post" > <input type="text" name="email" id="email" placeholder="Username"/> <input type="<PASSWORD>" name="password" id="password" placeholder="<PASSWORD>"/> <button>login</button> </form> </div> </div> <?php include('config/js.php'); ?> </body> <file_sep>/admin/views/users.php <?php if(isset($opened['user_id'])) { ?> <script> $(document).ready(function() { Dropzone.autoDiscover = false; var myDropzone = new Dropzone("#avatar-dropzone"); }); </script> <?php } ?> <div class="container" style="padding-top:100px;"> <h4>User Manager</h4> <div class="row"> <div class="col-sm-5 col-md-3"> <div class="list-group"> <a class="list-group-item" href="?page=users"> <i class="fa fa-plus"></i>Add New User </a> <?php $query="SELECT * FROM users ORDER BY user_first_name ASC"; $result=mysqli_query($conn, $query); while($list = mysqli_fetch_assoc($result)){ $list = data_user($conn, $list['user_id']); //$blurb = substr(strip_tags($list['page_banner_des']), 0, 60); ?> <a class="list-group-item <?php selected($list['user_id'], $opened['user_id'], 'active'); ?>" href="index.php?page=users&id=<?php echo $list['user_id']?>"> <h4 class="list-group-item-heading"><?php echo $list['fullname'];?></h4> <!-- <p class="list-group-item-text"> --><?php //echo $blurb;?><!-- </p> --> </a> <?php } ?> </div> </div> <div class="col-sm-7 col-md-9"> <?php if(isset($message)){ echo $message; } ?> <form action="index.php?page=users&id=<?php echo $opened['user_id']; ?>" method="post" role="form"> <!-- cancel if you want to --> <?php if($opened['avatar'] =! ''){ ?> <img scr="../uploads/<?php echo $opened['avatar']; ?>"> <?php } ?> <div class="form-group"> <label for="first_name">First Name:</label> <input type="text" name="first_name" id="first_name" class="form-control" value="<?php echo $opened['user_first_name']; ?>" placeholder="First Name" autocomplete="off"> </div> <div class="form-group"> <label for="last_name">Last Name:</label> <input type="text" name="last_name" id="last_name" class="form-control" value="<?php echo $opened['user_last_name']; ?>" placeholder="Last Name" autocomplete="off"> </div> <div class="form-group"> <label for="user_email">Email Address:</label> <input type="text" name="user_email" id="user_email" class="form-control" value="<?php echo $opened['user_email']; ?>" placeholder="Email Address" autocomplete="off"> </div> <div class="form-group"> <label for="user_password">Password:</label> <input type="<PASSWORD>" name="user_password" id="user_password" class="form-control" value="" placeholder="<PASSWORD>" autocomplete="off"> </div> <div class="form-group"> <label for="user_confirm_password">Confirm Your Password:</label> <input type="<PASSWORD>" name="user_confirm_password" id="user_confirm_password" class="form-control" value="" placeholder="Type Your Password Again" autocomplete="off"> </div> <div class="form-group"> <label for="user_status">User Status</label> <select name="user_status" id="user_status" class="form-control"> <option value="0" <?php if(isset($_GET['id'])){ selected('0', $opened['user_status'], 'selected'); } ?>>Inactive</option> <option value="1" <?php if(isset($_GET['id'])){ selected('1', $opened['user_status'], 'selected'); } ?>>Active</option> </select> </div> <button type="submit" class="btn btn-default">Save</button> <input type="hidden" name="submitted" value="1"> <?php if(isset($opened['user_id'])) { ?> <input type="text" name="id" value="<?php echo $opened['user_id']; ?>"> <?php } ?> </form> <?php if(isset($opened['user_id'])) { ?> <form class="dropzone" id="avatar-dropzone" action="uploads.php?id=<?php echo $opened['user_id']; ?>"> <input type="file" name="file"> </form> <?php } ?> </div> </div> </div><file_sep>/admin/template/header.php <?php #start the session: session_start(); if(!isset($_SESSION['username'])){ header('Location: login.php'); } ?> <?php include('config/setup.php'); ?> <!DOCTYPE html> <head> <title>Manfootster | Admin Panel <!-- <?php echo $page['page_name']; ?> --></title> <?php include('config/css.php'); ?> </head> <body> <div id="fh5co-page"> <?php include(D_TEMPLATE.'/navigation.php'); ?><file_sep>/admin/template/footer.php </div> <div> <h5>This is a footer.</h5> </div> <?php if($debug == 1) { include('widgets/debug.php'); } ?> <?php include('config/js.php'); ?> </body> </html><file_sep>/functions/data.php <?php // function striped_data($body){ // $data['bodywith_nohtml'] = strip_tags($data['body']); // if($data['body'] == $data['bodywith_nohtml']){ // $data['body_formatted'] = '<p>'.$data['body'].'</p>'; // } else { // $data['body_formatted'] = $data['body']; // } // } function data_setting_value($conn, $id){ $query ="SELECT * FROM settings WHERE setting_id = '$id'"; $result = mysqli_query($conn, $query); $data = mysqli_fetch_assoc($result); return $data['setting_value']; } function data_page($conn, $id){ // Page Setup(Data) if(is_numeric($id)){ $cond = "WHERE page_id = $id"; } else{ $cond = "WHERE page_slug = '$id'"; } $query = "SELECT * FROM pages $cond"; $result = mysqli_query($conn, $query); $data = mysqli_fetch_assoc($result); // incase we put html in database $data['bodywith_nohtml'] = strip_tags($data['page_banner_des']); if($data['page_banner_des'] == $data['bodywith_nohtml']){ $data['body_formatted'] = '<p>'.$data['page_banner_des'].'</p>'; } else { $data['body_formatted'] = $data['page_banner_des']; } return $data; } ?><file_sep>/functions/template.php <?php function nav_main($conn, $path){ $query = "SELECT * FROM pages"; $result = mysqli_query($conn, $query); while($nav = mysqli_fetch_assoc($result)){ ?> <li<?php selected( $path['call_parts'][0], $nav['page_slug'], ' class="active"');?> ><a href="<?php echo $nav['page_slug'] ?>"><?php echo $nav['page_title'] ?></a></li> <?php } } ?><file_sep>/index.php <?php include('config/setup.php'); ?> <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Manfootster | <?php echo $page['page_name']; ?></title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Rowhaagan College Project" /> <meta name="keywords" content="Rowhaagan, Maharjan, Rohan, Futsal, Online Booking Futsal, Nepal Futsal" /> <meta name="author" content="<NAME>" /> <!-- Facebook and Twitter integration --> <meta property="og:title" content=""/> <meta property="og:image" content=""/> <meta property="og:url" content=""/> <meta property="og:site_name" content=""/> <meta property="og:description" content=""/> <meta name="twitter:title" content="" /> <meta name="twitter:image" content="" /> <meta name="twitter:url" content="" /> <meta name="twitter:card" content="" /> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="shortcut icon" href="favicon.ico"> <?php include('config/css.php'); ?> </head> <body> <div id="fh5co-page"> <?php include(D_TEMPLATE.'/navigation.php'); ?> <!-- --> <div class="fh5co-cover fh5co-cover-style-2 js-full-height" data-stellar-background-ratio="0.5" data-next="yes" style="background-image: url(images/full_1.jpg);"> <span class="scroll-btn wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.4s"> <a href="#"> <span class="mouse"><span></span></span> </a> </span> <div class="fh5co-overlay"></div> <div class="fh5co-cover-text"> <div class="container"> <div class="row"> <div class="col-md-push-6 col-md-6 full-height js-full-height"> <div class="fh5co-cover-intro"> <h1 class="cover-text-lead wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s"><?php echo $page['page_banner_title']; ?></h1> <h2 class="cover-text-sublead wow fadeInUp" data-wow-duration="1s" data-wow-delay=".8s"><?php echo $page['page_banner_des']; ?></h2> <p class="wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.1s"><a href="http://freehtml5.co/" class="btn btn-primary btn-outline btn-lg"><?php echo $page['page_banner_btn_text']; ?></a></p> </div> </div> </div> </div> </div> </div> <?php if($debug == 1){ include('widgets/debug.php'); } ?> <div class="fh5co-project-style-2"> <div class="container"> <div class="row p-b"> <div class="col-md-6 col-md-offset-3 text-center"> <h2 class="fh5co-heading wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s">News</h2> <p class="wow fadeInUp" data-wow-duration="1s" data-wow-delay=".8s">Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics.</p> <p class="wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.1s"><a href="#" class="btn btn-success btn-lg">Read More</a></p> </div> </div> </div> <div class="fh5co-projects"> <ul> <li class="wow fadeInUp" style="background-image: url(images/full_4.jpg);" data-wow-duration="1s" data-wow-delay="1.4s" data-stellar-background-ratio="0.5"> <a href="#"> <div class="fh5co-overlay"></div> <div class="container"> <div class="fh5co-text"> <div class="fh5co-text-inner"> <div class="row"> <div class="col-md-6"><h3>Barclays Premier Leauge</h3></div> <div class="col-md-6"><p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p></div> </div> </div> </div> </div> </a> </li> <li class="wow fadeInUp" style="background-image: url(images/full_2.jpg);" data-wow-duration="1s" data-wow-delay="1.7s" data-stellar-background-ratio="0.5"> <a href="#"> <div class="fh5co-overlay"></div> <div class="container"> <div class="fh5co-text"> <div class="fh5co-text-inner"> <div class="row"> <div class="col-md-6"><h3>National Leauge</h3></div> <div class="col-md-6"><p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p></div> </div> </div> </div> </div> </a> </li> <li class="wow fadeInUp" style="background-image: url(images/full_1.jpg);" data-wow-duration="1s" data-wow-delay="2s" data-stellar-background-ratio="0.5"> <a href="#"> <div class="fh5co-overlay"></div> <div class="container"> <div class="fh5co-text"> <div class="fh5co-text-inner"> <div class="row"> <div class="col-md-6"><h3>UEFA Champians Leauge</h3></div> <div class="col-md-6"><p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p></div> </div> </div> </div> </div> </a> </li> </ul> </div> </div> <div class="fh5co-blog-style-1"> <div class="container"> <div class="row p-b"> <div class="col-md-6 col-md-offset-3 text-center"> <h2 class="fh5co-heading wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s">Our Futsal</h2> <p class="wow fadeInUp" data-wow-duration="1s" data-wow-delay=".8s">Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. </p> </div> </div> <div class="row p-b"> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12"> <div class="fh5co-post wow fadeInLeft" data-wow-duration="1s" data-wow-delay="1.1s"> <div class="fh5co-post-image"> <div class="fh5co-overlay"></div> <div class="fh5co-category"><a href="#">Kathmandu</a></div> <img src="images/img_same_dimension_2.jpg" alt="Image" class="img-responsive"> </div> <div class="fh5co-post-text"> <h3><a href="#"><NAME></a></h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts...</p> </div> <div class="fh5co-post-meta"> <a href="#"><i class="icon-chat"></i> 33</a> <a href="#"><i class="icon-clock2"></i> 2 hours ago</a> </div> </div> </div> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12"> <div class="fh5co-post wow fadeInLeft" data-wow-duration="1s" data-wow-delay="1.4s"> <div class="fh5co-post-image"> <div class="fh5co-overlay"></div> <div class="fh5co-category"><a href="#">Bhaktapur</a></div> <img src="images/img_same_dimension_3.jpg" alt="Image" class="img-responsive"> </div> <div class="fh5co-post-text"> <h3><a href="#"><NAME></a></h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts...</p> </div> <div class="fh5co-post-meta"> <a href="#"><i class="icon-chat"></i> 33</a> <a href="#"><i class="icon-clock2"></i> 2 hours ago</a> </div> </div> </div> <div class="clearfix visible-sm-block"></div> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12"> <div class="fh5co-post wow fadeInLeft" data-wow-duration="1s" data-wow-delay="1.7s"> <div class="fh5co-post-image"> <div class="fh5co-overlay"></div> <div class="fh5co-category"><a href="#">Lalitpur</a></div> <img src="images/img_same_dimension_4.jpg" alt="Image" class="img-responsive"> </div> <div class="fh5co-post-text"> <h3><a href="#"><NAME></a></h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts...</p> </div> <div class="fh5co-post-meta"> <a href="#"><i class="icon-chat"></i> 33</a> <a href="#"><i class="icon-clock2"></i> 2 hours ago</a> </div> </div> </div> <div class="clearfix visible-sm-block"></div> </div> <div class="row"> <div class="col-md-4 col-md-offset-4 text-center wow fadeInUp" data-wow-duration="1s" data-wow-delay="2s"> <a href="#" class="btn btn-primary btn-lg">View All Futsals</a> </div> </div> </div> </div> <div class="fh5co-features-style-1" style="background-image: url(images/full_4.jpg);" data-stellar-background-ratio="0.5"> <div class="fh5co-overlay"></div> <div class="container" style="z-index: 3; position: relative;"> <div class="row p-b"> <div class="col-md-6 col-md-offset-3 text-center wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s"> <h2 class="fh5co-heading">What We Promise</h2> </div> </div> <div class="row"> <div class="fh5co-features"> <div class="fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay=".8s"> <div class="icon"><i class="icon-ribbon"></i></div> <h3>Online Booking</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p> </div> <div class="fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.1s"> <div class="icon"><i class="icon-image22"></i></div> <h3>Gallery for your Best</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p> </div> <div class="fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.4s"> <div class="icon"><i class=" icon-monitor"></i></div> <h3>Web Simplicity</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p> </div> <div class="fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.7s"> <div class="icon"><i class="icon-video2"></i></div> <h3>Video Recordings</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p> </div> <div class="fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay="2s"> <div class="icon"><i class="icon-bag"></i></div> <h3>E-Commerce Integration</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p> </div> <div class="fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay="2.3s"> <div class="icon"><i class="icon-mail2"></i></div> <h3>Notifications</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia.</p> </div> </div> </div> </div> </div> <!-- <div class="fh5co-features-style-2"> <div class="container"> <div class="row p-b"> <div class="col-md-6 col-md-offset-3 text-center"> <h2 class="fh5co-heading wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s">Why Choose Us</h2> <p class="wow fadeInUp" data-wow-duration="1s" data-wow-delay=".8s">Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics.</p> </div> </div> <div class="row"> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12 fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.1s"> <div class="fh5co-icon"><i class="icon-command"></i></div> <div class="fh5co-desc"> <h3>100% Free</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. </p> </div> </div> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12 fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.4s"> <div class="fh5co-icon"><i class="icon-eye22"></i></div> <div class="fh5co-desc"> <h3>Retina Ready</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. </p> </div> </div> <div class="clearfix visible-sm-block visible-xs-block"></div> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12 fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.7s"> <div class="fh5co-icon"><i class="icon-toggle"></i></div> <div class="fh5co-desc"> <h3>Fully Responsive</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. </p> </div> </div> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12 fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay="2s"> <div class="fh5co-icon"><i class="icon-archive22"></i></div> <div class="fh5co-desc"> <h3>Lightweight</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. </p> </div> </div> <div class="clearfix visible-sm-block visible-xs-block"></div> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12 fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay="2.3s"> <div class="fh5co-icon"><i class="icon-heart22"></i></div> <div class="fh5co-desc"> <h3>Made with Love</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. </p> </div> </div> <div class="col-md-4 col-sm-6 col-xs-6 col-xxs-12 fh5co-feature wow fadeInUp" data-wow-duration="1s" data-wow-delay="2.6s"> <div class="fh5co-icon"><i class="icon-umbrella"></i></div> <div class="fh5co-desc"> <h3>Eco Friendly</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. </p> </div> </div> <div class="clearfix visible-sm-block visible-xs-block"></div> </div> </div> </div> --> <div class="fh5co-pricing-style-2"> <div class="container"> <div class="row"> <div class="row p-b"> <div class="col-md-6 col-md-offset-3 text-center"> <h2 class="fh5co-heading wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s">Be A Member</h2> <p class="wow fadeInUp" data-wow-duration="1s" data-wow-delay=".7s">Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. </p> </div> </div> </div> <div class="row"> <div class="pricing"> <div class="pricing-item wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.1s"> <h3 class="pricing-title">Basic</h3> <p class="pricing-sentence">Little description here</p> <div class="pricing-price"><span class="pricing-currency">$</span>19<span class="pricing-period">/ 3 month</span></div> <ul class="pricing-feature-list"> <li class="pricing-feature">10 presentations/month</li> <li class="pricing-feature">Support at $25/hour</li> <li class="pricing-feature">1 year</li> </ul> <button class="btn btn-success btn-outline">Become</button> </div> <div class="pricing-item pricing-item--featured wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.4s"> <h3 class="pricing-title">Standard</h3> <p class="pricing-sentence">Little description here</p> <div class="pricing-price"><span class="pricing-currency">$</span>29<span class="pricing-period">/ 3 month</span></div> <ul class="pricing-feature-list"> <li class="pricing-feature">50 presentations/month</li> <li class="pricing-feature">5 hours of free support</li> <li class="pricing-feature">2 year</li> </ul> <button class="btn btn-success btn-lg">Become</button> </div> <div class="pricing-item wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.7s"> <h3 class="pricing-title">Enterprise</h3> <p class="pricing-sentence">Little description here</p> <div class="pricing-price"><span class="pricing-currency">$</span>79<span class="pricing-period">/ 3 month</span></div> <ul class="pricing-feature-list"> <li class="pricing-feature">Unlimited presentations</li> <li class="pricing-feature">Unlimited support</li> <li class="pricing-feature">Unlimited campaigns</li> </ul> <button class="btn btn-success btn-outline">Become</button> </div> </div> </div> </div> </div> <div class="fh5co-content-style-6"> <div class="container"> <div class="row p-b text-center"> <div class="col-md-6 col-md-offset-3"> <h2 class="wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s">Gallery</h2> <p class="wow fadeInUp" data-wow-duration="1s" data-wow-delay=".8s">Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics.</p> </div> </div> <div class="row"> <div class="col-md-3 col-sm-6 col-xs-6 col-xxs-12 wow fadeInLeft" data-wow-duration="1s" data-wow-delay=".5s"> <a href="#" class="link-block"> <figure><img src="images/img_same_dimension_1.jpg" alt="Image" class="img-responsive img-rounded"></figure> <h3><NAME></h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p> <p><a href="#" class="btn btn-primary btn-sm">View More</a></p> </a> </div> <div class="col-md-3 col-sm-6 col-xs-6 col-xxs-12 wow fadeInLeft" data-wow-duration="1s" data-wow-delay=".8s"> <a href="#" class="link-block"> <figure><img src="images/img_same_dimension_2.jpg" alt="Image" class="img-responsive img-rounded"></figure> <h3><NAME>sal</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p> <p><a href="#" class="btn btn-primary btn-sm">View More</a></p> </a> </div> <div class="clearfix visible-sm-block"></div> <div class="col-md-3 col-sm-6 col-xs-6 col-xxs-12 wow fadeInLeft" data-wow-duration="1s" data-wow-delay="1.1s"> <a href="#" class="link-block"> <figure><img src="images/img_same_dimension_3.jpg" alt="Image" class="img-responsive img-rounded"></figure> <h3><NAME></h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p> <p><a href="#" class="btn btn-primary btn-sm">View More</a></p> </a> </div> <div class="col-md-3 col-sm-6 col-xs-6 col-xxs-12 wow fadeInLeft" data-wow-duration="1s" data-wow-delay="1.4s"> <a href="#" class="link-block"> <figure><img src="images/img_same_dimension_4.jpg" alt="Image" class="img-responsive img-rounded"></figure> <h3>Hattiban Futsal</h3> <p>Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.</p> <p><a href="#" class="btn btn-primary btn-sm">View More</a></p> </a> </div> </div> </div> </div> <div class="fh5co-counter-style-2" style="background-image: url(images/full_2.jpg);" data-stellar-background-ratio="0.5"> <div class="fh5co-overlay"></div> <div class="container"> <div class="fh5co-section-content-wrap"> <div class="fh5co-section-content"> <div class="row"> <div class="col-md-4 text-center wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s"> <div class="icon"> <i class="icon-command"></i> </div> <span class="fh5co-counter js-counter" data-from="0" data-to="3" data-speed="5000" data-refresh-interval="50"></span> <span class="fh5co-counter-label">Districts</span> </div> <div class="col-md-4 text-center wow fadeInUp" data-wow-duration="1s" data-wow-delay=".8s"> <div class="icon"> <i class="icon-power"></i> </div> <span class="fh5co-counter js-counter" data-from="0" data-to="18" data-speed="5000" data-refresh-interval="50"></span> <span class="fh5co-counter-label">Futsals</span> </div> <div class="col-md-4 text-center wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.1s"> <div class="icon"> <i class="icon-code2"></i> </div> <span class="fh5co-counter js-counter" data-from="0" data-to="2000" data-speed="5000" data-refresh-interval="50"></span> <span class="fh5co-counter-label">Members</span> </div> </div> </div> </div> </div> </div> <div class="fh5co-testimonial-style-2"> <div class="container"> <div class="row p-b"> <div class="col-md-6 col-md-offset-3 text-center"> <h2 class="fh5co-heading wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s">Futsal Owners</h2> <p class="wow fadeInUp" data-wow-duration="1s" data-wow-delay=".8s">Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. </p> </div> </div> <div class="row"> <div class="col-md-4 col-sm-6 col-xs-12"> <div class="fh5co-testimonial-item wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.1s"> <div class="fh5co-name"> <img src="images/person_5.jpg" alt=""> <div class="fh5co-meta"> <h3>Lorem</h3> <span class="fh5co-company">XYZ Inc.</span> </div> </div> <div class="fh5co-text"> <p>&ldquo;Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.&rdquo;</p> </div> </div> </div> <div class="col-md-4 col-sm-6 col-xs-12"> <div class="fh5co-testimonial-item wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.4s"> <div class="fh5co-name"> <img src="images/person_4.jpg" alt=""> <div class="fh5co-meta"> <h3>Lorem</h3> <span class="fh5co-company">XYZ Inc.</span> </div> </div> <div class="fh5co-text"> <p>&ldquo;Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. &rdquo;</p> </div> </div> </div> <div class="clearfix visible-sm-block"></div> <div class="col-md-4 col-sm-6 col-xs-12"> <div class="fh5co-testimonial-item wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.7s"> <div class="fh5co-name"> <img src="images/person_3.jpg" alt=""> <div class="fh5co-meta"> <h3>Lorem</h3> <span class="fh5co-company">XYZ Inc.</span> </div> </div> <div class="fh5co-text"> <p>&ldquo;Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.&rdquo;</p> </div> </div> </div> <div class="clearfix visible-lg-block visible-md-block"></div> <div class="col-md-4 col-sm-6 col-xs-12"> <div class="fh5co-testimonial-item wow fadeInUp" data-wow-duration="1s" data-wow-delay="2s"> <div class="fh5co-name"> <img src="images/person_1.jpg" alt=""> <div class="fh5co-meta"> <h3>Lorem</h3> <span class="fh5co-company">XYZ Inc.</span> </div> </div> <div class="fh5co-text"> <p>&ldquo;Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. &rdquo;</p> </div> </div> </div> <div class="clearfix visible-sm-block"></div> <div class="col-md-4 col-sm-6 col-xs-12"> <div class="fh5co-testimonial-item wow fadeInUp" data-wow-duration="1s" data-wow-delay="2.3s"> <div class="fh5co-name"> <img src="images/person_2.jpg" alt=""> <div class="fh5co-meta"> <h3>Lorem</h3> <span class="fh5co-company">XYZ Inc.</span> </div> </div> <div class="fh5co-text"> <p>&ldquo;Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.&rdquo;</p> </div> </div> </div> <div class="col-md-4 col-sm-6 col-xs-12"> <div class="fh5co-testimonial-item wow fadeInUp" data-wow-duration="1s" data-wow-delay="2.6s"> <div class="fh5co-name"> <img src="images/person_6.jpg" alt=""> <div class="fh5co-meta"> <h3>Lorem</h3> <span class="fh5co-company">XYZ Inc.</span> </div> </div> <div class="fh5co-text"> <p>&ldquo;Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.&rdquo;</p> </div> </div> </div> <div class="clearfix visible-sm-block"></div> </div> </div> </div> <?php include(D_TEMPLATE.'/footer.php'); ?> <!-- footer --> </div> <!-- END page--> <?php include('config/js.php'); ?> </body> </html> <file_sep>/admin/views/settings.php <div class="container" style="padding-top:100px;"> <h4>Site Settings</h4> <div class="row"> <div class="col-sm-12 col-md-12"> <?php if(isset($message)){ echo $message; }?> <?php $query="SELECT * FROM settings ORDER BY setting_id ASC"; $result=mysqli_query($conn, $query); while($opened = mysqli_fetch_assoc($result)){ ?> <form class="form-inline" action="index.php?page=settings&id=<?php echo $opened['setting_id']; ?>" method="post" role="form"> <!-- cancel if you want to --> <div class="form-group"> <label for="setting_id" class="sr-only">Setting ID:</label> <input type="text" name="setting_id" id="setting_id" class="form-control" value="<?php echo $opened['setting_id']; ?>" placeholder="Setting ID Name" autocomplete="off"> </div> <div class="form-group"> <label for="setting_label" class="sr-only">Setting Label:</label> <input type="text" name="setting_label" id="setting_label" class="form-control" value="<?php echo $opened['setting_label']; ?>" placeholder="Setting Label" autocomplete="off"> </div> <div class="form-group"> <label for="setting_value" class="sr-only">Setting Status:</label> <input type="text" name="setting_value" id="setting_value" class="form-control" value="<?php echo $opened['setting_value']; ?>" placeholder="Setting Value" autocomplete="off"> </div> <button type="submit" class="btn btn-default">Save</button> <input type="hidden" name="submitted" value="1"> <input type="hidden" name="opened_id" value="<?php echo $opened['setting_id']; ?>"> </form> <?php } ?> </div> </div> </div><file_sep>/admin/functions/data.php <?php // function striped_data($body){ // $data['bodywith_nohtml'] = strip_tags($data['body']); // if($data['body'] == $data['bodywith_nohtml']){ // $data['body_formatted'] = '<p>'.$data['body'].'</p>'; // } else { // $data['body_formatted'] = $data['body']; // } // } function data_setting_value($conn, $id){ $query ="SELECT * FROM settings WHERE setting_id = '$id'"; $result = mysqli_query($conn, $query); $data = mysqli_fetch_assoc($result); return $data['setting_value']; } function data_user($conn, $id){ if(is_numeric($id)){ $cond = "WHERE user_id = '$id'"; }else{ $cond = "WHERE user_email = '$id'"; } $query="SELECT * FROM users $cond"; $result= mysqli_query($conn, $query); $data = mysqli_fetch_assoc($result); $data[fullname] = $data[user_first_name].' '.$data[user_last_name]; $data[reverse_name] = $data[user_last_name].' '.$data[user_first_name]; return $data; } function data_page($conn, $id){ // Page Setup(Data) $query = "SELECT * FROM pages WHERE page_id = $id"; $result = mysqli_query($conn, $query); $data = mysqli_fetch_assoc($result); // incase we put html in database $data['bodywith_nohtml'] = strip_tags($data['page_banner_des']); if($data['page_banner_des'] == $data['bodywith_nohtml']){ $data['body_formatted'] = '<p>'.$data['page_banner_des'].'</p>'; } else { $data['body_formatted'] = $data['page_banner_des']; } return $data; } ?><file_sep>/config/setup.php <?php // setup files: error_reporting(0); // Database connection $conn = mysqli_connect('localhost', 'rowhaagan', 'password', '<PASSWORD>') OR die('Could not connect because: '. mysqli_connect_error()); // Constants DEFINE('D_TEMPLATE', 'template'); // function include('functions/sandbox.php'); include('functions/data.php'); include('functions/template.php'); // site setup $debug = data_setting_value($conn, 'debug-status'); $path = get_path(); if(!isset($path['call_parts'][0]) || $path['call_parts']['0'] == ''){ header('location: home'); //$path['call_parts'][0] = 'home'; //set $pageid to equal the value given the url } // Page Setup $page = data_page($conn, $path['call_parts'][0]); ?><file_sep>/admin/config/queries.php <?php switch ($page) { case 'dashboard': # code... break; case 'pages': if(isset($_POST['submitted']) == 1){ $page_name = mysqli_real_escape_string($conn, $_POST['name']); $page_title = mysqli_real_escape_string($conn, $_POST['title']); $page_banner_title = mysqli_real_escape_string($conn, $_POST['banner_text']); $page_banner_des = mysqli_real_escape_string($conn, $_POST['banner_des']); $page_banner_btn_text = mysqli_real_escape_string($conn, $_POST['banner_btn_text']); if(isset($_POST['id']) != ''){ # isset hatauda milyo but functiona;;ity ma bigriyo $action = "updated"; $query= "UPDATE pages SET user_id = $_POST[user], page_slug = '$_POST[slug]', page_name = '$page_name', page_title = '$page_title', page_banner_title = '$page_banner_title', page_banner_des = '$page_banner_des', page_banner_btn_text = '$page_banner_btn_text' WHERE page_id = $_GET[id] "; } else { $action = "added"; $query = "INSERT INTO pages (user_id, page_slug, page_name, page_title, page_banner_title, page_banner_des, page_banner_btn_text) VALUES ($_POST[user], '$_POST[slug]', '$page_name', '$page_title', '$page_banner_title', '$page_banner_des', '$page_banner_btn_text')"; } $result=mysqli_query($conn, $query); if($result){ $message = '<p class="alert alert-success"> Page was '.$action.'.</p>'; }else{ $message = '<p class="alert alert-danger"> Page could not be '.$action.' because: '.mysqli_error($conn).'</p>'; $message .= '<p class="alert alert-warning">'.$query.'</p>'; } } if(isset($_GET['id'])){ $opened = data_page($conn, $_GET['id']); } break; case 'users': if(isset($_POST['submitted']) == 1){ $first_name = mysqli_real_escape_string($conn, $_POST['first_name']); $last_name = mysqli_real_escape_string($conn, $_POST['last_name']); if($_POST['user_password'] != ''){ if($_POST['user_password'] == $_POST['user_confirm_password']) { $user_password = " user_password = sha1('$_POST[user_password]'),"; $confirm = true; }else{ $confirm = false; } }else{ $confirm = false; } if(isset($_POST['id']) != ''){ # isset hatauda milyo but functiona;;ity ma bigriyo $action = "updated"; $query= "UPDATE users SET user_first_name = '$first_name', user_last_name = '$last_name', user_email = '$_POST[user_email]', $user_password user_status = $_POST[user_status] WHERE user_id = $_GET[id] "; $result=mysqli_query($conn, $query); } else { $action = "added"; $query = "INSERT INTO users (user_first_name, user_last_name, user_email, user_password, user_status) VALUES ('$first_name', '$last_name', '$_POST[user_email]', sha1('$_POST[user_password]'), $_POST[user_status])"; if($confirm == true){ $result=mysqli_query($conn, $query); } } if($result){ $message = '<p class="alert alert-success"> User was '.$action.'.</p>'; }else{ $message = '<p class="alert alert-danger"> User could not be '.$action.' because: '.mysqli_error($conn).'</p>'; if($confirm == false){ $message .= '<p class="alert alert-danger"> Password fields doesnot matches or are empty.</p>'; } $message .= '<p class="alert alert-warning">'.$query.'</p>'; } } if(isset($_GET['id'])){ $opened = data_user($conn, $_GET['id']); } break; case 'settings': if(isset($_POST['submitted']) == 1){ $setting_label = mysqli_real_escape_string($conn, $_POST['setting_label']); $setting_value = mysqli_real_escape_string($conn, $_POST['setting_value']); if(isset($_POST['opened_id']) != ''){ $action = "updated"; $query= "UPDATE settings SET setting_id = '$_POST[setting_id]', setting_label = '$setting_label', setting_value = '$setting_value' WHERE setting_id = '$_POST[opened_id]'"; $result=mysqli_query($conn, $query); } if($result){ $message = '<p class="alert alert-success"> Setting was '.$action.'.</p>'; }else{ $message = '<p class="alert alert-danger"> Setting could not be '.$action.' because: '.mysqli_error($conn).'</p>'; $message .= '<p class="alert alert-warning">'.$query.'</p>'; } } break; default: # code... break; } ?><file_sep>/admin/template/navigation.php <nav class="fh5co-nav-style-1" role="navigation" data-offcanvass-position="fh5co-offcanvass-left"> <div class="acontainer"> <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 fh5co-logo"> <a href="#" class="js-fh5co-mobile-toggle fh5co-nav-toggle"><i></i></a> <a href="#">Manfootster</a> </div> <div class="col-lg-6 col-md-5 col-sm-5 text-center fh5co-link-wrap"> <ul data-offcanvass="yes"> <li><a href="?page=dashboard">Dashboard</a></li> <li><a href="?page=pages">Pages</a></li> <li><a href="?page=users">Users</a></li> <li><a href="?page=settings">Settings</a></li> </ul> </div> <div class="col-lg-3 col-md-4 col-sm-4 text-right fh5co-link-wrap"> <ul class="fh5co-special" data-offcanvass="yes"> <li><?php if($debug == 1) { ?> <button id="btn-debug" class="btn btn-default"><i class="fa fa-bug"></i></button> </li><?php } ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><?php echo $user['fullname']; ?> <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="logout.php">Logout</a></li> </ul> </li> </ul> </div> </div> </nav><file_sep>/admin/functions/template.php <?php function nav_main($conn, $pageid){ $query = "SELECT * FROM pages"; $result = mysqli_query($conn, $query); while($nav = mysqli_fetch_assoc($result)){ ?> <li<?php if($pageid == $nav['page_id']) { echo ' class="active"';}?> ><a href="?page=<?php echo $nav['page_id'] ?>"><?php echo $nav['page_title'] ?></a></li> <?php } } ?>
008efed33a6094ada6b94c243f52ec79d933d5df
[ "Markdown", "PHP" ]
19
PHP
Rowhaagan/futsalphp
628da84cc8dfb9b9fceb4641893ca8ee0c4f6aaf
d799864bf512c0b500b65563e30e9b0e9e5af725
refs/heads/master
<repo_name>ndwrobotics/2019Season<file_sep>/ftc_app-master/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/HeadlessOmniOp.java /* [][][] [][][] [][] [][][] [] [] [] [] [] [][] [][][] [][][] [][] [][][] * */ package org.firstinspires.ftc.teamcode; import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cGyro; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; @TeleOp(name = "headless omni op", group="default") //@Disabled public class HeadlessOmniOp extends OpMode { ElapsedTime tm = new ElapsedTime(); DcMotor left; DcMotor right; DcMotor front; DcMotor back; ModernRoboticsI2cGyro gyro; int heading; int zeroHeading; double GYRO_COMPENSATION_FACTOR = 83.0/90.0; @Override public void init() { back = hardwareMap.dcMotor.get("back"); front = hardwareMap.dcMotor.get("front"); right = hardwareMap.dcMotor.get("right"); left = hardwareMap.dcMotor.get("left"); gyro = (ModernRoboticsI2cGyro)hardwareMap.gyroSensor.get("gyro"); left.setDirection(DcMotor.Direction.REVERSE); right.setDirection(DcMotor.Direction.FORWARD); front.setDirection(DcMotor.Direction.REVERSE); back.setDirection(DcMotor.Direction.FORWARD); gyro.calibrate(); while (gyro.isCalibrating()){ } zeroHeading = (int)findHeading(); } @Override public void start () { tm.reset(); } @Override public void loop() { heading = (int)findHeading(); double y = -gamepad1.left_stick_y; double x = gamepad1.left_stick_x; double magnitude = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); double desiredHeading = Math.atan2(y, x); int desiredHeadingDegrees = (int) (desiredHeading * 180.0/Math.PI); telemetry.addData("desiredHeadingDegrees: ", desiredHeadingDegrees); telemetry.addData("heading: ", heading); int error = heading - desiredHeadingDegrees; error = error % 360; telemetry.addData("error: ", error); int angle = zeroHeading + 180 - error; double lrPower; double udPower; if (magnitude > 0.02) { lrPower = Math.cos(angle * Math.PI / 180.0) * magnitude; udPower = Math.sin(angle * Math.PI / 180.0) * magnitude; telemetry.addData("lrPower: ", lrPower); telemetry.addData("udPower: ", udPower); } else { lrPower = 0; udPower = 0; } double turnPower = gamepad1.right_stick_x; left.setPower(0.5*(lrPower + turnPower)); right.setPower(0.5*(lrPower - turnPower)); front.setPower(0.5*(udPower + turnPower)); back.setPower(0.5*(udPower - turnPower)); if (gamepad1.a){ zeroHeading = (int)findHeading(); } } public double findHeading(){ return gyro.getIntegratedZValue()/GYRO_COMPENSATION_FACTOR; } }<file_sep>/ftc_app-master/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Selectron.java package org.firstinspires.ftc.teamcode; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; import static com.qualcomm.robotcore.hardware.DcMotor.ZeroPowerBehavior.BRAKE; public class Selectron { DcMotor fl; DcMotor fr; DcMotor bl; DcMotor br; DcMotor lift; DcMotor spin; DcMotor intake; Servo dropper; Servo colorS; LinearOpMode op; double DROPPER_IN = 0.7; double DROPPER_OUT = 0.3; BNO055IMU imu; ElapsedTime r; public Selectron(LinearOpMode opMode){ op = opMode; dropper = op.hardwareMap.servo.get("drop"); colorS = op.hardwareMap.servo.get("colorS"); lift = op.hardwareMap.get(DcMotor.class, "lift"); lift.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); lift.setMode(DcMotor.RunMode.RUN_USING_ENCODER); lift.setZeroPowerBehavior(BRAKE); intake = op.hardwareMap.get(DcMotor.class, "intake"); spin = op.hardwareMap.get(DcMotor.class, "spin"); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode parameters.loggingEnabled = true; parameters.loggingTag = "IMU"; parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator(); // Retrieve and initialize the IMU. We expect the IMU to be attached to an I2C port // on a Core Device Interface Module, configured to be a sensor of type "AdaFruit IMU", // and named "imu". imu = op.hardwareMap.get(BNO055IMU.class, "imu"); imu.initialize(parameters); bl = op.hardwareMap.dcMotor.get("bL"); br = op.hardwareMap.dcMotor.get("bR"); fr = op.hardwareMap.dcMotor.get("fL"); fl = op.hardwareMap.dcMotor.get("fR"); bl.setDirection(DcMotor.Direction.REVERSE); br.setDirection(DcMotor.Direction.FORWARD); fl.setDirection(DcMotor.Direction.REVERSE); fr.setDirection(DcMotor.Direction.FORWARD); bl.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); br.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); fl.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); fr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); bl.setMode(DcMotor.RunMode.RUN_TO_POSITION); br.setMode(DcMotor.RunMode.RUN_TO_POSITION); fl.setMode(DcMotor.RunMode.RUN_TO_POSITION); fr.setMode(DcMotor.RunMode.RUN_TO_POSITION); intake.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); intake.setMode(DcMotor.RunMode.RUN_USING_ENCODER); r = new ElapsedTime(); } public double findHeading(){ return imu.getAngularOrientation().firstAngle; } public void snooze(double milliseconds){ double startTime = r.milliseconds(); while (r.milliseconds() < startTime + milliseconds && op.opModeIsActive()){ } } public void timeAngleDrive(int angleDegrees, double milliseconds){ timeAnglePowerDrive(angleDegrees, milliseconds, 1.0); } public void timeAnglePowerDrive(int angleDegrees, double milliseconds, double power){ double flbrPower = power * Math.cos(Math.PI * (angleDegrees + 45)/180.0); double frblPower = power * Math.sin(Math.PI * (angleDegrees + 45)/180.0); fl.setPower(flbrPower); fr.setPower(frblPower); bl.setPower(frblPower); br.setPower(flbrPower); snooze(milliseconds); stopMotors(); snooze(200); } // 0 is the forwards public void timeAngleEncoderDrive(int angleDegrees, double inches, double power){ double encoderCounts = 1120*inches/(4*Math.PI); int flbrDistance = (int)(encoderCounts * Math.cos(Math.PI * (angleDegrees + 45)/180.0)); int frblDistance = (int)(encoderCounts * Math.sin(Math.PI * (angleDegrees + 45)/180.0)); double flbrPower = power * (Math.cos(Math.PI * (angleDegrees + 45)/180.0)); double frblPower = power * (Math.sin(Math.PI * (angleDegrees + 45)/180.0)); fl.setTargetPosition(fl.getCurrentPosition() + flbrDistance); br.setTargetPosition(br.getCurrentPosition() + flbrDistance); fr.setTargetPosition(fr.getCurrentPosition() + frblDistance); bl.setTargetPosition(bl.getCurrentPosition() + frblDistance); fl.setPower(flbrPower); fr.setPower(frblPower); bl.setPower(frblPower); br.setPower(flbrPower); while(op.opModeIsActive() && (fl.isBusy() || fr.isBusy() || bl.isBusy() || br.isBusy())){} stopMotors(); snooze(100); } public void stopMotors(){ fl.setPower(0); fr.setPower(0); bl.setPower(0); br.setPower(0); } public void setEncoders(DcMotor.RunMode runMode){ fl.setMode(runMode); fr.setMode(runMode); bl.setMode(runMode); br.setMode(runMode); } }<file_sep>/ftc_app-master/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Op2.java /* [][][] [][][] [][] [][][] [] [] [] [] [] [][] [][][] [][][] [][] [][][] * */ package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.navigation.Acceleration; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import org.firstinspires.ftc.robotcore.external.navigation.Position; import org.firstinspires.ftc.robotcore.external.navigation.Velocity; @TeleOp(name = "Op 2", group="default") //@Disabled public class Op2 extends LinearOpMode { ElapsedTime tm = new ElapsedTime(); int heading; int zeroHeading; // State used for updating telemetry Orientation angles; Acceleration gravity; Selectron s; @Override public void runOpMode() { s = new Selectron(this); s.setEncoders(DcMotor.RunMode.RUN_USING_ENCODER); waitForStart(); zeroHeading = (int) s.findHeading(); tm.reset(); s.imu.startAccelerationIntegration(new Position(), new Velocity(), 1000); while(opModeIsActive()) { heading = (int) s.findHeading(); angles = s.imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); double y = -gamepad1.left_stick_y; double x = gamepad1.left_stick_x; double magnitude = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); double desiredHeading = Math.atan2(y, x); int desiredHeadingDegrees = (int) (desiredHeading * 180.0 / Math.PI); telemetry.addData("desiredHeadingDegrees: ", desiredHeadingDegrees); telemetry.addData("heading: ", heading); int error = desiredHeadingDegrees - heading; error = error % 360; telemetry.addData("error: ", error); int angle = zeroHeading + 225 - error; double lrPower; double udPower; if (magnitude > 0.02) { lrPower = Math.cos(angle * Math.PI / 180.0) * magnitude; udPower = Math.sin(angle * Math.PI / 180.0) * magnitude; telemetry.addData("lrPower: ", lrPower); telemetry.addData("udPower: ", udPower); } else { lrPower = 0; udPower = 0; } double turnPower = gamepad1.right_stick_x; double lPower = lrPower + turnPower; double rPower = lrPower - turnPower; double uPower = udPower + turnPower; double dPower = udPower - turnPower; double max = Math.max(Math.max(Math.abs(lPower), Math.abs(rPower)), Math.max(Math.abs(uPower), Math.abs(dPower))); if (max > 1.0) { lPower /= max; rPower /= max; uPower /= max; dPower /= max; } s.fl.setPower(lPower); s.br.setPower(rPower); s.fr.setPower(uPower); s.bl.setPower(dPower); if (gamepad1.left_trigger > 0.5) { zeroHeading = (int) s.findHeading(); } /*if (gamepad1.x) { s.robotLift.setPower(0.6); } else if (gamepad1.b){ s.robotLift.setPower(-0.6); } else { s.robotLift.setPower(0); } telemetry.addData("Robot lift position: ", s.robotLift.getCurrentPosition());*/ telemetry.update(); } } }<file_sep>/ftc_app-master/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RevAuto1.java /* [][][] [][][] [][] [][][] [] [] [] [] [] [][] [][][] [][][] [][] [][][] * */ package org.firstinspires.ftc.teamcode; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.navigation.Acceleration; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import org.firstinspires.ftc.robotcore.external.navigation.Position; import org.firstinspires.ftc.robotcore.external.navigation.Velocity; @TeleOp(name = "Rev Auto 1", group="default") //@Disabled public class RevAuto1 extends LinearOpMode { ElapsedTime tm = new ElapsedTime(); DcMotor fl; DcMotor fr; DcMotor bl; DcMotor br; Servo dropper; int heading; int zeroHeading; BNO055IMU imu; // State used for updating telemetry Orientation angles; Acceleration gravity; double DROPPER_IN = 0.04; double DROPPER_OUT = 0.8; @Override public void runOpMode() { BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode parameters.loggingEnabled = true; parameters.loggingTag = "IMU"; parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator(); // Retrieve and initialize the IMU. We expect the IMU to be attached to an I2C port // on a Core Device Interface Module, configured to be a sensor of type "AdaFruit IMU", // and named "imu". imu = hardwareMap.get(BNO055IMU.class, "imu"); imu.initialize(parameters); dropper = hardwareMap.servo.get("dropper"); bl = hardwareMap.dcMotor.get("bl"); br = hardwareMap.dcMotor.get("br"); fl = hardwareMap.dcMotor.get("fl"); fr = hardwareMap.dcMotor.get("fr"); bl.setDirection(DcMotor.Direction.REVERSE); br.setDirection(DcMotor.Direction.FORWARD); fl.setDirection(DcMotor.Direction.REVERSE); fr.setDirection(DcMotor.Direction.FORWARD); zeroHeading = (int)findHeading(); bl.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); br.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); fl.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); fr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); waitForStart(); imu.startAccelerationIntegration(new Position(), new Velocity(), 1000); tm.reset(); heading = (int)findHeading(); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); double y = -gamepad1.left_stick_y; double x = gamepad1.left_stick_x; double magnitude = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); double desiredHeading = Math.atan2(y, x); int desiredHeadingDegrees = (int) (desiredHeading * 180.0/Math.PI); telemetry.addData("desiredHeadingDegrees: ", desiredHeadingDegrees); telemetry.addData("heading: ", heading); int error = desiredHeadingDegrees - heading; error = error % 360; telemetry.addData("error: ", error); int angle = zeroHeading + 180 - error; timeAngleDrive(90, 1500); timeAngleDrive(0, 1000); dropper.setPosition(DROPPER_OUT); timeAngleDrive(180, 2000); timeAnglePowerDrive(180, 2000, 0.6); } public double findHeading(){ return imu.getAngularOrientation().firstAngle; } public void s(double milliseconds){ double startTime = tm.milliseconds(); while (tm.milliseconds() < startTime + milliseconds && opModeIsActive()){ } } public void timeAngleDrive(int angleDegrees, double milliseconds){ timeAnglePowerDrive(angleDegrees, milliseconds, 1.0); } public void timeAnglePowerDrive(int angleDegrees, double milliseconds, double power){ double flbrPower = power * Math.cos(Math.PI * (angleDegrees + 45)/180.0); double frblPower = power * Math.sin(Math.PI * (angleDegrees + 45)/180.0); fl.setPower(flbrPower); fr.setPower(frblPower); bl.setPower(frblPower); br.setPower(flbrPower); s(milliseconds); stopMotors(); s(200); } public void stopMotors(){ fl.setPower(0); fr.setPower(0); bl.setPower(0); br.setPower(0); } }<file_sep>/ftc_app-master/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/HeadlessOmniOpRev.java /* [][][] [][][] [][] [][][] [] [] [] [] [] [][] [][][] [][][] [][] [][][] * */ package org.firstinspires.ftc.teamcode; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cGyro; import com.qualcomm.hardware.rev.RevBlinkinLedDriver; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.navigation.Acceleration; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import org.firstinspires.ftc.robotcore.external.navigation.Position; import org.firstinspires.ftc.robotcore.external.navigation.Velocity; @TeleOp(name = "headless omni op Rev", group="default") //@Disabled public class HeadlessOmniOpRev extends OpMode { ElapsedTime tm = new ElapsedTime(); DcMotor fl; DcMotor br; DcMotor fr; DcMotor bl; int heading; int zeroHeading; BNO055IMU imu; // State used for updating telemetry Orientation angles; Acceleration gravity; @Override public void init() { BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode parameters.loggingEnabled = true; parameters.loggingTag = "IMU"; parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator(); // Retrieve and initialize the IMU. We expect the IMU to be attached to an I2C port // on a Core Device Interface Module, configured to be a sensor of type "AdaFruit IMU", // and named "imu". imu = hardwareMap.get(BNO055IMU.class, "imu"); imu.initialize(parameters); bl = hardwareMap.dcMotor.get("bl"); fr = hardwareMap.dcMotor.get("fr"); br = hardwareMap.dcMotor.get("br"); fl = hardwareMap.dcMotor.get("fl"); fl.setDirection(DcMotor.Direction.REVERSE); br.setDirection(DcMotor.Direction.FORWARD); fr.setDirection(DcMotor.Direction.REVERSE); bl.setDirection(DcMotor.Direction.FORWARD); bl.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); br.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); fl.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); fr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); zeroHeading = (int)findHeading(); } @Override public void start () { tm.reset(); imu.startAccelerationIntegration(new Position(), new Velocity(), 1000); } @Override public void loop() { heading = (int)findHeading(); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); double y = -gamepad1.left_stick_y; double x = gamepad1.left_stick_x; double magnitude = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); double desiredHeading = Math.atan2(y, x); int desiredHeadingDegrees = (int) (desiredHeading * 180.0/Math.PI); telemetry.addData("desiredHeadingDegrees: ", desiredHeadingDegrees); telemetry.addData("heading: ", heading); int error = desiredHeadingDegrees - heading; error = error % 360; telemetry.addData("error: ", error); int angle = zeroHeading + 225 - error; double lrPower; double udPower; if (magnitude > 0.02) { lrPower = Math.cos(angle * Math.PI / 180.0) * magnitude; udPower = Math.sin(angle * Math.PI / 180.0) * magnitude; telemetry.addData("lrPower: ", lrPower); telemetry.addData("udPower: ", udPower); } else { lrPower = 0; udPower = 0; } double turnPower = gamepad1.right_stick_x; double lPower = lrPower + turnPower; double rPower = lrPower - turnPower; double uPower = udPower + turnPower; double dPower = udPower - turnPower; double max = Math.abs(Math.max(Math.max(lPower, rPower), Math.max(uPower, dPower))); if(max > 1.0){ lPower /= max; rPower /= max; uPower /= max; dPower /= max; } fl.setPower(lPower); br.setPower(rPower); fr.setPower(uPower); bl.setPower(dPower); if (gamepad1.a){ zeroHeading = (int)findHeading(); } } public double findHeading(){ return imu.getAngularOrientation().firstAngle; } }<file_sep>/ftc_app-master/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RevAuto2BlueGold.java /* [][][] [][][] [][] [][][] [] [] [] [] [] [][] [][][] [][][] [][] [][][] * */ package org.firstinspires.ftc.teamcode; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.navigation.Acceleration; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import org.firstinspires.ftc.robotcore.external.navigation.Position; import org.firstinspires.ftc.robotcore.external.navigation.Velocity; import static com.qualcomm.robotcore.hardware.DcMotor.RunMode.RUN_TO_POSITION; @Autonomous(name = "Rev Auto 2 Gold", group="default") //@Disabled public class RevAuto2BlueGold extends LinearOpMode { ElapsedTime tm = new ElapsedTime(); DcMotor fl; DcMotor fr; DcMotor bl; DcMotor br; Servo dropper; int heading; int zeroHeading; BNO055IMU imu; // State used for updating telemetry Orientation angles; Acceleration gravity; double DROPPER_IN = 0.04; double DROPPER_OUT = 0.8; @Override public void runOpMode() { BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode parameters.loggingEnabled = true; parameters.loggingTag = "IMU"; parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator(); // Retrieve and initialize the IMU. We expect the IMU to be attached to an I2C port // on a Core Device Interface Module, configured to be a sensor of type "AdaFruit IMU", // and named "imu". imu = hardwareMap.get(BNO055IMU.class, "imu"); imu.initialize(parameters); dropper = hardwareMap.servo.get("drop"); bl = hardwareMap.dcMotor.get("bl"); br = hardwareMap.dcMotor.get("br"); fl = hardwareMap.dcMotor.get("fl"); fr = hardwareMap.dcMotor.get("fr"); bl.setDirection(DcMotor.Direction.REVERSE); br.setDirection(DcMotor.Direction.FORWARD); fl.setDirection(DcMotor.Direction.REVERSE); fr.setDirection(DcMotor.Direction.FORWARD); zeroHeading = (int)findHeading(); bl.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); br.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); fl.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); fr.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); bl.setMode(RUN_TO_POSITION); br.setMode(RUN_TO_POSITION); fl.setMode(RUN_TO_POSITION); fr.setMode(RUN_TO_POSITION); waitForStart(); imu.startAccelerationIntegration(new Position(), new Velocity(), 1000); tm.reset(); timeAngleEncoderDrive(-90, 60, 0.4); timeAngleEncoderDrive(90, 2, 0.4); timeAngleEncoderDrive(180, 42, 0.4); dropper.setPosition(DROPPER_OUT); s(200); timeAngleEncoderDrive(0, 78, 0.4); } public double findHeading(){ return imu.getAngularOrientation().firstAngle; } public void s(double milliseconds){ double startTime = tm.milliseconds(); while (tm.milliseconds() < startTime + milliseconds && opModeIsActive()){ } } public void timeAngleDrive(int angleDegrees, double milliseconds){ timeAnglePowerDrive(angleDegrees, milliseconds, 1.0); } public void timeAnglePowerDrive(int angleDegrees, double milliseconds, double power){ double flbrPower = power * Math.cos(Math.PI * (angleDegrees + 45)/180.0); double frblPower = power * Math.sin(Math.PI * (angleDegrees + 45)/180.0); fl.setPower(flbrPower); fr.setPower(frblPower); bl.setPower(frblPower); br.setPower(flbrPower); s(milliseconds); stopMotors(); s(200); } // 0 is the forwards direction public void timeAngleEncoderDrive(int angleDegrees, double inches, double power){ double encoderCounts = 1120*inches/(4*Math.PI); int flbrDistance = (int)(encoderCounts * Math.cos(Math.PI * (angleDegrees + 45)/180.0)); int frblDistance = (int)(encoderCounts * Math.sin(Math.PI * (angleDegrees + 45)/180.0)); fl.setTargetPosition(fl.getCurrentPosition() + flbrDistance); br.setTargetPosition(br.getCurrentPosition() + flbrDistance); fr.setTargetPosition(fr.getCurrentPosition() + frblDistance); bl.setTargetPosition(bl.getCurrentPosition() + frblDistance); fl.setPower(power); fr.setPower(power); bl.setPower(power); br.setPower(power); while(opModeIsActive() && (fl.isBusy() || fr.isBusy() || bl.isBusy() || br.isBusy())){} stopMotors(); s(200); } public void stopMotors(){ fl.setPower(0); fr.setPower(0); bl.setPower(0); br.setPower(0); } }<file_sep>/ftc_app-master/TeamCode/src/main/java/org/firstinspires/ftc/teamcode/ServoCalibration.java package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.Servo; @TeleOp(name="Servo calibration", group="NONONONONONONONOOOOO") public class ServoCalibration extends LinearOpMode { Servo servo; @Override public void runOpMode(){ servo = hardwareMap.servo.get("servo"); double position = 0.5; boolean a_now; boolean b_now; boolean x_now; boolean y_now; boolean a_then = false; boolean b_then = false; boolean x_then = false; boolean y_then = false; waitForStart(); while(opModeIsActive()){ a_now = gamepad1.a; b_now = gamepad1.b; x_now = gamepad1.x; y_now = gamepad1.y; if (a_now && !a_then){ position += 0.1; } else if (b_now && !b_then){ position -= 0.1; } else if (x_now && !x_then){ position += 0.01; } else if (y_now && !y_then){ position -= 0.001; } a_then = a_now; b_then = b_now; x_then = x_now; y_then = y_now; servo.setPosition(position); telemetry.addData("Position: ", position); telemetry.update(); } } }
d2ad44bb1cdadff7ddeae65db9f2e121b050f454
[ "Java" ]
7
Java
ndwrobotics/2019Season
050a55ccbabb03e4978eb06ccdad2a6012ecaa5e
f296d69b4a7ddc38f3f8f4751d3316bd95361fb7
refs/heads/master
<repo_name>Nacer-Ben/php-csv-exporter<file_sep>/src/Contracts/ExporterContract.php <?php namespace Sujan\Exporter\Contracts; use Generator; interface ExporterContract { public function set(): Generator; public function get(): void; }
02f1ce3220b88143f7f987e92f76da7f963d1f88
[ "PHP" ]
1
PHP
Nacer-Ben/php-csv-exporter
9fc359a3054a5c1df8807094bc0f22ca28adfadd
965f5a1d4a45b876758fce2eceeb4fefd061eab3
refs/heads/master
<file_sep>[<script type="text/javascript" > function preventBack(){window.history.forward();} setTimeout("preventBack()", 0); window.onunload=function(){null}; </script> <?php $examId = $_GET['id']; $selExam = $conn->query("SELECT * FROM exam_tbl WHERE ex_id='$examId' ")->fetch(PDO::FETCH_ASSOC); $selExamTimeLimit = $selExam['ex_time_limit']; $exDisplayLimit = $selExam['ex_questlimit_display']; ?> <div class="app-main__outer"> <div class="app-main__inner"> <div class="col-md-12"> <div class="app-page-title"> <div class="page-title-wrapper"> <div class="page-title-heading"> <div> <?php echo $selExam['ex_title']; ?> <div class="page-title-subheading"> <?php echo $selExam['ex_description']; ?> </div> </div> </div> <div class="page-title-actions mr-5" style="font-size: 20px;"> <form name="cd"> <input type="hidden" name="" id="timeExamLimit" value="<?php echo $selExamTimeLimit; ?>"> <label>Remaining Time : </label> <input style="border:none;background-color: transparent;color:blue;font-size: 25px;" name="disp" type="text" class="clock" id="txt" value="00:00" size="5" readonly="true" /> </form> </div> </div> </div> </div> <div class="modal-dialog" role="document"> <form class="refreshFrm" id="addFeebacks" method="post"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Submit Your Coding</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="col-md-12"> <div class="form-group"> <label>Language As</label><br> <?php $selMe = $conn->query("SELECT * FROM examinee_tbl WHERE exmne_id='$exmneId' ")->fetch(PDO::FETCH_ASSOC); ?> <input type="radio" name="asMe" value="C/C++"> C Language <br> <input type="radio" name="asMe" value="Java"> Java Language </div> <div class="form-group"> <textarea name="myFeedbacks" class="form-control" rows="3" placeholder="Input your Solution here.."></textarea> </div> </div> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary" >Submit Your Answer</button> </div> </div> </div> </form> Hi! <?php echo $selMe['exmne_fullname']; ?>Please choose the appropriate language: <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $('#button').click(function(){ if(!$('#iframe').length) { $('#iframeHolder').html('<iframe height="400px" width="100%" src="https://replit.com/@Akil01/VapidLinenDownloads?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe>'); } }); }); </script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $('#buttons').click(function(){ if(!$('#iframe').length) { $('#iframeHolders').html('<iframe height="400px" width="100%" src="https://replit.com/@Akil01/PaleTemporalSystemresource?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe>'); } }); }); </script> <style> .dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover {background-color: #f1f1f1} .dropdown:hover .dropdown-content { display: block; } .dropdown:hover .dropbtn { background-color: #3e8e41; } </style> <div class="dropdown"> <button class="dropbtn">Click Here</button> <div class="dropdown-content"> <a> <button id="button">C</button> </a> <a><button id="buttons">Java</button></a> </div> </div> <div id="iframeHolder"></div> <div id="iframeHolders"></div><file_sep><div class="app-main__outer"> <div class="app-main__inner"> <div class="app-page-title"> <div class="page-title-wrapper"> <div class="page-title-heading"> <div><b>CODE CHALLENGE ANSWERS</b></div> </div> </div> </div> <div class="col-md-12"> <div class="main-card mb-3 card"> <div class="card-header">Submitted Answers's List </div> <div class="table-responsive"> <table class="align-middle mb-0 table table-borderless table-striped table-hover" id="tableList"> <thead> <tr> <th class="text-left pl-4" width="20%">Language</th> <th class="text-left ">Answers</th> <th class="text-center" width="15%">Submitted Date</th> </tr> </thead> <tbody> <?php $selExam = $conn->query("SELECT * FROM feedbacks_tbl ORDER BY fb_id DESC "); if($selExam->rowCount() > 0) { while ($selExamRow = $selExam->fetch(PDO::FETCH_ASSOC)) { ?> <tr> <td class="pl-4"><?php echo $selExamRow['fb_exmne_as']; ?></td> <td><?php echo $selExamRow['fb_feedbacks']; ?></td> <td><?php echo $selExamRow['fb_date']; ?></td> </tr> <?php } } else { ?> <tr> <td colspan="5"> <h3 class="p-3">No Answers Have Been Submitted</h3> </td> </tr> <?php } ?> </tbody> </table> </div> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $('#button').click(function(){ if(!$('#iframe').length) { $('#iframeHolder').html('<iframe height="400px" width="100%" src="https://replit.com/@Akil01/VapidLinenDownloads?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe>'); } }); }); </script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $('#buttons').click(function(){ if(!$('#iframe').length) { $('#iframeHolders').html('<iframe height="400px" width="100%" src="https://replit.com/@Akil01/PaleTemporalSystemresource?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe>'); } }); }); </script> <style> .dropbtn { background-color: #4CAF50; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } .dropdown { position: relative; display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 160px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); z-index: 1; } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover {background-color: #f1f1f1} .dropdown:hover .dropdown-content { display: block; } .dropdown:hover .dropbtn { background-color: #3e8e41; } </style> <div class="dropdown"> <button class="dropbtn">Click Here To Evaluate</button> <div class="dropdown-content"> <a> <button id="button">C</button> </a> <a><button id="buttons">Java</button></a> </div> </div> <div id="iframeHolder"></div> <div id="iframeHolders"></div> </div> </div> </div> <file_sep> <div class="app-main__outer"> <div id="refreshData"> <div class="app-main__inner"> <div class="app-page-title"> <div class="page-title-wrapper"> <div class="page-title-heading"> <div class="page-title-icon"> <i class="pe-7s-car icon-gradient bg-mean-fruit"> </i> </div> <div><NAME> COLLEGE <div class="page-title-subheading">Lake Road, Velrampet, Pondicherry, India 605 004 </div> </div> </div> <br> <br> <br> <br> <br> <br> <br> </div> <div class="row"> <div class="col-md-6 col-xl-4"> <div class="card mb-3 widget-content bg-midnight-bloom"> <div class="widget-content-wrapper text-white"> <div class="widget-content-left"> <div class="widget-heading">Total Course</div> <div class="widget-subheading" style="color:transparent;">.</div> </div> <div class="widget-content-right"> <div class="widget-numbers text-white"> <span><?php echo $totalCourse = $selCourse['totCourse']; ?></span> </div> </div> </div> </div> </div> <div class="col-md-6 col-xl-4"> <div class="card mb-3 widget-content bg-arielle-smile"> <div class="widget-content-wrapper text-white"> <div class="widget-content-left"> <div class="widget-heading">Total Exam</div> <div class="widget-subheading" style="color:transparent;">.</div> </div> <div class="widget-content-right"> <div class="widget-numbers text-white"> <span><?php echo $totalCourse = $selExam['totExam']; ?></span> </div> </div> </div> </div> </div> <div class="col-md-6 col-xl-4"> <div class="card mb-3 widget-content bg-grow-early"> <div class="widget-content-wrapper text-white"> <div class="widget-content-left"> <div class="widget-heading">Total Examinee</div> <div class="widget-subheading" style="color:transparent;">.</div> </div> <div class="widget-content-right"> <div class="widget-numbers text-white"><span>46%</span></div> </div> </div> </div> </div> <!-- <?php include("includes/graph.php"); ?> --> </div> </div>
b82f19e8ea6490fead2c92b453c86ef2381e4d7d
[ "PHP" ]
3
PHP
akilanselvam/Online-Examination-System-Code-Challenge
9ad56c4697e37926d4c4f7fca465fa04f8622018
2342da79a1fc8c3ecb599cb0086526cb8d4c8118
refs/heads/master
<repo_name>jsimonetti/pwscheme<file_sep>/ssha512/ssha512.go // Package ssha512 provides functions to generate and validate {SSHA512} styled // password schemes. // The method used is defined in RFC 2307 and uses a salted SHA512 secure hashing // algorithm package ssha512 import ( "crypto/rand" "crypto/sha512" "crypto/subtle" "encoding/base64" "errors" "fmt" ) // ErrNotSshaPassword occurs when Validate receives a non-SSHA512 hash var ErrNotSshaPassword = errors.New("string is not a SSHA512 hashed password") // ErrBase64DecodeFailed occurs when the given hash cannot be decode var ErrBase64DecodeFailed = errors.New("base64 decode of hash failed") // ErrNotMatching occurs when the given password and hash do not match var ErrNotMatching = errors.New("hash does not match password") // Generate encrypts a password with a random salt of definable length and // returns the {SSHA512} encoding of the password func Generate(password string, length uint8) (string, error) { salt := make([]byte, length) _, err := rand.Read(salt) if err != nil { return "", err } hash := createHash(password, salt) ret := fmt.Sprintf("{SSHA512}%s", base64.StdEncoding.EncodeToString(hash)) return ret, nil } // Validate compares a given password with a {SSHA512} encoded password // Returns true is they match or an error otherwise func Validate(password string, hash string) (bool, error) { if len(hash) < 10 || string(hash[0:9]) != "{SSHA512}" { return false, ErrNotSshaPassword } data, err := base64.StdEncoding.DecodeString(hash[9:]) if len(data) < 65 || err != nil { return false, ErrBase64DecodeFailed } newhash := createHash(password, data[64:]) hashedpw := base64.StdEncoding.EncodeToString(newhash) if subtle.ConstantTimeCompare([]byte(hashedpw), []byte(hash[9:])) == 1 { return true, nil } return false, ErrNotMatching } // This function appends password and salt together to a byte array func createHash(password string, salt []byte) []byte { pass := []byte(password) str := append(pass[:], salt[:]...) sum := sha512.Sum512(str) result := append(sum[:], salt[:]...) return result } <file_sep>/ssha256/ssha256.go // Package ssha256 provides functions to generate and validate {SSHA256} styled // password schemes. // The method used is defined in RFC 2307 and uses a salted SHA256 secure hashing // algorithm package ssha256 import ( "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/base64" "errors" "fmt" ) // ErrNotSshaPassword occurs when Validate receives a non-SSHA256 hash var ErrNotSshaPassword = errors.New("string is not a SSHA256 hashed password") // ErrBase64DecodeFailed occurs when the given hash cannot be decode var ErrBase64DecodeFailed = errors.New("base64 decode of hash failed") // ErrNotMatching occurs when the given password and hash do not match var ErrNotMatching = errors.New("hash does not match password") // Generate encrypts a password with a random salt of definable length and // returns the {SSHA256} encoding of the password func Generate(password string, length uint8) (string, error) { salt := make([]byte, length) _, err := rand.Read(salt) if err != nil { return "", err } hash := createHash(password, salt) ret := fmt.Sprintf("{SSHA256}%s", base64.StdEncoding.EncodeToString(hash)) return ret, nil } // Validate compares a given password with a {SSHA256} encoded password // Returns true is they match or an error otherwise func Validate(password string, hash string) (bool, error) { if len(hash) < 10 || string(hash[0:9]) != "{SSHA256}" { return false, ErrNotSshaPassword } data, err := base64.StdEncoding.DecodeString(hash[9:]) if len(data) < 33 || err != nil { return false, ErrBase64DecodeFailed } newhash := createHash(password, data[32:]) hashedpw := base64.StdEncoding.EncodeToString(newhash) if subtle.ConstantTimeCompare([]byte(hashedpw), []byte(hash[9:])) == 1 { return true, nil } return false, ErrNotMatching } // createHash appends password and salt together to a byte array func createHash(password string, salt []byte) []byte { pass := []byte(password) str := append(pass[:], salt[:]...) sum := sha256.Sum256(str) result := append(sum[:], salt[:]...) return result } <file_sep>/md5crypt/md5crypt_test.go package md5crypt_test import ( "testing" "github.com/jsimonetti/pwscheme/md5crypt" ) func TestValidPassword(t *testing.T) { pass := "<PASSWORD>" hash := "{MD5-CRYPT}$1$UNq3KKXM$hsrKHTk9BaYGZwafpr4K80" if res, err := md5crypt.Validate(pass, hash); err != nil || res != true { t.Errorf("Valid password fails validation: %s", err) } } func TestInValidPassword(t *testing.T) { pass := "<PASSWORD>" hash := "{MD5-CRYPT}$1$UNq3KKXM$hsrKHTk9BaYGZwafpr4K80" if res, err := md5crypt.Validate(pass, hash); res != false { t.Errorf("Invalid password passes validation: %s", err) } } func TestGenerate4(t *testing.T) { pass := "<PASSWORD>" var hash string var err error var res bool if hash, err = md5crypt.Generate(pass, 4); err != nil { t.Errorf("Generate password fails: %s", err) return } if res, err = md5crypt.Validate(pass, hash); err != nil || res != true { t.Errorf("Generated hash can not be validated: %s", err) } } func TestGenerate8(t *testing.T) { pass := "<PASSWORD>" var hash string var err error var res bool if hash, err = md5crypt.Generate(pass, 8); err != nil { t.Errorf("Generate password fails: %s", err) return } if res, err = md5crypt.Validate(pass, hash); err != nil || res != true { t.Errorf("Generated hash can not be validated: %s", err) } } func TestGenerate0(t *testing.T) { if _, err := md5crypt.Generate("", 0); err != md5crypt.ErrSaltLengthInCorrect { t.Errorf("Generated hash with too short salt did not fail") } } func TestGenerate9(t *testing.T) { if _, err := md5crypt.Generate("", 9); err != md5crypt.ErrSaltLengthInCorrect { t.Errorf("Generated hash with too long salt did not fail") } } func TestGenerateManyPasses(t *testing.T) { pass := "<PASSWORD>" var hash string var err error var res bool errors := 0 for i := 0; i < 1000; i++ { if hash, err = md5crypt.Generate(pass, 8); err != nil { t.Errorf("Generate password fails: %s", err) return } if res, err = md5crypt.Validate(pass, hash); err != nil || res != true { t.Errorf("Generated hash can not be validated: %s", err) errors += 1 } } if errors != 0 { t.Errorf("%d error(s) occurred when running 1000 passes", errors) } } <file_sep>/README.md [![GoDoc](https://godoc.org/github.com/jsimonetti/pwscheme?status.svg)](https://godoc.org/github.com/jsimonetti/pwscheme) [![Travis](https://api.travis-ci.org/jsimonetti/pwscheme.svg?branch=master)](https://travis-ci.org/jsimonetti/pwscheme) # pwscheme Golang package defining password schemes Supported schemes - {SSHA} Salted SHA1 - {SSHA256} Salted SHA256 - {SSHA512} Salted SHA512 - {MD5-CRYPT} Crypt with MD5 Docs: https://godoc.org/github.com/jsimonetti/pwscheme <file_sep>/go.mod module github.com/jsimonetti/pwscheme go 1.13 require ( golang.org/x/crypto v0.0.0-20220919173607-35f4265a4bc0 // indirect golang.org/x/net v0.0.0-20220921155015-db77216a4ee9 // indirect golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8 // indirect golang.org/x/term v0.0.0-20220919170432-7a66f970e087 // indirect ) <file_sep>/md5crypt/md5crypt.go // Package md5crypt provides functions to generate and validate {MD5-CRYPT} styled // password schemes. // The method used is compatible with libc crypt used in /etc/shadow package md5crypt import ( "crypto/md5" "crypto/rand" "crypto/subtle" "errors" "fmt" "strings" ) const itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" var md5CryptSwaps = [16]int{12, 6, 0, 13, 7, 1, 14, 8, 2, 15, 9, 3, 5, 10, 4, 11} var magic = []byte("$1$") // ErrNotMd5cryptPassword occurs when Validate receives a non-SSHA hash var ErrNotMd5cryptPassword = errors.New("string is not a MD5-CRYPT password") // ErrNotMatching occurs when the given password and hash do not match var ErrNotMatching = errors.New("hash does not match password") // ErrSaltLengthInCorrect occurs when the given salt is not of the correct // length var ErrSaltLengthInCorrect = errors.New("salt length incorrect") // Generate encrypts a password with a random salt of definable length and // returns the {MD5-CRYPT} encoding of the password func Generate(password string, length uint8) (string, error) { if length > 8 || length < 1 { return "", ErrSaltLengthInCorrect } salt := make([]byte, length) _, err := rand.Read(salt) if err != nil { return "", err } // we need to reject salts that contain the char $ for strings.Count(string(salt), "$") != 0 { _, err := rand.Read(salt) if err != nil { return "", err } } hash := fmt.Sprintf("{MD5-CRYPT}%s", crypt([]byte(password), salt)) return hash, nil } // Validate compares a given password with a {SSHA} encoded password // Returns true is they match or an error otherwise func Validate(password string, hash string) (bool, error) { if len(hash) < 15 || string(hash[0:14]) != "{MD5-CRYPT}$1$" { return false, ErrNotMd5cryptPassword } data := strings.Split(hash[14:], "$") newhash := crypt([]byte(password), []byte(data[0])) if subtle.ConstantTimeCompare(newhash, []byte(hash[11:])) == 1 { return true, nil } return false, ErrNotMatching } func crypt(password, salt []byte) []byte { d := md5.New() d.Write(password) d.Write(magic) d.Write(salt) d2 := md5.New() d2.Write(password) d2.Write(salt) d2.Write(password) for i, mixin := 0, d2.Sum(nil); i < len(password); i++ { d.Write([]byte{mixin[i%16]}) } for i := len(password); i != 0; i >>= 1 { if i&1 == 0 { d.Write([]byte{password[0]}) } else { d.Write([]byte{0}) } } final := d.Sum(nil) for i := 0; i < 1000; i++ { d2 := md5.New() if i&1 == 0 { d2.Write(final) } else { d2.Write(password) } if i%3 != 0 { d2.Write(salt) } if i%7 != 0 { d2.Write(password) } if i&1 == 0 { d2.Write(password) } else { d2.Write(final) } final = d2.Sum(nil) } result := make([]byte, 0, 22) v := uint(0) bits := uint(0) for _, i := range md5CryptSwaps { v |= (uint(final[i]) << bits) for bits = bits + 8; bits > 6; bits -= 6 { result = append(result, itoa64[v&0x3f]) v >>= 6 } } result = append(result, itoa64[v&0x3f]) return append(append(append(magic, salt...), '$'), result...) } <file_sep>/ssha256/ssha256_test.go package ssha256_test import ( "testing" "github.com/jsimonetti/pwscheme/ssha256" ) func TestValidPassword(t *testing.T) { pass := "<PASSWORD>" hash := "{SSHA256}czO44OTV17PcF1cRxWrLZLy9xHd7CWyVYplr1rOhuMlx/7IK" if res, err := ssha256.Validate(pass, hash); err != nil || res != true { t.Errorf("Valid password fails validation: %s", err) } } func TestInValidPassword(t *testing.T) { pass := "<PASSWORD>" hash := "{SSHA256}czO44OTV17PcF1cRxWrLZLy9xHd7CWyVYplr1rOhuMlx/7IK" if res, err := ssha256.Validate(pass, hash); res != false { t.Errorf("Invalid password passes validation: %s", err) } } func TestGenerate4(t *testing.T) { pass := "<PASSWORD>" var hash string var err error var res bool if hash, err = ssha256.Generate(pass, 4); err != nil { t.Errorf("Generate password fails: %s", err) return } if res, err = ssha256.Validate(pass, hash); err != nil || res != true { t.Errorf("Generated hash can not be validated: %s", err) } } func TestGenerate8(t *testing.T) { pass := "<PASSWORD>" var hash string var err error var res bool if hash, err = ssha256.Generate(pass, 8); err != nil { t.Errorf("Generate password fails: %s", err) return } if res, err = ssha256.Validate(pass, hash); err != nil || res != true { t.Errorf("Generated hash can not be validated: %s", err) } } func TestGenerateManyPasses(t *testing.T) { pass := "<PASSWORD>" var hash string var err error var res bool errors := 0 for i := 0; i < 1000; i++ { if hash, err = ssha256.Generate(pass, 8); err != nil { t.Errorf("Generate password fails: %s", err) return } if res, err = ssha256.Validate(pass, hash); err != nil || res != true { t.Errorf("Generated hash can not be validated: %s", err) errors += 1 } } if errors != 0 { t.Errorf("%d error(s) occurred when running 1000 passes", errors) } }
0c4300a7bb8d80c396afcb548a7949f86c4d9ff5
[ "Markdown", "Go Module", "Go" ]
7
Go
jsimonetti/pwscheme
67a4d090f150fa1f65cd4efa392988fc3c4f6a5a
cd346a9c11274c731f09ad4d9631ee719b5d210a
refs/heads/main
<repo_name>Pandoradoomer/PDProject<file_sep>/index.js const { removeAllListeners } = require('nodemon'); var io = require('socket.io')(process.env.PORT || 29015); console.log('Server has started'); var hostsockets = [] io.on('connection',function(socket){ socket.on('hasconnected',function(){ console.log('Connected!'); socket.emit('serverconnect'); }); //we employ this function when the host starts a room socket.on('createroom',function(){ hostsockets.push(socket); console.log('Creating room...'); var roomCode = ""; var badCodes = ['SHIT', 'FUCK', 'PISS', 'CUNT', 'TWAT', 'TWIT', 'FAGT', 'NIGR']; roomCode = makeRoomCode(4); //assign a roomCode at random, and first verify if it's bad while(badCodes.includes(roomCode)) { roomCode = makeRoomCode(4); } //then verify if there's another room of the same name on the server var found = true while(found) { found = false; for(var room in io.sockets.adapter.rooms) if(room == roomCode) { roomCode = makeRoomCode(4) found = true; } } socket.join(roomCode); console.log('Joined room ' + roomCode); for(var room in io.sockets.adapter.rooms) console.log(room); socket.emit('roomcode',roomCode); }); socket.on('disconnect',function(){ console.log('Disconnected!'); for(var sock in hostsockets) if(socket == sock) { } }); }); function makeRoomCode(length) { var result = ''; var characters = 'ABCDEFGHIJKLMNOPQRTSUVWXYZ'; var charLength = characters.length; for(var i = 0 ; i < length; i++) result += characters.charAt(Math.floor(Math.random() * charLength)); return result; }
5615af77c58f8d8f4e68ce0f40773f000b800442
[ "JavaScript" ]
1
JavaScript
Pandoradoomer/PDProject
c56d6f99f6bab02e10ceb7a7b9a5503ebfdb4924
d6fb12917f7bebf79b0c2c8ad629533433a16472
refs/heads/master
<file_sep>Temporary readme for the life-ishort repo. "An electronic manager for life...," the ishort Life Manager is meant to keep track of various tidbits of data through the use of a plethora of tabs performing differing tasks, from keeping track of contacts, to creating lists of tasks for a day's work. Life Manager's MainFrame class is meant to be a lightweight container for these tabs, and should be able to add, reload, and remove various tabs through the use of Java reflections and file I/O. <file_sep>/* * TabUI.java * * V0.0.1 'Hax' * * 14/11/01 (Date of First Creation in YY/MM/DD) * 14/11/01 (Date of Version Change in YY/MM/DD) * * Copyright (c) 2014-2015 Silverwood Laboratories. * This software is provided as is. We assume * no responsibilities for the damages incurred using this program * or any modified versions of this prototype. Use at your own risk. * ---Chris Productions--- */ package io.github.cappycot.life.ui; import java.io.File; import javax.swing.JPanel; /** * The format for a tab in the {@link MainFrame}. * * @author <NAME> */ public abstract class TabUI extends JPanel { // Constants private static final long serialVersionUID = 2L; // Instance Variables private String name; private String desc; private MainFrame frame; private File dir; /** * The constructors for tabs should only instantiate these three variables.<br> * The only other thing that should take place in the constructor is the * modification<br> * of the layout of the internal components. * * @param name * @param frame * @param dir */ public TabUI(String name, String desc, MainFrame frame, File dir) { this.name = name; this.desc = desc; this.frame = frame; this.dir = dir; } /** * Get the ground running for the variables and how they govern the tab. * * @param objects */ public abstract void init(Object... objects); /** * Update once every second. */ public abstract void tick(); /** * Safe shutdown of the tab. */ public abstract void kill(); public String getName() { return name; } public String getDesc() { return desc; } public MainFrame getFrame() { return frame; } public File getDir() { return dir; } } <file_sep>/* * TimeTab.java * * V0.0.1 'Hax' * * 14/11/02 (Date of First Creation in YY/MM/DD) * 14/11/08 (Date of Version Change in YY/MM/DD) * * Copyright (c) 2014-2015 Silverwood Laboratories. * This software is provided as is. We assume * no responsibilities for the damages incurred using this program * or any modified versions of this prototype. Use at your own risk. * ---Chris Productions--- */ package io.github.cappycot.life.tabs; import io.github.cappycot.life.ui.MainFrame; import io.github.cappycot.life.ui.TabUI; import java.io.File; import java.util.Calendar; /** * Manages your time on the computer, making an attempt to auto shutdown if * possible. * * @author <NAME> */ public class TimeTab extends TabUI { // Constants private static final long serialVersionUID = 102L; // Instance Variables private int dayStart; // Determines beginning to computer period. private int dayEnd; // The period between dayStart and dayEnd is viable time // to use the computer. private int timeLimit; private int timeSpent; private boolean shutdown; private int shutdownTime; public TimeTab(String name, String desc, MainFrame frame, File dir) { super(name, desc, frame, dir); } @Override public void init(Object... objects) { load(); } /** * Read the Timedata file found in the */ public synchronized void load() { File dir = getDir(); } public boolean canShutdown() { return shutdown; } public void setShutdown(boolean shutdown) { this.shutdown = shutdown; } @Override public void kill() { // Do nothing. } /** * Recheck calendar time and determine shutdown. */ public void tick() { Calendar cal = Calendar.getInstance(); int hour = cal.get(Calendar.HOUR); } } <file_sep>package io.github.cappycot.life.tasks; import java.awt.TrayIcon; import java.io.File; public class TaskRunner extends Thread { // Constants public static final boolean testing = false; /* Instance Variables */ private TaskTab window; private File dir; public TaskRunner(TaskTab window) { this.window = window; dir = window.getDir(); } public void run() { // TODO: Establish update regimen... System.out.println("Thread"); // TODO: ...then run updates periodically. } public void message(String title, String msg, TrayIcon.MessageType type) { // TODO: window.getFrame()... } } <file_sep>/* * ChatTab.java * * V0.0.1 'Hax' * * 14/11/08 (Date of First Creation in YY/MM/DD) * 14/11/08 (Date of Version Change in YY/MM/DD) * * Copyright (c) 2014-2015 Silverwood Laboratories. * This software is provided as is. We assume * no responsibilities for the damages incurred using this program * or any modified versions of this prototype. Use at your own risk. * ---Chris Productions--- */ package io.github.cappycot.life.chat; import io.github.cappycot.life.ui.MainFrame; import io.github.cappycot.life.ui.TabUI; import java.io.File; /** * Tab for chatting via a specialized server.<br> * Coming soon. * * @author <NAME> */ public class ChatTab extends TabUI { private static final long serialVersionUID = 6092610971112258058L; public ChatTab(String name, String desc, MainFrame frame, File dir) { super(name, desc, frame, dir); } @Override public void init(Object... objects) { // TODO Auto-generated method stub } @Override public void tick() { // TODO Auto-generated method stub } @Override public void kill() { // TODO Auto-generated method stub } }
630bff2250d72d12ab123e62f87aa9bca2428ec0
[ "Markdown", "Java" ]
5
Markdown
Cappycot/life-ishort
b02f9bea4e85890cc98bc5bdb102886636c8351d
502b2c5bb6bad722f6025e57aa42736511312cb4
refs/heads/master
<repo_name>sobaya-0141/Sceneform<file_sep>/app/src/main/java/sobaya/app/sceneform/PointerDrawable.kt package sobaya.app.sceneform import android.graphics.* import android.graphics.drawable.Drawable class PointerDrawable : Drawable() { private val paint = Paint() var enabled = false override fun draw(canvas: Canvas) { val cx = canvas.width.toFloat() val cy = canvas.height.toFloat() if (enabled) { paint.color = Color.GREEN canvas.drawCircle(cx, cy, 10f, paint) } else { paint.color = Color.GRAY canvas.drawText("X", cx, cy, paint) } } override fun setAlpha(alpha: Int) {} override fun getOpacity() = PixelFormat.UNKNOWN override fun setColorFilter(colorFilter: ColorFilter?) {} }<file_sep>/settings.gradle include ':app' rootProject.name='Sceneform'
28cee88eb5c7ddf4ef0d554b0f4ff33c70b53cb5
[ "Kotlin", "Gradle" ]
2
Kotlin
sobaya-0141/Sceneform
878ab76c017c86b21064dc460f687b2ec28fe9f0
4783cba15e958cf3e85be4a7cded6c5fe7b35018
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RepetierHostExtender.interfaces; namespace CncPlugin { public class CncPlugin : IHostPlugin { private CncControl cool; IHost host; /// <summary> /// Called first to allow filling some lists. Host is not fully set up at that moment. /// </summary> /// <param name="host"></param> public void PreInitalize(IHost _host) { host = _host; } /// <summary> /// Called after everything is initalized to finish parts, that rely on other initializations. /// Here you must create and register new Controls and Windows. /// </summary> public void PostInitialize() { // Add the CoolControl to the right tab cool = new CncControl(); cool.Connect(host); host.RegisterHostComponent(cool); // Add some text in the about dialog host.AboutDialog.RegisterThirdParty("CncPlugin", "\r\n\r\nCNC control plugin by <NAME>"); } /// <summary> /// Last round of plugin calls. All controls exist, so now you may modify them to your wishes. /// </summary> public void FinializeInitialize() { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RepetierHostExtender.interfaces; namespace CncPlugin { public class PluginPreferences { private IHost host; public int jog_key_x_minus; public int jog_key_x_plus; public int jog_key_y_minus; public int jog_key_y_plus; public int jog_key_z_minus; public int jog_key_z_plus; public int step_key_1; public int step_key_2; public int step_key_3; public int step_key_4; public int step_key_5; public double jog_step_1; public double jog_step_2; public double jog_step_3; public double jog_step_4; public double jog_step_5; public string spindle_start; public string spindle_stop; public string spindle_pwm; public string jog_unit; public bool globalkeys; public bool enablespindle; public PluginPreferences(IHost h) { host = h; loadDefaults(); } public void loadDefaults() { IRegMemoryFolder reg = host.GetRegistryFolder("CncPlugin"); jog_key_x_minus = reg.GetInt("jog_x_minus", 37); // LEFT jog_key_x_plus = reg.GetInt("jog_x_plus", 39); // RIGHT jog_key_y_minus = reg.GetInt("jog_y_minus", 40); // DOWN jog_key_y_plus = reg.GetInt("jog_y_plus", 38); // UP jog_key_z_minus = reg.GetInt("jog_z_minus", 34); // PGDN jog_key_z_plus = reg.GetInt("jog_z_plus", 33); // PGUP jog_step_1 = reg.GetDouble("jog_step_1", 50); jog_step_2 = reg.GetDouble("jog_step_2", 10); jog_step_3 = reg.GetDouble("jog_step_3", 1); jog_step_4 = reg.GetDouble("jog_step_4", 0.1); jog_step_5 = reg.GetDouble("jog_step_5", 100); step_key_1 = reg.GetInt("step_key_1", 120); // F9 step_key_2 = reg.GetInt("step_key_2", 121); // F10 step_key_3 = reg.GetInt("step_key_3", 122); // F11 step_key_4 = reg.GetInt("step_key_4", 123); // F12 step_key_5 = reg.GetInt("step_key_5", 119); // F8 spindle_start = reg.GetString("spindle_start", "M106 S%p"); spindle_stop = reg.GetString("spindle_stop", "M107"); spindle_pwm = reg.GetString("spindle_pwm", "M106 S%p"); enablespindle = reg.GetBool("enablespindle", false); jog_unit = reg.GetString("jog_unit", "mm"); globalkeys = reg.GetBool("globalkeys", false); } public void save() { IRegMemoryFolder reg = host.GetRegistryFolder("CncPlugin"); reg.SetInt("jog_x_minus", jog_key_x_minus); reg.SetInt("jog_x_plus", jog_key_x_plus); reg.SetInt("jog_y_minus", jog_key_y_minus); reg.SetInt("jog_y_plus", jog_key_y_plus); reg.SetInt("jog_z_minus", jog_key_z_minus); reg.SetInt("jog_z_plus", jog_key_z_plus); reg.SetDouble("jog_step_1", jog_step_1); reg.SetDouble("jog_step_2", jog_step_2); reg.SetDouble("jog_step_3", jog_step_3); reg.SetDouble("jog_step_4", jog_step_4); reg.SetDouble("jog_step_5", jog_step_5); reg.SetInt("step_key_1", step_key_1); reg.SetInt("step_key_2", step_key_2); reg.SetInt("step_key_3", step_key_3); reg.SetInt("step_key_4", step_key_4); reg.SetInt("step_key_5", step_key_5); reg.SetString("spindle_start", spindle_start); reg.SetString("spindle_stop", spindle_stop); reg.SetString("spindle_pwm", spindle_pwm); reg.SetString("jog_unit", jog_unit); reg.SetBool("globalkeys", globalkeys); reg.SetBool("enablespindle", enablespindle); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using RepetierHostExtender.interfaces; using System.Globalization; /* TODO * 0.1mm round error * use the pref values in the other dialog * dropdown with key friendly names */ namespace CncPlugin { public partial class preferences : Form { private IHost host; private PluginPreferences pref; private CncControl _cc; public preferences(IHost h, PluginPreferences _pref, CncControl cc) { InitializeComponent(); this.FormBorderStyle = FormBorderStyle.FixedDialog; host = h; pref = _pref; _cc = cc; pref.loadDefaults(); } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } void loadDefault() { txt_jog_x_minus.Text = pref.jog_key_x_minus.ToString(); txt_jog_x_plus.Text = pref.jog_key_x_plus.ToString(); txt_jog_y_minus.Text = pref.jog_key_y_minus.ToString(); txt_jog_y_plus.Text = pref.jog_key_y_plus.ToString(); txt_jog_z_minus.Text = pref.jog_key_z_minus.ToString(); txt_jog_z_plus.Text = pref.jog_key_z_plus.ToString(); txt_step_1.Text = pref.jog_step_1.ToString(); txt_step_2.Text = pref.jog_step_2.ToString(); txt_step_3.Text = pref.jog_step_3.ToString(); txt_step_4.Text = pref.jog_step_4.ToString(); txt_step_5.Text = pref.jog_step_5.ToString(); txt_step1_key.Text = pref.step_key_1.ToString(); txt_step2_key.Text = pref.step_key_2.ToString(); txt_step3_key.Text = pref.step_key_3.ToString(); txt_step4_key.Text = pref.step_key_4.ToString(); txt_step5_key.Text = pref.step_key_5.ToString(); txt_spindle_start.Text = pref.spindle_start; txt_spindle_stop.Text = pref.spindle_stop; txt_spindle_pwm.Text = pref.spindle_pwm; if (pref.jog_unit == "mm") { rb_unit_mm.Checked = true; } else { rb_unit_inch.Checked = true; } cb_globalkeys.Checked = pref.globalkeys; cb_EnSpindle.Checked = pref.enablespindle; } private void preferences_Load(object sender, EventArgs e) { loadDefault(); if (host.IsMono) { groupWindows.Enabled = false; cb_globalkeys.Checked = false; } } private void btnSave_Click(object sender, EventArgs e) { SavePreferences(); this.Close(); } private void SavePreferences() { pref.jog_key_x_minus = int.Parse(txt_jog_x_minus.Text); pref.jog_key_x_plus = int.Parse(txt_jog_x_plus.Text); pref.jog_key_y_minus = int.Parse(txt_jog_y_minus.Text); pref.jog_key_y_plus = int.Parse(txt_jog_y_plus.Text); pref.jog_key_z_minus = int.Parse(txt_jog_z_minus.Text); pref.jog_key_z_plus = int.Parse(txt_jog_z_plus.Text); pref.jog_step_1 = Double.Parse(txt_step_1.Text); pref.jog_step_2 = Double.Parse(txt_step_2.Text); pref.jog_step_3 = Double.Parse(txt_step_3.Text); pref.jog_step_4 = Double.Parse(txt_step_4.Text); pref.jog_step_5 = Double.Parse(txt_step_5.Text); pref.step_key_1 = int.Parse(txt_step1_key.Text); pref.step_key_2 = int.Parse(txt_step2_key.Text); pref.step_key_3 = int.Parse(txt_step3_key.Text); pref.step_key_4 = int.Parse(txt_step4_key.Text); pref.step_key_5 = int.Parse(txt_step5_key.Text); pref.spindle_start = txt_spindle_start.Text; pref.spindle_stop = txt_spindle_stop.Text; pref.spindle_pwm = txt_spindle_pwm.Text; if (rb_unit_mm.Checked == true) { pref.jog_unit = "mm"; } else { pref.jog_unit = "inch"; } pref.globalkeys = cb_globalkeys.Checked; pref.enablespindle = cb_EnSpindle.Checked; host.LogMessage("CncPlugin: Preferences saved"); pref.save(); _cc.refreshPref(); } private void OnlyNumericalData(object sender, KeyPressEventArgs e) { if (!(char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back) || e.KeyChar == Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator))) e.Handled = true; } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { IRegMemoryFolder reg = host.GetRegistryFolder("CncPlugin"); reg.DeleteThisFolder(); pref.loadDefaults(); loadDefault(); _cc.refreshPref(); } private void groupBox2_Enter(object sender, EventArgs e) { } private void cb_EnSpindle_CheckedChanged(object sender, EventArgs e) { (this.Owner as form).groupBox4.Visible = cb_EnSpindle.Checked; } } }
e1c02fb2a02e3c554c37883caa4cebed5d10f70c
[ "C#" ]
3
C#
damienj210/repetier-cncplugin
5ba1e554b2acbfb50af2ca7f05798fe7cbaebe91
85d241a9d5fcbff9baabefd7a7f98eaff0513bf8
refs/heads/main
<file_sep><?php namespace App\Models; class Channel extends Model { public function discussions() { return $this->hasMany(Discussion::class,'channel_id'); } } <file_sep>**Discussion Forum** It is a discussion forum which is built on **Laravel 7+** followed by **Kati-Frantz** (udemy instructor). **Modules**: 1- Discussion Module 2- Reply Module 3- Notification Module 4- Queues 5- Filteration 6- Email Verification **NOTE:** "Code is updated, if further changes are applied so they will be updated too. **Thank You!**" **For contact:** Follow me on Github **OR** Email: **<EMAIL>** <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\CheckDiscussionRequest; use App\Models\Discussion; use App\Models\Reply; use Illuminate\Http\Request; use App\Models\Channel; use Illuminate\Support\Str; class DiscussionController extends Controller { public function __construct() { $this->middleware(['auth','verified'])->only(['create', 'store', 'edit', 'update', 'destroy']); } public function index() { return view('admin.discussion.index') ->withPage('index') ->withDiscussions(Discussion::filterByChannels()->orderBy('created_at','DESC')->paginate(10)); } public function create() { return view('admin.discussion.create') ->withChannels(Channel::get()); } public function store(CheckDiscussionRequest $cdr) { auth()->user()->discussions()->create([ 'title' => request()->title, 'content' => request()->content, 'slug' => Str::slug(request()->title), 'channel_id' => request()->channel_id, ]); return redirect() ->route('discussions.index') ->with('success', 'Discussion posted successfully.'); } public function show(Discussion $discussion) { return view('admin.discussion.show') ->withPage('show') ->withDiscussion($discussion); } public function edit($id) { // } public function update(Request $request, $id) { // } public function destroy($id) { // } public function markAsBestReply(Discussion $discussion, Reply $reply) { $discussion->markAsBestReply($reply); return redirect() ->back() ->with('success', 'Marked as best reply.'); } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\CheckReplyRequest; use App\Models\Discussion; use App\Notifications\NewReplyAdded; use Illuminate\Http\Request; class ReplyController extends Controller { public function index() { // } public function create() { // } public function store(CheckReplyRequest $crr, Discussion $discussion) { auth()->user()->replies()->create([ 'reply' => request()->reply, 'discussion_id' => $discussion->id, ]); if($discussion->author->id != auth()->user()->id) { $discussion->author->notify(new NewReplyAdded($discussion)); } return redirect() ->back() ->with('success', 'Reply posted successfully.'); } public function show($id) { // } public function edit($id) { // } public function update(Request $request, $id) { // } public function destroy($id) { // } } <file_sep><?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class UserController extends Controller { public function notification() { auth()->user()->unreadNotifications->markAsRead(); return view('admin.user.notification') ->withNotifications(auth()->user()->notifications()->paginate(8)); } } <file_sep><?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use App\Models\Channel; class ChannelsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('channels')->truncate(); $channels = [ [ 'name' => 'Laravel 7.0', 'slug' => Str::slug('Laravel 7.0'), 'created_at' => \Carbon\Carbon::now() ], [ 'name' => 'Laravel Vue JS', 'slug' => Str::slug('Laravel Vue JS'), 'created_at' => \Carbon\Carbon::now() ], [ 'name' => 'CodeIgniter 4.0', 'slug' => Str::slug('CodeIgniter 4.0'), 'created_at' => \Carbon\Carbon::now() ], [ 'name' => 'WordPress 4.0', 'slug' => Str::slug('WordPress 4.0'), 'created_at' => \Carbon\Carbon::now() ], [ 'name' => 'Node JS', 'slug' => Str::slug('Node JS'), 'created_at' => \Carbon\Carbon::now() ] ]; Channel::insert($channels); } } <file_sep><?php use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return redirect('admin/login'); }); Route::prefix('admin')->group(function () { Auth::routes(['verify' => true]); Route::get('/home', 'HomeController@index')->name('home'); Route::resource('discussions', 'Admin\DiscussionController'); Route::resource('discussions/{discussion}/replies', 'Admin\ReplyController'); Route::post('discussions/{discussion}/replies/{reply}/mark-as-best-reply', 'Admin\DiscussionController@markAsBestReply') ->name('discussion.best-reply'); Route::get('users/notifications', 'Admin\UserController@notification') ->name('users.notification'); });
f77de4ea62129946c6bd96a9d2091e71c98854ea
[ "Markdown", "PHP" ]
7
PHP
taimoorKVD/Discussion-Forum
73597122d355f271afd6256e4813207d4928bcd6
9f75e12fb49e08075a9386bf87565a3e82dee897
refs/heads/master
<file_sep># X but for Y Your next elevator pitch is only a click away. <file_sep>import os from random import randint from flask import Flask, render_template app = Flask(__name__) class ElevatorPitch(object): def __init__(self): def _read_list(filename): datadir = os.path.join( os.path.dirname(os.path.realpath(__file__)), "data" ) with open(os.path.join(datadir, filename)) as f: return f.read().splitlines() self.companies = _read_list("companies.txt") self.nouns = _read_list("nouns.txt") def generate(self): x_row = randint(0, len(self.companies) - 1) y_row = randint(0, len(self.nouns) - 1) x = self.companies[x_row] y = pluralize(self.nouns[y_row]) return "{} but for {}".format(x, y) def pluralize(noun): if len(noun) > 1: if noun.endswith('s'): return noun if any(noun.endswith(s) for s in ['sh', 'x', 'o', 'ch']): return noun + 'es' if noun.endswith('y'): if noun[-2] not in "aeoui": return noun[:-1] + 'ies' return noun + 's' def get_pitch(): elevator_pitch = ElevatorPitch() return elevator_pitch.generate() @app.route('/') def index(): result = get_pitch() return render_template("index.html", result=result)
1747f7dd38102272ed5213e4b9bc67bed765cd18
[ "Markdown", "Python" ]
2
Markdown
engstrom/xbutfory
08189b94dfe48b51087ce5f94eadb43ca25da33a
126c4ce6d88a20f4a76c0776c4821a85568f2d1d
refs/heads/master
<file_sep>class HomersController < ApplicationController # GET /homers # GET /homers.json def index @homers = Homer.all respond_to do |format| format.html # index.html.erb format.json { render json: @homers } end end # GET /homers/1 # GET /homers/1.json def show @homer = Homer.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @homer } end end # GET /homers/new # GET /homers/new.json def new @homer = Homer.new respond_to do |format| format.html # new.html.erb format.json { render json: @homer } end end # GET /homers/1/edit def edit @homer = Homer.find(params[:id]) end # POST /homers # POST /homers.json def create @homer = Homer.new(params[:homer]) respond_to do |format| if @homer.save format.html { redirect_to @homer, notice: 'Homer was successfully created.' } format.json { render json: @homer, status: :created, location: @homer } else format.html { render action: "new" } format.json { render json: @homer.errors, status: :unprocessable_entity } end end end # PUT /homers/1 # PUT /homers/1.json def update @homer = Homer.find(params[:id]) respond_to do |format| if @homer.update_attributes(params[:homer]) format.html { redirect_to @homer, notice: 'Homer was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @homer.errors, status: :unprocessable_entity } end end end # DELETE /homers/1 # DELETE /homers/1.json def destroy @homer = Homer.find(params[:id]) @homer.destroy respond_to do |format| format.html { redirect_to homers_url } format.json { head :no_content } end end end
eaa8ff60f555da074ce215d91bfe26f525f9581c
[ "Ruby" ]
1
Ruby
4rajackson/things_i_bought
6a03569d02d2cdd787f462a7a4219b96dd872121
e8162e44ed1f00d2954abdb73af3ba5551f01d06
refs/heads/master
<repo_name>idhere703/totemo-takai-desu<file_sep>/src/data/ExpensesStore.js import Immutable from 'immutable'; import { ReduceStore } from 'flux/utils'; import ExpensesActionTypes from './ExpensesActionTypes'; import ExpensesDispatcher from './ExpensesDispatcher'; import Counter from './Counter'; import Expense from './Expense'; class ExpensesStore extends ReduceStore { constructor() { super(ExpensesDispatcher); } getInitialState() { return Immutable.OrderedMap(); } reduce(state, action) { switch (action.type) { case ExpensesActionTypes.ADD_EXPENSE: const id = Counter.increment(); return state.set(id, new Expense({ id, value: action.value || 0, category: action.category || '', label: action.label || '' })); case ExpensesActionTypes.DELETE_EXPENSE: return state.delete(action.id); case ExpensesActionTypes.EDIT_EXPENSE: return state.update(action.expense.id, record => record = { ...action.expense }); case ExpensesActionTypes.UPLOAD_EXPENSE_FILE: console.log('Action file upload', action); return state; default: return state; } } } export default new ExpensesStore();<file_sep>/src/data/Counter.js let _counter = 0; const Counter = { increment() { return _counter++; }, }; export default Counter;<file_sep>/src/containers/AppContainer.js import ExpensesView from '../views/ExpensesView'; import { Container } from 'flux/utils'; import ExpensesStore from '../data/ExpensesStore'; import ExpensesActions from '../data/ExpensesActions'; function getStores() { return [ ExpensesStore, ]; } function getState() { return { expenses: ExpensesStore.getState(), onAddExpense: ExpensesActions.addExpense, onDeleteExpense: ExpensesActions.deleteExpense, onEditExpense: ExpensesActions.editExpense, onUploadExpenseFile: ExpensesActions.uploadExpenseFile }; } export default Container.createFunctional(ExpensesView, getStores, getState);<file_sep>/src/components/Footer.js import React from 'react'; export default (props) => { if (props.expenses.size === 0) { return null; } let total = 0; [...props.expenses.values()].forEach((expense) => total += parseFloat(expense.value)); return ( <footer className="App-footer"> <span>{ 'Total:' }<strong>{ total.toFixed(2) }</strong></span> </footer> ); }<file_sep>/src/data/ExpensesActionTypes.js const ActionTypes = { ADD_EXPENSE: 'ADD_EXPENSE', DELETE_EXPENSE: 'DELETE_EXPENSE', EDIT_EXPENSE: 'EDIT_EXPENSE', UPLOAD_EXPENSE_FILE: 'UPLOAD_EXPENSE_FILE' }; export default ActionTypes;<file_sep>/src/components/Header.js import React from 'react'; import FileUpload from './FileUpload'; import AddExpenseBtn from './AddExpenseBtn'; export default (props) => { return ( <header className="App-header row"> <div className="col col-6">Expenses</div> <div className="col"> <AddExpenseBtn {...props} /> </div> <div className="col"> <FileUpload {...props} /> </div> </header> ); }
65827861024014a4a55e0aae8c3380c094b65650
[ "JavaScript" ]
6
JavaScript
idhere703/totemo-takai-desu
cb3ce34415e73de7eef01fafb56143d8e02d3741
d4a6851c41d33c6dd36faae2fae4683f39e5bf5d
refs/heads/master
<file_sep>var React = require('react-native'); var { DeviceEventEmitter } = React; var BackgroundGeolocationManager = React.NativeModules.RNBackgroundGeolocation; var BackgroundGeolocation = { configure: function(config) { BackgroundGeolocationManager.configure(config); }, setConfig: function(config) { BackgroundGeolocationManager.setConfig(config); }, getState: function(callback) { BackgroundGeolocationManager.getState(callback); }, on: function(event, callback) { return DeviceEventEmitter.addListener(event, callback); }, start: function(callback) { BackgroundGeolocationManager.start(callback); }, stop: function() { BackgroundGeolocationManager.stop(); }, onHttp: function(callback) { return DeviceEventEmitter.addListener("http", callback); }, onMotionChange: function(callback) { return DeviceEventEmitter.addListener("motionchange", callback); }, onLocation: function(callback) { return DeviceEventEmitter.addListener("location", callback); }, onGeofence: function(callback) { return DeviceEventEmitter.addListener("geofence", callback); }, onError: function(callback) { return DeviceEventEmitter.addListener("error", callback); }, sync: function(callback) { BackgroundGeolocation.sync(callback); }, changePace: function(value) { BackgroundGeolocationManager.changePace(value); }, finish: function(taskId) { BackgroundGeolocationManager.finish(taskId); }, getCurrentPosition: function(options, success, failure) { if (typeof(options) === 'function') { success = options; options = {}; } options = options || {}; failure = failure || function() {}; BackgroundGeolocationManager.getCurrentPosition(options, success, failure); }, getOdometer: function(callback) { BackgroundGeolocationManager.getOdometer(callback); }, resetOdometer: function(callback) { BackgroundGeolocationManager.resetOdometer(callback); }, addGeofence: function(config) { BackgroundGeolocationManager.addGeofence(config); }, removeGeofence: function(identifier) { BackgroundGeolocationManager.removeGeofence(identifier); }, getGeofences: function(callback) { BackgroundGeolocationManager.getGeofences(callback); } }; module.exports = BackgroundGeolocation;
bb6ecb252488d9ee1ccf78427d7126c42d379a92
[ "JavaScript" ]
1
JavaScript
behboud/react-native-background-geolocation
ef153befd498371cdac7fe50a9a4e4f5612e2cd1
1a901aac6e53a11394d739ef02644c0127d8171b
refs/heads/master
<repo_name>Jerry9757/pytw_a01<file_sep>/ex1_tk.py # github Pytw_T01, Git 練習 from tkinter import * from tkinter import ttk my_window =Tk() my_window.geometry("400x450") # window size my_window.title("Hello tkinter") # window size label_one= Label(my_window, text='Message ') label_one.grid(row=0, column=0) text_msg=Text(my_window,height=1, width=20) text_msg.grid(row=0, column=1) text_msg.insert(END, "Hello world! ") my_window.mainloop() <file_sep>/vi_ex1.py import json import random <file_sep>/requirements.txt tkinter # requests==2.21.0 # numpy==1.19.1 # pandas==1.1.1 <file_sep>/Dockerfile # Use an official Python FROM python:3 # Set the working directory to app WORKDIR /app # Copy the Current directory contemts to the container at /app COPY . /app #COPY requirements.txt requirements.txt # Install package RUN pip install -r requirements.txt # Run py when the container lunches CMD ["python", "ex1_tk.py"]
9fc950f49fdcdd31bad731098fa8d5d1c9b4d4d3
[ "Python", "Text", "Dockerfile" ]
4
Python
Jerry9757/pytw_a01
a54558e89f2c3b78618059d0775525c565632fde
d2992fd1a85ca27ae36c33daf6e9e66e6056f122
refs/heads/master
<file_sep>INSERT INTO projects (title, category, funding_goal, start_date, end_date) VALUES ("one", "tech", 500, "1/1/16", "1/20/16"); INSERT INTO projects (title, category, funding_goal, start_date, end_date) VALUES ("two", "tech", 500, "1/10/16", "1/15/16"); INSERT INTO projects (title, category, funding_goal, start_date, end_date) VALUES ("three", "clothing", 5500, "2/1/16", "1/20/17"); INSERT INTO projects (title, category, funding_goal, start_date, end_date) VALUES ("four", "gadgets", 509, "1/5/16", "1/31/16"); INSERT INTO projects (title, category, funding_goal, start_date, end_date) VALUES ("five", "tech", 50000000, "1/31/16", "2/20/16"); INSERT INTO projects (title, category, funding_goal, start_date, end_date) VALUES ("six", "tech", 30, "7/1/16", "10/20/16"); INSERT INTO projects (title, category, funding_goal, start_date, end_date) VALUES ("seven", "computers", 1, "1/8/16", "8/1/16"); INSERT INTO projects (title, category, funding_goal, start_date, end_date) VALUES ("eight", "food", 5000, "1/16/16", "1/20/16"); INSERT INTO projects (title, category, funding_goal, start_date, end_date) VALUES ("nine", "clothing", 25000, "11/10/16", "1/20/17"); INSERT INTO projects (title, category, funding_goal, start_date, end_date) VALUES ("tex", "gear", 150, "1/1/17", "1/20/17"); INSERT INTO users (name, age) VALUES ("J", 28); INSERT INTO users (name, age) VALUES ("Juice", 2); INSERT INTO users (name, age) VALUES ("Bob", 87); INSERT INTO users (name, age) VALUES ("ZZTop", 65); INSERT INTO users (name, age) VALUES ("Jon", 26); INSERT INTO users (name, age) VALUES ("Tim", 28); INSERT INTO users (name, age) VALUES ("Caleb", 18); INSERT INTO users (name, age) VALUES ("Chris56", 56); INSERT INTO users (name, age) VALUES ("<NAME>", 12); INSERT INTO users (name, age) VALUES ("Timbo88", 27); INSERT INTO users (name, age) VALUES ("Dog", 43); INSERT INTO users (name, age) VALUES ("colin", 29); INSERT INTO users (name, age) VALUES ("J24", 24); INSERT INTO users (name, age) VALUES ("Tombot", 62); INSERT INTO users (name, age) VALUES ("CJ", 38); INSERT INTO users (name, age) VALUES ("BBking", 74); INSERT INTO users (name, age) VALUES ("JJ", 8); INSERT INTO users (name, age) VALUES ("YoYo", 40); INSERT INTO users (name, age) VALUES ("<NAME>", 90); INSERT INTO users (name, age) VALUES ("Walter", 100); INSERT INTO pledges (amount, user_id, project_id) VALUES (100, 20, 1); INSERT INTO pledges (amount, user_id, project_id) VALUES (1000, 10, 1); INSERT INTO pledges (amount, user_id, project_id) VALUES (1000, 19, 10); INSERT INTO pledges (amount, user_id, project_id) VALUES (10000, 2, 10); INSERT INTO pledges (amount, user_id, project_id) VALUES (10, 2, 9); INSERT INTO pledges (amount, user_id, project_id) VALUES (1, 2, 9); INSERT INTO pledges (amount, user_id, project_id) VALUES (10, 1, 8); INSERT INTO pledges (amount, user_id, project_id) VALUES (1000000, 20, 7); INSERT INTO pledges (amount, user_id, project_id) VALUES (1, 3, 7); INSERT INTO pledges (amount, user_id, project_id) VALUES (1, 3, 7); INSERT INTO pledges (amount, user_id, project_id) VALUES (1, 20, 6); INSERT INTO pledges (amount, user_id, project_id) VALUES (10, 4, 6); INSERT INTO pledges (amount, user_id, project_id) VALUES (160, 4, 6); INSERT INTO pledges (amount, user_id, project_id) VALUES (150, 9, 6); INSERT INTO pledges (amount, user_id, project_id) VALUES (140, 19, 5); INSERT INTO pledges (amount, user_id, project_id) VALUES (140, 19, 5); INSERT INTO pledges (amount, user_id, project_id) VALUES (140, 5, 5); INSERT INTO pledges (amount, user_id, project_id) VALUES (1030, 6, 4); INSERT INTO pledges (amount, user_id, project_id) VALUES (10, 6, 4); INSERT INTO pledges (amount, user_id, project_id) VALUES (10, 8, 4); INSERT INTO pledges (amount, user_id, project_id) VALUES (100, 8, 4); INSERT INTO pledges (amount, user_id, project_id) VALUES (122, 18, 4); INSERT INTO pledges (amount, user_id, project_id) VALUES (12, 20, 3); INSERT INTO pledges (amount, user_id, project_id) VALUES (80, 20, 3); INSERT INTO pledges (amount, user_id, project_id) VALUES (1000, 15, 2); INSERT INTO pledges (amount, user_id, project_id) VALUES (100, 2, 2); INSERT INTO pledges (amount, user_id, project_id) VALUES (300, 15, 2); INSERT INTO pledges (amount, user_id, project_id) VALUES (3300, 8, 1); INSERT INTO pledges (amount, user_id, project_id) VALUES (800, 18, 1); INSERT INTO pledges (amount, user_id, project_id) VALUES (2, 1, 1);
8c6b16b485e76a7a6ba6a840449c8529a42b7e67
[ "SQL" ]
1
SQL
gormanjp/sql-crowdfunding-lab-v-000
dc2560948d9477d0cbdb6d36b2a5553960788f72
f84989509388fb2d29c68657e1888c8e33922edd
refs/heads/master
<repo_name>adamaulia/RAI_Task_3<file_sep>/RAI-Socket-2/src/rai/socket/pkg2/GUI.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rai.socket.pkg2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Adam */ public class GUI extends javax.swing.JFrame { public Socket soket; BufferedReader buff; /** * Creates new form GUI */ public GUI() { try { initComponents(); buff = new BufferedReader(new InputStreamReader(soket.getInputStream())); ReadInput RI = new ReadInput(buff); RI.start(); } catch (Exception ex) { System.out.println("someting error "+ex); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); JMessage = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); TextOUT = new javax.swing.JTextArea(); JTextIP = new javax.swing.JTextField(); JtextUser = new javax.swing.JTextField(); IpButton = new javax.swing.JButton(); ButtonOK = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setBackground(new java.awt.Color(204, 204, 204)); JMessage.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JMessageActionPerformed(evt); } }); JMessage.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { JMessageKeyPressed(evt); } }); TextOUT.setColumns(20); TextOUT.setRows(5); jScrollPane1.setViewportView(TextOUT); JTextIP.setText("Input IP Address"); JtextUser.setText("Input username"); JtextUser.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { JtextUserActionPerformed(evt); } }); IpButton.setText("ok"); IpButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { IpButtonActionPerformed(evt); } }); ButtonOK.setText("ok"); ButtonOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ButtonOKActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(JMessage, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(JTextIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(IpButton) .addGap(56, 56, 56) .addComponent(JtextUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE) .addComponent(ButtonOK))) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(JMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(JTextIP) .addComponent(IpButton) .addComponent(JtextUser) .addComponent(ButtonOK)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void JtextUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JtextUserActionPerformed // TODO add your handling code here: }//GEN-LAST:event_JtextUserActionPerformed private void IpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_IpButtonActionPerformed // TODO add your handling code here: String ip=JTextIP.getText(); try { System.out.println("ip"+ip); soket = new Socket(ip, 1234); } catch (IOException ex) { System.out.println("error "+ex); } }//GEN-LAST:event_IpButtonActionPerformed private void ButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonOKActionPerformed // TODO add your handling code here: String user; user = JtextUser.getText(); try { System.out.println("user "+user); PrintWriter output = new PrintWriter(soket.getOutputStream(),true); output.println(user); output.flush(); } catch (Exception ex) { System.out.println("someting error"+ex);; } }//GEN-LAST:event_ButtonOKActionPerformed private void JMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JMessageActionPerformed // TODO add your handling code here: String message; message=JMessage.getText(); try { PrintWriter output = new PrintWriter(soket.getOutputStream(),true); output.println(message); output.flush(); JMessage.setText(""); } catch (IOException ex) { Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_JMessageActionPerformed private void JMessageKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_JMessageKeyPressed // TODO add your handling code here: String message; message=JMessage.getText(); try { System.out.println("message "+message); PrintWriter output = new PrintWriter(soket.getOutputStream(),true); output.println(message); output.flush(); JMessage.setText(""); } catch (IOException ex) { Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_JMessageKeyPressed class ReadInput extends Thread{ private BufferedReader inputStream; public ReadInput(BufferedReader inputReader) { this.inputStream = inputStream; } @Override public void run() { try { String inputan; while ((inputan = inputStream.readLine()) != null) { TextOUT.append(inputan+"\n"); System.out.println(">>"); } } catch (Exception e) { System.out.println("something error"); } } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new GUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton ButtonOK; private javax.swing.JButton IpButton; private javax.swing.JTextField JMessage; private javax.swing.JTextField JTextIP; private javax.swing.JTextField JtextUser; private javax.swing.JTextArea TextOUT; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables } <file_sep>/Socket/src/socket/Server.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.HashSet; /** * * @author Adam * original copy from * http://cs.lmu.edu/~ray/notes/javanetexamples/ */ public class Server { private static final int PORT = 9001; public static void main(String[] args) throws Exception { System.out.println("Server Socket is ON "); ServerSocket listener = new ServerSocket(PORT); try { while (true) { new ServerThread(listener.accept()).start(); } } finally { listener.close(); } } }
f74035304a6856283d034320f7c996b2a6ecc0ae
[ "Java" ]
2
Java
adamaulia/RAI_Task_3
2ed9757ddcb37084daf8414fa7565a4de08ea861
295e63aabe2c8c52eefddb5d0321a05001653ff9
refs/heads/master
<repo_name>luxedo/node-SPOS<file_sep>/spos/blocks.js /* SPOS - Small Payload Object Serializer MIT License Copyright (c) 2020 [<NAME>](<EMAIL>) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ const { utils } = require("./utils.js"); class BlockABC { constructor(blockSpec) { this.input = []; this.required = {}; this.optional = {}; this.initVariables(); this.blockSpec = blockSpec; if ("bits" in blockSpec) this.bits = blockSpec.bits; if ("value" in blockSpec) this.value = blockSpec.value; } initVariables() {} validateBlockSpecKeys(blockSpec) { // Check required settings for (const [key, value] of Object.entries(this.required)) { if (!(key in blockSpec)) throw new ReferenceError(`Block must have key ${key}`); if (!this.validateType(value, blockSpec[key])) throw new RangeError( `Block ${blockSpec.key} key '${key}' has unexpected type.` ); } // Check optional settings Object.entries(this.optional).forEach(([key, value]) => { if (key in blockSpec) this.validateType(value, blockSpec[key]); else { this.blockSpec[key] = value.default; } }); // Check for unexpected keys Object.keys(blockSpec).forEach((key) => { if ( !( Object.keys(this.required).includes(key) || Object.keys(this.optional).includes(key) || ["key", "type", "value", "alias"].includes(key) ) ) throw new ReferenceError( `Block '${blockSpec.key}' has an unexpected key '${key}'.` ); }); } /* Abstract Method*/ initializeBlock(blockSpec) {} validateValue(value) { if (this.validateType(this.input, value)) return true; throw RangeError(`Unexpected type for value ${value}, ${this.input}.`); } validateType(types, value) { types = Array.isArray(types) ? types : [types]; for (let tp of types) { if (tp == null) return true; else if (tp == "boolean" && typeof value == "boolean") return true; else if (tp == "integer" && Number.isInteger(value)) return true; else if (tp == "number" && utils.isNumber(value)) return true; else if (tp == "string" && utils.isString(value)) return true; else if (tp == "bin" && utils.isString(value) && value.match(/^[0-1]+$/)) return true; else if ( tp == "hex" && utils.isString(value) && value.match(/^([0-9a-zA-Z]{2})+$/) ) return true; else if (tp == "array" && Array.isArray(value)) return true; else if (tp == "object" && utils.isObject(value)) return true; else if (tp == "blocklist" && Array.isArray(value)) return true; else if (tp == "blocks" && utils.isObject(value)) return true; } return false; } /* Abstract Method*/ _binEncode(value) {} binEncode(value) { if (this.value) { return this._binEncode(this.value); } this.validateValue(value); return this._binEncode(value); } /* Abstract Method*/ _binDecode(message) {} binDecode(message) { return this._binDecode(message); } consume(message) { let bits = this.accumulateBits(message); let value = this.binDecode(message.slice(0, bits)); return [value, message.slice(bits)]; } accumulateBits(message) { return this.bits; } } class BooleanBlock extends BlockABC { initVariables() { this.input = ["boolean", "integer"]; this.bits = 1; } _binEncode(value) { value = Number.isInteger(value) ? value !== 0 : value; return value === true ? "1" : "0"; } _binDecode(message) { return message === "1"; } } class BinaryBlock extends BlockABC { initVariables() { this.input = ["bin", "hex"]; this.required = { bits: "integer" }; } _binEncode(value) { value = !(value.replace(/[01]/g, "") == "") ? (value = parseInt(value, 16) .toString(2) .padStart(value.length * 4, "0")) : value; return value.padStart(this.bits, "0").slice(0, this.bits); } _binDecode(message) { return message; } } class IntegerBlock extends BlockABC { initVariables() { this.input = ["integer"]; this.required = { bits: "integer" }; this.optional = { offset: { type: "integer", default: 0 }, mode: { type: "string", default: "truncate", choices: ["truncate", "remainder"], }, }; } _binEncode(value) { const overflow = Math.pow(2, this.bits) - 1; value -= this.blockSpec.offset; if (this.blockSpec.mode == "remainder") { value %= Math.pow(2, this.blockSpec.bits); } else { value = Math.min(overflow, Math.max(0, value)); } return value.toString(2).padStart(this.bits, "0"); } _binDecode(message) { return this.blockSpec.offset + parseInt(message, 2); } } class FloatBlock extends BlockABC { initVariables() { this.input = ["number"]; this.required = { bits: "integer" }; this.optional = { lower: { type: "number", default: 0 }, upper: { type: "number", default: 1 }, approximation: { type: "string", default: "round", choices: ["round", "floor", "ceil"], }, }; } _binEncode(value) { const bits = this.bits; const upper = this.blockSpec.upper; const lower = this.blockSpec.lower; const approximation = this.blockSpec.approximation == "ceil" ? Math.ceil : this.blockSpec.approximation == "floor" ? Math.floor : utils.round2Even; const overflow = Math.pow(2, this.bits) - 1; const delta = upper - lower; value = (overflow * (value - lower)) / delta; value = approximation(Math.min(overflow, Math.max(0, value))); return value.toString(2).padStart(this.bits, "0"); } _binDecode(message) { const overflow = Math.pow(2, this.bits) - 1; return ( (parseInt(message, 2) * (this.blockSpec.upper - this.blockSpec.lower)) / overflow + this.blockSpec.lower ); } } class PadBlock extends BlockABC { initVariables() { this.input = [null]; this.required = { bits: "integer" }; } _binEncode(value) { return "".padStart(this.bits, "1"); } _binDecode(message) { return null; } } class ArrayBlock extends BlockABC { initVariables() { this.input = ["array"]; this.required = { length: "integer", blocks: "blocks" }; this.optional = { fixed: { type: "boolean", default: false } }; } initializeBlock(blockSpec) { this.bits = Math.ceil(Math.log2(blockSpec.length + 1)); this.lengthBlock = new Block({ key: "length", type: "integer", bits: this.bits, }); this.itemsBlock = new Block(blockSpec.blocks); } _binEncode(value) { let message = ""; let length; if (this.blockSpec.fixed) { length = this.blockSpec.length; } else { length = value.length > this.blockSpec.length ? this.blockSpec.length : value.length; message += this.lengthBlock.binEncode(length); } message += value .slice(0, length) .reduce((acc, v, idx) => acc + this.itemsBlock.binEncode(v), ""); return message; } _binDecode(message) { let length; if (!this.blockSpec.fixed) { [length, message] = this.lengthBlock.consume(message); } else { length = this.blockSpec.length; } let value = []; for (let i = 0; i < length; i++) { let v; [v, message] = this.itemsBlock.consume(message); value.push(v); } return value; } accumulateBits(message) { let bits = 0; let length, msg; if (!this.blockSpec.fixed) { [length, msg] = this.lengthBlock.consume(message); bits += this.bits; } else { length = this.blockSpec.length; msg = message; } bits += length * this.itemsBlock.accumulateBits(msg); return bits; } } class ObjectBlock extends BlockABC { initVariables() { this.input = ["object"]; this.required = { blocklist: "blocklist" }; } initializeBlock(blockSpec) { this.blocklist = blockSpec.blocklist.map((b_spec) => new Block(b_spec)); } getValue(key, obj) { let ks = key.split("."); if (ks.length > 1) return this.getValue(ks.slice(1).join("."), obj[ks[0]]); return obj[key]; } nestObject(obj) { let newObj = {}; for (const [key, value] of Object.entries(obj)) { let kSplit = key.split("."); let newVal; if (kSplit.length > 1) { let inKey = kSplit[0]; let newKey = kSplit.slice(1).join("."); let nest = {}; nest[newKey] = value; newVal = this.nestObject(nest); newObj[inKey] = this.mergeObj(newObj[inKey] || {}, newVal); } else { if (Array.isArray(value)) { if (utils.isObject(value[0])) newObj[key] = value.map(this.nestObject); else newObj[key] = value; } else if (utils.isObject(value)) { newObj[key] = this.mergeObj(newObj[key] || {}, value); } else { newObj[key] = value; } } } return newObj; } removeNull(obj) { let newObj = {}; for (const [key, val] of Object.entries(obj)) { if (utils.isObject(val)) { newObj[key] = this.removeNull(obj[key]); } else { newObj[key] = val; } if (newObj[key] == null) { delete newObj[key]; } } return newObj; } mergeObj(obj1, obj2) { let merged = JSON.parse(JSON.stringify(obj1)); for (const [key, val] of Object.entries(obj2)) { if (utils.isObject(val)) { merged[key] = this.mergeObj(merged[key] || {}, val); } else { merged[key] = val; } } return merged; } _binEncode(value) { return this.blocklist .map((block) => block.binEncode(this.getValue(block.blockSpec.key, value)) ) .join(""); } _binDecode(message) { let values = {}; for (let block of this.blocklist) { let v; [v, message] = block.consume(message); const alias = "alias" in block.blockSpec ? block.blockSpec.alias : block.blockSpec.key; values[alias] = v; } return this.removeNull(this.nestObject(values)); } accumulateBits(message) { return this.blocklist.reduce( ([bits, message], block) => { let b = block.accumulateBits(message); return [bits + b, message.slice(b)]; }, [0, message] )[0]; } } class StringBlock extends BlockABC { initVariables() { this.input = ["string"]; this.required = { length: "integer" }; this.optional = { custom_alphabeth: { type: "object", default: {} } }; } initializeBlock(blockSpec) { const _b64_alphabeth = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; this.alphabeth = utils.fromEntries( new Map( _b64_alphabeth.split("").map((c, i) => { if (i in blockSpec.custom_alphabeth) return [blockSpec.custom_alphabeth[i], i]; return [c, i]; }) ) ); this.rev_alphabeth = Object.entries(this.alphabeth).reduce( (acc, [key, value]) => { acc[value] = key; return acc; }, {} ); this.letterBlock = new Block({ key: "letter", type: "integer", bits: 6 }); } _binEncode(value) { value = value .padStart(this.blockSpec.length, " ") .substring(0, this.blockSpec.length); return value .split("") .map((char) => char in this.alphabeth ? this.alphabeth[char] : char == " " ? 62 : 63 ) .map((index) => this.letterBlock.binEncode(index)) .join(""); } _binDecode(message) { return new Array(message.length / 6) .fill(0) .map((_, i) => message.substring(6 * i, 6 * (i + 1))) .map((message) => this.letterBlock.binDecode(message)) .map((index) => this.rev_alphabeth[index]) .join(""); } } class StepsBlock extends BlockABC { initVariables() { this.input = "number"; this.required = { steps: "array" }; this.optional = { steps_names: { type: "array", default: [] } }; } initializeBlock(blockSpec) { if (!utils.isSorted(this.blockSpec.steps)) throw RangeError(`Steps Block must be ordered`); this.bits = Math.ceil(Math.log2(this.blockSpec.steps.length + 1)); this.stepsBlock = new Block({ key: "steps", type: "integer", bits: this.bits, offset: 0, }); if (this.blockSpec.steps_names.length == 0) { this.blockSpec.steps_names = [`x<${this.blockSpec.steps[0]}`]; for (let i = 0; i <= this.blockSpec.steps.length - 2; i++) { this.blockSpec.steps_names.push( `${this.blockSpec.steps[i]}<=x<${this.blockSpec.steps[i + 1]}` ); } this.blockSpec.steps_names.push( `x>=${this.blockSpec.steps.slice(-1)[0]}` ); } if (this.blockSpec.steps_names.length != this.blockSpec.steps.length + 1) throw RangeError(`steps_names' has to have length 1 + len(steps)`); this.blockSpec.steps.push(Infinity); } _binEncode(value) { const _value = this.blockSpec.steps.reduce( (acc, cur, idx) => (acc != -1 ? acc : value < cur ? idx : -1), -1 ); return this.stepsBlock.binEncode(_value); } _binDecode(message) { let value = this.stepsBlock.binDecode(message); return this.blockSpec.steps_names[value]; } } class CategoriesBlock extends BlockABC { initVariables() { this.input = "string"; this.required = { categories: "array" }; this.optional = { error: { type: "string", default: null, }, }; } initializeBlock(blockSpec) { let length = this.blockSpec.categories.length; length += !!this.blockSpec.error && !this.blockSpec.categories.includes(this.blockSpec.error) ? 1 : 0; this.bits = Math.ceil(Math.log2(length)); this.categoriesBlock = new Block({ key: "categories", type: "integer", bits: this.bits, offset: 0, }); } _binEncode(value) { let index = this.blockSpec.categories.indexOf(value); if (index == -1) { if (this.blockSpec.categories.includes(this.blockSpec.error)) index = this.blockSpec.categories.indexOf(this.blockSpec.error); else if (!!this.blockSpec.error) index = this.blockSpec.categories.length; else throw RangeError("Invalid value for category."); } return this.categoriesBlock.binEncode(index); } _binDecode(message) { let value = this.categoriesBlock.binDecode(message); return value < this.blockSpec.categories.length ? this.blockSpec.categories[value] : value == this.blockSpec.categories.length && !!this.blockSpec.error ? this.blockSpec.error : "error"; } } class Block { constructor(blockSpec) { this.TYPES = { boolean: BooleanBlock, binary: BinaryBlock, integer: IntegerBlock, float: FloatBlock, pad: PadBlock, array: ArrayBlock, object: ObjectBlock, string: StringBlock, steps: StepsBlock, categories: CategoriesBlock, }; this.blockSpec = JSON.parse(JSON.stringify(blockSpec)); this.validateBlockSpec(this.blockSpec); this.block = new this.TYPES[blockSpec.type](this.blockSpec); this.block.validateBlockSpecKeys(this.blockSpec); this.block.initializeBlock(this.blockSpec); this.binEncode = this.block.binEncode.bind(this.block); this.binDecode = this.block.binDecode.bind(this.block); this.consume = this.block.consume.bind(this.block); this.accumulateBits = this.block.accumulateBits.bind(this.block); } validateBlockSpec(blockSpec) { if (!("key" in blockSpec)) throw new ReferenceError( `Block ${JSON.stringify(blockSpec)} must have 'key'.` ); if (!utils.isString(blockSpec.key)) throw new RangeError(`Block ${blockSpec.key} 'key' must be a string .`); if (!("type" in blockSpec)) throw new ReferenceError(`Block ${blockSpec.key} must have 'type'.`); if (!(blockSpec.type in this.TYPES)) throw new RangeError( `Block ${blockSpec.key} has type: ${ blockSpec.type }, should be one of: ${Object.keys(this.TYPES).join(", ")}.` ); } } module.exports.blocks = { Block, }; <file_sep>/test/test_random.js /* SPOS - Small Payload Object Serializer MIT License Copyright (c) 2020 [<NAME>](<EMAIL>) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* These tests requires the python version of SPOS installed */ const { exec } = require("child_process"); const fs = require("fs"); const path = require("path"); const { assert } = require("chai"); const spos = require("spos"); const { utils } = require("../spos/utils.js"); const DELTA = 0.1; assert.arrayCloseTo = (actual, expected, delta = DELTA, message = "") => { assert.equal(actual.length, expected.length, message); actual.forEach((value, idx) => { if (utils.isObject(actual[idx])) assert.objectCloseTo(actual[idx], expected[idx], delta, message); else if (Array.isArray(actual[idx])) assert.arrayCloseTo(actual[idx], expected[idx], delta, message); else if (utils.isString(actual[idx]) || utils.isBoolean(actual[idx])) assert.equal(actual[idx], expected[idx], message); else assert.closeTo(actual[idx], expected[idx], delta, message); }); }; assert.objectCloseTo = (actual, expected, delta = DELTA, message = "") => { let keysA = Object.keys(actual); let keysE = Object.keys(expected); keysA.sort(); keysE.sort(); assert.deepEqual(keysA, keysE, message); Object.keys(actual).forEach((key) => { if (utils.isObject(actual[key])) assert.objectCloseTo(actual[key], expected[key], delta, message); else if (Array.isArray(actual[key])) assert.arrayCloseTo(actual[key], expected[key], delta, message); else if (utils.isString(actual[key]) || utils.isBoolean(actual[key])) assert.equal(actual[key], expected[key], message); else assert.closeTo(actual[key], expected[key], delta, message); }); }; describe("Random payloads tests", () => { const jsonDir = "test/json/"; const N = 100; fs.readdir(jsonDir, (err, files) => { if (err) console.error(err); files .filter((file) => file.match("spec")) .forEach((file) => { const pSpecFile = path.join(jsonDir, file); it(`Encodes ${pSpecFile} random payloads`, function (done) { this.timeout(20000); for (let i = 0; i < N; i++) { exec(`spos -p ${pSpecFile} -f hex -r`, (error, stdout, stderr) => { if (error || stderr || !stdout) { throw error; } const message = stdout; fs.readFile(pSpecFile, (err, data) => { if (err) throw err; const payloadSpec = JSON.parse(data); exec( `echo ${message}| spos -p ${pSpecFile} -f hex -d -m`, (error, stdout, stderr) => { if (error || stderr || !stdout) { throw error; } const decoded = JSON.parse(stdout); const jsDecoded = spos.decode( message.replace(/^0[xX]/, ""), payloadSpec, "hex" ); assert.objectCloseTo( decoded, jsDecoded, DELTA, "pyDecoded: \n" + JSON.stringify(decoded, null, 2) + "\njsDecoded: \n" + JSON.stringify(jsDecoded, null, 2) ); } ); }); }); } setImmediate(done); }); }); }); }); describe("Random decodeFromSpecs tests", () => { const jsonDir = "test/json/"; const N = 100; fs.readdir(jsonDir, (err, files) => { if (err) console.error(err); files = Object.fromEntries( files .filter((file) => file.match("spec")) .map((file) => { const pSpecFile = path.join(jsonDir, file); return [pSpecFile, JSON.parse(fs.readFileSync(pSpecFile))]; }) ); const payloadSpecs = Object.values(files); new Array(N).fill(0).forEach((n, idx) => { const pSpecFile = choose(Object.keys(files)); it(`Random decodeFromSpecs ${idx}`, function (done) { this.timeout(20000); exec(`spos -p ${pSpecFile} -f hex -r`, (error, stdout, stderr) => { if (error || stderr || !stdout) { throw error; } const message = stdout; exec( `echo ${message}| spos -p ${pSpecFile} -f hex -d -m`, (error, stdout, stderr) => { if (error || stderr || !stdout) { throw error; } const decoded = JSON.parse(stdout); const jsDecoded = spos.decodeFromSpecs( message.replace(/^0[xX]/, ""), payloadSpecs, "hex" ); assert.objectCloseTo( decoded, jsDecoded, DELTA, "pyDecoded: \n" + JSON.stringify(decoded, null, 2) + "\njsDecoded: \n" + JSON.stringify(jsDecoded, null, 2) ); setImmediate(done); } ); }); }); }); }); }); function choose(choices) { var index = Math.floor(Math.random() * choices.length); return choices[index]; } <file_sep>/spos/index.js /* SPOS - Small Payload Object Serializer MIT License Copyright (c) 2020 [<NAME>](<EMAIL>) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ const { blocks } = require("./blocks.js"); const { utils } = require("./utils.js"); /* * Encodes value with the block specification to binary. * @param value The value to encode. * @param {object} block The block specification. * @return {string} A binary string. */ function encodeBlock(value, blockSpec) { return new blocks.Block(blockSpec).binEncode(value); } /* * Decodes binary with the block specification. * @param {string} message The binary message to be decoded. * @param {object} block The block specification. * @return value The value of the message. */ function decodeBlock(value, blockSpec) { return new blocks.Block(blockSpec).binDecode(value); } /* * Validates a payload specification, throwing errors if it is malformed. * @param {payloadSpec} block The block to be validated. * @throws ReferenceError, RangeError */ function validatePayloadSpec(payloadSpec) { if (!("name" in payloadSpec)) throw new ReferenceError(`payloadSpec must have key 'name'.`); if (typeof payloadSpec.name != "string") throw new RangeError(`payloadSpec 'name' must be a string.`); if (!("version" in payloadSpec)) throw new ReferenceError(`payloadSpec must have key 'version'.`); if (!Number.isInteger(payloadSpec.version)) throw new RangeError(`payloadSpec 'version' must be an integer.`); if (!("body" in payloadSpec)) throw new ReferenceError(`payloadSpec must have key 'body'.`); if (!Array.isArray(payloadSpec.body)) throw new RangeError(`payloadSpec 'body' must be an array.`); if ("meta" in payloadSpec) { if (!utils.isObject(payloadSpec.meta)) throw new RangeError(`payloadSpec.meta must be an object.`); if ("crc8" in payloadSpec.meta && typeof payloadSpec.meta.crc8 != "boolean") throw new RangeError(`payloadSpec.meta.crc8 must be boolean.`); if ("header" in payloadSpec.meta) { if (!Array.isArray(payloadSpec.meta.header)) throw new RangeError(`payloadSpec.meta.header must be an array.`); validatePayloadSpec({ name: "header", version: 0, body: payloadSpec.meta.header, }); } let keys = Object.keys(payloadSpec.meta).filter( (key) => ["encode_version", "version_bits", "crc8", "header"].indexOf(key) == -1 ); if (keys.length) throw new RangeError(`Unexpected keys in payloadSpec ${keys}`); } let keys = Object.keys(payloadSpec).filter( (key) => ["name", "body", "version", "meta"].indexOf(key) == -1 ); if (keys.length) throw new RangeError(`Unexpected keys in payloadSpec ${keys}`); } /* * Validates an arrya of payload specifications, throwing errors if any * of them are malformed. Also checks if there are two payloadSpecs with * the same version number and if the names don't match. * @param {payloadSpec} block The block to be validated. * @throws ReferenceError, RangeError */ function validatePayloadSpecs(payloadSpecs) { if (!Array.isArray(payloadSpecs)) throw RangeError("PayloadSpecs expected to be an array."); payloadSpecs.forEach(validatePayloadSpec); let names = new Set(payloadSpecs.map((ps) => ps.name)); let versions = new Set(payloadSpecs.map((ps) => ps.version)); if (names.size > 1) throw RangeError(`Name mismatch in payloadSpecs ${names}`); if (versions.size !== payloadSpecs.length) throw RangeError( `Confliting payloadSpecs versions ${payloadSpecs.map((ps) => ps.version)}` ); } /* * Encodes the payloadData according to payloadSpec. * @param {array} payloadData The object containing the values to be encoded. * @param {object} payloadSpec Payload specifications. * @return {string} message The message as a binary string. */ function binEncode(payloadData, payloadSpec) { validatePayloadSpec(payloadSpec); let meta = payloadSpec.meta || {}; let message = ""; if (meta.encode_version) { message += encodeBlock(payloadSpec.version, { key: "version", type: "integer", bits: meta.version_bits, }); } if (meta.header) { message += new blocks.Block({ key: "header", type: "object", blocklist: meta.header.filter( (blockSpec) => !blockSpec.hasOwnProperty("value") ), }).binEncode(payloadData); } message += new blocks.Block({ key: "payload", type: "object", blocklist: payloadSpec.body, }).binEncode(payloadData); message = message.padEnd(Math.ceil(message.length / 8) * 8, "0"); if (meta.crc8) { message += utils.crc8Encode(message); } return message; } /* * Decodes binary message according to payloadSpec. * @param {string} message The message as a binary string. * @param {object} payloadSpec Payload specifications. * @return {array} payloadData The object containing the decoded values. */ function binDecode(message, payloadSpec) { validatePayloadSpec(payloadSpec); let meta = payloadSpec.meta || {}; let msgMeta = { name: payloadSpec.name, version: payloadSpec.version, message: "0x" + utils.binToHex(message), }; if (meta.crc8) { msgMeta.crc8 = utils.crc8Validate(message); message = message.slice(0, -8); } if (meta.encode_version) { [msgMeta.version, message] = new blocks.Block({ key: "version", type: "integer", bits: meta.version_bits, }).consume(message); if (msgMeta.version != payloadSpec.version) throw RangeError( `Received message version doesn't match. ${payloadSpec.version} != ${msgMeta.version}` ); } if (meta.header) { [msgMeta.header, message] = new blocks.Block({ key: "header", type: "object", blocklist: meta.header.filter((blockSpec) => !("value" in blockSpec)), }).consume(message); msgMeta.header = Object.assign( {}, msgMeta.header, meta.header .filter((blockSpec) => "value" in blockSpec) .reduce((acc, blockSpec) => { acc[blockSpec.key] = blockSpec.value; return acc; }, {}) ); } let payloadData = new blocks.Block({ key: "payload", type: "object", blocklist: payloadSpec.body, }).binDecode(message); return { meta: msgMeta, body: payloadData }; } /* * Encodes the payloadData according to payloadSpec. * @param {array} payloadData The object containing the values to be encoded. * @param {object} payloadSpec Payload specifications. * @param {string} output the output message format (bytes|hex|bin) * @return {Uint8Array|hex string|bin string} message */ function encode(payloadData, payloadSpec, output = "bytes") { let message = binEncode(payloadData, payloadSpec); if (output === "bin") return message; else if (output === "hex") return utils.binToHex(message); else if (output === "bytes") return utils.hexToBytes(utils.binToHex(message)); else throw RangeError( `Invalid output ${output}. Chose from 'bin', 'hex' or 'bytes'` ); } /* * Decodes message according to payloadSpec. * @param {Uint8Array|hex string|bin string} message * @param {object} payloadSpec Payload specifications. * @param {string} input the input message format (bytes|hex|bin) * @return {object} decoded The object containing the decoded values. */ function decode(message, payloadSpec, input = "bytes") { if (input === "bin") return binDecode(message, payloadSpec); else if (input === "hex") return binDecode(utils.hexToBin(message), payloadSpec); else if (input === "bytes") return binDecode(utils.hexToBin(utils.bytesToHex(message)), payloadSpec); else throw RangeError( `Invalid input ${input}. Chose from 'bin', 'hex' or 'bytes'` ); } /* * Decodes message according to one payloadSpec in payloadSpecs. * @param {Uint8Array|hex string|bin string} message * @param {array} payloadSpecs Array of payload specifications. * @param {string} input the input message format (bytes|hex|bin) * @return {object} decoded The object containing the decoded values. */ function decodeFromSpecs(message, payloadSpecs, input = "bytes") { validatePayloadSpecs(payloadSpecs); for (let payloadSpec of payloadSpecs) { try { return decode(message, payloadSpec, input); } catch (err) { // Ignore and try the next payloadSpec } } throw RangeError("Message did not match any version."); } module.exports.encodeBlock = encodeBlock; module.exports.decodeBlock = decodeBlock; module.exports.encode = encode; module.exports.decode = decode; module.exports.decodeFromSpecs = decodeFromSpecs; module.exports.utils = utils; module.exports.validatePayloadSpec = validatePayloadSpec; <file_sep>/README.md # node-SPOS > **SPOS** stands for **Small Payload Object Serializer**. [![codecov](https://codecov.io/gh/luxedo/node-spos/branch/master/graph/badge.svg)](https://codecov.io/gh/luxedo/node-spos) [![CodeFactor](https://www.codefactor.io/repository/github/luxedo/node-spos/badge)](https://www.codefactor.io/repository/github/luxedo/node-spos) [![npm version](https://badge.fury.io/js/spos.svg)](https://badge.fury.io/js/spos) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) > This is and implementation of the `SPOS` specification in `Javascript`. See > HTTPS://github.com/luxedo/SPOS for details. `SPOS` is a tool for serializing simple objects. This tool focuses in maintaining a consistent payload size while sacrificing precision. Applications with limited bandwidth like [LoRa](https://lora-alliance.org/) or [Globalstar](https://www.globalstar.com/en-us/) are ideal candidates for `SPOS`. `SPOS` has implementations for python3 ([SPOS](https://github.com/luxedo/SPOS)) and node.js ([node-SPOS](https://github.com/luxedo/node-SPOS)). > In this document we will be using JSON notation to describe payload > specifications and payload data. For each programming language there's > usually an analogous data type for each notation. Eg: > `object <=> dict`, `array <=> list`, etc. ## Quick Start To encode data, `SPOS` needs two arguments to serialize the data: The `payload_data` to be serialized and the [payload specification](https://github.com/luxedo/SPOS#Payload-specification). ```javascript const spos = require("spos") payload_spec = { name: "example payload", version: 1, body: [{ type: "integer", key: "constant_data", value: 2, // 10 bits: 2 }, { type: "integer", key: "int_data", bits: 6 }, { type: "float", key: "float_data", bits: 6 }] payload_data = { int_data: 13, // 001101 float_data: 0.6 // 010011 (19/32 or 0.59375) // padding 000 } message = spos.binEncode(payload_data, payload_spec, output="bin") "1000110110011000" ``` Decoding data ```javascript const spos = require("spos") const payload_spec = { name: "example payload", version: 1, body: [{ type: "integer", key: "constant_data", value: 2, bits: 2 }, { type: "integer", key: "int_data", bits: 6 }, { type: "float", key: "float_data", bits: 6 }] const message = "1000110110011000" const decoded = spos.decode(message, payload_spec, input="bin") decoded { meta: { name: "example payload", version: 1, }, body: { constant_data: 2, int_data: 13, float_data: 0.59375 } } ``` ## Installation ```bash npm install spos ``` ## Functions ```javascript /* * Encodes the payloadData according to payloadSpec. * @param {array} payloadData The object containing the values to be encoded. * @param {object} payloadSpec Payload specifications. * @param {string} output the output message format (bytes|hex|bin) * @return {Uint8Array|hex string|bin string} message */ function encode(payloadData, payloadSpec, output = "bytes") ``` ```javascript /* * Decodes message according to payloadSpec. * @param {Uint8Array|hex string|bin string} message * @param {object} payloadSpec Payload specifications. * @param {string} input the input message format (bytes|hex|bin) * @return {object} decoded The object containing the decoded values. */ function decode(message, payloadSpec, input = "bytes") ``` ```javascript /* * Decodes message according to one payloadSpec in payloadSpecs. * @param {Uint8Array|hex string|bin string} message * @param {array} payloadSpecs Array of payload specifications. * @param {string} input the input message format (bytes|hex|bin) * @return {object} decoded The object containing the decoded values. */ function decodeFromSpecs(message, payloadSpecs, input = "bytes") ``` ```javascript /* * Validates a payload specification, throwing errors if it is malformed. * @param {payloadSpec} block The block to be validated. * @throws ReferenceError, RangeError */ function validatePayloadSpec(payloadSpec) ``` ## License > MIT License > > Copyright (c) 2020 [<NAME>](<EMAIL>) > > Permission is hereby granted, free of charge, to any person obtaining a copy > of this software and associated documentation files (the "Software"), to deal > in the Software without restriction, including without limitation the rights > to use, copy, modify, merge, publish, distribute, sublicense, and/or sell > copies of the Software, and to permit persons to whom the Software is > furnished to do so, subject to the following conditions: > > The above copyright notice and this permission notice shall be included in all > copies or substantial portions of the Software. > > THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR > IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, > FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE > AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER > LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, > OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE > SOFTWARE.
53979258473eb1b03e372e13587b703251419cc4
[ "JavaScript", "Markdown" ]
4
JavaScript
luxedo/node-SPOS
b54002511509196ae1eb97905fe4defeedbade50
3ad8a0779f5e700987d3fd09e76e9f4a932d59a5
refs/heads/master
<file_sep><?php if ( ! defined( 'ABSPATH' ) ) { exit; } class wf_iupick_woocommerce_shipping_method extends WC_Shipping_Method { private $found_rates; private $services; public function __construct() { $this->id = WF_IUPICK_ID; $this->method_title = __( 'IUPICK', 'wf-shipping-iupick' ); $this->method_description = __( 'Obtains real time shipping waypints.', 'wf-shipping-iupick' ); $this->init(); } private function init() { // Load the settings. $this->init_form_fields(); $this->init_settings(); // Define user set variables $en = $this->get_option( 'enabled' ); $this->enabled = ($en === 'enabled') ? 'yes' : 'no'; $this->cost_rate = $this->get_option( 'cost_rate' ); $this->title = $this->get_option( 'title', $this->method_title ); $this->secret_token = $this->get_option( 'secret_token' ); $this->public_token = $this->get_option( 'public_token' ); $this->secret_token_sandbox = $this->get_option( 'secret_token_sandbox' ); $this->public_token_sandbox = $this->get_option( 'public_token_sandbox' ); $this->sandbox = ( $bool = $this->get_option( 'sandbox' ) ) && $bool == 'yes' ? true : false; $this->debug = ( $bool = $this->get_option( 'debug' ) ) && $bool == 'yes' ? true : false; add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) ); } public function debug( $message, $type = 'notice' ) { if ( $this->debug ) { wc_add_notice( $message, $type ); } } private function environment_check() { /*if ( ! $this->origin && $this->enabled == 'yes' ) { echo '<div class="error"> <p>' . __( 'FedEx is enabled, but the origin postcode has not been set.', 'wf-shipping-iupick' ) . '</p> </div>'; }*/ } public function admin_options() { // Check users environment supports this method $this->environment_check(); // Show settings parent::admin_options(); } public function init_form_fields() { $this->form_fields = include( 'data-wf-settings.php' ); } public function calculate_shipping( $package = array() ) { // Debugging $this->debug( __( 'IUPICK debug mode is on - to hide these messages, turn debug mode off in the settings.', 'wf-shipping-iupick' ) ); $this->add_found_rates(); } public function add_found_rates() { $this->add_rate( array( 'id' => "IUPICK", // ID for the rate. If not passed, this id:instance default will be used. 'label' => $this->title, // Label for the rate 'cost' => $this->cost_rate, // Amount or array of costs (per item shipping) 'taxes' => '', // Pass taxes, or leave empty to have it calculated for you, or 'false' to disable calculations 'calc_tax' => 'per_order', // Calc tax per_order or per_item. Per item needs an array of costs 'meta_data' => array(), // Array of misc meta data to store along with this rate - key value pairs. 'package' => false, // Package array this rate was generated for @since 2.6.0 ) ); } private function wf_load_product( $product ){ if( !$product ){ return false; } return ( WC()->version < '2.7.0' ) ? $product : new wf_product( $product ); } } <file_sep><?php return [ "DF" => "Ciudad de México", "JA" => "Jalisco", "NL" => "Nuevo León", "AG" => "Aguascalientes", "BC" => "Baja California", "BS" => "Baja California Sur", "CM" => "Campeche", "CS" => "Chiapas", "CH" => "Chihuahua", "CO" => "Coahuila", "CL" => "Colima", "DG" => "Durango", "GT" => "Guanajuato", "GR" => "Guerrero", "HG" => "Hidalgo", "MX" => "Estado de México", "MI" => "Michoacán", "MO" => "Morelos", "NA" => "Nayarit", "OA" => "Oaxaca", "PU" => "Puebla", "QT" => "Querétaro", "QR" => "Quintana Roo", "SL" => "San Luis Potosí", "SI" => "Sinaloa", "SO" => "Sonora", "TB" => "Tabasco", "TM" => "Tamaulipas", "TL" => "Tlaxcala", "VE" => "Veracruz", "YU" => "Yucatán", "ZA" => "Zacatecas" ]; <file_sep><?php if ( ! defined( 'ABSPATH' ) ) { exit; } $states = include( 'data-wf-states.php' ); /** * Array of settings */ return array( 'enabled' => array( 'title' => __( 'Enabled IUPICK', 'wf-shipping-iupick' ), 'type' => 'select', 'default' => 'disabled', 'class' => '', 'desc_tip' => true, 'options' => array( 'enabled' => __( 'Enabled iupick', 'wf-shipping-iupick' ), 'override' => __( 'Override flat rate shipping with iupick', 'wf-shipping-iupick' ), 'disabled' => __( 'Disabled', 'wf-shipping-iupick' ), ), ), 'cost_rate' => array( 'title' => __( 'Shipping cost', 'wf-shipping-iupick' ), 'type' => 'number', 'label' => __( 'Cost', 'wf-shipping-iupick' ), 'default' => '0' ), 'title' => array( 'title' => __( 'Method Title', 'wf-shipping-iupick' ), 'type' => 'text', 'description' => __( 'This controls the title which the user sees during checkout.', 'wf-shipping-iupick' ), 'default' => __( 'IUPICK', 'wf-shipping-iupick' ), 'desc_tip' => true ), 'secret_token' => array( 'title' => __( 'IUPICK Secret token', 'wf-shipping-iupick' ), 'type' => 'text', 'description' => __( 'Secret token .', 'wf-shipping-iupick' ), 'default' => '' ), 'public_token' => array( 'title' => __( 'IUPICK Public token', 'wf-shipping-iupick' ), 'type' => 'text', 'description' => __( 'Public token.', 'wf-shipping-iupick' ), 'default' => '' ), 'secret_token_sandbox'=> array( 'title' => __( 'Sandbox IUPICK Secret token', 'wf-shipping-iupick' ), 'type' => 'text', 'description' => __( 'Sandbox Secret token .', 'wf-shipping-iupick' ), 'default' => '' ), 'public_token_sandbox'=> array( 'title' => __( 'Sandbox IUPICK Public token', 'wf-shipping-iupick' ), 'type' => 'text', 'description' => __( 'Sandbox Public token.', 'wf-shipping-iupick' ), 'default' => '' ), 'sandbox' => array( 'title' => __( 'Sandbox', 'wf-shipping-iupick' ), 'label' => __( 'Enable sandbox mode', 'wf-shipping-iupick' ), 'type' => 'checkbox', 'default' => 'no', 'desc_tip' => true, 'description' => __( 'Enable sandbox mode to use sandbox environmnet', 'wf-shipping-iupick' ) ), 'debug' => array( 'title' => __( 'Debug Mode', 'wf-shipping-iupick' ), 'label' => __( 'Enable debug mode', 'wf-shipping-iupick' ), 'type' => 'checkbox', 'default' => 'no', 'desc_tip' => true, 'description' => __( 'Enable debug mode to show debugging information on the cart/checkout.', 'wf-shipping-iupick' ) ), 'maps_api'=> array( 'title' => __( 'Google Maps Api Key', 'wf-shipping-iupick' ), 'type' => 'text', 'description' => __( 'Obtén una API Key de Google <a href="https://developers.google.com/maps/documentation/javascript/get-api-key?hl=ES" target="_blank">aquí</a>', 'wf-shipping-iupick' ), 'default' => 'AIzaSyCaI8tlA-dmA_hf3Y6F6KW5LoYSw8smmuY' ), 'reference' => array( 'title' => __( 'Shop Reference (required)', 'wf-shipping-iupick' ), 'type' => 'text', 'default' => __( 'IUPICK shop reference', 'wf-shipping-iupick' ), 'desc_tip' => true ), 'shipper_name' => array( 'title' => __( 'Shipper name (required)', 'wf-shipping-iupick' ), 'type' => 'text', ), 'shipper_phone' => array( 'title' => __( 'Shipper phone (required)', 'wf-shipping-iupick' ), 'type' => 'text', ), 'shipper_email' => array( 'title' => __( 'Shipper email (required)', 'wf-shipping-iupick' ), 'type' => 'text', ), 'shipper_title' => array( 'title' => __( 'Shipper title', 'wf-shipping-iupick' ), 'type' => 'text', ), 'shipper_company' => array( 'title' => __( 'Shipper company (required)', 'wf-shipping-iupick' ), 'type' => 'text', ), 'shipper_phone_extension' => array( 'title' => __( 'Shipper phone extension ', 'wf-shipping-iupick' ), 'type' => 'text', ), 'shipper_city' => array( 'title' => __( 'Shipper Address city (required)', 'wf-shipping-iupick' ), 'type' => 'text', ), 'shipper_state_code' => array( 'title' => __( 'Shipper Address State (required)', 'wf-shipping-iupick' ), 'type' => 'select', 'options' => $states ), 'shipper_line_one' => array( 'title' => __( 'Shipper Address line one (required)', 'wf-shipping-iupick' ), 'type' => 'text', ), 'shipper_line_two' => array( 'title' => __( 'Shipper Address line two (required)', 'wf-shipping-iupick' ), 'type' => 'text', ), 'shipper_neighborhood' => array( 'title' => __( 'Shipper Address neighborhood (required)', 'wf-shipping-iupick' ), 'type' => 'text', ), 'shipper_postal_code' => array( 'title' => __( 'Shipper Address postal_code (required)', 'wf-shipping-iupick' ), 'type' => 'text', ), );<file_sep><?php /** * Smartpost hubs in array format */ return array( 'dhl' => 'DHL', 'estafeta' => 'Estafeta', 'fedex' => 'FeDex', );<file_sep>jQuery(function(){ jQuery('#create_iupick_shipping').click(function(e){ e.preventDefault(); if( jQuery('#iupick_shipping_vendor').val() === '' || jQuery('#iupick_tracking_number').val() === '' || jQuery('#iupick_length').val() === '' || jQuery('#iupick_width').val() === '' || jQuery('#iupick_height').val() === '' || jQuery('#iupick_weight').val() === '' ){ alert("Debes registrar las medidas, la compañia y el numero de rastreo."); return false; } if( !confirm('¿Estas seguro que deseas registrar el envio?') ){ return false; } var data = { 'action': 'iupick_add_tracking', 'order_id': jQuery('#iupick_order_id').val(), 'nonce': jQuery('#iupick_field_nonce').val(), 'shipping_vendor': jQuery('#iupick_shipping_vendor').val(), 'tracking_number': jQuery('#iupick_tracking_number').val(), 'length': jQuery('#iupick_length').val(), 'width': jQuery('#iupick_width').val(), 'height': jQuery('#iupick_height').val(), 'weight': jQuery('#iupick_weight').val() }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php jQuery.post(ajaxurl, data, function(response) { if( response.status == 'ok' ){ jQuery( '#iupick-packages' ).html( response.html ); alert('Se registro correctamente el envio.'); jQuery('#iupick_shipping_vendor').val(''); jQuery('#iupick_tracking_number').val(''); jQuery('#iupick_length').val(''), jQuery('#iupick_width').val(''), jQuery('#iupick_height').val(''), jQuery('#iupick_weight').val('') }else{ //jQuery( '#iupick-packages' ).html( response.html ); alert('Ocurrio un error al registrar el envio.'); } }, 'json'); }); });<file_sep><?php /* Plugin Name: iupick WooCommerce Extension Plugin URI: https://github.com/javolero/iupick-woocommerce-shipping-method Description: Obtain real time shipping waypoints. Version: 1.0 Author: javolero Author URI: https://github.com/javolero/ Text Domain: wf-shipping-iupick Domain Path: /languages */ if (!defined('WF_IUPICK_ID')){ define("WF_IUPICK_ID", "wf_iupick_woocommerce_shipping"); } if (!defined('WF_IUPICK_VERSION')){ define("WF_IUPICK_VERSION", "1.1.0"); } if (!defined('WF_IUPICK_ADV_DEBUG_MODE')){ define("WF_IUPICK_ADV_DEBUG_MODE", "off"); // Turn 'on' to allow advanced debug mode. } /** * Plugin activation check */ function wf_iupick_plugin_pre_activation_check(){ //TODO: check this - set_transient('wf_iupick_welcome_screen_activation_redirect', true, 30); } register_activation_hook( __FILE__, 'wf_iupick_plugin_pre_activation_check' ); add_action( 'plugins_loaded', 'iupick_load_textdomain' ); function iupick_load_textdomain() { load_plugin_textdomain( 'wf-shipping-iupick' , false, basename( dirname( __FILE__ ) ) . '/languages/' ); } /** * Check if WooCommerce is active */ if (in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) )) { wp_register_script('iupick-js', "https://s3-us-west-1.amazonaws.com/iupick-map/jquery-iupick-map.js", array('jquery'), WF_IUPICK_VERSION , true); //wp_register_script('iupick-js', plugins_url('iupick.js', __FILE__), array('jquery'), WF_IUPICK_VERSION , true); //wp_enqueue_style('iupick-leaflet', 'https://unpkg.com/leaflet@1.2.0/dist/leaflet.css', array(), WF_IUPICK_VERSION ); wp_enqueue_style('iupick-css', 'https://s3-us-west-1.amazonaws.com/iupick-map/iupick-style.css', array(), WF_IUPICK_VERSION ); add_action('admin_enqueue_scripts', 'iupick_admin_js'); if (!function_exists('iupick_admin_js')){ function iupick_admin_js() { wp_enqueue_script('iupick-admin-js', plugins_url('iupick-admin.js', __FILE__), array('jquery'), WF_IUPICK_VERSION , true); } } add_action('woocommerce_after_checkout_validation', 'rei_after_checkout_validation'); if (!function_exists('rei_after_checkout_validation')){ function rei_after_checkout_validation( $posted ) { $shipping_methods = WC()->shipping->get_shipping_methods(); $enabled = $shipping_methods[ WF_IUPICK_ID ]->settings['enabled']; $selected = WC()->session->get( 'chosen_shipping_methods' ); if( $enabled === 'override' || ( !empty( $selected ) && $selected[0] === 'IUPICK' ) ){ if (empty($_POST['wf_iupick_id'])) { wc_add_notice( __( "Waypoint is needed", 'wf-shipping-iupick' ), 'error' ); } } } } add_action( 'woocommerce_checkout_update_order_meta', 'iupick_checkout_field_update_order_meta' ); if( !function_exists( 'iupick_checkout_field_update_order_meta' ) ){ function iupick_checkout_field_update_order_meta( $order_id ) { if ( ! empty( $_POST['wf_iupick_id'] ) ) { update_post_meta( $order_id, 'wf_iupick_id', sanitize_text_field( $_POST['wf_iupick_id'] ) ); //update_post_meta( $order_id, 'wf_iupick_name', sanitize_text_field( $_POST['wf_iupick_name'] ) ); } } } add_action( 'woocommerce_order_details_after_order_table', 'iupick_thankyoupage' ); function iupick_thankyoupage($order){ $wf_iupick_id = get_post_meta( $order->id, 'wf_iupick_id', true ); $wf_iupick_name = $order->get_shipping_company(); if( !empty( $wf_iupick_id ) ){ echo "<h2>" . __('You can pick up your order with your ID and tracking number.', 'wf-shipping-iupick') . "</h2>"; echo "<label>" . __('Waypoint:', 'wf-shipping-iupick') . " </label>"; echo "<span>" . $wf_iupick_name . "</span><br/><br/>"; } } add_action( 'add_meta_boxes', 'mv_add_meta_boxes' ); if ( ! function_exists( 'mv_add_meta_boxes' ) ) { function mv_add_meta_boxes() { add_meta_box( 'mv_other_fields', __('IUPICK','wf-shipping-iupick'), 'mv_add_other_fields_for_packaging', 'shop_order', 'side', 'core' ); } } function wf_iupick_woocommerce_email_order_details( $order, $sent_to_admin, $plain_text ) { if( $order->has_status('completed') ){ $wf_iupick_packages = get_post_meta( $order->ID, 'wf_iupick_packages', false ); if( !empty( $wf_iupick_packages ) ){ if( $plain_text ){ echo __('You can pick up your order with your ID and tracking number.','wf-shipping-iupick'); }else{ echo "<h3>".__('You can pick up your order with your ID and tracking number.','wf-shipping-iupick')."</h3><p>"; } foreach( $wf_iupick_packages as $package ){ $package = explode('|', $package); echo __('Company: ','wf-shipping-iupick'). $package[0] .', ' . __('Tracking number: ','wf-shipping-iupick') .$package[1]; if( $plain_text ){ echo "\n"; }else{ echo "<br/>"; } } if( !$plain_text ){ echo "</p>"; } } } } add_action('woocommerce_email_order_details', 'wf_iupick_woocommerce_email_order_details', 30, 3 ); // Adding Meta field in the meta container admin shop_order pages if ( ! function_exists( 'mv_add_other_fields_for_packaging' ) ) { function mv_add_other_fields_for_packaging() { global $post; $wf_iupick_id = get_post_meta( $post->ID, 'wf_iupick_id', true ) ? get_post_meta( $post->ID, 'wf_iupick_id', true ) : ''; echo '<input type="hidden" id="iupick_order_id" value="' . $post->ID . '">'; echo '<input type="hidden" id="iupick_field_nonce" value="' . wp_create_nonce() . '">'; if( !empty( $wf_iupick_id ) ){ $wf_iupick_packages = get_post_meta( $post->ID, 'wf_iupick_packages', false ); echo "<h2>Packages</h2>"; echo'<ul id="iupick-packages">'; if( !empty( $wf_iupick_packages ) ){ foreach( $wf_iupick_packages as $package ){ $package = explode('|', $package); echo '<li class="iupick-package"><span class="iupick-company">'. $package[0] .'</span> - <span class="iupick-tracking">'.$package[1].'</span> </li>'; } }else{ echo '<li>'.__('No packages found.','wf-shipping-iupick').'</li>'; } echo "</ul>"; echo '<p><label>'.__('Length', 'wf-shipping-iupick').'</label><br/>'; echo '<input type="text" class="input-text" id="iupick_length" placeholder="' . __('Length', 'wf-shipping-iupick') . '">'; echo '</p>'; echo '<p><label>'.__('Width', 'wf-shipping-iupick').'</label><br/>'; echo '<input type="text" class="input-text" id="iupick_width" placeholder="' . __('Width', 'wf-shipping-iupick') . '">'; echo '</p>'; echo '<p><label>'.__('Height', 'wf-shipping-iupick').'</label><br/>'; echo '<input type="text" class="input-text" id="iupick_height" placeholder="' . __('Height', 'wf-shipping-iupick') . '">'; echo '</p>'; echo '<p><label>'.__('Weight', 'wf-shipping-iupick').'</label><br/>'; echo '<input type="text" class="input-text" id="iupick_weight" placeholder="' . __('Weight', 'wf-shipping-iupick') . '">'; echo '</p>'; $wf_iupick_shipping_vendors = include( 'includes/data-wf-shipping-vendors.php' ); echo '<p><label>'.__('Shipping vendor', 'wf-shipping-iupick').'</label><br/>'; echo '<select id="iupick_shipping_vendor">'; echo '<option value="">'. __('None', 'wf-shipping-iupick') . '</option>'; foreach( $wf_iupick_shipping_vendors as $key => $vendor ){ echo '<option value="'. $key .'">'. $vendor . '</option>'; } echo '</select></p>'; echo '<p><label>'.__('Tracking number', 'wf-shipping-iupick').'</label><br/>'; echo '<input type="text" class="input-text" id="iupick_tracking_number" placeholder="' . __('Tracking number', 'wf-shipping-iupick') . '">'; echo '</p>'; echo '<button id="create_iupick_shipping" class="button">'.__('Create IUPICK shipping', 'wf-shipping-iupick').'</button>'; } $est_delivery['fedex_delivery_time'] = date( 'd-m-Y', strtotime("+".$days." days", strtotime($est_delivery['fedex_delivery_time']))); $day = date('D', strtotime($est_delivery['fedex_delivery_time']) ); $est_delivery['fedex_delivery_time'] = date( 'd-m-Y', strtotime("+".$days." days", strtotime($est_delivery['fedex_delivery_time']))); } } // Save the data of the Meta field add_action( 'wp_ajax_iupick_add_tracking', 'wc_order_iupick_fields'); if ( ! function_exists( 'wc_order_iupick_fields' ) ) { function wc_order_iupick_fields( ) { // We need to verify this with the proper authorization (security stuff). // Check if our nonce is set. if ( ! isset( $_POST[ 'nonce' ] ) ) { echo json_encode(array('status' => 'error')); wp_die(); } $nonce = $_REQUEST[ 'nonce' ]; //Verify that the nonce is valid. if ( ! wp_verify_nonce( $nonce ) ) { echo json_encode(array('status' => 'error')); wp_die(); } $post_id = $_POST[ 'order_id' ]; $order = new WC_Order($post_id); $wf_iupick_id = get_post_meta( $post_id, 'wf_iupick_id', true ); $package = implode('|', array( $_POST[ 'shipping_vendor' ], $_POST[ 'tracking_number' ] )); include 'iupick-php/lib/Iupick.php'; include 'iupick-php/lib/Shipment.php'; include 'iupick-php/lib/Waypoints.php'; $states = include( 'includes/data-wf-states.php' ); $shipping_methods = WC()->shipping->get_shipping_methods(); $sandbox = $shipping_methods[ WF_IUPICK_ID ]->settings['sandbox']; if( $sandbox == 'yes' ){ Iupick\Iupick::setSecretToken( $shipping_methods[ WF_IUPICK_ID ]->settings['secret_token_sandbox'] ); Iupick\Iupick::setPublicToken( $shipping_methods[ WF_IUPICK_ID ]->settings['public_token_sandbox'] ); Iupick\Iupick::setEnviroment('sandbox'); }else{ Iupick\Iupick::setSecretToken( $shipping_methods[ WF_IUPICK_ID ]->settings['secret_token'] ); Iupick\Iupick::setPublicToken( $shipping_methods[ WF_IUPICK_ID ]->settings['public_token'] ); Iupick\Iupick::setEnviroment('production'); } $length = $_POST['length']; $width = $_POST['width']; $height = $_POST['height']; $weight = $_POST['weight']; try{ $shipmentToken = Iupick\Shipment::create( intval($length) , intval($width),intval($height),intval($weight)); $shipmentToken = $shipmentToken['shipment_token']; $shipperAddress = Iupick\Iupick::createAddress( $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_city'], $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_line_one'], $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_line_two'], $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_postal_code'], $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_neighborhood'], $states[ $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_state_code'] ], $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_state_code'] ); $shipperContact = Iupick\Iupick::createPerson( $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_name'], $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_phone'], $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_email'], $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_title'], $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_company'], $shipping_methods[ WF_IUPICK_ID ]->settings['shipper_phone_extension'] ); $recipientContact = Iupick\Iupick::createPerson( $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name(), $order->get_billing_phone(), $order->get_billing_email(), '', '', '' ); $data = [ 'shipmentToken' => $shipmentToken, 'waypointId' => intval($wf_iupick_id), 'shipperAddress' => $shipperAddress, 'shipperContact' => $shipperContact, 'recipientContact' => $recipientContact, 'thirdPartyReference' => $shipping_methods[ WF_IUPICK_ID ]->settings['reference'] ]; $addInformation = Iupick\Shipment::addInformation($data); //$waybill = Iupick\Shipment::generateWaybill($shipmentToken); if( isset( $addInformation['error'] ) && !empty( $addInformation['error'] ) ){ echo json_encode(array('status' => 'error', 'error' => $waybill['error'], 'html' => $html )); wp_die(); } add_post_meta( $post_id, 'wf_iupick_addinformation', json_encode( $addInformation ) ); }catch(Exception $ex){ echo json_encode(array('status' => 'error', 'error' => $e->getMessage() )); wp_die(); } add_post_meta( $post_id, 'wf_iupick_packages', $package ); $wf_iupick_packages = get_post_meta( $post_id, 'wf_iupick_packages', false ); $html = ''; if( !empty( $wf_iupick_packages ) ){ foreach( $wf_iupick_packages as $package ){ $package = explode('|', $package); $html.= '<li class="iupick-package"><span class="iupick-company">'. $package[0] .'</span> - <span class="iupick-tracking">'.$package[1].'</span> </li>'; } } echo json_encode(array('status' => 'ok', 'html' => $html)); wp_die(); } } if (!function_exists('wf_get_settings_url')){ function wf_get_settings_url(){ return version_compare(WC()->version, '2.1', '>=') ? "wc-settings" : "woocommerce_settings"; } } if (!function_exists('wf_plugin_override')){ add_action( 'plugins_loaded', 'wf_plugin_override' ); function wf_plugin_override() { if (!function_exists('WC')){ function WC(){ return $GLOBALS['woocommerce']; } } } } if (!function_exists('wf_get_shipping_countries')){ function wf_get_shipping_countries(){ $woocommerce = WC(); $shipping_countries = method_exists($woocommerce->countries, 'get_shipping_countries') ? $woocommerce->countries->get_shipping_countries() : $woocommerce->countries->countries; return $shipping_countries; } } if(!class_exists('wf_iupick_wooCommerce_shipping_setup')){ class wf_iupick_wooCommerce_shipping_setup { public function __construct() { /*add_action('admin_init', array($this,'wf_iupick_welcome')); add_action('admin_menu', array($this,'wf_iupick_welcome_screen')); add_action('admin_head', array($this,'wf_iupick_welcome_screen_remove_menus'));*/ $this->wf_init(); add_action( 'init', array( $this, 'init' ) ); add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'plugin_action_links' ) ); add_action( 'woocommerce_shipping_init', array( $this, 'wf_iupick_wooCommerce_shipping_init' ) ); add_filter( 'woocommerce_shipping_methods', array( $this, 'wf_iupick_wooCommerce_shipping_methods' ) ); add_filter( 'admin_enqueue_scripts', array( $this, 'wf_iupick_scripts' ) ); add_action('woocommerce_before_order_notes', array($this, 'wogmlf_my_custom_checkout_field') ); } /*public function wf_iupick_welcome() { } public function wf_iupick_welcome_screen() { add_dashboard_page('Welcome To Fedex', 'Welcome To Fedex', 'read', 'Fedex-Welcome', array($this,'wf_iupick_screen_content')); } public function wf_iupick_screen_content() { include 'includes/wf_iupick_welcome.php'; } public function wf_iupick_welcome_screen_remove_menus() { remove_submenu_page('index.php', 'Fedex-Welcome'); }*/ public function wogmlf_my_custom_checkout_field( $checkout ) { $shipping_methods = WC()->shipping->get_shipping_methods(); $enabled = $shipping_methods[ WF_IUPICK_ID ]->settings['enabled']; $secret_token = $shipping_methods[ WF_IUPICK_ID ]->settings['secret_token']; $public_token = $shipping_methods[ WF_IUPICK_ID ]->settings['public_token']; $is_sandbox = 'false'; if( $shipping_methods[ WF_IUPICK_ID ]->settings['sandbox'] === 'yes' ){ $secret_token = $shipping_methods[ WF_IUPICK_ID ]->settings['secret_token_sandbox']; $public_token = $shipping_methods[ WF_IUPICK_ID ]->settings['public_token_sandbox']; $is_sandbox = 'true'; } $maps_api = $shipping_methods[ WF_IUPICK_ID ]->settings['maps_api']; if ( is_checkout() ) { //wp_enqueue_script('iupick-markercluster'); wp_enqueue_script('iupick-js'); } ?> <div id="woocommerce-iupick"> <?php woocommerce_form_field( 'wf_iupick_id', array( 'type' => 'text', 'label' => __('Waypoint ID', 'wf-shipping-iupick'), 'required' => true, 'class' => array('my-field-class orm-row-wide'), ), $checkout->get_value( 'wf_iupick_id' )); ?> <a href="#" class="btn-select-waypoint button"><?= __('Select one waypoint on the map', 'wf-shipping-iupick') ?></a> <script type="text/javascript"> var iupick_object = null; var iupick_disable_autoload = true; var iupickButton; function initIupickMap(){ iupickButton.initMap(); } jQuery(function(){ iupickButton = jQuery('.btn-select-waypoint').iupickmap({ google_maps_api_key: '<?= $maps_api ?>', iupick_token: 'Token <?= $<PASSWORD> ?>', input_box_placeholder: '<?= __('Escribe tu dirección o CP', 'wf-shipping-iupick') ?>', callback_function: selectedWaypoint, is_sandbox: <?= $is_sandbox ?> }); }); var iupick_moved = false; var use_iupick = false; var enabled_all = <?= ($enabled === 'override')?'true':'false' ?>; jQuery( document ).on( 'updated_checkout', function() { if( enabled_all || jQuery('.shipping_method:checked').val() === 'IUPICK' || jQuery('input#shipping_method_0').val() === 'IUPICK' ){ jQuery( '#woocommerce-iupick' ).show(); if( !iupick_moved ){ jQuery( '#woocommerce-iupick' ).insertBefore('.woocommerce-shipping-fields'); iupick_moved = true; } }else{ jQuery( '#woocommerce-iupick' ).hide(); } } ); jQuery('body').on('change', '.shipping_method', function(){ if( jQuery('.shipping_method:checked').val() === 'IUPICK' ){ iupick_object = null; jQuery('.btn-select-waypoint').click(); } }); function selectedWaypoint(waypoint) { //console.log('Selected Waypoint:', waypoint); iupick_object = waypoint; if( iupick_object == null ){ alert('<?= __('You need select a waypoint on the map', 'wf-shipping-iupick') ?>'); return; } if( confirm( '<?= __('Select this waypoint override your previous shipping address, continue?', 'wf-shipping-iupick') ?>' ) ){ console.log(iupick_object); jQuery('#wf_iupick_id').val( iupick_object.id ); jQuery('#shipping_company').val( "Ocurre: " + iupick_object.entity + ' ' + iupick_object.name ); jQuery('#shipping_address_1').val( iupick_object.address.line_one ); jQuery('#shipping_address_2').val( iupick_object.address.line_two ); jQuery('#shipping_postcode').val( iupick_object.address.postal_code.code ); jQuery('#shipping_city').val( iupick_object.address.city ); jQuery('#shipping_state').val( iupick_object.address.postal_code.state.code ); jQuery('#shipping_state').change(); jQuery('#ship-to-different-address-checkbox').prop('checked', true).change(); } } jQuery(function(){ jQuery('#wf_iupick_id_field').attr('readonly', true ); }) </script> <style> /*#woocommerce-iupick{ display: none; }*/ #wf_iupick_id_field{ display: none; } .waypoint-text{ width: 100%; display: block; } </style> </div> <?php } public function init(){ if ( ! class_exists( 'wf_order' ) ) { include_once 'includes/class-wf-legacy.php'; } } public function wf_init() { // Localisation } public function wf_iupick_scripts() { wp_enqueue_script( 'jquery-ui-sortable' ); } public function plugin_action_links( $links ) { $plugin_links = array( '<a href="' . admin_url( 'admin.php?page=' . wf_get_settings_url() . '&tab=shipping&section=wf_iupick_woocommerce_shipping_method' ) . '">' . __( 'Settings', 'wf-shipping-iupick' ) . '</a>', ); return array_merge( $plugin_links, $links ); } public function wf_iupick_wooCommerce_shipping_init() { include_once( 'includes/class-wf-iupick-woocommerce-shipping.php' ); } public function wf_iupick_wooCommerce_shipping_methods( $methods ) { $methods[] = 'wf_iupick_woocommerce_shipping_method'; return $methods; } } new wf_iupick_wooCommerce_shipping_setup(); } }
7e1ee6313a143d35762d924de01f9702559f2ea8
[ "JavaScript", "PHP" ]
6
PHP
javolero/iupick-woocommerce-shipping-method
df210d133110970d9f2d4ca9ff4b899b1ce99e68
0e9dcc864a57b92bf60a56390db71f178de3055b
refs/heads/master
<repo_name>AdityaSub/FEM_2D_Heat_Steady<file_sep>/README.md # FEM_2D_Heat_Steady 2D finite-element solver for steady-state heat transfer; uses linear basis functions but the code is written to be easily modularizable; currently supports square and circular domains, but this can be extended to arbitrary geometries by modifying Dirichlet conditions in 'Mesh.cpp'; the solver uses 'eigen' and 'PETSc' libraries; this code is meant to serve as an instructional example only <file_sep>/src/main.cpp // main.cpp // Solve a 2D heat-conduction problem with Dirichlet boundary conditions (u = 1 on top face, u = 0 on sides and bottom face) #include<iostream> #include<vector> #include<string> #include "Mesh.h" using namespace std; static char help[] = "Solves 2D Poisson's equation with KSP.\n\n"; int main(int argc, char* argv[]) { PetscInitialize(&argc,&argv,(char*)0,help); string fileName = argv[1]; Mesh m(fileName); m.Assemble(); m.writeField("initial"); m.Solve(); m.writeField("solution"); m.computeL2Error(); } <file_sep>/include/Mesh.h #pragma once #include<vector> #include<string> #include<Eigen/Dense> #include "Element.h" #include<petscksp.h> class Mesh { public: Mesh(std::string&); // constructor void readMesh(); // read mesh-data from file const std::vector<Element>& getGrid() const; // return reference to grid void Assemble(); // assemble linear system void Solve(); // solve linear system for unknowns void writeField(const std::string&); // write solution-field to file void computeL2Error(); // calculate L2 error ~Mesh(); // destructor private: std::string meshFileName; // input mesh-filename std::vector <std::vector<double>> nodes; // node-list for grid std::vector <std::vector<int>> elements; // connectivities std::vector<Element> mesh; // grid-vector containing list of elements //std::vector<std::vector<double>> globalStiffness; // global stiffness matrix for grid //std::vector<double> globalForce; // global force vector Eigen::VectorXd x_sol; // solution-vector double x_min = 0.0, y_min = 0.0, x_max = 0.0, y_max = 0.0; // mesh bounds Vec x, b; Mat A; KSP ksp; PC pc; PetscErrorCode ierr; PetscInt its; }; <file_sep>/src/Mesh.cpp #include<iostream> #include<iomanip> #include<vector> #include<fstream> #include<Eigen/Dense> #include<Eigen/Eigenvalues> #include<math.h> #include<cmath> #include "Mesh.h" #define PI 3.14159265358979323846 using namespace std; using namespace Eigen; // constructor Mesh::Mesh(string& fileName) : meshFileName(fileName) { readMesh(); for (size_t i = 0; i < static_cast<size_t>(elements.size()); i++) { const Node n1(elements[i][0], nodes[elements[i][0]][0], nodes[elements[i][0]][1]); const Node n2(elements[i][1], nodes[elements[i][1]][0], nodes[elements[i][1]][1]); const Node n3(elements[i][2], nodes[elements[i][2]][0], nodes[elements[i][2]][1]); mesh.push_back(Element(n1, n2, n3, i)); } cout << "Grid generated! Bounds: x_min = " << x_min << ", y_min = " << y_min << ", x_max = " << x_max << ", y_max = " << y_max << ", nodes = " << nodes.size() << ", elements = " << elements.size() << endl; } // read mesh-data from file void Mesh::readMesh() { ifstream mesh_read; mesh_read.open(meshFileName); // read node coordinates int n_nodes, n_dim; // number of nodes, number of dimensions mesh_read >> n_nodes >> n_dim; nodes.resize(n_nodes); for (int i = 0; i < n_nodes; i++) { nodes[i].resize(n_dim); } for (int i = 0; i < n_nodes; i++) { for (int j = 0; j < n_dim; j++) { mesh_read >> nodes[i][j]; } } // read connectivities int n_elems, n_nodes_per_elem; mesh_read >> n_elems >> n_nodes_per_elem; // number of elements, number of nodes per element elements.resize(n_elems); for (int i = 0; i < n_elems; i++) { elements[i].resize(n_nodes_per_elem); } for (int i = 0; i < n_elems; i++) { for (int j = 0; j < n_nodes_per_elem; j++) { mesh_read >> elements[i][j]; elements[i][j] -= 1; // '0' - indexing } } mesh_read.close(); for (int i = 0; i < n_nodes; i++) { if (x_max < nodes[i][0]) x_max = nodes[i][0]; if (x_min > nodes[i][0]) x_min = nodes[i][0]; if (y_max < nodes[i][1]) y_max = nodes[i][1]; if (y_min > nodes[i][1]) y_min = nodes[i][1]; } } // return reference to grid const vector<Element>& Mesh::getGrid() const { return mesh; } // assemble global stiffness matrix void Mesh::Assemble() { double num_elems = elements.size(); // initialize global stiffness matrix /*globalStiffness.resize(nodes.size()); for (int i = 0; i < nodes.size(); i++) { globalStiffness[i].resize(nodes.size()); for (vector<double>::iterator it = globalStiffness[i].begin(); it != globalStiffness[i].end(); it++) *it = 0.0; } globalForce.resize(nodes.size()); //x.resize(nodes.size()); for (int i = 0; i < nodes.size(); i++) { globalForce[i] = 0.0; x(i) = 0.0; }*/ cout << "global stiffness matrix, global force-vector, solution-vector initialized!" << endl; vector<int> nodeIDs; nodeIDs.resize(3); array<array<double, 2>, 3> elemCoords; double factor = 1/3.0; array<double, 3> gauss_pt_weights = { factor, factor, factor }; Matrix<double, 3, 2> gauss_pts; gauss_pts << 0.5, 0.0, 0.0, 0.5, 0.5, 0.5; array<double, 3> basis_values; double x_query = 0.0; double y_query = 0.0; PetscInt indices1M[3]; PetscScalar zero = 0.0, one = 1.0, force_calc, Dirichlet_value; PetscReal norm, tol = 1.e-14; ierr = MatCreate(PETSC_COMM_WORLD,&A); ierr = MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,nodes.size(),nodes.size()); ierr = MatSetUp(A); ierr = MatZeroEntries(A); ierr = VecCreate(PETSC_COMM_WORLD,&x); ierr = VecSetSizes(x,PETSC_DECIDE,nodes.size()); ierr = VecSetFromOptions(x); ierr = VecSet(x,zero); ierr = VecCreate(PETSC_COMM_WORLD,&b); ierr = VecSetSizes(b,PETSC_DECIDE,nodes.size()); ierr = VecSetFromOptions(b); ierr = KSPCreate(PETSC_COMM_WORLD,&ksp); ierr = KSPSetOperators(ksp,A,A); ierr = KSPGetPC(ksp,&pc); ierr = PCSetType(pc,PCJACOBI); ierr = KSPSetTolerances(ksp,1.e-5,PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT); ierr = KSPSetFromOptions(ksp); // loop through elements and add up contributions (except at Dirichlet boundary nodes) for (vector<Element>::iterator it = mesh.begin(); it != mesh.end(); it++) { //cout << endl; int elemID = it->getElemID(); nodeIDs[0] = it->getNode1().getID(); nodeIDs[1] = it->getNode2().getID(); nodeIDs[2] = it->getNode3().getID(); elemCoords[0] = it->getNode1().getCoord(); elemCoords[1] = it->getNode2().getCoord(); elemCoords[2] = it->getNode3().getCoord(); //cout << "elemID: " << elemID << "n1 n2 n3 " << nodeIDs[0] << " " << nodeIDs[1] << " " << nodeIDs[2] << endl; //cout << "elemID: " << elemID << " c1: (" << elemCoords[0][0] << ", " << elemCoords[0][1] << ")" << " c2: (" << elemCoords[1][0] << ", " << elemCoords[1][1] << ")" << " c3: (" << elemCoords[2][0] << ", " << elemCoords[2][1] << ")" << endl; it->calcElementStiffness(); //it->printElemStiffness(); const array<array<double, 3>, 3> elemStiffness = it->getElemStiffness(); for (int i = 0; i < 3; i++) { ierr = MatAssemblyBegin(A,MAT_FLUSH_ASSEMBLY); ierr = MatAssemblyEnd(A,MAT_FLUSH_ASSEMBLY); if ((elemCoords[i][0] == x_min) || (elemCoords[i][0] == x_max) || (elemCoords[i][1] == y_min) || (elemCoords[i][1] == y_max)) { // left, right, bottom, top boundaries //if ((elemCoords[i][0] == x_min) || (elemCoords[i][0] == x_max) || (elemCoords[i][1] == y_min)) { // left, right, bottom boundaries //if (std::abs(sqrt(pow(elemCoords[i][0], 2.0) + pow(elemCoords[i][1], 2.0)) - 1.0) < 1e-3) { //globalStiffness[nodeIDs[i]][nodeIDs[i]] = 1.0; //globalForce[nodeIDs[i]] = 0.0; ierr = MatSetValues(A,1,&nodeIDs[i],1,&nodeIDs[i],&one,INSERT_VALUES); /* if ((elemCoords[i][0] > 0) && (elemCoords[i][1] >= 0)) { Dirichlet_value = sin(3*atan((elemCoords[i][1])/elemCoords[i][0])); } else if ((elemCoords[i][0] < 0) && (elemCoords[i][1] >= 0)) { Dirichlet_value = sin(3*(PI - atan((elemCoords[i][1])/std::abs(elemCoords[i][0])))); } else if ((elemCoords[i][0] < 0) && (elemCoords[i][1] <= 0)) { Dirichlet_value = sin(3*(PI + atan(std::abs((elemCoords[i][1])/elemCoords[i][0])))); } else if ((elemCoords[i][0] > 0) && (elemCoords[i][1] <= 0)) { Dirichlet_value = sin(3*(2*PI - atan(std::abs(elemCoords[i][1])/elemCoords[i][0]))); } else if ((elemCoords[i][0] == 0) && (elemCoords[i][1] >= 0)) { Dirichlet_value = sin(3*PI/2); } else if ((elemCoords[i][0] == 0) && (elemCoords[i][1] < 0)) { Dirichlet_value = sin(9*PI/2); }*/ ierr = VecSetValues(b,1,&nodeIDs[i],&zero,INSERT_VALUES); /*ierr = VecSetValues(b,1,&nodeIDs[i],&Dirichlet_value,INSERT_VALUES); }*/ /*else if (std::abs(sqrt(pow(elemCoords[i][0], 2.0) + pow(elemCoords[i][1], 2.0)) - 0.2) < 1e-3) { Dirichlet_value = 2.0; ierr = MatSetValues(A,1,&nodeIDs[i],1,&nodeIDs[i],&one,INSERT_VALUES); ierr = VecSetValues(b,1,&nodeIDs[i],&Dirichlet_value,INSERT_VALUES); }*/ /*else if (elemCoords[i][1] == y_max) { // top boundary //globalStiffness[nodeIDs[i]][nodeIDs[i]] = 1.0; //globalForce[nodeIDs[i]] = 1.0; ierr = MatSetValues(A,1,&nodeIDs[i],1,&nodeIDs[i],&one,INSERT_VALUES); ierr = VecSetValues(b,1,&nodeIDs[i],&one,INSERT_VALUES); }*/ } else { ierr = MatAssemblyBegin(A,MAT_FLUSH_ASSEMBLY); ierr = MatAssemblyEnd(A,MAT_FLUSH_ASSEMBLY); for (int j = 0; j < 3; j++) { //globalStiffness[nodeIDs[i]][nodeIDs[j]] += elemStiffness[i][j]; ierr = MatSetValues(A,1,&nodeIDs[i],1,&nodeIDs[j],&elemStiffness[i][j],ADD_VALUES); //cout << "Ag for " << nodeIDs[i] << ", " << nodeIDs[j] << ": " << globalStiffness[nodeIDs[i]][nodeIDs[j]] << endl; } //globalForce[nodeIDs[i]] = 0.0; //ierr = VecSetValues(b,1,&nodeIDs[i],&zero,INSERT_VALUES); for (int k = 0; k < gauss_pts.rows(); k++) { basis_values = it->getBasis().calcBasis(gauss_pts(k, 0), gauss_pts(k, 1)); //globalForce[nodeIDs[i]] += (-0.5) * gauss_pt_weights[k] * basis_values[i] * it->getBasis().getDetJ(); x_query = 0.0; y_query = 0.0; for (int l = 0; l < basis_values.size(); l++) { x_query += basis_values[l] * elemCoords[l][0]; y_query += basis_values[l] * elemCoords[l][1]; } //cout << "elemID: " << elemID << " gp" << k << ": (" << x_query << ", " << y_query << ")" << endl; //globalForce[nodeIDs[i]] += 0.5 * gauss_pt_weights[k] * basis_values[i] * (-2) * pow(PI, 2.0) * sin(PI * x_query) * sin(PI * y_query) * it->getBasis().getDetJ(); force_calc = 0.5 * gauss_pt_weights[k] * basis_values[i] * (-2) * pow(PI, 2.0) * sin(PI * x_query) * sin(PI * y_query) * it->getBasis().getDetJ(); ierr = VecSetValues(b,1,&nodeIDs[i],&force_calc,ADD_VALUES); } } } } ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY); ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY); //ierr = MatView(A,PETSC_VIEWER_STDOUT_SELF); ierr = VecAssemblyBegin(b); ierr = VecAssemblyEnd(b); //ierr = VecView(b,PETSC_VIEWER_STDOUT_SELF); } void Mesh::Solve() { /*MatrixXd matGlobalSti(globalStiffness.size(), globalStiffness[0].size()); VectorXd vecGlobalFor = Map<VectorXd, Unaligned>(globalForce.data(), globalForce.size()); for (int i = 0; i < nodes.size(); i++) { matGlobalSti.row(i) = VectorXd::Map(&globalStiffness[i][0], globalStiffness[i].size()); } //cout << matGlobalSti << endl; //cout << vecGlobalFor << endl; cout << "Solving..."; x = matGlobalSti.householderQr().solve(vecGlobalFor); //x = matGlobalSti.lu().solve(vecGlobalFor); double relative_error = (matGlobalSti*x - vecGlobalFor).norm() / vecGlobalFor.norm(); // relative error cout << "done! Relative error = " << relative_error << endl;*/ //cout << x << endl; ierr = KSPSetFromOptions(ksp); ierr = KSPSolve(ksp,b,x); ierr = KSPView(ksp,PETSC_VIEWER_STDOUT_WORLD); ierr = KSPGetIterationNumber(ksp,&its); } void Mesh::writeField(const string& solName) { ofstream outFile; stringstream ss; ss << solName << ".plt"; outFile.open(ss.str()); outFile << "TITLE = \"SOLUTION_FIELD\"" << endl; outFile << "VARIABLES = \"x\" \"y\" \"T\"" << endl; outFile << "ZONE N=" << nodes.size() << ", E=" << elements.size() << ", F=FEPOINT, ET=TRIANGLE" << endl; x_sol.resize(nodes.size()); for (int i=0; i<nodes.size(); i++) { VecGetValues(x,1,&i,&x_sol(i)); outFile << setprecision(6) << nodes[i][0] << "\t" << setprecision(6) << nodes[i][1] << "\t" << setprecision(6) << x_sol(i) << endl; } for (int i=0; i<elements.size(); i++) { outFile << elements[i][0] + 1 << "\t" << elements[i][1] + 1 << "\t" << elements[i][2] + 1 << endl; } outFile.close(); } void Mesh::computeL2Error() { vector<int> nodeIDs; nodeIDs.resize(3); array<array<double, 2>, 3> elemCoords; double factor = 1/3.0; array<double, 3> gauss_pt_weights = { factor, factor, factor }; Matrix<double, 3, 2> gauss_pts; gauss_pts << 0.5, 0.0, 0.0, 0.5, 0.5, 0.5; array<double, 3> basis_values; array<double, 3> elem_dofs; double x_query = 0.0, y_query = 0.0, dof_val = 0.0; double L2_error = 0.0; for (vector<Element>::iterator it = mesh.begin(); it != mesh.end(); it++) { nodeIDs[0] = it->getNode1().getID(); nodeIDs[1] = it->getNode2().getID(); nodeIDs[2] = it->getNode3().getID(); elemCoords[0] = it->getNode1().getCoord(); elemCoords[1] = it->getNode2().getCoord(); elemCoords[2] = it->getNode3().getCoord(); elem_dofs[0] = x_sol(nodeIDs[0]); elem_dofs[1] = x_sol(nodeIDs[1]); elem_dofs[2] = x_sol(nodeIDs[2]); for (int k = 0; k < gauss_pts.rows(); k++) { basis_values = it->getBasis().calcBasis(gauss_pts(k, 0), gauss_pts(k, 1)); x_query = 0.0; y_query = 0.0; dof_val = 0.0; for (int l = 0; l < basis_values.size(); l++) { x_query += basis_values[l] * elemCoords[l][0]; y_query += basis_values[l] * elemCoords[l][1]; dof_val += basis_values[l] * elem_dofs[l]; } L2_error += 0.5 * gauss_pt_weights[k] * pow(dof_val - sin(PI * x_query) * sin(PI * y_query), 2.0) * it->getBasis().getDetJ(); } } L2_error = sqrt(L2_error); cout << "L2 error: " << L2_error << endl; } // destructor Mesh::~Mesh() { ierr = MatDestroy(&A); ierr = VecDestroy(&x); ierr = VecDestroy(&b); ierr = KSPDestroy(&ksp); ierr = PetscFinalize(); cout << "Grid destroyed!" << endl; }
5e100bd939046c0273adcbae7a2cb893d9fd01ab
[ "Markdown", "C++" ]
4
Markdown
AdityaSub/FEM_2D_Heat_Steady
9aa29fcd6b408fd67a61d8d88202032439917fb6
8b70a64d45aa99fb1ebfd2818565c6242d98fd4a
refs/heads/master
<file_sep># DMHotelsFoundation - This is a sample framework to test framework based modularization. Para que todo funcione correctamente, debes ejecutar la siguiente línea pod install <file_sep>workspace '../DMWorkspace/DMHotels.xcworkspace' xcodeproj 'DMHotelsFoundation.xcodeproj' pod 'DeepLinkKit'
48a808c883d015be1711a0b4a55950e0b8f21c5b
[ "Markdown", "Ruby" ]
2
Markdown
smatias1989/DMHotelsFoundation
59052707dea21c2ce86cb157ea96ad871aaa7d9c
33965c40693014c868bff53c2c37775860bf50fb
refs/heads/master
<file_sep>#ifndef UTILS_H #define UTILS_H #include <sqlite3.h> #include <r_core.h> typedef struct wkr_mapping_t { char* name; ut64 from; ut64 to; } wkr_mapping; typedef struct wkr_hitcount_t { ut64 address; ut64 count; } wkr_hitcount; typedef struct wkr_db_t { sqlite3* handle; bool pie; ut64 exec_off; ut64 map_low; ut64 map_high; } wkr_db; typedef enum wkr_err_t { WKR_OK, WKR_FORMAT, WKR_PROG, WKR_SQLITE } wkr_err; wkr_err wkr_db_open(wkr_db* db, RCore* core, const char* filename); wkr_err wkr_db_close(wkr_db* db); const char* wkr_db_errmsg(wkr_db* db, wkr_err err); wkr_err wkr_db_branchcount(wkr_db* db, int* count); wkr_err wkr_db_mapcount(wkr_db* db, int* count); wkr_err wkr_db_hitcount(wkr_db* db, int* count); wkr_err wkr_db_mappings(wkr_db* db, RList** res); // RList<wkr_mapping> wkr_err wkr_db_bbs(wkr_db* db, RList** res); // RList<wkr_hitcount> wkr_err wkr_db_xrefs(wkr_db* db, ut64 address, RList** res); // RList<wkr_hitcount> ut64 wkr_db_frompie(wkr_db* db, ut64 address); ut64 wkr_db_topie(wkr_db* db, ut64 address); #endif <file_sep># r2wakare r2wakare is a radare2 plugin able to load trace databases generated by wakare-converter. - Wakare project: https://github.com/lse/wakare ## Installation You will need to go into the ```plugins/r2wakare``` folder of this repository and build the plugin. To build and install the plugin you must use r2pm: ``` r2pm -i r2wakare ``` or build locally ``` $ r2pm -r make && r2pm -r make install ``` ## Features - Basic block listing - Basic block hitcount comments (hard to do bb highlighting in cli) - Basic block diffing (Difference / Intersection) - Branch target resolution (\wkrx) - Supports PIE executables/traces ## Requirements - make - r2pm - sqlite3 ## Usage ``` [0x00001040]> \wkr Wakare plugin: \wkro [file] : Open a trace database \wkri : Displays information about the loaded database \wkrx : Displays the xrefs from the current address \wkrbl : Displays the list of basic blocks \wkrbh : Adds hitcounts in basic blocks comments \wkrbc : Cleans the hitcount comments \wkrdd [file] : Does a difference based diffing with another trace \wkrdi [file] : Does an intersection based diffing with another trace \wkrdr : Resets the database to its original state ``` ## Example ### Getting basic block list ``` $ r2 prog.pie -- Most likely your core dump fell into a blackhole, can't see it. [0x00001050]> aa [x] Analyze all flags starting with sym. and entry0 (aa) [0x00001050]> \wkro trace_pie.db [0x00001050]> \wkrbl 0x1190: 6 main 0x11c2: 6 main 0x1341: 6 main 0x134c: 6 main 0x12ec: 2 main 0x1020: 2 0x1040: 2 sym.imp.strtoul 0x1080: 1 sym.deregister_tm_clones 0x10a8: 1 sym.deregister_tm_clones 0x10b0: 1 sym.register_tm_clones 0x10e8: 1 sym.register_tm_clones 0x10fd: 1 entry.fini0 0x110b: 1 entry.fini0 0x1118: 1 entry.fini0 0x1140: 1 entry.init0 0x116e: 1 main 0x118a: 1 main 0x1000: 1 sym._init 0x1030: 1 sym.imp.printf 0x11e4: 1 main 0x123c: 1 main 0x1294: 1 main 0x1036: 1 0x1310: 1 main 0x133e: 1 main 0x1340: 1 main 0x1016: 1 sym._init 0x1046: 1 0x1360: 1 main 0x1370: 1 sym.__libc_csu_init 0x13a7: 1 sym.__libc_csu_init 0x13c6: 1 sym.__libc_csu_init [0x00001050]> ``` ### Getting xrefs from an instruction ``` $ r2 prog.pie -- Dissasemble? No dissasemble, no dissassemble!!!!! [0x00001050]> aa [x] Analyze all flags starting with sym. and entry0 (aa) [0x00001050]> \wkro trace_pie.db [0x00001050]> \wkrx @ 0x000011e2 --- Found 5 xrefs from 0x11e2 --- 0x12ec: 2 main 0x11e4: 1 main 0x123c: 1 main 0x1294: 1 main 0x1310: 1 main [0x00001050]> ``` ## Screenshot ![VM main screen](assets/r2-screen-global.png) <file_sep>#include <string.h> #include <r_core.h> #include "utils.h" static void wkr_mapping_free(void* obj) { wkr_mapping* wobj = (wkr_mapping*)obj; free(wobj->name); free(wobj); } static wkr_err sql_count_rows(sqlite3* handle, const char* column_name, int* count) { sqlite3_stmt* query = NULL; char* buff = r_str_newf("SELECT COUNT(*) FROM %s;", column_name); if(sqlite3_prepare_v2(handle, buff, -1, &query, 0) != SQLITE_OK) { free(buff); return WKR_SQLITE; } if(sqlite3_step(query) != SQLITE_ROW) { free(buff); sqlite3_finalize(query); return WKR_SQLITE; } *count = sqlite3_column_int(query, 0); sqlite3_finalize(query); free(buff); return WKR_OK; } wkr_err wkr_db_open(wkr_db* db, RCore* core, const char* filename) { memset(db, 0, sizeof(wkr_db)); // Opening the db if(sqlite3_open_v2(filename, &db->handle, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) { return WKR_SQLITE; } int count = 0; // Sanity checking (making sure the required sections are present) if(sql_count_rows(db->handle, "branches", &count) != WKR_OK || sql_count_rows(db->handle, "hitcounts", &count) != WKR_OK || sql_count_rows(db->handle, "mappings", &count) != WKR_OK) { return WKR_FORMAT; } // Checking if the executable is in the trace wkr_err err; bool is_present = false; RList* mappings = NULL; RListIter* it = NULL; wkr_mapping* map = NULL; const char* file_basename = r_file_basename(core->bin->file); if((err = wkr_db_mappings(db, &mappings)) != WKR_OK) { return err; } r_list_foreach(mappings, it, map) { if(r_str_endswith(map->name, file_basename)) { is_present = true; db->map_low = map->from; db->map_high = map->to; } } r_list_free(mappings); if(!is_present) { return WKR_PROG; } // Now checking for PIE (setting up address translation) db->pie = r_bin_get_baddr(core->bin) == 0; if(db->pie) { RBinSection* section; r_list_foreach(r_bin_get_sections(core->bin), it, section) { if(section->is_segment && section->perm & R_PERM_X) { db->exec_off = section->paddr; break; } } if(db->exec_off == 0) { return WKR_FORMAT; } } return WKR_OK; } wkr_err wkr_db_close(wkr_db* db) { sqlite3_close(db->handle); db->handle = NULL; } const char* wkr_db_errmsg(wkr_db* db, wkr_err err) { switch(err) { case WKR_OK: return "No error"; case WKR_SQLITE: return sqlite3_errmsg(db->handle); case WKR_FORMAT: return "Database is not a valid wakare trace"; case WKR_PROG: return "Trace does not contain the specified executable"; default: return "Unknown error"; } } wkr_err wkr_db_branchcount(wkr_db* db, int* count) { return sql_count_rows(db->handle, "branches", count); } wkr_err wkr_db_mapcount(wkr_db* db, int* count) { return sql_count_rows(db->handle, "mappings", count); } wkr_err wkr_db_hitcount(wkr_db* db, int* count) { return sql_count_rows(db->handle, "hitcounts", count); } // RList<wkr_mapping> wkr_err wkr_db_mappings(wkr_db* db, RList** res) { sqlite3_stmt* query = NULL; if(sqlite3_prepare_v2(db->handle, "SELECT * FROM mappings;", -1, &query, 0) != SQLITE_OK) { return WKR_SQLITE; } int err = 0; RList* mapping_list = r_list_newf(wkr_mapping_free); while((err = sqlite3_step(query)) != SQLITE_DONE) { if(err != SQLITE_ROW) { r_list_free(mapping_list); return WKR_SQLITE; } wkr_mapping* map = R_NEW0(wkr_mapping); map->name = strdup(sqlite3_column_text(query, 1)); map->from = sqlite3_column_int64(query, 2); map->to = sqlite3_column_int64(query, 3); r_list_append(mapping_list, map); } sqlite3_finalize(query); *res = mapping_list; return WKR_OK; } wkr_err wkr_db_bbs(wkr_db* db, RList** res) { sqlite3_stmt* query = NULL; if(sqlite3_prepare_v2(db->handle, "SELECT * FROM hitcounts;", -1, &query, 0) != SQLITE_OK) { return WKR_SQLITE; } int err = 0; RList* hitcount_list = r_list_new(); while((err = sqlite3_step(query)) != SQLITE_DONE) { if(err != SQLITE_ROW) { r_list_free(hitcount_list); return WKR_SQLITE; } wkr_hitcount* hit = R_NEW0(wkr_hitcount); hit->address = wkr_db_frompie(db, sqlite3_column_int64(query, 1)); hit->count = sqlite3_column_int64(query, 2); r_list_append(hitcount_list, hit); } sqlite3_finalize(query); *res = hitcount_list; return WKR_OK; } wkr_err wkr_db_xrefs(wkr_db* db, ut64 address, RList** res) { sqlite3_stmt* query = NULL; if(sqlite3_prepare_v2(db->handle, "SELECT * FROM branches WHERE source=?1;", -1, &query, 0) != SQLITE_OK) { return WKR_SQLITE; } if(sqlite3_bind_int64(query, 1, wkr_db_topie(db, address)) != SQLITE_OK) { return WKR_SQLITE; } int err = 0; RList* xref_list = r_list_new(); RListIter* iter; while((err = sqlite3_step(query)) != SQLITE_DONE) { if(err != SQLITE_ROW) { r_list_free(xref_list); sqlite3_finalize(query); return WKR_SQLITE; } ut64 destination = wkr_db_frompie(db, sqlite3_column_int64(query, 3)); wkr_hitcount* hit = NULL; wkr_hitcount* it = NULL; r_list_foreach(xref_list, iter, it) { if(it->address == destination) { hit = it; break; } } if(hit) { hit->count++; } else { hit = R_NEW0(wkr_hitcount); hit->address = destination; hit->count = 1; r_list_append(xref_list, hit); } } *res = xref_list; return WKR_OK; } ut64 wkr_db_frompie(wkr_db* db, ut64 address) { if(db->pie) { // Should not happen if(address < db->map_low || address > db->map_high) return address; return (address - db->map_low) + db->exec_off; } return address; } ut64 wkr_db_topie(wkr_db* db, ut64 address) { if(db->pie) { return (address - db->exec_off) + db->map_low; } return address; } <file_sep>#include <string.h> #include <r_core.h> #include <sqlite3.h> #include "utils.h" wkr_db tracedb; RList* bb_list = NULL; static const char* usage[] = { "Wakare plugin:", "\\wkro [file] : Open a trace database", "\\wkri : Displays information about the loaded database", "\\wkrx : Displays the xrefs from the current address", "\\wkrbl : Displays the list of basic blocks", "\\wkrbh : Adds hitcounts in basic blocks comments", "\\wkrbc : Cleans the hitcount comments", "\\wkrdd [file] : Does a difference based diffing with another trace", "\\wkrdi [file] : Does an intersection based diffing with another trace", "\\wkrdr : Resets the database to its original state", NULL }; static void print_usage() { for(int i = 0; usage[i] != NULL; i++) r_cons_printf("%s\n", usage[i]); } // RListComparator for list of basic blocks (wkr_hitcount) static int bb_hitcount_cmp_dec(const void* a, const void* b) { wkr_hitcount* am = (wkr_hitcount*)a; wkr_hitcount* bm = (wkr_hitcount*)b; if(am->count > bm->count) { return -1; } else if(am->count < bm->count){ return 1; } else { return 0; } } static int bb_address_cmd_inc(const void* a, const void* b) { wkr_hitcount* am = (wkr_hitcount*)a; wkr_hitcount* bm = (wkr_hitcount*)b; if(am->address > bm->address) { return 1; } else if(am->address < bm->address) { return -1; } else { return 0; } } // wkro: Opens a trace database static void cmd_wkro(RCore* core, const char* filename) { wkr_err err = wkr_db_open(&tracedb, core, filename); if(err != WKR_OK) { r_cons_printf("Error while opening database: %s\n", wkr_db_errmsg(&tracedb, err)); wkr_db_close(&tracedb); return; } if((err = wkr_db_bbs(&tracedb, &bb_list)) != WKR_OK) { bb_list = NULL; r_cons_printf("Error while gettings basic blocks: %s\n", wkr_db_errmsg(&tracedb ,err)); wkr_db_close(&tracedb); return; } r_list_sort(bb_list, bb_hitcount_cmp_dec); } // wkri: Displays information about the currently loaded trace database static void cmd_wkri() { if(tracedb.handle == NULL) { r_cons_printf("No database was loaded\n"); return; } int hitcount = 0; int branchcount = 0; int mapcount = 0; wkr_err err; if((err = wkr_db_hitcount(&tracedb, &hitcount)) != WKR_OK) goto fail; if((err = wkr_db_branchcount(&tracedb, &branchcount)) != WKR_OK) goto fail; if((err = wkr_db_mapcount(&tracedb, &mapcount)) != WKR_OK) goto fail; RList* mappings = NULL; if((err = wkr_db_mappings(&tracedb, &mappings)) != WKR_OK) goto fail; r_cons_printf("Branches : %i\n", branchcount); r_cons_printf("Basic blocks : %i\n", hitcount); r_cons_printf("Mappings : %i\n", mapcount); r_cons_printf("----- Mapping list -----\n"); RListIter* iter; wkr_mapping* map; r_list_foreach(mappings, iter, map) { r_cons_printf("0x%lx - 0x%lx: %s\n", map->from, map->to, map->name); } r_list_free(mappings); return; fail: r_cons_printf("Error while getting trace info: %s\n", wkr_db_errmsg(&tracedb, err)); } // wkrx: Displays branch xrefs from the current address static void cmd_wkrx(RCore* core) { if(tracedb.handle == NULL) { r_cons_printf("No database was loaded\n"); return; } wkr_err err; RList* xref_list; RListIter* iter; wkr_hitcount* hit; if((err = wkr_db_xrefs(&tracedb, core->offset, &xref_list)) != WKR_OK) { r_cons_printf("Error while gettings xrefs: %s\n", wkr_db_errmsg(&tracedb, err)); return; } // Printing the result r_cons_printf("--- Found %i xrefs from 0x%lx ---\n", r_list_length(xref_list), core->offset); r_list_sort(xref_list, bb_hitcount_cmp_dec); r_list_foreach(xref_list, iter, hit) { RAnalFunction* fcn = r_anal_get_fcn_in(core->anal, hit->address, 0); const char* funcname = (fcn) ? fcn->name : ""; r_cons_printf("0x%lx: %lu %s\n", hit->address, hit->count, funcname); } r_list_free(xref_list); } // wkrbb: Displays the list of basic blocks static void cmd_wkrbl(RCore* core) { if(bb_list == NULL || tracedb.handle == NULL) { r_cons_printf("No database was loaded\n"); return; } RListIter* iter; wkr_hitcount* hit; r_list_foreach(bb_list, iter, hit) { RAnalFunction* fcn = r_anal_get_fcn_in(core->anal, hit->address, 0); const char* funcname = (fcn) ? fcn->name : ""; r_cons_printf("0x%lx: %lu %s\n", hit->address, hit->count, funcname); } } // wkrbh: Adds comments to basic blocks specifying their hitcount static void cmd_wkrbh(RCore* core) { if(tracedb.handle == NULL || bb_list == NULL) { r_cons_printf("No database was loaded\n"); return; } RListIter* iter; wkr_hitcount* hit; // TODO: Handle overlapping comments r_list_foreach(bb_list, iter, hit) { char* cmt = r_str_newf("(hitcount: %d)", hit->count); r_meta_set_string(core->anal, R_META_TYPE_COMMENT, hit->address, cmt); free(cmt); } } // wkrbc: Clears wakare comments on top of basic blocks (deletes first comment // of basic blocks) static void cmd_wkrbc(RCore* core) { if(tracedb.handle == NULL) { r_cons_printf("No database was loaded\n"); return; } wkr_err err; RList* bbs = NULL; if((err = wkr_db_bbs(&tracedb, &bbs)) != WKR_OK) { r_cons_printf("Could not get basic blocks: %s\n", wkr_db_errmsg(&tracedb, err)); return; } RListIter* iter; wkr_hitcount* hit; // TODO: Handle overlapping comments r_list_foreach(bbs, iter, hit) { r_meta_del(core->anal, R_META_TYPE_COMMENT, hit->address, 1); } r_list_free(bbs); } // wkrdr: Resets the cached basic block list to its original state static void cmd_wkrdr() { if(tracedb.handle == NULL) { r_cons_printf("No database was loaded\n"); return; } int old_length = r_list_length(bb_list); r_list_free(bb_list); bb_list = NULL; wkr_err err; if((err = wkr_db_bbs(&tracedb, &bb_list)) != WKR_OK) { r_cons_printf("Could not get basic blocks: %s\n", wkr_db_errmsg(&tracedb, err)); } r_list_sort(bb_list, bb_hitcount_cmp_dec); r_cons_printf("New basic block count %d (previously %d)\n", r_list_length(bb_list), old_length); } // wkrdd: Difference diffing static void cmd_wkrdd(RCore* core, const char* filename) { if(tracedb.handle == NULL) { r_cons_printf("No database was loaded\n"); return; } wkr_db diffdb; wkr_err err = wkr_db_open(&diffdb, core, filename); if(err != WKR_OK) { r_cons_printf("Could not open database for diffing: %s\n", wkr_db_errmsg(&diffdb, err)); wkr_db_close(&diffdb); return; } RList* target_bb_list; if((err = wkr_db_bbs(&diffdb, &target_bb_list)) != WKR_OK) { r_cons_printf("Error while getting basic blocks from diff database: %s\n", wkr_db_errmsg(&diffdb, err)); wkr_db_close(&diffdb); return; } // Now we sort both the list by address for processing r_list_sort(target_bb_list, bb_address_cmd_inc); r_list_sort(bb_list, bb_address_cmd_inc); RList* diffed_bb = r_list_new(); RListIter* source_it = r_list_iterator(bb_list); RListIter* diff_it = r_list_iterator(target_bb_list); while(source_it != NULL && diff_it != NULL) { wkr_hitcount* src_hc = (wkr_hitcount*)source_it->data; wkr_hitcount* diff_hc = (wkr_hitcount*)diff_it->data; if(src_hc->address < diff_hc->address) { wkr_hitcount* new_hc = R_NEW0(wkr_hitcount); new_hc->address = src_hc->address; new_hc->count = src_hc->count; r_list_append(diffed_bb, new_hc); source_it = source_it->n; } else if(src_hc->address > diff_hc->address) { diff_it = diff_it->n; } else { // They are the same so we skip them source_it = source_it->n; diff_it = diff_it->n; } } // If there are remaining bbs we append them to the list while(source_it != NULL) { wkr_hitcount* src_hc = (wkr_hitcount*)source_it->data; wkr_hitcount* new_hc = R_NEW0(wkr_hitcount); new_hc->address = src_hc->address; new_hc->count = src_hc->count; r_list_append(diffed_bb, new_hc); source_it = source_it->n; } r_cons_printf("New basic block count %d (previously %d)\n", r_list_length(diffed_bb), r_list_length(bb_list)); r_list_sort(diffed_bb, bb_hitcount_cmp_dec); r_list_free(bb_list); r_list_free(target_bb_list); bb_list = diffed_bb; } // wkrdi: Intersection diffing static void cmd_wkrdi(RCore* core, const char* filename) { if(tracedb.handle == NULL) { r_cons_printf("No database was loaded\n"); return; } wkr_db diffdb; wkr_err err = wkr_db_open(&diffdb, core, filename); if(err != WKR_OK) { r_cons_printf("Could not open database for diffing: %s\n", wkr_db_errmsg(&diffdb, err)); wkr_db_close(&diffdb); return; } RList* target_bb_list; if((err = wkr_db_bbs(&diffdb, &target_bb_list)) != WKR_OK) { r_cons_printf("Error while getting basic blocks from diff database: %s\n", wkr_db_errmsg(&diffdb, err)); wkr_db_close(&diffdb); return; } // Now we sort both the list by address for processing r_list_sort(target_bb_list, bb_address_cmd_inc); r_list_sort(bb_list, bb_address_cmd_inc); RList* diffed_bb = r_list_new(); RListIter* source_it = r_list_iterator(bb_list); RListIter* diff_it = r_list_iterator(target_bb_list); while(source_it != NULL && diff_it != NULL) { wkr_hitcount* src_hc = (wkr_hitcount*)source_it->data; wkr_hitcount* diff_hc = (wkr_hitcount*)diff_it->data; if(src_hc->address < diff_hc->address) { source_it = source_it->n; } else if(src_hc->address > diff_hc->address) { diff_it = diff_it->n; } else { wkr_hitcount* new_hc = R_NEW0(wkr_hitcount); new_hc->address = src_hc->address; new_hc->count = src_hc->count; r_list_append(diffed_bb, new_hc); source_it = source_it->n; diff_it = diff_it->n; } } r_cons_printf("New basic block count %d (previously %d)\n", r_list_length(diffed_bb), r_list_length(bb_list)); r_list_sort(diffed_bb, bb_hitcount_cmp_dec); r_list_free(bb_list); r_list_free(target_bb_list); bb_list = diffed_bb; } static int cmd_handler(void* user, const char* input) { RCore* core = (RCore*)user; if(r_str_cmp(input, "\\wkr", 4) != 0 || r_str_ansi_len(input) < 4) { return 0; } switch(input[4]) { case 'o': cmd_wkro(core, r_str_trim_ro(input + 5)); break; case 'i': cmd_wkri(); break; case 'x': cmd_wkrx(core); break; case 'd': switch(input[5]) { case 'd': cmd_wkrdd(core, r_str_trim_ro(input + 6)); break; case 'i': cmd_wkrdi(core, r_str_trim_ro(input + 6)); break; case 'r': cmd_wkrdr(); break; default: print_usage(); break; } break; case 'b': switch(input[5]) { case 'l': cmd_wkrbl(core); break; case 'h': cmd_wkrbh(core); break; case 'c': cmd_wkrbc(core); break; default: print_usage(); break; } break; default: print_usage(); } return 0; } RCorePlugin r_core_plugin_wakare = { .name = "wakare", .author = "Sideway", .desc = "Loads execution traces from sqlite databases generated by Wakare", .call = cmd_handler, }; #ifndef CORELIB RLibStruct radare_plugin = { .type = R_LIB_TYPE_CORE, .data = &r_core_plugin_wakare, .version = R2_VERSION }; #endif <file_sep>R2_PLUGIN_PATH=$(shell r2pm -H R2PM_PLUGDIR) CFLAGS=-g -fPIC $(shell pkg-config --cflags r_core) LDFLAGS=-shared $(shell pkg-config --libs r_core) $(shell pkg-config --libs sqlite3) SO_EXT=$(shell uname|grep -q Darwin && echo dylib || echo so) PLUGIN=r2wakare.$(SO_EXT) all: $(PLUGIN) $(PLUGIN): wakare.o utils.o $(CC) $(LDFLAGS) $^ -o $@ %.o: %.c $(CC) $(CFLAGS) -r $^ -o $@ .PHONY: clean clean: rm -f *.o rm -f *.$(SO_EXT) .PHONY: install install: cp -f $(PLUGIN) $(R2_PLUGIN_PATH)/ .PHONY: uninstall uninstall: rm -f $(R2_PLUGIN_PATH)/$(PLUGIN)
4a05a4e4dd1ae745ea8bcdb8a3e4d5eba349f253
[ "Markdown", "C", "Makefile" ]
5
C
SiD3W4y/r2wakare
54754abc7551c03463dd0eb4f198251bbae031a8
4c72ecb87b7f4ed786e31a5c57f2f0bdcc6632f9
refs/heads/master
<file_sep>import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import pandas as pd get_name = lambda parts: f"{parts[0]}:{parts[1]}-{parts[2]}" matches = {line.split("\t")[2] for line in open(snakemake.input.matches) if not line.startswith("#") and line.strip()} hits = [get_name(line.split()) in matches for line in open(snakemake.input.peaks)] ratio = np.cumsum(hits)/np.arange(1, len(hits)+1) plt.plot(ratio) plt.savefig(snakemake.output[0]) pd.DataFrame({"x": np.arange(ratio.size), "y": ratio}).to_pickle(snakemake.output[1]) <file_sep>motifs = {"CTCF": "MA0139.1", "ATF3": "MA0605.2", "MAFK": "MA0496.1"} jaspar_address = "http://jaspar.genereg.net/api/v1/matrix/" rule get_meme: output: "results/motifs/{condition}.meme" run: shell('wget {jaspar_address}%s.meme -O {output} --user-agent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"' % motifs[wildcards.condition]) rule sort_peaks: input: "results/{caller}/{regions}/{filename}" output: "results/{caller}/sorted_{regions}/{filename}" shell: "sort -nr -k5 {input} > {output}" rule get_peak_sequences: input: peaks="results/{caller}/{regions}/{sample}.narrowPeak", output: "results/{caller}/{regions}_fasta/{sample}.fa" params: reference=config["reference_fasta"] shell: "bedtools getfasta -fi {params.reference} -bed {input.peaks} > {output}" rule motif_enrichment: input: fasta="results/{caller}/{regions}_fasta/{celltype}_{condition}.fa", meme="results/motifs/{condition}.meme" output: multiext("results/{caller}/motif_matches_{regions}/{celltype}_{condition}/fimo", ".html", ".xml", ".tsv", ".gff") shell: "fimo --oc results/{wildcards.caller}/motif_matches_{wildcards.regions}/{wildcards.celltype}_{wildcards.condition}/ {input.meme} {input.fasta}" rule motif_plot: input: matches="results/{caller}/motif_matches_{regions}/{sample}/fimo.tsv", peaks="results/{caller}/sorted_{regions}/{sample}.narrowPeak" output: "results/{caller}/motif_plots/{regions}/{sample}.png", "results/{caller}/motif_plots/{regions}/{sample}.pkl" script: "../scripts/motifplot.py" rule join_plot: input: expand("results/{caller}/motif_plots/{{regions}}/{{sample}}.pkl", caller=config["callers"]) output: report("results/plots/motif/{regions}/{sample}.png", category="Motif plots") script: "../scripts/joinplots.py" <file_sep>import pandas as pd import os macs_output=["treat_pileup.bdg", "control_lambda.bdg", "peaks.narrowPeak"] genomesize = config.get("max_pos", "hs") rule macs_wo_control: input: treatment=lambda w: [f"results/reads/{sample}.bed.gz" for sample in samples.index[(samples["condition"]==w.condition) & (samples["celltype"]==w.celltype)]] output: expand("results/macs2_folder/{{celltype}}_{{condition}}_{filetype}", filetype=macs_output) shell: """macs2 callpeak -t {input.treatment} -g {genomesize} --bdg --outdir results/macs2_folder/ -n {wildcards.celltype}_{wildcards.condition} --nomodel --extsize 176""" rule hmmacs_wo_control: input: treatment="results/macs2_folder/{sample}_treat_pileup.bdg", control="results/macs2_folder/{sample}_control_lambda.bdg" output: "results/hmmacs/peaks/{sample}.narrowPeak" shell: "hmmacs {input.treatment} {input.control} {output}" rule filter_hmmacs: input: "results/hmmacs/peaks/{sample}.narrowPeak" output: "results/filtered_hmmacs/peaks/{sample}.narrowPeak" shell: "awk '{{if ($3-$2>=176) print}}' {input} > {output}" rule callpeak_w_control: input: treatment=lambda w: expand("results/reads/{sample}.bed.gz", sample==samples.index[samples["condition"]==w.condition & samples["celltype"]==w.celltype]), control=lambda w: expand("results/reads/{sample}.bed.gz", sample==samples.index[samples["condition"]=="input" & samples["celltype"]==w.celltype]) output: expand("results/controlled_macs2_folder/{{celltype}}_{{condition}}_{filetype}", filetype=macs_output) shell: """macs2 callpeak -t {input.treatment} -c {input.control} -g {genomesize} --bdg --outdir macs2_folder/ -n {wildcards.celltype}_{wildcards.condition}""" rule move_macs_peaks: input: "results/macs2_folder/{sample}_peaks.narrowPeak" output: "results/macs2/peaks/{sample}.narrowPeak" shell: "mv {input} {output}" rule summit_regions: input: "results/{caller}/peaks/{sample}.narrowPeak" output: "results/{caller}/summit_regions/{sample}.narrowPeak" shell: """awk '{{OFS="\t"}}{{print $1, $2+$10-200, $2+$10+200, ".", $5}}' {input} > {output}""" <file_sep>from pathlib import PurePath import seaborn as sns import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import pandas as pd filenames = snakemake.input plt.figure(figsize=(10, 10)) dfs = [pd.read_pickle(filename) for filename in filenames] xmax = min(df["x"].max() for df in dfs) for df, filename in zip(dfs, filenames): df["name"] = filename.split("/")[1] print(filename, df) df = pd.concat(dfs) p = sns.lineplot(data=df, x="x", y="y", hue="name") plt.xlabel("Rank") plt.ylabel("Proportion motif hits") plt.xlim((0, xmax)) plt.title("Motif_Plot") plt.savefig(snakemake.output[0]) <file_sep>rule encode_download: output: "results/reads/{sample}.bam" shell: temp("wget https://www.encodeproject.org/files/{wildcards.sample}/@@download/{wildcards.sample}.bam -O {output}") def region_filter(): if "chrom" not in config: return "1" f = '$1=="%s"' % config["chrom"] if "max_pos" in config: f += " && $3<%s" % config["max_pos"] return f region_f = region_filter() print(region_f) rule region_bamtobed: input: "results/reads/{sample}.bam", output: temp("results/unsorted_reads/{sample}.bed") shell: """bedtools bamtobed -i {input} | awk '{{if ({region_f}) print}}' > {output}""" rule sortbed: input: "results/unsorted_reads/{sample}.bed" output: "results/reads/{sample}.bed.gz" shell: "sort -k 1,1 -k2,2n {input} | gzip > {output}"
79203ee9137a45ac7ffc22b7170703e6be7e596f
[ "Python" ]
5
Python
knutdrand/peak-eval
377092ba2a0954f0163f20de9a4a73d2bcf62a7e
1a8b3918c10c22c5c812f4051550a61b159e7201
refs/heads/main
<repo_name>ropturpvp/copytabs<file_sep>/api.php <?php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST'); header("Access-Control-Allow-Headers: X-Requested-With"); include_once("database.php"); $status["status"]=""; $data=1; $select=$DB->prepare("SELECT pagesText FROM pages WHERE (:id)"); $select->bindParam(':id', $data); $select->execute(); $select=$select->fetch(PDO::FETCH_ASSOC); $result=json_encode($select); { print($result); } ?> <file_sep>/save.php <?php include_once("database.php"); $status["status"]=""; if(isset($_POST["data"])) { $id=1; $select=$DB->prepare("UPDATE pages SET pagesText=:pagesText WHERE id=:id"); $select->bindParam(':id', $id); $select->bindParam(':pagesText', $_POST["data"]); $select->execute(); $status["status"]="ok"; } else { $status["status"]="error"; echo json_encode($status); }; ?> <file_sep>/database.php <?php $host=getenv('DB_HOST'); $dbName=getenv('DB_NAME'); $user=getenv('DB_USER'); $password=getenv('DB_PASS'); $DB = new PDO('mysql:host='.$host.';dbname='.$dbName.'', $user, $password); ?>
efce389cc9739e7498c5db9f6fbf65b42165ea30
[ "PHP" ]
3
PHP
ropturpvp/copytabs
40600d5254ff59bf5dead907292b1ec791ce5ae8
f1425ccdadf7233605afa931bbc3730cdc0c0988
refs/heads/master
<repo_name>lowocon/PaymentInterface<file_sep>/src/main/java/com/globalfreepay/payment/support/Consts.java package com.globalfreepay.payment.support; /** * Created by yixian on 2016-06-29. */ public class Consts { public static final String WECHATINFO = "WECHATINFO"; public static final String MANAGER_STATUS = "MANAGER_STATUS"; public static final String PARTNER_STATUS = "PARTNER_STATUS"; } <file_sep>/src/main/java/com/globalfreepay/payment/support/exceptions/ServerErrorException.java package com.globalfreepay.payment.support.exceptions; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; /** * 500 * Created by yixian on 2016-04-25. */ @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public class ServerErrorException extends RuntimeException { public ServerErrorException() { } public ServerErrorException(String message) { super(message); } public ServerErrorException(String message, Throwable cause) { super(message, cause); } public ServerErrorException(Throwable cause) { super(cause); } } <file_sep>/src/main/java/com/globalfreepay/payment/web/CallbackController.java package com.globalfreepay.payment.web; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; /** * Created by davep on 2016-07-24. */ @RestController @RequestMapping("/api/orders/{orderId}/callback") public class CallbackController { private Logger logger = LoggerFactory.getLogger(getClass()); @Resource private SimpMessagingTemplate messagingTemplate; @RequestMapping(method = RequestMethod.POST) public JSONObject handleCallback(@RequestBody JSONObject entity, @PathVariable String orderId) { logger.info("callback:" + JSON.toJSONString(entity, SerializerFeature.PrettyFormat)); messagingTemplate.convertAndSend("/app/orders/" + orderId + "/paid", "{}"); JSONObject res = new JSONObject(); res.put("return_code", "SUCCESS"); return res; } } <file_sep>/src/main/resources/application.properties server.port=10290 app.host=https://pay.globepay.co/ <file_sep>/src/main/java/com/globalfreepay/payment/param/req/CreateSDKPayment.java package com.globalfreepay.payment.param.req; public class CreateSDKPayment { private String description; // 必填,订单标题(最大长度128字符,超出自动截取) private int price; // 必填,金额,单位为货币最小单位,例如使用100表示1.00 GBP private String currency; // 币种代码 // 默认值: // GBP // 允许值:GBP, // CNY private String channel; private String notify_url; // 支付通知url,详见支付通知api, // 不填则不会推送支付通知 private String operator; private String system; private String version; private String appid; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public String getNotify_url() { return notify_url; } public void setNotify_url(String notify_url) { this.notify_url = notify_url; } public String getChannel() { return channel; } public void setChannel(String channel) { this.channel = channel; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public String getSystem() { return system; } public void setSystem(String system) { this.system = system; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } } <file_sep>/src/main/java/com/globalfreepay/payment/support/http/HttpRequestResult.java package com.globalfreepay.payment.support.http; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.commons.codec.binary.StringUtils; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpResponse; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; /** * bean contains http request result * Created by yixian on 2015-11-30. */ public class HttpRequestResult { private IOException e; private HttpResponse response; private byte[] responseBytes; private final Map<String, String> headerMap = new HashMap<String, String>(); HttpRequestResult(IOException e) { this.e = e; } HttpRequestResult(HttpResponse response) { this.response = response; for (Header header : response.getAllHeaders()) { headerMap.put(header.getName().toLowerCase(), header.getValue()); } } public boolean isSuccess() { return (e == null) && (getStatusCode() - 200 < 100); } public InputStream getResponseContentStream() throws IOException { return response.getEntity().getContent(); } public byte[] getResponseContent() throws IOException { if (responseBytes == null) { InputStream responseContent = getResponseContentStream(); responseBytes = IOUtils.toByteArray(responseContent); IOUtils.closeQuietly(responseContent); } return responseBytes; } public String getResponseContentString() throws IOException { return StringUtils.newStringUtf8(getResponseContent()); } public JSONObject getResponseContentJSONObj() throws IOException { return JSON.parseObject(getResponseContentString()); } public JSONArray getResponseContentJSONArr() throws IOException { return JSON.parseArray(getResponseContentString()); } public HttpResponse getResponse() { return response; } public int getStatusCode() { return response.getStatusLine().getStatusCode(); } public String getHeader(String key) { return headerMap.get(key.toLowerCase()); } } <file_sep>/src/main/java/com/globalfreepay/payment/param/req/CreateApplyForRefund.java package com.globalfreepay.payment.param.req; public class CreateApplyForRefund { private int fee; public int getFee() { return fee; } public void setFee(int fee) { this.fee = fee; } }
7b997cc93655d7e9ef569034946f9e4666a3f3e3
[ "Java", "INI" ]
7
Java
lowocon/PaymentInterface
f63dc94ce698132be4b4a47e58f07ceb00a6a91c
e1073146e4baad50b781ce742ebbc26fc23bc277
refs/heads/master
<repo_name>kevinenax/SwiftShell<file_sep>/SwiftShell/Utility.swift // // Utility.swift // SwiftShell // // Created by <NAME> on 2/8/16. // Copyright © 2016 NotTooBad Software. All rights reserved. // import Foundation func + <T, U> (left: [T : U], right: [T : U]) -> [T : U] { var copy = left for (k, v) in right { copy.updateValue(v, forKey: k) } return copy }<file_sep>/SwiftShell/Command.swift /* * Released under the MIT License (MIT), http://opensource.org/licenses/MIT * * Copyright (c) 2014 <NAME>, NotTooBad Software (nottoobadsoftware.com) * * Contributors: * <NAME>, https://github.com/kareman - initial API and implementation. * <NAME>, https://github.com/kevinenax - Addition of environment variable logic */ import Foundation private func newtask (shellcommand: String, environmentVariables:[String:String]?) -> NSTask { let task = NSTask() if let env = environmentVariables { let pEnv = NSProcessInfo().environment task.environment = env + pEnv } task.arguments = ["-c", shellcommand] task.launchPath = "/bin/bash" return task } // Summary: it is used exclusively for sending a stream through the forward operator and use it as standardInput in a run command. // Required to enable "func run (shellcommand: String) -> ReadableStreamType" to also be run by itself on a single line. private var _nextinput_: ReadableStreamType? /** Specific handling of func run (shellcommand: String) -> ReadableStreamType on the right side using the stream on the left side as standard input. Warning: is only meant to be used with the "run" command, but could also unintentionally catch other uses of "ReadableStreamType |> ReadableStreamType", though that statement doesn't make any sense. */ public func |> (lhs: ReadableStreamType, @autoclosure rhs: () -> ReadableStreamType) -> ReadableStreamType { assert(_nextinput_ == nil) _nextinput_ = lhs let result = rhs() if _nextinput_ != nil { printErrorAndExit("The statement 'ReadableStreamType |> ReadableStreamType' is invalid.") } return result } /** Run a shell command synchronously with no standard input, or if to the right of a "ReadableStreamType |> ", use the stream on the left side as standard input. - returns: Standard output */ public func run (shellcommand: String, environmentVariables:[String:String]?) -> ReadableStreamType { let task = newtask(shellcommand, environmentVariables: environmentVariables) if let input = _nextinput_ { task.standardInput = input as! FileHandle _nextinput_ = nil } else { // avoids implicit reading of the main script's standardInput task.standardInput = NSPipe () } let output = NSPipe () task.standardOutput = output task.launch() // necessary for now to ensure one shellcommand is finished before another begins. // uncontrolled asynchronous shell processes could be messy. // but shell commands on the same line connected with the pipe operator should preferably be asynchronous. task.waitUntilExit() return output.fileHandleForReading } public func run (shellcommand: String) -> ReadableStreamType { return run(shellcommand, environmentVariables: nil) } /** Shortcut for in-line command, returns output as String. */ public func $ (shellcommand: String) -> String { let task = newtask(shellcommand, environmentVariables: nil) // avoids implicit reading of the main script's standardInput task.standardInput = NSPipe () let output = NSPipe () task.standardOutput = output task.launch() task.waitUntilExit() return output.fileHandleForReading.read().trim() } /** Turn a sequence into valid parameters for a shell command, properly quoted */ public func parameters <S : SequenceType> (sequence: S) -> String { return " " + ( sequence.map { "\"\($0)\"" } ).joinWithSeparator(" ") }
959f08c30a759d0c12555445b86ff08f697e1b25
[ "Swift" ]
2
Swift
kevinenax/SwiftShell
3a95ab75a4f87990394f19ff855fa448b2e6c797
eeb5291f7e29b5886f3c299b7df3d8fd13ae2c67
refs/heads/main
<repo_name>SannevanKempen/AANN<file_sep>/Simulation.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 6 10:36:15 2021 @author: Ingrid """ import numpy as np from matplotlib import pyplot as plt directory = "/Users/Ingrid/Documents/Github/AANN/" def relu(x): return max(0,x) def square01(x, nrHiddenLayers): """Compute square of x in [0,1] using neural network with nrHiddenLayers hidden layers. L = m + 2 W = 3m + 2 E = 12m - 5 """ b1 = 0 b2 = -1/2 b3 = -1 w1 = 2 w2 = -4 w3 = 2 output = x g = x for i in range(1,nrHiddenLayers+1): n1 = relu(g + b1) n2 = relu(g + b2) n3 = relu(g + b3) g = w1*n1 + w2*n2 + w3*n3 output += -1/(2**(2*i))*g return output vSquare01 = np.vectorize(square01) def squareM(x, M, nrHiddenLayers): """Compute square of x in [-M,M] using neural network with nrHiddenLayers hidden layers. """ return square01(np.abs(x)/M, nrHiddenLayers)*M vSquareM = np.vectorize(squareM) def mult2(x, y, M, N, nrHiddenLayers): """Compute multiplication xy in [-M,M]x[-N,N] using neural network with nrHiddenLayers hidden layers. """ return 2*(M*N)**2*(square01(np.abs(x+y)/(2*M*N), nrHiddenLayers) - square01(np.abs(x)/(2*M*N), nrHiddenLayers) - square01(np.abs(y)/(2*M*N), nrHiddenLayers)) vMult2 = np.vectorize(mult2) def g(s,x): for k in range(0,2**(s-1)+2): if 2*k/2**s <= x <= (2*k+1)/2**s: return x*2**s - 2*k elif (2*k+1)/2**s <= x <= (2*k+2)/2**s: return 2*(k+1) - x*2**s vg = np.vectorize(g) def plotg(s): fig = plt.figure(figsize =(10, 7)) for j in range(1,s+1): n = np.repeat(j, 1000) x = np.arange(-0,1,0.001) gsx = vg(n,x) x = np.concatenate((np.arange(-.2,0,.001),x,np.arange(1,1.2,0.001))) gsx = np.concatenate((np.repeat(0,200),gsx,np.repeat(0,200))) plt.plot(x, gsx, label = f"$g_{j}$", linewidth = 2) # plt.xlabel("$x$") plt.legend(loc = "best", prop={'size': 15}) plt.tick_params(axis='x', labelsize=14) plt.tick_params(axis='y', labelsize=14) plt.savefig(directory + "functiongs.pdf", bbox_inches = 'tight') plt.show() def plotSquare01(m): """Create plot similar to Yarotsky2017 Figure 2b""" fig = plt.figure(figsize =(10, 7)) for j in range(0,m+1): n = np.repeat(j, 100) x = np.arange(0,1,0.01) xSquaredEst = vSquare01(x, n) plt.plot(x, xSquaredEst, label = f"$h_{j}$", linewidth = 2) plt.plot(x, x**2, "--", label = "$f$", color = "black") # plt.xlabel("$x$") plt.legend(loc = "best", prop={'size': 15}) plt.tick_params(axis='x', labelsize=14) plt.tick_params(axis='y', labelsize=14) plt.savefig(directory + "functionhm.pdf", bbox_inches = 'tight') def plotSquareM(m,M): fig = plt.figure(figsize =(10, 7)) for j in range(0,m+1): n = np.repeat(j, 100) vM = np.repeat(M, 100) x = np.arange(-M,M,2*M/100) xSquaredEst = vSquareM(x, vM, n) plt.plot(x, xSquaredEst, label = j) plt.xlabel("$x$", fontsize = 14) plt.ylabel("$\tilde{f}_m(x)$", fontsize = 14) plt.legend(loc = "best", prop={'size': 15}) plt.tick_params(axis='x', labelsize=14) plt.tick_params(axis='y', labelsize=14) plt.savefig(directory + "functiontildeh.pdf", bbox_inches = 'tight') def plotMult2(m,x,N): fig = plt.figure(figsize =(10, 7)) axes = plt.gca() axes.set_ylim([-150,100]) M = np.abs(x) for j in range(1,m+1): n = np.repeat(j, 1000) vM = np.repeat(M, 1000) vN = np.repeat(N, 1000) vx = np.repeat(x, 1000) vy = np.arange(-N,N,2*N/1000) xyEst = vMult2(vx, vy, vM, vN, n) plt.plot(vy, xyEst, label = j) plt.plot(vy, x*vy, "--", label = "$xy$", linewidth = 2, color = "black") plt.xlabel("$y$", fontsize = 14) plt.legend(loc = "best", prop={'size': 15}) plt.tick_params(axis='x', labelsize=14) plt.tick_params(axis='y', labelsize=14) plt.savefig(directory + "functiontimes.pdf", bbox_inches = 'tight') plotg(3) # plotSquare01(2) # plotSquareM(5,5) # plotMult2(5,5,10) # fig = plt.figure(figsize =(10, 7)) # x = np.arange(0,2,0.01) # y = np.arange(.5,1,0.01) # z = np.arange(1,2,0.01) # plt.plot(x, 2*x, label = "2$\sigma(x)$") # plt.plot(y, 2*y-4*(y-1/2), label = "2$\sigma(x)-4\sigma(x-1/2)$") # plt.plot(z, 2*z-4*(z-1/2)+2*(z-1), label = "2$\sigma(x)$") # plt.legend(loc = "best")#prop={'size': 16})
2ec0d17cbcefe27cf06456da57f2655cdfa92788
[ "Python" ]
1
Python
SannevanKempen/AANN
51ca6f2483644c6c262966ce40b233fde4f48b53
07c0186152df7d726e63a4327e32df3c8601f216
refs/heads/master
<file_sep>package com.example.ejercicio_ficheros; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class Actividad3 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.actividad3); // setup reclycerview with adapter RecyclerView recyclerView = findViewById(R.id.rv_lista_webs); final AdaptadorPaginasWeb adaptador = new AdaptadorPaginasWeb(this, cargarPaginas()); recyclerView.setAdapter(adaptador); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adaptador.setOnItemClickListener(new AdaptadorPaginasWeb.OnItemClickListener() { @Override public void onIrPulsado(int position) { Uri uri = Uri.parse(adaptador.mdata.get(position).getEnlace()); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } }); } private ArrayList<PaginaWeb> cargarPaginas() { ArrayList<PaginaWeb> paginas = new ArrayList<PaginaWeb>(); try{ InputStream fraw = getResources().getAssets().open("recursos/paginas_webs.txt"); BufferedReader brin = new BufferedReader(new InputStreamReader(fraw)); String linea = brin.readLine(); while (linea != null) { String [] trozos = linea.split(";"); paginas.add(new PaginaWeb(trozos[0].trim(), trozos[1].trim(), trozos[2].trim(), trozos[3].trim())); linea = brin.readLine(); } fraw.close(); } catch (Exception ex){ Log.e("Ficheros", "Error al leer fichero de recursos en Assets"); } return paginas; } } <file_sep>include ':app' rootProject.name='EJERCICIO_FICHEROS' <file_sep>package com.example.ejercicio_ficheros; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.Context; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class Actividad1 extends AppCompatActivity { private EditText txtAgregar; private TextView txtVer; // Variables para los permisos private static final int SOLICITUD_PERMISO_WRITE_SD = 0; private static final int SOLICITUD_PERMISO_READ_SD = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.actividad1); txtAgregar = findViewById(R.id.editTextAgregar); txtVer = findViewById(R.id.txtVer); } public void agregarInterno(View view) { try{ OutputStreamWriter osw= new OutputStreamWriter(openFileOutput("fichero_interno.txt", Context.MODE_APPEND)); osw.write(txtAgregar.getText().toString() + "\n"); txtAgregar.setText(""); osw.close(); Toast.makeText(this, "Texto guardado en FICH. INT.", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Log.e ("Ficheros", "ERROR!! al escribir fichero en memoria interna"); } } public void leerInterno(View view) { try{ BufferedReader fin = new BufferedReader(new InputStreamReader(openFileInput("fichero_interno.txt"))); String todo = ""; String texto = fin.readLine(); while (texto!=null) { todo = todo + texto + "\n"; texto = fin.readLine(); } fin.close(); txtVer.setText(todo); } catch (Exception ex){ Log.e("Ficheros", "Error al leer fichero desde memoria interna"); } } public void leerRecurso(View view) { try{ InputStream fraw = getResources().getAssets().open("recursos/recurso_prueba.txt"); BufferedReader brin = new BufferedReader(new InputStreamReader(fraw)); String todo = ""; String linea = brin.readLine(); while (linea != null) { todo = todo + linea + "\n"; linea = brin.readLine(); } fraw.close(); txtVer.setText(todo); } catch (Exception ex){ Log.e("Ficheros", "Error al leer fichero de recursos en Assets"); } } public void borrarFichInterno(View view) { try{ OutputStreamWriter osw= new OutputStreamWriter(openFileOutput("fichero_interno.txt", Context.MODE_APPEND)); osw.write(""); osw.close(); Toast.makeText(this, "Fichero interno borrado", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Log.e ("Ficheros", "ERROR!! al escribir fichero en memoria interna"); } } public void agregarExterno(View view) { if (comprobarPermisos()) { Toast.makeText(this, "Tenemos permisos para escribir", Toast.LENGTH_SHORT).show(); if (sdDisponible()) { escribirEnSD(); } else Toast.makeText(this, "Tarjeta NO lista para poder escribir", Toast.LENGTH_SHORT).show(); } else { solicitarPermiso( Manifest.permission.WRITE_EXTERNAL_STORAGE, "Sin este permiso no se puede ESCRIBIR en el dispositivo externo", SOLICITUD_PERMISO_WRITE_SD, this); } } public void leerExterno(View view) { if (comprobarPermisos()) { Toast.makeText(this, "Tenemos permisos para leer", Toast.LENGTH_SHORT).show(); if (sdDisponible()) { leerDeSD(); } else Toast.makeText(this, "Tarjeta NO lista para poder leer", Toast.LENGTH_SHORT).show(); } else { solicitarPermiso( Manifest.permission.WRITE_EXTERNAL_STORAGE, "Sin este permiso no se puede LEER en el dispositivo externo", SOLICITUD_PERMISO_WRITE_SD, this); } } public void borrarFichExterno(View view) { if (comprobarPermisos()) { Toast.makeText(this, "Tenemos permisos para borrar", Toast.LENGTH_SHORT).show(); if (sdDisponible()) { borrarEnSD(); } else Toast.makeText(this, "Tarjeta NO lista para poder borrar", Toast.LENGTH_SHORT).show(); } else { solicitarPermiso( Manifest.permission.WRITE_EXTERNAL_STORAGE, "Sin este permiso no se puede LEER en el dispositivo externo", SOLICITUD_PERMISO_WRITE_SD, this); } } private boolean comprobarPermisos (){ //Comprobamos que tenemos permiso para realizar la operación. if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { return true; } else { return false; } } private boolean sdDisponible () { boolean sdDisponible = false; boolean sdAccesoEscritura = false; //Comprobamos el estado de la memoria externa String estado = Environment.getExternalStorageState(); Log.i("Memoria", estado); if (estado.equals(Environment.MEDIA_MOUNTED)) { sdDisponible = true; sdAccesoEscritura = true; } else if (estado.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { sdDisponible = true; sdAccesoEscritura = false; } else { sdDisponible = false; sdAccesoEscritura = false; } if (sdDisponible) Toast.makeText(getApplicationContext(), "Tengo Tarjeta SD", Toast.LENGTH_SHORT).show(); if (sdAccesoEscritura) Toast.makeText(getApplicationContext(), "La tarjeta SD es escribible", Toast.LENGTH_SHORT).show(); if (sdDisponible && sdAccesoEscritura) return true; else return false; } private void escribirEnSD (){ try { File ruta_sd = Environment.getExternalStorageDirectory(); File f = new File(ruta_sd.getAbsolutePath(), "prueba_sd.txt"); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(f)); osw.write(txtAgregar.getText().toString()+"\n"); osw.close(); Log.i("Ficheros", "fichero escrito correctamente"); } catch (Exception ex) { Log.e("Ficheros", "Error al escribir fichero en tarjeta SD"); } } private void borrarEnSD (){ try { File ruta_sd = Environment.getExternalStorageDirectory(); File f = new File(ruta_sd.getAbsolutePath(), "prueba_sd.txt"); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(f)); osw.write(""); osw.close(); Log.i("Ficheros", "fichero borrado correctamente"); } catch (Exception ex) { Log.e("Ficheros", "Error al borrar fichero en tarjeta SD"); } } private void leerDeSD(){ try {File ruta_sd = Environment.getExternalStorageDirectory(); File f = new File(ruta_sd.getAbsolutePath(), "prueba_sd.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f))); String texto = ""; String linea = br.readLine(); while (linea != null) { texto = texto + linea + "\n"; linea = br.readLine(); } br.close(); Log.i("Ficheros", texto); txtVer.setText(texto); } catch (Exception ex) { Log.e("Ficheros", "ERROR!! en la lectura del fichero en SD"); } } private static void solicitarPermiso (final String permiso, String justificacion, final int requestCode, final Actividad1 actividad){ if (ActivityCompat.shouldShowRequestPermissionRationale( actividad, permiso)) { //Informamos al usuario para qué y por qué // se necesitan los permisos new AlertDialog.Builder(actividad).setTitle("Solicitud de permiso") .setMessage(justificacion).setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityCompat.requestPermissions(actividad, new String[]{permiso}, requestCode); } }).show(); } else { //Muestra el cuadro de dialogo para la solicitud de permisos y // registra el permiso según respuesta del usuario ActivityCompat.requestPermissions(actividad, new String[]{permiso}, requestCode); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == SOLICITUD_PERMISO_WRITE_SD){ if (grantResults.length >=1 &&grantResults[0]==PackageManager.PERMISSION_GRANTED){ sdDisponible(); escribirEnSD(); } else { Toast.makeText(this,"No se puede escribir en la memoria externa", Toast.LENGTH_LONG ).show(); } } else if (requestCode == SOLICITUD_PERMISO_READ_SD){ if (grantResults.length == 1 &&grantResults[0]==PackageManager.PERMISSION_GRANTED){ leerDeSD(); } else { Toast.makeText(this,"No se puede leer en la memoria externa", Toast.LENGTH_LONG ).show(); } } } }
f844ad97e0b6a38bd1a8e320eb316995aada2374
[ "Java", "Gradle" ]
3
Java
Gian-Piero/EJERCICIO_FICHEROS
0d71a081fe56c1f7d3cb34c54219fcb640cf65b4
c7d8c2ee1da3c7992d8be6dd56f69fbda69aef9e
refs/heads/master
<repo_name>wigy-opensource-developer/dart-sys<file_sep>/readme.md # `dart-sys` #### *Native bindings to the dart native extensions sdk.* This crate exposes an api for [`dart_api.h`](https://github.com/dart-lang/sdk/blob/master/runtime/include/dart_api.h), which exposes the basic [dart](https://dart.dev/) native [extensions api](https://dart.dev/server/c-interop-native-extensions). This crate used [`bindgen`](https://github.com/rust-lang/rust-bindgen) to generate the bindings to the header. ##### Requirements - Provide a path to the dart sdk using a `dart_sdk` environment variable. - If this variable is not available, will look for either a chocolatey install path, or an entry in the `PATH` variable which contains `dart-sdk` in it. This will fall back to the `flutter` sdk should it not find a dart sdk, but this is not recommended, as it is more difficult to compile using the flutter sdk and it appears it ships a non-standard dart sdk. - Have `clang` installed and on your path. ##### Usage Include the following in your `Cargo.toml`: ```toml [lib] crate-type = ["cdylib"] [dependencies] dart-sys = "0.1.0" ``` And follow the guide on the [native extensions api page](https://dart.dev/server/c-interop-native-extensions). ##### Examples Please visit the [examples directory](https://github.com/OptimisticPeach/dart-sys/tree/master/examples) for more information. If there should appear more idiomatic bindings, I will try to keep this updated to link to them. ### Note A few things are not mentioned on the [native extensions api](https://dart.dev/server/c-interop-native-extensions) page: - You should compile using an x64 compiler (eg., `[stable|nightly|beta]-x86_64-pc-windows-msvc`) - You should place the compiled library in the same directory as the root of your dart package (I.E. outside of your `lib` directory) <file_sep>/examples/async.rs #![crate_type = "cdylib"] use dart_sys as ffi; use rand::{ Rng, SeedableRng, prelude::StdRng, }; use std::mem::MaybeUninit; fn random_array(seed: u32, length: i32) -> Option<Vec<u8>> { if length <= 0 || length > 10000000 { return None; } let mut rng = StdRng::seed_from_u64(seed as _); let mut values: Vec<u8> = (0..length) .map(move |_| rng.gen()) .collect(); Some(values) } unsafe extern fn wrapped_random_array(reply_port_id: ffi::Dart_Port, message: *mut ffi::Dart_CObject) { if (*message).type_ == ffi::Dart_CObject_Type_Dart_CObject_kArray && 2 == (*message).value.as_array.length { let param0 = *(*message).value.as_array.values; let param1 = *(*message).value.as_array.values.add(1); if (*param0).type_ == ffi::Dart_CObject_Type_Dart_CObject_kInt32 && (*param1).type_ == ffi::Dart_CObject_Type_Dart_CObject_kInt32 { let length = (*param0).value.as_int32; let seed = (*param1).value.as_int32; let values = random_array(seed as _, length); if let Some(mut val) = values { let mut val: Vec<ffi::Dart_CObject> = val.into_iter().map(|x| { let mut value = MaybeUninit::<ffi::Dart_CObject>::uninit(); (*value.as_mut_ptr()).value.as_int32 = x as i32; (*value.as_mut_ptr()).type_ = ffi::Dart_CObject_Type_Dart_CObject_kInt32; value.assume_init() }).collect(); let mut array: MaybeUninit<ffi::_Dart_CObject__bindgen_ty_1__bindgen_ty_3> = MaybeUninit::uninit(); (*array.as_mut_ptr()).values = &mut val.as_mut_ptr(); (*array.as_mut_ptr()).length = val.len() as _; let mut value = MaybeUninit::<ffi::_Dart_CObject__bindgen_ty_1>::uninit(); (*value.as_mut_ptr()).as_array = array.assume_init(); let mut result = ffi::Dart_CObject { type_: ffi::Dart_CObject_Type_Dart_CObject_kArray, value: value.assume_init(), }; ffi::Dart_PostCObject(reply_port_id, &mut result); return; } } let mut result = MaybeUninit::<ffi::Dart_CObject>::uninit(); (*result.as_mut_ptr()).type_ = ffi::Dart_CObject_Type_Dart_CObject_kNull; ffi::Dart_PostCObject(reply_port_id, result.as_mut_ptr()); } } #[no_mangle] unsafe extern fn randomArrayServicePort(arguments: ffi::Dart_NativeArguments) { ffi::Dart_SetReturnValue(arguments, ffi::Dart_Null()); let mut service_port = ffi::Dart_NewNativePort(b"RandomArrayService\0".as_ptr() as *const _, Some(wrapped_random_array), true); if service_port != 0 { // https://github.com/dart-lang/sdk/blob/9a683de40dd5d0ab623b2a105295ea58964d6afc/runtime/include/dart_api.h#L1173 let send_port = ffi::Dart_NewSendPort(service_port); ffi::Dart_SetReturnValue(arguments, send_port); } } fn main() {}
85a6b1bc5513d0c0eebfad1a29b4ef981a397053
[ "Markdown", "Rust" ]
2
Markdown
wigy-opensource-developer/dart-sys
1e618d76e9303d68e230591b26b0a2a862329ccb
39933beb14715d6a7544a92090a4e97ee2750259
refs/heads/master
<repo_name>joyliu-q/Six-Degrees-of-Wikipedia<file_sep>/src/main.py # Import import time import sys import numpy as np import argparse import string import concurrent from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, Future, as_completed, wait # Webscraping Imports from bs4 import BeautifulSoup, SoupStrainer from urllib.request import urlopen from urllib.error import URLError, HTTPError import grequests # Viualization Imports import networkx as nx import matplotlib.pyplot as plt # Argparse Set-up parser = argparse.ArgumentParser(description="Find the Distance between Two Wikipedia Pages") parser.add_argument('--fromtitle', type=str, required=True, help="the root wikipedia title") parser.add_argument('--totitle', type=str, required=True, help="the target wikipedia title") parser.add_argument('--tp', action='store_true', help="enable threadpool (recommended for high depth)") parser.add_argument('--graph', action='store_true', help="enable network graph creation") parser.add_argument('--saveGraph', type=str, metavar='<path>', help='path to save graph network') args = parser.parse_args() if args.saveGraph and not args.graph: print("You must have --graph enabled to save the graph!") sys.exit(1) # Tree Visualization G = nx.DiGraph() # Changable Variables USE_THREADPOOL = False if args.tp: USE_THREADPOOL = True MAKE_GRAPH = False if args.graph: MAKE_GRAPH = True # Dismissed links are links shared by all sites and do not factor into 6 degrees of separation dismissed_links = ["Talk", "Categories", "Contributions", "Article", "Read", "Main page", "Contents", "Current events", "Random article", "About Wikipedia", "Help", "Community portal", "Recent changes", "Upload file", "What links here", "Related changes", "Upload file", "Special pages", "About Wikipedia", "Disclaimers", "Articles with short description", "Short description matches Wikidata", "Wikipedia indefinitely semi-protected biographies of living people", "Use mdy dates from October 2016", "Articles with hCards", "BLP articles lacking sources from October 2017", "All BLP articles lacking sources", "Commons category link from Wikidata", "Articles with IBDb links", "Internet Off-Broadway Database person ID same as Wikidata", "Short description is different from Wikidata", "PMID", "ISBN", "doi"] degree = 0 path = [] path_found = False current_generation = [] child_generation = [] # Configure args.fromtitle and args.totitle args.fromtitle = string.capwords(args.fromtitle.lower()).replace(" ", "_") args.totitle = string.capwords(args.totitle.lower()).replace(" ", "_") # BS4 optimization only_a_tags = SoupStrainer("a", href=lambda href: href and href.startswith('/wiki/')) # Define Node class Node: def __init__(self, title, url): self.title = title self.url = url self.parent = None self.children = [] self.searched = False def get_url(self): return self.url # find_children - A function that returns all relevant referrals by Wikipedia def find_children(self): global USE_THREADPOOL response = urlopen(self.url) soup = BeautifulSoup(response, 'html.parser', parse_only = only_a_tags) for entry in soup: if str(entry.contents) != "[]": if "/wiki/Help:" in entry.contents[0] or "Wikipedia articles with" in entry.contents[0] or "[<" in entry.contents[0] or "<" in str(entry.contents[0]) or entry.contents[0] == None: continue else: if entry.contents[0] in dismissed_links: continue # If relevant, add to entries child_node = Node(entry.contents[0],"https://en.wikipedia.org" + entry["href"]) child_node.parent = self # Visualization self.children.append(child_node) def attempt_match_children(current_node, to_node): global child_generation global path global path_found global USE_THREADPOOL if USE_THREADPOOL == False: current_node.find_children() current_node.searched = True # Check children for any matches w/ to_node for child_node in current_node.children: # Check if child_node was already searched if child_node.searched == False: # Add child_node to new generation child_generation.append(child_node) # If child_node is the to_node, search is over if child_node.url == to_node.url: path.append(current_node) path.append(child_node) path_found = True return True return False # Determine amount of degrees and commonalities, with origin and end being urls def determine_path(from_node, to_node): global path_found global current_generation global path global degree global child_generation global USE_THREADPOOL # 0th degree if from_node.url == to_node.url: path_found == True return path # 1st degree degree += 1 from_node.find_children() attempt_match_children(from_node, to_node) # 2+ degree: if none of the children match, continue to search through loop if path_found == False: current_node = from_node current_generation = current_node.children path.append(current_node) while path_found == False: print("Degree Raised") degree += 1 child_generation = [] '''# Special Threadpool to find children: attempt to stop bottleneck if USE_THREADPOOL == True: with ThreadPoolExecutor(max_workers=4) as executor: [executor.map(sibling_node.find_children()) for sibling_node in current_generation] ''' # Keep Looping through each sibling_node and check sibling's children for sibling_node in current_generation: if sibling_node.searched == False: attempt_match_children(sibling_node, to_node) # If found match in current degree if path_found == True: return sibling_node # If none of the siblings in the level matched, move to higher degree if path_found == False: current_generation = child_generation child_generation = [] return path def main(): global current_generation start = time.time() #root = Node("<NAME>", "https://en.wikipedia.org/wiki/Kevin_Bacon") #target = Node("Neo-noir", "https://en.wikipedia.org/wiki/Hollywood") # Find/Check Valid Root and Target URL try: urlopen("https://en.wikipedia.org/wiki/" + args.fromtitle) print("https://en.wikipedia.org/wiki/" + args.fromtitle) print("https://en.wikipedia.org/wiki/" + args.totitle) urlopen("https://en.wikipedia.org/wiki/" + args.totitle) except HTTPError: print("HTTPError: Invalid Name") sys.exit(1) except URLError: print("URLError: Invalid Name") sys.exit(1) except ValueError: print("ValueError: Invalid Name") sys.exit(1) # Set-Up Nodes of Root and Target root = Node(args.fromtitle, "https://en.wikipedia.org/wiki/" + args.fromtitle) target = Node(args.totitle, "https://en.wikipedia.org/wiki/" + args.totitle) current_generation.append(root) determine_path(root, target) # Present Data path_names = [] for node in path: path_names.append(node.title) print(time.time() - start) print("Path: " + str(path_names)) print("Degree: " + str(degree)) # Visualization of Path if MAKE_GRAPH: for i, node in enumerate(path): G.add_node(node.title) if i > 0: G.add_edge(path[i-1].title, node.title) print(node.url) nx.draw(G, with_labels=True) if args.saveGraph: plt.savefig(args.saveGraph) #plt.savefig('../res/found_path.svg') else: plt.show() if __name__ == '__main__': main() <file_sep>/README.md # Six-Degrees-of-Wikipedia Six degrees of Kevin Bacon, but for Wikipedia. This is a webscraping project inspired by the six degrees of Kevin Bacon (also known as the six degrees of separation), where "all people are six, or fewer, social connections away from each other" (Wikipedia). This project determines the whether this rule also falls true with Wikipedia pages and their redirect links, finding the shortest path between two pages given their url input. ## Installation Not available as of now. ## Known Issues Code may take a significant amount of time to run beyond the 3rd degree. This is because each Wikipedia page has around 300~500 links and the runtime increases with each degree raised. ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. <file_sep>/requirements.txt beautifulsoup4==4.9.1 bs4==0.0.1 grequests==0.6.0 jsonschema==3.2.0 jupyter==1.0.0 jupyter-client==6.1.7 jupyter-console==6.2.0 jupyter-core==4.6.3 k==0.0.1 kiwisolver==1.2.0 lazy-object-proxy==1.4.3 lib50==2.0.8 lxml==4.5.2 matplotlib==3.3.1<file_sep>/src/test.py import requests import urllib.request from bs4 import BeautifulSoup, SoupStrainer from urllib.request import urlopen import numpy as np import json import time import sys # Experimenting with using MediaWiki API instead of BS4 url grab # avg time: 0.3 - 0.8 s, which is still kind of a feels-bad when ea page has 300-500 links # 100 trials: 30.61058211326599 s start = time.time() for i in range(1): response = urlopen("https://en.wikipedia.org/w/api.php?action=query&titles=" + "Title" + "&prop=links&pllimit=max&format=json") dab = time.time() DATA = json.loads(response.read()) print(DATA) #print(json.dumps(DATA, indent=4, sort_keys=True)) print(time.time() - dab) # Normal/Old method: using BS4: average ime 0.5-0.6. # 100 trials: 60.8656702041626 s """ start = time.time() only_a_tags = SoupStrainer("a", href=lambda href: href and href.startswith('/wiki/')) for i in range(100): response = urlopen("https://en.wikipedia.org/wiki/Bacon") soup = BeautifulSoup(response, 'html.parser', parse_only = only_a_tags) print(time.time() - start) """
8294e88b9f93637558ed6d793e59fb444ad7ce89
[ "Markdown", "Python", "Text" ]
4
Python
joyliu-q/Six-Degrees-of-Wikipedia
a96cabe4310b84671b9bed94d5e8a5e91c503469
6d408f059a5d842103297dbfa38cdcca3d0d181b
refs/heads/master
<repo_name>bermeitinger-b/nolearn_utils<file_sep>/nolearn_utils/hooks.py import pickle import numpy as np class EarlyStopping(object): """From https://github.com/dnouri/kfkd-tutorial""" def __init__(self, patience=50): self.patience = patience self.best_valid = np.inf self.best_valid_epoch = 0 self.best_params = None def __call__(self, nn, train_history): current_valid = train_history[-1]['valid_loss'] current_train = train_history[-1]['train_loss'] current_epoch = train_history[-1]['epoch'] # Ignore if training loss is greater than valid loss if current_train > current_valid: return if current_valid < self.best_valid: self.best_valid = current_valid self.best_valid_epoch = current_epoch self.best_params = nn.get_all_params_values() elif self.best_valid_epoch + self.patience <= current_epoch: print('Early stopping.') print('Best valid loss was {:.6f} at epoch {}.'.format( self.best_valid, self.best_valid_epoch)) nn.load_params_from(self.best_params) raise StopIteration() class StepDecay(object): """From https://github.com/dnouri/kfkd-tutorial""" def __init__(self, name, start=0.03, stop=0.001, delay=0): self.name = name self.delay = delay self.start, self.stop = start, stop self.ls = None def __call__(self, net, train_history): if self.ls is None: self.ls = np.linspace(self.start, self.stop, net.max_epochs - self.delay) epoch = train_history[-1]['epoch'] - self.delay if epoch >= 0: new_value = float32(self.ls[epoch - 1]) getattr(net, self.name).set_value(new_value) class SaveTrainingHistory(object): def __init__(self, path, verbose=0): self.path = path self.verbose = verbose def __call__(self, nn, train_history): with open(self.path, 'wb') as f: pickle.dump(train_history, f, -1) def float32(x): return np.cast['float32'](x)
0fe19dc31a818da482a036017abe437ad19d10d4
[ "Python" ]
1
Python
bermeitinger-b/nolearn_utils
8c14cb1de1d31425a8418f23d5ff9eae4c730521
e62a312682d1fa0fb1bcfa61a36ca8142d3fd22d
refs/heads/master
<repo_name>cendydwierianto/office_HR<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Interfaces/IAttendance.cs using TrillionBitsPortal.Common.Models; using System; using System.Collections.Generic; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Interfaces { public interface IAttendance { ResponseModel CheckIn(AttendanceEntryModel model); ResponseModel AddAttendanceAsLeave(AttendanceEntryModel model); ResponseModel CheckOut(AttendanceEntryModel model); ResponseModel SaveCheckPoint(UserMovementLogModel model); List<AttendanceModel> GetAttendanceFeed(int companyId,DateTime date); List<AttendanceModel> GetAttendance(int companyId, DateTime startDate, DateTime endDate); List<AttendanceModel> GetAttendance(string userId, int companyId, DateTime startDate, DateTime endDate); List<UserMovementLogModel> GetMovementDetails(string userId, DateTime date); AttendanceModel GetMyTodayAttendance(string userId, DateTime date); } } <file_sep>/hr Office/HrApp/components/Screen/leaves/LeaveList.js import React from 'react'; import { Platform, StatusBar, Dimensions, RefreshControl, TouchableOpacity, View, Text, FlatList, Image, ScrollView, ActivityIndicator,AsyncStorage } from 'react-native'; import { AppLoading, Asset, Font, Icon } from 'expo'; import { Actions } from 'react-native-router-flux'; import * as actions from '../../../common/actions'; import { GetLeaveList, LeaveApproved, LeaveRejected } from '../../../services/Leave'; import apiConfig from "../../../services/api/config"; import { LeaveListStyle } from './LeaveListStyle'; import { SearchBar } from 'react-native-elements'; import { CommonStyles } from '../../../common/CommonStyles'; import { AdMobBanner } from 'expo-ads-admob'; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar/> </View> ); } export default class LeaveList extends React.Component { constructor(props) { super(props); this.state = { leaveList: [], progressVisible: true, refreshing: false } this.arrayholder = []; } _onRefresh = async () =>{ this.setState({ refreshing: true}); setTimeout(function () { this.setState({ refreshing: false, userId:"", companyId:0, }); }.bind(this), 2000); this.getLeaveList(this.state.companyId,false); }; goBack() { Actions.pop(); } renderHeader = () => { return ( <SearchBar placeholder="Type Here..." style={{ position: 'absolute', zIndex: 1 }} lightTheme containerStyle={{backgroundColor:'#f6f7f9',}} inputContainerStyle={{ backgroundColor: 'white',}} round onChangeText={text => this.searchFilterFunction(text)} autoCorrect={false} value={this.state.value} /> ); }; searchFilterFunction = text => { this.setState({ value: text, }); const newData = this.arrayholder.filter(item => { const itemData = `${item.EmployeeName.toUpperCase()} ${item.EmployeeName.toUpperCase()} ${item.EmployeeName.toUpperCase()}`; const textData = text.toUpperCase(); return itemData.indexOf(textData) > -1; }); this.setState({ leaveList: newData, }); }; async componentDidMount() { const cId= await AsyncStorage.getItem("companyId"); this.setState({companyId:cId}); this.getLeaveList(cId,true); } getLeaveList = async (companyId,isProgress) => { try { this.setState({ progressVisible: isProgress }); await GetLeaveList(companyId) .then(res => { this.setState({ leaveList: res.result , progressVisible: false}); this.arrayholder=res.result; console.log(res.result,'leaveresultlist.............') }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); } catch (error) { this.setState({ progressVisible: false }); console.log(error); } } leaveApprove = async (item) => { const uId= await AsyncStorage.getItem("userId"); await LeaveApproved(item.Id,uId) .then(res => { this.getLeaveList(this.state.companyId,true); }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); } leaveReject = async (item) => { await LeaveRejected(item.Id) .then(res => { this.getLeaveList(this.state.companyId,true); }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); this.getLeaveList(this.state.companyId,true); } render() { var { width, height } = Dimensions.get('window'); return ( <View style={LeaveListStyle.container}> <StatusBarPlaceHolder /> <View style={CommonStyles.HeaderContent}> <View style={CommonStyles.HeaderFirstView}> <TouchableOpacity style={CommonStyles.HeaderMenuicon} onPress={() => { Actions.drawerOpen(); }}> <Image resizeMode="contain" style={CommonStyles.HeaderMenuiconstyle} source={require('../../../assets/images/menu_b.png')}> </Image> </TouchableOpacity> <View style={CommonStyles.HeaderTextView}> <Text style={CommonStyles.HeaderTextstyle}> LEAVE REQUESTS </Text> </View> </View> </View> <View style={{ flex: 1, }}> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={LeaveListStyle.loaderIndicator} />) : null} <ScrollView showsVerticalScrollIndicator={false}> <View style={{ flex: 1, }}> <FlatList refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> } data={this.state.leaveList} keyExtractor={(x, i) => i.toString()} renderItem={({ item }) => <View style={LeaveListStyle.listContainer} > <View style={{flexDirection:'row',borderBottomColor:'gray',borderBottomWidth:.4,padding:8,paddingLeft:0}}> <Text style={{fontFamily: 'Montserrat_SemiBold',fontSize:14}}>{item.EmployeeName}</Text> </View> <View style={LeaveListStyle.listInnerContainer}> <Text style={LeaveListStyle.leaveType}> Cause: </Text> <Text style={LeaveListStyle.leaveFrom}> From: </Text> </View> <View style={LeaveListStyle.leaveReasonContainer}> <Text style={[LeaveListStyle.leaveReasonText, { fontFamily: 'Montserrat_SemiBold' }]}> {item.LeaveReason} </Text> <Text style={LeaveListStyle.reasonFromDate}> {item.FromDateVw} </Text> </View> <View style={LeaveListStyle.causeContainer}> <Text style={LeaveListStyle.causeText}> Leave Type: </Text> <Text style={LeaveListStyle.leaveToText}> To: </Text> </View> <View style={LeaveListStyle.detailsContainer}> <Text style={LeaveListStyle.reasonFromDate}> {item.LeaveType} </Text> <Text style={LeaveListStyle.detailsTextInner}> {item.ToDateVw} </Text> </View> {(item.ApprovedBy != null && item.ApprovedBy != '') ? <View style={LeaveListStyle.approvedByContainer}> <Text style={LeaveListStyle.approvedByText}> Approved By: {item.ApprovedBy} </Text> <Text style={LeaveListStyle.approvedAtText}> Approved At: {item.ApprovedAtVw} </Text> </View> : null} <View style={LeaveListStyle.statusButton}> <View style={LeaveListStyle.statusButtonInner}> {item.IsApproved == true ? (<Text style={{ color: 'green', }}> Approved </Text>) : (item.IsRejected == true ? (<Text style={{ color: 'red', }}> Rejected </Text>) : (<Text style={{ color: '#f1b847', }}> Pending </Text>))} </View> <View style={LeaveListStyle.daysBox}> <Text style={LeaveListStyle.statusDate}> {item.LeaveInDays} Days </Text> </View> </View> </View> } ListHeaderComponent={this.renderHeader()} /> </View> </ScrollView> </View> <AdMobBanner bannerSize="fullBanner" adUnitID={apiConfig.bannerUnitId} onDidFailToReceiveAdWithError={this.bannerError} /> </View> ); } } <file_sep>/hr Office/HrApp/services/UserService/AccountService.js import {postApi, deleteApi, getApi } from "../api"; export const ChangePasswords = async data => postApi("User/changepassword", {}, data); export const ChangePasswordforEmp = async data => postApi("User/resetpassword", {}, data); export const Login = async data => postApi("RtAccountApi/LoginUser", {}, data); export const UpdateEmployee = async data => postApi("RtEmployeeApi/UpdateEmployee", {}, data); export const GetUserClaim = async (userKey) => getApi("RtAccountApi/GetUserClaims?userKey="+userKey, {}, {}); <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/LeavingReason.cs namespace TrillionBitsPortal.ResourceTracker.Models { public class LeavingReason { public int Id { get; set; } public string EmployeeUserId { get; set; } public string Description { get; set; } public string LeavingDateTime { get; set; } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/ResponseModel.cs  namespace TrillionBitsPortal.Common.Models { public class ResponseModel { public bool Success { get; set; } public string Message { get; set; } public string ReturnCode { get; set; } public int ReturnId { get; set; } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/ResourceTracker/RtDepartmentApiController.cs using System.Net; using System.Net.Http; using System.Web.Http; using TrillionBits.ResourceTracker; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.Web.Controllers.Api.ResourceTracker { public class RtDepartmentApiController : BaseApiController { private readonly IDepartment _departmentRepository; public RtDepartmentApiController() { _departmentRepository = RTUnityMapper.GetInstance<IDepartment>(); } [HttpGet] public HttpResponseMessage GetDepartmentByCompanyId(string companyId) { var result = _departmentRepository.GetDepartmentByCompanyId(companyId); return Request.CreateResponse(HttpStatusCode.OK, result); } [HttpPost] public IHttpActionResult Save(Department json) { var department = new Department { CompanyId = json.CompanyId, DepartmentName = json.DepartmentName, }; var response = _departmentRepository.Create(department, json.UserId); return Ok(response); } [HttpPost] public IHttpActionResult UpdateDepartment(Department json) { var department = new Department { Id = json.Id, CompanyId = json.CompanyId, DepartmentName = json.DepartmentName, }; var response = _departmentRepository.UpdateDepartment(department); return Ok(response); } } } <file_sep>/hr Office/HrApp/components/Screen/UserScreen/leaves/LeaveApply.js import React, { Component } from 'react'; import { Text, View, Platform, Image, StatusBar, ScrollView, Dimensions, BackHandler, TouchableOpacity, KeyboardAvoidingView, TextInput, AsyncStorage, ToastAndroid, NetInfo, } from 'react-native'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons' import { CommonStyles } from '../../../../common/CommonStyles'; import Modal from 'react-native-modalbox'; import { Actions, Scene } from 'react-native-router-flux'; import DatePicker from 'react-native-datepicker' import { LeaveApplyStyle, } from './LeaveApplyStyle'; import { LeaveListStyle } from './LeaveListStyle'; import moment from 'moment' import AntDesign from 'react-native-vector-icons/AntDesign' import { createLeave } from '../../../../services/UserService/Leave'; import { GetLeaveStatusList } from '../../../../services/UserService/Leave'; export default class LeaveApply extends Component { constructor(props) { super(props); this.state = { date: new Date(), date1: new Date(), CompanyId: "", UserId: "", LeaveApplyFrom: "", LeaveApplyTo: "", IsHalfDay: false, LeaveTypeId: "", LeaveReason: "", CreatedAt: new Date(), IsApproved: false, IsRejected: false, RejectReason: "", ApprovedById: null, ApprovedAt: null, leave: { LeaveArrayText: '', LeaveArrayValue: '', }, LeaveArray: [], } this.onDateChange = this.onDateChange.bind(this); this.onDateChange2 = this.onDateChange2.bind(this); } onDateChange2(date1) { this.setState({ date1: date1, }); dateValue1 = date1; } onDateChange(date) { this.setState({ date: date, }); dateValue = date; } getStatus = async () => { try { await GetLeaveStatusList() .then(res => { this.setState({ LeaveArray: res.result, }); console.log(res.result, "statusList"); }) .catch(() => { console.log("error occured"); }); } catch (error) { console.log(error); } } handleBackButton = () => { this.goBack(); return true; } goBack() { Actions.LeaveList(); } async componentDidMount() { this.getStatus(); const uId = await AsyncStorage.getItem("userId"); const cId = await AsyncStorage.getItem("companyId"); this.setState({ UserId: uId, CompanyId: cId }); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } LeaveTypeDropDown(value, text) { this.setState(Object.assign(this.state.leave, { LeaveArrayText: value })); this.setState(Object.assign(this.state.leave, { LeaveArrayValue: text })); this.refs.LeaveTypeModal.close() } async createLeave() { if (this.state.taskTitle !== "") { let leaveModel = { CompanyId: this.state.CompanyId, UserId: this.state.UserId, LeaveApplyFrom: moment(new Date(this.state.date)).format('YYYY-MM-DD HH:mm:ss a'), LeaveApplyTo: moment(new Date(this.state.date1)).format('YYYY-MM-DD HH:mm:ss a'), IsHalfDay: this.state.IsHalfDay, LeaveTypeId: this.state.leave.LeaveArrayText, LeaveReason: this.state.LeaveReason, CreatedAt: this.state.CreatedAt, IsApproved: this.state.IsApproved, IsRejected: this.state.IsRejected, RejectReason: this.state.RejectReason, ApprovedById: this.state.ApprovedById, ApprovedAt: this.state.ApprovedAt, }; console.log("leaveModel", leaveModel); if (leaveModel.LeaveTypeId != "") { if (leaveModel.LeaveReason != "") { let response = await createLeave(leaveModel); ToastAndroid.show('Leave applied successfully', ToastAndroid.TOP); this.goBack(); } else { ToastAndroid.show('Please Enter Reason', ToastAndroid.TOP); } } else { ToastAndroid.show('Please Enter Cause', ToastAndroid.TOP); } } } renderLeaveArrayList() { let content = this.state.LeaveArray.map((arraytext, i) => { arraytext return ( <TouchableOpacity style={{ paddingVertical: 7, borderBottomColor: '#D5D5D5', borderBottomWidth: 2 }} key={i} onPress={() => { this.LeaveTypeDropDown(arraytext.Id, arraytext.Name) }}> <Text style={LeaveApplyStyle.renderLeaveArrayListTextStyle} key={arraytext.Id}>{arraytext.Name} </Text> </TouchableOpacity> ) }); return content; } render() { var { width, height } = Dimensions.get('window'); return ( <View style={LeaveApplyStyle.container}> <View style={CommonStyles.HeaderContent}> <View style={CommonStyles.HeaderFirstView}> <TouchableOpacity style={CommonStyles.HeaderMenuicon} onPress={() => { this.goBack() }}> <Image resizeMode="contain" style={CommonStyles.HeaderMenuiconstyle} source={require('../../../../assets/images/left_arrow.png')}> </Image> </TouchableOpacity> <View style={CommonStyles.HeaderTextView}> <Text style={CommonStyles.HeaderTextstyle}> Leave Apply </Text> </View> </View> <View style={LeaveListStyle.ApplyButtonContainer}> <TouchableOpacity onPress={() => this.createLeave()} style={LeaveListStyle.ApplyButtonTouch}> <View style={LeaveListStyle.plusButton}> <MaterialCommunityIcons name="content-save" size={17.5} color="#ffffff" /> </View> <View style={LeaveListStyle.ApplyTextButton}> <Text style={LeaveListStyle.ApplyButtonText}> REQUEST </Text> </View> </TouchableOpacity> </View> </View> <View style={{ flex: 1 }}> <KeyboardAvoidingView behavior="padding" enabled style={{ flex: 1, }}> <ScrollView showsVerticalScrollIndicator={false} keyboardDismissMode="on-drag" style={{ flex: 1, }}> <View style={LeaveApplyStyle.mainBodyStyle}> <View style={LeaveApplyStyle.mainBodyTopStyle}> <Text style={LeaveApplyStyle.fromTextStyle}> from: </Text> <Text style={LeaveApplyStyle.toTextStyle}> To: </Text> </View> <View style={LeaveApplyStyle.datePickerRowStyle}> <View style={LeaveApplyStyle.datePickerLeftStyle}> <DatePicker date={this.state.date} style={LeaveApplyStyle.datePickerWidth} placeholder='Check Previous Date' mode="date" format="DD MMMM YYYY" confirmBtnText="Confirm" cancelBtnText="Cancel" showIcon={false} customStyles={{ dateInput: { borderRadius: 8, backgroundColor: "#f5f7fb", height: 30, width: '100%', marginRight: 25, }, dateText: { color: "#848f98", fontFamily: "Montserrat_SemiBold", fontWeight: "bold", fontStyle: "normal", padding: 5, } }} onDateChange={this.onDateChange} > </DatePicker> </View> <View style={LeaveApplyStyle.datePickerRightStyle}> <DatePicker date={this.state.date1} style={LeaveApplyStyle.datePickerWidth} placeholder='Check Previous Date' mode="date" format="DD MMMM YYYY" confirmBtnText="Confirm" cancelBtnText="Cancel" showIcon={false} customStyles={{ dateInput: { borderRadius: 8, backgroundColor: "#f5f7fb", height: 30, width: '100%', marginRight: 25, }, dateText: { color: "#848f98", fontFamily: "Montserrat_SemiBold", fontWeight: "bold", fontStyle: "normal", } }} onDateChange={this.onDateChange2} > </DatePicker> </View> </View> <View style={LeaveApplyStyle.leaveTypeRowStyle}> <Text style={LeaveApplyStyle.leaveTypeRowTextStyle}> Leave Type: </Text> </View> <View style={LeaveApplyStyle.leaveDropDownRow}> <TouchableOpacity style={LeaveApplyStyle.leaveDropDownStyle} onPress={() => this.refs.LeaveTypeModal.open()}> <Text style={LeaveApplyStyle.leaveDropDownText}> {this.state.leave.LeaveArrayValue == '' ? "Leave type" : this.state.leave.LeaveArrayValue} </Text> <AntDesign name="caretdown" style={LeaveApplyStyle.leaveDropDownIconStyle} size={14} color="#848f98"> </AntDesign> </TouchableOpacity> </View> <View style={LeaveApplyStyle.leaveCauseRow}> <Text style={LeaveApplyStyle.leaveCauseText}> Cause: </Text> </View> <View style={LeaveApplyStyle.leaveTextInputRow}> <TextInput style={LeaveApplyStyle.leaveCauseTextInputStyle} multiline={true} placeholderTextColor="#cbcbcb" placeholder="write cause here" autoCorrect={false} autoCapitalize="none" onChangeText={text => this.setState({ LeaveReason: text })} /> </View> </View> </ScrollView> </KeyboardAvoidingView> <Modal style={LeaveApplyStyle.leaveTypeModalMainStyle} position={"center"} ref={"LeaveTypeModal"} isDisabled={this.state.isDisabled} backdropPressToClose={false} onOpened={() => this.setState({ floatButtonHide: true })} onClosed={() => this.setState({ floatButtonHide: false })} swipeToClose={false}> <View> <View style={{ justifyContent: "space-between", flexDirection: "row" }}> <View style={{ alignItems: "flex-start" }}> </View> <View style={{ alignItems: "flex-end" }}> <TouchableOpacity style={{ padding: 5, }} onPress={() => this.refs.LeaveTypeModal.close()}> <AntDesign name="closecircle" size={30} color="black"> </AntDesign> </TouchableOpacity> </View> </View> <View // style={{ paddingVertical: 20, }} > <ScrollView showsVerticalScrollIndicator={false} style={{ height: (height * 50) / 100, }}> <View style={{ width: "100%" }} > {this.state.LeaveArray != null ? this.renderLeaveArrayList() : <Text>No Leave Selected</Text>} </View> </ScrollView> </View> </View> </Modal> </View> </View > ) } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Filters/ValidateUserAttribute.cs using System; using System.Web; using System.Web.Mvc; using TrillionBitsPortal.Common; namespace TrillionBitsPortal.Web.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public class ValidateUserAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpSessionStateBase session = filterContext.HttpContext.Session; var user = session[Constants.CurrentUser]; if (session != null && (((user == null) && (!session.IsNewSession)) || (session.IsNewSession))) { //send them off to the login page var url = new UrlHelper(filterContext.RequestContext); var loginUrl = url.Content("~/Account/RedirectToLogOff"); filterContext.HttpContext.Response.Redirect(loginUrl, true); } } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/ResourceTracker/RtEmployeeApiController.cs using TrillionBitsPortal.Common; using TrillionBitsPortal.Common.Models; using System; using System.Web.Http; using TrillionBits.ResourceTracker; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Models; using System.Linq; using System.Text; using System.Configuration; using System.Collections.Generic; using System.Threading.Tasks; namespace TrillionBitsPortal.Web.Controllers.Api.ResourceTracker { public class RtEmployeeApiController : BaseApiController { private readonly IEmployee _employeeRepository; private readonly IUserCredential _userCredential; public RtEmployeeApiController() { _employeeRepository = RTUnityMapper.GetInstance<IEmployee>(); _userCredential = RTUnityMapper.GetInstance<IUserCredential>(); } [HttpPost] public IHttpActionResult CreateEmployee(EmployeeRegistrationModel json) { if(json==null || json.CompanyId==0) return Ok(new { Success = false, Message = "Please create a company from setting menu." }); var model = new EmployeeRegistrationModel { Email = json.Email, PhoneNumber = json.PhoneNumber, Password = <PASSWORD>, UserName = json.UserName, Gender = json.Gender, UserFullName = json.UserFullName, UserType = json.UserType, Designation = json.Designation, DepartmentId = json.DepartmentId, CompanyId = json.CompanyId, IsAutoCheckPoint = json.IsAutoCheckPoint, AutoCheckPointTime = json.AutoCheckPointTime, MaximumOfficeHours = json.MaximumOfficeHours, OfficeOutTime = json.OfficeOutTime }; var response=CreateUser(model); if (!response.Success) return Ok(response); EmployeeUser empUser = new EmployeeUser { UserId = response.ReturnCode, UserName = model.UserFullName, PhoneNumber = model.PhoneNumber, Designation = model.Designation, DepartmentId = Convert.ToInt32(model.DepartmentId), CompanyId = model.CompanyId, IsAutoCheckPoint = model.IsAutoCheckPoint, AutoCheckPointTime = model.AutoCheckPointTime, MaximumOfficeHours = model.MaximumOfficeHours, OfficeOutTime = model.OfficeOutTime }; var userResponse = _employeeRepository.Create(empUser); return Ok(new { Success=true, Message = response.Message}); } private ResponseModel CreateUser(EmployeeRegistrationModel model) { var userModel = _userCredential.GetByLoginID(model.PhoneNumber, UserType.ResourceTrackerAdmin); if (userModel != null) return new ResponseModel { Message = "This mobile number already exists." }; var p = GeneratePassword(); var password = CryptographyHelper.CreateMD5Hash(p); var response = _userCredential.Save(new UserCredentialModel { FullName = model.UserFullName, UserTypeId = (int)UserType.ResourceTrackerUser, Email = model.Email, ContactNo = model.PhoneNumber, LoginID = model.PhoneNumber, IsActive = true, Password = <PASSWORD> }); if (response.Success) { Task.Run(() => SendMailToUser(model.Email,model.PhoneNumber, p)); } return new ResponseModel { Success = response.Success, Message = response.Success?p:string.Empty,ReturnCode=response.ReturnCode }; } public void SendMailToUser(string email,string loginID, string p) { if (string.IsNullOrEmpty(email)) return; var sb = new StringBuilder(); sb.Append(string.Format("Please download App from playstore.")); sb.Append(string.Format("<div></div>")); sb.Append(string.Format("<div>Your Login ID : {0}</div>", loginID)); sb.Append(string.Format("<div>Your Password : {0}</div>", p)); var recipient = new List<string> {email}; new Email(ConfigurationManager.AppSettings["AttndEmailSender"], ConfigurationManager.AppSettings["AttndEmailSender"], "Your User Credential", sb.ToString()).SendEmail(recipient, ConfigurationManager.AppSettings["AttndEmailSenderPassword"]); } private static string _numbers = "0123456789"; Random random = new Random(); private string GeneratePassword() { StringBuilder builder = new StringBuilder(6); string numberAsString = ""; for (var i = 0; i < 6; i++) { builder.Append(_numbers[random.Next(0, _numbers.Length)]); } numberAsString = builder.ToString(); return numberAsString; } [HttpDelete] public IHttpActionResult DeleteEmployee(string id) { var userResponse = _employeeRepository.Delete(id); return Ok(userResponse); } [HttpPost] public IHttpActionResult UpdateEmployee(PortalUserViewModel json) { var response = _employeeRepository.UpdateEmployee(json); return Ok(response); } [HttpGet] public IHttpActionResult GetEmployeeAsTextValue(int companyId) { var userResponse = _employeeRepository.GetEmployeeAsTextValue(companyId); return Ok(userResponse); } [HttpGet] public IHttpActionResult GetEmployeeByCompanyId(int companyId) { var userResponse = _employeeRepository.GetEmployeeByCompanyId(companyId); var data=(from x in userResponse select new { x.Id, x.UserId, x.UserName, x.PhoneNumber, x.MaximumOfficeHours, x.CompanyId, x.Designation, x.DepartmentId, x.DepartmentName, x.ImageFileId, x.ImageFileName, x.IsActive }); return Ok(data); } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/ResourceTracker/RtAccountApiController.cs using TrillionBitsPortal.Common; using TrillionBitsPortal.Web.Models; using System.Web.Http; using TrillionBits.ResourceTracker; using TrillionBitsPortal.ResourceTracker.Interfaces; namespace TrillionBitsPortal.Web.Controllers.Api.ResourceTracker { public class RtAccountApiController : BaseApiController { private readonly IEmployee _emplpoyeeRepository; private readonly IUserCredential _userCredential; public RtAccountApiController() { _emplpoyeeRepository = RTUnityMapper.GetInstance<IEmployee>(); _userCredential = RTUnityMapper.GetInstance<IUserCredential>(); } [HttpPost] [AllowAnonymous] public IHttpActionResult Register([FromBody]ResourceTrackerRegisterModel model) { if (ModelState.IsValid) { var userModel = _userCredential.GetByLoginID(model.PhoneNumber, UserType.ResourceTrackerAdmin); if (userModel != null) return BadRequest("This mobile number already exists."); var password = <PASSWORD>(model.Password); var response = _userCredential.Save(new Common.Models.UserCredentialModel { FullName = model.UserFullName, UserTypeId = (int)UserType.ResourceTrackerAdmin, Email = model.Email, ContactNo = model.PhoneNumber, LoginID = model.PhoneNumber, IsActive = true, Password = <PASSWORD> }); return Ok(response); } return BadRequest("Invalid model."); } [HttpPost] [AllowAnonymous] public IHttpActionResult Login([FromBody]ResourceTrackerLoginModel model) { if (ModelState.IsValid) { var password = <PASSWORD>Helper.<PASSWORD>(model.Password); var user = _userCredential.Get(model.UserName, password); if (user == null) return Ok(new { Success = false, message = "Invalid userid/password" }); int companyId = 0; if (user.UserTypeId == (int)UserType.ResourceTrackerUser) { var userProfileModel = _emplpoyeeRepository.GetByPortalUserId(user.Id); companyId = userProfileModel == null ? 0 : userProfileModel.CompanyId; } return Ok(new { Success = true, Token = TokenManager.GenerateToken(model.UserName), UserKey = user.Id, UserName = user.FullName, IsAdmin = user.UserTypeId == (int)UserType.ResourceTrackerAdmin, IsEmployee = user.UserTypeId == (int)UserType.ResourceTrackerUser, CompanyId = companyId }); } return BadRequest(); } [HttpPost] [AllowAnonymous] public IHttpActionResult LoginAdmin([FromBody]ResourceTrackerLoginModel model) { if (ModelState.IsValid) { var password = <PASSWORD>graphyHelper.CreateMD5Hash(model.Password); var user = _userCredential.GetByLoginID(model.UserName, password, UserType.ResourceTrackerAdmin); if (user == null) return Ok(new { Success = false, message = "Invalid userid/password" }); if (user.UserTypeId == (int)UserType.ResourceTrackerAdmin) return Ok(new { Success = true, Token = TokenManager.GenerateToken(model.UserName), UserKey = user.Id, UserName = user.FullName }); return Ok(new { Success = false, message = "Login failed" }); } return BadRequest(); } [HttpPost] [AllowAnonymous] public IHttpActionResult LoginUser([FromBody]ResourceTrackerLoginModel model) { if (ModelState.IsValid) { var password = <PASSWORD>graphyHelper.CreateMD5Hash(model.Password); var user = _userCredential.GetByLoginID(model.UserName, password, UserType.ResourceTrackerUser); if (user == null) return Ok(new { Success = false, message = "Invalid userid/password" }); if (user.UserTypeId == (int)UserType.ResourceTrackerUser) { var userProfileModel = _emplpoyeeRepository.GetByPortalUserId(user.Id); return Ok(new { Success = true, Token = TokenManager.GenerateToken(model.UserName), UserKey = user.Id, CompanyId = userProfileModel == null ? 0 : userProfileModel.CompanyId, UserName = user.FullName }); } return Ok(new { Success = false, message = "Login failed" }); } return BadRequest(); } [HttpGet] public ResourceTrackerRegisterModel GetUserClaims(string userKey) { var dd = _userCredential.GetProfileDetails(userKey); ResourceTrackerRegisterModel model = new ResourceTrackerRegisterModel() { Id = dd.Id, UserName = dd.LoginID, PhoneNumber = dd.ContactNo, Email = dd.Email, Gender = "Male", UserFullName = dd.FullName, UserType = dd.UserTypeId == (int)UserType.ResourceTrackerAdmin ? "admin" : "user" }; return model; } [HttpGet] [AllowAnonymous] public IHttpActionResult CheckExistPhone(string phoneno) { var userModel = _userCredential.GetByLoginID(phoneno, UserType.ResourceTrackerAdmin); if (userModel != null) return BadRequest("This mobile number already exists."); return Ok(new { Success = true}); } [HttpPost] public IHttpActionResult ChangePassword(LocalPasswordModel model) { if (ModelState.IsValid) { var password = CryptographyHelper.CreateMD5Hash(model.OldPassword); var user = _userCredential.GetByLoginID(model.UserName); if (user == null) return Ok(new { Success = false, Message = "Invalid userid/password." }); var response = _userCredential.ChangePassword(user.Id, CryptographyHelper.CreateMD5Hash(model.ConfirmPassword)); return Ok(response); } return Ok(new { Success = false, Message = "Oops!try again." }); } } } <file_sep>/hr Office/HrApp/components/Screen/notice/Notice.js import React from 'react'; import { Platform, StatusBar, Dimensions, RefreshControl, TouchableOpacity, View, Text, FlatList, Image, ScrollView, ActivityIndicator, AsyncStorage, Alert, BackHandler, } from 'react-native'; import { AppLoading, Asset, Font, Icon } from 'expo'; import { Actions } from 'react-native-router-flux'; import * as actions from '../../../common/actions'; import { NoticeStyle } from './NoticeStyle'; import { getNotice } from '../../../services/Notice'; import apiConfig from "../../../services/api/config"; import { CommonStyles } from '../../../common/CommonStyles'; import { SearchBar } from 'react-native-elements'; import { FontAwesome, } from '@expo/vector-icons'; import { AdMobBanner } from 'expo-ads-admob'; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar /> </View> ); } export default class Notice extends React.Component { constructor() { super(); this.state = { noticeList: [], companyId: 0, refreshing: false, } this.arrayholder = []; } goBack() { Actions.pop(); } goToDetail(item) { console.log(item, '.............item'); actions.push("NoticeDetail", { aItem: item }); }; goToCreateNotice() { actions.push("CreateNotice", {}); } _onRefresh = async () => { this.setState({ refreshing: true }); setTimeout(function () { this.setState({ refreshing: false, }); }.bind(this), 2000); this.getNoticeList(this.state.companyId, false); } async componentDidMount() { const cId = await AsyncStorage.getItem("companyId"); this.setState({ companyId: cId }); this.getNoticeList(cId, true); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillMount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } handleBackButton = () => { BackHandler.exitApp() return true; } searchFilterFunction = text => { this.setState({ value: text, }); const newData = this.arrayholder.filter(item => { const itemData = `${item.PostingDate.toUpperCase()} ${item.Details.toUpperCase()}`; const textData = text.toUpperCase(); return itemData.indexOf(textData) > -1; }); this.setState({ noticeList: newData, }); }; renderHeader = () => { return ( <SearchBar placeholder="Type Here..." style={{ position: 'absolute', zIndex: 1, marginBottom: 0 }} lightTheme containerStyle={{ backgroundColor: '#f6f7f9', }} inputContainerStyle={{ backgroundColor: 'white', }} round onChangeText={text => this.searchFilterFunction(text)} autoCorrect={false} value={this.state.value} /> ); }; getNoticeList = async (companyId, isProgress) => { try { this.setState({ progressVisible: isProgress }); await getNotice(companyId) .then(res => { this.setState({ noticeList: res.result, progressVisible: false }); this.arrayholder = res.result; console.log(res.result, '.....noticeresult'); }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); } catch (error) { this.setState({ progressVisible: false }); console.log(error); } } render() { return ( <View style={NoticeStyle.container}> <StatusBarPlaceHolder /> <View style={CommonStyles.HeaderContent}> <View style={CommonStyles.HeaderFirstView}> <TouchableOpacity style={CommonStyles.HeaderMenuicon} onPress={() => { Actions.drawerOpen(); }}> <Image resizeMode="contain" style={CommonStyles.HeaderMenuiconstyle} source={require('../../../assets/images/menu_b.png')}> </Image> </TouchableOpacity> <View style={CommonStyles.HeaderTextView}> <Text style={CommonStyles.HeaderTextstyle}> Notice Board </Text> </View> </View> <View style={NoticeStyle.createNoticeButtonContainer}> <View style={NoticeStyle.ApplyButtonContainer}> <TouchableOpacity onPress={() => this.goToCreateNotice()} style={NoticeStyle.ApplyButtonTouch}> <View style={NoticeStyle.plusButton}> <FontAwesome name="plus" size={18} color="#ffffff"> </FontAwesome> </View> <View style={NoticeStyle.ApplyTextButton}> <Text style={NoticeStyle.ApplyButtonText}> NOTICE </Text> </View> </TouchableOpacity> </View> </View> </View> <View style={{ flex: 1, }}> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={NoticeStyle.loaderIndicator} />) : null} <ScrollView refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> }> <View style={{ flex: 1, padding: 10, }}> <FlatList data={this.state.noticeList} keyExtractor={(x, i) => i.toString()} renderItem={({ item }) => <TouchableOpacity onPress={() => this.goToDetail(item)}> <View style={NoticeStyle.listContainer}> {item.ImageFileName === "" ? <View style={NoticeStyle.listDivider}> <View style={NoticeStyle.noticepart}> <Text style={{}}>{item.Details}</Text> </View> </View> : <View style={{ justifyContent: 'space-between', flexDirection: 'row', borderBottomColor: 'white', borderBottomWidth: 2, paddingBottom: 10, }}> <View style={{ alignItems: 'flex-start', width: '80%', color: '#1a1a1a', fontSize: 10, fontFamily: 'OPENSANS_REGULAR' }}> <Text style={{}}>{item.Details}</Text> </View> <View style={{ alignItems: 'flex-end', width: '20%', }}> <View style={{ borderRadius: 5, }}> {item.ImageFileName !== "" ? <Image resizeMode="cover" style={NoticeStyle.noticelistImage} source={{ uri: "http://medilifesolutions.blob.core.windows.net/resourcetracker/" + item.ImageFileName }} /> : <Text></Text>} </View> </View> </View>} <View style={NoticeStyle.dateContainer}> <View style={{ alignItems: 'flex-start', }}> <Text style={NoticeStyle.postedtextStyle}> Posted Date </Text> </View> <View style={{ alignItems: 'flex-end', }}> <Text style={NoticeStyle.createDateStyle}> {item.CreateDate} </Text> </View> </View> </View> </TouchableOpacity> } ListHeaderComponent={this.renderHeader()} /> </View> </ScrollView> </View> <AdMobBanner bannerSize="fullBanner" adUnitID={apiConfig.bannerUnitId} onDidFailToReceiveAdWithError={this.bannerError} /> </View> ); } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Interfaces/IEmployeeLeave.cs using TrillionBitsPortal.Common.Models; using System.Collections.Generic; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Interfaces { public interface IEmployeeLeave { List<EmployeeLeaveModel> GetLeaveByCompanyId(string companyId); List<EmployeeLeaveModel> GetUserLeaves(string userId); List<EmployeeLeaveModel> GetLeaveById(int id); ResponseModel CreateEmployeeLeave(EmployeeLeaveModel model); ResponseModel Approved(int id, string userId); ResponseModel Rejected(int id); } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Interfaces/INoticeBoard.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Interfaces { public interface INoticeBoard { List<NoticeBoard> GetNoticeBoardByCompanyId(int companyId); NoticeBoard GetNoticeBoardById(string noticeId); NoticeDepartmentVIewModel CreateNoticeBoard(NoticeDepartmentVIewModel model); } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Mappers/CommonMapper.cs using TrillionBitsPortal.Common; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Diagnostics; namespace TrillionBitsPortal.ResourceTracker.Mappers { public class CommonMapper { public List<RowsCount> ToPostDetailCountModel(DbDataReader readers) { if (readers == null) return null; var models = new List<RowsCount>(); while (readers.Read()) { var model = new RowsCount { Rows = Convert.ToInt32(readers["CountRows"]), }; models.Add(model); } return models; } public List<StringReturnModel> ToStringReturnModel(DbDataReader readers) { if (readers == null) return null; var models = new List<StringReturnModel>(); while (readers.Read()) { var model = new StringReturnModel { Value = Convert.ToString(readers["Name"]), }; models.Add(model); } return models; } public List<Dictionary<string, object>> ModelDataCollection(DbDataReader readers) { if (readers == null) return null; List<Dictionary<string, object>> dictionaries = new List<Dictionary<string, object>>(); List<string> strs = new List<string>(); for (int i = 0; i < readers.FieldCount; i++) { strs.Add(readers.GetName(i)); } while (readers.Read()) { dictionaries.Add(GetFields(strs, readers)); } return dictionaries; } [DebuggerStepThrough] public List<T> LoadModelCollection<T>(string cmdText, params object[] parameters) where T : class { return LoadModelCollection<T>(cmdText, CommandType.Text, parameters); } [DebuggerStepThrough] public List<T> LoadModelCollection<T>(string cmdText, CommandType cmdType, params object[] parameters) where T : class { return this.LoadModelCollection<T>(null, cmdText, cmdType, parameters); } [DebuggerStepThrough] public List<T> LoadModelCollection<T>(DbUtil.OverrideModel<T> mapFunc, string cmdText, params object[] parameters) where T : class { return LoadModelCollection<T>(mapFunc, cmdText, CommandType.Text, parameters); } //[DebuggerStepThrough] //public List<T> LoadModelCollection<T>(DbUtil.OverrideModel<T> mapFunc, string cmdText, CommandType cmdType, params object[] parameters) //where T : class //{ // List<T> ts; // IDataReader dataReader = null; // try // { // dataReader = base.ExecuteReader(cmdText, cmdType, parameters); // ts = this.LoadModelCollection<T>(dataReader, mapFunc); // } // catch (Exception exception) // { // throw exception; // } // finally // { // dataReader.CloseReader(); // } // return ts; //} [DebuggerStepThrough] public List<T> LoadModelCollection<T>(IDataReader reader) where T : class { return this.LoadModelCollection<T>(reader, null); } [DebuggerStepThrough] public List<T> LoadModelCollection<T>(IDataReader reader, DbUtil.OverrideModel<T> mapFunc) where T : class { if (!typeof(T).IsBaseModel()) { throw new Exception("Item must be inherited from BaseModel class."); } List<T> ts = new List<T>(); while (reader.Read()) { Dictionary<string, object> fields = GetFields(reader); ts.Add((mapFunc.IsNotNull() ? mapFunc(fields) : CreateModel<T>(fields))); } return ts; } private static T CreateModel<T>(Dictionary<string, object> fields) { T t = Activator.CreateInstance<T>(); PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(t); foreach (KeyValuePair<string, object> field in fields) { PropertyDescriptor propertyDescriptor = properties.Find(field.Key, true); if (propertyDescriptor.IsNull()) { continue; } object obj = field.Value.MapField(propertyDescriptor.PropertyType); propertyDescriptor.SetValue(t, obj); } PropertyDescriptor propertyDescriptor1 = properties.Find("State", true); if (propertyDescriptor1.IsNotNull()) { propertyDescriptor1.SetValue(t, ModelState.Unchanged); } return t; } private static Dictionary<string, object> GetFields(IDataRecord reader) { int fieldCount = reader.FieldCount; Dictionary<string, object> strs = new Dictionary<string, object>(fieldCount); for (int i = 0; i < fieldCount; i++) { string name = reader.GetName(i); int ordinal = reader.GetOrdinal(name); strs[name] = reader.GetValue(ordinal); } return strs; } private static Dictionary<string, object> GetFields(IEnumerable<string> cols, IDataRecord reader) { DateTime dateTime; Dictionary<string, object> strs = new Dictionary<string, object>(); foreach (string col in cols) { int ordinal = reader.GetOrdinal(col); string dataTypeName = reader.GetDataTypeName(ordinal); object value = reader.GetValue(ordinal); if (value.IsNullOrDbNull()) { strs[col] = value; } else if (dataTypeName == "bigint") { strs[col] = value.ToString(); } else if (dataTypeName == "date") { dateTime = (DateTime)value; strs[col] = dateTime.ToString(Util.ConvertedDateFormat); } else if (dataTypeName == "datetime") { dateTime = (DateTime)value; strs[col] = dateTime.ToString(string.Concat(Util.ConvertedDateFormat, " hh:mm:ss tt")); } else if (dataTypeName == "time") { dateTime = DateTime.MinValue.Add((TimeSpan)value); strs[col] = dateTime.ToString("hh:mm tt"); } else { strs[col] = value; } } return strs; } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/CompanyListModel.cs using TrillionBitsPortal.Common; using System; namespace TrillionBitsPortal.ResourceTracker.Models { public class CompanyListModel { public int Id { get; set; } public string CompanyName { get; set; } public string Address { get; set; } public string OfficePhone { get; set; } public string ContactPerson { get; set; } public string ContactPersonMobile { get; set; } public string Country { get; set; } public DateTime? CreatedDate { get; set; } public string CreatedAt { get { return CreatedDate.HasValue ? CreatedDate.Value.ToZoneTimeBD().ToString(Constants.DateTimeLongFormat) : string.Empty; } } public int TotalEmployee { get; set; } public string Email { get; set; } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Mappers/LeavingReasonMapper.cs using System; using System.Collections.Generic; using System.Data.Common; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Mappers { public static class LeavingReasonMapper { public static List<LeavingReason> ToLeavingReasonModel(DbDataReader readers) { if (readers == null) return null; var models = new List<LeavingReason>(); while (readers.Read()) { var model = new LeavingReason { Id = Convert.ToInt32(readers["Id"]), EmployeeUserId = Convert.IsDBNull(readers["DepartmentName"]) ? string.Empty : Convert.ToString(readers["DepartmentName"]), Description = Convert.IsDBNull(readers["Description"]) ? string.Empty : Convert.ToString(readers["Description"]), LeavingDateTime = Convert.IsDBNull(readers["LeavingDateTime"]) ? string.Empty : Convert.ToDateTime(readers["LeavingDateTime"]).ToString(), }; models.Add(model); } return models; } } }<file_sep>/hr Office/HrApp/services/api/config.js export const urlDev = "http://192.168.0.131:5087//api/ResourceTracker/"; export var initialUrl = urlDev; export default { clientId: "<KEY>", url: initialUrl, bannerUnitId:"", interstitialUnitId:"", rewardedUnitId:"" }; <file_sep>/hr Office/HrApp/components/Screen/UserScreen/myPanel/MyPanel.js import React, { Component } from 'react'; import { Actions } from 'react-native-router-flux'; import Modal from 'react-native-modalbox'; import Timeline from 'react-native-timeline-flatlist' import * as ImagePicker from 'expo-image-picker'; import Constants from 'expo-constants'; import * as Location from 'expo-location'; import * as Permissions from 'expo-permissions'; // import Geocoder from 'react-native-geocoding'; import Geocoder from 'react-native-geocoder'; //import RNAndroidLocationEnabler from 'react-native-android-location-enabler'; import { MyPanelStyle } from './MyPanelStyle'; import { loadFromStorage, storage, CurrentUserProfile } from "../../../../common/storage"; const options = { title: 'Select', // customButtons: [{ name: 'fb', title: 'Choose Photo from Facebook' }], storageOptions: { skipBackup: true, path: 'images', }, }; import { Platform, PermissionsAndroid, ScrollView, Text, View, Image, NetInfo, StatusBar, ActivityIndicator, ToastAndroid, RefreshControl, Alert, TextInput, TouchableOpacity, BackHandler, AsyncStorage, StyleSheet, } from 'react-native'; import AntDesign from 'react-native-vector-icons/AntDesign' import Entypo from 'react-native-vector-icons/Entypo' import Geolocation from 'react-native-geolocation-service'; //import { Location, Permissions, Constants, Svg, ImagePicker, } from 'expo'; import { CheckIn, CheckOut, CheckPoint, GetMyTodayAttendance, GetMovementDetails, } from '../../../../services/UserService/EmployeeTrackService'; import { UpdateEmployee } from '../../../../services/UserService/AccountService' import { NoticeStyle } from '../../notice/NoticeStyle' import { DailyAttendanceCombo, } from '../../../MenuDrawer/DrawerContent'; // const { Circle, Line, } = Svg; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar // barStyle="light-content" /> </View> ); } export default class MyPanel extends Component { constructor(props) { super(props); this.state = { progressVisible: false, refreshing: false, gps: false, svgLinHeight: 60 * 0 - 60, touchabledisable: false, errorMessage: "", location: "", touchabledisablepointcheckin: false, touchabledisablepoint: false, touchabledisablepointcheckout: false, attendanceModel: null, EmpTrackList: [], AttendanceDateVw: "", CheckInTimeVw: "", CheckOutTimeVw: "", DepartmentName: "", Designation: "", EmployeeName: "", IsCheckedIn: false, IsCheckedOut: false, OfficeStayHour: "", Status: "", image: null, UserId: "", Latitude: null, Longitude: null, LogLocation: null, // DeviceName: Constants.deviceName, DeviceOSVersion: Platform.OS === 'ios' ? Platform.systemVersion : Platform.Version, CompanyId: "", Reason: "", ImageFileName: "", mobile: '', name: '', gmail: '', Imageparam: "resourcetracker", ImageFileId: "", EmployeeId: 0, data: [], location: null, currentLongitude: 'unknown',//Initial Longitude currentLatitude: 'unknown',//Initial Latitude myApiKey: "<KEY>", pointcheck:"", } } _onRefresh = async () => { this.setState({ refreshing: true }); setTimeout(function () { this.setState({ refreshing: false, }); }.bind(this), 2000); //s this._getLocationAsyncforgps(); this.getMyTodayAttendance(this.state.UserId); }; closeModalEditProfile() { this.updateEmployeeRecords(); } openModalEditProfile() { this.refs.modalEditEmp.open() } openmodalForImage() { this.refs.modalForImage.open(); } openmodalForprofileImg() { this._takePhoto(); } _takePhoto = async () => { this.refs.modalForImage.close() await Permissions.askAsync(Permissions.CAMERA_ROLL); await Permissions.askAsync(Permissions.CAMERA); let pickerResult = await ImagePicker.launchCameraAsync({ allowsEditing: true, // aspect: [4, 4], //quality: .2, height: 250, width: 250, }); console.log(pickerResult, '.......................') if (pickerResult.cancelled == false) { this.handleUploadPhoto(pickerResult) } }; handleUploadPhoto = async (pickerResult) => { const userToken = await AsyncStorage.getItem("userToken"); console.log(pickerResult.uri, '...............send') var data = new FormData(); data.append('my_photo', { uri: pickerResult.uri, name: 'my_photo.jpg', type: 'image/jpg' }) this.setState({ progressVisible: true }); fetch("https://medilifesolutions.com/api/AzureFileStorageApi/Upload?containerName=" + this.state.Imageparam, { headers: { 'Authorization': `bearer ${userToken}`, 'Accept': 'application/json', 'Content-Type': 'multipart/form-data' }, method: "POST", body: data }) .then(response => response.json()) .then(response => { console.log("upload succes", response); this.setState({ image: "https://medilifesolutions.blob.core.windows.net/resourcetracker/" + response.ReturnCode }); this.setState({ ImageFileName: response.ReturnCode }); this.setState({ progressVisible: false }); ToastAndroid.show('Uploaded successfully', ToastAndroid.TOP); console.log(response.ReturnCode, 'return..............'); //this.updateEmployeeRecords(); this.setState({ photo: null }); }) .catch(error => { console.log("upload error", error); ToastAndroid.show('Upload Fail', ToastAndroid.TOP); }); }; _pickImage = async () => { this.refs.modalForImage.close() await Permissions.askAsync(Permissions.CAMERA_ROLL); await Permissions.askAsync(Permissions.CAMERA); let pickerResult = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, //aspect: [4, 4], quality: 1, height: 250, width: 250, }); if (pickerResult.cancelled == false) { this.handleUploadPhoto(pickerResult) } }; async updateEmployeeRecords() { let data = { UserFullName: this.state.EmployeeName, DesignationName: this.state.Designation, Id: this.state.EmployeeId, ImageFileName: this.state.ImageFileName, ImageFileId: this.state.ImageFileId, }; console.log('data...', data); try { let response = await UpdateEmployee(data); this.setState({ successMessage: response.result.message }); if (response && response.isSuccess) { this.refs.modalEditEmp.close() this.getMyTodayAttendance(this.state.UserId); console.log(response.result, '.....update.....') } else { alert(response.result); Alert.alert( "", response.result.message, [ { text: 'OK', }, ], { cancelable: false } ) } } catch (errors) { Alert.alert( "", "data does not saved", [ { text: 'OK', }, ], { cancelable: false } ) } } async componentDidMount() { global.DrawerContentId = 3; const uId = await AsyncStorage.getItem("userId"); this.setState({ UserId: uId }); const comId = await AsyncStorage.getItem("companyId"); var response = await loadFromStorage(storage, CurrentUserProfile); console.log(response, 'Response.............for............Emp') await this.setState({ name: response.item.UserFullName }); await this.setState({ mobile: response.item.PhoneNumber }); await this.setState({ gmail: response.item.Email }); this.setState({ CompanyId: comId }); // this.getEmpTrackingTodayList(); this.getMyTodayAttendance(uId); // this._getLocationAsyncforgps(); // this.interval = setInterval(() => this.getCheckPoint(), 3000000); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } getData(currentLatitude, currentLongitude) { var pos = { latitude: parseFloat(currentLatitude), longitude: parseFloat(currentLongitude), }; Location.reverseGeocodeAsync(pos).then(res => { let addressformate = res[0].street +", "+ res[0].city+", "+ res[0].country if(this.state.pointcheck=="CheckIn"){ this. createCheckingIn(currentLatitude, currentLongitude,addressformate); }else if(this.state.pointcheck=="CheckPoint"){ this.createCheckPoint(currentLatitude, currentLongitude,addressformate); }else{ this.createCheckOut(currentLatitude, currentLongitude,addressformate); } this.setState({ LogLocation: addressformate, }); console.log(res, 'position ready'); // alert(res[0].formattedAddress); }) .catch(error => alert(error)); } componentWillUnmount() { clearInterval(this.interval); Geolocation.clearWatch(this.watchID); BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } handleBackButton = () => { BackHandler.exitApp() return true; } goBack() { DailyAttendanceCombo(); } getMyTodayAttendance = async (cId) => { this.setState({ progressVisible: true }); await GetMyTodayAttendance(cId) .then(res => { this.setState({ attendanceModel: res.result, }); this.setState({ EmployeeName: res.result.EmployeeName, }); this.setState({ DepartmentName: res.result.DepartmentName, }); this.setState({ Designation: res.result.Designation, }); this.setState({ CheckInTimeVw: res.result.CheckInTimeVw, }); this.setState({ CheckOutTimeVw: res.result.CheckOutTimeVw, }); this.setState({ OfficeStayHour: res.result.OfficeStayHour, }); this.setState({ IsCheckedIn: res.result.IsCheckedIn, }); this.setState({ IsCheckedOut: res.result.IsCheckedOut, }); this.setState({ Status: res.result.Status, }); this.setState({ EmployeeId: res.result.EmployeeId, }); this.setState({ ImageFileName: res.result.ImageFileName, }); console.log("attendanceModel", res.result); console.log('IsCheckedIn', this.state.IsCheckedIn); this.setState({ progressVisible: false }); }).catch(() => { this.setState({ progressVisible: false }); console.log("GetMyTodayAttendance error occured"); }); this.setState({ progressVisible: true }); await GetMovementDetails(cId) .then(res => { // this.setState({data: null }); this.setState({ EmpTrackList: res.result }); if (this.state.data.length != 0) { this.setState({ data: [] }); } res.result.map((userData) => { var title = ''; var color = ''; if (userData.IsCheckInPoint) { title = "Checked In"; color = "green" } else if (userData.IsCheckOutPoint) { title = "Checked Out"; color = "red" } else { title = "Checked point"; color = "gray" } var myObj = { "time": userData.LogTimeVw, "title": title, "description": userData.LogLocation, "circleColor": color }; this.state.data.push(myObj); }) console.log(this.state.data, 'location@@@@@@@@@@@@@@@@@@'); this.setState({ progressVisible: false }); console.log('EmpTrackList........', this.state.EmpTrackList); }).catch(() => { this.setState({ progressVisible: false }); console.log("GetMovementDetails error occured"); }); } getLoction = async () => { // var that = this; //Checking for the permission just after component loaded if (Platform.OS === 'android' && !Constants.isDevice) { this.setState({ errorMessage: 'Oops, this will not work on Sketch in an Android emulator. Try it on your device!', }); ToastAndroid.show(errorMessage, ToastAndroid.TOP); } else { await this._getLocationAsync(); } } callLocation(that) { //alert("callLocation Called"); Geolocation.getCurrentPosition( //Will give you the current location (position) => { console.log(position, 'test positions') const currentLongitude = JSON.stringify(position.coords.longitude); //getting the Longitude from the location json const currentLatitude = JSON.stringify(position.coords.latitude); this.setState({ UserId: this.state.UserId, Latitude: currentLatitude, Longitude: currentLongitude, // LogLocation: emplocation.name + "," + emplocation.street + "," + emplocation.city, DeviceName: this.state.DeviceName, DeviceOSVersion: this.state.DeviceOSVersion, CompanyId: this.state.CompanyId, Reason: this.state.Reason, }); console.log(this.state.Latitude, 'test positions...........') console.log(this.state.Longitude, 'test positions...........') //getting the Latitude from the location json that.setState({ currentLongitude: currentLongitude }); //Setting state Longitude to re re-render the Longitude Text that.setState({ currentLatitude: currentLatitude }); //Setting state Latitude to re re-render the Longitude Text }, (error) => alert(error.message), { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 } ); } _getLocationAsync = async () => { let { status } = await Permissions.askAsync(Permissions.LOCATION); if (status !== 'granted') { ToastAndroid.show(errorMessage, ToastAndroid.TOP); this.setState({ errorMessage: 'Permission to access location was denied', }); } await Location.getCurrentPositionAsync({ enableHighAccuracy: false, timeout: 20000, maximumAge: 0, distanceFilter: 10 }).then((position)=>{ console.log(position, 'test positions'); const currentLongitude = JSON.stringify(position.coords.longitude); //getting the Longitude from the location json const currentLatitude = JSON.stringify(position.coords.latitude); //getting the Latitude from the location json this.setState({ Latitude: currentLongitude }); //Setting state Longitude to re re-render the Longitude Text this.setState({ Longitude: currentLatitude }); //Setting state Latitude to re re-render the Longitude Text this.getData(currentLatitude, currentLongitude); }); // var pos = { // latitude: location.coords.latitude, // longitude: location.coords.longitude, // }; // let location2 = await Location.reverseGeocodeAsync(pos); // let emplocation = location2[0]; // const currentLongitude = JSON.stringify(location.coords.longitude); // const currentLatitude = JSON.stringify(location.coords.latitude); // console.log(emplocation, 'emplocation.....emp'); // this.setState({ // UserId: this.state.UserId, // Latitude: currentLatitude, // Longitude: currentLongitude, // LogLocation: emplocation.name + "," + emplocation.street + "," + emplocation.city, // DeviceName: this.state.DeviceName, // DeviceOSVersion: this.state.DeviceOSVersion, // CompanyId: this.state.CompanyId, // Reason: this.state.Reason, // }); // this.getData(currentLatitude, currentLongitude) }; _getLocationAsyncforgps = async () => { navigator.geolocation.getCurrentPosition( (position) => { alert(hoice) this.setState({ latitude: position.coords.latitude, longitude: position.coords.longitude, error: null, }); }, (error) => this.setState({ error: error.message }), { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }, ); } renderTrackList() { return ( <View style={styles.container}> <Timeline style={styles.list} data={this.state.data} circleSize={20} circleColor={"circleColor"} lineColor='rgb(45,156,219)' timeContainerStyle={{ minWidth: 52, marginTop: -5 }} timeStyle={{ textAlign: 'center', backgroundColor: '#ff9797', color: 'white', padding: 5, borderRadius: 13, marginTop: 5, }} descriptionStyle={{ color: 'gray' }} options={{ style: { paddingTop: 5 } }} innerCircle={'dot'} /> </View> ) } async createCheckingIn(Latitude,Longitude,loglocation) { try { const TrackingModel = { UserId: this.state.UserId, Latitude: Latitude, Longitude: Longitude, LogLocation: loglocation, DeviceName: this.state.DeviceName, DeviceOSVersion: this.state.DeviceOSVersion, CompanyId: this.state.CompanyId }; this.state.progressVisible = true; const response = await CheckIn(TrackingModel); if (response && response.isSuccess) { console.log("createCheckingIn response", response) // this.getEmpTrackingTodayList(); this.getMyTodayAttendance(this.state.UserId); this.state.progressVisible = false } else { ToastAndroid.show('Something went wrong', ToastAndroid.TOP); this.state.progressVisible = false; } } catch (errors) { console.log("createCheckingIn Errors", errors); this.state.progressVisible = false; } } createCheckPoint = async (Latitude,Longitude,loglocation) => { try { this.setState({ progressVisible: true }); const TrackingModel = { UserId: this.state.UserId, Latitude: Latitude, Longitude: Longitude, LogLocation: loglocation, DeviceName: this.state.DeviceName, DeviceOSVersion: this.state.DeviceOSVersion, CompanyId: this.state.CompanyId }; console.log("TrackingModel response", TrackingModel) const response = await CheckPoint(TrackingModel); if (response && response.isSuccess) { console.log("createCheckPoint response", response) // this.getEmpTrackingTodayList(); this.getMyTodayAttendance(this.state.UserId); this.state.progressVisible = false; } else { ToastAndroid.show('Something went wrong', ToastAndroid.TOP); this.state.progressVisible = false; } } catch (errors) { console.log("createCheckPoint Errors", errors); this.state.progressVisible = false; } } async createCheckOut(Latitude,Longitude,loglocation) { try { const TrackingModel = { UserId: this.state.UserId, Latitude: Latitude, Longitude: Longitude, LogLocation: loglocation, DeviceName: this.state.DeviceName, DeviceOSVersion: this.state.DeviceOSVersion, CompanyId: this.state.CompanyId }; const response = await CheckOut(TrackingModel) this.state.progressVisible = true; console.log("CheckOut TrackingModel", TrackingModel); if (response && response.isSuccess) { console.log("createCheckOut response", response) // this.getEmpTrackingTodayList(); this.getMyTodayAttendance(this.state.UserId); this.state.progressVisible = false; } else { ToastAndroid.show('Something went wrong', ToastAndroid.TOP); this.state.progressVisible = false; } } catch (errors) { console.log("createCheckOut Errors", errors); this.state.progressVisible = false; } } getCheckIn = async () => { this.setState({ pointcheck:"CheckIn"}); this.setState({ touchabledisablepointcheckin: true, }); // if (await NetInfo.isConnected.fetch()) { this.setState({ touchabledisable: true, progressVisible: true }); console.log('check for getCheckIn', this.state.IsCheckedIn); if (this.state.IsCheckedOut === false) { if (this.state.IsCheckedIn === false) { this.setState({ progressVisible: true, }); await this.getLoction(); this.setState({ touchabledisablepointcheckin: false, }); } else { this.setState({ progressVisible: false }); this.setState({ touchabledisablepointcheckin: false, }); ToastAndroid.show('You have already checked in today', ToastAndroid.TOP); } } else { this.setState({ progressVisible: false }); this.setState({ touchabledisablepointcheckin: false, }); ToastAndroid.show('You have already checked out today', ToastAndroid.TOP); } // } else { // ToastAndroid.show("No Internet Detected", ToastAndroid.TOP); // } } getCheckOut = async () => { this.setState({ pointcheck:"CheckOut"}); this.setState({ touchabledisablepointcheckout: true, }); this.setState({ touchabledisable: true, progressVisible: true }); console.log('check for getCheckOut', this.state.IsCheckedOut); if (this.state.IsCheckedOut == false) { if (this.state.IsCheckedIn === true && this.state.IsCheckedOut == false) { this.setState({ progressVisible: false, }); await this.getLoction(); } else { this.setState({ progressVisible: false }); this.setState({ touchabledisablepointcheckout: false, }); ToastAndroid.show('You have not checked in today', ToastAndroid.TOP); } } else { this.setState({ progressVisible: false }); this.setState({ touchabledisablepointcheckout: false, }); ToastAndroid.show('You have already checked out today', ToastAndroid.TOP); } } getCheckPoint = async () => { this.setState({ pointcheck:"CheckPoint"}); this.setState({ touchabledisablepoint: true, }); this.setState({ progressVisible: true }); this.setState({ touchabledisable: true, }); console.log('check for getCheckPoint', this.state.IsCheckedIn); if (this.state.IsCheckedOut === false) { if (this.state.IsCheckedIn === true && this.state.IsCheckedOut == false) { this.getLoction(); // console.log("clicked"); this.setState({ progressVisible: false }); this.setState({ touchabledisablepoint: false, }); } else { this.setState({ progressVisible: false }); ToastAndroid.show('You have not checked in today', ToastAndroid.TOP); this.setState({ progressVisible: false }); this.setState({ touchabledisablepoint: false, }); } } else { this.setState({ progressVisible: false }); ToastAndroid.show('You have already checked out today', ToastAndroid.TOP); this.setState({ progressVisible: false }); this.setState({ touchabledisablepoint: false, }); } } renderTimeStatusList() { return ( <View style={MyPanelStyle.TimeInfoBar}> <View style={MyPanelStyle.First2TimePanelView}> <View style={MyPanelStyle.AllTimePanelRow}> <Text> {this.state.CheckInTimeVw ? (<AntDesign name="arrowdown" size={18} color="#07c15d" style={{ marginTop: 3, }} />) : (<Text style={MyPanelStyle.TimeStatusText}> NOT YET </Text>) } </Text> <Text style={MyPanelStyle.CheckedInText}> {this.state.CheckInTimeVw} </Text> </View> <View style={MyPanelStyle.AllTimePanelRow}> <Text style={MyPanelStyle.TimeStatusText}> CHECKED IN </Text> </View> </View> <View style={MyPanelStyle.First2TimePanelView}> <View style={MyPanelStyle.AllTimePanelRow}> <Text> {this.state.OfficeStayHour ? (<Entypo name="stopwatch" size={17} color="#a1b1ff" style={{ marginTop: 2, marginRight: 2, }} />) : (<Text style={MyPanelStyle.TimeStatusText}> NOT YET </Text>) } </Text> <Text style={MyPanelStyle.WorkingTimeText}> {this.state.OfficeStayHour} </Text> </View> <View style={MyPanelStyle.AllTimePanelRow}> <Text style={MyPanelStyle.TimeStatusText}> WORKING TIME </Text> </View> </View> <View style={MyPanelStyle.Last1TimePanelView}> <View style={MyPanelStyle.AllTimePanelRow}> <Text> {this.state.OfficeStayHour ? (<AntDesign name="arrowup" size={18} style={{ marginTop: 3, }} color="#a1d3ff" />) : (<Text style={MyPanelStyle.TimeStatusText}> NOT YET </Text>) } </Text> <Text style={MyPanelStyle.CheckedOutText}> {this.state.CheckOutTimeVw} </Text> </View> <View style={MyPanelStyle.AllTimePanelRow}> <Text style={MyPanelStyle.TimeStatusText}> CHECKED OUT </Text> </View> </View> </View> ) } render() { return ( <View style={MyPanelStyle.container}> <StatusBarPlaceHolder /> <View style={MyPanelStyle.HeaderContent}> <View style={MyPanelStyle.HeaderFirstView}> <TouchableOpacity style={MyPanelStyle.HeaderMenuicon} onPress={() => { Actions.drawerOpen(); }}> <Image resizeMode="contain" style={MyPanelStyle.HeaderMenuiconstyle} source={require('../../../../assets/images/menu_b.png')}> </Image> </TouchableOpacity> <View style={MyPanelStyle.HeaderTextView}> <Text style={MyPanelStyle.HeaderTextstyle}> MY PANEL </Text> </View> </View> </View> <ScrollView refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> }> <View style={MyPanelStyle.MainInfoBar}> <View style={MyPanelStyle.MainInfoBarTopRow}> <View style={MyPanelStyle.MainInfoBarTopRowLeft}> {this.state.ImageFileName !== "" ? ( <Image resizeMode='cover' style={ { ...Platform.select({ ios: { width: 80, height: 80, marginRight: 10, borderRadius: 40, }, android: { width: 80, height: 80, // elevation: 10 , borderRadius: 40, }, }), } } source={{ uri: "http://medilifesolutions.blob.core.windows.net/resourcetracker/" + this.state.ImageFileName }} />) : (<Image style={ { ...Platform.select({ ios: { width: 80, height: 80, marginRight: 10, borderRadius: 40, }, android: { width: 80, height: 80, // elevation: 10 , borderRadius: 600, }, }), } } resizeMode='contain' source={require('../../../../assets/images/employee.png')} />)} <View style={MyPanelStyle.TextInfoBar}> <Text style={MyPanelStyle.UserNameTextStyle}> {this.state.EmployeeName} </Text> <Text style={MyPanelStyle.DesignationTextStyle}> {this.state.Designation} </Text> <Text style={MyPanelStyle.DepartmentTextStyle}> {this.state.DepartmentName} </Text> </View> </View> <View style={MyPanelStyle.MainInfoBarTopRowRight}> <TouchableOpacity onPress={() => this.openModalEditProfile()} style={MyPanelStyle.EditButtonContainer}> <Image resizeMode='contain' source={require('../../../../assets/images/editprofie.png')} style={{ width: 47, height: 50 }}> </Image> </TouchableOpacity> </View > </View> </View> <View> {this.renderTimeStatusList()} </View> <View style={MyPanelStyle.ButtonBar}> <TouchableOpacity disabled={this.state.touchabledisablepointcheckin} onPress={() => this.getCheckIn()} style={MyPanelStyle.ButtonContainer}> <Image resizeMode='contain' source={require('../../../../assets/images/checkin.png')} style={MyPanelStyle.ButtonImage}> </Image> </TouchableOpacity> <TouchableOpacity disabled={this.state.touchabledisablepoint} onPress={() => this.getCheckPoint()} style={MyPanelStyle.ButtonContainer}> <Image resizeMode='contain' source={require('../../../../assets/images/checkpoint.png')} style={MyPanelStyle.ButtonImage}> </Image> </TouchableOpacity> <TouchableOpacity disabled={this.state.touchabledisablepointcheckout} onPress={() => this.getCheckOut()} style={MyPanelStyle.ButtonContainer}> <Image resizeMode='contain' source={require('../../../../assets/images/checkout.png')} style={MyPanelStyle.ButtonImage}> </Image> </TouchableOpacity> </View > <View style={MyPanelStyle.TimeLineMainView}> <View style={MyPanelStyle.TimeLineHeaderBar}> <Image resizeMode="contain" style={{ width: 19.8, height: 19.8, }} source={require('../../../../assets/images/goal.png')}> </Image> <Text style={MyPanelStyle.TimeLineHeaderText}> Timeline </Text> </View> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={MyPanelStyle.loaderIndicator} />) : null} <View style={{}}> {this.renderTrackList()} </View> </View> </ScrollView> <Modal style={[MyPanelStyle.modalForEditProfile]} position={"center"} ref={"modalEditEmp"} isDisabled={this.state.isDisabled} backdropPressToClose={false} swipeToClose={false} > <View style={{ justifyContent: "space-between", flexDirection: "row" }}> <View style={{ alignItems: "flex-start" }}> </View> <View style={{ alignItems: "flex-end" }}> <TouchableOpacity onPress={() => this.refs.modalEditEmp.close()} style={{ marginLeft: 0, marginTop: 0, }}> <Image resizeMode="contain" style={{ width: 15, height: 15, marginRight: 17, marginTop: 15 }} source={require('../../../../assets/images/close.png')}> </Image> </TouchableOpacity> </View> </View> <View style={MyPanelStyle.modelContent}> <View> <Text style={{ fontWeight: 'bold', fontSize: 25 }}> EDIT PROFILE </Text> {this.state.image == null ? (this.state.ImageFileName != "" ? (<Image style={{ ...Platform.select({ ios: { width: 100, height: 100, borderRadius: 50 }, android: { width: 100, height: 100, marginVertical: 12, borderRadius: 50, alignSelf: 'center' }, }), }} resizeMode='cover' source={{ uri: "http://medilifesolutions.blob.core.windows.net/resourcetracker/" + this.state.ImageFileName }} />) : (<Image style={{ ...Platform.select({ ios: { width: 100, height: 100, borderRadius: 50 }, android: { width: 100, height: 100, marginVertical: 12, borderRadius: 50, alignSelf: 'center' }, }), }} resizeMode='contain' source={require('../../../../assets/images/employee.png')} />)) : (<Image style={{ ...Platform.select({ ios: { width: 100, height: 100, borderRadius: 50 }, android: { width: 100, height: 100, marginVertical: 12, borderRadius: 600, alignSelf: 'center' }, }), }} resizeMode='contain' source={{ uri: this.state.image }} />)} </View> <View style={{ marginTop: -60, marginLeft: "27%", }}> <TouchableOpacity onPress={() => this.openmodalForImage()}> <Image resizeMode="contain" style={{ width: 40, height: 40, }} source={require('../../../../assets/images/photo_camera.png')}> </Image> </TouchableOpacity> </View> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={MyPanelStyle.loaderIndicator} />) : null} <View style={{ width: "100%" }}> <TextInput style={{ height: 40, margin: 15, padding: 5, backgroundColor: "#f1f4f6", borderRadius: 10, }} value={this.state.EmployeeName} placeholder="Name" placeholderTextColor="#dee1e5" autoCapitalize="none" onChangeText={text => this.setState({ EmployeeName: text })} > </TextInput> <TextInput style={{ height: 40, margin: 15, padding: 5, marginTop: 0, backgroundColor: "#f1f4f6", borderRadius: 10, }} value={this.state.mobile} placeholder="Phone" editable={false} placeholderTextColor="#dee1e5" autoCapitalize="none" > </TextInput> <TextInput style={{ height: 40, margin: 10, marginTop: 0, padding: 5, backgroundColor: "#f1f4f6", borderRadius: 10, }} value={this.state.Designation} placeholder="Gmail" placeholderTextColor="#dee1e5" autoCapitalize="none" onChangeText={text => this.setState({ Designation: text })} > </TextInput> </View> </View> <TouchableOpacity style={MyPanelStyle.addPeopleBtn} onPress={() => this.closeModalEditProfile()} > <Text style={{ color: 'white', fontWeight: 'bold', textAlign: 'center' }}>Save</Text> </TouchableOpacity> </Modal> <Modal style={NoticeStyle.ImagemodalContainer} position={"center"} ref={"modalForImage"} isDisabled={this.state.isDisabled} backdropPressToClose={true} swipeToClose={false} > <View style={{ justifyContent: "space-between", flexDirection: "row" }}> <View style={{ alignItems: "flex-start" }}> </View> <View style={{ alignItems: "flex-end" }}> <TouchableOpacity onPress={() => this.refs.modalForImage.close()} style={NoticeStyle.modalClose}> <Image resizeMode="contain" style={NoticeStyle.closeImage} source={require('../../../../assets/images/close.png')}> </Image> </TouchableOpacity> </View> </View> <View> <View> <Text style={NoticeStyle.addPhotoText}>Add Photos</Text> </View> <View style={NoticeStyle.cemaraImageContainer}> <TouchableOpacity onPress={() => this._takePhoto()} style={{ alignItems: "center", paddingLeft: 35 }}> <Image resizeMode='contain' style={{ height: 36, width: 36, }} source={require('../../../../assets/images/photo_camera_black.png')}></Image> <Text style={NoticeStyle.takePhotoText}>Take Photo</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this._pickImage()} style={{ alignItems: 'center', paddingRight: 35 }}> <Image resizeMode='contain' style={{ height: 36, width: 36, }} source={require('../../../../assets/images/Gallary.png')}></Image> <Text style={NoticeStyle.takePhotoText}>From Gallary</Text> </TouchableOpacity> </View> </View> </Modal> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, padding: 20, paddingTop: 0, backgroundColor: 'white' }, list: { flex: 1, marginTop: 20, }, });<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Global.asax.cs using System.Globalization; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Microsoft.Practices.Unity; using TrillionBits.ResourceTracker; namespace TrillionBitsPortal.Web { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { private static IUnityContainer _container; protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); _container = new UnityContainer(); RTUnityMapper.RegisterComponents(_container); } protected void Application_BeginRequest() { var cInf = new CultureInfo("en-US", false) { DateTimeFormat = { DateSeparator = "/", ShortDatePattern = "dd/MM/yyyy", LongDatePattern = "dd/MM/yyyy hh:mm:ss tt" } }; // NOTE: change the culture name en-ZA to whatever culture suits your needs System.Threading.Thread.CurrentThread.CurrentCulture = cInf; System.Threading.Thread.CurrentThread.CurrentUICulture = cInf; HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept"); HttpContext.Current.Response.End(); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE"); HttpContext.Current.Response.End(); } } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/InMemoryCache.cs using System; using System.Runtime.Caching; using System.Linq; namespace TrillionBitsPortal.Common { public class InMemoryCache : ICacheService { private static ICacheService _cacheService; private ObjectCache _cache; private readonly int DefaultCacheDurationInMin = 60; static InMemoryCache() { _cacheService = new InMemoryCache(); } private InMemoryCache() { _cache = MemoryCache.Default; } public TValue Get<TValue>(string cacheKey, Func<TValue> getItemCallback) where TValue : class { TValue item = _cache.Get(cacheKey) as TValue; if (item == null) { item = getItemCallback(); var policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTime.Now.AddMinutes(DefaultCacheDurationInMin); _cache.Set(cacheKey, item, policy); } return item; } public TValue Get<TValue, TId>(string cacheKeyFormat, TId id, Func<TId, TValue> getItemCallback) where TValue : class { string cacheKey = string.Format(cacheKeyFormat, id); TValue item = _cache.Get(cacheKey) as TValue; if (item == null) { item = getItemCallback(id); var policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTime.Now.AddMinutes(DefaultCacheDurationInMin); _cache.Set(cacheKey, item, policy); } return item; } public T Get<T>(string cacheID) where T : class { T item = _cache.Get(cacheID) as T; return item; } public void Set<T>(string cacheID, T data) where T : class { var policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTime.Now.AddMinutes(DefaultCacheDurationInMin); _cache.Set(cacheID, data, policy); } public void Remove(string cacheId) { _cache.Remove(cacheId); } public void RemoveAll(string cacheInitial) { var cacheIdList = _cache.Where(x => x.Key.StartsWith(cacheInitial)).ToList(); foreach (var x in cacheIdList) { _cache.Remove(x.Key); } } public static ICacheService CacheService { get { return _cacheService; } } } public interface ICacheService { TValue Get<TValue>(string cacheKey, Func<TValue> getItemCallback) where TValue : class; TValue Get<TValue, TId>(string cacheKeyFormat, TId id, Func<TId, TValue> getItemCallback) where TValue : class; T Get<T>(string cacheID) where T : class; void Set<T>(string cacheID, T data) where T : class; void Remove(string cacheId); void RemoveAll(string cacheInitial); } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Mappers/EmployeeTaskMapper.cs using TrillionBitsPortal.Common.Models; using System; using System.Collections.Generic; using System.Data.Common; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Mappers { public static class EmployeeTaskMapper { public static List<TaskGroupModel> ToTaskGroup(DbDataReader readers) { if (readers == null) return null; var models = new List<TaskGroupModel>(); while (readers.Read()) { var model = new TaskGroupModel { Id = Convert.ToInt32(readers["Id"]), Name = Convert.IsDBNull(readers["Name"]) ? string.Empty : Convert.ToString(readers["Name"]), Description = Convert.IsDBNull(readers["Description"]) ? string.Empty : Convert.ToString(readers["Description"]), BackGroundColor = Convert.IsDBNull(readers["BackGroundColor"]) ? string.Empty : Convert.ToString(readers["BackGroundColor"]), CreatedAt = Convert.IsDBNull(readers["CreatedAt"]) ? (DateTime?)null : Convert.ToDateTime(readers["CreatedAt"]), CreatedById = Convert.IsDBNull(readers["CreatedById"]) ? string.Empty : Convert.ToString(readers["CreatedById"]), }; models.Add(model); } return models; } public static List<ToDoTaskModel> ToToDoTask(DbDataReader readers) { if (readers == null) return null; var models = new List<ToDoTaskModel>(); while (readers.Read()) { var model = new ToDoTaskModel { Id = Convert.ToString(readers["Id"]), Title = Convert.IsDBNull(readers["Title"]) ? string.Empty : Convert.ToString(readers["Title"]), Description = Convert.IsDBNull(readers["Description"]) ? string.Empty : Convert.ToString(readers["Description"]), Completed = Convert.IsDBNull(readers["Completed"]) ? false : Convert.ToBoolean(readers["Completed"]), CreatedAt = Convert.IsDBNull(readers["CreatedAt"]) ? (DateTime?)null : Convert.ToDateTime(readers["CreatedAt"]), CreatedById = Convert.IsDBNull(readers["CreatedById"]) ? string.Empty : Convert.ToString(readers["CreatedById"]), }; models.Add(model); } return models; } public static List<TaskModel> ToTask(DbDataReader readers) { if (readers == null) return null; var models = new List<TaskModel>(); while (readers.Read()) { var model = new TaskModel { Id = Convert.ToString(readers["Id"]), TaskNo = Convert.IsDBNull(readers["TaskNo"]) ? (int?)null : Convert.ToInt32(readers["TaskNo"]), Title = Convert.IsDBNull(readers["Title"]) ? string.Empty : Convert.ToString(readers["Title"]), Description = Convert.IsDBNull(readers["Description"]) ? string.Empty : Convert.ToString(readers["Description"]), AssignedToId = Convert.IsDBNull(readers["AssignedToId"]) ? string.Empty : Convert.ToString(readers["AssignedToId"]), StatusId = Convert.IsDBNull(readers["StatusId"]) ? (int?)null : Convert.ToInt32(readers["StatusId"]), TaskGroupId = Convert.IsDBNull(readers["TaskGroupId"]) ? (int?)null : Convert.ToInt32(readers["TaskGroupId"]), CreatedAt = Convert.IsDBNull(readers["CreatedAt"]) ? (DateTime?)null : Convert.ToDateTime(readers["CreatedAt"]), CreatedById = Convert.IsDBNull(readers["CreatedById"]) ? string.Empty : Convert.ToString(readers["CreatedById"]), DueDate = Convert.IsDBNull(readers["DueDate"]) ? (DateTime?)null : Convert.ToDateTime(readers["DueDate"]), AssignToName = Convert.IsDBNull(readers["AssignToName"]) ? string.Empty : Convert.ToString(readers["AssignToName"]), UpdatedAt = Convert.IsDBNull(readers["UpdatedAt"]) ? (DateTime?)null : Convert.ToDateTime(readers["UpdatedAt"]), PriorityId = Convert.IsDBNull(readers["PriorityId"]) ? (int?)null : Convert.ToInt32(readers["PriorityId"]), CreatedByName = Convert.IsDBNull(readers["CreatedByName"]) ? string.Empty : Convert.ToString(readers["CreatedByName"]), UpdatedByName = Convert.IsDBNull(readers["UpdatedByName"]) ? string.Empty : Convert.ToString(readers["UpdatedByName"]), }; models.Add(model); } return models; } public static List<TaskAttachment> ToTaskAttachment(DbDataReader readers) { if (readers == null) return null; var models = new List<TaskAttachment>(); while (readers.Read()) { var model = new TaskAttachment { Id = Convert.ToString(readers["Id"]), TaskId = Convert.IsDBNull(readers["TaskId"]) ? string.Empty : Convert.ToString(readers["TaskId"]), FileName = Convert.IsDBNull(readers["FileName"]) ? string.Empty : Convert.ToString(readers["FileName"]), BlobName = Convert.IsDBNull(readers["BlobName"]) ? string.Empty : Convert.ToString(readers["BlobName"]), UpdatedAt = Convert.IsDBNull(readers["UpdatedAt"]) ? (DateTime?)null : Convert.ToDateTime(readers["UpdatedAt"]), UpdatedById = Convert.IsDBNull(readers["UpdatedById"]) ? string.Empty : Convert.ToString(readers["UpdatedById"]) }; models.Add(model); } return models; } } }<file_sep>/hr Office/HrApp/common/checkNetConnection.js import { NetInfo,ToastAndroid } from 'react-native'; export const CheckConnection = { async isconnection(){ if (await NetInfo.isConnected.fetch()){ ToastAndroid.show('Connected', ToastAndroid.TOP); } else{ ToastAndroid.show('Plese Connect the Internet', ToastAndroid.TOP); } } } <file_sep>/hr Office/HrApp/components/Screen/reports/DetailScreen.js import React from 'react'; import { ToastAndroid, Platform, StatusBar, Picker, Dimensions, RefreshControl, TouchableOpacity, View, Text, FlatList, Image, ScrollView, ActivityIndicator, AsyncStorage } from 'react-native'; import { Actions } from 'react-native-router-flux'; import { ReportStyle } from './ReportStyle'; import { CommonStyles } from '../../../common/CommonStyles'; import { FontAwesome, Entypo, AntDesign } from '@expo/vector-icons'; import { GetMonthlyAttendanceDetails } from '../../../services/Report' const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar /> </View> ); } export default class DetailScreen extends React.Component { constructor() { super(); this.state = { workingDetailList:[], companyId:0, progressVisible: false, } } goBack() { Actions.pop(); } componentDidMount(){ this.GetAllEmployeeAttendanceDetail(); } GetAllEmployeeAttendanceDetail = async () => { try { const cId = await AsyncStorage.getItem("companyId"); this.setState({ companyId: cId }); this.setState({ progressVisible: true }); await GetMonthlyAttendanceDetails(this.props.detailItem.UserId,cId,this.props.year,this.props.month) .then(res => { this.setState({ workingDetailList: res.result}); this.setState({ progressVisible: false }); }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); } catch (error) { this.setState({ progressVisible: false }); console.log(error); } } render() { const { width, height } = Dimensions.get('window'); return ( <View style={ReportStyle.container}> <StatusBarPlaceHolder /> <View style={CommonStyles.HeaderContent}> <View style={CommonStyles.HeaderFirstView}> <TouchableOpacity style={CommonStyles.HeaderMenuicon} onPress={() => { this.goBack() }}> <Image resizeMode="contain" style={CommonStyles.HeaderMenuiconstyle} source={require('../../../assets/images/left_arrow.png')}> </Image> </TouchableOpacity> <View style={CommonStyles.HeaderTextView}> <Text style={CommonStyles.HeaderTextstyle}> Attandance of {this.props.detailItem.EmployeeName} </Text> </View> </View> </View> <ScrollView showsVerticalScrollIndicator={false} // refreshControl={ // <RefreshControl // refreshing={this.state.refreshing} // onRefresh={this._onRefresh.bind(this)} // /> // } > <View style={ReportStyle.summaryContiner}> <View style={ReportStyle.Summaryhead}> <View style={ReportStyle.SummryheadLeft}> <Text style={ReportStyle.SummaryText}>Year : {this.props.year}</Text> </View> <View style={ReportStyle.CalanderIconContainer}> <FontAwesome name="calendar" size={15} style={{ marginRight: 6, alignSelf: 'center' }} color="#6a6a6a" /> <Text style={ReportStyle.monthText}>{this.props.month}</Text> </View> </View> <View style={ReportStyle.valueContainer}> <View style={ReportStyle.valueContainerFirst}> <View style={ReportStyle.IconContainer}> <Entypo name="controller-stop" size={18} color="#553e6b" style={{ }}> </Entypo> <Text style={ReportStyle.receiveText}>Total Office Hours</Text> </View> <View style={{ flexDirection: 'row', marginBottom: 15 }}> <Entypo name="controller-stop" size={18} color="#3b875e" style={{ }}> </Entypo> <Text style={ReportStyle.depositeText}>Completed Hours</Text> </View> <View style={{ flexDirection: 'row', marginBottom: 5 }}> <Entypo name="controller-stop" size={18} color="#919191" style={{ }}> </Entypo> <Text style={ReportStyle.previousText}>Over/Due Times </Text> </View> <View style={{ flexDirection: 'row' }}> <Entypo name="controller-stop" size={18} color="#c49602" style={{ }}> </Entypo> <Text style={ReportStyle.DeuBillTExt}>Present (Days) </Text> </View> </View> <View style={{ alignItems: 'flex-end', marginTop: 7, }}> <View style={{ marginBottom: 2, }}> <Text style={ReportStyle.FirstValueText}>{this.props.detailItem.TotalOfficeHour} hrs</Text> </View> <View style={{ marginBottom: 15, }}> <Text style={ReportStyle.SecondValueText}>{this.props.detailItem.TotalStayTime} hrs</Text> </View> <View style={{ marginBottom: 5, }}> <Text style={ReportStyle.ThirdValueText}>{this.props.detailItem.OvertimeOrDueHour} hrs</Text> </View> <View> <Text style={ReportStyle.FourthvalueText}>{this.props.detailItem.TotalPresent} Days</Text> </View> </View> </View> </View> <View style={{ margin: 10, }}> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={ReportStyle.loaderIndicator} />) : null} <FlatList data={this.state.workingDetailList} keyExtractor={(x, i) => i.toString()} renderItem={({ item }) => <View style={{ justifyContent: 'space-between', flexDirection: 'row' }}> <View style={{ alignItems: 'flex-start', backgroundColor: "white", width: (width * 20) / 100, borderRadius: 10, marginBottom: 10, height: 70 }}> <View style={{ alignSelf: 'center', backgroundColor: '#6b7787', width: (width * 20) / 100, borderTopLeftRadius: 10, borderTopRightRadius: 10 }}> <Text style={{ textAlign: 'center', color: 'white', fontFamily: 'PRODUCT_SANS_REGULAR' }}>{item.AttendancceDayName}</Text> </View> <View style={{ alignSelf: 'center' }}> { !item.IsLeave? <Text style={{ fontSize: 35, textAlign: 'center', fontFamily: 'PRODUCT_SANS_REGULAR' }}>{item.AttendancceDayNumber}</Text> : <Text style={{ fontSize: 35, color:"red",textAlign: 'center', fontFamily: 'PRODUCT_SANS_REGULAR' }}>{item.AttendancceDayNumber}</Text> } </View> </View> <View style={{ alignItems: 'flex-end', backgroundColor: 'white', height: 70, width: (width * 70) / 100, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', borderRadius: 10, borderBottomColor: '#553e6b', }}> <View style={{ borderRightWidth: 1, borderRightColor: 'gray',paddingLeft:17, width: (width * 28) / 100, flexDirection: "column", alignItems: 'center', }}> <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }}> { !item.IsLeave? <AntDesign name="arrowdown" size={16} color="#07c15d" style={{ marginTop: 3, }}> </AntDesign> :null} { !item.IsLeave? <Text style={{ fontSize: 14, textAlign: "right", color: "#076332", fontFamily: "PRODUCT_SANS_BOLD" }}> {item.CheckInTimeVw} </Text> : <Text style={{ fontSize: 14, textAlign: "right", color: "red", fontFamily: "PRODUCT_SANS_BOLD" }}> {item.CheckInTimeVw} </Text> } </View> { !item.IsLeave? <View style={{ alignItems: 'flex-end', }}> <Text style={{ fontSize: 9, color: "#a8a8a8", fontFamily: 'Montserrat_Medium', textAlign: 'center' }}> CHECKED IN </Text> </View> :null} </View> <View style={{ borderRightWidth: 1, borderRightColor: 'gray', width: (width * 25) / 100, flexDirection: "column", alignItems: 'center', }}> { !item.IsLeave? <View style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', }}> <AntDesign name="arrowup" size={16} color="red" style={{ marginTop: 3, }}> </AntDesign> <Text style={{ fontSize: 14, textAlign: "right", color: "red" }}> {item.CheckOutTimeVw} </Text> </View> :null} <View style={{ alignItems: 'center', }}> <Text style={{ fontSize: 9, textAlign: "right", color: "#a8a8a8" }}> CHECKED OUT </Text> </View> </View> <View style={{ borderRightColor: 'gray', width: (width * 30) / 100, // flexDirection: "column", //alignItems: 'center', // alignSelf:'center' paddingLeft:10, }}> <View style={{ flexDirection: 'row', // justifyContent: 'center', // alignItems: 'center', }}> <Entypo name="stopwatch" size={13} color="#a1b1ff" style={{ marginTop: 2, marginRight: 2, }}> </Entypo> <Text style={{ fontSize: 14, textAlign: "center", color: "#437098" }}> {item.OfficeStayHour} </Text> </View> <View style={{}}> <Text style={{ fontSize: 9, textAlign: "left", color: "#a8a8a8" }}> WORKING TIME </Text> </View> </View> </View> </View> }/> </View> </ScrollView> </View> ); } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/ResourceTracker/RtLeaveApiController.cs using System; using System.Net; using System.Net.Http; using System.Web.Http; using TrillionBits.ResourceTracker; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Models; using System.Linq; using TrillionBitsPortal.Common; using TrillionBitsPortal.Common.Models; namespace TrillionBitsPortal.Web.Controllers.Api.ResourceTracker { public class RtLeaveApiController : BaseApiController { private readonly IEmployeeLeave _leaveRepository; private readonly IDepartment _departmentRepository; private readonly INoticeBoard _noticeBoardRepository; private readonly IAttendance _attendance; public RtLeaveApiController() { _leaveRepository = RTUnityMapper.GetInstance<IEmployeeLeave>(); _departmentRepository = RTUnityMapper.GetInstance<IDepartment>(); _noticeBoardRepository = RTUnityMapper.GetInstance<INoticeBoard>(); _attendance = RTUnityMapper.GetInstance<IAttendance>(); } [HttpGet] public HttpResponseMessage GetLeaveByCompanyId(string companyId) { var result = _leaveRepository.GetLeaveByCompanyId(companyId); return Request.CreateResponse(HttpStatusCode.OK, result); } [HttpGet] public HttpResponseMessage GetUserLeaves(string userId) { var result = _leaveRepository.GetUserLeaves(userId); return Request.CreateResponse(HttpStatusCode.OK, result); } [HttpPost] public IHttpActionResult CreateLeave(EmployeeLeaveModel json) { var model = new EmployeeLeaveModel { CompanyId = json.CompanyId, EmployeeId = json.EmployeeId, FromDate =Convert.ToDateTime(json.LeaveApplyFrom), ToDate = Convert.ToDateTime(json.LeaveApplyTo), IsHalfDay = json.IsHalfDay, LeaveTypeId = json.LeaveTypeId, LeaveReason = json.LeaveReason, CreatedAt = DateTime.Now.ToString(), IsApproved = false, IsRejected = false, RejectReason = json.RejectReason, ApprovedById = null, ApprovedAt = null, UserId=json.UserId }; var response = _leaveRepository.CreateEmployeeLeave(model); if (!response.Success) return Ok(response); return Ok(new { Success = true }); } [HttpGet] public IHttpActionResult Approved(int id,string userId) { var response = _leaveRepository.Approved(id,userId); if (response.Success) { var result = _leaveRepository.GetLeaveById(id).First(); if (result.IsApproved && !result.IsRejected) { var noticeBoard = new NoticeDepartmentVIewModel { Details = string.Format("{0} is taking leave from {1} to {2}.", result.EmployeeName, result.FromDate.ToString(Constants.DateLongFormat), result.ToDate.ToString(Constants.DateLongFormat)), PostingDate = DateTime.Now.ToString(), CompanyId = result.CompanyId, CreatedBy = result.ApprovedById, CreateDate = DateTime.Now.ToString() }; var noticeResponse = _noticeBoardRepository.CreateNoticeBoard(noticeBoard); _attendance.AddAttendanceAsLeave(new AttendanceEntryModel { UserId=userId, CompanyId=result.CompanyId }); } } return Ok(response); } [HttpGet] public IHttpActionResult Rejected(int id) { var response = _leaveRepository.Rejected(id); return Ok(response); } [HttpGet] public IHttpActionResult GetLeaveTypeList() { var list = Enum.GetValues(typeof(LeaveType)).Cast<LeaveType>().Select(v => new NameIdPairModel { Name = EnumUtility.GetDescriptionFromEnumValue(v), Id = (int)v }).ToList(); return Ok(list); } } } <file_sep>/hr Office/HrApp/components/Screen/company/CompanySetupRowComponent.js import React from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Image, Dimensions } from 'react-native'; const _EditCom = async (item) => { methodforcom(item); this.refs.modalcomupdate.open(); } const methodforcom = async (item) => { this.setState({ ComName: item.Text }) this.setState({ ComId: item.Value }) this.setState({ Address: item.Address }) this.setState({ phone: item.phone }) this.setState({ MaximumOfficeHours: item.MaximumOfficeHours }) this.setState({ OfficeOutTime: item.OfficeOutTime }) } var { width } = Dimensions.get('window'); const CompanySetupRowComponent = (props) => ( <View style={{ padding: 15, borderWidth: 0, backgroundColor: '#ffffff', marginBottom: 5, marginLeft: 10, marginRight: 10, borderRadius: 15, justifyContent: 'space-between', flexDirection: 'row', borderColor: "white", flexDirection: 'row', borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 10, height: -5 }, elevation: 2, }}> <View style={{ alignItems: 'flex-start', marginLeft: 10 }}> <Text style={{ fontSize: 17, fontWeight: '500', color: '#4a4a4a', marginBottom: 2, }}> {props.itemData.Text} </Text> <View style={{ flexDirection: 'row', width: (width * 50) / 100, }}> <Image resizeMode="contain" style={{ height: 15, width: 15, marginTop: 4, marginRight: 5 }} source={require('../../../assets/images/Path_87.png')}></Image> <Text style={{ flex: 1, flexWrap: 'wrap', fontSize: 14, margingLeft: 5, color: '#4a4a4a', }}> {props.itemData.Address} </Text> </View> <View style={{ flexDirection: 'row', width: (width * 50) / 100, }}> <Image style={{ height: 15, width: 15, marginTop: 4, marginRight: 5 }} source={require('../../../assets/images/Path_86.png')}></Image> <Text style={{ flex: 1, flexWrap: 'wrap', fontSize: 14, margingLeft: 5, color: '#4a4a4a' }}> {props.itemData.phone} </Text> </View> </View> <TouchableOpacity onPress={() => _EditCom(props.itemData)} style={{ marginTop: 5, }}> <View style={{ alignItems: 'flex-end', marginRight: 20, }}> <Image style={{ height: 30, width: 30, alignSelf: "flex-end", marginTop: 6 }} source={require('../../../assets/images/edit.png')}></Image> <Text style={{ color: "#58687a", fontSize: 12, marginRight: 2, marginTop: 3, fontWeight: '500' }}>EDIT</Text> </View> </TouchableOpacity> </View> ); export default CompanySetupRowComponent; <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Mappers/EmployeeMapper.cs using TrillionBitsPortal.Common.Models; using System; using System.Collections.Generic; using System.Data.Common; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Mappers { public static class EmployeeMapper { public static List<EmployeeUser> ToEmployeeModel(DbDataReader readers) { if (readers == null) return null; var models = new List<EmployeeUser>(); while (readers.Read()) { var model = new EmployeeUser { Id = Convert.ToInt32(readers["Id"]), UserName = Convert.IsDBNull(readers["UserName"]) ? string.Empty : Convert.ToString(readers["UserName"]), Designation = Convert.IsDBNull(readers["Designation"]) ? string.Empty : Convert.ToString(readers["Designation"]), CompanyId = Convert.ToInt32(readers["CompanyId"]), DepartmentId = Convert.ToInt32(readers["DepartmentId"]), PhoneNumber = Convert.IsDBNull(readers["PhoneNumber"]) ? string.Empty : Convert.ToString(readers["PhoneNumber"]), ImageFileName = Convert.IsDBNull(readers["ImageFileName"]) ? string.Empty : Convert.ToString(readers["ImageFileName"]), ImageFileId = Convert.IsDBNull(readers["ImageFileId"]) ? string.Empty : Convert.ToString(readers["ImageFileId"]), UserId = Convert.IsDBNull(readers["UserId"]) ? string.Empty : Convert.ToString(readers["UserId"]), DepartmentName = Convert.IsDBNull(readers["DepartmentName"]) ? string.Empty : Convert.ToString(readers["DepartmentName"]), IsActive = Convert.IsDBNull(readers["IsActive"]) ? (bool?)null : Convert.ToBoolean(readers["IsActive"]), }; models.Add(model); } return models; } public static List<TextValuePairModel> ToTextValuePairModel(DbDataReader readers) { if (readers == null) return null; var models = new List<TextValuePairModel>(); while (readers.Read()) { var model = new TextValuePairModel { Text = Convert.IsDBNull(readers["Name"]) ? string.Empty : Convert.ToString(readers["Name"]), Value = Convert.IsDBNull(readers["Id"]) ? string.Empty : Convert.ToString(readers["Id"]) }; models.Add(model); } return models; } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/EmployeeRegistrationModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.ResourceTracker.Models { public class EmployeeRegistrationModel { public string Email { get; set; } public string PhoneNumber { get; set; } public string Gender { get; set; } public string Password { get; set; } public string UserName { get; set; } public string UserFullName { get; set; } public string UserType { get; set; } public string Designation { get; set; } public string DepartmentId { get; set; } public int CompanyId { get; set; } public bool IsAutoCheckPoint { get; set; } public string AutoCheckPointTime { get; set; } public string MaximumOfficeHours { get; set; } public string OfficeOutTime { get; set; } } } <file_sep>/hr Office/HrApp/components/Register.js import React, { Component } from 'react'; import RegisterForm from './Screen/registerForm'; import { KeyboardAvoidingView, StyleSheet, Platform, Dimensions, View, Image, Text, StatusBar, ScrollView } from 'react-native'; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar /> </View> ); } var { width, height } = Dimensions.get('window'); export default class Register extends Component { static navigationOptions = { title: "Screen One", header: null } render() { const { navigate } = this.props.navigation; return ( <KeyboardAvoidingView behavior="padding" enabled style={styles.container}> <ScrollView showsVerticalScrollIndicator={false}> <StatusBarPlaceHolder /> <View style={styles.mainView}> <Text style={styles.AdminText}> ADMIN </Text> <Text style={styles.RegisterText}> REGISTER </Text> </View> <RegisterForm /> </ScrollView> </KeyboardAvoidingView> ) } } const styles = StyleSheet.create({ container: { backgroundColor: '#f5f6f8', flex: 1, alignItems: 'center', justifyContent: 'center', marginTop: 10, }, imageContainer: { flex: 1 //justifyContent:'flex-end', }, logo: { //flex: 1, width: 355, height: 250, top: -35 }, AdminText: { fontFamily: "Montserrat_Bold", fontSize: 20, textAlign: "left", color: "#9f9f9f" }, RegisterText: { fontFamily: "Montserrat_Bold", fontSize: 31, textAlign: "left", color: "#030303" }, mainView: { flexDirection: 'column', justifyContent: 'flex-start' }, }) <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Helpers/CommonUtility.cs using TrillionBitsPortal.Common; using TrillionBitsPortal.Common.Models; namespace TrillionBitsPortal.Web.Helpers { public static class CommonUtility { static CommonUtility() { } public static UserSessionModel GetCurrentUser() { return System.Web.HttpContext.Current.Session[Constants.CurrentUser] as UserSessionModel; } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Mappers/EmployeeTrackingMapper.cs using System; using System.Collections.Generic; using System.Data.Common; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Mappers { public static class EmployeeTrackingMapper { public static List<EmployeeTrack> ToEmployeeTrackModel(DbDataReader readers) { if (readers == null) return null; var models = new List<EmployeeTrack>(); while (readers.Read()) { var model = new EmployeeTrack { Id = Convert.ToInt32(readers["Id"]), EmployeeUserId = Convert.ToInt32(readers["EmployeeUserId"]), TrackTypeName = Convert.IsDBNull(readers["TrackTypeName"]) ? string.Empty : Convert.ToString(readers["TrackTypeName"]), TrackDateTime = Convert.IsDBNull(readers["TrackDateTime"]) ? string.Empty : Convert.ToDateTime(readers["TrackDateTime"]).ToString(), TrackLatitude = Convert.IsDBNull(readers["TrackLatitude"]) ? (decimal?)null : Convert.ToDecimal(readers["TrackLatitude"]), TrackLongitude = Convert.IsDBNull(readers["TrackLongitude"]) ? (decimal?)null : Convert.ToDecimal(readers["TrackLongitude"]), TrackPlaceName = Convert.IsDBNull(readers["TrackPlaceName"]) ? string.Empty : Convert.ToString(readers["TrackPlaceName"]), }; models.Add(model); } return models; } } }<file_sep>/hr Office/HrApp/components/Screen/setting/Setting.js import React from 'react'; import { Platform, StatusBar, BackHandler, AsyncStorage, Alert, View, Text, Image, ScrollView, ToastAndroid, TouchableOpacity, TextInput } from 'react-native'; import * as Font from 'expo-font' import Modal from 'react-native-modalbox'; import { FontAwesome, Ionicons } from '@expo/vector-icons'; import { SettingStyle } from './SettingStyle' import { loadFromStorage, storage, CurrentUserProfile } from "../../../common/storage"; import { Actions } from 'react-native-router-flux'; import * as actions from '../../../common/actions'; import { CommonStyles } from '../../../common/CommonStyles'; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar /> </View> ); } export default class SettingScreen extends React.Component { constructor(props) { super(props); this.state = { ImageFileName: "", Name: '', Phone: '', Email: '', userId: '' } } modalchangepassword() { this.refs.modalchangepassword.open() } closemodalchangepassword() { this.setState({ progressVisible: true }) if (this.state.oldpassword == "" && this.state.newpassword == "" && this.state.confirmpassword == "") { alert("Field can not be empty") } else if (this.state.newpassword != this.state.confirmpassword) { alert("Password does not match"); } else { this.changepassword(); } } async changepassword() { console.log("trying changepassword.."); var response = await loadFromStorage(storage, CurrentUserProfile); this.setState({ userId: response.item.Id }) try { let UserModel = { CurrentPassword: <PASSWORD>, NewPassword: <PASSWORD>, UserId: this.state.userId, }; let response = await ChangePasswords(UserModel); if (response && response.isSuccess) { AsyncStorage.removeItem("userToken"); Actions.login(); this.setState({ progressVisible: false }) } else { this.setState({ progressVisible: false }) alert("Password Not Updated. Please try again"); } } catch (errors) { console.log(errors); } } handleBackButton = () => { BackHandler.exitApp() return true; } componentDidMount() { this._bootstrapAsync(); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); // await this.setState({ userId: storageOb.item.Id }); } componentWillMount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } openModal2() { Actions.CompanysetupScreen(); } gotoExpense() { Actions.Expenses(); } gotoIncome() { Actions.Incomes(); } openmodalforEmpList() { Actions.EmployeeSetupScreen(); } _bootstrapAsync = async () => { var response = await loadFromStorage(storage, CurrentUserProfile); await this.setState({ Name: response.item.UserFullName }); await this.setState({ Phone: response.item.PhoneNumber }); await this.setState({ Email: response.item.Email }); console.log(response, '...............'); } openModal3() { Actions.DepartmentSetupScreen(); } render() { const logOut = () => { Alert.alert( 'Log Out' , 'Log Out From The App?', [{ text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel' }, { text: 'OK', style: 'ok', onPress:async () => { await AsyncStorage.clear(); Actions.login(); } },], { cancelable: false } ) return true; }; const Soon = () => { }; return ( <View style={SettingStyle.container}> <StatusBarPlaceHolder /> <View style={CommonStyles.HeaderContent}> <View style={CommonStyles.HeaderFirstView}> <TouchableOpacity style={CommonStyles.HeaderMenuicon} onPress={() => { Actions.drawerOpen(); }}> <Image resizeMode="contain" style={CommonStyles.HeaderMenuiconstyle} source={require('../../../assets/images/menu_b.png')}> </Image> </TouchableOpacity> <View style={CommonStyles.HeaderTextView}> <Text style={CommonStyles.HeaderTextstyle}> SETTINGS </Text> </View> </View> </View> <ScrollView showsVerticalScrollIndicator={false}> <View style={SettingStyle.profileContainer}> <View style={SettingStyle.settingImageCotainer}> <Image style={SettingStyle.porfileImage} source={require('../../../assets/images/employee.png')} resizeMode='cover' /> <View style={{}}> <Text style={SettingStyle.profileName}> {this.state.Name} </Text> <Text style={SettingStyle.profilePhone}> {this.state.Phone} </Text> </View> </View> </View> <View style={SettingStyle.middleViewContainer}> <View style={SettingStyle.view1}> <TouchableOpacity onPress={() => this.openModal2()}> <View style={SettingStyle.view2}> <View style={SettingStyle.view3}> <Image style={SettingStyle.view1Image} source={require('../../../assets/images/s_1.png')}> </Image> <Text style={SettingStyle.text1}> Company Setup </Text> </View> <View style={SettingStyle.ChevronRightStyle}> <FontAwesome name="chevron-right" size={18} color="#cccccc" style={{ marginRight: 20 }} /> </View> </View> </TouchableOpacity> </View> <View style={SettingStyle.view1}> <TouchableOpacity onPress={() => this.openModal3()}> <View style={SettingStyle.view2}> <View style={SettingStyle.view3}> <Image style={SettingStyle.view1Image} source={require('../../../assets/images/s_2.png')}> </Image> <Text style={SettingStyle.text1}> Department Setup </Text> </View> <View style={SettingStyle.ChevronRightStyle}> <FontAwesome name="chevron-right" size={18} color="#cccccc" style={{ marginRight: 20 }} /> </View> </View> </TouchableOpacity> </View> <View style={SettingStyle.view1}> <TouchableOpacity onPress={() => this.openmodalforEmpList()}> <View style={SettingStyle.view2}> <View style={SettingStyle.view3}> <Image style={SettingStyle.view1Image} source={require('../../../assets/images/s_3.png')}> </Image> <Text style={SettingStyle.text1}> Employee Setup </Text> </View> <View style={SettingStyle.ChevronRightStyle}> <FontAwesome name="chevron-right" size={18} color="#cccccc" style={{ marginRight: 20 }} /> </View> </View> </TouchableOpacity> </View> <View style={SettingStyle.viewchangePass}> <TouchableOpacity // onPress={() => this.modalchangepassword()}> onPress={Soon}> <View style={SettingStyle.view2}> <View style={SettingStyle.view3}> <Image style={SettingStyle.view1Image} source={require('../../../assets/images/s_4.png')}> </Image> <Text style={SettingStyle.text1}> Change Password </Text> </View> <View style={SettingStyle.ChevronRightStyle}> <FontAwesome name="chevron-right" size={18} color="#cccccc" style={{ marginRight: 20 }} /> </View> </View> </TouchableOpacity> </View> </View> <View style={SettingStyle.lastViewContainer}> <View style={SettingStyle.viewchangePass}> <TouchableOpacity onPress={logOut}> <View style={SettingStyle.view2}> <View style={SettingStyle.view3}> <Image style={SettingStyle.view1Image} source={require('../../../assets/images/s_5.png')}> </Image> <Text style={SettingStyle.text1}> Logout </Text> </View> <View style={SettingStyle.ChevronRightStyle}> <FontAwesome name="chevron-right" size={18} color="#cccccc" style={{ marginRight: 20 }} /> </View> </View> </TouchableOpacity> </View> </View> <Modal style={[SettingStyle.modal3]} position={"center"} ref={"modalchangepassword"} isDisabled={this.state.isDisabled} onOpened={() => this.setState({ floatButtonHide: true })}> <View style={{ justifyContent: "space-between", flexDirection: "column" }}> <View style={{ alignItems: "flex-start" }}></View> <View style={{ alignItems: "flex-end" }}> <TouchableOpacity onPress={() => this.refs.modalchangepassword.close()} style={SettingStyle.changepassmodalToucah}> <Image resizeMode="contain" style={{ width: 30, height: 30, }} source={require('../../../assets/images/close.png')}> </Image> </TouchableOpacity> </View> </View> <View style={SettingStyle.modelContent}> <Text style={{ fontWeight: 'bold', fontSize: 25 }}> Change Password </Text> <View style={SettingStyle.horizontalLine} /> <Image resizeMode="contain" style={SettingStyle.addPeopleImg} source={require('../../../assets/images/key.png')}> </Image> </View> <View style={{ alignSelf: 'center' }}> <TextInput style={SettingStyle.inputBoxchagePass} placeholder="Old Password" placeholderTextColor="#cbcbcb" returnKeyType="next" autoCorrect={false} secureTextEntry onSubmitEditing={() => this.refs.txtnewpass.focus()} onChangeText={(text) => this.setState({ oldpassword: text })} /> <TextInput style={SettingStyle.inputBoxchagePass} placeholder="New Password" placeholderTextColor="#cbcbcb" returnKeyType="next" autoCorrect={false} secureTextEntry ref={"txtnewpass"} onSubmitEditing={() => this.refs.txtcomfirmpass.focus()} onChangeText={(text) => this.setState({ newpassword: text })} /> <TextInput style={SettingStyle.inputBoxchagePass} placeholder="Confirm New Password" placeholderTextColor="#cbcbcb" returnKeyType="go" autoCorrect={false} secureTextEntry onChangeText={(text) => this.setState({ confirmpassword: text })} ref={"txtcomfirmpass"} /> <TouchableOpacity style={SettingStyle.addPeopleBtnchangpass} onPress={() => this.closemodalchangepassword()} > <Text style={SettingStyle.changePassModalSave}> Save </Text> </TouchableOpacity> </View> </Modal> </ScrollView> </View > ); } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/ResourceTracker/RtAttendanceApiController.cs using System; using System.Web.Http; using TrillionBits.ResourceTracker; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Models; using System.Linq; using TrillionBitsPortal.Common.Models; using System.Globalization; using System.Collections.Generic; namespace TrillionBitsPortal.Web.Controllers.Api.ResourceTracker { public class RtAttendanceApiController : BaseApiController { private readonly IAttendance _attendance; private readonly ICompany _company; public RtAttendanceApiController() { _attendance = RTUnityMapper.GetInstance<IAttendance>(); _company = RTUnityMapper.GetInstance<ICompany>(); } [HttpPost] public IHttpActionResult CheckIn(AttendanceEntryModel model) { var attendanceFeed = _attendance.GetAttendanceFeed(model.CompanyId.Value, DateTime.UtcNow).ToList(); if (attendanceFeed.Any(x => x.UserId == model.UserId && x.IsCheckedIn)) return Ok(new ResponseModel {Message="Already checked-in." }); var companyModel = _company.GetCompanyById(model.CompanyId.Value); if(companyModel!=null && !string.IsNullOrEmpty(companyModel.MaximumOfficeHours)) { var maxOfficeHourList = companyModel.MaximumOfficeHours.Split(':'); model.OfficeHour = (Convert.ToInt32(maxOfficeHourList[0]) * 60) + Convert.ToInt32(maxOfficeHourList[1]); } if (companyModel != null && !string.IsNullOrEmpty(companyModel.OfficeOutTime)) { var outTimeList = companyModel.OfficeOutTime.Split(':'); model.AllowOfficeLessTime = (Convert.ToInt32(outTimeList[0]) * 60) + Convert.ToInt32(outTimeList[1]); } var response = _attendance.CheckIn(model); if (response.Success) { _attendance.SaveCheckPoint(new UserMovementLogModel { UserId=model.UserId, CompanyId=model.CompanyId, Latitude=model.Latitude, Longitude=model.Longitude, LogLocation=model.LogLocation, DeviceName=model.DeviceName, DeviceOSVersion=model.DeviceOSVersion, IsCheckInPoint=true }); } return Ok(response); } [HttpPost] public IHttpActionResult CheckOut(AttendanceEntryModel model) { var response = _attendance.CheckOut(model); if (response.Success) { _attendance.SaveCheckPoint(new UserMovementLogModel { UserId = model.UserId, CompanyId = model.CompanyId, Latitude = model.Latitude, Longitude = model.Longitude, LogLocation = model.LogLocation, DeviceName = model.DeviceName, DeviceOSVersion = model.DeviceOSVersion, IsCheckOutPoint = true }); } return Ok(response); } [HttpPost] public IHttpActionResult CheckPoint(AttendanceEntryModel model) { if (string.IsNullOrEmpty(model.LogLocation)) return Ok(new ResponseModel { Message="LogLocation is required."}); var response= _attendance.SaveCheckPoint(new UserMovementLogModel { UserId = model.UserId, CompanyId = model.CompanyId, Latitude = model.Latitude, Longitude = model.Longitude, LogLocation = model.LogLocation, DeviceName = model.DeviceName, DeviceOSVersion = model.DeviceOSVersion }); return Ok(response); } [HttpGet] public IHttpActionResult GetAttendanceFeed(int companyId) { var result = _attendance.GetAttendanceFeed(companyId, DateTime.UtcNow); return Ok(new { EmployeeList = result, StatusCount = new { TotalEmployee = result.Count, TotalCheckIn = result.Count(x => x.CheckInTime.HasValue), TotalCheckOut = result.Count(x => x.CheckOutTime.HasValue), TotalNotAttend = result.Count(x => !x.CheckInTime.HasValue) } }); } [HttpGet] public IHttpActionResult GetMyTodayAttendance(string userId) { var data = _attendance.GetMyTodayAttendance(userId, DateTime.UtcNow); if (data == null) return Ok(new { EmployeeName =string.Empty}); return Ok( new { data.EmployeeId, data.EmployeeName, data.Designation, data.DepartmentName, data.CheckInTimeVw, data.CheckOutTimeVw, data.AttendanceDateVw, data.IsCheckedIn, data.IsCheckedOut, data.ImageFileName, data.Status, data.OfficeStayHour, data.IsLeave }); } [HttpGet] public IHttpActionResult GetMovementDetails(string userId) { return Ok(_attendance.GetMovementDetails(userId, DateTime.UtcNow).OrderBy(x=>x.LogDateTime)); } [HttpGet] public IHttpActionResult GetEmployeeAttendanceFeedWithDate(int companyId,DateTime startDate,DateTime endDate, string userId) { userId = userId == "null" ? null : userId; var result = _attendance.GetAttendance(userId,companyId,startDate,endDate); return Ok(new { EmployeeList = result, StatusCount = new { TotalEmployee = result.Count, TotalCheckIn = result.Count(x => x.CheckInTime.HasValue), TotalCheckOut = result.Count(x => x.CheckOutTime.HasValue), TotalNotAttend = result.Count(x => !x.CheckInTime.HasValue) } }); } [HttpGet] public IHttpActionResult GetAllEmployeeAttendance(int companyId,DateTime startdate, DateTime enddate) { var result = _attendance.GetAttendance(companyId, startdate, enddate); if (result == null) return Ok(new { EmployeeName = string.Empty }); return Ok(new { EmployeeList = result, StatusCount = new { TotalEmployee = result.Count, TotalPresent = result.Count(x => x.CheckInTime.HasValue), TotalNotAttend = result.Count(x => !x.CheckInTime.HasValue) } }); } private List<AttendanceTotalModel> GetMonthlySummary(int companyId, string month, int year) { int monthnumber = DateTime.ParseExact(month, "MMMM", CultureInfo.InvariantCulture).Month; var startDate = new DateTime(year, monthnumber, 1); var endDate = new DateTime(year, monthnumber, DateTime.DaysInMonth(year, monthnumber)); var result = _attendance.GetAttendance(companyId, startDate, endDate); if (result == null) return new List<AttendanceTotalModel>(); var aList = new List<AttendanceTotalModel>(); var empList = result.GroupBy(x => x.UserId).ToList(); foreach (var e in empList) { var aModel = new AttendanceTotalModel(); var employee = result.FirstOrDefault(x => x.UserId == e.Key); aModel.EmployeeName = employee.EmployeeName; aModel.DepartmentName = employee.DepartmentName; aModel.Designation = employee.Designation; aModel.ImageFileName = employee.ImageFileName; aModel.UserId = e.Key; aModel.TotalPresent = result.Count(y => y.UserId == e.Key && y.IsPresent); aModel.TotalLeave = result.Count(y => y.UserId == e.Key && y.IsLeave.HasValue && y.IsLeave.Value); aModel.TotalCheckedOutMissing = result.Count(y => y.UserId == e.Key && y.NotCheckedOut); var totalMinute = result.Where(y => y.UserId == e.Key).Sum(x => x.TotalStayTimeInMinute); aModel.TotalStayTime = string.Format("{0}:{1}", totalMinute / 60, totalMinute % 60); var officeHourInMin = result.Where(y => y.UserId == e.Key).Sum(x => x.DailyWorkingTimeInMin); aModel.TotalOfficeHour = string.Format("{0}:{1}", officeHourInMin / 60, officeHourInMin % 60); var overTimeOrDue = totalMinute - officeHourInMin; aModel.OvertimeOrDueHour = string.Format("{0}:{1}", overTimeOrDue / 60, overTimeOrDue % 60); aList.Add(aModel); } return aList; } [HttpGet] public IHttpActionResult GetAllEmployeeAttendanceWithMonth(int companyId, string month, int year) { var aList = GetMonthlySummary(companyId, month, year); aList = aList.OrderBy(x => x.EmployeeName).ToList(); return Ok(aList); } [HttpGet] public IHttpActionResult GetLeaderboardData(int companyId, string month, int year) { var aList = GetMonthlySummary(companyId, month, year); foreach (var x in aList) { x.TotalScore = x.TotalPresent.HasValue ? (x.TotalPresent.Value * 0.5) - ((x.TotalCheckedOutMissing.HasValue ? x.TotalCheckedOutMissing.Value : 0) * 0.5) : 0; } aList = aList.OrderByDescending(x => x.TotalScore).ToList(); return Ok(aList); } [HttpGet] public IHttpActionResult GetMonthlyAttendanceDetails(string userId, int companyId, int year, string month) { int monthnumber = DateTime.ParseExact(month, "MMMM", CultureInfo.InvariantCulture).Month; var startDate = new DateTime(year, monthnumber, 1); var endDate = new DateTime(year, monthnumber, DateTime.DaysInMonth(year, monthnumber)); var result = _attendance.GetAttendance(userId,companyId, startDate, endDate).OrderBy(x=>x.AttendanceDate); return Ok(result); } } } <file_sep>/hr Office/HrApp/common/actions.js import { Actions } from 'react-native-router-flux'; export const push = (destinationScene, props) => { // console.log('push', destinationScene, Actions.currentScene, props); if (Actions.currentScene === destinationScene) { return; } return Actions[destinationScene](props); };<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/TokenApiController.cs using TrillionBitsPortal.Common; using TrillionBitsPortal.Web.Models; using System.Web.Http; using TrillionBits.ResourceTracker; using TrillionBitsPortal.ResourceTracker.Interfaces; namespace TrillionBitsPortal.Web.Controllers.Api { public class TokenApiController : ApiController { [HttpPost] [AllowAnonymous] public IHttpActionResult CreateToken([FromBody] LoginModel model) { var password = CryptographyHelper.CreateMD5Hash(model.Password); var user = RTUnityMapper.GetInstance<IUserCredential>().Get(model.LoginID, password); if (user == null) { return BadRequest(); } var token = TokenManager.GenerateToken(model.LoginID); return Ok(new { Success = true, Token = TokenManager.GenerateToken(model.LoginID), UserKey = user.DoctorId }); } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/BaseApiController.cs using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Web; using System.Web.Http; namespace TrillionBitsPortal.Web.Controllers.Api { [JwtAuthentication] public class BaseApiController : ApiController { } } <file_sep>/hr Office/HrApp/components/Screen/myPanel/MyPanel.js import React, { Component } from 'react'; import { Actions } from 'react-native-router-flux'; import Modal from 'react-native-modalbox'; import { MyPanelStyle } from './MyPanelStyle'; import { loadFromStorage, storage, CurrentUserProfile } from "../../../common/storage"; import { Platform, ScrollView, Text, View, Image, NetInfo, StatusBar, ActivityIndicator, ToastAndroid, RefreshControl, Alert, TextInput, TouchableOpacity, BackHandler, AsyncStorage, } from 'react-native'; import { AntDesign, Entypo, } from '@expo/vector-icons'; import { Location, Permissions, Constants, Svg, ImagePicker, } from 'expo'; import { CheckIn, CheckOut, CheckPoint, GetMyTodayAttendance, GetMovementDetails, } from '../../../services/EmployeeTrackService'; import { UpdateEmployee } from '../../../services/AccountService' import { NoticeStyle } from '../notice/NoticeStyle' import { DailyAttendanceCombo, } from '../../MenuDrawer/DrawerContent'; const { Circle, Line, } = Svg; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar // barStyle="light-content" /> </View> ); } export default class MyPanel extends Component { constructor(props) { super(props); this.state = { progressVisible: false, refreshing: false, gps: false, svgLinHeight: 60 * 0 - 60, touchabledisable: false, errorMessage: "", location: "", touchabledisablepointcheckin: true, touchabledisablepoint: true, touchabledisablepointcheckout: true, attendanceModel: null, EmpTrackList: [], AttendanceDateVw: "", CheckInTimeVw: "", CheckOutTimeVw: "", DepartmentName: "", Designation: "", EmployeeName: "", IsCheckedIn: false, IsCheckedOut: false, OfficeStayHour: "", Status: "", image: null, UserId: "", Latitude: null, Longitude: null, LogLocation: null, DeviceName: Constants.deviceName, DeviceOSVersion: Platform.OS === 'ios' ? Platform.systemVersion : Platform.Version, CompanyId: "", Reason: "", ImageFileName: "", mobile: '', name: '', gmail: '', Imageparam: "resourcetracker", ImageFileId: "", EmployeeId: 0, } } _onRefresh = async () => { this.setState({ refreshing: true }); setTimeout(function () { this.setState({ refreshing: false, }); }.bind(this), 2000); this._getLocationAsyncforgps(); this.getMyTodayAttendance(this.state.UserId); }; closeModalEditProfile() { this.updateEmployeeRecords(); } openModalEditProfile() { this.refs.modalEditEmp.open() } openmodalForprofileImg() { this.refs.modalForImage.open() } _takePhoto = async () => { this.refs.modalForImage.close() await Permissions.askAsync(Permissions.CAMERA_ROLL); await Permissions.askAsync(Permissions.CAMERA); let pickerResult = await ImagePicker.launchCameraAsync({ allowsEditing: true, aspect: [4, 4], quality: .2, height: 250, width: 250, }); console.log(pickerResult, '.......................') if (pickerResult.cancelled == false) { this.handleUploadPhoto(pickerResult) } }; handleUploadPhoto = async (pickerResult) => { const userToken = await AsyncStorage.getItem("userToken"); console.log(pickerResult.uri, '...............send') var data = new FormData(); data.append('my_photo', { uri: pickerResult.uri, name: 'my_photo.jpg', type: 'image/jpg' }) this.setState({ progressVisible: true }); fetch("https://medilifesolutions.com/api/AzureFileStorageApi/Upload?containerName=" + this.state.Imageparam, { headers: { 'Authorization': `bearer ${userToken}`, 'Accept': 'application/json', 'Content-Type': 'multipart/form-data' }, method: "POST", body: data }) .then(response => response.json()) .then(response => { console.log("upload succes", response); this.setState({ image: "https://medilifesolutions.blob.core.windows.net/resourcetracker/" + response.ReturnCode }); this.setState({ ImageFileName: response.ReturnCode }); this.setState({ progressVisible: false }); ToastAndroid.show('Image Uploaded successfully', ToastAndroid.TOP); console.log(response.ReturnCode, 'return..............'); //this.updateEmployeeRecords(); this.setState({ photo: null }); }) .catch(error => { console.log("upload error", error); ToastAndroid.show('Upload Fail', ToastAndroid.TOP); }); }; _pickImage = async () => { this.refs.modalForImage.close() await Permissions.askAsync(Permissions.CAMERA_ROLL); await Permissions.askAsync(Permissions.CAMERA); let pickerResult = await ImagePicker.launchImageLibraryAsync({ allowsEditing: true, aspect: [4, 4], quality: .2, height: 250, width: 250, }); if (pickerResult.cancelled == false) { this.handleUploadPhoto(pickerResult) } }; async updateEmployeeRecords() { let data = { UserFullName: this.state.EmployeeName, DesignationName: this.state.Designation, Id: this.state.EmployeeId, ImageFileName: this.state.ImageFileName, ImageFileId: this.state.ImageFileId, }; console.log('data...', data); try { let response = await UpdateEmployee(data); this.setState({ successMessage: response.result.message }); if (response && response.isSuccess) { this.refs.modalEditEmp.close() this.getMyTodayAttendance(this.state.UserId); console.log(response.result, '.....update.....') } else { alert(response.result); Alert.alert( "", response.result.message, [ { text: 'OK', }, ], { cancelable: false } ) } } catch (errors) { Alert.alert( "", "data does not saved", [ { text: 'OK', }, ], { cancelable: false } ) } } async componentDidMount() { global.DrawerContentId = 2; if (await NetInfo.isConnected.fetch()) { const uId = await AsyncStorage.getItem("userId"); this.setState({ UserId: uId }); const comId = await AsyncStorage.getItem("companyId"); var response = await loadFromStorage(storage, CurrentUserProfile); console.log(response, 'Response.............for............Emp') await this.setState({ name: response.item.UserFullName }); await this.setState({ mobile: response.item.PhoneNumber }); await this.setState({ gmail: response.item.Email }); this.setState({ CompanyId: comId }); this.getEmpTrackingTodayList(); this.getMyTodayAttendance(uId); this._getLocationAsyncforgps(); } else { ToastAndroid.show('Please connect to internet', ToastAndroid.TOP); } BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } handleBackButton = () => { BackHandler.exitApp() return true; } goBack() { DailyAttendanceCombo(); } getMyTodayAttendance = async (cId) => { this.setState({ progressVisible: true }); await GetMyTodayAttendance(cId) .then(res => { this.setState({ attendanceModel: res.result, }); this.setState({ EmployeeName: res.result.EmployeeName, }); this.setState({ DepartmentName: res.result.DepartmentName, }); this.setState({ Designation: res.result.Designation, }); this.setState({ CheckInTimeVw: res.result.CheckInTimeVw, }); this.setState({ CheckOutTimeVw: res.result.CheckOutTimeVw, }); this.setState({ OfficeStayHour: res.result.OfficeStayHour, }); this.setState({ IsCheckedIn: res.result.IsCheckedIn, }); this.setState({ IsCheckedOut: res.result.IsCheckedOut, }); this.setState({ Status: res.result.Status, }); this.setState({ EmployeeId: res.result.EmployeeId, }); this.setState({ ImageFileName: res.result.ImageFileName, }); console.log("attendanceModel", res.result); console.log('IsCheckedIn', this.state.IsCheckedIn); this.setState({ progressVisible: false }); }).catch(() => { this.setState({ progressVisible: false }); console.log("GetMyTodayAttendance error occured"); }); this.setState({ progressVisible: true }); await GetMovementDetails(cId) .then(res => { this.setState({ EmpTrackList: res.result }); this.setState({ progressVisible: false }); console.log('EmpTrackList........', this.state.EmpTrackList); }).catch(() => { this.setState({ progressVisible: false }); console.log("GetMovementDetails error occured"); }); } getLoction = async () => { if (Platform.OS === 'android' && !Constants.isDevice) { this.setState({ errorMessage: 'Oops, this will not work on Sketch in an Android emulator. Try it on your device!', }); ToastAndroid.show(errorMessage, ToastAndroid.TOP); } else { await this._getLocationAsync(); } } _getLocationAsync = async () => { let { status } = await Permissions.askAsync(Permissions.LOCATION); if (status !== 'granted') { ToastAndroid.show(errorMessage, ToastAndroid.TOP); this.setState({ errorMessage: 'Permission to access location was denied', }); } let location = await Location.getCurrentPositionAsync({ enableHighAccuracy: false, timeout: 20000, maximumAge: 0, distanceFilter: 10 }); var pos = { latitude: location.coords.latitude, longitude: location.coords.longitude, }; let location2 = await Location.reverseGeocodeAsync(pos); let emplocation = location2[0]; console.log(emplocation, 'emplocation.....emp'); this.setState({ UserId: this.state.UserId, Latitude: location.coords.latitude, Longitude: location.coords.longitude, LogLocation: emplocation.name + "," + emplocation.street + "," + emplocation.city, DeviceName: this.state.DeviceName, DeviceOSVersion: this.state.DeviceOSVersion, CompanyId: this.state.CompanyId, Reason: this.state.Reason, }); }; _getLocationAsyncforgps = async () => { let iosgps = Location.hasServicesEnabledAsync(); let gps = await Location.getProviderStatusAsync(); this.setState({ gps: gps.gpsAvailable }); } getEmpTrackingTodayList = async () => { try { this.setState({ progressVisible: true }); await GetMovementDetails(this.state.UserId) .then(res => { this.setState({ EmpTrackList: res.result }); const tcount = 60 * res.result.length - 60; this.setState({ svgLinHeight: tcount === 0 ? 60 : tcount }); this.setState({ progressVisible: false }); this.setState({ touchabledisablepointcheckin: false }); this.setState({ touchabledisablepoint: false }); this.setState({ touchabledisablepointcheckout: false }); }) .catch(() => { this.setState({ progressVisible: false }); }); } catch (error) { this.setState({ progressVisible: false }); } } renderTrackList() { let content = this.state.EmpTrackList.map((item, i) => { if (item.IsCheckInPoint === true) { return ( <View key={i}> <View style={{ position: 'absolute' }}> <Svg height={this.state.svgLinHeight} width="200" > <Line x1="45" y1="0" x2="45" y2={this.state.svgLinHeight} stroke="#BABABA" strokeWidth="2" /> </Svg> </View> <View style={MyPanelStyle.TrackListRowVIew}> <View style={{ flexDirection: 'column', alignItems: 'center' }}> <Text style={{ color: '#313131' }} key={item.Id}> {item.LogTimeVw} </Text> </View> <Svg height="20" width="20"> <Circle cx="10" cy="10" r="5" stroke="#24B978" strokeWidth="2.5" fill="#20A66C" /> </Svg> <Text style={MyPanelStyle.TrackListText} key={item.Id}> Checked In at {item.LogLocation} </Text> </View> </View> ) } else if (item.IsCheckOutPoint === true) { return ( <View key={i}> <View style={MyPanelStyle.TrackListRowVIew}> <View style={{ flexDirection: 'column', alignItems: 'center' }}> <Text style={{ color: '#313131' }} key={item.Id}> {item.LogTimeVw} </Text> </View> <Svg height="20" width="20"> <Circle cx="10" cy="10" r="5" stroke="#B92436" strokeWidth="2.5" fill="#A62030" /> </Svg> <Text style={MyPanelStyle.TrackListText} key={item.Id}> Checked Out at {item.LogLocation} </Text> </View> </View> ) } else if (item.IsCheckInPoint === null && item.IsCheckOutPoint === null) { return ( <View key={i}> <View style={MyPanelStyle.TrackListRowVIew}> <View style={{ flexDirection: 'column', alignItems: 'center' }}> <Text style={{ color: '#313131' }} key={item.Id}> {item.LogTimeVw} </Text> </View> <Svg height="20" width="20"> <Circle cx="10" cy="10" r="5" stroke="#ACACAC" strokeWidth="2.5" fill="#9A9A9A" /> </Svg> <Text style={MyPanelStyle.TrackListText} key={item.Id}> Check Point at {item.LogLocation} </Text> </View> </View> ) } }); return content; } async createCheckingIn() { try { const TrackingModel = { UserId: this.state.UserId, Latitude: this.state.Latitude, Longitude: this.state.Longitude, LogLocation: this.state.LogLocation, DeviceName: this.state.DeviceName, DeviceOSVersion: this.state.DeviceOSVersion, CompanyId: this.state.CompanyId }; this.state.progressVisible = true; const response = await CheckIn(TrackingModel); if (response && response.isSuccess) { console.log("createCheckingIn response", response) this.getEmpTrackingTodayList(); this.getMyTodayAttendance(this.state.UserId); this.state.progressVisible = false } else { ToastAndroid.show('Something went wrong', ToastAndroid.TOP); this.state.progressVisible = false; } } catch (errors) { console.log("createCheckingIn Errors", errors); this.state.progressVisible = false; } } async createCheckPoint() { try { this.setState({ progressVisible: true }); const TrackingModel = { UserId: this.state.UserId, Latitude: this.state.Latitude, Longitude: this.state.Longitude, LogLocation: this.state.LogLocation, DeviceName: this.state.DeviceName, DeviceOSVersion: this.state.DeviceOSVersion, CompanyId: this.state.CompanyId }; console.log("TrackingModel response", TrackingModel) const response = await CheckPoint(TrackingModel); if (response && response.isSuccess) { console.log("createCheckPoint response", response) this.getEmpTrackingTodayList(); this.state.progressVisible = false; } else { ToastAndroid.show('Something went wrong', ToastAndroid.TOP); this.state.progressVisible = false; } } catch (errors) { console.log("createCheckPoint Errors", errors); this.state.progressVisible = false; } } async createCheckOut() { try { const TrackingModel = { UserId: this.state.UserId, Latitude: this.state.Latitude, Longitude: this.state.Longitude, LogLocation: this.state.LogLocation, DeviceName: this.state.DeviceName, DeviceOSVersion: this.state.DeviceOSVersion, CompanyId: this.state.CompanyId }; const response = await CheckOut(TrackingModel) this.state.progressVisible = true; console.log("CheckOut TrackingModel", TrackingModel); if (response && response.isSuccess) { console.log("createCheckOut response", response) this.getEmpTrackingTodayList(); this.getMyTodayAttendance(this.state.UserId); this.state.progressVisible = false; } else { ToastAndroid.show('Something went wrong', ToastAndroid.TOP); this.state.progressVisible = false; } } catch (errors) { console.log("createCheckOut Errors", errors); this.state.progressVisible = false; } } getCheckIn = async () => { this.setState({ touchabledisablepointcheckin: true, }); // if (await NetInfo.isConnected.fetch()) { this.setState({ touchabledisable: true, progressVisible: true }); console.log('check for getCheckIn', this.state.IsCheckedIn); if (this.state.gps) { if (this.state.IsCheckedOut === false) { if (this.state.IsCheckedIn === false) { this.setState({ progressVisible: true, }); await this.getLoction(); await this.createCheckingIn(); this.setState({ touchabledisablepointcheckin: false, }); } else { this.setState({ progressVisible: false }); this.setState({ touchabledisablepointcheckin: false, }); ToastAndroid.show('You have already checked in today', ToastAndroid.TOP); } } else { this.setState({ progressVisible: false }); this.setState({ touchabledisablepointcheckin: false, }); ToastAndroid.show('You have already checked out today', ToastAndroid.TOP); } } else { this.setState({ progressVisible: false }); this.setState({ touchabledisablepointcheckin: false, }); ToastAndroid.show('Please turn on your gps', ToastAndroid.TOP); } // } else { // ToastAndroid.show("No Internet Detected", ToastAndroid.TOP); // } } getCheckOut = async () => { this.setState({ touchabledisablepointcheckout: true, }); if (await NetInfo.isConnected.fetch()) { this.setState({ touchabledisable: true, progressVisible: true }); console.log('check for getCheckOut', this.state.IsCheckedOut); if (this.state.gps === true) { if (this.state.IsCheckedOut == false) { if (this.state.IsCheckedIn === true && this.state.IsCheckedOut == false) { this.setState({ progressVisible: false, }); await this.getLoction(); this.createCheckOut(); } else { this.setState({ progressVisible: false }); this.setState({ touchabledisablepointcheckout: false, }); ToastAndroid.show('You have not checked in today', ToastAndroid.TOP); } } else { this.setState({ progressVisible: false }); this.setState({ touchabledisablepointcheckout: false, }); ToastAndroid.show('You have already checked out today', ToastAndroid.TOP); } } else { this.setState({ touchabledisablepointcheckout: false, }); ToastAndroid.show("No Internet Detected", ToastAndroid.TOP); } } } getCheckPoint = async () => { this.setState({ touchabledisablepoint: true, }); if (await NetInfo.isConnected.fetch()) { this.setState({ progressVisible: true }); this.setState({ touchabledisable: true, }); console.log('check for getCheckPoint', this.state.IsCheckedIn); if (this.state.gps === true) { if (this.state.IsCheckedOut === false) { if (this.state.IsCheckedIn === true && this.state.IsCheckedOut == false) { await this.getLoction(); // console.log("clicked"); await this.createCheckPoint(); this.setState({ progressVisible: false }); this.setState({ touchabledisablepoint: false, }); } else { this.setState({ progressVisible: false }); ToastAndroid.show('You have not checked in today', ToastAndroid.TOP); this.setState({ progressVisible: false }); this.setState({ touchabledisablepoint: false, }); } } else { this.setState({ progressVisible: false }); ToastAndroid.show('You have already checked out today', ToastAndroid.TOP); this.setState({ progressVisible: false }); this.setState({ touchabledisablepoint: false, }); } } else { this.setState({ progressVisible: false }); ToastAndroid.show('Please turn on your gps', ToastAndroid.TOP); this.setState({ progressVisible: false }); this.setState({ touchabledisablepoint: false, }); } } else { ToastAndroid.show("No Internet Detected", ToastAndroid.TOP); this.setState({ touchabledisablepoint: false, }); } } renderTimeStatusList() { return ( <View style={MyPanelStyle.TimeInfoBar}> <View style={MyPanelStyle.First2TimePanelView}> <View style={MyPanelStyle.AllTimePanelRow}> <Text> {this.state.CheckInTimeVw ? (<AntDesign name="arrowdown" size={18} color="#07c15d" style={{ marginTop: 3, }} />) : (<Text style={MyPanelStyle.TimeStatusText}> NOT YET </Text>) } </Text> <Text style={MyPanelStyle.CheckedInText}> {this.state.CheckInTimeVw} </Text> </View> <View style={MyPanelStyle.AllTimePanelRow}> <Text style={MyPanelStyle.TimeStatusText}> CHECKED IN </Text> </View> </View> <View style={MyPanelStyle.First2TimePanelView}> <View style={MyPanelStyle.AllTimePanelRow}> <Text> {this.state.OfficeStayHour ? (<Entypo name="stopwatch" size={17} color="#a1b1ff" style={{ marginTop: 2, marginRight: 2, }} />) : (<Text style={MyPanelStyle.TimeStatusText}> NOT YET </Text>) } </Text> <Text style={MyPanelStyle.WorkingTimeText}> {this.state.OfficeStayHour} </Text> </View> <View style={MyPanelStyle.AllTimePanelRow}> <Text style={MyPanelStyle.TimeStatusText}> WORKING TIME </Text> </View> </View> <View style={MyPanelStyle.Last1TimePanelView}> <View style={MyPanelStyle.AllTimePanelRow}> <Text> {this.state.OfficeStayHour ? (<AntDesign name="arrowup" size={18} style={{ marginTop: 3, }} color="#a1d3ff" />) : (<Text style={MyPanelStyle.TimeStatusText}> NOT YET </Text>) } </Text> <Text style={MyPanelStyle.CheckedOutText}> {this.state.CheckOutTimeVw} </Text> </View> <View style={MyPanelStyle.AllTimePanelRow}> <Text style={MyPanelStyle.TimeStatusText}> CHECKED OUT </Text> </View> </View> </View> ) } render() { return ( <View style={MyPanelStyle.container}> <StatusBarPlaceHolder /> <View style={MyPanelStyle.HeaderContent}> <View style={MyPanelStyle.HeaderFirstView}> <TouchableOpacity style={MyPanelStyle.HeaderMenuicon} onPress={() => { Actions.drawerOpen(); }}> <Image resizeMode="contain" style={MyPanelStyle.HeaderMenuiconstyle} source={require('../../../assets/images/menu_b.png')}> </Image> </TouchableOpacity> <View style={MyPanelStyle.HeaderTextView}> <Text style={MyPanelStyle.HeaderTextstyle}> MY PANEL </Text> </View> </View> </View> <ScrollView refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> }> <View style={MyPanelStyle.MainInfoBar}> <View style={MyPanelStyle.MainInfoBarTopRow}> <View style={MyPanelStyle.MainInfoBarTopRowLeft}> {this.state.ImageFileName !== "" ? ( <Image resizeMode="contain" style={ { ...Platform.select({ ios: { width: 80, height: 80, marginRight: 10, borderRadius: 40, }, android: { width: 80, height: 80, // elevation: 10 , borderRadius: 600, }, }), } } source={{ uri: "http://medilifesolutions.blob.core.windows.net/resourcetracker/" + this.state.ImageFileName }} />) : (<Image style={ { ...Platform.select({ ios: { width: 80, height: 80, marginRight: 10, borderRadius: 40, }, android: { width: 80, height: 80, // elevation: 10 , borderRadius: 600, }, }), } } resizeMode='contain' source={require('../../../assets/images/employee.png')} />)} <View style={MyPanelStyle.TextInfoBar}> <Text style={MyPanelStyle.UserNameTextStyle}> {this.state.EmployeeName} </Text> <Text style={MyPanelStyle.DesignationTextStyle}> {this.state.Designation} </Text> <Text style={MyPanelStyle.DepartmentTextStyle}> {this.state.DepartmentName} </Text> </View> </View> <View style={MyPanelStyle.MainInfoBarTopRowRight}> <TouchableOpacity onPress={() => this.openModalEditProfile()} style={MyPanelStyle.EditButtonContainer}> <Image resizeMode='contain' source={require('../../../assets/images/editprofie.png')} style={{ width: 47, height: 50 }}> </Image> </TouchableOpacity> </View > </View> </View> <View> {this.renderTimeStatusList()} </View> <View style={MyPanelStyle.ButtonBar}> <TouchableOpacity disabled={this.state.touchabledisablepointcheckin} onPress={() => this.getCheckIn()} style={MyPanelStyle.ButtonContainer}> <Image resizeMode='contain' source={require('../../../assets/images/checkin.png')} style={MyPanelStyle.ButtonImage}> </Image> </TouchableOpacity> <TouchableOpacity disabled={this.state.touchabledisablepoint} onPress={() => this.getCheckPoint()} style={MyPanelStyle.ButtonContainer}> <Image resizeMode='contain' source={require('../../../assets/images/checkpoint.png')} style={MyPanelStyle.ButtonImage}> </Image> </TouchableOpacity> <TouchableOpacity disabled={this.state.touchabledisablepointcheckout} onPress={() => this.getCheckOut()} style={MyPanelStyle.ButtonContainer}> <Image resizeMode='contain' source={require('../../../assets/images/checkout.png')} style={MyPanelStyle.ButtonImage}> </Image> </TouchableOpacity> </View > <View style={MyPanelStyle.TimeLineMainView}> <View style={MyPanelStyle.TimeLineHeaderBar}> <Image resizeMode="contain" style={{ width: 19.8, height: 19.8, }} source={require('../../../assets/images/goal.png')}> </Image> <Text style={MyPanelStyle.TimeLineHeaderText}> Timeline </Text> </View> <View style={{ padding: 20 }}> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={MyPanelStyle.loaderIndicator} />) : null} {this.renderTrackList()} </View> </View> </ScrollView> <Modal style={[MyPanelStyle.modalForEditProfile]} position={"center"} ref={"modalEditEmp"} isDisabled={this.state.isDisabled} backdropPressToClose={false} swipeToClose={false} > <View style={{ justifyContent: "space-between", flexDirection: "row" }}> <View style={{ alignItems: "flex-start" }}> </View> <View style={{ alignItems: "flex-end" }}> <TouchableOpacity onPress={() => this.refs.modalEditEmp.close()} style={{ marginLeft: 0, marginTop: 0, }}> <Image resizeMode="contain" style={{ width: 15, height: 15, marginRight: 17, marginTop: 15 }} source={require('../../../assets/images/close.png')}> </Image> </TouchableOpacity> </View> </View> <View style={MyPanelStyle.modelContent}> <View> <Text style={{ fontWeight: 'bold', fontSize: 25 }}> EDIT PROFILE </Text> {this.state.image == null ? (this.state.ImageFileName != "" ? (<Image style={{ ...Platform.select({ ios: { width: 100, height: 100, borderRadius: 50 }, android: { width: 100, height: 100, marginVertical: 12, borderRadius: 600, alignSelf: 'center' }, }), }} resizeMode="contain" source={{ uri: "http://medilifesolutions.blob.core.windows.net/resourcetracker/" + this.state.ImageFileName }} />) : (<Image style={{ ...Platform.select({ ios: { width: 100, height: 100, borderRadius: 50 }, android: { width: 100, height: 100, marginVertical: 12, borderRadius: 600, alignSelf: 'center' }, }), }} resizeMode='contain' source={require('../../../assets/images/employee.png')} />)) : (<Image style={{ ...Platform.select({ ios: { width: 100, height: 100, borderRadius: 50 }, android: { width: 100, height: 100, marginVertical: 12, borderRadius: 600, alignSelf: 'center' }, }), }} resizeMode='contain' source={{ uri: this.state.image }} />)} </View> <View style={{ marginTop: -60, marginLeft: "27%", }}> <TouchableOpacity onPress={() => this.openmodalForprofileImg()}> <Image resizeMode="contain" style={{ width: 40, height: 40, }} source={require('../../../assets/images/photo_camera.png')}> </Image> </TouchableOpacity> </View> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={MyPanelStyle.loaderIndicator} />) : null} <View style={{ width: "100%" }}> <TextInput style={{ height: 40, margin: 15, padding: 5, backgroundColor: "#f1f4f6", borderRadius: 10, }} value={this.state.EmployeeName} placeholder="Name" placeholderTextColor="#dee1e5" autoCapitalize="none" onChangeText={text => this.setState({ EmployeeName: text })} > </TextInput> <TextInput style={{ height: 40, margin: 15, padding: 5, marginTop: 0, backgroundColor: "#f1f4f6", borderRadius: 10, }} value={this.state.mobile} placeholder="Phone" editable={false} placeholderTextColor="#dee1e5" autoCapitalize="none" > </TextInput> <TextInput style={{ height: 40, margin: 10, marginTop: 0, padding: 5, backgroundColor: "#f1f4f6", borderRadius: 10, }} value={this.state.Designation} placeholder="Gmail" placeholderTextColor="#dee1e5" autoCapitalize="none" onChangeText={text => this.setState({ Designation: text })} > </TextInput> </View> </View> <TouchableOpacity style={MyPanelStyle.addPeopleBtn} onPress={() => this.closeModalEditProfile()} > <Text style={{ color: 'white', fontWeight: 'bold', textAlign: 'center' }}>Save</Text> </TouchableOpacity> </Modal> <Modal style={NoticeStyle.ImagemodalContainer} position={"center"} ref={"modalForImage"} isDisabled={this.state.isDisabled} backdropPressToClose={true} swipeToClose={false} > <View style={{ justifyContent: "space-between", flexDirection: "row" }}> <View style={{ alignItems: "flex-start" }}> </View> <View style={{ alignItems: "flex-end" }}> <TouchableOpacity onPress={() => this.refs.modalForImage.close()} style={NoticeStyle.modalClose}> <Image resizeMode="contain" style={NoticeStyle.closeImage} source={require('../../../assets/images/close.png')}> </Image> </TouchableOpacity> </View> </View> <View> <View> <Text style={NoticeStyle.addPhotoText}>Add Photos</Text> </View> <View style={NoticeStyle.cemaraImageContainer}> <TouchableOpacity onPress={() => this._takePhoto()} style={{ alignItems: "center", paddingLeft: 35 }}> <Image resizeMode='contain' style={{ height: 36, width: 36, }} source={require('../../../assets/images/photo_camera_black.png')}></Image> <Text style={NoticeStyle.takePhotoText}>Take Photo</Text> </TouchableOpacity> <TouchableOpacity onPress={() => this._pickImage()} style={{ alignItems: 'center', paddingRight: 35 }}> <Image resizeMode='contain' style={{ height: 36, width: 36, }} source={require('../../../assets/images/Gallary.png')}></Image> <Text style={NoticeStyle.takePhotoText}>From Gallary</Text> </TouchableOpacity> </View> </View> </Modal> </View> ) } } <file_sep>/hr Office/HrApp/components/Splash.js import React,{Component} from 'react' import {StyleSheet,Text,View} from 'react-native' export default class Splash extends Component{ render (){ return( <View style={styles.container}> <Text style={styles.title}> Hello this is splash</Text> </View> ) } } const styles=StyleSheet.create({ container:{ backgroundColor:'#f4f5f7', flex:1, alignItems:'center', justifyContent:'center' }, title:{ fontWeight:'bold', fontSize:18, color:'black' } })<file_sep>/hr Office/HrApp/services/UserService/EmployeeTrackService.js import { postApi, getApi } from "../api"; export const CheckIn = async data => postApi("RtAttendanceApi/CheckIn", {}, data); export const CheckOut = async data => postApi("RtAttendanceApi/CheckOut", {}, data); export const CheckPoint = async data => postApi("RtAttendanceApi/CheckPoint", {}, data); export const GetMovementDetails = async (userId) => getApi("RtAttendanceApi/GetMovementDetails?userId="+userId, {}, {}); export const GetAttendanceFeed = async (companyId) => getApi("RtAttendanceApi/GetAttendanceFeed?companyId="+companyId, {}, {}); export const GetMyTodayAttendance = async (userId) => getApi("RtAttendanceApi/GetMyTodayAttendance?userId="+userId, {}, {}); export const EmployeeList = async (companyId) => getApi("RtEmployeeApi/GetEmployeeAsTextValue?companyId="+companyId, {}, {}); <file_sep>/hr Office/HrApp/components/Screen/Board/TaskBoard.js import React, { Component } from 'react'; import { ToastAndroid, FlatList, Text, View, Image, StatusBar, ActivityIndicator, AsyncStorage, Dimensions, TextInput, TouchableOpacity, Platform, RefreshControl, ScrollView, Alert, BackHandler, } from 'react-native'; import { Actions } from 'react-native-router-flux'; import * as actions from '../../../common/actions'; import Modal from 'react-native-modalbox'; import RadioButton from 'radio-button-react-native'; import { GetGroups, SaveTaskGroup } from '../../../services/TaskService'; import { TaskStyle } from '../tasks/TaskStyle'; import { CommonStyles } from '../../../common/CommonStyles'; // import { // FontAwesome, // } from '@expo/vector-icons' import FontAwesome from 'react-native-vector-icons/FontAwesome' const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar /> </View> ); } const numColumns = 2; export default class TaskBoard extends React.Component { constructor() { super(); this.state = { isChecked: false, default: '', value: '#5a7fbf', userId: "", companyId: 0, progressVisible: false, groupList: [], groupName: "", } } goBack() { actions.push("app", {}) } handleOnPress(value) { this.setState({ value: value }) } goToCreateBoard() { this.refs.modalForBoard.open(); } _onRefresh = async () => { this.setState({ refreshing: true }); setTimeout(function () { this.setState({ refreshing: false, }); }.bind(this), 2000); this.getTaskGroups(this.state.companyId, false); }; async saveTaskGroup() { var istrue = false if (this.state.groupName !== "") { this.state.groupList.map((userData) => { if (userData.Name.toUpperCase() == this.state.groupName.toUpperCase()) { istrue = true } }); if (!istrue) { try { let groupModel = { CreatedById: this.state.userId, CompanyId: this.state.companyId, Name: this.state.groupName, BackGroundColor: this.state.value }; this.setState({ progressVisible: true }); await SaveTaskGroup(groupModel) .then(res => { this.setState({ progressVisible: false }); this.refs.modalForBoard.close(); ToastAndroid.show('Task Board Created.', ToastAndroid.TOP); this.getTaskGroups(this.state.companyId, true); }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); } catch (error) { this.setState({ progressVisible: false }); console.log(error); } } else { ToastAndroid.show('This Name already exist', ToastAndroid.TOP); } } } async componentDidMount() { const uId = await AsyncStorage.getItem("userId"); const cId = await AsyncStorage.getItem("companyId"); this.setState({ userId: uId, companyId: cId }); this.getTaskGroups(cId, true); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillMount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } handleBackButton = () => { BackHandler.exitApp() return true; } getTaskGroups = async (companyId, isProgress) => { try { this.setState({ progressVisible: isProgress }); await GetGroups(companyId) .then(res => { this.setState({ groupList: res.result, progressVisible: false }); console.log(this.state.groupList, 'BoardList....'); }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); } catch (error) { this.setState({ progressVisible: false }); console.log(error); } } gotoBordDetail(item) { actions.push("TaskBordDetail", { BordDetail: item }); } renderItem = ({ item, index }) => { return ( <TouchableOpacity style={{ flex: 1, }} onPress={() => { this.gotoBordDetail(item) }} > <View style={{ backgroundColor: item.BackGroundColor, alignItems: 'center', justifyContent: 'center', flex: 1, margin: 5, alignItems: 'center', borderRadius: 15, height: (Dimensions.get('window').width / numColumns) * .85, }} > <View style={{ justifyContent: 'center', flex: 8, marginTop: 10, }}> <View style={{ alignItems: 'center', }}> <Text style={{ fontSize: 20, color: '#ffffff', textAlign: 'center' }}>{item.Name}</Text> </View> </View> <View style={{ flex: 2, flexDirection: 'row', paddingLeft: 15, marginTop: 5, }}> <Image style={{ width: 15, height: 15 }} resizeMode='contain' source={require('../../../assets/images/group.png')}> </Image> <Text style={{ color: "white", fontSize: 10, }}> {item.TotalTask} TASKS</Text> </View> </View> </TouchableOpacity> ); }; render() { return ( <View style={TaskStyle.container}> <StatusBarPlaceHolder /> <View style={CommonStyles.HeaderContent}> <View style={CommonStyles.HeaderFirstView}> <TouchableOpacity style={CommonStyles.HeaderMenuicon} onPress={() => { Actions.drawerOpen(); }}> <Image resizeMode="contain" style={CommonStyles.HeaderMenuiconstyle} source={require('../../../assets/images/menu_b.png')}> </Image> </TouchableOpacity> <View style={CommonStyles.HeaderTextView}> <Text style={CommonStyles.HeaderTextstyle}> BOARD </Text> </View> </View> <View style={CommonStyles.createTaskButtonContainer}> <TouchableOpacity onPress={() => this.goToCreateBoard()} style={CommonStyles.createTaskButtonTouch}> <View style={CommonStyles.plusButton}> <FontAwesome name="plus" size={18} color="#ffffff"> </FontAwesome> </View> <View style={CommonStyles.ApplyTextButton}> <Text style={CommonStyles.ApplyButtonText}> BOARD </Text> </View> </TouchableOpacity> </View> {/* <View style={TaskStyle.createTaskButtonContainer}> <TouchableOpacity onPress={() => this.goToCreateBoard()} style={TaskStyle.createTaskButtonTouch}> <Image style={{ width: 90, height: 90 }} resizeMode='contain' source={require('../../../assets/images/board_p.png')}> </Image> </TouchableOpacity> </View> */} </View> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={TaskStyle.loaderIndicator} />) : null} <ScrollView> <View style={TaskStyle.scrollContainerView}> <FlatList refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> } data={this.state.groupList} keyExtractor={(i, index) => index.toString()} showsVerticalScrollIndicator={false} style={TaskStyle.taskBoardContainer} renderItem={this.renderItem} numColumns={numColumns} /> </View> </ScrollView> <Modal style={TaskStyle.colorSelectModal} position={"center"} ref={"modalForBoard"} isDisabled={this.state.isDisabled} backdropPressToClose={false} onOpened={() => this.setState({ floatButtonHide: true })} > <View style={TaskStyle.modalforViewContainerView}> <View style={TaskStyle.flexstartView}></View> <View style={TaskStyle.flexEnd}> <TouchableOpacity onPress={() => this.refs.modalForBoard.close()} style={TaskStyle.modalClose}> <Image resizeMode="contain" style={TaskStyle.closemodalImage} source={require('../../../assets/images/close.png')}> </Image> </TouchableOpacity> </View> </View> <View style={TaskStyle.modelContent}> <Text style={{ fontWeight: 'bold', fontSize: 20 }}> Create Board </Text> </View> <Text style={TaskStyle.titleText}>Title</Text> <View style={TaskStyle.creaatebordContent}> <TextInput style={TaskStyle.boardInput} placeholderTextColor="#cbcbcb" returnKeyType="next" autoCorrect={false} onChangeText={text => this.setState({ groupName: text })} /> <View style={TaskStyle.radioButtonContainer}> <Text style={{ marginRight: 10, color: '#848f98', fontFamily: 'PRODUCT_SANS_BOLD' }}>Color:</Text> <RadioButton borderWidth={4} innerCircleColor='#5a7fbf' outerCircleColor='#5a7fbf' value={"#5a7fbf"} currentValue={this.state.value} onPress={this.handleOnPress.bind(this)}> <Text style={TaskStyle.radioButtonText}></Text> </RadioButton> <RadioButton innerCircleColor='#5abfbc' outerCircleColor='#5abfbc' value={"#5abfbc"} currentValue={this.state.value} onPress={this.handleOnPress.bind(this)}> <Text style={TaskStyle.radioButtonText}></Text> </RadioButton> <RadioButton innerCircleColor='#4899d6' outerCircleColor='#4899d6' value={"#4899d6"} currentValue={this.state.value} onPress={this.handleOnPress.bind(this)}> <Text style={TaskStyle.radioButtonText}></Text> </RadioButton> <RadioButton innerCircleColor='#106d85' outerCircleColor='#106d85' value={"#106d85"} currentValue={this.state.value} onPress={this.handleOnPress.bind(this)}> <Text style={TaskStyle.radioButtonText}></Text> </RadioButton> <RadioButton innerCircleColor='#13598f' outerCircleColor='#13598f' value={"#13598f"} currentValue={this.state.value} onPress={this.handleOnPress.bind(this)}> <Text style={TaskStyle.radioButtonText}></Text> </RadioButton> </View> <TouchableOpacity style={TaskStyle.createTouchableOpacity} onPress={() => this.saveTaskGroup()} > <Text style={TaskStyle.createText}>Create</Text> </TouchableOpacity> </View> </Modal> </View> ); } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/Company.cs namespace TrillionBitsPortal.ResourceTracker.Models { public class Company { public int Id { get;set; } public string PortalUserId { get; set; } public string CompanyName { get; set; } public string Address { get; set; } public string MaximumOfficeHours { get; set; } public string OfficeOutTime { get; set; } public string PhoneNumber { get; set; } public string ImageFileName { get; set; } public string ImageFileId { get; set; } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/DataAccess/CompanyDataAccess.cs using TrillionBitsPortal.Common; using TrillionBitsPortal.Common.Models; using Microsoft.Practices.EnterpriseLibrary.Data; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using TrillionBits.DataAccess.Common; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Mappers; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.DataAccess { public class CompanyDataAccess : BaseDatabaseHandler, ICompany { public List<Company> GetCompanyByUserId( string userId ) { string err = string.Empty; string sql = @"select * from ResourceTracker_Company where PortalUserId='" + userId+"'"; var results = ExecuteDBQuery ( sql , null , CompanyMapper.ToCompanyModel ); return results.Any () ? results : null; } public List<Company> GetCompanyByEmpUserId(string userId) { string err = string.Empty; string sql = @"SELECT c.* FROM ResourceTracker_EmployeeUser eu left join ResourceTracker_Company c on eu.CompanyId=c.Id where eu.UserId='" + userId + "'"; var results = ExecuteDBQuery(sql, null, CompanyMapper.ToCompanyModel); return results.Any() ? results : null; } public Company GetCompanyByIdentity( string userId ) { string err = string.Empty; string sql = @"select * from ResourceTracker_company where Id in (select top 1 Id from Company where PortalUserId='" + userId+"' order by Id desc)"; var results = ExecuteDBQuery ( sql , null , CompanyMapper.ToCompanyModel ); return results.Any () ? results.FirstOrDefault () : null; } public Company GetCompanyById(int companyId) { string err = string.Empty; string sql = @"select * from ResourceTracker_company where Id=@id"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@id", ParamValue =companyId}, }; var results = ExecuteDBQuery(sql, queryParamList, CompanyMapper.ToCompanyModel); return results.Any() ? results.FirstOrDefault() : null; } public Company Create( Company model ) { var err = string.Empty; Database db = GetSQLDatabase (); var returnId = -1; using ( DbConnection conn = db.CreateConnection () ) { conn.Open (); DbTransaction trans = conn.BeginTransaction (); try { returnId=SaveCompany ( model , db , trans ); trans.Commit (); } catch ( Exception ex ) { trans.Rollback (); err=ex.Message; } if ( returnId>=1 ) { string sql = @"select * from ResourceTracker_company where Id in (select top 1 Id from ResourceTracker_Company where PortalUserId='" + model.PortalUserId+"' order by Id desc)"; var results = ExecuteDBQuery ( sql , null , CompanyMapper.ToCompanyModel ); model=results.Any () ? results.FirstOrDefault () : null; } } return model; } public ResponseModel UpdateCompany( Company model ) { var err = string.Empty; Database db = GetSQLDatabase (); using ( DbConnection conn = db.CreateConnection () ) { conn.Open (); DbTransaction trans = conn.BeginTransaction (); try { const string sql = @"UPDATE ResourceTracker_Company SET CompanyName=@CompanyName, Address =@Address ,PhoneNumber = @PhoneNumber,MaximumOfficeHours=@MaximumOfficeHours,OfficeOutTime=@OfficeOutTime WHERE Id=@Id"; var queryParamList = new QueryParamList { new QueryParamObj { ParamName = "@CompanyName", ParamValue = model.CompanyName}, new QueryParamObj { ParamName = "@Address", ParamValue = model.Address}, new QueryParamObj { ParamName = "@PhoneNumber", ParamValue = model.PhoneNumber}, new QueryParamObj { ParamName = "@MaximumOfficeHours", ParamValue =model.MaximumOfficeHours}, new QueryParamObj { ParamName = "@OfficeOutTime", ParamValue =model.OfficeOutTime}, new QueryParamObj { ParamName = "@Id", ParamValue = model.Id} }; DBExecCommandEx ( sql , queryParamList , ref err ); trans.Commit (); } catch ( Exception ex ) { trans.Rollback (); err=ex.Message; } } return new ResponseModel { Success=string.IsNullOrEmpty ( err ) }; } public int SaveCompany( Company model , Database db , DbTransaction trans ) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@PortalUserId", ParamValue =model.PortalUserId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CompanyName", ParamValue =model.CompanyName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Address", ParamValue =model.Address}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@PhoneNumber", ParamValue =model.PhoneNumber}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@MaximumOfficeHours", ParamValue =model.MaximumOfficeHours}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@OfficeOutTime", ParamValue =model.OfficeOutTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ImageFileName", ParamValue =model.ImageFileName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ImageFileId", ParamValue =model.ImageFileId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CreatedDate", ParamValue =DateTime.UtcNow,DBType=DbType.DateTime}, }; const string sql = @"IF NOT EXISTS(SELECT TOP 1 * FROM ResourceTracker_Company C WHERE C.CompanyName=@CompanyName AND PortalUserId=@PortalUserId) BEGIN INSERT INTO ResourceTracker_Company(PortalUserId,CompanyName,Address,PhoneNumber,MaximumOfficeHours,OfficeOutTime,ImageFileName,ImageFileId,CreatedDate) VALUES(@PortalUserId,@CompanyName,@Address,@PhoneNumber,@MaximumOfficeHours,@OfficeOutTime,@ImageFileName,@ImageFileId,@CreatedDate) END"; return DBExecCommandExTran ( sql , queryParamList , trans , db , ref errMessage ); } public List<CompanyListModel> GetCompanyList() { const string sql = @"DECLARE @T AS TABLE(Id INT,TotalEmployee INT) INSERT INTO @T(Id,TotalEmployee) SELECT U.CompanyId,Count(U.Id) FROM ResourceTracker_EmployeeUser U WHERE U.IsActive=1 GROUP BY U.CompanyId SELECT C.Id,C.CompanyName,C.Address,c.PhoneNumber OfficePhone,C.CreatedDate,CR.Email, cr.FullName ContactPerson,cr.ContactNo ContactPersonMobile,ISNULL(T.TotalEmployee,0) TotalEmployee FROM UserCredentials CR left JOIN ResourceTracker_Company C ON c.PortalUserId=cr.Id LEFT JOIN @T T ON C.Id=T.Id where cr.UserTypeId=6"; var data = ExecuteDBQuery(sql, null, CompanyMapper.ToList); return data; } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/ResourceTracker/RtCompanyApiController.cs using System.Net; using System.Net.Http; using System.Web.Http; using TrillionBits.ResourceTracker; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.Web.Controllers.Api.ResourceTracker { public class RtCompanyApiController : BaseApiController { private readonly ICompany _companyRepository; public RtCompanyApiController() { _companyRepository = RTUnityMapper.GetInstance<ICompany>(); } [HttpGet] public HttpResponseMessage GetCompanyByUserId(string userId) { var result = _companyRepository.GetCompanyByUserId(userId); return Request.CreateResponse(HttpStatusCode.OK, result); } [HttpGet] public HttpResponseMessage GetCompanyByEmpUserId(string userId) { var result = _companyRepository.GetCompanyByEmpUserId(userId); return Request.CreateResponse(HttpStatusCode.OK, result); } [HttpGet] public HttpResponseMessage GetCompanyByIdentity(string userId) { var result = _companyRepository.GetCompanyByIdentity(userId); return Request.CreateResponse(HttpStatusCode.OK, result); } [HttpPost] public IHttpActionResult Save([FromBody]Company json) { var company = new Company { CompanyName = json.CompanyName, Address = json.Address, PhoneNumber = json.PhoneNumber, MaximumOfficeHours = json.MaximumOfficeHours, OfficeOutTime = json.OfficeOutTime, PortalUserId = json.PortalUserId, ImageFileName = json.ImageFileName, ImageFileId = json.ImageFileId }; var response = _companyRepository.Create(company); return Ok(response); } [HttpPost] public IHttpActionResult UpdateCompany(Company json) { var company = new Company { Id = json.Id, CompanyName = json.CompanyName, Address = json.Address, PhoneNumber = json.PhoneNumber, MaximumOfficeHours = json.MaximumOfficeHours, OfficeOutTime = json.OfficeOutTime, ImageFileName = json.ImageFileName, ImageFileId = json.ImageFileId }; var response = _companyRepository.UpdateCompany(company); return Ok(response); } } } <file_sep>/hr Office/HrApp/components/Screen/tasks/TaskStyle.js import { StyleSheet, Dimensions } from 'react-native'; const { height } = Dimensions.get('window'); export const TaskStyle = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f6f7f9', flexDirection: 'column', }, descriptionInputRow: { margin: 10, flexDirection: 'column', height: (height * 30) / 100, }, headerContainer: { flexDirection: 'row', height: 60, paddingTop: 0, backgroundColor: '#fff', shadowColor: 'rgba(181,181,181,0.02)', shadowOffset: { width: 0, height: -2 }, elevation: 10, shadowRadius: 8, shadowOpacity: 0.3, alignItems: 'center', paddingHorizontal: 10, justifyContent: 'space-between', borderBottomRightRadius: 10, borderBottomLeftRadius: 10 }, headerText: { fontWeight: 'bold', fontSize: 20, color: '#141414', marginTop: 3, }, headerBar: { justifyContent: 'space-between', backgroundColor: 'white', flexDirection: 'row', padding: 10, borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 0, height: -5 }, elevation: 10, height: 60, }, backIcon: { justifyContent: 'flex-start', flexDirection: 'row', alignItems: 'center', }, backIconTouch: { padding: 10, flexDirection: 'row', alignItems: 'center' }, headerTitleText: { color: '#4E4E4E', marginTop: 1, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: 'center', }, headerTitle: { padding: 0, paddingLeft: 10, margin: 0, flexDirection: 'row', }, createTaskButtonContainer: { justifyContent: 'flex-end', marginRight: 0, marginLeft: 0, flexDirection: 'row', alignItems: 'center', }, createTaskButtonTouch: { flexDirection: 'row', alignItems: 'center', padding: 3, }, taskStatusContainer: { width: "100%", flexDirection: 'row', justifyContent: 'center', marginHorizontal: 5, marginLeft: -2, alignItems: 'center', marginTop: -4, backgroundColor: '#f6f7f9', borderBottomLeftRadius: 10, borderBottomRightRadius: 10, }, onProgress: { color: "#f5f7fb" // padding: 5, // width: "30%", // height: 41.1, // borderRightColor: '#ffffff', // backgroundColor: "#f5f7fb", // justifyContent: 'center', // flexDirection: 'row', // alignItems: 'center', // marginTop: 3, // marginBottom: 3, // borderRightWidth: 2, }, completed: { padding: 5, width: "30%", height: 41.1, borderRightWidth: 2, borderRightColor: '#ffffff', backgroundColor: "#f5f7fb", justifyContent: 'center', flexDirection: 'row', alignItems: 'center', marginTop: 3, marginBottom: 3 }, cancelled: { height: 41.1, padding: 5, justifyContent: 'center', flexDirection: 'row', alignItems: 'center', backgroundColor: "#f5f7fb", marginTop: 3, marginBottom: 3 }, progressActiveNotClicked: { fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#bbc3c7", paddingTop: 8, paddingLeft: 2, justifyContent: 'flex-start', }, progressActiveClicked: { color: "#3ab875", fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", paddingTop: 8, paddingLeft: 2, justifyContent: 'flex-start', }, completeActiveNotClicked: { fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", paddingTop: 8, paddingLeft: 2, justifyContent: 'center', color: "#bbc3c7", }, completeActiveClicked: { fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", paddingTop: 8, paddingLeft: 2, justifyContent: 'center', color: "#6f9fc9", }, cancelActiveClicked: { fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#e2b24e", paddingTop: 8, paddingLeft: 1, justifyContent: 'center', }, cancelActiveNotClicked: { fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#bbc3c7", paddingTop: 8, paddingLeft: 1, justifyContent: 'center', }, flatlistContainer: { flexDirection: 'column', justifyContent: 'space-between', paddingTop: 8, paddingBottom: 5, padding: 13, borderRadius: 15, marginTop: 10, marginBottom: 10, flex: 1, flexWrap: 'wrap', backgroundColor: "#f6f7f9", }, taskHeader: { flexDirection: 'row', justifyContent: 'flex-start', flex: 1, flexWrap: 'wrap', padding: 2, paddingTop: 5, marginBottom: 15, }, taskHeaderText: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 14, textAlign: "left", color: "#505050", }, taskBody: { flexDirection: 'row', justifyContent: 'space-between', padding: 2, alignItems: 'center', flex: 1, flexWrap: 'wrap', }, taskBodyLeft: { justifyContent: 'flex-start', flex: 1, paddingBottom: 5, flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', }, taskBodyText: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#878787", marginLeft: 2, }, taskBodyRight: { justifyContent: 'flex-end', flexDirection: 'row', alignItems: 'flex-start', flex: 1, flexWrap: 'wrap', }, taskFooter: { flexDirection: 'row', justifyContent: 'space-between', borderTopWidth: 0.5, borderTopColor: "#f6f7f9", paddingTop: 5, paddingBottom: 5, alignItems: 'center', }, taskFooterLeft: { flexDirection: 'row', justifyContent: 'flex-start', width: "50%", // alignItems: 'flex-start' alignItems: 'center', }, taskFooterText: { paddingLeft: 10, justifyContent: 'flex-end', fontFamily: "Montserrat_Bold", fontSize: 10, textAlign: "left", // color: "#b2955a",//orange color: "#3d8851",//Green // color: "#823e3e",//Red }, taskFooterRight: { flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center', }, taskFooterDateText: { fontFamily: "Montserrat_Bold", fontSize: 11, textAlign: "left", color: "#878787" }, viewTaskContainer: { flex: 1, backgroundColor: '#ffffff', flexDirection: 'column', }, viewTaskInnerContainer: { flexDirection: 'row', height: 60, paddingTop: 0, backgroundColor: '#ffffff', shadowColor: 'rgba(181,181,181,0.02)', shadowOffset: { width: 0, height: -2 }, elevation: 10, shadowRadius: 8, shadowOpacity: 0.3, alignItems: 'center', paddingHorizontal: 10, justifyContent: 'space-between', borderBottomRightRadius: 10, borderBottomLeftRadius: 10, }, viewTaskHeader: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: "center", color: "#141414", marginTop: 4, }, viewTaskTitle: { width: "100%", flexDirection: 'column', justifyContent: 'flex-start', marginHorizontal: 5, marginLeft: 1, marginRight: 1.5, marginTop: -4, paddingVertical: 15, padding: 10, backgroundColor: '#ffffff', }, viewTaskTitle1: { width: "100%", flexDirection: 'column', justifyContent: 'flex-start', marginHorizontal: 5, marginLeft: 1, marginRight: 1.5, marginTop: -4, paddingVertical: 15, padding: 10, backgroundColor: '#ffffff', }, viewTaskTitleText: { paddingVertical: 8, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: "left", color: "#505050", borderBottomColor: '#f6f7f9', borderBottomWidth: 1, }, viewTaskDescription: { paddingVertical: 8, color: "#505050", fontFamily: "PRODUCT_SANS_REGULAR", fontSize: 16, textAlign: "left", }, viewTaskBodyContainer: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 2, marginHorizontal: 8, marginVertical: 8, }, viewTaskBodyContainer1: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 2, marginHorizontal: 8, }, viewTaskStatusContainer: { justifyContent: 'flex-start', flexDirection: 'column', marginBottom: 3, width: "48%" }, viewTaskStatusLabel: { opacity: 0.3, fontSize: 13, fontFamily: "PRODUCT_SANS_BOLD", textAlign: "left", color: "#848f98", marginBottom: 5, marginLeft: 12, }, viewTaskStatusCheckboxContainer: { borderRadius: 10, flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'center', padding: 5, }, viewTaskStatusText: { marginLeft: 8, justifyContent: 'center', fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#ffffff", padding: 2, }, viewTaskDueDateContainer: { justifyContent: 'flex-end', flexDirection: 'column', marginBottom: 3, width: "50%", }, viewTaskDueDateLabel: { justifyContent: 'flex-end', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "right", color: "#1a1a1a", marginBottom: 5, marginRight: "25%", }, viewTaskDueDateValueContainer: { borderRadius: 5, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', padding: 5, backgroundColor: "#f6f7f9", marginRight: 7, }, viewTaskDueDateValue: { marginLeft: 8, fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, viewTaskAssignToContainer: { flex: 1, flexDirection: 'row', alignItems: 'center', marginHorizontal: 10 }, viewTaskAssignToInnerContainer: { flex: 1, borderRadius: 4, padding: 7, backgroundColor: '#4375d9', alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between', }, viewTaskAssignToLeftIcon: { flex: 1, flexWrap: 'wrap', fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "left", color: "#ffffff" }, viewTaskAssignToBottom: { flex: 1, borderRadius: 4, padding: 7, backgroundColor: '#ffffff', alignItems: 'center', flexDirection: 'row', marginLeft: 10, justifyContent: 'center', }, viewTaskAttachmentContainer: { width: "95%", borderRadius: 4, backgroundColor: "#ffffff", alignItems: 'center', justifyContent: 'space-between', // padding: 8, paddingVertical: 7, marginTop: 4, marginBottom: 4, marginHorizontal: 10, flexDirection: 'row', borderBottomColor: '#f6f7f9', borderBottomWidth: 1, }, viewTaskAttachmentInnerContainer: { justifyContent: 'flex-start', flexDirection: 'row', marginLeft: 18, alignItems: 'center', }, viewTaskAttachmentLeftIcon: { fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#4a535b", marginLeft: 6, }, viewTaskAttachmentPlusIcon: { justifyContent: 'flex-end', flexDirection: 'row', alignItems: 'center', padding: 5, }, loaderIndicator: { position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, justifyContent: 'center', alignContent: 'center', }, createTaskSaveButtonContainer: { position: 'absolute', bottom: 0, width: "100%", justifyContent: 'center', alignItems: 'center', height: 50, flexDirection: 'row', backgroundColor: "#4570cb", }, createTaskSaveButtonText: { fontFamily: "Montserrat_Bold", fontSize: 15, textAlign: "center", color: "#ffffff" }, createTaskTitleLabel: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "left", color: "#848f98", marginBottom: 10, marginLeft: 20, marginTop: 5 }, createTaskTitleLabelExpenses: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "left", color: "#848f98", marginBottom:5, marginLeft: 20, marginTop: 12 }, createTaskTitleLabel1: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "left", color: "#848f98", marginBottom: 10, marginLeft: 15, marginTop: 15 }, createTaskTitleLabel11: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "left", color: "#848f98", marginBottom: 10, marginLeft: 5, marginTop: 5 }, createTaskTitleTextBox: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "left", color: "#4a535b", flex: 1, flexWrap: 'wrap', paddingHorizontal: 7, paddingVertical: 5, borderRadius: 8, backgroundColor: "#f5f7fb", }, createTaskTitleTextBox1: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: "left", color: "#4a535b", flex: 1, flexWrap: 'wrap', paddingHorizontal: 7, paddingVertical: 8, borderRadius: 8, backgroundColor: "#f5f7fb", marginLeft: 10, marginRight: 10, }, createTaskTitleTextBoxEx: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "left", color: "#4a535b", flex: 1, flexWrap: 'wrap', paddingHorizontal: 10, paddingVertical:7, borderRadius: 8, backgroundColor: "#f5f7fb", margin: 10,marginTop:3, }, createTaskDescriptionLabel: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "left", color: "#848f98", marginBottom: 10, marginLeft: 20, }, createTaskDescriptionTextBox: { textAlignVertical: "top", fontFamily: "OPENSANS_REGULAR", fontSize: 13, textAlign: "left", color: "#4a535b", flex: 1, flexWrap: 'wrap', height: 200, paddingHorizontal: 7, paddingVertical: 6, backgroundColor: "#f5f7fb", borderRadius: 8, }, createTaskDescriptionTextBox1: { textAlignVertical: "top", fontFamily: "OPENSANS_REGULAR", fontSize: 13, textAlign: "left", color: "#4a535b", flex: 1, flexWrap: 'wrap', height: 150, paddingHorizontal: 7, paddingVertical: 6, backgroundColor: "#f5f7fb", borderRadius: 8, marginTop: 10, }, assignePeopleContainer: { flex: 1, margin: 10, flexDirection: 'row', marginLeft: 20, alignItems: 'center', justifyContent: 'space-between', }, emptyView: { height: 50 }, assigneePeopleTextBox: { fontFamily: "Montserrat_Bold", fontSize: 13, textAlign: "left", color: "#4a535b", flex: 1, paddingHorizontal: 7, }, assigneePeopleTextBoxDivider: { backgroundColor: "#ffffff", borderTopColor: '#dee1e5', borderTopWidth: .3, width: "50%", marginLeft: 10, marginTop: -10, }, createTaskAttachmentContainer: { flex: 1, margin: 10, flexDirection: 'column', justifyContent: 'space-between', }, backarrow: { marginLeft: 0 }, createTaskAttachmentInnerContainer: { flex: 1, marginBottom: 7, flexDirection: 'row', alignItems: 'center' }, createTaskAttachmentLeft: { borderRadius: 4, padding: 7, backgroundColor: "#f1f3f5", flexDirection: 'row', flex: 1, }, createTaskAttachmentLabel: { fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#4a535b" }, createTaskSetLocationIcon: { borderRadius: 4, padding: 7, backgroundColor: "#f1f3f5", flexDirection: 'row', flex: 1, marginLeft: 10, }, createTaskSetLocationText: { fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#4a535b" }, createTaskDueDateContainer: { flex: 1, marginBottom: 7, flexDirection: 'row', alignItems: 'center', marginTop: 3, }, createTaskDueDateIcon: { borderRadius: 4, padding: 7, backgroundColor: "#f1f3f5", flexDirection: 'row', flex: 1, }, createTaskDueDateText: { fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#4a535b" }, taskBoardContainer: { flex: 1, // padding: 10, }, scrollContainerView: { flex: 1, marginHorizontal: 5, marginVertical: 5 }, colorSelectModal: { height: 300, width: "83%", borderRadius: 20, }, modalforViewContainerView: { justifyContent: "space-between", flexDirection: "column" }, flexstartView: { alignItems: "flex-start" }, flexEnd: { alignItems: "flex-end" }, closemodalImage: { width:15 , height: 15,marginRight:17,marginTop:15, }, titleText: { color: '#848f98', fontFamily: 'PRODUCT_SANS_BOLD', marginLeft: 30 }, creaatebordContent: { alignSelf: "center" }, radioButtonContainer: { flexDirection: 'row', padding: 25, }, radioButtonText: { textAlign: "right", fontSize: 16, color: '#6C7272', fontWeight: '500', marginTop: 0, marginRight: 5, marginLeft: 2 }, createTouchableOpacity: { backgroundColor: '#3D3159', padding: 10, width: 100, alignSelf: 'center', borderRadius: 20, marginTop: "3%", alignItems: 'center', }, createText: { color: 'white', fontWeight: 'bold' }, modalClose: { marginLeft: 0, marginTop: 0, }, modelContent: { alignItems: 'center' }, boardInput: { width: 240, height: 40, backgroundColor: '#ebebeb', color: '#2c2930', paddingHorizontal: 10, alignSelf: 'center', borderRadius: 10, textAlign: 'center', marginVertical: 8, }, createtaskcontainer: { flex: 1, backgroundColor: '#ffffff', flexDirection: 'column', }, createtaskBackimage: { width: 25, height: 25 }, createTasktitleView: { alignItems: 'center' }, cteateflexEnd: { alignItems: 'flex-end', marginRight: 10, }, descriptioncontainerView: { flex: 1, margin: 10, flexDirection: 'column', }, Viewforavoid: { borderRadius: 4, padding: 7, flexDirection: 'row', flex: 1, marginLeft: 10, }, modalforCreateCompany1: { height: 350, width: "75%", borderRadius: 20, backgroundColor: '#EBEBEB', }, dblModelContent: { paddingVertical: 20, }, dbblModalText: { fontWeight: 'bold', fontSize: 20, color: '#535353' }, }); <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/DbUtility/ExtensionMethods.cs using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.Common { public static class ExtensionMethods { public const string UserCookieName = "LogUserInfo"; public static void AcceptChanges<T>(this List<T> list) where T : class { if (!typeof(T).IsBaseModel()) { return; } BaseModel[] array = list.Cast<BaseModel>().ToArray<BaseModel>(); int num = 0; while (num < (int)array.Length) { BaseModel baseModel = array[num]; switch (baseModel.ModelState) { case ModelState.Added: case ModelState.Modified: { baseModel.SetUnchanged(); goto case ModelState.Unchanged; } case ModelState.Deleted: case ModelState.Detached: { list.Remove((T)Convert.ChangeType(baseModel, typeof(T))); goto case ModelState.Unchanged; } case ModelState.Unchanged: { num++; continue; } default: { goto case ModelState.Unchanged; } } } } public static string BuildXmlString(string xmlRootName, IEnumerable<string> values) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendFormat("<{0}>", xmlRootName); foreach (string value in values) { stringBuilder.AppendFormat("<value>{0}</value>", value); } stringBuilder.AppendFormat("</{0}>", xmlRootName); return stringBuilder.ToString(); } public static void CloseReader(this IDataReader reader) { if (reader.IsNotNull() && !reader.IsClosed) { reader.Close(); } } public static bool Compare<T>(T x, T y) { return EqualityComparer<T>.Default.Equals(x, y); } public static void Copy(this object dst, object src) { PropertyInfo[] properties = src.GetType().GetProperties(); for (int i = 0; i < (int)properties.Length; i++) { PropertyInfo propertyInfo = properties[i]; if (propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0) { PropertyInfo property = dst.GetType().GetProperty(propertyInfo.Name); if (property != null && property.CanWrite) { property.SetValue(dst, propertyInfo.GetValue(src, null), null); } } } } public static List<T> Copy<T>(this List<T> list) { MemoryStream memoryStream = new MemoryStream(); BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, list); memoryStream.Position = (long)0; return (List<T>)binaryFormatter.Deserialize(memoryStream); } public static string FromDictionaryToJson(this Dictionary<string, string> dictionary) { IEnumerable<string> strs = from kvp in dictionary select string.Format("\"{0}\":\"{1}\"", kvp.Key, string.Concat(",", kvp.Value)); return string.Concat("{", string.Join(",", strs), "}"); } public static Dictionary<string, string> FromJsonToDictionary(this string json) { return json.Replace("{", string.Empty).Replace("}", string.Empty).Replace("\"", string.Empty).Split(new char[] { ',' }).ToDictionary<string, string, string>((string item) => item.Split(new char[] { ':' })[0], (string item) => item.Split(new char[] { ':' })[1]); } public static int GetAge(this DateTime dateOfBirth) { DateTime today = DateTime.Today; int year = (today.Year * 100 + today.Month) * 100 + today.Day; int num = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day; return (year - num) / 10000; } public static List<KeyValuePair<int, string>> GetAllMonths() { List<KeyValuePair<int, string>> keyValuePairs = new List<KeyValuePair<int, string>>(); for (int i = 1; i <= 12; i++) { if (DateTimeFormatInfo.CurrentInfo != null) { keyValuePairs.Add(new KeyValuePair<int, string>(i, DateTimeFormatInfo.CurrentInfo.GetMonthName(i))); } } return keyValuePairs; } public static bool GetBoolean(this IDataRecord reader, string columnName) { if (reader[columnName].Equals(DBNull.Value)) { return false; } return (bool)reader[columnName]; } public static byte[] GetBytes(this DbDataRecord reader, string columnName) { if (reader[columnName].Equals(DBNull.Value)) { return null; } return (byte[])reader[columnName]; } public static IEnumerable<BaseModel> GetChanges(this IEnumerable<BaseModel> list) { return list.Where<BaseModel>((BaseModel item) => { if (item.IsAdded || item.IsModified) { return true; } return item.IsDeleted; }); } public static IEnumerable<BaseModel> GetChanges(this IEnumerable<BaseModel> list, ModelState itemState) { return from item in list where item.ModelState.Equals(itemState) select item; } public static DateTime GetDateTime(this IDataRecord reader, string columnName) { if (reader[columnName].Equals(DBNull.Value)) { return DateTime.MinValue; } return DateTime.Parse(reader[columnName].ToString()); } public static decimal GetDecimal(this IDataRecord reader, string columnName) { if (!reader[columnName].Equals(DBNull.Value)) { return (decimal)reader[columnName]; } return new decimal(0, 0, 0, false, 1); } public static double GetDouble(this IDataRecord reader, string columnName) { if (reader[columnName].Equals(DBNull.Value)) { return 0; } return (double)reader[columnName]; } public static short GetInt16(this IDataRecord reader, string columnName) { if (reader[columnName].Equals(DBNull.Value)) { return 0; } return (short)reader[columnName]; } public static int GetInt32(this IDataRecord reader, string columnName) { if (reader[columnName].Equals(DBNull.Value)) { return 0; } return (int)reader[columnName]; } public static long GetInt64(this IDataRecord reader, string columnName) { if (reader[columnName].Equals(DBNull.Value)) { return (long)0; } return (long)reader[columnName]; } public static string GetRandomNumber(int count) { if (count < 4) { count = 4; } Random random = new Random(); return new string(( from s in Enumerable.Repeat<string>("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", count) select s[random.Next(s.Length)]).ToArray<char>()); } public static string GetString(this IDataRecord reader, string columnName) { return reader[columnName].ToString(); } public static Type GetTypeFromName(this string typeName) { if (typeName == null) { throw new ArgumentNullException("typeName"); } bool flag = false; bool flag1 = false; if (typeName.IndexOf("[]", StringComparison.Ordinal) != -1) { flag = true; typeName = typeName.Remove(typeName.IndexOf("[]", StringComparison.Ordinal), 2); } if (typeName.IndexOf("?", StringComparison.Ordinal) != -1) { flag1 = true; typeName = typeName.Remove(typeName.IndexOf("?", StringComparison.Ordinal), 1); } typeName = typeName.ToLower(); string str = null; switch (typeName) { case "bool": case "boolean": { str = "System.bool"; break; } case "byte": { str = "System.Byte"; break; } case "char": { str = "System.Char"; break; } case "datetime": { str = "System.DateTime"; break; } case "datetimeoffset": { str = "System.DateTimeOffset"; break; } case "decimal": { str = "System.Decimal"; break; } case "double": { str = "System.Double"; break; } case "float": { str = "System.Single"; break; } case "int16": case "short": { str = "System.Int16"; break; } case "int32": case "int": { str = "System.int"; break; } case "int64": case "long": { str = "System.Int64"; break; } case "object": { str = "System.object"; break; } case "sbyte": { str = "System.SByte"; break; } case "string": { str = "System.string"; break; } case "timespan": { str = "System.TimeSpan"; break; } case "uint16": case "ushort": { str = "System.UInt16"; break; } case "uint32": case "uint": { str = "System.UInt32"; break; } case "uint64": case "ulong": { str = "System.UInt64"; break; } } if (str == null) { str = typeName; } else { if (flag) { str = string.Concat(str, "[]"); } if (flag1) { str = string.Concat("System.Nullable`1[", str, "]"); } } return Type.GetType(str); } public static bool IsBaseModel(this Type type) { if (type.BaseType == null) { return false; } if (type.BaseType == typeof(BaseModel)) { return true; } return type.BaseType.IsBaseModel(); } public static bool IsFalse(this bool val) { return !val; } public static bool IsMinValue(this DateTime obj) { return obj == DateTime.MinValue; } public static bool IsNotMinValue(this DateTime obj) { return obj != DateTime.MinValue; } public static bool IsNotNull(this BaseModel obj) { return obj != null; } public static bool IsNotNull(this object obj) { return obj != null; } public static bool IsNotZero(this long val) { return !val.Equals((long)0); } public static bool IsNotZero(this decimal val) { return !val.Equals(decimal.Zero); } public static bool IsNotZero(this double val) { return !val.Equals(0); } public static bool IsNotZero(this int val) { return !val.Equals(0); } public static bool IsNull(this BaseModel obj) { return obj == null; } public static bool IsNull(this object obj) { return obj == null; } public static bool IsNullable<T>(this T obj) { if (obj.IsNull()) { return true; } Type type = typeof(T); if (!type.IsValueType) { return true; } return Nullable.GetUnderlyingType(type).IsNotNull(); } public static bool IsNullable(this Type type) { if (type.IsNull()) { return true; } if (!type.IsValueType) { return true; } return Nullable.GetUnderlyingType(type).IsNotNull(); } public static bool IsNullOrDbNull(this object obj) { if (obj == null) { return true; } return obj == DBNull.Value; } public static bool IsNullOrMinValue(this DateTime? obj) { if (!obj.HasValue) { return true; } DateTime? nullable = obj; DateTime minValue = DateTime.MinValue; if (!nullable.HasValue) { return false; } if (!nullable.HasValue) { return true; } return nullable.GetValueOrDefault() == minValue; } public static bool IsTrue(this bool val) { return val; } public static bool IsZero(this long val) { return val.Equals((long)0); } public static bool IsZero(this decimal val) { return val.Equals(decimal.Zero); } public static bool IsZero(this double val) { return val.Equals(0); } public static bool IsZero(this int val) { return val.Equals(0); } public static IList<dynamic> ListFrom<T>() { List<object> objs = new List<object>(); Type type = typeof(T); foreach (object value in Enum.GetValues(type)) { objs.Add(new { Name = Enum.GetName(type, value), Value = value }); } return objs; } public static T MapField<T>(this object value) { if (value.GetType() == typeof(T)) { return (T)value; } if (value == DBNull.Value) { return default(T); } Type underlyingType = Nullable.GetUnderlyingType(typeof(T)); if (underlyingType.IsNull()) { underlyingType = typeof(T); } return (T)Convert.ChangeType(value, underlyingType); } public static object MapField(this object value, Type type) { if (value.GetType() == type) { return value; } if (value == DBNull.Value) { return null; } if (type.IsEnum) { if (value is string) return Enum.Parse(type, value as string); else return Enum.ToObject(type, value); } if (!type.IsInterface && type.IsGenericType) { Type innerType = type.GetGenericArguments()[0]; object innerValue = Convert.ChangeType(value, innerType); return Activator.CreateInstance(type, new object[] { innerValue }); } if (value is string && type == typeof(Guid)) return new Guid(value as string); if (value is string && type == typeof(Version)) return new Version(value as string); if (!(value is IConvertible)) return value.ToString(); Type underlyingType = Nullable.GetUnderlyingType(type); if (underlyingType.IsNull()) { underlyingType = type; } return Convert.ChangeType(value, underlyingType); } public static DateTime MapTimeField(this object value) { DateTime minValue; if (value != DBNull.Value) { minValue = DateTime.MinValue; return minValue.Add((TimeSpan)value); } if (!value.IsNullable<object>()) { throw new NullReferenceException(); } minValue = new DateTime(); return minValue; } public static DateTime? MapTimeNullableField(this object value) { if (value != DBNull.Value) { return new DateTime?(DateTime.MinValue.Add((TimeSpan)value)); } if (!value.IsNullable<object>()) { throw new NullReferenceException(); } return null; } public static bool NotEquals<T>(this T val, T compVal) { return !ExtensionMethods.Compare<T>(val, compVal); } public static IEnumerable<BaseModel>[] Reverse(this IEnumerable<BaseModel>[] list) { IEnumerable<BaseModel>[] enumerableArrays = new IEnumerable<BaseModel>[(int)list.Length]; int num = 0; for (int i = (int)list.Length; i >= 1; i--) { enumerableArrays[num] = list[i - 1]; num++; } return enumerableArrays; } public static void Sort<T, TU>(this List<T> list, Func<T, TU> expression, IComparer<TU> comparer) where TU : IComparable<TU> { list.Sort((T x, T y) => comparer.Compare(expression(x), expression(y))); } public static string StringValue(this DateTime dateTime) { if (dateTime.Equals(DateTime.MinValue)) { return string.Empty; } return dateTime.ToShortDateString(); } public static string StringValue(this DateTime? dateTime) { if (!dateTime.HasValue) { return string.Empty; } return Convert.ToDateTime(dateTime).ToShortDateString(); } public static object Value(this object value) { object obj = value; if (obj == null) { obj = DBNull.Value; } return obj; } public static object Value(this DateTime dateTime, string format = "dd-MMM-yyyy") { if (dateTime.Equals(DateTime.MinValue)) { return DBNull.Value; } return dateTime.ToString(format); } public static object Value(this DateTime? dateTime, string format = "dd-MMM-yyyy") { if (!dateTime.HasValue || dateTime.Equals(DateTime.MinValue)) { return DBNull.Value; } return Convert.ToDateTime(dateTime).ToString(format); } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/BaseModel.cs using TrillionBitsPortal.Common; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TrillionBitsPortal.ResourceTracker.Models { [Serializable] public abstract class BaseModel : IModelState { private ModelState state; [Key] [JsonProperty("Id")] public virtual int Id { get; set; } [NotMapped] public int TotalRows { get; set; } public Dictionary<string, object> GetParameterInfo { get; set; } [Browsable(false)] public bool IsAdded { get { return this.state.Equals(ModelState.Added); } } [Browsable(false)] public bool IsDeleted { get { return this.state.Equals(ModelState.Deleted); } } [Browsable(false)] public bool IsDetached { get { return this.state.Equals(ModelState.Detached); } } [Browsable(false)] public bool IsModified { get { return this.state.Equals(ModelState.Modified); } } [Browsable(false)] public bool IsUnchanged { get { return this.state.Equals(ModelState.Unchanged); } } [Browsable(false)] [NotMapped] public ModelState ModelState { get { return this.state; } set { this.state = value; } } protected BaseModel() { } public T Copy<T>() { return (T)this.MemberwiseClone(); } protected bool PropertyChanged<T>(T oldValue, T newValue) { if (!oldValue.NotEquals<T>(newValue)) { return false; } if (this.IsUnchanged) { this.SetModified(); } return true; } public void SetAdded() { this.state = ModelState.Added; } public void SetDeleted() { this.state = (this.IsAdded ? ModelState.Detached : ModelState.Deleted); } public void SetDetached() { this.state = ModelState.Detached; } public void SetModified() { this.state = ModelState.Modified; } public void SetUnchanged() { this.state = ModelState.Unchanged; } public override string ToString() { return string.Format("Name = {0}, State = {1}", this.GetType().Name, this.state); } } } <file_sep>/hr Office/HrApp/components/Screen/company/CompanysetupComponent.js import React from 'react'; import { View, FlatList, StyleSheet } from 'react-native'; import CompanyLists from './CompanySetupRowComponent'; const styles = StyleSheet.create({ container: { flex: 1, }, }); const CompanysetupComponent = (props) => ( <View style={styles.container}> <FlatList data={props.itemList} keyExtractor={(x, i) => i.toString()} renderItem={({ item }) => <CompanyLists itemData={item}/> } /> </View> ); export default CompanysetupComponent;<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/EmployeeViewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.ResourceTracker.Models { public class EmployeeViewModel { public int Id { get; set; } public string UserId { get; set; } public string UserName { get; set; } public string UserFullName { get; set; } public string PhoneNumber { get; set; } public string Gender { get; set; } public string Designation { get; set; } public bool IsAutoCheckPoint { get; set; } public string DepartmentName { get; set; } public int? CompanyId { get; set; } public int? DepartmentId { get; set; } public string AutoCheckPointTime { get; set; } public string MaximumOfficeHours { get; set; } public string OfficeOutTime { get; set; } public string ImageFileName { get; set; } public string ImageFileId { get; set; } public string Checkin { get; set; } public string Checkout { get; set; } public string CheckinTime { get; set; } public string CheckOutTime { get; set; } public bool IsCheckedIn { get { return !string.IsNullOrEmpty(Checkin) && string.IsNullOrEmpty(Checkout); } } public bool IsCheckedOut { get { return !string.IsNullOrEmpty(Checkin) && !string.IsNullOrEmpty(Checkout); } } public bool NotAttend { get { return string.IsNullOrEmpty(Checkin) && string.IsNullOrEmpty(Checkout); } } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/DbUtility/Util.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.Common { public static class Util { public const string DateFormat = "dd-MMM-yyyy"; public const string TimeFormat = "hh:mm:ss tt"; public const string EntryTimeFormat = "hh:mm tt"; public const string DateTimeFormat = "yyyy-MM-dd hh:mm:ss.fff"; public static string ConvertedDateFormat; public static string DbDateFormat; static Util() { Util.ConvertedDateFormat = "MM/dd/yyyy"; Util.DbDateFormat = "yyyy-MM-dd"; } public static int GetEnumValue(Type enumType, string value) { if (value == "Integer") { value = "int"; } else if (value == "Float") { value = "double"; } return (int)Enum.Parse(enumType, value); } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Interfaces/IUserCredential.cs using System.Collections.Generic; using TrillionBitsPortal.Common.Models; using TrillionBitsPortal.Common; namespace TrillionBitsPortal.ResourceTracker.Interfaces { public interface IUserCredential { ResponseModel Save(UserCredentialModel model); UserCredentialModel Get(string username, string password); ResponseModel ChangePassword(string userInitial, string newPassword); UserCredentialModel GetProfileDetails(string userId); UserCredentialModel GetByLoginID(string loginID); UserCredentialModel GetByLoginID(string loginID, UserType uType); UserCredentialModel GetByLoginID(string loginID, string password, UserType uType); UserCredentialModel GetUserFullInfo(string userId); } }<file_sep>/hr Office/HrApp/components/Screen/UserScreen/tasks/TaskListComponent.js import React from 'react'; import { View, FlatList, StyleSheet,RefreshControl,Platform,StatusBar } from 'react-native'; import TaskLists from './TaskListRowCompoent'; const styles = StyleSheet.create({ container: { flex: 1, }, }); const TaskListComponent = (props) => ( <View style={styles.container}> <FlatList data={props.itemList} keyExtractor={(x, i) => i.toString()} renderItem={({ item }) => <TaskLists itemData={item} /> } ListHeaderComponent={props.headerRenderer} /> </View> ); export default TaskListComponent; <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/EmployeeTrack.cs namespace TrillionBitsPortal.ResourceTracker.Models { public class EmployeeTrack { public int Id { get; set; } public int EmployeeUserId { get; set; } public string TrackTypeName { get; set; } public string TrackDateTime { get; set; } public decimal? TrackLatitude { get; set; } public decimal? TrackLongitude { get; set; } public string TrackPlaceName { get; set; } public string UserId { get; set; } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Interfaces/IEmployee.cs using TrillionBitsPortal.Common.Models; using System.Collections.Generic; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Interfaces { public interface IEmployee { EmployeeUser Create(EmployeeUser model); List<EmployeeUser> GetEmployeeByCompanyId(int companyId); ResponseModel Delete(string id); EmployeeUser GetEmployeeById(int id); List<TextValuePairModel> GetEmployeeAsTextValue(int companyId); EmployeeUser GetByPortalUserId(string userId); ResponseModel UpdateEmployee(PortalUserViewModel model); } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Mappers/DepartmentMapper.cs using System; using System.Collections.Generic; using System.Data.Common; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Mappers { public static class DepartmentMapper { public static List<Department> ToDepartmentModel(DbDataReader readers) { if (readers == null) return null; var models = new List<Department>(); while (readers.Read()) { var model = new Department { Id = Convert.ToInt32(readers["Id"]), CompanyId = Convert.ToInt32(readers["Id"]), DepartmentName = Convert.IsDBNull(readers["DepartmentName"]) ? string.Empty : Convert.ToString(readers["DepartmentName"]), }; models.Add(model); } return models; } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/DataAccess/EmployeeDataAccess.cs using TrillionBitsPortal.Common; using TrillionBitsPortal.Common.Models; using System.Collections.Generic; using System.Data; using System.Linq; using TrillionBits.DataAccess.Common; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Mappers; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.DataAccess { public class EmployeeDataAccess : BaseDatabaseHandler, IEmployee { public EmployeeUser GetEmployeeById(int id) { string err = string.Empty; string sql = @"SELECT E.*,D.DepartmentName from ResourceTracker_EmployeeUser e LEFT JOIN ResourceTracker_Department D ON E.DepartmentId=D.Id where E.Id=@id"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@id", ParamValue =id}, }; var results = ExecuteDBQuery(sql, queryParamList, EmployeeMapper.ToEmployeeModel); return results.Any() ? results.FirstOrDefault() : null; } public List<EmployeeUser> GetEmployeeByCompanyId(int companyId) { string err = string.Empty; string sql = @"SELECT E.*,D.DepartmentName from ResourceTracker_EmployeeUser e LEFT JOIN ResourceTracker_Department D ON E.DepartmentId=D.Id where E.CompanyId=@companyId"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@companyId", ParamValue =companyId}, }; var results = ExecuteDBQuery(sql, queryParamList, EmployeeMapper.ToEmployeeModel); return results; } public EmployeeUser GetByPortalUserId(string userId) { string err = string.Empty; string sql = @"SELECT E.*,D.DepartmentName from ResourceTracker_EmployeeUser e LEFT JOIN ResourceTracker_Department D ON E.DepartmentId=D.Id where E.UserId=@userId"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@userId", ParamValue =userId}, }; var data = ExecuteDBQuery(sql, queryParamList, EmployeeMapper.ToEmployeeModel); return (data!=null && data.Count>0)?data.FirstOrDefault():null; } public EmployeeUser Create(EmployeeUser model) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UserName", ParamValue =model.UserName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Designation", ParamValue =model.Designation}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CompanyId", ParamValue =model.CompanyId,DBType = DbType.Int32}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@DepartmentId", ParamValue =model.DepartmentId,DBType = DbType.Int32}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@PhoneNumber", ParamValue =model.PhoneNumber}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ImageFileName", ParamValue =model.ImageFileName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ImageFileId", ParamValue =model.ImageFileId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@IsAutoCheckPoint", ParamValue =model.IsAutoCheckPoint}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@AutoCheckPointTime", ParamValue =model.AutoCheckPointTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@MaximumOfficeHours", ParamValue =model.MaximumOfficeHours}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@OfficeOutTime", ParamValue =model.OfficeOutTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UserId", ParamValue =model.UserId}, }; const string sql = @"INSERT INTO [ResourceTracker_EmployeeUser] ([UserName] ,[Designation] ,[CompanyId], [DepartmentId], [PhoneNumber], [ImageFileName],[ImageFileId],[IsAutoCheckPoint],[AutoCheckPointTime] ,[MaximumOfficeHours],[OfficeOutTime],[UserId],IsActive) VALUES (@UserName, @Designation, @CompanyId, @DepartmentId, @PhoneNumber, @ImageFileName, @ImageFileId, @IsAutoCheckPoint, @AutoCheckPointTime ,@MaximumOfficeHours,@OfficeOutTime,@UserId,1)"; DBExecCommandEx(sql, queryParamList, ref errMessage); return model; } public ResponseModel Delete(string id) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UserId", ParamValue =id}, }; const string sql = @"DELETE FROM ResourceTracker_EmployeeTrack WHERE EmployeeUserId = (SELECT Id FROM ResourceTracker_EmployeeUser WHERE UserId=@UserId) DELETE FROM ResourceTracker_EmployeeUser WHERE UserId=@UserId "; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public List<TextValuePairModel> GetEmployeeAsTextValue(int companyId) { const string sql = @"SELECT E.UserId Id,e.UserName Name FROM ResourceTracker_EmployeeUser E INNER JOIN UserCredentials U ON E.UserId=U.Id where E.CompanyId=@companyId and E.IsActive=1"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@companyId", ParamValue = companyId} }; return ExecuteDBQuery(sql, queryParamList, EmployeeMapper.ToTextValuePairModel); } public ResponseModel UpdateEmployee(PortalUserViewModel model) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue =model.Id}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UserFullName", ParamValue =model.UserFullName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@DesignationName", ParamValue =model.DesignationName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ImageFileName", ParamValue =model.ImageFileName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ImageFileId", ParamValue =model.ImageFileId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@IsActive", ParamValue =model.IsActive}, }; const string sql = @"UPDATE ResourceTracker_EmployeeUser SET UserName=@UserFullName,Designation=@DesignationName, ImageFileName=@ImageFileName,ImageFileId=@ImageFileId,IsActive=@IsActive WHERE Id=@Id"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } } }<file_sep>/hr Office/HrApp/App.js /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, {Fragment} from 'react'; import { ActivityIndicator, AsyncStorage } from 'react-native'; import * as Font from 'expo-font' import AppNavigator from './AppNavigator'; export default class App extends React.Component { constructor(props) { super(props); this.state = { time: null, show_Main_App: true, loading: true, fontsLoaded: false }; } async componentDidMount() { this.fontLoad(); } async fontLoad() { await Font.loadAsync({ 'PRODUCT_SANS_REGULAR': require('./assets/fonts/PRODUCT_SANS_REGULAR.ttf'), 'Montserrat_Bold': require('./assets/fonts/Montserrat_Bold.ttf'), 'Montserrat_Medium': require('./assets/fonts/Montserrat_Medium.ttf'), 'Montserrat_SemiBold': require('./assets/fonts/Montserrat_SemiBold.ttf'), 'OPENSANS_BOLD': require('./assets/fonts/OPENSANS_BOLD.ttf'), 'OPENSANS_REGULAR': require('./assets/fonts/OPENSANS_REGULAR.ttf'), 'PRODUCT_SANS_BOLD': require('./assets/fonts/PRODUCT_SANS_BOLD.ttf') }); this.setState({ fontsLoaded: true, loading: false }); } componentWillUnmount() { } render() { if (this.state.loading === true) { return ( <ActivityIndicator size="large" color="#1B7F67" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, justifyContent: 'center', alignContent: 'center', }} /> ) } else { return (<AppNavigator />); } } }<file_sep>/hr Office/HrApp/components/Screen/tasks/TabnavigationInTasks.js import React, { Component } from 'react'; import { View, Image } from 'react-native'; import { Router, Stack, Scene, Drawer, SideMenu, } from 'react-native-router-flux'; import TaskListScreen from './TaskList'; import TaskBoardScreen from './TaskBoard'; import CreateTask from './CreateTask'; import ViewTask from './ViewTask'; import TaskBordDetail from './TaskBordDetail'; import TaskListByGroupId from './TaskListByGroupId'; import LandingScreen from '../../../LandingScreen/LandingScreen'; import app from '../../../AppNavigator' export default class TabnavigationInTasks extends Component { render() { return ( <Router> <Scene key="root" hideNavBar={true}> <Scene key="tabbar" tabs={true} tabBarStyle={{ backgroundColor: '#FFFFFF', }} labelStyle={{ fontSize: 14, padding: 5 }} activeBackgroundColor="white" activeTintColor="#26065c" inactiveBackgroundColor=" #FFFFFF" inactiveTintColor="#9e9e9e" > <Scene key="TaskListScreen" title="TASKS" hideNavBar={true} icon={({ focused }) => ( focused ? <Image source={require('../../../assets/images/list_s.png')} style={{ height: 20, width: 20, marginBottom:5,marginTop:15, }}></Image> : <Image source={require('../../../assets/images/list_a.png')} style={{ height: 20, width: 20, marginBottom:5,marginTop:15, }}></Image> )}> <Scene key="TaskListScreen" component={TaskListScreen} title="TASKS" initial /> </Scene> <Scene key="TaskBoardScreen" title="BOARDS" hideNavBar={true} // tabBarLabel="Board" icon={({ focused }) => ( focused ? <Image source={require('../../../assets/images/Board_s.png')} style={{ height: 20, width: 20, marginBottom:5,marginTop:15, }}></Image> : <Image source={require('../../../assets/images/Board.png')} style={{ height: 20, width: 20, marginBottom:5,marginTop:15,}}></Image> )}> <Scene key="TaskBoardScreen" component={TaskBoardScreen} title="Board" //titleStyle={{marginTop:10,}} /> </Scene> </Scene> <Scene key="CreateTask" component={CreateTask} /> <Scene key="ViewTask" component={ViewTask} /> <Scene key="LandingScreen" component={LandingScreen} /> <Scene key="TaskBordDetail" component={TaskBordDetail} /> <Scene key="app" component={app} /> <Scene key="TaskListByGroupId" component={TaskListByGroupId} /> <Scene key="TaskListScreen" component={TaskListScreen} /> </Scene> </Router> ) } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/DataAccess/AttendanceDataAccess.cs using TrillionBitsPortal.Common; using TrillionBitsPortal.Common.Models; using System; using System.Collections.Generic; using System.Data; using TrillionBits.DataAccess.Common; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Mappers; using TrillionBitsPortal.ResourceTracker.Models; using System.Linq; namespace TrillionBitsPortal.ResourceTracker.DataAccess { public class AttendanceDataAccess : BaseDatabaseHandler, IAttendance { public ResponseModel CheckIn(AttendanceEntryModel model) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UserId", ParamValue =model.UserId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CompanyId", ParamValue = model.CompanyId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@AttendanceDate", ParamValue =DateTime.UtcNow,DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CheckInTime", ParamValue = DateTime.UtcNow,DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@DailyWorkingTimeInMin", ParamValue = model.OfficeHour,DBType=DbType.Int32}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@AllowOfficeLessTime", ParamValue = model.AllowOfficeLessTime,DBType=DbType.Int32}, }; const string sql = @"IF NOT EXISTS(SELECT * FROM ResourceTracker_Attendance A WHERE A.UserId=@UserId AND CONVERT(DATE,AttendanceDate)=CONVERT(DATE,@AttendanceDate)) BEGIN INSERT INTO ResourceTracker_Attendance(UserId,CompanyId,AttendanceDate,CheckInTime,DailyWorkingTimeInMin,AllowOfficeLessTime) VALUES(@UserId,@CompanyId,@AttendanceDate,@CheckInTime,@DailyWorkingTimeInMin,@AllowOfficeLessTime) END"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public ResponseModel AddAttendanceAsLeave(AttendanceEntryModel model) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UserId", ParamValue =model.UserId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CompanyId", ParamValue = model.CompanyId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@AttendanceDate", ParamValue =DateTime.UtcNow,DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@IsLeave", ParamValue =true,DBType=DbType.Boolean} }; const string sql = @"IF NOT EXISTS(SELECT * FROM ResourceTracker_Attendance A WHERE A.UserId=@UserId AND CONVERT(DATE,AttendanceDate)=CONVERT(DATE,@AttendanceDate)) BEGIN INSERT INTO ResourceTracker_Attendance(UserId,CompanyId,AttendanceDate,IsLeave) VALUES(@UserId,@CompanyId,@AttendanceDate,@IsLeave) END"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public ResponseModel CheckOut(AttendanceEntryModel model) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UserId", ParamValue =model.UserId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@LessTimeReason", ParamValue =model.Reason}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CheckOutTime", ParamValue = DateTime.UtcNow,DBType=DbType.DateTime} }; const string sql = @"DECLARE @id bigint SELECT TOP 1 @id=Id FROM ResourceTracker_Attendance WHERE UserId=@UserId AND CheckOutTime IS NULL ORDER BY Id DESC UPDATE ResourceTracker_Attendance SET CheckOutTime=@CheckOutTime,LessTimeReason=@LessTimeReason WHERE Id=@id"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public ResponseModel SaveCheckPoint(UserMovementLogModel model) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue =Guid.NewGuid().ToString()}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UserId", ParamValue =model.UserId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@LogDateTime", ParamValue =DateTime.UtcNow,DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Latitude", ParamValue =model.Latitude}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Longitude", ParamValue =model.Longitude}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@LogLocation", ParamValue =model.LogLocation}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@IsCheckInPoint", ParamValue =model.IsCheckInPoint}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@IsCheckOutPoint", ParamValue =model.IsCheckOutPoint}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@DeviceName", ParamValue =model.DeviceName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@DeviceOSVersion", ParamValue =model.DeviceOSVersion}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CompanyId", ParamValue =model.CompanyId} }; const string sql = @"INSERT INTO ResourceTracker_UserMovementLog(Id,UserId,LogDateTime,Latitude,Longitude,LogLocation,IsCheckInPoint, IsCheckOutPoint,DeviceName,DeviceOSVersion,CompanyId) VALUES(@Id,@UserId,@LogDateTime,@Latitude,@Longitude,@LogLocation,@IsCheckInPoint, @IsCheckOutPoint,@DeviceName,@DeviceOSVersion,@CompanyId)"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public List<AttendanceModel> GetAttendanceFeed(int companyId, DateTime date) { const string sql = @" SELECT c.Id,t.UserId,t.AttendanceDate,t.CheckInTime,t.CheckOutTime,t.AllowOfficeLessTime,T.IsLeave, t.LessTimeReason,t.DailyWorkingTimeInMin,t.CompanyId,C.Id EmployeeId ,C.UserName EmployeeName,C.Designation,d.DepartmentName,c.ImageFileName,c.PhoneNumber, null TotalHours, null TotalMinutes FROM ResourceTracker_Attendance t LEFT JOIN ResourceTracker_EmployeeUser C ON T.UserId=C.UserId LEFT JOIN UserCredentials CR ON C.UserId=CR.Id left join ResourceTracker_Department d on c.DepartmentId=d.Id where t.CompanyId=@companyId and convert(date,t.AttendanceDate)=convert(date,@date) UNION ALL SELECT t.Id,t.UserId,@date AttendanceDate,NULL CheckInTime,NULL CheckOutTime,NULL AllowOfficeLessTime,NULL IsLeave, NULL LessTimeReason,NULL DailyWorkingTimeInMin,t.CompanyId,t.Id EmployeeId ,t.UserName EmployeeName,t.Designation,d.DepartmentName,t.ImageFileName,t.PhoneNumber, null TotalHours, null TotalMinutes FROM ResourceTracker_EmployeeUser t LEFT JOIN UserCredentials CR ON T.UserId=CR.Id left join ResourceTracker_Department d on t.DepartmentId=d.Id where t.CompanyId=@companyId AND t.UserId NOT in ( SELECT T.UserId FROM ResourceTracker_Attendance t where t.CompanyId=@companyId and convert(date,t.AttendanceDate)=convert(date,@date) )"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@companyId", ParamValue = companyId,DBType=DbType.Int32}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@date", ParamValue = date,DBType=DbType.DateTime} }; var data = ExecuteDBQuery(sql, queryParamList, AttendanceMapper.ToAttendance); return data; } public List<AttendanceModel> GetAttendance(int companyId, DateTime startDate, DateTime endDate) { const string sql = @" SELECT c.Id,t.UserId,t.AttendanceDate,t.CheckInTime,t.CheckOutTime,t.AllowOfficeLessTime,T.IsLeave, t.LessTimeReason,t.DailyWorkingTimeInMin,t.CompanyId,C.Id EmployeeId ,C.UserName EmployeeName,C.Designation,d.DepartmentName,c.ImageFileName,c.PhoneNumber, null TotalHours, null TotalMinutes FROM ResourceTracker_Attendance t LEFT JOIN ResourceTracker_EmployeeUser C ON T.UserId=C.UserId LEFT JOIN UserCredentials CR ON C.UserId=CR.Id left join ResourceTracker_Department d on c.DepartmentId=d.Id where t.CompanyId=@companyId and (CONVERT(DATE,AttendanceDate) BETWEEN convert(date,@startDate) AND convert(date,@endDate))"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@companyId", ParamValue = companyId,DBType=DbType.Int32}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@startDate", ParamValue = startDate,DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@endDate", ParamValue = endDate,DBType=DbType.DateTime} }; var data = ExecuteDBQuery(sql, queryParamList, AttendanceMapper.ToAttendance); return data; } public List<AttendanceModel> GetAttendance(string userId, int companyId, DateTime startDate, DateTime endDate) { const string sql = @" SELECT c.Id,t.UserId,t.AttendanceDate,t.CheckInTime,t.CheckOutTime,t.AllowOfficeLessTime,T.IsLeave, t.LessTimeReason,t.DailyWorkingTimeInMin,t.CompanyId,C.Id EmployeeId ,C.UserName EmployeeName,C.Designation,d.DepartmentName,c.ImageFileName,c.PhoneNumber, null TotalHours, null TotalMinutes FROM ResourceTracker_Attendance t LEFT JOIN ResourceTracker_EmployeeUser C ON T.UserId=C.UserId LEFT JOIN UserCredentials CR ON C.UserId=CR.Id left join ResourceTracker_Department d on c.DepartmentId=d.Id where t.CompanyId=@companyId AND T.UserId=@userId and (CONVERT(DATE,AttendanceDate) BETWEEN convert(date,@startDate) AND convert(date,@endDate))"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@userId", ParamValue = userId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@companyId", ParamValue = companyId,DBType=DbType.Int32}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@startDate", ParamValue = startDate,DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@endDate", ParamValue = endDate,DBType=DbType.DateTime} }; var data = ExecuteDBQuery(sql, queryParamList, AttendanceMapper.ToAttendance); return data; } public AttendanceModel GetMyTodayAttendance(string userId, DateTime date) { const string sql = @"IF EXISTS(SELECT TOP 1 * FROM ResourceTracker_Attendance A WHERE A.UserId=@userId and convert(date,A.AttendanceDate)=convert(date,@date)) BEGIN SELECT T.Id,t.UserId,t.AttendanceDate,t.CheckInTime,t.CheckOutTime,t.AllowOfficeLessTime,T.IsLeave, t.LessTimeReason,t. DailyWorkingTimeInMin,t.CompanyId,C.Id EmployeeId ,C.UserName EmployeeName,c.Designation,d.DepartmentName,c.ImageFileName,c.PhoneNumber, null TotalHours, null TotalMinutes FROM ResourceTracker_Attendance t LEFT JOIN ResourceTracker_EmployeeUser C ON T.UserId=C.UserId LEFT JOIN UserCredentials CR ON C.UserId=CR.Id left join ResourceTracker_Department d on c.DepartmentId=d.Id where t.UserId=@userId and convert(date,t.AttendanceDate)=convert(date,@date) END ELSE BEGIN SELECT T.Id,t.UserId,@date AttendanceDate,NULL CheckInTime,NULL CheckOutTime,NULL AllowOfficeLessTime,NULL IsLeave, NULL LessTimeReason,NULL DailyWorkingTimeInMin,t.CompanyId,t.Id EmployeeId ,t.UserName EmployeeName,t.Designation,d.DepartmentName,t.ImageFileName,t.PhoneNumber, null TotalHours, null TotalMinutes FROM ResourceTracker_EmployeeUser t LEFT JOIN UserCredentials CR ON T.UserId=CR.Id left join ResourceTracker_Department d on t.DepartmentId=d.Id where t.UserId=@userId END"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@userId", ParamValue = userId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@date", ParamValue = date,DBType=DbType.DateTime} }; var data = ExecuteDBQuery(sql, queryParamList, AttendanceMapper.ToAttendance); return (data != null && data.Count > 0) ? data.FirstOrDefault() : null; } public List<UserMovementLogModel> GetMovementDetails(string userId, DateTime date) { const string sql = @"SELECT T.* FROM ResourceTracker_UserMovementLog t where t.UserId=@userId and convert(date,t.LogDateTime)=convert(date,@date)"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@userId", ParamValue = userId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@date", ParamValue = date,DBType=DbType.DateTime} }; var data = ExecuteDBQuery(sql, queryParamList, AttendanceMapper.ToMovementLog); return data; } } } <file_sep>/hr Office/HrApp/services/UserService/TaskService.js import { postApi, getApi } from "../api"; //export const GetRelatedToMeTasks = async (userId) => getApi("RtTaskApi/GetRelatedToMeTasks?userId="+userId, {}, {}); export const SaveTask = async data => postApi("RtTaskApi/SaveTask", {}, data); export const GetCreatedByme = async (userId) => getApi("RtTaskApi/GetCreatedByMeTasks?userId="+userId, {}, {}); export const GetRelatedToMeTasks = async (userId) => getApi("RtTaskApi/GetAssignedToMeTasks?userId="+userId, {}, {}); export const TaskStatus = async () => getApi("RtTaskApi/GetTaskStatusList", {}, {}); export const PriorityList = async () => getApi("RtTaskApi/GetPriorityList", {}, {}); export const SaveFile = async data => postApi("RtTaskApi/SaveTaskAttachment", {}, data); export const GetTaskAttachments = async (taskId) => getApi("RtTaskApi/GetTaskAttachments?taskId="+taskId, {}, {}); <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/EmployeeTrackInfoViewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.ResourceTracker.Models { public class EmployeeTrackInfoViewModel { public int? EmployeeId { get; set; } public string UserName { get; set; } public string UserFullName { get; set; } public string PhoneNumber { get; set; } public string Gender { get; set; } public string CompanyName { get; set; } public string DepartmentName { get; set; } public int? DepartmentId { get; set; } public string CompanyId { get; set; } public string Designation { get; set; } public string TrackDateTime { get; set; } public string ImageFileName { get; set; } public bool? IsCheckInToday { get; set; } public bool? IsCheckOutToday { get; set; } public string LastTrackDateTime { get; set; } public decimal? LastTrackLatitude { get; set; } public decimal? LastTrackLongitude { get; set; } public bool IsAutoCheckPoint { get; set; } public string MaximumOfficeHours { get; set; } public string OfficeOutTime { get; set; } public string CheckOutTime { get; set; } } } <file_sep>/hr Office/HrApp/services/AccountService.js import {postApi, deleteApi, getApi } from "./api"; export const GetEmpInfoByUserId = async (userId,date) => getApi("RtEmployeeApi/GetEmpInfo?userId="+userId+"&date="+date, {}, {}); export const GetEmployeeWithCompanyId = async (companyId) => getApi("RtEmployeeApi/GetEmployeeByCompanyId?companyId="+companyId, {}, {}); // export const CreateAccount = async data => postApi("User/Register", {}, data); export const CreateAccount = async data => postApi("RtAccountApi/Register", {}, data); export const ChangePasswords = async data => postApi("User/changepassword", {}, data); export const ChangePasswordforEmp = async data => postApi("User/resetpassword", {}, data); export const CreateEmployee = async data => postApi("RtEmployeeApi/CreateEmployee", {}, data); export const UpdateEmployee = async data => postApi("RtEmployeeApi/UpdateEmployee", {}, data); // export const Login = async data => postApi("RtAccountApi/LoginAdmin", {}, data); export const Login = async data => postApi("RtAccountApi/Login", {}, data); export const GetUserClaim = async (userKey) => getApi("RtAccountApi/GetUserClaims?userKey="+userKey, {}, {}); export const DeleteEmployee = async (id) => deleteApi("RtEmployeeApi/DeleteEmployee?id="+id, {}); export const getTokenforResetEmptPass = async (userId) => getApi("GetResetPasswordToken?userId="+userId, {}, {}); export const CheckExistPhone = async (PhoneNumber) => getApi("RtAccountApi/CheckExistPhone?phoneno="+PhoneNumber, {}, {}); export const VerifyEmail = async email => postApi("account/VerifyEmail/" + email, {}, {}); export const VerifyCurrentPassword = async password => postApi("account/VerifyCurrentPassword/" + password, {}, {}); export const ResetPassword = async (email, password) => postApi("account/ResetPassword/" + email + "/" + password, {}, {}); export const SendOTP = async (userName) => postApi("account/SendOTP/" + userName ,{}); export const ChangePassword = async (userName, currentPassword, newPassword) => postApi( "account/ChangePassword/" + userName + "/" + currentPassword + "/" + newPassword, {}, {}, {} ); export const AddDeviceToken = async deviceToken => postApi("account/DeviceToken/" + deviceToken, null, null); export const RemoveDeviceToken = async deviceToken => deleteApi("account/DeviceToken/" + deviceToken, null, null);<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/ResourceTracker/RtTaskApiController.cs using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using TrillionBits.ResourceTracker; using TrillionBitsPortal.Common; using TrillionBitsPortal.Common.Models; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.Web.Controllers.Api.ResourceTracker { public class RtTaskApiController : BaseApiController { private readonly IEmployeeTask _taskRepository; public RtTaskApiController() { _taskRepository = RTUnityMapper.GetInstance<IEmployeeTask>(); } [HttpPost] public IHttpActionResult SaveTaskGroup(TaskGroupModel model) { var result = _taskRepository.SaveTaskGroup(model); return Ok(result); } [HttpPost] public IHttpActionResult SaveToDoTask(ToDoTaskModel model) { var result = _taskRepository.SaveToDoTask(model); return Ok(result); } [HttpGet] public IHttpActionResult ToDoTaskAsDone(string id) { var result = _taskRepository.ToDoTaskAsDone(id); return Ok(result); } [HttpPost] public IHttpActionResult ToDoTaskShare(string taskId, List<string> userList) { var result = _taskRepository.ToDoTaskShare(taskId, userList); return Ok(result); } [HttpPost] public IHttpActionResult SaveTask(TaskModel model) { if (!model.StatusId.HasValue) { model.StatusId = (int)TaskStatus.ToDo; } if (!model.PriorityId.HasValue) { model.PriorityId = (int)TaskPriority.Normal; } var result = _taskRepository.SaveTask(model); return Ok(result); } [HttpPost] public IHttpActionResult SaveTaskAttachment(TaskAttachment model) { var result = _taskRepository.SaveTaskAttachment(model); return Ok(result); } [HttpGet] public IHttpActionResult GetTaskAttachments(string taskId) { var result = _taskRepository.GetTaskAttachments(taskId); return Ok(result); } [HttpGet] public IHttpActionResult GetGroups(string companyId) { var result = _taskRepository.GetGroups(companyId); return Ok(result); } [HttpGet] public IHttpActionResult GetToDoList(string userId) { var result = _taskRepository.GetToDoList(userId); return Ok(result); } [HttpGet] public IHttpActionResult GetTasksByGroup(int groupId) { var result = _taskRepository.GetTaskList(new TaskModel { TaskGroupId = groupId }).OrderByDescending(x => x.CreatedAt); return Ok(result); } [HttpGet] public IHttpActionResult GetCreatedByMeTasks(string userId) { var result = _taskRepository.GetTaskList(new TaskModel { CreatedById = userId }).OrderByDescending(x => x.CreatedAt); return Ok(result); } [HttpGet] public IHttpActionResult GetAssignedToMeTasks(string userId) { var result = _taskRepository.GetTaskList(new TaskModel { AssignedToId = userId }).OrderByDescending(x => x.CreatedAt); return Ok(result); } [HttpGet] public IHttpActionResult GetRelatedToMeTasks(string userId) { var result = _taskRepository.GetRelatedToMeTaskList(userId).OrderByDescending(x => x.CreatedAt); return Ok(result); } [HttpGet] public IHttpActionResult DeleteTask(string id) { var result = _taskRepository.DeleteTask(id); return Ok(result); } [HttpGet] public IHttpActionResult GetTaskDetails(string id) { var result = _taskRepository.GetTaskDetails(id); return Ok(result); } [HttpGet] public IHttpActionResult GetTaskStatusList() { var list = Enum.GetValues(typeof(TaskStatus)).Cast<TaskStatus>().Select(v => new NameIdPairModel { Name = EnumUtility.GetDescriptionFromEnumValue(v), Id = (int)v }).ToList(); return Ok(list); } [HttpGet] public IHttpActionResult GetPriorityList() { var list = Enum.GetValues(typeof(TaskPriority)).Cast<TaskPriority>().Select(v => new NameIdPairModel { Name = EnumUtility.GetDescriptionFromEnumValue(v), Id = (int)v }).ToList(); return Ok(list); } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/DataAccess/EmployeeTaskDataAccess.cs using TrillionBitsPortal.Common; using Microsoft.Practices.EnterpriseLibrary.Data; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using TrillionBits.DataAccess.Common; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Mappers; using TrillionBitsPortal.ResourceTracker.Models; using TrillionBitsPortal.Common.Models; namespace TrillionBitsPortal.ResourceTracker.DataAccess { public class EmployeeTaskDataAccess : BaseDatabaseHandler, IEmployeeTask { public ResponseModel SaveTaskGroup(TaskGroupModel model) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue =model.Id}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Name", ParamValue =model.Name}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Description", ParamValue = model.Description}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@BackGroundColor", ParamValue = model.BackGroundColor}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CreatedAt", ParamValue = DateTime.UtcNow,DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CreatedById", ParamValue = model.CreatedById}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CompanyId", ParamValue = model.CompanyId} }; const string sql = @"IF NOT EXISTS(SELECT TOP 1 P.Id FROM ResourceTracker_TaskGroup P WHERE P.Id=@Id) BEGIN INSERT INTO ResourceTracker_TaskGroup(Name,Description,BackGroundColor,CreatedAt,CreatedById,CompanyId) VALUES(@Name,@Description,@BackGroundColor,@CreatedAt,@CreatedById,@CompanyId) END ELSE BEGIN UPDATE ResourceTracker_TaskGroup SET Name=@Name,Description=@Description,BackGroundColor=@BackGroundColor WHERE Id=@Id END"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public ResponseModel SaveToDoTask(ToDoTaskModel model) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue =string.IsNullOrEmpty(model.Id)?Guid.NewGuid().ToString():model.Id}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Title", ParamValue =model.Title}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Description", ParamValue = model.Description}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CreatedAt", ParamValue = DateTime.UtcNow,DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CreatedById", ParamValue = model.CreatedById} }; const string sql = @"IF NOT EXISTS(SELECT TOP 1 P.Id FROM ResourceTracker_ToDoTask P WHERE P.Id=@Id) BEGIN DECLARE @companyId int SELECT TOP 1 @companyId=CompanyId FROM ResourceTracker_EmployeeUser WHERE UserId=@CreatedById INSERT INTO ResourceTracker_ToDoTask(Id,Title,Description,CreatedAt,CreatedById,CompanyId,Completed) VALUES(@Id,@Title,@Description,@CreatedAt,@CreatedById,@CompanyId,0) END ELSE BEGIN UPDATE ResourceTracker_ToDoTask SET Title=@Title,Description=@Description WHERE Id=@Id END"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public ResponseModel ToDoTaskAsDone(string id) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue =id}, }; const string sql = @"UPDATE ResourceTracker_ToDoTask SET Completed=1 WHERE Id=@Id"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public ResponseModel ToDoTaskShare(string taskId, List<string> userList) { var errMessage = string.Empty; foreach (var x in userList) { var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue =Guid.NewGuid().ToString()}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@TaskId", ParamValue =taskId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ShareWithId", ParamValue =x}, }; const string sql = @"INSERT INTO ResourceTracker_ToDoTaskShare(Id,TaskId,ShareWithId) VALUES(@Id,@TaskId,@ShareWithId)"; DBExecCommandEx(sql, queryParamList, ref errMessage); } return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public ResponseModel SaveTask(TaskModel model) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue =string.IsNullOrEmpty(model.Id)?Guid.NewGuid().ToString():model.Id}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Title", ParamValue =model.Title}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Description", ParamValue = model.Description}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CreatedAt", ParamValue = DateTime.UtcNow,DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CreatedById", ParamValue = model.CreatedById}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@AssignedToId", ParamValue = model.AssignedToId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@StatusId", ParamValue = model.StatusId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@TaskGroupId", ParamValue = model.TaskGroupId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@DueDate", ParamValue = model.DueDate.HasValue?model.DueDate.Value(Constants.ServerDateTimeFormat):(DateTime?)null,DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CompanyId", ParamValue = model.CompanyId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@PriorityId", ParamValue = model.PriorityId} }; const string sql = @"IF NOT EXISTS(SELECT TOP 1 P.Id FROM ResourceTracker_Task P WHERE P.Id=@Id) BEGIN DECLARE @tNo INT=0 SELECT @tNo=count(t.Id) FROM ResourceTracker_Task T WHERE T.CompanyId=@CompanyId INSERT INTO ResourceTracker_Task(Id,TaskNo,Title,Description,CreatedAt,CreatedById,AssignedToId,StatusId,TaskGroupId,DueDate,CompanyId,PriorityId) VALUES(@Id,@tNo+1,@Title,@Description,@CreatedAt,@CreatedById,@AssignedToId,@StatusId,@TaskGroupId,@DueDate,@CompanyId,@PriorityId) END ELSE BEGIN UPDATE ResourceTracker_Task SET Title=@Title,Description=@Description,AssignedToId=@AssignedToId,PriorityId=@PriorityId, StatusId=@StatusId,TaskGroupId=@TaskGroupId,DueDate=@DueDate,UpdatedById=@CreatedById,UpdatedAt=@CreatedAt WHERE Id=@Id END"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public ResponseModel SaveTaskAttachment(TaskAttachment model) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue = Guid.NewGuid().ToString()}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@TaskId", ParamValue =model.TaskId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@FileName", ParamValue =model.FileName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@BlobName", ParamValue =model.BlobName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UpdatedAt", ParamValue =DateTime.UtcNow,DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UpdatedById", ParamValue =model.UpdatedById}, }; const string sql = @"INSERT INTO ResourceTracker_TaskAttachments(Id,TaskId,FileName,BlobName,UpdatedAt,UpdatedById) VALUES (@Id,@TaskId,@FileName,@BlobName,@UpdatedAt,@UpdatedById)"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public List<TaskAttachment> GetTaskAttachments(string taskId) { const string sql = @"SELECT * FROM ResourceTracker_TaskAttachments where TaskId=@taskId"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@taskId", ParamValue = taskId} }; return ExecuteDBQuery(sql, queryParamList, EmployeeTaskMapper.ToTaskAttachment); } public List<TaskGroupModel> GetGroups(string companyId) { const string sql = @"SELECT * FROM ResourceTracker_TaskGroup where CompanyId=@companyId"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@companyId", ParamValue = companyId} }; return ExecuteDBQuery(sql, queryParamList, EmployeeTaskMapper.ToTaskGroup); } public List<ToDoTaskModel> GetToDoList(string userId) { const string sql = @"SELECT * FROM ResourceTracker_ToDoTask where CreatedById=@userId"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@userId", ParamValue = userId} }; return ExecuteDBQuery(sql, queryParamList, EmployeeTaskMapper.ToToDoTask); } public List<TaskModel> GetTaskList(TaskModel sModel) { const string sql = @"SELECT T.*,C.FullName AssignToName,CreatedBy.FullName CreatedByName,UpdatedBy.FullName UpdatedByName FROM ResourceTracker_Task t LEFT JOIN UserCredentials C ON T.AssignedToId=C.Id LEFT JOIN UserCredentials CreatedBy ON T.CreatedById=CreatedBy.Id LEFT JOIN UserCredentials UpdatedBy ON T.UpdatedById=UpdatedBy.Id where (@CreatedById is null or t.CreatedById=@CreatedById) and (@AssignedToId is null or t.AssignedToId=@AssignedToId) and (@TaskGroupId is null or t.TaskGroupId=@TaskGroupId)"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CreatedById", ParamValue =string.IsNullOrEmpty(sModel.CreatedById)?null:sModel.CreatedById}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@AssignedToId", ParamValue = string.IsNullOrEmpty(sModel.AssignedToId)?null:sModel.AssignedToId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@TaskGroupId", ParamValue = sModel.TaskGroupId}, }; return ExecuteDBQuery(sql, queryParamList, EmployeeTaskMapper.ToTask); } public List<TaskModel> GetRelatedToMeTaskList(string userId) { const string sql = @"SELECT T.*,C.FullName AssignToName,CreatedBy.FullName CreatedByName,UpdatedBy.FullName UpdatedByName FROM ResourceTracker_Task t LEFT JOIN UserCredentials C ON T.AssignedToId=C.Id LEFT JOIN UserCredentials CreatedBy ON T.CreatedById=CreatedBy.Id LEFT JOIN UserCredentials UpdatedBy ON T.UpdatedById=UpdatedBy.Id where (T.AssignedToId=@userId OR T.CreatedById=@userId)"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@userId", ParamValue =userId} }; return ExecuteDBQuery(sql, queryParamList, EmployeeTaskMapper.ToTask); } public TaskModel GetTaskDetails(string id) { const string sql = @"SELECT T.*,C.FullName AssignToName,CreatedBy.FullName CreatedByName,UpdatedBy.FullName UpdatedByName FROM ResourceTracker_Task t LEFT JOIN UserCredentials C ON T.AssignedToId=C.Id LEFT JOIN UserCredentials CreatedBy ON T.CreatedById=CreatedBy.Id LEFT JOIN UserCredentials UpdatedBy ON T.UpdatedById=UpdatedBy.Id where T.Id=@id"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@id", ParamValue =id} }; var data = ExecuteDBQuery(sql, queryParamList, EmployeeTaskMapper.ToTask); return (data != null && data.Count > 0) ? data.FirstOrDefault() : null; } public ResponseModel DeleteTask(string id) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue =id}, }; const string sql = @"DELETE FROM ResourceTracker_Task WHERE Id=@Id"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } } } <file_sep>/hr Office/HrApp/components/MenuDrawer/DrawerContentStyle.js import { StyleSheet, Platform, StatusBar } from 'react-native'; export const DrawerContentStyle = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f4f6f9', flexDirection: 'column', marginTop: StatusBar.currentHeight, }, itemContainer: { flexDirection: 'row', alignItems: 'center', height: 40, marginVertical: 8, paddingLeft: 15, }, itemContainerSelected: { flexDirection: 'row', alignItems: 'center', height: 40, marginVertical: 8, paddingLeft: 15, marginRight: 5, backgroundColor: "#E8F0F5", borderBottomRightRadius: 20, borderTopRightRadius: 20, padding:27, }, itemTextStyle: { marginLeft: 15, fontSize: 16, fontWeight: "bold", color: "#555555", fontFamily: "PRODUCT_SANS_REGULAR", }, logoImage: { paddingLeft: 10, // justifyContent: 'center', // alignItems: 'center', flexDirection: 'row', }, ImagestyleFromServer: { ...Platform.select({ ios: { width: 60, height: 60, borderRadius: 30 }, android: { width: 60, height: 60, borderRadius: 200 }, }), }, RightTextView: { flexDirection: 'column', marginTop: 3, }, NameText: { fontFamily: "OPENSANS_BOLD", fontSize: 30, textAlign: "left", color: "#19260c", }, DesignationText: { fontSize: 12, fontFamily: "OPENSANS_REGULAR", textAlign: "left", color: "#8f8f8f" }, DepartmentText: { fontSize: 12, fontFamily: "OPENSANS_REGULAR", textAlign: "left", color: "#b5b5b5" }, emptyLineStyle: { width: "100%", borderBottomWidth: 0.5, paddingVertical: 10, borderBottomColor: "black", }, CompanyModalStyle: { // justifyContent: 'center', // alignItems: 'center', flexDirection: 'row', flex: 1, flexWrap: 'wrap', borderRadius: 15, padding: 5, }, CompanyModalTextStyle: { // justifyContent: 'flex-start', color: '#4E4E4E', fontSize: 16, fontFamily: "PRODUCT_SANS_BOLD", }, CompanyModalDefaultTextStyle: { color: '#ff9966', fontSize: 14, fontFamily: "PRODUCT_SANS_BOLD", }, CompanyModalIconStyle: { marginTop: 4, marginLeft: 4, justifyContent: 'flex-end', }, }) <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/UserCredentialModel.cs using System; using System.ComponentModel.DataAnnotations; namespace TrillionBitsPortal.Common.Models { public class UserCredentialModel { public string Id { get; set; } [Required] public string Email { get; set; } [Required(ErrorMessage = "The Login ID field is required")] public string LoginID { get; set; } [Required(ErrorMessage = "The Full Name field is required")] public string FullName { get; set; } [Required(ErrorMessage = "The Contact No field is required")] public string ContactNo { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public int UserTypeId { get; set; } public bool IsActive { get; set; } public string CreatedAt { get; set; } public string AssistantId { get; set; } public string AssistantName { get; set; } public string DoctorId { get; set; } public int? Theme { get; set; } public string OrganizationId { get; set; } public string OrganizationName { get; set; } } [Serializable] public class UserSessionModel { public string Id { get; set; } public int UserTypeId { get; set; } public string DoctorId { get; set; } public int? Theme { get; set; } public string FullName { get; set; } public string UserInitial { get; set; } public string Email { get; set; } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/AzureFileStorageApiController.cs using TrillionBitsPortal.Common; using TrillionBitsPortal.Web.AzureService; using System; using System.IO; using System.Web; using System.Web.Http; namespace TrillionBitsPortal.Web.Controllers.Api { public class AzureFileStorageApiController : BaseApiController { private readonly IFileStorageService _fileStorageService; public AzureFileStorageApiController() { _fileStorageService = new AzureStorageService(); } [HttpPost] public IHttpActionResult Upload(AzureStorageContainerType containerName) { try { var httpRequest = HttpContext.Current.Request; if (httpRequest.Files.Count > 0) { HttpFileCollection fileCollection; HttpPostedFile postedFile; Stream fileStream; fileCollection = httpRequest.Files; postedFile = fileCollection[0]; fileStream = postedFile.InputStream; var fileType = Path.GetExtension(postedFile.FileName); string blobName = Guid.NewGuid() + fileType; _fileStorageService.Upload(fileStream, blobName, containerName); return Ok(new { Success = true, Message = string.Empty, ReturnCode = blobName }); } } catch (Exception exception) { return Ok(new {Success=false,Message=exception.Message }); } return Ok(new { Success = false, Message = string.Empty }); } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/DbUtility/Resources.cs using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Resources; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.Common { [CompilerGenerated] [DebuggerNonUserCode] [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "192.168.127.12")] internal class Resources { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; internal static string CompanyGroupName { get { return Resources.ResourceManager.GetString("CompanyGroupName", Resources.resourceCulture); } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return Resources.resourceCulture; } set { Resources.resourceCulture = value; } } internal static string DbName { get { return Resources.ResourceManager.GetString("DbName", Resources.resourceCulture); } } internal static string DbPwd { get { return Resources.ResourceManager.GetString("DbPwd", Resources.resourceCulture); } } internal static string DbServerName { get { return Resources.ResourceManager.GetString("DbServerName", Resources.resourceCulture); } } internal static string DbUserName { get { return Resources.ResourceManager.GetString("DbUserName", Resources.resourceCulture); } } internal static string EfConfiguration { get { return Resources.ResourceManager.GetString("EfConfiguration", Resources.resourceCulture); } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (Resources.resourceMan == null) { Resources.resourceMan = new ResourceManager("TrillionBitsPortal.Common", typeof(Resources).Assembly); } return Resources.resourceMan; } } internal Resources() { } } } <file_sep>/hr Office/HrApp/services/CompanyService.js import { postApi, getApi } from "./api"; //export const CreateCompany = async data => postApi("RtCompanyApi/Save", {}, data); export const CreateCompany = async data => postApi("RtCompanyApi/Save", {}, data); export const updatedeCompany = async data => postApi("RtCompanyApi/UpdateCompany", {}, data); export const GetCompanyByUserId = async (userId) => getApi("RtCompanyApi/GetCompanyByUserId?userId="+userId, {}, {}); export const GetCompanyByEmpUserId = async (userId) => getApi("RtCompanyApi/GetCompanyByEmpUserId?userId="+userId, {}, {}); export const GetCompanyByIdentity = async () => getApi("RtCompanyApi/GetCompanyByIdentity", {}, {}); <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/EmployeeLeaveModel.cs using TrillionBitsPortal.Common; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.ResourceTracker.Models { public class EmployeeLeaveModel { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public int CompanyId { get; set; } public int EmployeeId { get; set; } public string EmployeeName { get; set; } public DateTime FromDate { get; set; } public DateTime ToDate { get; set; } public bool? IsHalfDay { get; set; } public int LeaveTypeId { get; set; } public string LeaveReason { get; set; } public string CreatedAt { get; set; } public bool IsApproved { get; set; } public bool IsRejected { get; set; } public string RejectReason { get; set; } public string ApprovedById { get; set; } public DateTime? ApprovedAt { get; set; } public string ApprovedBy { get; set; } public string LeaveApplyFrom { get; set; } public string LeaveApplyTo { get; set; } public string UserId { get; set; } public string LeaveType { get { return EnumUtility.GetDescriptionFromEnumValue((LeaveType)LeaveTypeId); } } public int LeaveInDays { get { return ((int)ToDate.Subtract(FromDate).TotalDays)+1; } } public string FromDateVw { get { return FromDate.ToString(Constants.DateLongFormat); } } public string ApprovedAtVw { get { return ApprovedAt.HasValue? ApprovedAt.Value.ToString(Constants.DateLongFormat):string.Empty; } } public string ToDateVw { get { return ToDate.ToString(Constants.DateLongFormat); } } } public enum LeaveType { [Description("Casual Leave")] CasualLeave = 1, [Description("Sick Leave")] SickLeave = 2 } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Mappers/EmployeeLeaveMapper.cs using System; using System.Collections.Generic; using System.Data.Common; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Mappers { public static class EmployeeLeaveMapper { public static List<EmployeeLeaveModel> ToEmployeeLeaveMapperModel(DbDataReader readers) { if (readers == null) return null; var models = new List<EmployeeLeaveModel>(); while (readers.Read()) { var model = new EmployeeLeaveModel { Id = Convert.ToInt32(readers["Id"]), CompanyId = Convert.ToInt32(readers["CompanyId"]), EmployeeId = Convert.ToInt32(readers["EmployeeId"]), FromDate = Convert.ToDateTime(readers["FromDate"]), ToDate = Convert.ToDateTime(readers["ToDate"]), IsHalfDay = Convert.IsDBNull(readers["IsHalfDay"]) ? (bool?)null : Convert.ToBoolean(readers["IsHalfDay"]), LeaveTypeId = Convert.ToInt32(readers["LeaveTypeId"]), LeaveReason = Convert.IsDBNull(readers["LeaveReason"]) ? string.Empty : Convert.ToString(readers["LeaveReason"]), CreatedAt = Convert.IsDBNull(readers["CreatedAt"]) ? string.Empty : Convert.ToDateTime(readers["CreatedAt"]).ToString(), IsApproved = Convert.IsDBNull(readers["IsApproved"]) ? false : Convert.ToBoolean(readers["IsApproved"]), IsRejected = Convert.IsDBNull(readers["IsRejected"]) ?false : Convert.ToBoolean(readers["IsRejected"]), ApprovedById = Convert.IsDBNull(readers["ApprovedById"]) ? string.Empty : Convert.ToString(readers["ApprovedById"]).ToString(), ApprovedAt = Convert.IsDBNull(readers["ApprovedAt"]) ? (DateTime?)null : Convert.ToDateTime(readers["ApprovedAt"]), EmployeeName = Convert.IsDBNull(readers["EmployeeName"]) ? string.Empty : Convert.ToString(readers["EmployeeName"]), ApprovedBy = Convert.IsDBNull(readers["ApprovedBy"]) ? string.Empty : Convert.ToString(readers["ApprovedBy"]), }; models.Add(model); } return models; } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Interfaces/IDepartment.cs using TrillionBitsPortal.Common.Models; using System.Collections.Generic; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Interfaces { public interface IDepartment { List<Department> GetDepartmentByCompanyId(string companyId); Department Create(Department model,string userId); ResponseModel UpdateDepartment(Department model); } }<file_sep>/hr Office/HrApp/components/Screen/UserScreen/notice/NoticeStyle.js import { StyleSheet, Platform } from 'react-native'; export const NoticeStyle = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f6f7f9', }, HeaderContent: { justifyContent: 'space-between', backgroundColor: '#fff', flexDirection: 'row', padding: 10, borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 10, height: -5 }, elevation: 10, height: 60, }, HeaderFirstView: { justifyContent: 'flex-start', flexDirection: 'row', marginLeft: 5, alignItems: 'center', }, HeaderMenuicon: { alignItems: 'center', padding: 10, }, HeaderMenuLeft: { alignItems: 'center', }, HeaderMenuLeftStyle: { alignItems: 'center', height: 40, width: 75, }, HeaderMenuiconstyle: { width: 20, height: 20, }, HeaderTextView: { backgroundColor: 'white', padding: 0, marginLeft: 17, margin: 0, flexDirection: 'row', alignItems: 'center', }, HeaderTextstyle: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: "left", color: "#2a2a2a", }, loaderIndicator: { position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, justifyContent: 'center', alignContent: 'center', }, detailTextStyle: { padding: 10, marginTop: 16, flex: 1, marginHorizontal: 6, }, noticeDetailTextStyle: { fontFamily: "OPENSANS_REGULAR", fontSize: 16, textAlign: "left", color: "#636363", padding: 10, }, noticelistImage: { ...Platform.select({ ios: { width: 40, height: 40, padding: 10, }, android: { width: 40, height: 40, padding: 10, }, }), }, createDateStyle: { // marginBottom: 5, textAlign: 'right', //color: '#c5cbcf', fontSize: 14, fontFamily: 'PRODUCT_SANS_BOLD' }, postedtextStyle: { // marginBottom: 5, textAlign: 'right', // color: '#c5cbcf', fontSize: 14, fontFamily: 'PRODUCT_SANS_BOLD' }, dateContainer: { flexDirection: 'row', justifyContent: 'space-between', paddingTop: 10, }, listContainer: { flex: 1, backgroundColor: '#ffffff', marginBottom:5,marginTop:5, borderRadius: 5, padding: 15,elevation: 2, }, listDivider: { justifyContent: 'space-between', flexDirection: 'row', borderBottomColor: '#edeeef', borderBottomWidth: 1, paddingBottom: 10, }, noticepart: { alignItems: 'flex-start', color: '#1a1a1a', fontSize: 10, fontFamily: 'OPENSANS_REGULAR' }, imagePart: { alignItems: 'flex-end', width: '20%', }, NoticeItemDetailText: { color: '#1a1a1a', fontSize: 10, fontFamily: 'OPENSANS_REGULAR' }, headerContainer: { flexDirection: 'row', height: 60, paddingTop: 0, backgroundColor: 'white', shadowColor: 'rgba(181,181,181,0.02)', shadowOffset: { width: 0, height: -2 }, elevation: 10, shadowRadius: 8, shadowOpacity: 0.3, alignItems: 'center', paddingHorizontal: 10, justifyContent: 'space-between', borderBottomRightRadius: 10, borderBottomLeftRadius: 10 }, headerTitle: { alignItems: 'flex-start', flexDirection: 'row' }, headerText: { fontWeight: 'bold', fontSize: 20, color: '#141414', marginTop: 3, }, headerTextRight: { alignItems: 'flex-end', marginRight: 10, }, ImagemodalContainer: { height: 180, width: 250, borderRadius: 20, }, addPhotoText: { color: '#000000', fontSize: 24, textAlign: 'center', fontWeight: '500' }, cemaraImageContainer: { flexDirection: 'row', padding: 15, justifyContent: 'space-between', paddingTop: 20, }, takePhotoText: { textAlign: 'center', marginTop: 4, color: '#7a7a7a', fontSize: 10 }, closeImage: { width:15 , height: 15,marginRight:17,marginTop:15 }, }); <file_sep>/hr Office/HrApp/services/UserService/Leave.js import { postApi, getApi } from "../api"; export const createLeave = async data => postApi("RtLeaveApi/CreateLeave", {}, data); export const GetLeaveList = async (userId) => getApi("RtLeaveApi/GetUserLeaves?userId="+userId, {}, {}); export const GetLeaveStatusList = async () => getApi("RtLeaveApi/GetLeaveTypeList", {}, {}); <file_sep>/hr Office/HrApp/components/Screen/leaves/LeaveListStyle.js import { StyleSheet, Platform } from 'react-native'; export const LeaveListStyle = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f6f7f9', }, headerContainer: { flexDirection: 'row', height: 60, paddingTop: 0, backgroundColor: 'white', shadowColor: 'rgba(181,181,181,0.02)', shadowOffset: { width: 0, height: -2 }, elevation: 10, shadowRadius: 8, shadowOpacity: 0.3, alignItems: 'center', paddingHorizontal: 10, justifyContent: 'space-between', borderBottomRightRadius: 10, borderBottomLeftRadius: 10 }, headerText: { fontWeight: 'bold', fontSize: 20, color: '#141414', marginTop: 3, }, loaderIndicator: { position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, justifyContent: 'center', alignContent: 'center', }, HeaderContent: { justifyContent: 'space-between', backgroundColor: '#fff', flexDirection: 'row', padding: 10, borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 10, height: -5 }, elevation: 10, height: 60, }, HeaderFirstView: { justifyContent: 'flex-start', flexDirection: 'row', marginLeft: 5, alignItems: 'center', }, HeaderMenuicon: { alignItems: 'center' }, HeaderMenuiconstyle: { width: 20, height: 20, }, HeaderTextView: { backgroundColor: 'white', padding: 0, marginLeft: 17, margin: 0, flexDirection: 'row', alignItems: 'center', }, HeaderTextstyel: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: "left", color: "#2a2a2a", }, headerBar: { justifyContent: 'space-between', backgroundColor: 'white', flexDirection: 'row', padding: 10, borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 0, height: -5 }, elevation: 10, height: 60, }, backIcon: { justifyContent: 'flex-start', flexDirection: 'row', alignItems: 'center', }, backIconTouch: { padding: 10, flexDirection: 'row', alignItems: 'center' }, headerTitleText: { color: '#4E4E4E', marginTop: 1, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: 'center', }, headerTitle: { padding: 0, paddingLeft: 10, margin: 0, flexDirection: 'row', }, listContainer: { flexDirection: 'column', justifyContent: 'space-between', paddingTop: 2, paddingBottom: 2, padding: 15, borderRadius: 5, marginTop: 5, marginBottom: 5, backgroundColor: '#ffffff', margin: 10, elevation: 2, }, listInnerContainer: { marginTop: 5, flexDirection: 'row', justifyContent: 'space-between', padding: 2 }, leaveType: { width: "60%", justifyContent: 'flex-start', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, leaveFrom: { justifyContent: 'flex-end', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, leaveReasonContainer: { flexDirection: 'row', justifyContent: 'space-between', }, leaveReasonText: { width: "60%", justifyContent: 'flex-start', fontFamily: "Montserrat_Bold", fontSize: 14, textAlign: "left", color: "#1a1a1a" }, reasonFromDate: { justifyContent: 'flex-end', fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, causeContainer: { flexDirection: 'row', justifyContent: 'space-between', padding: 2, paddingVertical: 5, }, causeContainer1: { justifyContent: 'space-between', padding: 2, paddingRight:0, flexDirection:'row', marginBottom:5, }, causeText: { width: "60%", justifyContent: 'flex-start', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, causeText1: { // width: "60%", //justifyContent: 'flex-start', //opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "right", alignItems:"flex-end" }, leaveToText: { justifyContent: 'flex-end', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, detailsContainer: { flexDirection: 'row', justifyContent: 'space-between', paddingBottom: 10, }, detailsText: { width: "60%", justifyContent: 'flex-start', fontFamily: "PRODUCT_SANS_REGULAR", fontSize: 14, textAlign: "left", color: "#1a1a1a", marginLeft:3, }, detailsTextInner: { justifyContent: 'flex-end', fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, approvedByContainer: { flex: 1, flexDirection: 'column', justifyContent: 'space-between', padding: 2, paddingVertical: 5, borderTopWidth: 0.4, borderTopColor: "black", }, approvedByText: { // width: "60%", justifyContent: 'flex-start', // flex: 1, flexWrap: 'wrap', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, approvedByText1: { //width: "60%", justifyContent: 'flex-start', fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", }, approvedAtText: { // flex: 1, flexWrap: 'wrap', justifyContent: 'flex-end', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a", marginTop: 5, }, approvedAtText1: { justifyContent: 'flex-end', fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", }, statusButton: { flexDirection: 'row', justifyContent: 'space-between', borderTopWidth: 0.4, borderTopColor: "black", paddingTop: 5, paddingBottom: 8, alignItems: 'center', }, statusButtonInner: { flexDirection: 'row', justifyContent: 'flex-start', width: "60%", padding: 5, }, statusDate: { justifyContent: 'flex-end', fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, paddingLeft: 3, textAlign: "center", color: "#929292", marginRight: 5, }, daysBox: { alignItems: 'center', justifyContent: 'center', backgroundColor: "#f4f5f6", borderWidth: 0.5, padding: 4, borderRadius: 10, }, statusDate1: { alignItems: 'flex-end', fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#929292", marginRight: 5, marginTop: 15, }, buttonContainer: { flexDirection: 'row', // justifyContent: 'flex-start', //width: "60%", justifyContent: 'space-between', borderTopWidth: 0.5, borderTopColor: '#f6f7f9', }, buttonTouchable: { width: 82.3, height: 29.4, borderRadius: 5, backgroundColor: "#1e8555", justifyContent: 'center', marginBottom: 10, }, approveText: { fontFamily: "Montserrat_Bold", fontSize: 10, textAlign: "center", color: "#ffffff", }, rejectButtonTouchable: { width: 82.3, height: 29.4, borderRadius: 5, backgroundColor: "#c24a4a", justifyContent: 'center', marginLeft: 4, }, rejectText: { fontFamily: "Montserrat_Bold", fontSize: 10, textAlign: "center", color: "#ffffff" }, foraligmentitem: { alignItems: 'flex-start', flexDirection: 'row', marginTop: 10, } }); <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/DbUtility/DbConnectionSrtingManager.cs using Microsoft.Win32; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.Common { public class DbConnectionSrtingManager { private static string dbName; private static string dbServer; private static string dbUser; private static string dbPassword; private static int conTimeout; static DbConnectionSrtingManager() { DbConnectionSrtingManager.conTimeout = 15; } public DbConnectionSrtingManager() { } public static string GetCompanyGroupId() { string str; try { str = (new AppSettingsReader()).GetValue("CGID", typeof(string)).ToString(); } catch { throw new CustomException(Resources.CompanyGroupName, null); } return str; } private static string GetCompanyGroupName() { string str; try { str = (new AppSettingsReader()).GetValue("CGNAME", typeof(string)).ToString(); } catch { throw new CustomException(Resources.CompanyGroupName, null); } return str; } private static string GetDb() { string str; try { str = (new AppSettingsReader()).GetValue("DBNAME", typeof(string)).ToString(); } catch { throw new CustomException(Resources.DbName, null); } return str; } public static string GetDbConnectionString() { string str; //DbConnectionSrtingManager.GetCompanyGroupName(); try { if (string.IsNullOrEmpty(DbConnectionSrtingManager.dbUser)) { DbConnectionSrtingManager.dbName = DbConnectionSrtingManager.GetDb(); DbConnectionSrtingManager.dbServer = DbConnectionSrtingManager.GetDbServer(); DbConnectionSrtingManager.dbUser = DbConnectionSrtingManager.GetDbUser(); DbConnectionSrtingManager.dbPassword = DbConnectionSrtingManager.GetDbPwd(); DbConnectionSrtingManager.conTimeout = DbConnectionSrtingManager.GetDbConTimeout(); } str = string.Format("Data Source='{0}'; Initial Catalog='{1}'; User ID='{2}';Password='{3}';Trusted_Connection=False;Connect Timeout={4}; MultipleActiveResultSets=True;", new object[] { DbConnectionSrtingManager.dbServer, DbConnectionSrtingManager.dbName, DbConnectionSrtingManager.dbUser, DbConnectionSrtingManager.dbPassword, DbConnectionSrtingManager.conTimeout }); } catch (Exception exception) { throw new CustomException(string.Concat("Database configuration fail! ", exception), null); } return str; } private static int GetDbConTimeout() { int num; try { num = Convert.ToInt16((new AppSettingsReader()).GetValue("DBCONTIMEOUT", typeof(string))); } catch { num = DbConnectionSrtingManager.conTimeout; } return num; } private static string GetDbPwd() { string str; try { str = (new AppSettingsReader()).GetValue("DBUSERPWD", typeof(string)).ToString(); } catch { throw new CustomException(Resources.DbPwd, null); } return str; } private static string GetDbServer() { string str; try { str = (new AppSettingsReader()).GetValue("DBSERVER", typeof(string)).ToString(); } catch { throw new CustomException(Resources.DbServerName, null); } return str; } private static void GetDbSettings(string key) { RegistryKey registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(string.Concat("SOFTWARE\\Wow6432Node\\DBDATA\\", key), true) ?? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(string.Concat("SOFTWARE\\Wow6432Node\\DBDATA\\", key), true); DbConnectionSrtingManager.dbServer = registryKey.GetValue("DBServer").ToString(); DbConnectionSrtingManager.dbUser = registryKey.GetValue("DBUser").ToString(); DbConnectionSrtingManager.dbPassword = registryKey.GetValue("DBPassword").ToString(); DbConnectionSrtingManager.dbName = registryKey.GetValue("DBName").ToString(); registryKey.Close(); } private static string GetDbUser() { string str; try { str = (new AppSettingsReader()).GetValue("DBUSERID", typeof(string)).ToString(); } catch { throw new CustomException(Resources.DbUserName, null); } return str; } } } <file_sep>/hr Office/HrApp/components/Screen/tasks/CompleteTaskFilter.js import React, { Component } from 'react'; import { Text, View, Image, StatusBar, BackHandler, AsyncStorage, Dimensions, TouchableOpacity, Platform, Alert, RefreshControl, ActivityIndicator, ScrollView, } from 'react-native'; import { SearchBar } from 'react-native-elements'; import _ from "lodash"; import { TaskStyle } from './TaskStyle'; import { GetRelatedToMeTasks } from '../../../services/TaskService'; import { Actions } from 'react-native-router-flux'; import * as actions from '../../../common/actions'; import TaskLists from "./TaskListComponent" import { CommonStyles } from '../../../common/CommonStyles'; // import // { // FontAwesome, // } from '@expo/vector-icons'; import FontAwesome from 'react-native-vector-icons/FontAwesome' const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar /> </View> ); } var screen = Dimensions.get('window'); export default class CompleteTaskFilter extends Component { constructor(props) { super(props); this.state = { progressVisible: false, refreshing: false, userId: "", taskList: [], } this.arrayholder = []; } _onRefresh = async () => { this.setState({ refreshing: true }); setTimeout(function () { this.setState({ refreshing: false, }); }.bind(this), 2000); this.getTaskList(this.state.userId, false); }; async componentDidMount() { const uId = await AsyncStorage.getItem("userId"); this.setState({ userId: uId }); this.getTaskList(uId, true); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillMount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } handleBackButton = () => { BackHandler.exitApp() return true; } searchFilterFunction = text => { this.setState({ value: text, }); const newData = this.arrayholder.filter(item => { const itemData = `${item.Title.toUpperCase()} ${item.Title.toUpperCase()} ${item.Title.toUpperCase()}`; const textData = text.toUpperCase(); return itemData.indexOf(textData) > -1; }); this.setState({ taskList: newData, }); }; renderHeader = () => { return ( <SearchBar placeholder="Type Here..." lightTheme containerStyle={{ backgroundColor: '#f6f7f9', }} inputContainerStyle={{ backgroundColor: 'white', }} round onChangeText={text => this.searchFilterFunction(text)} autoCorrect={false} value={this.state.value} /> ); }; getTaskList = async (userId, isProgress) => { try { this.setState({ progressVisible: isProgress }); await GetRelatedToMeTasks(userId) .then(res => { this.setState({ taskList: res.result.filter(x=>x.StatusName==="Completed" || x.StatusName==="Cancelled"), progressVisible: false }); console.log(this.arrayholder, 'taskresutl...'); }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); } catch (error) { this.setState({ progressVisible: false }); console.log(error); } } goToCreateTask() { Actions.CreateTask() } gotoDetails(task) { actions.push("ViewTask", { TaskModel: task, arrayholder: this.arrayholder, }); } render() { return ( <View style={TaskStyle.container}> <StatusBarPlaceHolder /> <View style={CommonStyles.HeaderContent}> <View style={CommonStyles.HeaderFirstView}> <TouchableOpacity style={CommonStyles.HeaderMenuicon} onPress={() => { Actions.drawerOpen(); }}> <Image resizeMode="contain" style={CommonStyles.HeaderMenuiconstyle} source={require('../../../assets/images/menu_b.png')}> </Image> </TouchableOpacity> <View style={CommonStyles.HeaderTextView}> <Text style={CommonStyles.HeaderTextstyle}> TASKS </Text> </View> </View> <View style={CommonStyles.createTaskButtonContainer}> <TouchableOpacity onPress={() => this.goToCreateTask()} style={CommonStyles.createTaskButtonTouch}> <View style={CommonStyles.plusButton}> <FontAwesome name="plus" size={18} color="#ffffff"> </FontAwesome> </View> <View style={CommonStyles.ApplyTextButton}> <Text style={CommonStyles.ApplyButtonText}> TASK </Text> </View> </TouchableOpacity> </View> </View> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={TaskStyle.loaderIndicator} />) : null} <ScrollView refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> } > <TaskLists itemList={this.state.taskList} headerRenderer={this.renderHeader()} /> </ScrollView> </View > ) } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/AttendanceModel.cs using TrillionBitsPortal.Common; using System; using System.Globalization; using System.Web.Script.Serialization; namespace TrillionBitsPortal.ResourceTracker.Models { public class AttendanceEntryModel { public string UserId { get; set; } public decimal? Latitude { get; set; } public decimal? Longitude { get; set; } public string LogLocation { get; set; } public string DeviceName { get; set; } public string DeviceOSVersion { get; set; } public int? CompanyId { get; set; } public string Reason { get; set; } public int? OfficeHour { get; set; } public int? AllowOfficeLessTime { get; set; } public bool? IsLeave { get; set; } } public class AttendanceTotalModel { public string UserId { get; set; } public string EmployeeName { get; set; } public string Designation { get; set; } public string DepartmentName { get; set; } public string ImageFileName { get; set; } public int? TotalPresent { get; set; } public int? TotalCheckedOutMissing { get; set; } public string TotalStayTime { get; set; } public string TotalOfficeHour { get; set; } public string OvertimeOrDueHour { get; set; } public int? TotalLeave { get; set; } public double TotalScore { get; set; } } public class AttendanceModel { public int Id { get; set; } public string UserId { get; set; } [ScriptIgnore] public DateTime? AttendanceDate { get; set; } [ScriptIgnore] public DateTime? CheckInTime { get; set; } [ScriptIgnore] public DateTime? CheckOutTime { get; set; } public bool? IsLeave { get; set; } public string LessTimeReason { get; set; } public int? DailyWorkingTimeInMin { get; set; } public int? AllowOfficeLessTimeInMin { get; set; } public int? CompanyId { get; set; } public int? EmployeeId { get; set; } public string EmployeeName { get; set; } public string PhoneNumber { get; set; } public string Designation { get; set; } public string DepartmentName { get; set; } public string AttendanceDateVw { get { return AttendanceDate.HasValue ? AttendanceDate.Value.ToZoneTimeBD().ToString(Constants.DateLongFormat) : string.Empty; } } public string AttendancceDayName { get { return AttendanceDate.HasValue ? AttendanceDate.Value.ToZoneTimeBD().ToString("ddd") : string.Empty; } } public string AttendancceDayNumber { get { return AttendanceDate.HasValue ? string.Format("{0}",AttendanceDate.Value.ToZoneTimeBD().Day) : string.Empty; } } public string CheckInTimeVw { get { return CheckInTime.HasValue ? CheckInTime.Value.ToZoneTimeBD().ToString(Constants.TimeFormat) : (IsLeave.HasValue && IsLeave.Value?"Leave": string.Empty); } } public string CheckOutTimeVw { get { return CheckOutTime.HasValue ? CheckOutTime.Value.ToZoneTimeBD().ToString(Constants.TimeFormat) : string.Empty; } } public string OfficeStayHour { get { if (!CheckInTime.HasValue) return string.Empty; TimeSpan result = CheckOutTime.HasValue? CheckOutTime.Value.ToZoneTimeBD().Subtract(CheckInTime.Value.ToZoneTimeBD()): DateTime.UtcNow.ToZoneTimeBD().Subtract(CheckInTime.Value.ToZoneTimeBD()); int hours = result.Hours; int minutes = result.Minutes; return string.Format("{0}:{1}",hours,minutes); } } public bool IsCheckedIn { get { return CheckInTime.HasValue && !CheckOutTime.HasValue; } } public bool IsPresent { get { return CheckInTime.HasValue; } } public bool IsCheckedOut { get { return CheckInTime.HasValue && CheckOutTime.HasValue; } } public bool NotCheckedOut { get { return CheckInTime.HasValue && !CheckOutTime.HasValue; } } public bool NotAttend { get { return !CheckInTime.HasValue && !CheckOutTime.HasValue; } } public string ImageFileName { get; set; } public string Status { get { if (CheckInTime.HasValue && !CheckOutTime.HasValue) return "Checked-In"; else if (CheckInTime.HasValue && CheckOutTime.HasValue) return "Checked-Out"; else if (!CheckInTime.HasValue && !CheckOutTime.HasValue && !IsLeave.HasValue) return "Absent"; else if (!CheckInTime.HasValue && !CheckOutTime.HasValue && IsLeave.HasValue && IsLeave.Value) return "Leave"; else return string.Empty; } } public int? TotalStayTimeInMinute { get { if (!CheckInTime.HasValue) return 0; TimeSpan result = CheckOutTime.HasValue ? CheckOutTime.Value.ToZoneTimeBD().Subtract(CheckInTime.Value.ToZoneTimeBD()) : CheckInTime.Value.ToZoneTimeBD().Subtract(CheckInTime.Value.ToZoneTimeBD()); int hours = result.Hours; int minutes = result.Minutes; return hours * 60 + minutes; } } } public class UserMovementLogModel { public string Id { get; set; } public string UserId { get; set; } public DateTime? LogDateTime { get; set; } public decimal? Latitude { get; set; } public decimal? Longitude { get; set; } public string LogLocation { get; set; } public bool? IsCheckInPoint { get; set; } public bool? IsCheckOutPoint { get; set; } public string DeviceName { get; set; } public string DeviceOSVersion { get; set; } public int? CompanyId { get; set; } public string LogTimeVw { get { return LogDateTime.HasValue ? LogDateTime.Value.ToZoneTimeBD().ToString(Constants.TimeFormat) : string.Empty; } } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/NoticeDepartmentVIewModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.ResourceTracker.Models { public class NoticeDepartmentVIewModel { public string Id { get; set; } public string Details { get; set; } public string PostingDate { get; set; } public string ImageFileName { get; set; } public string CreatedBy { get; set; } public string CreateDate { get; set; } public int? CompanyId { get; set; } } } <file_sep>/hr Office/HrApp/services/api/index.js import { AsyncStorage, NetInfo,ToastAndroid } from "react-native"; import _ from "lodash"; import apiConfig from "./config"; import {CheckConnection} from '../../common/checkNetConnection' export const getApi = async (action, headers = {}) => { try { if (await NetInfo.isConnected.fetch()){ const userToken = await AsyncStorage.getItem("userToken"); console.log('UserToker:',userToken); let requestHeaders = _.pickBy( { ...(userToken ? { Authorization: `bearer ${userToken}` } : { "Client-ID": apiConfig.clientId }), ...headers, ...{ Accept: "application/json", "Content-Type": "application/json" } }, item => !_.isEmpty(item) ); console.log(`getApi url: ${apiConfig.url}${action}`); let response = await fetch(`${apiConfig.url}${action}`, { method: "GET", headers: requestHeaders }); // console.log(response,'text phone number.........'); if (response.ok) { let responseJson = await response.json(); return { result: responseJson, isSuccess: true, message: "" }; } return { result: null, isSuccess: false, message: response.statusText }; }else{ ToastAndroid.show('Please Connect to Internet', ToastAndroid.TOP); } } catch (error) { console.error(error); return { result: null, isSuccess: false, message: error }; } } export const postApi = async (action, headers = {}, body = {}) => { try { if (await NetInfo.isConnected.fetch()){ console.log(`body: ${body}`); const userToken = await AsyncStorage.getItem("userToken"); let requestHeaders = _.pickBy( { ...(userToken ? { Authorization: `bearer ${userToken}` } : { "Client-ID": apiConfig.clientId }), ...headers, ...{ Accept: "application/json", "Content-Type": "application/json" } }, item => !_.isEmpty(item) ); console.log(`postApi url: ${apiConfig.url}${action}`); let response = await fetch(`${apiConfig.url}${action}`, { method: "POST", headers: requestHeaders, body: JSON.stringify(body) }); console.log("response",response); let responseJson = await response.json(); console.log("responseJson",responseJson); if (response.ok) { return { result: responseJson, isSuccess: true, message: "" }; } return { result: null, isSuccess: false, message: "" }; }else{ ToastAndroid.show('Please Connect to Internet', ToastAndroid.TOP); } } catch (error) { console.error(error); return { result: null, isSuccess: false, message: error }; } }; // export const postApi = async (action, headers = {}, body = {}) => { // try { // console.log(`body: ${body}`); // const userToken = await AsyncStorage.getItem("userToken"); // let requestHeaders = _.pickBy( // { // ...(userToken // ? { // Authorization: `Bearer ${userToken}` // } // : { // "Client-ID": apiConfig.clientId // }), // ...headers, // ...{ // "Content-Type": "application/json" // } // }, // item => !_.isEmpty(item) // ); // var object = { // method: 'POST', // headers:requestHeaders, // body:body // }; // console.log(`postApi url: ${apiConfig.url}${action}`); // console.log(`postApi body`,object); // let response = await fetch(`${apiConfig.url}${action}`, object); // let responseJson = await response.json(); // console.log("responseJson",responseJson); // if (response.ok) { // return { result: responseJson, isSuccess: true, message: "" }; // } // return { result: null, isSuccess: false, message: "" }; // } catch (error) { // console.error(error); // return { result: null, isSuccess: false, message: error }; // } // }; export const loginPostApi = async (action, headers = {}, body = {}) => { try { if (await NetInfo.isConnected.fetch()){ console.log(`body: ${body}`); if(await !NetInfo.isConnected.fetch()){ alert("test..."); // this.setState({alertHeading:"Invalid Phonenumber!"}) throw "Please Connect Internet"; } const userToken = await AsyncStorage.getItem("userToken"); let requestHeaders = _.pickBy( { ...(userToken ? { Authorization: `Bearer ${userToken}` } : { "Client-ID": apiConfig.clientId }), ...headers, ...{ // "Content-Type": "application/x-www-form-urlencoded" } }, item => !_.isEmpty(item) ); console.log(`postApi url: ${apiConfig.url}${action}`); console.log(`postApi body`, "userName=" + encodeURIComponent(body.UserName) + "&password=" + encodeURIComponent(body.Password) + "&grant_type=password"); let response = await fetch(`${apiConfig.url}${action}`, { method: "POST", headers: requestHeaders, body: "UserName=" + encodeURIComponent(body.UserName) + "&Password=" + encodeURIComponent(body.<PASSWORD>) + "&grant_type=password", }); console.log let responseJson = await response.json(); console.log("responseJson",responseJson); if (response.ok) { return { result: responseJson, isSuccess: true, message: "" }; } return { result: null, isSuccess: false, message: "" }; }else{ ToastAndroid.show('Please Connect to Internet', ToastAndroid.TOP); } } catch (error) { console.error(error); return { result: null, isSuccess: false, message: error }; } }; export const postApiFormDataForPDF = async ( action, headers = {}, keyValue = {}, uri = "", fileType = "", fileName = "" ) => { try { if (await NetInfo.isConnected.fetch()){ const userToken = await AsyncStorage.getItem("userToken"); let requestHeaders = _.pickBy( { ...(userToken ? { Authorization: `Bearer ${userToken}` } : { "Client-ID": apiConfig.clientId }), ...headers, ...{ Accept: "application/json", "Content-Type": "multipart/form-data" } }, item => !_.isEmpty(item) ); var formData = new FormData(); //Fields in the post formData.append(keyValue.key, keyValue.Value); // pictureSource is object containing image data. if (uri) { var document = { uri: uri, type: 'document/pdf', name: 'files.pdf' }; formData.append("files", document); } console.log(`${apiConfig.url}${action}`); let response = await fetch(`${apiConfig.url}${action}`, { method: "POST", headers: requestHeaders, body: formData }); let responseJson = await response.json(); return { result: responseJson, isSuccess: true, message: "" }; }else{ ToastAndroid.show('Please Connect to Internet', ToastAndroid.TOP); } } catch (error) { console.error(error); return { result: null, isSuccess: false, message: error }; } }; export const postApiFormData = async ( action, headers = {}, keyValue = {}, uri = "", fileType = "", fileName = "" ) => { try { if (await NetInfo.isConnected.fetch()){ const userToken = await AsyncStorage.getItem("userToken"); let requestHeaders = _.pickBy( { ...(userToken ? { Authorization: `Bearer ${userToken}` } : { "Client-ID": apiConfig.clientId }), ...headers, ...{ Accept: "application/json", "Content-Type": "multipart/form-data" } }, item => !_.isEmpty(item) ); var formData = new FormData(); // Fields in the post formData.append(keyValue.key, keyValue.Value); // pictureSource is object containing image data. if (uri) { var photo = { uri: uri, type: fileType, name: fileName }; formData.append("files", photo); } console.log(`${apiConfig.url}${action}`); let response = await fetch(`${apiConfig.url}${action}`, { method: "POST", headers: requestHeaders, body: formData }); if (response.ok) { let responseJson = await response.json(); return { result: responseJson, isSuccess: true, message: "" }; } return { result: null, isSuccess: false, message: response.statusText }; }else{ ToastAndroid.show('Please Connect to Internet', ToastAndroid.TOP); } } catch (error) { console.error(error); return { result: null, isSuccess: false, message: error }; } }; export const deleteApi = async (action, headers = {}) => { try { if (await NetInfo.isConnected.fetch()){ const userToken = await AsyncStorage.getItem("userToken"); let requestHeaders = _.pickBy( { ...(userToken ? { Authorization: `bearer ${userToken}` } : { "Client-ID": apiConfig.clientId }), ...headers, ...{ Accept: "application/json", "Content-Type": "application/json" } }, item => !_.isEmpty(item) ); console.log(`${apiConfig.url}${action}`); let response = await fetch(`${apiConfig.url}${action}`, { method: "DELETE", headers: requestHeaders }); console.log(response,'..........................') if (response.ok) { let responseJson = await response.json(); return { result: responseJson, isSuccess: true, message: "" }; } return { result: null, isSuccess: false, message: response.statusText }; }else{ ToastAndroid.show('Please Connect to Internet', ToastAndroid.TOP); } } catch (error) { console.error(error); return { result: null, isSuccess: false, message: error }; } };<file_sep>/hr Office/HrApp/components/Screen/company/CompanysetupScreen.js import React from 'react'; import { Platform, StatusBar, ToastAndroid, Dimensions, KeyboardAvoidingView, Alert, View, BackHandler, Text, FlatList, Image, AsyncStorage, ScrollView, ActivityIndicator, TouchableOpacity, TextInput } from 'react-native'; import Modal from 'react-native-modalbox'; import moment from 'moment'; import { Actions } from 'react-native-router-flux'; import * as actions from '../../../common/actions'; import { IsNullOrEmpty } from '../../../services/settingService'; import { FontAwesome, } from '@expo/vector-icons' import DateTimePicker from 'react-native-modal-datetime-picker'; import { CreateCompany, GetCompanyByUserId, GetCompanyByIdentity, updatedeCompany } from '../../../services/CompanyService'; import { loadFromStorage, storage, CurrentUserProfile, } from "../../../common/storage"; import { NoticeStyle } from '../../Screen/notice/NoticeStyle' import { CompanySetupStyle } from './CompanySetupStyle' const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar // barStyle="light-content" /> </View> ); } export default class CompanysetupScreen extends React.Component { constructor(props) { super(props); this.state = { date: new Date(), companyList: [], ComName: "", ComId: "", Address: '', phone: '', isDateTimePickerVisible: false, isDateTimePickerVisible1: false, IsAutoCheckPoint: false, selectedStartDate: null, PortalUserId: '', UserId: '', isDisabled: false, swipeToClose: false, backdropPressToClose: false, CompanyName: '', CompanyAddress: '', CompanyMobileNo: '', DepartmentName: '', MaximumOfficeHours: '8:00:00', OfficeOutTime: '00:30:00', progressVisible: true, refreshing: false, companyid: null, } } _showDateTimePicker = () => this.setState({ isDateTimePickerVisible: true }); _hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false }); _handleDatePicked = (date) => { this.setState({ MaximumOfficeHours: moment(date).format("HH:mm:ss") }) console.log('A date has been picked: ', moment(date).format("HH:mm:ss")); this._hideDateTimePicker(); // alert( moment(date).format("HH:mm:ss")); } _showDateTimePicker1 = () => this.setState({ isDateTimePickerVisible1: true }); _hideDateTimePicker1 = () => this.setState({ isDateTimePickerVisible1: false }); _handleDatePicked1 = (date) => { this.setState({ OfficeOutTime: moment(date).format("HH:mm:ss") }) console.log('A date has been picked: ', moment(date).format("HH:mm:ss")); this._hideDateTimePicker1(); // alert( moment(date).format("HH:mm:ss")); } handleBackButton = () => { this.goBack(); return true; } async componentDidMount() { this._bootstrapAsync(); this.getCompany(); const companyid = await AsyncStorage.getItem("companyId"); this.setState({ companyid: companyid }); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillMount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } openModal2() { this.getCompany(); this.refs.modal2.open() } openmodalforEmpList() { this.getCompany(); this.refs.modalforEmpList.open(); } _bootstrapAsync = async () => { var response = await loadFromStorage(storage, CurrentUserProfile); await this.setState({ PortalUserId: response.item.Id }); } _EditCom = async (item) => { this.methodforcom(item); this.refs.modalcomupdate.open(); // this.refs.modal3.close(); } methodforcom = async (item) => { this.setState({ ComName: item.Text }) this.setState({ ComId: item.Value }) this.setState({ Address: item.Address }) this.setState({ phone: item.phone }) this.setState({ MaximumOfficeHours: item.MaximumOfficeHours }) this.setState({ OfficeOutTime: item.OfficeOutTime }) } closemodalForupdateCom() { if (this.state.ComName == "" && this.state.Address == "" && this.state.phone == "") { ToastAndroid.show('Field can not be empty', ToastAndroid.TOP); } else { this.refs.modalcomupdate.close(); this.updateCom(); } } updateCom = async () => { try { let company = { Id: this.state.ComId, CompanyName: this.state.ComName, Address: this.state.Address, PhoneNumber: this.state.phone, MaximumOfficeHours: this.state.MaximumOfficeHours, OfficeOutTime: this.state.OfficeOutTime }; let response = await updatedeCompany(company); console.log('Company..', response); if (response && response.isSuccess) { this.getCompany(); } else { Alert.alert( "", "Invalid Input", [ { text: 'OK', }, ], { cancelable: false } ) } } catch (errors) { console.log(errors); } } getCompany = async () => { try { this.setState({ progressVisible: true }) var response = await loadFromStorage(storage, CurrentUserProfile); await GetCompanyByUserId(response.item.Id) .then(res => { console.log('company', res.result); if (res.result === null) { this.setState({ progressVisible: false }) } else if (res.result.length > 0) { const cList = []; res.result.forEach(function (item) { const ob = { 'Text': item.CompanyName, 'Value': item.Id, 'Address': item.Address, 'phone': item.PhoneNumber, 'MaximumOfficeHours': item.MaximumOfficeHours, 'OfficeOutTime': item.OfficeOutTime, } cList.push(ob); }); this.setState( { companyList: cList } ) this.setState({ selctedCompanyValue: this.state.companyList[0].Text }) this.setState({ slectedCompanyIndex: this.state.companyList[0].Value }) if (this.state.companyid == null) { AsyncStorage.setItem("companyId", this.state.companyList[0].Value.toString()); } this.setState({ progressVisible: false }) } }) .catch(() => { this.setState({ progressVisible: false }) console.log("error occured"); }); } catch (error) { this.setState({ progressVisible: false }) console.log(error); } } closeModal4() { if (this.state.CompanyName == "") { ToastAndroid.show('CompanyName can not be empty', ToastAndroid.TOP); } else if (this.state.CompanyAddress == '') { ToastAndroid.show('Address can not be empty', ToastAndroid.TOP); } else if (this.state.CompanyMobileNo == '') { ToastAndroid.show('Phonenumber can not be empty', ToastAndroid.TOP); } else { this.onFetchCompanyRecords(); } } async onFetchCompanyRecords() { console.log("trying company create.."); try { let CompanyModel = { MaximumOfficeHours: this.state.MaximumOfficeHours, OfficeOutTime: this.state.OfficeOutTime, CompanyName: this.state.CompanyName, Address: this.state.CompanyAddress, PhoneNumber: this.state.CompanyMobileNo, PortalUserId: this.state.PortalUserId, }; console.log(CompanyModel, 'savetest') let response = await CreateCompany(CompanyModel); console.log('com', response); if (response && response.isSuccess) { console.log('com', response); const ob = { 'Text': response.result.CompanyName, 'Value': response.result.Id } this.state.companyList.push(ob); this.getCompany(); ToastAndroid.show("Company created successfully", ToastAndroid.TOP); this.refs.modal4.close(); this.setState({ CompanyName: '', CompanyAddress: '', CompanyMobileNo: '', }) } else { ToastAndroid.show("error", ToastAndroid.TOP); } } catch (errors) { ToastAndroid.show("error", ToastAndroid.TOP); } } openModal4() { this.refs.modal4.open() } goBack() { Actions.pop(); } render() { var { width, } = Dimensions.get('window'); return ( <View style={CompanySetupStyle.container}> <StatusBarPlaceHolder /> <View style={NoticeStyle.headerBarforCompany}> <View style={NoticeStyle.backIcon}> <TouchableOpacity style={NoticeStyle.backIconTouch} onPress={() => { this.goBack() }}> <Image resizeMode="contain" style={{ width: 20, height: 20, }} source={require('../../../assets/images/left_arrow.png')}> </Image> </TouchableOpacity> <View style={NoticeStyle.headerTitle}> <Text style={NoticeStyle.headerTitleText}> COMPANY SETUP </Text> </View> </View> <View style={NoticeStyle.createNoticeButtonContainer}> <View style={NoticeStyle.ApplyButtonContainer}> <TouchableOpacity onPress={() => this.openModal4()} style={NoticeStyle.ApplyButtonTouch}> <View style={NoticeStyle.plusButtonforCompany}> <FontAwesome name="plus" size={18} color="#ffffff"> </FontAwesome> </View> <View style={NoticeStyle.ApplyTextButtonforNotice}> <Text style={NoticeStyle.ApplyButtonText}> NEW </Text> </View> </TouchableOpacity> </View> </View> </View> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, justifyContent: 'center', alignContent: 'center', }} />) : null} <View style={CompanySetupStyle.FlatListContainer}> <FlatList data={this.state.companyList} keyExtractor={(x, i) => i.toString()} renderItem={({ item }) => <View style={CompanySetupStyle.FlatListItemContainer}> <View style={CompanySetupStyle.ListPart}> <Text style={CompanySetupStyle.companyText}>{item.Text}</Text> <View style={{ flexDirection: 'row', width: (width * 50) / 100, }}> <Image resizeMode="contain" style={CompanySetupStyle.locationIcon} source={require('../../../assets/images/Path_87.png')}></Image> <Text style={CompanySetupStyle.locationText}>{item.Address}</Text> </View> <View style={{ flexDirection: 'row', width: (width * 50) / 100, }}> <Image style={CompanySetupStyle.phoneIcon} source={require('../../../assets/images/Path_86.png')}></Image> <Text style={CompanySetupStyle.phoneText}>{item.phone}</Text> </View> </View> <TouchableOpacity onPress={() => this._EditCom(item)} style={{ marginTop: 5, }}> <View style={CompanySetupStyle.editCotainer}> <Image style={CompanySetupStyle.editImage} source={require('../../../assets/images/edit.png')}></Image> <Text style={CompanySetupStyle.editText}>EDIT</Text> </View> </TouchableOpacity> </View> } /> {/* <CompanyLists itemList={this.state.companyList}/> */} </View> <Modal style={[CompanySetupStyle.modal3]} position={"center"} ref={"modal4"} isDisabled={this.state.isDisabled} onOpened={() => this.setState({ floatButtonHide: true })} backdropPressToClose={false} swipeToClose={true} > <View style={CompanySetupStyle.modalHeader}> <View style={CompanySetupStyle.modalheaderLeft}></View> <View style={CompanySetupStyle.modalheaderRight}> <TouchableOpacity onPress={() => this.refs.modal4.close()} style={CompanySetupStyle.closeTouchable}> <Image resizeMode="contain" style={{ width: 15, height: 15, marginRight: 17, marginTop: 15 }} source={require('../../../assets/images/close.png')}> </Image> </TouchableOpacity> </View> </View> <View style={CompanySetupStyle.modelContent}> <Text style={{ fontWeight: 'bold', fontSize: 25 }}> ADD COMPANY </Text> <Image resizeMode="contain" style={CompanySetupStyle.addPeopleImg} source={require('../../../assets/images/company.png')}> </Image> </View> <TextInput style={CompanySetupStyle.addCompanyinputBox} placeholder="Company Name" placeholderTextColor="#cbcbcb" returnKeyType="next" autoCorrect={false} onSubmitEditing={() => this.refs.txtAddress.focus()} onChangeText={(text) => this.setState({ CompanyName: text })} value={this.state.CompanyName} /> <TextInput style={CompanySetupStyle.addCompanyinputBox} placeholder="Address" placeholderTextColor="#cbcbcb" returnKeyType="next" autoCorrect={false} ref={"txtAddress"} onSubmitEditing={() => this.refs.txtPhone.focus()} onChangeText={(text) => this.setState({ CompanyAddress: text })} value={this.state.CompanyAddress} /> <TextInput style={CompanySetupStyle.addCompanyinputBox} placeholder="Mobile Number" placeholderTextColor="#cbcbcb" keyboardType="number-pad" ref={"txtPhone"} returnKeyType="go" autoCorrect={false} onChangeText={(text) => this.setState({ CompanyMobileNo: text })} value={this.state.CompanyMobileNo} /> <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', }}> <Text style={{ // marginTop: 10, marginLeft: 20, justifyContent: 'flex-start' }}> Maximum Office Hours: </Text> <TouchableOpacity onPress={this._showDateTimePicker} style={{ marginRight: 18, justifyContent: "flex-end" }} > <View> <TextInput editable={false} style={CompanySetupStyle.inputstylecom} value={this.state.MaximumOfficeHours} /> </View> </TouchableOpacity> <DateTimePicker isVisible={this.state.isDateTimePickerVisible} onConfirm={this._handleDatePicked} onCancel={this._hideDateTimePicker} mode={'time'} /> </View> <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}> <Text style={{ // marginTop: 10, marginLeft: 20, justifyContent: 'flex-start', }}> Can Leave Before: </Text> <TouchableOpacity onPress={this._showDateTimePicker1} style={{ marginRight: 18, justifyContent: "flex-end" }} > <View> <TextInput editable={false} style={CompanySetupStyle.inputstylecom} value={this.state.OfficeOutTime} /> </View> </TouchableOpacity> <DateTimePicker isVisible={this.state.isDateTimePickerVisible1} onConfirm={this._handleDatePicked1} onCancel={this._hideDateTimePicker1} mode={'time'} /> </View> <TouchableOpacity style={CompanySetupStyle.addPeopleBtn} onPress={() => this.closeModal4()} > <Text style={{ color: 'white', fontWeight: 'bold', textAlign: 'center', }}>Add</Text> </TouchableOpacity> </Modal> <Modal style={[CompanySetupStyle.modalforCreateCompany]} position={"center"} ref={"modalcomupdate"} isDisabled={this.state.isDisabled} backdropPressToClose={false} swipeToClose={false} > <View style={{ justifyContent: "space-between", flexDirection: "row" }}> <View style={{ alignItems: "flex-start" }}> </View> <View style={{ alignItems: "flex-end" }}> <TouchableOpacity onPress={() => this.refs.modalcomupdate.close()} style={CompanySetupStyle.closeTouchable}> <Image resizeMode="contain" style={{ width: 15, height: 15, marginRight: 17, marginTop: 15 }} source={require('../../../assets/images/close.png')}> </Image> </TouchableOpacity> </View> </View> <View style={{ marginTop: 10 }}> <View style={{}}> <Text style={CompanySetupStyle.lablecompanyName}> Company Name: </Text> </View> <View> <TextInput style={CompanySetupStyle.inputstyle} value={this.state.ComName} onChangeText={(txt) => this.setState({ ComName: txt })} /> </View> </View> <View style={{ marginTop: 5 }}> <View style={{}}> <Text style={CompanySetupStyle.lableAddress}> Company Address: </Text> </View> <View> <TextInput style={CompanySetupStyle.inputstyle} value={this.state.Address} onChangeText={(txt) => this.setState({ Address: txt })} /> </View> </View> <View style={{ marginTop: 5 }}> <View style={{}}> <Text style={CompanySetupStyle.labelphone}> Company Phone: </Text> </View> <View> <TextInput style={CompanySetupStyle.inputstyle} value={this.state.phone} onChangeText={(txt) => this.setState({ phone: txt })} /> </View> </View> <View style={CompanySetupStyle.labelContainerMax}> <Text style={CompanySetupStyle.lablemax}> Maximum Office Hours: </Text> <TouchableOpacity onPress={this._showDateTimePicker} style={CompanySetupStyle.TextinputTouch} > <View> <TextInput editable={false} style={CompanySetupStyle.inputstylecom} value={this.state.MaximumOfficeHours} /> </View> </TouchableOpacity> <DateTimePicker isVisible={this.state.isDateTimePickerVisible} onConfirm={this._handleDatePicked} onCancel={this._hideDateTimePicker} mode={'time'} /> </View> <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', }}> <Text style={CompanySetupStyle.canleaveText}> Can Leave Before: </Text> <TouchableOpacity onPress={this._showDateTimePicker1} style={{ marginRight: 18, justifyContent: "flex-end" }} > <View> <TextInput editable={false} style={CompanySetupStyle.inputstylecom} value={this.state.OfficeOutTime} /> </View> </TouchableOpacity> <DateTimePicker isVisible={this.state.isDateTimePickerVisible1} onConfirm={this._handleDatePicked1} onCancel={this._hideDateTimePicker1} mode={'time'} /> </View> <TouchableOpacity style={CompanySetupStyle.addPeopleBtncom} onPress={() => this.closemodalForupdateCom()} > <Text style={CompanySetupStyle.SaveStyle}>Save</Text> </TouchableOpacity> </Modal> </View> ); } } <file_sep>/hr Office/HrApp/components/Screen/department/DepartmentSetupStyle.js import { StyleSheet } from 'react-native'; export const DepartmentSetupStyle = StyleSheet.create({ FlatListContainer: { flex: 1, marginTop: 10 }, flatlistLeftItemcontainer: { padding: 14, borderWidth: 0, backgroundColor: '#ffffff', marginBottom: 5, marginLeft: 10, marginRight: 10, borderRadius: 10, borderColor: "white", justifyContent: 'space-between', flexDirection: 'row', borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 10, height: -5 }, elevation: 2, }, DepartmentNameTextCon: { alignItems: 'flex-start', alignItems: 'center' }, DepartmentText: { fontSize: 16, color: '#4a4a4a', marginTop: 7, marginLeft: 10, fontWeight: '500' }, EditContainer: { alignItems: 'flex-end', alignItems: 'center', flexDirection: 'row', marginRight: 15 }, EditImage: { height: 30, width: 30, alignSelf: "flex-end", marginTop: 3 }, EditText: { fontSize: 14, fontWeight: '500', color: '#58687a', marginTop: 2, marginLeft: 4 }, modalheaderContainer: { justifyContent: "space-between", flexDirection: "column" }, Leftheader: { alignItems: "flex-start" }, RightHeader: { alignItems: "flex-end" }, MenuBackTouch: { marginLeft: 0, marginTop: 0, width: 30, height: 30, borderRadius: 30, }, modalCloseImage: { width:15 , height: 15,marginLeft:0,marginTop:15 }, TextInputStyle: { width: 180, height: 40, backgroundColor: '#ebebeb', color: '#2c2930', paddingHorizontal: 10, alignSelf: 'center', borderRadius: 10, textAlign: 'center', marginVertical: 8, }, AddTouch: { backgroundColor: '#3D3159', padding: 10, width: 100, alignSelf: 'center', borderRadius: 20, marginTop: "3%", alignItems: 'center', }, ModalUpContainer: { height: "40%", width: "75%", borderRadius: 20, backgroundColor: '#EBEBEB', }, Deptlable: { marginTop: 15 }, DeptlableText: { fontSize: 14, marginLeft: 15, marginBottom: 5, color: 'gray' }, SaveText: { color: 'white', fontWeight: 'bold', textAlign: 'center' }, Editinput: { width: 240, height: 40, backgroundColor: '#ddd', color: '#2c2930', paddingHorizontal: 10, alignSelf: 'center', borderRadius: 10, textAlign: 'center', marginVertical: 8, }, container: { flex: 1, backgroundColor: '#f6f7f9', }, addPeopleBtn: { backgroundColor: '#319E67', padding: 15, width: 150, alignSelf: 'center', borderRadius: 20, marginVertical: 15, marginTop: "10%" }, addPeopleBtncom: { backgroundColor: '#319E67', padding: 15, width: 150, alignSelf: 'center', borderRadius: 20, marginVertical: 15, marginTop: "7%" }, addPeopleBtn1: { backgroundColor: '#319E67', padding: 15, width: 150, borderRadius: 20, }, modal2: { height: "70%", width: "85%", borderRadius: 20, }, modalforCreateCompany: { height: "70%", width: "75%", borderRadius: 20, backgroundColor: '#EBEBEB', }, modalforCompanyshow: { height: 350, width: "75%", borderRadius: 20, backgroundColor: '#EBEBEB', }, dblModelContent: { paddingVertical: 20, }, dbblModalText: { fontWeight: 'bold', fontSize: 20, color: '#535353' }, modalForEditProfile: { height: "80%", width: "85%", borderRadius: 20, }, modelContent: { alignItems: 'center', marginBottom: 15, }, modal6: { height: 200, width: 300, borderRadius: 20, }, inputstyle: { width: 240, height: 40, backgroundColor: '#ddd', color: '#2c2930', paddingHorizontal: 10, alignSelf: 'center', borderRadius: 10, textAlign: 'center', marginVertical: 4, }, inputstylecom: { width: 100, height: 30, backgroundColor: '#ddd', color: '#2c2930', paddingHorizontal: 10, alignSelf: 'center', borderRadius: 10, textAlign: 'center', marginVertical: 8, }, modalforDept: { height: "40%", width: "83%", borderRadius: 20, }, }) <file_sep>/hr Office/HrApp/components/Screen/employees/EmpCreateScreenStyle.js import { StyleSheet,Platform } from 'react-native'; export const EmpCreateScreenStyle = StyleSheet.create({ HeaderContent: { justifyContent: 'space-between', backgroundColor: '#fff', flexDirection: 'row', padding: 10, borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderColor: '#fff', shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 10, height: -5 }, // elevation: 10, height: 60, }, createEmployeeLabel: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "left", color: "#848f98", marginBottom:5, marginLeft: 20, marginTop: 12 }, createEmpTextBox: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "left", color: "#4a535b", flex: 1, flexWrap: 'wrap', paddingHorizontal: 10, paddingVertical:7, borderRadius: 8, backgroundColor: "#f5f7fb", margin: 10,marginTop:3, }, ModalSelectorStyle: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, flex: 1, flexWrap: 'wrap', paddingHorizontal: 10, color: "#4a535b", paddingVertical:7, borderRadius: 8, backgroundColor: "#f5f7fb", margin: 10,marginTop:3, }, }); <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/Email.cs using System; using System.Collections.Generic; using System.Configuration; using System.Net; using System.Net.Mail; namespace TrillionBitsPortal.Common { public class Email { public string _Recipient; public string _Subject; public string _Body; public string _Sender; public string _SenderName; public List<string> _CcList; public Email(string senderName, string sender, string subject, string body, string recipient) { _SenderName = senderName; _Sender = sender; _Subject = subject; _Body = body; _Recipient = recipient; } public Email(string senderName, string sender, string subject, string body) { _SenderName = senderName; _Sender = sender; _Subject = subject; _Body = body; } public Email(string senderName, string sender, string subject, string body, string recipient, List<string> ccList) { _SenderName = senderName; _Sender = sender; _Subject = subject; _Body = body; _Recipient = recipient; _CcList = ccList; } public bool SendEmail(List<string> recipients, List<string> ccList, string senderPassword) { var mail = new MailMessage(); foreach (var recipient in recipients) { mail.To.Add(recipient); } mail.From = new MailAddress(_Sender, _SenderName); mail.IsBodyHtml = true; mail.Subject = _Subject; mail.Body = _Body; if (ccList != null) { foreach (var c in ccList) { mail.CC.Add(c); } } var smtp = new SmtpClient("smtp.gmail.com", 587) { UseDefaultCredentials = false, Credentials = new NetworkCredential(_Sender, senderPassword), EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network }; try { smtp.Send(mail); return true; } catch (Exception ex) { return false; } } public bool SendEmail(List<string> recipients,string senderPassword) { var mail = new MailMessage(); foreach (var recipient in recipients) { mail.To.Add(recipient); } mail.From = new MailAddress(_Sender, _SenderName); mail.IsBodyHtml = true; mail.Subject = _Subject; mail.Body = _Body; var smtp = new SmtpClient("smtp.gmail.com", 587) { UseDefaultCredentials = false, Credentials = new NetworkCredential(_Sender, senderPassword), EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network }; try { smtp.Send(mail); return true; } catch (Exception ex) { return false; } } } } <file_sep>/hr Office/HrApp/components/Screen/UserScreen/notice/Notice.js import React from 'react'; import { Platform, StatusBar, RefreshControl, TouchableOpacity, View, Text, FlatList, Image, ScrollView, ActivityIndicator, BackHandler, AsyncStorage } from 'react-native'; import { ActionConst, Actions } from 'react-native-router-flux'; import * as actions from '../../../../common/actions'; import { NoticeStyle } from './NoticeStyle'; import { getNotice } from '../../../../services/UserService/Notice'; import { SearchBar } from 'react-native-elements'; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar /> </View> ); } export default class Notice extends React.Component { constructor() { super(); this.state = { noticeList: [], companyId: 0 } this.arrayholder = []; } handleBackButton = () => { BackHandler.exitApp() return true; } goBack() { Actions.DailyAttendance(); } goToDetail(item) { actions.push("NoticeDetailUser", { aItem: item }); }; _onRefresh = async () => { this.setState({ refreshing: true }); setTimeout(function () { this.setState({ refreshing: false, }); }.bind(this), 2000); this.getNoticeList(this.state.companyId, false); }; async componentDidMount() { const cId = await AsyncStorage.getItem("companyId"); this.setState({ companyId: cId }); this.getNoticeList(cId, true); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } getNoticeList = async (companyId, isProgress) => { try { this.setState({ progressVisible: isProgress }); await getNotice(companyId) .then(res => { this.setState({ noticeList: res.result, progressVisible: false }); this.arrayholder = res.result; console.log(res.result, '.....noticeresult'); }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); } catch (error) { this.setState({ progressVisible: false }); console.log(error); } } searchFilterFunction = text => { this.setState({ value: text, }); const newData = this.arrayholder.filter(item => { const itemData = `${item.PostingDate.toUpperCase()} ${item.Details.toUpperCase()}`; const textData = text.toUpperCase(); return itemData.indexOf(textData) > -1; }); this.setState({ noticeList: newData, }); }; renderHeader = () => { return ( <SearchBar placeholder="Type Here..." style={{ position: 'absolute', zIndex: 1 }} lightTheme containerStyle={{ backgroundColor: '#f6f7f9', }} inputContainerStyle={{ backgroundColor: 'white', }} round onChangeText={text => this.searchFilterFunction(text)} autoCorrect={false} value={this.state.value} /> ); }; render() { return ( <View style={NoticeStyle.container}> <StatusBarPlaceHolder /> <View style={NoticeStyle.HeaderContent}> <View style={NoticeStyle.HeaderFirstView}> <TouchableOpacity style={NoticeStyle.HeaderMenuicon} onPress={() => { Actions.drawerOpen(); }}> <Image resizeMode="contain" style={NoticeStyle.HeaderMenuiconstyle} source={require('../../../../assets/images/menu_b.png')}> </Image> </TouchableOpacity> <View style={NoticeStyle.HeaderTextView}> <Text style={NoticeStyle.HeaderTextstyle}> NOTICE BOARD </Text> </View> </View> </View> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={NoticeStyle.loaderIndicator} />) : null} <ScrollView> <View style={{ flex: 1, margin: 10, }}> <FlatList refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> } data={this.state.noticeList} keyExtractor={(x, i) => i.toString()} ListHeaderComponent={this.renderHeader()} renderItem={({ item }) => <TouchableOpacity onPress={() => this.goToDetail(item)} > <View style={NoticeStyle.listContainer}> {item.ImageFileName === "" ? <View style={NoticeStyle.listDivider}> <View style={NoticeStyle.noticepart}> <Text style={{ fontFamily: 'OPENSANS_REGULAR'}}>{item.Details}</Text> </View> </View> : <View style={{ justifyContent: 'space-between', flexDirection: 'row', borderBottomColor: '#edeeef', borderBottomWidth: 1, paddingBottom: 10, }}> <View style={{ alignItems: 'flex-start', width: '80%', color: '#1a1a1a', fontSize: 10, fontFamily: 'OPENSANS_REGULAR' }}> <Text style={{}}>{item.Details}</Text> </View> <View style={{ alignItems: 'flex-end', width: '20%', }}> <View style={{ borderRadius: 5, }}> {item.ImageFileName !== "" ? <Image resizeMode="cover" style={NoticeStyle.noticelistImage} source={{ uri: "http://medilifesolutions.blob.core.windows.net/resourcetracker/" + item.ImageFileName }} /> : <Text></Text>} </View> </View> </View>} <View style={NoticeStyle.dateContainer}> <View style={{ alignItems: 'flex-start', }}> <Text style={NoticeStyle.postedtextStyle}> Posted Date </Text> </View> <View style={{ alignItems: 'flex-end', }}> <Text style={NoticeStyle.createDateStyle}> {item.CreateDate.substr(0, 10)} </Text> </View> </View> </View> </TouchableOpacity> } > </FlatList> </View> </ScrollView> </View> ); } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/PagerModel.cs using System; using System.Data; namespace TrillionBitsPortal.Common { public class FilterModel { public int? UserId { get; set; } public DateTime? startDate { get; set; } public DateTime? endDate { get; set; } public string StatusName { get; set; } public string TicketType { get; set; } public PagerModel PagerModel { get; set; } } public class PagerModel { public int PageSize { get; set; } public int PageNo { get; set; } public string OrderBy { get; set; } public string OrderByDirection { get; set; } public DataTable FilterModel { get; set; } } } <file_sep>/hr Office/HrApp/components/Screen/employees/CreateEmployeeScreen.js import React, { Component } from 'react'; import { ScrollView, Text, View, StatusBar, BackHandler, AsyncStorage, TextInput, TouchableOpacity, ToastAndroid, Platform, KeyboardAvoidingView, NetInfo, Image, Switch,Share } from 'react-native'; import { Actions } from 'react-native-router-flux'; import { Clipboard } from 'react-native'; import ModalSelector from 'react-native-modal-selector'; import Modal from 'react-native-modalbox'; import { CommonStyles } from '../../../common/CommonStyles'; import { EmpSetScreenStyle } from './EmpSetScreenStyle'; import { EmpCreateScreenStyle } from './EmpCreateScreenStyle'; import RadioButton from 'radio-button-react-native'; import { debounce } from 'lodash' import { GetDepartmentByCompanyId, CreateDepartment, } from "../../../services/DepartmentService"; import { CreateEmployee } from "../../../services/AccountService"; import { FontAwesome, Feather, MaterialCommunityIcons } from '@expo/vector-icons' import { loadFromStorage, storage, CurrentUserProfile } from "../../../common/storage"; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar /> </View> ); } const withPreventDoubleClick = (WrappedComponent) => { class PreventDoubleClick extends React.PureComponent { debouncedOnPress = () => { this.props.onPress && this.props.onPress(); } onPress = debounce(this.debouncedOnPress, 300, { leading: true, trailing: false }); render() { return <WrappedComponent {...this.props} onPress={this.onPress} />; } } PreventDoubleClick.displayName = `withPreventDoubleClick(${WrappedComponent.displayName ||WrappedComponent.name})` return PreventDoubleClick; } const ButtonEx = withPreventDoubleClick(TouchableOpacity); export default class CreateEmployeeScreen extends Component { constructor(props) { super(props); this.state = { userId: "", companyId: "", date: new Date(), departmentList: [], DeptName: '', DeptId: '', UserFullName: "", PhoneNumber: "", Designation: "", DepartmentId: "", Gender:'Male', value:'Male', Email: "", IsAutoCheckPoint: false, AutoCheckPointTime: "1:00:00", MaximumOfficeHours: '8:00:00', OfficeOutTime: '00:30:00', Employee: { UserName: '', Password: '', DepartmentId: '', }, } // preserve the initial state in a new object this.baseState = this.state } async componentDidMount() { const uId = await AsyncStorage.getItem("userId"); const cId = await AsyncStorage.getItem("companyId"); this.setState({ userId: uId, companyId: cId }); this.getDepartment(cId); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } resetForm = () => { this.setState(this.baseState) } handleOnPress(value) { this.setState({ value: value }) } goBack() { Actions.pop(); } toggleSwitch = value => { this.setState({ IsAutoCheckPoint: value }); }; toggleIsActiveSwitch = value => { this.setState({ IsActive: value }); }; async onFetchDepartmentRecords() { console.log("trying Department create.."); try { let Departmentodel = { DepartmentName: this.state.Dept.DepartmentName, CompanyId: this.state.companyId, }; if (this.state.companyId == "") { ToastAndroid.show("At first create a company.", ToastAndroid.SHORT); return; } console.log(Departmentodel, '..depttest'); let response = await CreateDepartment(Departmentodel); if (response && response.isSuccess) { console.log('com', response); alert("Department created successully"); this.state.departmentList.push({ key: response.result.Id, label: response.result.DepartmentName }) const depList = []; Object.assign(depList, this.state.departmentList); console.log('tttt', depList); this.setState( { departmentList: depList } ) console.log('dept', this.state.departmentList) this.setState({ DepartmentId: this.state.departmentList[0].Value }); this.setState({ PickerSelectedVal: this.state.departmentList[0].Value }); console.log('deptlist', this.state.departmentList); } else { alert("error"); } } catch (errors) { console.log(errors); } } getUniqueUserName = async () => { const newUser = this.state.PhoneNumber; console.log(newUser); this.setState(Object.assign(this.state.Employee, { UserName: newUser })); } onShare = async (username, password) => { try { const result = await Share.share({ message: "UserName: " + username + " Password: " + <PASSWORD> }); if (result.action === Share.sharedAction) { if (result.activityType) { Actions.EmployeeSetupScreen(); } else { } } else if (result.action === Share.dismissedAction) { Actions.EmployeeSetupScreen(); } } catch (error) { alert(error.message); } }; copyToClicpBord = (username, password) => { this.setState({ CopyUsername: username }); this.setState({ CopyPassword: <PASSWORD> }); Clipboard.setString("UserName: " + username + " Password: " + password); ToastAndroid.show('Text copied to clipboard', ToastAndroid.SHORT); setTimeout( () => { this.openModalforusername(); }, 100, ); this.onShare(username, password); } openModalforusername() { this.refs.modalforusername.open() } async saveEmployee() { let data = { UserFullName: this.state.UserFullName, PhoneNumber: this.state.PhoneNumber, UserType: 7, Designation: this.state.Designation, DepartmentId: this.state.Employee.DepartmentId, CompanyId: this.state.companyId, Gender: this.state.value, Email: this.state.Email, IsAutoCheckPoint: this.state.IsAutoCheckPoint, AutoCheckPointTime: this.state.AutoCheckPointTime, MaximumOfficeHours: this.state.MaximumOfficeHours, OfficeOutTime: this.state.OfficeOutTime, IsActive: this.state.IsActive }; try { let response = await CreateEmployee(data) this.setState({ successMessage: response.result.Message }); if (response && response.result.Success) { this.resetForm(); this.openModalforusername(); } else { ToastAndroid.show(response.result.Message, ToastAndroid.TOP); } } catch (errors) { console.log(errors); } } getDepartment = async (companyId) => { try { await GetDepartmentByCompanyId(companyId) .then(res => { console.log('comlen', res.result); if (res.result !== null) { console.log('comlen2', res.result); if (res.result.length > 0) { const depList = []; res.result.forEach(function (item) { const ob = { // 'Text': item.DepartmentName, // 'Value': item.Id 'key': item.Id, 'label': item.DepartmentName, } depList.push(ob); }); this.setState( { departmentList: depList } ) console.log(this.state.departmentList, 'testcall') } } else { this.setState( { departmentList: [] }) } }) .catch(() => { console.log("error occured"); }); } catch (error) { console.log(error); } } handleBackButton = () => { this.goBack(); return true; } openModalForDeptSelection() { this.refs.ModalForDeptSelection.open(); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } closeSuccessModal(){ this.refs.modalforusername.close(); Actions.EmployeeSetupScreen(); } openModaladdPeople() { if (this.state.UserFullName == "") { ToastAndroid.show('Employee Name can not be empaty', ToastAndroid.SHORT); } else if (this.state.Designation == "") { ToastAndroid.show('Employee Designation can not be empaty', ToastAndroid.SHORT); } else if (this.state.PhoneNumber == "") { ToastAndroid.show('Employee PhoneNumber can not be empaty', ToastAndroid.SHORT); } else if (this.state.Email == "") { ToastAndroid.show('Employee Email can not be empaty', ToastAndroid.SHORT); } else if (this.state.Employee.DepartmentId == "") { ToastAndroid.show('Please Select Department', ToastAndroid.SHORT); } else { this.getUniqueUserName(); this.saveEmployee(); } } render() { return ( <View style={{ flex: 1, backgroundColor: '#ffffff', flexDirection: 'column', }}> <StatusBarPlaceHolder /> <View style={CommonStyles.HeaderContent}> <View style={CommonStyles.HeaderFirstView}> <TouchableOpacity style={CommonStyles.HeaderMenuicon} onPress={() => { this.goBack() }}> <Image resizeMode="contain" style={CommonStyles.HeaderMenuiconstyle} source={require('../../../assets/images/left_arrow.png')}> </Image> </TouchableOpacity> <View style={CommonStyles.HeaderTextView}> <Text style={CommonStyles.HeaderTextstyle}> Create Employee </Text> </View> </View> <View style={CommonStyles.createTaskButtonContainer}> <ButtonEx disabled={this.state.touchabledisableForsaveExpense} onPress={() => this.openModaladdPeople()} style={CommonStyles.createTaskButtonTouch}> <View style={CommonStyles.plusButton}> <MaterialCommunityIcons name="content-save" size={17.5} color="#ffffff" /> </View> <View style={CommonStyles.ApplyTextButton}> <Text style={CommonStyles.ApplyButtonText}> POST </Text> </View> </ButtonEx> </View> </View> <KeyboardAvoidingView behavior="padding" enabled style={{ flex: 1, }}> <ScrollView showsVerticalScrollIndicator={false} keyboardDismissMode="on-drag" style={{ flex: 1, }}> <View> <Text style={EmpCreateScreenStyle.createEmployeeLabel}> Employee Name: </Text> <TextInput style={EmpCreateScreenStyle.createEmpTextBox} placeholder="Write employee name" placeholderTextColor="#dee1e5" returnKeyType="next" autoCorrect={false} value={this.state.UserFullName} ref={"txtDesignation"} autoCapitalize="none" onChangeText={(text) => this.setState({ UserFullName: text })} onSubmitEditing={() => this.txtDesignation.focus()} ref={input => { this.textname = input }} > </TextInput> </View> <View> <Text style={EmpCreateScreenStyle.createEmployeeLabel}> Designation: </Text> <TextInput style={EmpCreateScreenStyle.createEmpTextBox} placeholder="Designation" placeholderTextColor="#dee1e5" returnKeyType="next" autoCorrect={false} value={this.state.Designation} ref={"txtDesignation"} onChangeText={(text) => this.setState({ Designation: text })} onSubmitEditing={() => this.textmobile.focus()} ref={input => { this.txtDesignation = input }} > </TextInput> </View> <View> <Text style={EmpCreateScreenStyle.createEmployeeLabel}> Department: </Text> <View style={{ flexDirection: "row" }}> <View style={{ width: "90%" }}> <ModalSelector style={EmpCreateScreenStyle.ModalSelectorStyle} data={this.state.departmentList} initValue="Select Department" onChange={(option) => { const newUser = option.key this.setState(Object.assign(this.state.Employee, { DepartmentId: newUser })); }} /> </View> </View> </View> <View> <Text style={EmpCreateScreenStyle.createEmployeeLabel}> Mobile Number: </Text> <TextInput style={EmpCreateScreenStyle.createEmpTextBox} placeholder="Mobile Number" placeholderTextColor="#cbcbcb" keyboardType="number-pad" returnKeyType="go" autoCorrect={false} value={this.state.PhoneNumber} onSubmitEditing={() => this.textmail.focus()} onChangeText={(text) => this.setState({ PhoneNumber: text })} ref={input => { this.textmobile = input }} /> </View> <View> <Text style={EmpCreateScreenStyle.createEmployeeLabel}> Email: </Text> <TextInput style={EmpCreateScreenStyle.createEmpTextBox} placeholder="Email" placeholderTextColor="#cbcbcb" returnKeyType="go" autoCorrect={false} value={this.state.Email} onChangeText={(text) => this.setState({ Email: text })} ref={input => { this.textmail = input }} /> </View> <View style={EmpSetScreenStyle.RadioBtnView}> <RadioButton innerCircleColor='green' currentValue={this.state.value} value={"Male"} onPress={this.handleOnPress.bind(this)}> <Text style={EmpSetScreenStyle.RadioBtnFirst}> Male </Text> </RadioButton> <RadioButton innerCircleColor='green' currentValue={this.state.value} value={"Female"} onPress={this.handleOnPress.bind(this)}> <Text style={EmpSetScreenStyle.RadioBtnFirst}> Female </Text> </RadioButton> <RadioButton innerCircleColor='green' currentValue={this.state.value} value={"Other"} onPress={this.handleOnPress.bind(this)}> <Text style={EmpSetScreenStyle.RadioBtnLast}> Other </Text> </RadioButton> </View> <View style={EmpSetScreenStyle.ModalAddEmpLastRow}> <View style={EmpSetScreenStyle.AutoCheckRow}> <Text style={EmpSetScreenStyle.AutoCheckText}> Auto Check Point </Text> </View> <View style={[ (Platform.OS === 'android') ? (EmpSetScreenStyle.CheckpointSliderViewAndroid) : (EmpSetScreenStyle.CheckpointSliderViewIos) ]}> <Text style={[ (Platform.OS === 'android') ? (EmpSetScreenStyle.CheckpointSliderAndroidText) : (EmpSetScreenStyle.CheckpointSliderIosText) ]}> {this.state.IsAutoCheckPoint ? 'ON' : 'OFF'} </Text> <Switch onValueChange={this.toggleSwitch} value={this.state.IsAutoCheckPoint} /> </View> </View> <View style={{ alignSelf: 'center', justifyContent: 'flex-end', marginBottom: 20, }}> </View> </ScrollView> </KeyboardAvoidingView> <Modal style={[EmpSetScreenStyle.modal2]} position={"center"} ref={"modalforusername"} isDisabled={this.state.isDisabled} onClosed={() => this.setState({ floatButtonHide: !this.state.floatButtonHide })} backdropPressToClose={false} onOpened={() => this.setState({ floatButtonHide: true })} onClosed={() => this.setState({ floatButtonHide: false })}> <View style={EmpSetScreenStyle.modalUserFirstView}> <View style={{ alignItems: "flex-start" }}></View> <View style={{ alignItems: "flex-end" }}> <TouchableOpacity onPress={() => closeSuccessModal} style={EmpSetScreenStyle.modalUserTuachableOpacity}> <Image resizeMode="contain" style={{ width: 15, height: 15, marginRight: 17, marginTop: 15 }} source={require('../../../assets/images/close.png')}> </Image> </TouchableOpacity> </View> </View> <View style={EmpSetScreenStyle.modelContent}> <Text style={{ fontWeight: 'bold', fontSize: 25 }}> SUCCESSFUL </Text> <View style={EmpSetScreenStyle.horizontalLine} /> <Image resizeMode="contain" style={EmpSetScreenStyle.addPeopleImg} source={require('../../../assets/images/successful.png')}> </Image> </View> <View style={EmpSetScreenStyle.modalUserTextvaluecontainer}> <Text style={{ color: '#757575', paddingVertical: 10, textAlign: 'center' }}> Your employee added successfully send this info to log into employee's account.Mail already sent to employee. </Text> <Text style={EmpSetScreenStyle.modalUserUserName}> USERNAME </Text> <Text style={EmpSetScreenStyle.modalUserUservalue}> {this.state.UserName} </Text> <Text style={EmpSetScreenStyle.modalUserGeneratedPass}> GENERATED PASSWORD </Text> <Text style={EmpSetScreenStyle.modalUserGenratedpassvalue}> {this.state.successMessage} </Text> </View> <TouchableOpacity style={EmpSetScreenStyle.addCopyBtn} onPress={() => this.copyToClicpBord(this.state.UserName, this.state.successMessage)} > <Text style={EmpSetScreenStyle.testCopy}>Copy</Text> </TouchableOpacity> </Modal> </View> ) } } <file_sep>/hr Office/HrApp/components/Screen/UserScreen/leaves/LeaveList.js import React, { Component } from 'react'; import { Platform, StatusBar, Dimensions, RefreshControl, TouchableOpacity, View, Text, FlatList, Image, ScrollView, ActivityIndicator, AsyncStorage, BackHandler, Alert, } from 'react-native'; import { DailyAttendanceCombo, MyPanelCombo, MyTaskCombo, LeaveListCombo, BillsCombo, ExpensesCombo, NoticeCombo, drawerSelectedOption } from '../../../MenuDrawer/DrawerContent'; import FontAwesome from 'react-native-vector-icons/FontAwesome' import { Actions } from 'react-native-router-flux'; import { GetLeaveList } from '../../../../services/UserService/Leave'; import { LeaveListStyle } from './LeaveListStyle'; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; export default class LeaveList extends React.Component { constructor(props) { super(props); this.state = { leaveList: [], progressVisible: true, refreshing: false, userId: "", // selectedId: '', } } _onRefresh = async () => { this.setState({ refreshing: true }); setTimeout(function () { this.setState({ refreshing: false, }); }.bind(this), 2000); this.getLeaveList(this.state.userId, false); }; goBack() { DailyAttendanceCombo(); } async componentDidMount() { global.DrawerContentId = 4; const uId = await AsyncStorage.getItem("userId"); this.setState({ userId: uId }); this.getLeaveList(uId, true); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } handleBackButton = () => { BackHandler.exitApp() return true; } getLeaveList = async (userId, isProgress) => { try { this.setState({ progressVisible: isProgress }); await GetLeaveList(userId) .then(res => { this.setState({ leaveList: res.result, progressVisible: false }); }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); } catch (error) { this.setState({ progressVisible: false }); console.log(error); } } render() { var { width, height } = Dimensions.get('window'); return ( <View style={LeaveListStyle.container}> <View style={LeaveListStyle.HeaderContent}> <View style={LeaveListStyle.HeaderFirstView}> <TouchableOpacity style={LeaveListStyle.HeaderMenuicon} onPress={() => { Actions.drawerOpen(); }}> <Image resizeMode="contain" style={LeaveListStyle.HeaderMenuiconstyle} source={require('../../../../assets/images/menu_b.png')}> </Image> </TouchableOpacity> <View style={LeaveListStyle.HeaderTextView}> <Text style={LeaveListStyle.HeaderTextstyle}> LEAVE LIST </Text> </View> </View> <View style={LeaveListStyle.ApplyButtonContainer}> <TouchableOpacity onPress={() => Actions.LeaveApply()} style={LeaveListStyle.ApplyButtonTouch}> <View style={LeaveListStyle.plusButton}> <FontAwesome name="plus" size={18} color="#ffffff"> </FontAwesome> </View> <View style={LeaveListStyle.ApplyTextButton}> <Text style={LeaveListStyle.ApplyButtonText}> LEAVE </Text> </View> </TouchableOpacity> </View> </View> <View style={{ flex: 1,marginTop:5, }}> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={LeaveListStyle.loaderIndicator} />) : null} <ScrollView showsVerticalScrollIndicator={false}> <View style={{ flex: 1, // padding: 10, }}> <FlatList refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> } data={this.state.leaveList} keyExtractor={(x, i) => i.toString()} renderItem={({ item }) => <View style={LeaveListStyle.listContainer} > <View style={LeaveListStyle.listInnerContainer}> <Text style={LeaveListStyle.leaveType}> Cause: </Text> <Text style={LeaveListStyle.leaveFrom}> From: </Text> </View> <View style={LeaveListStyle.leaveReasonContainer}> <Text style={[LeaveListStyle.leaveReasonText, { fontFamily: 'Montserrat_SemiBold' }]}> {item.LeaveReason} </Text> <Text style={LeaveListStyle.reasonFromDate}> {item.FromDateVw} </Text> </View> <View style={LeaveListStyle.causeContainer}> <Text style={LeaveListStyle.causeText}> Leave Type: </Text> <Text style={LeaveListStyle.leaveToText}> To: </Text> </View> <View style={LeaveListStyle.detailsContainer}> <Text style={LeaveListStyle.reasonFromDate}> {item.LeaveType} </Text> <Text style={LeaveListStyle.detailsTextInner}> {item.ToDateVw} </Text> </View> {(item.ApprovedBy != null && item.ApprovedBy != '') ? <View style={LeaveListStyle.approvedByContainer}> <Text style={LeaveListStyle.approvedByText}> Approved By: {item.ApprovedBy} </Text> <Text style={LeaveListStyle.approvedAtText}> Approved At: {item.ApprovedAtVw} </Text> </View> : null} <View style={LeaveListStyle.statusButton}> <View style={LeaveListStyle.statusButtonInner}> {item.IsApproved == true ? (<Text style={{ color: 'green', }}> Approved </Text>) : (item.IsRejected == true ? (<Text style={{ color: 'red', }}> Rejected </Text>) : (<Text style={{ color: '#f1b847', }}> Pending </Text>))} </View> <View style={LeaveListStyle.daysBox}> <Text style={LeaveListStyle.statusDate}> {item.LeaveInDays} Days </Text> </View> </View> </View> } /> </View> </ScrollView> </View> </View> ); } } <file_sep>/hr Office/HrApp/components/Screen/UserScreen/attendance/DailyAttendance.js import React, { Component } from 'react'; import { FlatList, Text, View, Image, StatusBar, TouchableOpacity, Platform, RefreshControl, AsyncStorage, BackHandler } from 'react-native'; import { Actions } from 'react-native-router-flux'; import AntDesign from 'react-native-vector-icons/AntDesign' import { DailyAttendanceStyle } from './DailyAttendanceStyle'; import{GetAttendanceFeed} from '../../../../services/UserService/EmployeeTrackService' import { MyPanelCombo } from '../../../MenuDrawer/DrawerContent'; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar/> </View> ); } export default class DailyAttendances extends Component { constructor(props) { super(props); this.state = { employeeList: [], employeeDetail: {}, statusCount: { TotalEmployee: 0, TotalCheckIn: 0, TotalCheckOut: 0 }, refreshing: false, selectedId: 1, displayAbleEmployeeList: [], CompanyId: 0, UserId: 0, } } handleBackButton = () => { BackHandler.exitApp() return true; } _onRefresh = async () => { this.setState({ refreshing: true, selectedId: 1 }) setTimeout(function () { this.setState({ refreshing: false, }); }.bind(this), 2000); this.getAttendanceFeed(this.state.CompanyId); } setSelectedOption = (id) => { this.setState({ selectedId: id }); switch (id) { case 1: //All this.setState({ displayAbleEmployeeList: this.state.employeeList }); break; case 2: //checked in this.setState({ displayAbleEmployeeList: this.state.employeeList.filter(x => x.IsCheckedIn) }); break; case 3: //not attend this.setState({ displayAbleEmployeeList: this.state.employeeList.filter(x => x.NotAttend) }); break; case 3: //not attend this.setState({ displayAbleEmployeeList: this.state.employeeList.filter(x => x.NotAttend) }); break; } }; async componentDidMount() { global.DrawerContentId = 1; const UserId = await AsyncStorage.getItem("userId"); const cId = await AsyncStorage.getItem("companyId"); this.setState({ UserId: UserId, CompanyId: cId }); console.log("UserId", this.state.cId); this.getAttendanceFeed(cId); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } getAttendanceFeed = async (cId) => { await GetAttendanceFeed(cId) .then(res => { this.setState({ employeeList: res.result.EmployeeList.filter(x => x.UserId != this.state.UserId), displayAbleEmployeeList: res.result.EmployeeList, statusCount: res.result.StatusCount, employeeDetail: res.result.EmployeeList .filter(x => x.UserId === this.state.UserId)[0] }); console.log(res.result.EmployeeList, "employeeDetail...."); }).catch(() => { console.log("error occured"); }); } renderStatusList() { return ( <View style={DailyAttendanceStyle.countBoxContainer}> <TouchableOpacity onPress={() => this.setSelectedOption(1)}> <View style={DailyAttendanceStyle.countBoxColumn1}> <Text style={this.state.selectedId == 1 ? DailyAttendanceStyle.countBoxColumn1NumberActive : DailyAttendanceStyle.countBoxColumn1NumberInactive}> {this.state.statusCount.TotalEmployee} </Text> <Text style={this.state.selectedId == 1 ? DailyAttendanceStyle.countBoxColumn1LabelActive : DailyAttendanceStyle.countBoxColumn1LabelInactive}> TOTAL </Text> </View> </TouchableOpacity> <TouchableOpacity onPress={() => this.setSelectedOption(2)}> <View style={DailyAttendanceStyle.countBoxColumn2}> <Text style={ this.state.selectedId == 2 ? DailyAttendanceStyle.countBoxColumn2NumberActive : DailyAttendanceStyle.countBoxColumn2NumberInactive}> {this.state.statusCount.TotalCheckIn} </Text> <Text style={ this.state.selectedId == 2 ? DailyAttendanceStyle.countBoxColumn2LabelActive : DailyAttendanceStyle.countBoxColumn2LabelInactive}> CHECKED IN </Text> </View> </TouchableOpacity> <TouchableOpacity onPress={() => this.setSelectedOption(3)}> <View style={DailyAttendanceStyle.countBoxColumn3}> <Text style={ this.state.selectedId == 3 ? DailyAttendanceStyle.countBoxColumn3NumberActive : DailyAttendanceStyle.countBoxColumn3NumberInactive } > {this.state.statusCount.TotalNotAttend} </Text> <Text style={ this.state.selectedId == 3 ? DailyAttendanceStyle.countBoxColumn3LabelActive : DailyAttendanceStyle.countBoxColumn3LabelInactive} > Not Attend </Text> </View> </TouchableOpacity> </View> ); } render() { return ( <View style={DailyAttendanceStyle.container}> <StatusBarPlaceHolder /> <View style={DailyAttendanceStyle.HeaderContent}> <View style={DailyAttendanceStyle.HeaderFirstView}> <TouchableOpacity style={DailyAttendanceStyle.HeaderMenuicon} onPress={() => { Actions.drawerOpen(); }}> <Image resizeMode="contain" style={DailyAttendanceStyle.HeaderMenuiconstyle} // source={require('../../../../assets/images/menu_b.png')} source={require('../../../../assets/images/menu_b.png')} > </Image> </TouchableOpacity> <View style={DailyAttendanceStyle.HeaderTextView}> <Text style={DailyAttendanceStyle.HeaderTextstyle}> TODAY'S FEED </Text> </View> </View> </View> <View style={[ DailyAttendanceStyle.FlatListTouchableOpacity, style = { padding: 10, height: 100, // paddingVertical: 20, backgroundColor: "#f8f9fb" } ]}> <View style={ DailyAttendanceStyle.FlatListLeft }> <View style={{ paddingRight: 10, }}> {this.state.employeeDetail.ImageFileName !== "" ? ( <Image resizeMode='cover' style={ DailyAttendanceStyle.ImageLocal } source={{ uri: "http://medilifesolutions.blob.core.windows.net/resourcetracker/" + this.state.employeeDetail.ImageFileName }} />) : (<Image style={ DailyAttendanceStyle.ImagestyleFromServer } resizeMode='contain' source={require('../../../../assets/images/employee.png')} />)} {this.state.employeeDetail.IsCheckedOut ? (<Image resizeMode="contain" style={DailyAttendanceStyle.styleForonlineOfflineIcon} source={require('../../../../assets/images/icon_gray.png')} />) : (this.state.employeeDetail.IsCheckedIn ? (<Image style={DailyAttendanceStyle.styleForonlineOfflineIcon } resizeMode='contain' source={require('../../../../assets/images/icon_green.png')} />) : (<Image style={ DailyAttendanceStyle.styleForonlineOfflineIcon } resizeMode='contain' source={require('../../../../assets/images/icon_gray.png')} />)) } </View> <View style={DailyAttendanceStyle.RightTextView}> <Text style={ DailyAttendanceStyle.NameText } > {this.state.employeeDetail.EmployeeName} </Text> <Text style={ DailyAttendanceStyle.DesignationText } > {this.state.employeeDetail.Designation} </Text> <Text style={ DailyAttendanceStyle.DepartmentText } > {this.state.employeeDetail.DepartmentName} </Text> </View> </View> <View style={DailyAttendanceStyle.TimeContainer}> <TouchableOpacity onPress={() => Actions.MyPanel()}> <Image resizeMode="contain" style={{ width: 67, height: 56 }} source={require('../../../../assets/images/panelb.png')}> </Image> </TouchableOpacity> </View> </View> {/* <View style={ DailyAttendanceStyle.ListContainer }> {this.renderStatusList()} </View> */} <View style={ DailyAttendanceStyle.FlatListContainer }> <FlatList refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> } data={this.state.employeeList} keyExtractor={(x, i) => i.toString()} renderItem= {({ item }) => <View style={ DailyAttendanceStyle.FlatListTouchableOpacity }> <View style={ DailyAttendanceStyle.FlatListLeft }> <View style={{ paddingRight: 10, }}> {item.ImageFileName !== "" ? <Image resizeMode='cover' style={ DailyAttendanceStyle.ImageLocal } source={{ uri: "http://medilifesolutions.blob.core.windows.net/resourcetracker/" + item.ImageFileName }} /> : <Image style={ DailyAttendanceStyle.ImagestyleFromServer } resizeMode='contain' source={require('../../../../assets/images/employee.png')} />} {item.IsCheckedOut ? (<Image resizeMode="contain" style={DailyAttendanceStyle.styleForonlineOfflineIcon} source={require('../../../../assets/images/icon_gray.png')} />) : (item.IsCheckedIn ? (<Image style={DailyAttendanceStyle.styleForonlineOfflineIcon } resizeMode='contain' source={require('../../../../assets/images/icon_green.png')} />) : (<Image style={ DailyAttendanceStyle.styleForonlineOfflineIcon } resizeMode='contain' source={require('../../../../assets/images/icon_gray.png')} />)) } </View> <View style={DailyAttendanceStyle.RightTextView}> <Text style={ DailyAttendanceStyle.NameText } > {item.EmployeeName} </Text> <Text style={ DailyAttendanceStyle.DesignationText } > {item.Designation} </Text> <Text style={ DailyAttendanceStyle.DepartmentText } > {item.DepartmentName} </Text> </View> </View> <View style={DailyAttendanceStyle.TimeContainer}> <View style={ DailyAttendanceStyle.TimeContent }> <Text style={ DailyAttendanceStyle.CheckintimeStyle }> {item.CheckInTimeVw !== "" ? (<AntDesign name="arrowdown" size={10} color="#07c15d" style={DailyAttendanceStyle.AntDesignstyle}> </AntDesign>) : ("")} </Text> <Text style={ DailyAttendanceStyle.CheckinTimeText }> {item.CheckInTimeVw !== "" ? item.CheckInTimeVw : ("")}</Text> </View> <View style={ DailyAttendanceStyle.CheckOutTimeView }> <Text style={ DailyAttendanceStyle.CheckOutTimetext }> {item.IsCheckedOut ? (<AntDesign name="arrowup" size={10} color="#a1d3ff" style={ DailyAttendanceStyle.CheckOutTimeIconstyle }> </AntDesign>) : ("")} </Text> <Text style={ DailyAttendanceStyle.CheckOutTimeText }>{item.IsCheckedOut ? item.CheckOutTimeVw : ("")}</Text> </View> </View> </View> }> } </FlatList> </View> </View > ) } } <file_sep>/hr Office/HrApp/services/UserService/FinancialService.js import { postApi, getApi } from "../api"; export const SaveInvoice = async data => postApi("RtFinancialApi/SaveInvoice", {}, data); export const SaveBillCollection = async data => postApi("RtFinancialApi/SaveBillCollection", {}, data); export const GetInvoice = async (id) => getApi("RtFinancialApi/GetInvoice?id="+id, {}, {}); export const GetInvoiceList = async (userId) => getApi("RtFinancialApi/GetMyInvoiceList?userId="+userId, {}, {}); export const GetMyCollectedBills = async (userId) => getApi("RtFinancialApi/GetMyCollectedBills?userId="+userId, {}, {}); export const GetMyDepositedBills = async (userId) => getApi("RtFinancialApi/GetMyDepositedBills?userId="+userId, {}, {}); export const GetBillSummary = async (userId) => getApi("RtFinancialApi/GetBillSummary?userId="+userId, {}, {}); <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/DataAccess/EmployeeLeaveDataAccess.cs using TrillionBitsPortal.Common; using TrillionBitsPortal.Common.Models; using Microsoft.Practices.EnterpriseLibrary.Data; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using TrillionBits.DataAccess.Common; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Mappers; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.DataAccess { public class EmployeeLeaveDataAccess : BaseDatabaseHandler, IEmployeeLeave { public EmployeeLeaveDataAccess() { } public List<EmployeeLeaveModel> GetLeaveByCompanyId(string companyId) { string err = string.Empty; string sql = @"SELECT la.* ,uc.FullName as EmployeeName,AP.FullName ApprovedBy from ResourceTracker_LeaveApplication as la Left JOIN ResourceTracker_EmployeeUser eu on eu.id= la.EmployeeId Left JOIN UserCredentials uc on uc.id= eu.UserId LEFT JOIN UserCredentials AP ON LA.ApprovedById=AP.Id where la.CompanyId='" + companyId + "' order by la.Id desc"; var results = ExecuteDBQuery(sql, null, EmployeeLeaveMapper.ToEmployeeLeaveMapperModel); return results.Any() ? results : null; } public List<EmployeeLeaveModel> GetUserLeaves(string userId) { string err = string.Empty; string sql = @"SELECT la.* ,uc.FullName as EmployeeName,AP.FullName ApprovedBy from ResourceTracker_LeaveApplication as la Left JOIN ResourceTracker_EmployeeUser eu on eu.id= la.EmployeeId Left JOIN UserCredentials uc on uc.id= eu.UserId LEFT JOIN UserCredentials AP ON LA.ApprovedById=AP.Id where eu.UserId ='" + userId + "' order by la.Id desc"; var results = ExecuteDBQuery(sql, null, EmployeeLeaveMapper.ToEmployeeLeaveMapperModel); return results.Any() ? results : null; } public ResponseModel CreateEmployeeLeave(EmployeeLeaveModel model) { var errMessage = string.Empty; Database db = GetSQLDatabase(); var returnId = -1; using (DbConnection conn = db.CreateConnection()) { conn.Open(); DbTransaction trans = conn.BeginTransaction(); try { returnId = SaveEmployeeLeave(model, db, trans); trans.Commit(); } catch (Exception ex) { trans.Rollback(); errMessage = ex.Message; } } return new ResponseModel { Success = string.IsNullOrEmpty(errMessage), Message = errMessage }; } public int SaveEmployeeLeave(EmployeeLeaveModel model, Database db, DbTransaction trans) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CompanyId", ParamValue = model.CompanyId,DBType = DbType.Int32}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@userId", ParamValue = model.UserId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@FromDate", ParamValue = model.FromDate.ToString(Constants.ServerDateTimeFormat), DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ToDate", ParamValue = model.ToDate.ToString(Constants.ServerDateTimeFormat), DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@IsHalfDay", ParamValue =model.IsHalfDay, DBType=DbType.Boolean}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@LeaveTypeId", ParamValue =model.LeaveTypeId, DBType = DbType.Int32}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@LeaveReason", ParamValue = model.LeaveReason}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CreatedAt", ParamValue = Convert.ToDateTime(model.CreatedAt),DBType = DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@IsApproved", ParamValue = model.IsApproved, DBType=DbType.Boolean}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@IsRejected", ParamValue =model.IsRejected, DBType=DbType.Boolean}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@RejectReason", ParamValue =model.RejectReason}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ApprovedById", ParamValue =model.ApprovedById}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ApprovedAt", ParamValue =model.ApprovedAt, DBType = DbType.DateTime}, }; const string sql = @" DECLARE @employeeId INT SELECT TOP 1 @employeeId=U.Id FROM ResourceTracker_EmployeeUser U WHERE U.UserId=@userId INSERT INTO ResourceTracker_LeaveApplication (CompanyId ,EmployeeId ,FromDate ,ToDate ,IsHalfDay,LeaveTypeId ,LeaveReason,CreatedAt,IsApproved,IsRejected,RejectReason,ApprovedById,ApprovedAt) VALUES (@CompanyId ,@employeeId ,@FromDate ,@ToDate ,@IsHalfDay,@LeaveTypeId ,@LeaveReason,@CreatedAt,@IsApproved,@IsRejected,@RejectReason,@ApprovedById,@ApprovedAt)"; return DBExecCommandExTran(sql, queryParamList, trans, db, ref errMessage); } public List<EmployeeLeaveModel> GetLeaveById(int id) { string err = string.Empty; string sql = @"SELECT la.* ,uc.FullName as EmployeeName,AP.FullName ApprovedBy from ResourceTracker_LeaveApplication as la Left JOIN ResourceTracker_EmployeeUser eu on eu.id= la.EmployeeId Left JOIN UserCredentials uc on uc.id= eu.UserId LEFT JOIN UserCredentials AP ON LA.ApprovedById=AP.Id where la.Id ='" + id + "'"; var results = ExecuteDBQuery(sql, null, EmployeeLeaveMapper.ToEmployeeLeaveMapperModel); return results.Any() ? results : null; } public ResponseModel Approved(int id,string userId) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue =id}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ApprovedById", ParamValue =userId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ApprovedAt", ParamValue =DateTime.UtcNow,DBType=DbType.DateTime}, }; const string sql = @"UPDATE ResourceTracker_LeaveApplication SET IsApproved=1,ApprovedById=@ApprovedById,ApprovedAt=@ApprovedAt WHERE Id=@Id"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } public ResponseModel Rejected(int id) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue =id}, }; const string sql = @"UPDATE ResourceTracker_LeaveApplication SET IsRejected=1 WHERE Id=@Id"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage) }; } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/DbUtility/MappedDbType.cs using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.Common { public static class MappedDbType { private static Dictionary<Type, DbType> typeMap; public static DbType GetDbType(Type appType) { if (MappedDbType.typeMap.IsNull()) { MappedDbType.InitializeDbType(); } DbType item = MappedDbType.typeMap[appType]; if (!item.IsNull()) { return item; } return DbType.AnsiString; } private static void InitializeDbType() { Dictionary<Type, DbType> types = new Dictionary<Type, DbType>(); types[typeof(DBNull)] = DbType.AnsiString; types[typeof(byte)] = DbType.Byte; types[typeof(sbyte)] = DbType.SByte; types[typeof(short)] = DbType.Int16; types[typeof(ushort)] = DbType.UInt16; types[typeof(int)] = DbType.Int32; types[typeof(uint)] = DbType.UInt32; types[typeof(long)] = DbType.Int64; types[typeof(ulong)] = DbType.UInt64; types[typeof(float)] = DbType.Single; types[typeof(double)] = DbType.Double; types[typeof(decimal)] = DbType.Decimal; types[typeof(bool)] = DbType.Boolean; types[typeof(string)] = DbType.AnsiString; types[typeof(char)] = DbType.StringFixedLength; types[typeof(Guid)] = DbType.Guid; types[typeof(DateTime)] = DbType.DateTime; types[typeof(DateTimeOffset)] = DbType.DateTimeOffset; types[typeof(byte[])] = DbType.Binary; types[typeof(byte?)] = DbType.Byte; types[typeof(sbyte?)] = DbType.SByte; types[typeof(short?)] = DbType.Int16; types[typeof(ushort?)] = DbType.UInt16; types[typeof(int?)] = DbType.Int32; types[typeof(uint?)] = DbType.UInt32; types[typeof(long?)] = DbType.Int64; types[typeof(ulong?)] = DbType.UInt64; types[typeof(float?)] = DbType.Single; types[typeof(double?)] = DbType.Double; types[typeof(decimal?)] = DbType.Decimal; types[typeof(bool?)] = DbType.Boolean; types[typeof(char?)] = DbType.StringFixedLength; types[typeof(Guid?)] = DbType.Guid; types[typeof(DateTime?)] = DbType.DateTime; types[typeof(DateTimeOffset?)] = DbType.DateTimeOffset; MappedDbType.typeMap = types; } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/DbUtility/ModelState.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.Common { [Flags] public enum ModelState { Added = 1, Modified = 2, Deleted = 3, Unchanged = 4, Detached = 5 } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/DbUtility/CustomException.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.Common { public class CustomException : Exception { public ErrorLog ErrorInfo { get; set; } //public override string Message //{ // get // { // if (base.InnerException is DbUpdateConcurrencyException) // { // throw new Exception(); // } // DbUpdateException innerException = base.InnerException as DbUpdateException; // DbUpdateException dbUpdateException = innerException; // if (innerException != null && dbUpdateException != null && dbUpdateException.InnerException != null && dbUpdateException.InnerException.InnerException != null) // { // return (dbUpdateException.InnerException.InnerException as SqlException).Message; // } // DbEntityValidationException dbEntityValidationException = base.InnerException as DbEntityValidationException; // DbEntityValidationException dbEntityValidationException1 = dbEntityValidationException; // if (dbEntityValidationException == null) // { // return base.Message; // } // StringBuilder stringBuilder = new StringBuilder(); // stringBuilder.AppendLine(); // stringBuilder.AppendLine(); // foreach (DbEntityValidationResult entityValidationError in dbEntityValidationException1.EntityValidationErrors) // { // stringBuilder.AppendLine(string.Format("- Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", entityValidationError.Entry.Entity.GetType().FullName, entityValidationError.Entry.State)); // foreach (DbValidationError validationError in entityValidationError.ValidationErrors) // { // stringBuilder.AppendLine(string.Format("-- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"", validationError.PropertyName, entityValidationError.Entry.CurrentValues.GetValue<object>(validationError.PropertyName), validationError.ErrorMessage)); // } // } // stringBuilder.AppendLine(); // return stringBuilder.ToString(); // } //} public CustomException() { } public CustomException(string message, ErrorLog errorLog = default(ErrorLog)) : base(message) { this.ErrorInfo = errorLog; } public CustomException(string message, Exception cause, ErrorLog errorLog = default(ErrorLog)) : base(message, cause) { this.ErrorInfo = null; this.ErrorInfo = errorLog; } public CustomException(Exception cause) : base(null, cause) { this.ErrorInfo = null; } } } <file_sep>/hr Office/HrApp/AppNavigator.js import React, { Component } from 'react'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons' import { Image } from 'react-native'; import Login from './components/Login'; import Register from './components/Register'; import DailyAttendance from './components/Screen/attendance/DailyAttendance'; import DailyAttendances from './components/Screen/UserScreen/attendance/DailyAttendance'; import DailyAttendanceDetails from './components/Screen/attendance/DailyAttendanceDetails'; import UserSpecificTasks from './components/Screen/attendance/UserSpecificTasks'; import UserSpecificLeave from './components/Screen/attendance/UserSpecificLeave'; import { Router, Stack, Scene, Drawer, ActionConst, Tabs } from 'react-native-router-flux'; import DrawerContent from './components/MenuDrawer/DrawerContent'; import AuthLoadingScreen from './login/AuthLoadingScreen'; import SettingScreen from './components/Screen/setting/Setting'; import DepartmentSetupScreen from './components/Screen/department/DepartmentSetupScreen'; import EmployeeSetupScreen from './components/Screen/employees/EmployeeSetupScreen'; import CreateEmployeeScreen from './components/Screen/employees/CreateEmployeeScreen'; import CompanysetupScreen from './components/Screen/company/CompanysetupScreen'; import ReportScreen from './components/Screen/reports/ReportScreen'; import TaskListScreen from './components/Screen/tasks/TaskList'; import CompleteTaskFilter from './components/Screen/tasks/CompleteTaskFilter'; import TaskBoardScreen from './components/Screen/Board/TaskBoard'; import ViewTask from './components/Screen/tasks/ViewTask'; import CreateTask from './components/Screen/tasks/CreateTask'; import CreateTaskForBoard from './components/Screen/Board/CreateTaskForBoard'; import TaskBordDetail from './components/Screen/Board/TaskBordDetail'; import ViewBoardTask from './components/Screen/Board/ViewBoardTask'; import LeaveList from './components/Screen/leaves/LeaveList'; import LeaveListUser from './components/Screen/UserScreen/leaves/LeaveList'; import LeaveApply from './components/Screen/UserScreen/leaves/LeaveApply'; import CreateNotice from './components/Screen/notice/CreateNotice' import NoticeDetail from './components/Screen/notice/NoticeDetail' import Notice from './components/Screen/notice/Notice'; import NoticeUser from './components/Screen/UserScreen/notice/Notice'; import NoticeDetailUser from './components/Screen/UserScreen/notice/NoticeDetail'; import DetailScreen from './components/Screen/reports/DetailScreen'; import MyPanel from './components/Screen/UserScreen/myPanel/MyPanel'; import MyTask from './components/Screen/UserScreen/tasks/MyTask'; import CreateByMe from './components/Screen/UserScreen/tasks/CreateByMe'; import ViewAssignToMe from './components/Screen/UserScreen/tasks/ViewAssignToMe'; import LeaderBoardScreen from './components/Screen/leaderboard/LeaderBoardScreen'; export default class AppNavigator extends Component { render() { return ( <Router> <Stack key="root" hideNavBar={true}> <Scene key="auth" component={AuthLoadingScreen} hideNavBar={true} /> <Scene key="login" component={Login} title="Login" back={false} hideNavBar={true} /> <Scene key="register" component={Register} title="Register" hideNavBar={true} /> <Scene key="DrawerContent" component={DrawerContent} hideNavBar={true} /> <Drawer key="drawer" drawerImage={{ uri: null }} contentComponent={DrawerContent} type={ActionConst.RESET} hideDrawerButton={false} hideNavBar={true}> <Scene key="DailyAttendance" component={DailyAttendance} hideNavBar={true} /> <Scene key="DailyAttendances" component={DailyAttendances} hideNavBar={true} /> <Scene key="auth" component={AuthLoadingScreen} hideNavBar={true} /> <Scene key="SettingScreen" component={SettingScreen} hideNavBar={true} /> <Scene key="ReportScreen" component={ReportScreen} hideNavBar={true} /> <Scene key="TaskBoardScreen" component={TaskBoardScreen} hideNavBar={true} /> <Scene key="MyPanel" component={MyPanel} hideNavBar={true} /> <Scene key="LeaveList" component={LeaveList} hideNavBar={true} /> <Scene key="LeaveListUser" component={LeaveListUser} hideNavBar={true} /> <Scene key="LeaveApply" component={LeaveApply} hideNavBar={true} /> <Scene key="Notice" component={Notice} hideNavBar={true} /> <Scene key="CreateNotice" component={CreateNotice} hideNavBar={true} /> <Scene key="NoticeUser" component={NoticeUser} hideNavBar={true} /> <Scene key="LeaderBoard" component={LeaderBoardScreen} hideNavBar={true} /> <Tabs key="DetailsContainer" tabBarStyle={{ backgroundColor: '#FFFFFF', }} labelStyle={{ fontSize: 14, padding: 5 }} activeBackgroundColor="white" activeTintColor="#26065c" inactiveBackgroundColor=" #FFFFFF" inactiveTintColor="#9e9e9e" > <Scene key="DailyAttendanceDetails" title="Location" hideNavBar={true} icon={({ focused }) => ( focused ? <Image source={require('./assets/images/pin_s.png')} resizeMode='contain' style={{ height: 20, width: 20, marginTop: 15 }}></Image> : <Image source={require('./assets/images/pin.png')} resizeMode='contain' style={{ height: 20, width: 20, marginTop: 15 }}></Image> )}> <Scene key="DailyAttendanceDetails" component={DailyAttendanceDetails} title="Location" initial /> </Scene> <Scene key="UserSpecificTasks" title="Tasks" hideNavBar={true} icon={({ focused }) => ( focused ? <Image source={require('./assets/images/list_s.png')} resizeMode='contain' style={{ height: 20, width: 20, marginBottom: 5, marginTop: 15, }}></Image> : <Image source={require('./assets/images/list_a.png')} resizeMode='contain' style={{ height: 20, width: 20, marginBottom: 5, marginTop: 15, }}></Image> )}> <Scene key="UserSpecificTasks" component={UserSpecificTasks} title="Tasks" initial /> </Scene> <Scene key="UserSpecificLeave" title="Leave" hideNavBar={true} icon={({ focused }) => ( focused ? <Image source={require('./assets/images/briefcase_s.png')} resizeMode='contain' style={{ height: 20, width: 20, marginBottom: 5, marginTop: 15, }}></Image> : <Image source={require('./assets/images/briefcase.png')} resizeMode='contain' style={{ height: 20, width: 20, marginBottom: 5, marginTop: 15, }}></Image> )}> <Scene key="UserSpecificLeave" component={UserSpecificLeave} title="Leave" initial /> </Scene> </Tabs> <Tabs key="TabnavigationInTasks" tabs={true} tabBarStyle={{ backgroundColor: '#FFFFFF', }} tabStyle={{ flexDirection: 'row', }} labelStyle={{ fontSize: 14, marginTop: 12, marginRight: 60, }} activeBackgroundColor="white" activeTintColor="#26065c" inactiveBackgroundColor=" #FFFFFF" inactiveTintColor="#9e9e9e" > <Scene key="TaskListScreen" title="Pending" hideNavBar={true} icon={({ focused }) => ( focused ? <Image source={require('./assets/images/list_s.png')} style={{ height: 20, width: 20, marginTop: 15, marginLeft: 25, }} resizeMode="contain"></Image> : <Image source={require('./assets/images/list_a.png')} style={{ height: 20, width: 20, marginTop: 15, marginLeft: 25, }} resizeMode="contain"></Image> )}> <Scene key="TaskListScreen" component={TaskListScreen} title="Pending" initial titleStyle={{ color: "red" }} /> </Scene> <Scene key="CompleteTaskFilter" title="Completed" hideNavBar={true} icon={({ focused }) => ( focused ? <Image source={require('./assets/images/com.png')} resizeMode='contain' style={{ height: 20, width: 20, marginTop: 15, marginLeft: 5, }}></Image> : <Image source={require('./assets/images/com_a.png')} resizeMode='contain' style={{ height: 20, width: 20, marginTop: 15, marginLeft: 5, }}></Image> )}> <Scene key="CompleteTaskFilter" component={CompleteTaskFilter} title="Completed" /> </Scene> </Tabs> {/* .....................User Part............ */} <Tabs key="userTask" tabBarStyle={{ backgroundColor: '#FFFFFF', }} labelStyle={{ fontSize: 14, padding: 5 }} hideNavBar={true} > <Stack key="MyTask" title="Assigned to Me" hideNavBar={true} icon={({ focused }) => ( focused ? <MaterialCommunityIcons name="account-arrow-left" size={23} color="#2c82a1" style={{ marginTop: 10 }} /> : <MaterialCommunityIcons name="account-arrow-left" size={23} color="#4a535b" style={{ marginTop: 10 }} /> )}> <Scene key="MyTask" component={MyTask} title="Assigned to Me" initial /> </Stack> <Stack key="CreateByMe" title="Created By Me" hideNavBar={true} icon={({ focused }) => ( focused ? <MaterialCommunityIcons name="card-bulleted-outline" size={30} color="#2c82a1" style={{ marginTop: 10 }} /> : <MaterialCommunityIcons name="card-bulleted-outline" size={30} color="#4a535b" style={{ marginTop: 10 }} /> )}> <Scene key="CreateByMe" component={CreateByMe} title="Created By Me" /> </Stack> </Tabs> </Drawer> <Scene key="ReportScreen" component={DepartmentSetupScreen} hideNavBar={true} /> <Scene key="DepartmentSetupScreen" component={DepartmentSetupScreen} hideNavBar={true} /> <Scene key="EmployeeSetupScreen" component={EmployeeSetupScreen} hideNavBar={true} /> <Scene key="EmployeeCreateScreen" component={CreateEmployeeScreen} hideNavBar={true} /> <Scene key="CompanysetupScreen" component={CompanysetupScreen} hideNavBar={true} /> <Scene key="NoticeDetail" component={NoticeDetail} hideNavBar={true} /> <Scene key="NoticeDetailUser" component={NoticeDetailUser} hideNavBar={true} /> <Scene key="DetailScreen" component={DetailScreen} hideNavBar={true} /> <Scene key="TaskListScreen" component={TaskListScreen} hideNavBar={true} /> <Scene key="CompleteTaskFilter" component={CompleteTaskFilter} hideNavBar={true} /> <Scene key="CreateTask" component={CreateTask} hideNavBar={true} /> <Scene key="CreateTaskForBoard" component={CreateTaskForBoard} hideNavBar={true} /> <Scene key="TaskBordDetail" component={TaskBordDetail} hideNavBar={true} /> <Scene key="ViewBoardTask" component={ViewBoardTask} hideNavBar={true} /> <Scene key="ViewTask" component={ViewTask} hideNavBar={true} /> <Scene key="MyTask" component={MyTask} hideNavBar={true}/> <Scene key="ViewAssignToMe" component={ViewAssignToMe} hideNavBar={true} /> </Stack> </Router> ) } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.DataAccess.Common/BaseDatabaseHandler.cs using TrillionBitsPortal.Common; using Microsoft.Practices.EnterpriseLibrary.Data; using Microsoft.Practices.EnterpriseLibrary.Data.Sql; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.Common; using System.Data.SqlClient; namespace TrillionBits.DataAccess.Common { public abstract class BaseDatabaseHandler { protected string CONNECTIONSTRING; private readonly ILogger Logger; protected BaseDatabaseHandler() { CONNECTIONSTRING = ConfigurationManager.ConnectionStrings[Constants.ConnectionStringName].ConnectionString; Logger = MlsLogger.Instance; } protected Database GetSQLDatabase(string connectionString = null) { return string.IsNullOrEmpty(connectionString) ? new SqlDatabase(CONNECTIONSTRING) : new SqlDatabase(connectionString); } protected void AddWhereClause(ref string query, QueryParamList pParams) { query += " WHERE 1=1 "; if (pParams.Count > 0) { foreach (QueryParamObj item in pParams) { query += " AND " + item.ParamName + " = @" + item.ParamName; } } } protected void AddWhereClause(ref string query, QueryParamList pParams, string prefix) { query += " WHERE 1=1 "; if (pParams.Count > 0) { foreach (QueryParamObj item in pParams) { if (item.ParamValue != null) query += " AND " + prefix + item.ParamName + " = @" + item.ParamName; else { query += " AND " + prefix + item.ParamName + " IS NULL "; } } } } protected DataSet GetSPResultSetEx(string storedProcName, QueryParamList spParams, ref string pErrString) { Database db = GetSQLDatabase(); var ds = new DataSet(); try { using (DbCommand cmd = db.GetStoredProcCommand(storedProcName)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } ds = db.ExecuteDataSet(cmd); } } catch (Exception ex) { pErrString = ex.Message; Logger.LogException(ex); } return ds; } protected void DBExecSPInOutEx(string storedProcName, ref QueryParamList spParams, int pCommandTimeout, ref string pErrString) { Database db = GetSQLDatabase(); DbCommand cmd = db.GetStoredProcCommand(storedProcName); if (pCommandTimeout > 0) { cmd.CommandTimeout = pCommandTimeout; } if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddParameter(cmd, obj.ParamName, obj.DBType, obj.ParamDirection, null, DataRowVersion.Current, obj.ParamValue); } } try { db.ExecuteNonQuery(cmd); } catch (Exception ex) { pErrString = ex.Message; Logger.LogException(ex); } finally { if (spParams != null) { foreach (QueryParamObj obj in spParams) { obj.ParamValue = db.GetParameterValue(cmd, obj.ParamName); } } CloseConnection(cmd); } } protected void DBExecSPInOutWithSizeEx(string storedProcName, ref QueryParamList spParams, int pCommandTimeout, ref string pErrString) { Database db = GetSQLDatabase(); DbCommand cmd = db.GetStoredProcCommand(storedProcName); if (pCommandTimeout > 0) { cmd.CommandTimeout = pCommandTimeout; } if (spParams != null) { foreach (QueryParamObj obj in spParams) { if (obj.ParamLen > 0) db.AddParameter(cmd, obj.ParamName, obj.DBType, obj.ParamLen, obj.ParamDirection, true, 0, 1, null, DataRowVersion.Current, obj.ParamValue); else db.AddParameter(cmd, obj.ParamName, obj.DBType, obj.ParamDirection, null, DataRowVersion.Current, obj.ParamValue); } } try { db.ExecuteNonQuery(cmd); } catch (Exception ex) { pErrString = ex.Message; Logger.LogException(ex); } finally { if (spParams != null) { foreach (QueryParamObj obj in spParams) { obj.ParamValue = db.GetParameterValue(cmd, obj.ParamName); } } CloseConnection(cmd); } } protected void DBExecSPInOutWithSizeEx(string storedProcName, ref QueryParamList spParams, int pCommandTimeout, ref string pErrString, string connString) { Database db = GetSQLDatabase(connString); DbCommand cmd = db.GetStoredProcCommand(storedProcName); if (pCommandTimeout > 0) { cmd.CommandTimeout = pCommandTimeout; } if (spParams != null) { foreach (QueryParamObj obj in spParams) { if (obj.ParamLen > 0) db.AddParameter(cmd, obj.ParamName, obj.DBType, obj.ParamLen, obj.ParamDirection, true, 0, 1, null, DataRowVersion.Current, obj.ParamValue); else db.AddParameter(cmd, obj.ParamName, obj.DBType, obj.ParamDirection, null, DataRowVersion.Current, obj.ParamValue); } } try { db.ExecuteNonQuery(cmd); } catch (Exception ex) { pErrString = ex.Message; Logger.LogException(ex); } finally { if (spParams != null) { foreach (QueryParamObj obj in spParams) { obj.ParamValue = db.GetParameterValue(cmd, obj.ParamName); } } CloseConnection(cmd); } } /// <summary> /// Executes a stored procedure on the live config db with parameters specifying the company /// </summary> /// <param name="storedProcName"></param> /// <param name="spParams"></param> /// <param name="pCompanyNumber"></param> protected void DBExecStoredProc(string storedProcName, QueryParamList spParams, ref string pErrString) { Database db = GetSQLDatabase(); using (DbCommand cmd = db.GetStoredProcCommand(storedProcName)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } try { db.ExecuteNonQuery(cmd); } catch (Exception ex) { pErrString = ex.Message; Logger.LogException(ex); } } } protected void DBExecStoredProc(string storedProcName, QueryParamList spParams, ref string pErrString, string connectionString) { Database db = GetSQLDatabase(connectionString); using (DbCommand cmd = db.GetStoredProcCommand(storedProcName)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } try { db.ExecuteNonQuery(cmd); } catch (Exception ex) { pErrString = ex.Message; Logger.LogException(ex); } } } /// <summary> /// Executes a stored procedure on the live config db with parameters specifying the company with transaction parameter to do transaction management /// </summary> /// <param name="storedProcName"></param> /// <param name="spParams"></param> /// <param name="pCompanyNumber"></param> /// <param name="pTransaction"></param> /// <returns></returns> protected int DBExecStoredProcInTran(Database db, DbCommand cmd, QueryParamList spParams, DbTransaction pTransaction) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { if (obj.ParamLen > 0) db.AddParameter(cmd, obj.ParamName, obj.DBType, obj.ParamLen, obj.ParamDirection, true, 0, 1, null, DataRowVersion.Current, obj.ParamValue); else db.AddParameter(cmd, obj.ParamName, obj.DBType, obj.ParamDirection, null, DataRowVersion.Current, obj.ParamValue); } } return db.ExecuteNonQuery(cmd, pTransaction); } protected int DBExecStoredProcInTranReturnsIdentity(Database db, DbCommand cmd, QueryParamList spParams, DbTransaction pTransaction) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } object identity = db.ExecuteScalar(cmd, pTransaction); return identity != DBNull.Value ? Convert.ToInt32(identity) : -1; } /// <summary> ///Private Metod that executes a sql command on specified db that does not return a resultset /// </summary> /// <param name="queryName"></param> /// <param name="spParams"></param> /// <param name="db"></param> /// <returns></returns> protected bool DBExecCommandEx(string query, QueryParamList spParams, Database db, ref string pErrString) { try { using (DbCommand cmd = db.GetSqlStringCommand(query)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } db.ExecuteNonQuery(cmd); } } catch (Exception e) { pErrString = e.Message; Logger.LogException(e); return false; } return true; } protected bool DBExecCommandEx(string query, QueryParamList spParams, ref string pErrString) { Database db = GetSQLDatabase(); return DBExecCommandEx(query, spParams, db, ref pErrString); } protected bool DBExecCommandEx(string query, QueryParamList spParams, ref string pErrString, string connString) { Database db = GetSQLDatabase(connString); return DBExecCommandEx(query, spParams, db, ref pErrString); } protected int DBExecCommandExTran(string query, QueryParamList spParams, DbTransaction pTransaction, Database db, ref string pErrString) { DbCommand cmd = db.GetSqlStringCommand(query); if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } return db.ExecuteNonQuery(cmd, pTransaction); } protected DataSet LoadDataSet(string query, QueryParamList spParams, string tableName, ref string pErrString) { Database db = GetSQLDatabase(); DataSet ds = new DataSet(); try { using (DbCommand cmd = db.GetSqlStringCommand(query)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } db.LoadDataSet(cmd, ds, tableName); } } catch (Exception e) { pErrString = e.Message; Logger.LogException(e); } return ds; } protected object DBExecuteScalar(string query, QueryParamList spParams, ref string pErrString) { Database db = GetSQLDatabase(); object result = null; try { using (DbCommand cmd = db.GetSqlStringCommand(query)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } result = db.ExecuteScalar(cmd); } } catch (Exception e) { pErrString = e.Message; Logger.LogException(e); } return result; } protected object DBExecuteScalar(string query, QueryParamList spParams, DbTransaction pTransaction, Database db) { object result = null; using (DbCommand cmd = db.GetSqlStringCommand(query)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } result = db.ExecuteScalar(cmd, pTransaction); } return result; } protected object DBExecuteScalarSP(string spName, QueryParamList spParams, Database db) { object result = null; using (DbCommand cmd = db.GetStoredProcCommand(spName)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } try { result = db.ExecuteScalar(cmd); } catch (Exception ex) { Logger.LogException(ex); } } return result; } protected object DBExecuteScalarSP(string spName, QueryParamList spParams) { object result = null; Database db = GetSQLDatabase(); using (DbCommand cmd = db.GetStoredProcCommand(spName)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } try { result = db.ExecuteScalar(cmd); } catch (Exception ex) { Logger.LogException(ex); } } return result; } protected object DBExecuteScalarSP(string spName, QueryParamList spParams, DbTransaction pTransaction, Database db) { object result = null; using (DbCommand cmd = db.GetStoredProcCommand(spName)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } result = db.ExecuteScalar(cmd, pTransaction); } return result; } /// <summary> /// Runs a query on DB with parameters and returns a dbDataReader. must close the reader after done with reader. /// </summary> /// <param name="queryName"></param> /// <param name="queryParams"></param> /// <returns></returns> public DbDataReader GetDBQueryReader(string query, QueryParamList queryParams) { Database db = GetSQLDatabase(); DbCommand command = db.GetSqlStringCommand(query); if (command.Connection == null) command.Connection = db.CreateConnection(); if (queryParams != null) { foreach (QueryParamObj obj in queryParams) { db.AddInParameter(command, obj.ParamName, obj.DBType, obj.ParamValue); } } if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } DbDataReader reader = command.ExecuteReader(CommandBehavior.SingleResult); return reader; } public List<T> ExecuteDBQuery<T>(string query, QueryParamList queryParams, Func<DbDataReader, List<T>> populateData) { Database db = GetSQLDatabase(); DbCommand command = db.GetSqlStringCommand(query); if (command.Connection == null) command.Connection = db.CreateConnection(); if (queryParams != null) { foreach (QueryParamObj obj in queryParams) { db.AddInParameter(command, obj.ParamName, obj.DBType, obj.ParamValue); } } DbDataReader reader = null; List<T> list = new List<T>(); try { if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } reader = command.ExecuteReader(CommandBehavior.SingleResult); list = populateData(reader); } catch (Exception e) { Logger.LogException(e); } finally { if (reader != null) reader.Close(); CloseConnection(command); } return list; } public List<T> ExecuteDBQuery<T>(string query, QueryParamList queryParams, Func<DbDataReader, List<T>> populateData, string connString) { Database db = GetSQLDatabase(connString); DbCommand command = db.GetSqlStringCommand(query); if (command.Connection == null) command.Connection = db.CreateConnection(); if (queryParams != null) { foreach (QueryParamObj obj in queryParams) { db.AddInParameter(command, obj.ParamName, obj.DBType, obj.ParamValue); } } DbDataReader reader = null; List<T> list = new List<T>(); try { if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } reader = command.ExecuteReader(CommandBehavior.SingleResult); list = populateData(reader); } catch (Exception e) { Logger.LogException(e); } finally { if (reader != null) reader.Close(); CloseConnection(command); } return list; } public List<T> ExecuteDBQuery<T>(string query, QueryParamList queryParams, Func<DbDataReader, List<T>> populateData, bool addToCache, string cacheKey) { Database db = GetSQLDatabase(); DbCommand command = db.GetSqlStringCommand(query); if (command.Connection == null) command.Connection = db.CreateConnection(); if (queryParams != null) { foreach (QueryParamObj obj in queryParams) { db.AddInParameter(command, obj.ParamName, obj.DBType, obj.ParamValue); } } DbDataReader reader = null; List<T> list = new List<T>(); try { if (command.Connection.State != ConnectionState.Open) { command.Connection.Open(); } SqlDependency dependency = null; if (addToCache) { dependency = new SqlDependency(command as SqlCommand); } reader = command.ExecuteReader(CommandBehavior.SingleResult); list = populateData(reader); if (addToCache) { // InMemoryCache.CacheService.Set(cacheKey, list, dependency); } } catch (Exception e) { Logger.LogException(e); } finally { if (reader != null) reader.Close(); CloseConnection(command); } return list; } protected List<T> ExecuteStoreProcedure<T>(string storedProcName, QueryParamList spParams, Func<DbDataReader, List<T>> populateData) { Database db = GetSQLDatabase(); using (DbCommand cmd = db.GetStoredProcCommand(storedProcName)) { if (cmd.Connection == null) cmd.Connection = db.CreateConnection(); if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } DbDataReader reader = null; List<T> list = new List<T>(); try { if (cmd.Connection.State != ConnectionState.Open) { cmd.Connection.Open(); } cmd.CommandTimeout = 240; reader = cmd.ExecuteReader(CommandBehavior.SingleResult); list = populateData(reader); } catch (Exception e) { Logger.LogException(e); } finally { if (reader != null) reader.Close(); CloseConnection(cmd); } return list; } } protected List<T> ExecuteStoreProcedureWithDataTable<T>(string storedProcName, QueryParamList spParams, Func<DbDataReader, List<T>> populateData) { var db = (SqlDatabase)GetSQLDatabase(); using (DbCommand cmd = db.GetStoredProcCommand(storedProcName)) { if (cmd.Connection == null) cmd.Connection = db.CreateConnection(); if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.SqlDbType, obj.ParamValue); } } DbDataReader reader = null; List<T> list = new List<T>(); try { if (cmd.Connection.State != ConnectionState.Open) { cmd.Connection.Open(); } cmd.CommandTimeout = 240; reader = cmd.ExecuteReader(CommandBehavior.SingleResult); list = populateData(reader); } catch (Exception e) { Logger.LogException(e); } finally { if (reader != null) reader.Close(); CloseConnection(cmd); } return list; } } protected List<T> ExecuteStoreProcedure<T>(string storedProcName, QueryParamList spParams, Func<DbDataReader, List<T>> populateData, string connectionString) { Database db = GetSQLDatabase(connectionString); using (DbCommand cmd = db.GetStoredProcCommand(storedProcName)) { if (cmd.Connection == null) cmd.Connection = db.CreateConnection(); if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } DbDataReader reader = null; List<T> list = new List<T>(); try { if (cmd.Connection.State != ConnectionState.Open) { cmd.Connection.Open(); } cmd.CommandTimeout = 240; reader = cmd.ExecuteReader(CommandBehavior.SingleResult); list = populateData(reader); } catch (Exception e) { Logger.LogException(e); } finally { if (reader != null) reader.Close(); CloseConnection(cmd); } return list; } } protected int ExecuteMasterDetails(string query, IEnumerable<QueryParamObj> spParams, Database db, DbTransaction transaction) { var rValue = 0; using (DbCommand cmd = db.GetSqlStringCommand(query)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } try { rValue = db.ExecuteNonQuery(cmd, transaction); } catch (Exception ex) { rValue = -1; transaction.Rollback(); CloseConnection(cmd); } } return rValue; } protected void CloseConnection(DbCommand command) { if (command != null && command.Connection.State == ConnectionState.Open) { command.Connection.Close(); } } public DataSet GetData(string tableName, QueryParamList pParams, ref string pErrString) { string query = "SELECT * FROM " + tableName; AddWhereClause(ref query, pParams); return LoadDataSet(query, pParams, tableName, ref pErrString); } protected int ExecuteInsideTransaction(string query, IEnumerable<QueryParamObj> spParams, Database db, DbTransaction transaction) { var rValue = 0; using (DbCommand cmd = db.GetSqlStringCommand(query)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } try { rValue = db.ExecuteNonQuery(cmd, transaction); } catch (Exception ex) { Logger.LogException(ex); rValue = -1; transaction.Rollback(); CloseConnection(cmd); } } return rValue; } protected int ExecuteSPInsideTransaction(string spName, IEnumerable<QueryParamObj> spParams, Database db, DbTransaction transaction) { var rValue = 0; using (DbCommand cmd = db.GetStoredProcCommand(spName)) { if (spParams != null) { foreach (QueryParamObj obj in spParams) { db.AddInParameter(cmd, obj.ParamName, obj.DBType, obj.ParamValue); } } try { db.ExecuteNonQuery(cmd, transaction); } catch (Exception ex) { Logger.LogException(ex); rValue = -1; transaction.Rollback(); CloseConnection(cmd); } finally { if (spParams != null) { foreach (QueryParamObj obj in spParams) { obj.ParamValue = db.GetParameterValue(cmd, obj.ParamName); } } } } return rValue; } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/DataAccess/UserCredentialDataAccess.cs using System.Linq; using System.Data; using TrillionBitsPortal.Common; using TrillionBitsPortal.Common.Models; using System; using TrillionBits.DataAccess.Common; using TrillionBitsPortal.ResourceTracker.Interfaces; namespace TrillionBitsPortal.ResourceTracker.DataAccess { public class UserCredentialDataAccess : BaseDatabaseHandler, IUserCredential { public ResponseModel Save(UserCredentialModel model) { var errMessage = string.Empty; var pk = Guid.NewGuid().ToString(); var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id", ParamValue = pk}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@FullName", ParamValue = model.FullName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Email", ParamValue =model.Email}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@LoginID", ParamValue =model.LoginID}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ContactNo", ParamValue = model.ContactNo}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Password", ParamValue =model.Password}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@UserTypeId", ParamValue =model.UserTypeId} }; const string sql = @"INSERT INTO dbo.UserCredentials(Id,FullName,Email,ContactNo,Password,UserTypeId,IsActive,CreatedAt,LoginID) VALUES(@Id,@FullName,@Email,@ContactNo,@Password,@UserTypeId,1,GETDATE(),@LoginID)"; DBExecCommandEx(sql, queryParamList, ref errMessage); return new ResponseModel { Success = string.IsNullOrEmpty(errMessage), Message = errMessage, ReturnCode = pk }; } public UserCredentialModel Get(string username, string password) { const string sql = @"SELECT U.* FROM UserCredentials U WHERE U.LoginID=@Username and U.Password=@Password AND U.IsActive=1"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Username", ParamValue = username}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Password", ParamValue = password} }; var results = ExecuteDBQuery(sql, queryParamList, UserMapper.ToUserFullDetails); return results.Any() ? results.FirstOrDefault() : null; } public ResponseModel ChangePassword(string userInitial, string newPassword) { var err = string.Empty; const string sql = @"UPDATE UserCredentials set Password=@<PASSWORD> where LoginID=@userInitial"; var queryParamList = new QueryParamList { new QueryParamObj { ParamName = "@userInitial", ParamValue =userInitial}, new QueryParamObj { ParamName = "@newPassword", ParamValue =newPassword} }; DBExecCommandEx(sql, queryParamList, ref err); return new ResponseModel { Success = string.IsNullOrEmpty(err) }; } public UserCredentialModel GetProfileDetails(string userId) { const string sql = @"SELECT c.* FROM UserCredentials C WHERE c.Id=@userId and c.IsActive=1"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@userId", ParamValue = userId} }; var results= ExecuteDBQuery(sql, queryParamList, UserMapper.ToUserFullDetails); return results.Any() ? results.FirstOrDefault() : null; } public UserCredentialModel GetByLoginID(string loginID) { const string sql = @"SELECT c.* FROM UserCredentials C WHERE c.LoginID=@loginID"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@loginID", ParamValue = loginID} }; var results = ExecuteDBQuery(sql, queryParamList, UserMapper.ToUserFullDetails); return results.Any() ? results.FirstOrDefault() : null; } public UserCredentialModel GetByLoginID(string loginID,UserType uType) { const string sql = @"SELECT C.* FROM UserCredentials C WHERE c.LoginID=@loginID AND C.UserTypeId=@uType AND C.IsActive=1"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@loginID", ParamValue = loginID}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@uType", ParamValue = (int)uType} }; var results = ExecuteDBQuery(sql, queryParamList, UserMapper.ToUserFullDetails); return results.Any() ? results.FirstOrDefault() : null; } public UserCredentialModel GetByLoginID(string loginID,string password ,UserType uType) { const string sql = @"SELECT C.* FROM UserCredentials C WHERE c.LoginID=@loginID AND C.Password=@password AND C.UserTypeId=@uType"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@loginID", ParamValue = loginID}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@password", ParamValue = password}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@uType", ParamValue = (int)uType} }; var results = ExecuteDBQuery(sql, queryParamList, UserMapper.ToUserFullDetails); return results.Any() ? results.FirstOrDefault() : null; } public UserCredentialModel GetUserFullInfo(string userId) { const string sql = @"SELECT c.* FROM UserCredentials c WHERE c.Id=@userId and c.IsActive=1"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@userId", ParamValue = userId} }; var results = ExecuteDBQuery(sql, queryParamList, UserMapper.ToUserFullDetails); return results.Any() ? results.FirstOrDefault() : null; } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/DbUtility/CommonModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.Common { public class RowsCount { public int Rows { get; set; } } public class StringReturnModel { public string Value { get; set; } } } <file_sep>/hr Office/HrApp/services/TaskService.js import { postApi, getApi } from "./api"; export const GetRelatedToMeTasks = async (userId) => getApi("RtTaskApi/GetRelatedToMeTasks?userId="+userId, {}, {}); export const SaveTask = async data => postApi("RtTaskApi/SaveTask", {}, data); export const GetGroups = async (companyId) => getApi("RtTaskApi/GetGroups?companyId="+companyId, {}, {}); export const SaveTaskGroup = async data => postApi("RtTaskApi/SaveTaskGroup", {}, data); export const TaskStatus = async () => getApi("RtTaskApi/GetTaskStatusList", {}, {}); export const GetTaskByGroup = async (groupId) => getApi("RtTaskApi/GetTasksByGroup?groupId="+groupId, {}, {}); export const deleteTask = async (taskId) => getApi("RtTaskApi/DeleteTask?id="+taskId, {}, {}); export const PriorityList = async () => getApi("RtTaskApi/GetPriorityList", {}, {}); export const SaveFile = async data => postApi("RtTaskApi/SaveTaskAttachment", {}, data); export const GetTaskAttachments = async (taskId) => getApi("RtTaskApi/GetTaskAttachments?taskId="+taskId, {}, {}); <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/Logging/MlsLogger.cs using System; namespace TrillionBitsPortal.Common { public sealed class MlsLogger : ILogger { private readonly log4net.ILog log = null; private static readonly Lazy<MlsLogger> lazy = new Lazy<MlsLogger>(() => new MlsLogger()); public static MlsLogger Instance { get { return lazy.Value; } } private MlsLogger() { log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); } public void Log(Exception exception) { log.Error(exception); } public void Log(string message) { log.Info(message); } public void LogException(Exception exception) { log.Error(exception); } public void LogException(Exception exception, string additionalMessage) { log.Error(additionalMessage, exception); } public void LogMessage(string message) { log.Info(message); } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/DbUtility/DbUtil.cs using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.Common { public static class DbUtil { public static DataSet DataReaderToDataSet(IDataReader reader) { DataSet dataSet = new DataSet(); do { int fieldCount = reader.FieldCount; DataTable dataTable = new DataTable(); for (int i = 0; i < fieldCount; i++) { dataTable.Columns.Add(reader.GetName(i), reader.GetFieldType(i)); } dataTable.BeginLoadData(); object[] objArray = new object[fieldCount]; while (reader.Read()) { reader.GetValues(objArray); dataTable.LoadDataRow(objArray, true); } dataTable.EndLoadData(); dataSet.Tables.Add(dataTable); } while (reader.NextResult()); reader.Close(); return dataSet; } public static DataTable DataReaderToDataTable(IDataReader reader) { DataTable dataTable = new DataTable(); do { int fieldCount = reader.FieldCount; for (int i = 0; i < fieldCount; i++) { dataTable.Columns.Add(reader.GetName(i), reader.GetFieldType(i)); } dataTable.BeginLoadData(); object[] objArray = new object[fieldCount]; while (reader.Read()) { reader.GetValues(objArray); dataTable.LoadDataRow(objArray, true); } dataTable.EndLoadData(); } while (reader.NextResult()); reader.Close(); return dataTable; } public delegate T OverrideModel<out T>(Dictionary<string, object> fields); } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Mappers/AttendanceMapper.cs using System; using System.Collections.Generic; using System.Data.Common; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Mappers { public class AttendanceMapper { public static List<AttendanceModel> ToAttendance(DbDataReader readers) { if (readers == null) return null; var models = new List<AttendanceModel>(); while (readers.Read()) { var model = new AttendanceModel { EmployeeId = Convert.ToInt32(readers["EmployeeId"]), UserId = Convert.IsDBNull(readers["UserId"]) ? string.Empty : Convert.ToString(readers["UserId"]), EmployeeName = Convert.IsDBNull(readers["EmployeeName"]) ? string.Empty : Convert.ToString(readers["EmployeeName"]), PhoneNumber = Convert.IsDBNull(readers["PhoneNumber"]) ? string.Empty : Convert.ToString(readers["PhoneNumber"]), AttendanceDate = Convert.IsDBNull(readers["AttendanceDate"]) ? (DateTime?)null : Convert.ToDateTime(readers["AttendanceDate"]), CheckInTime = Convert.IsDBNull(readers["CheckInTime"]) ? (DateTime?)null : Convert.ToDateTime(readers["CheckInTime"]), CheckOutTime = Convert.IsDBNull(readers["CheckOutTime"]) ? (DateTime?)null : Convert.ToDateTime(readers["CheckOutTime"]), CompanyId = Convert.ToInt32(readers["CompanyId"]), LessTimeReason = Convert.IsDBNull(readers["LessTimeReason"]) ? string.Empty : Convert.ToString(readers["LessTimeReason"]), DepartmentName = Convert.IsDBNull(readers["DepartmentName"]) ? string.Empty : Convert.ToString(readers["DepartmentName"]), Designation = Convert.IsDBNull(readers["Designation"]) ? string.Empty : Convert.ToString(readers["Designation"]), ImageFileName = Convert.IsDBNull(readers["ImageFileName"]) ? string.Empty : Convert.ToString(readers["ImageFileName"]), DailyWorkingTimeInMin = Convert.IsDBNull(readers["DailyWorkingTimeInMin"]) ? (int?)null: Convert.ToInt32(readers["DailyWorkingTimeInMin"]), AllowOfficeLessTimeInMin = Convert.IsDBNull(readers["AllowOfficeLessTime"]) ? (int?)null : Convert.ToInt32(readers["AllowOfficeLessTime"]), IsLeave = Convert.IsDBNull(readers["IsLeave"]) ? (bool?)null : Convert.ToBoolean(readers["IsLeave"]), }; models.Add(model); } return models; } public static List<UserMovementLogModel> ToMovementLog(DbDataReader readers) { if (readers == null) return null; var models = new List<UserMovementLogModel>(); while (readers.Read()) { var model = new UserMovementLogModel { Id = Convert.IsDBNull(readers["Id"]) ? string.Empty : Convert.ToString(readers["Id"]), UserId = Convert.IsDBNull(readers["UserId"]) ? string.Empty : Convert.ToString(readers["UserId"]), LogDateTime = Convert.IsDBNull(readers["LogDateTime"]) ? (DateTime?)null : Convert.ToDateTime(readers["LogDateTime"]), Latitude = Convert.IsDBNull(readers["Latitude"]) ? (decimal?)null : Convert.ToDecimal(readers["Latitude"]), Longitude = Convert.IsDBNull(readers["Longitude"]) ? (decimal?)null : Convert.ToDecimal(readers["Longitude"]), CompanyId = Convert.ToInt32(readers["CompanyId"]), LogLocation = Convert.IsDBNull(readers["LogLocation"]) ? string.Empty : Convert.ToString(readers["LogLocation"]), DeviceName = Convert.IsDBNull(readers["DeviceName"]) ? string.Empty : Convert.ToString(readers["DeviceName"]), DeviceOSVersion = Convert.IsDBNull(readers["DeviceOSVersion"]) ? string.Empty : Convert.ToString(readers["DeviceOSVersion"]), IsCheckInPoint = Convert.IsDBNull(readers["IsCheckInPoint"]) ? (bool?)null : Convert.ToBoolean(readers["IsCheckInPoint"]), IsCheckOutPoint = Convert.IsDBNull(readers["IsCheckOutPoint"]) ? (bool?)null : Convert.ToBoolean(readers["IsCheckOutPoint"]), }; models.Add(model); } return models; } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/TaskModel.cs using System; using System.ComponentModel; using System.Web.Script.Serialization; using TrillionBitsPortal.Common; namespace TrillionBitsPortal.ResourceTracker.Models { public class TaskModel { public string Id { get; set; } public int? TaskNo { get; set; } public string Title { get; set; } public string Description { get; set; } public string CreatedById { get; set; } [ScriptIgnore] public DateTime? CreatedAt { get; set; } public string AssignedToId { get; set; } public int? StatusId { get; set; } public int? TaskGroupId { get; set; } public DateTime? DueDate { get; set; } public int? CompanyId { get; set; } public int? PriorityId { get; set; } public string UpdatedByName { get; set; } [ScriptIgnore] public DateTime? UpdatedAt { get; set; } public string DueDateVw { get { return DueDate.HasValue ? DueDate.Value.ToString(Constants.DateLongFormat) : string.Empty; } } public string CreatedAtVw { get { return CreatedAt.HasValue ? CreatedAt.Value.ToString(Constants.DateTimeLongFormat) : string.Empty; } } public string UpdatedAtVw { get { return UpdatedAt.HasValue ? UpdatedAt.Value.ToString(Constants.DateTimeLongFormat) : string.Empty; } } public string StatusName { get { if (!StatusId.HasValue) return string.Empty; return EnumUtility.GetDescriptionFromEnumValue((TaskStatus)StatusId); } } public string PriorityName { get { if (!PriorityId.HasValue) { PriorityId = (int)TaskPriority.Normal; } return EnumUtility.GetDescriptionFromEnumValue((TaskPriority)PriorityId); } } public bool HasAttachments { get { return false; } } public string AssignToName { get; set; } public string CreatedByName { get; set; } public bool CanDelete { get; set; } } public class TaskAttachment { public string Id { get; set; } public string TaskId { get; set; } public string FileName { get; set; } public string BlobName { get; set; } public string FilePath { get { if (string.IsNullOrEmpty(BlobName)) return string.Empty; return Constants.AzureBlobRootPath + "/" + AzureStorageContainerType.resourcetracker + "/" + BlobName; } } public string UpdatedById { get; set; } [ScriptIgnore] public DateTime? UpdatedAt { get; set; } public string UpdatedAtVw { get { return UpdatedAt.HasValue ? UpdatedAt.Value.ToString(Constants.DateTimeLongFormat) : string.Empty; } } } public class TaskGroupModel { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public string BackGroundColor { get; set; } public string CreatedById { get; set; } public DateTime? CreatedAt { get; set; } public int? CompanyId { get; set; } public int TotalTask { get; set; } } public class ToDoTaskShareModel { public string Id { get; set; } public string TaskId { get; set; } public string ShareWithId { get; set; } } public class ToDoTaskModel { public string Id { get; set; } public string Title { get; set; } public string Description { get; set; } public string CreatedById { get; set; } public DateTime? CreatedAt { get; set; } public int? CompanyId { get; set; } public bool Completed { get; set; } } public enum TaskStatus { [Description("To Do")] ToDo = 1, [Description("In Progress")] InProgress = 2, [Description("Pause")] Pause = 3, [Description("Completed")] Completed = 4, [Description("Done & Bill Collected")] BillCollected = 5, [Description("Cancelled")] Cancelled = 6 } public enum TaskPriority { [Description("Normal")] Normal = 1, [Description("High")] High = 2, [Description("Low")] Low = 3 } } <file_sep>/hr Office/HrApp/components/Screen/attendance/UserSpecificLeave.js import React from 'react'; import { Platform, StatusBar, Dimensions, RefreshControl, TouchableOpacity, View, Text, FlatList, ScrollView, ActivityIndicator, AsyncStorage, BackHandler, Image } from 'react-native'; import { Actions } from 'react-native-router-flux'; import * as actions from '../../../common/actions'; import { GetUserLeaves, LeaveApproved, LeaveRejected } from '../../../services/Leave'; import call from 'react-native-phone-call' import { LeaveListStyle } from '../leaves/LeaveListStyle'; import { SearchBar } from 'react-native-elements'; import { CommonStyles } from '../../../common/CommonStyles'; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar /> </View> ); } export default class UserSpecificLeave extends React.Component { constructor(props) { super(props); this.state = { leaveList: [], progressVisible: true, refreshing: false, companyId: "", userId: global.aItemUserId, } this.arrayholder = []; } _onRefresh = async () => { this.setState({ refreshing: true }); setTimeout(function () { this.setState({ refreshing: false, }); }.bind(this), 2000); this.getLeaveList(this.state.userId, false); }; componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } call = () => { //handler to make a call const args = { number: global.phoneNumber, prompt: false, }; call(args).catch(console.error); } handleBackButton() { Actions.DailyAttendance(); return true; } renderHeader = () => { return ( <ScrollView scrollEnabled={false}> <SearchBar placeholder="Type Here..." style={{ position: 'absolute', zIndex: 1 }} lightTheme containerStyle={{ backgroundColor: '#f6f7f9', }} inputContainerStyle={{ backgroundColor: 'white', }} round onChangeText={text => this.searchFilterFunction(text)} autoCorrect={false} value={this.state.value} /> </ScrollView> ); }; searchFilterFunction = text => { this.setState({ value: text, }); const newData = this.arrayholder.filter(item => { const itemData = `${item.EmployeeName.toUpperCase()} ${item.EmployeeName.toUpperCase()} ${item.EmployeeName.toUpperCase()}`; const textData = text.toUpperCase(); return itemData.indexOf(textData) > -1; }); this.setState({ leaveList: newData, }); }; async componentDidMount() { const cId = await AsyncStorage.getItem("companyId"); this.setState({ companyId: cId }); this.getLeaveList(this.state.userId, true); BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } getLeaveList = async (userId, isProgress) => { try { this.setState({ progressVisible: isProgress }); await GetUserLeaves(global.aItemUserId) .then(res => { this.setState({ leaveList: res.result, progressVisible: false }); this.arrayholder = res.result; console.log(res.result, 'leaveresultlist.............') }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); } catch (error) { this.setState({ progressVisible: false }); console.log(error); } } leaveApprove = async (item) => { const uId = await AsyncStorage.getItem("userId"); await LeaveApproved(item.Id, uId) .then(res => { this.getLeaveList(this.state.companyId, true); }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); } leaveReject = async (item) => { await LeaveRejected(item.Id) .then(res => { this.getLeaveList(this.state.companyId, true); }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); }); this.getLeaveList(this.state.companyId, true); } render() { var { width, height } = Dimensions.get('window'); return ( <View style={LeaveListStyle.container}> <StatusBarPlaceHolder /> <View style={CommonStyles.HeaderContent}> <View style={CommonStyles.HeaderFirstView}> <TouchableOpacity style={CommonStyles.HeaderMenuicon} onPress={() => { this.handleBackButton() }}> <Image resizeMode="contain" style={CommonStyles.HeaderMenuiconstyle} source={require('../../../assets/images/left_arrow.png')}> </Image> </TouchableOpacity> <View style={CommonStyles.HeaderTextView}> <Text style={CommonStyles.HeaderTextstyle}> {global.aItemEmployeeName} </Text> </View> </View> <View style={{ alignItems: 'flex-end' }}> <TouchableOpacity onPress={this.call} style={{ padding: 8, paddingVertical: 2, }}> <Image style={{ width: 20, height: 20,alignItems:'center',marginTop:5, }} resizeMode='contain' source={require('../../../assets/images/call.png')}> </Image> </TouchableOpacity> </View> </View> <View style={{ flex: 1, }}> {this.state.progressVisible == true ? (<ActivityIndicator size="large" color="#1B7F67" style={LeaveListStyle.loaderIndicator} />) : null} <ScrollView showsVerticalScrollIndicator={false}> <View style={{ flex: 1, padding: 10, }}> <FlatList refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> } data={this.state.leaveList} keyExtractor={(x, i) => i.toString()} renderItem={({ item }) => <View style={LeaveListStyle.listContainer} > <View style={LeaveListStyle.listInnerContainer}> <Text style={LeaveListStyle.leaveType}> Name: </Text> <Text style={LeaveListStyle.leaveFrom}> From: </Text> </View> <View style={LeaveListStyle.leaveReasonContainer}> <Text style={LeaveListStyle.leaveReasonText}> {item.EmployeeName} </Text> <Text style={LeaveListStyle.reasonFromDate}> {item.FromDateVw} </Text> </View> <View style={LeaveListStyle.causeContainer}> <Text style={LeaveListStyle.causeText}> Cause: </Text> <Text style={LeaveListStyle.leaveToText}> To: </Text> </View> <View style={LeaveListStyle.detailsContainer}> <Text style={LeaveListStyle.detailsText}> {item.LeaveReason} </Text> <Text style={LeaveListStyle.detailsTextInner}> {item.ToDateVw} </Text> </View> <View style={LeaveListStyle.causeContainer1}> <Text style={LeaveListStyle.causeText}> Leave Type: </Text> <Text style={LeaveListStyle.causeText1}> {item.LeaveType} </Text> </View> {(item.ApprovedBy != null && item.ApprovedBy != '') ? <View style={LeaveListStyle.approvedByContainer}> <View style={{ flexDirection: 'column' }}> <Text style={LeaveListStyle.approvedByText}> Approved By: </Text> <Text style={LeaveListStyle.approvedByText1}> {item.ApprovedBy} </Text> </View> <View> <Text style={LeaveListStyle.approvedAtText}> Approved At: </Text> <Text style={LeaveListStyle.approvedAtText1}> {item.ApprovedAtVw} </Text> </View> </View> : null} {(!item.IsApproved && !item.IsRejected) ? <View style={LeaveListStyle.buttonContainer}> <View style={LeaveListStyle.foraligmentitem}> <TouchableOpacity onPress={() => this.leaveApprove(item)} style={LeaveListStyle.buttonTouchable}> <Text style={LeaveListStyle.approveText}> APPROVE </Text> </TouchableOpacity> <TouchableOpacity onPress={() => this.leaveReject(item)} style={LeaveListStyle.rejectButtonTouchable}> <Text style={LeaveListStyle.rejectText}> REJECT </Text> </TouchableOpacity> </View> <Text style={LeaveListStyle.statusDate1}> {item.LeaveInDays} Days </Text> </View> : <View style={LeaveListStyle.statusButton}> <View style={LeaveListStyle.statusButtonInner}> {item.IsApproved == true ? (<Text style={{ color: 'green', }}> Approved </Text>) : (item.IsRejected == true ? (<Text style={{ color: 'red', }}> Rejecected </Text>) : (<Text style={{ color: '#f1b847', }}> Pending </Text>))} </View> <Text style={LeaveListStyle.statusDate}> {item.LeaveInDays} Days </Text> </View> } </View> } ListHeaderComponent={this.renderHeader()} /> </View> </ScrollView> </View> </View> ); } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/Constants.cs  using System; using System.ComponentModel; namespace TrillionBitsPortal.Common { public class Constants { public const string ConnectionStringName = "IsahakCon"; public static string CurrentUser = "A5151013-DF9F-4234-B0BA-7556A035011D"; public const string DateFormat = "dd/MM/yyyy"; public const string TimeFormat = "hh:mm tt"; public const string DateTimeFormat = "dd/MM/yyyy hh:mm:ss tt"; public const string DateSeparator = "/"; public const string ServerDateTimeFormat = "yyyy-MM-dd HH:mm:ss"; public const string DateLongFormat = "dd-MMM-yyyy"; public const string DateTimeLongFormat = "dd-MMM-yyyy hh:mm"; public const string AzureBlobConnectionName = "AzureBlogConnection"; public const string AzureBlobRootPath = "https://medilifesolutions.blob.core.windows.net/"; public const string AzureBlobStorageHttpFilePath = "http://medilifesolutions.blob.core.windows.net"; } public static class DateTimeConverter { public static DateTime ToZoneTimeBD(this DateTime t) { string bnTimeZoneKey = "Bangladesh Standard Time"; TimeZoneInfo bdTimeZone = TimeZoneInfo.FindSystemTimeZoneById(bnTimeZoneKey); return TimeZoneInfo.ConvertTimeFromUtc((t), bdTimeZone); } } public enum AzureStorageContainerType { resourcetracker } public enum UserType { ResourceTrackerAdmin=6, ResourceTrackerUser=7 } } <file_sep>/hr Office/HrApp/components/Screen/tasks/CreateTask.js import React, { Component } from 'react'; import { ScrollView, Text, View, StatusBar, ActivityIndicator, Image, BackHandler, AsyncStorage, TextInput, TouchableOpacity, ToastAndroid, Platform, KeyboardAvoidingView, NetInfo } from 'react-native'; import { DailyAttendanceCombo, TasksCombo, LeavesCombo, FinanceCombo, ReportsCombo, NoticeCombo, SettingsCombo, drawerSelectedOption } from '../../MenuDrawer/DrawerContent'; import { Actions } from 'react-native-router-flux'; import { EmployeeList } from '../../../services/EmployeeTrackService'; import { NoticeStyle } from '../notice/NoticeStyle' import Modal from 'react-native-modalbox'; import moment from "moment"; import { CommonStyles } from '../../../common/CommonStyles'; import DateTimePicker from 'react-native-modal-datetime-picker'; // import { // Feather, // Ionicons, // MaterialCommunityIcons // } from '@expo/vector-icons' import Feather from 'react-native-vector-icons/Feather' import Ionicons from 'react-native-vector-icons/Ionicons' import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons' import _ from "lodash"; import { TaskStyle } from './TaskStyle'; import * as actions from '../../../common/actions'; import { SaveTask, PriorityList } from '../../../services/TaskService'; const refreshOnBack = () => { if( global.userType=="admin"){ Actions.TabnavigationInTasks(); Actions.TaskListScreen(); }else{ Actions.userTask(); Actions.CreateByMe(); } } const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar /> </View> ); } export default class CreateTask extends Component { constructor(props) { super(props); this.state = { userId: "", companyId: "", date: '', taskTitle: "", taskDescription: "", EmployeeList: [], priorityList: [], isDateTimePickerVisible: false, PriorityId: null, PriorityName: null, touchabledisableForsaveTask: false, EmpName: null, EmpValue: null, TaskGroupId: 0, } } goBackToTasks() { TasksCombo(); } goBack() { Actions.pop(); } returnPage() { actions.push("TaskListScreen"); } _showDateTimePicker = () => this.setState({ isDateTimePickerVisible: true }); _hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false }); _handleDatePicked = (date) => { this.setState({ date: date }) this._hideDateTimePicker(); } async componentDidMount() { const uId = await AsyncStorage.getItem("userId"); const cId = await AsyncStorage.getItem("companyId"); this.setState({ userId: uId, companyId: cId }); this.getEmployeeList(cId); this.getPriorityList(); this.setState({ TaskGroupId: this.props.BoardId }) BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } async saveTask() { if (await NetInfo.isConnected.fetch()) { if (this.state.taskTitle !== "") { this.setState({ touchabledisableForsaveTask: true }) try { let taskModel = { CreatedById: this.state.userId, CompanyId: this.state.companyId, Title: this.state.taskTitle, Description: this.state.taskDescription, AssignToName: this.state.EmpName, AssignedToId: this.state.EmpValue, TaskGroupId: this.state.TaskGroupId, PriorityId: this.state.PriorityId, DueDate: moment(this.state.date).format("YYYYY-MM-DD") }; this.setState({ progressVisible: true }); await SaveTask(taskModel) .then(res => { this.setState({ progressVisible: false }); ToastAndroid.show('Task saved successfully', ToastAndroid.TOP); refreshOnBack(); // this.setState({ touchabledisableForsaveTask: false }) }) .catch(() => { this.setState({ progressVisible: false }); console.log("error occured"); this.setState({ touchabledisableForsaveTask: false }) }); } catch (error) { this.setState({ progressVisible: false }); console.log(error); } } else { ToastAndroid.show('Title Can not be Empty ', ToastAndroid.TOP); } } else { ToastAndroid.show('Please connect to Internet', ToastAndroid.TOP); } } getEmployeeList = async (companyId) => { try { await EmployeeList(companyId) .then(res => { this.setState({ EmployeeList: res.result, progressVisible: false }); }) .catch(() => { this.setState({ progressVisible: false }); }); } catch (error) { this.setState({ progressVisible: false }); } } getPriorityList = async () => { try { await PriorityList() .then(res => { this.setState({ priorityList: res.result, progressVisible: false }); }) .catch(() => { this.setState({ progressVisible: false }); }); } catch (error) { this.setState({ progressVisible: false }); } } async setAssignTo(v, t) { this.setState({ EmpName: t }) this.setState({ EmpValue: v }) this.refs.modal1.close() } renderEmpList() { let content = this.state.EmployeeList.map((empName, i) => { return ( <TouchableOpacity style={{ paddingVertical: 7, borderBottomColor: '#D5D5D5', borderBottomWidth: 2 }} key={i} onPress={() => { this.setAssignTo(empName.Value, empName.Text) }}> <Text style={[{ textAlign: 'center' }, TaskStyle.dbblModalText]} key={empName.Value}>{empName.Text}</Text> </TouchableOpacity> ) }); return content; } async setPriority(id, name) { this.setState({ PriorityId: id }) this.setState({ PriorityName: name }) this.refs.modalPriority.close() } renderPriorityList() { let content = this.state.priorityList.map((x, i) => { return ( <TouchableOpacity style={{ paddingVertical: 7, borderBottomColor: '#D5D5D5', borderBottomWidth: 2 }} key={i} onPress={() => { this.setPriority(x.Id, x.Name) }}> <Text style={[{ textAlign: 'center' }, TaskStyle.dbblModalText]} key={x.Id}>{x.Name}</Text> </TouchableOpacity> ) }); return content; } handleBackButton = () => { this.goBack(); return true; } componentWillUnmount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } render() { return ( <View style={{ flex: 1, backgroundColor: '#ffffff', flexDirection: 'column', }}> <StatusBarPlaceHolder /> <View style={CommonStyles.HeaderContent}> <View style={CommonStyles.HeaderFirstView}> <TouchableOpacity style={CommonStyles.HeaderMenuicon} onPress={() => { this.goBack() }}> <Image resizeMode="contain" style={CommonStyles.HeaderMenuiconstyle} source={require('../../../assets/images/left_arrow.png')}> </Image> </TouchableOpacity> <View style={CommonStyles.HeaderTextView}> <Text style={CommonStyles.HeaderTextstyle}> Create Task </Text> </View> </View> <View style={CommonStyles.createTaskButtonContainer}> <TouchableOpacity disabled={this.state.touchabledisableForsaveTask} onPress={() => this.saveTask()} style={CommonStyles.createTaskButtonTouch}> <View style={CommonStyles.plusButton}> <MaterialCommunityIcons name="content-save" size={17.5} color="#ffffff" /> </View> <View style={CommonStyles.ApplyTextButton}> <Text style={CommonStyles.ApplyButtonText}> POST </Text> </View> </TouchableOpacity> </View> </View> <View style={{ flex: 1 }}> <ScrollView showsVerticalScrollIndicator={false} keyboardDismissMode="on-drag" style={{ flex: 1, }}> <View style={TaskStyle.titleInputRow}> <Text style={TaskStyle.createTaskTitleLabel1}> Title: </Text> <TextInput style={TaskStyle.createTaskTitleTextBox1} placeholder="write a task name here" placeholderTextColor="#dee1e5" autoCapitalize="none" onChangeText={text => this.setState({ taskTitle: text })} > </TextInput> </View> <View style={TaskStyle.descriptionInputRow}> <Text style={TaskStyle.createTaskTitleLabel11}> Description: </Text> <TextInput style={TaskStyle.createTaskDescriptionTextBox} multiline={true} placeholder="write details here" placeholderTextColor="#dee1e5" autoCorrect={false} autoCapitalize="none" onChangeText={text => this.setState({ taskDescription: text })} > </TextInput> </View> <TouchableOpacity onPress={() => this.refs.modal1.open()}> <View style={TaskStyle.assignePeopleContainer}> <Ionicons name="md-people" size={20} style={{ marginRight: 4, }} color="#4a535b" /> <TextInput style={TaskStyle.assigneePeopleTextBox} placeholder="Assign People" placeholderTextColor="#dee1e5" editable={false} autoCapitalize="none" value={this.state.EmpName} > </TextInput> </View> </TouchableOpacity> <View style={TaskStyle.assigneePeopleTextBoxDivider}> {/* horizontal line dummy view */} </View> <TouchableOpacity onPress={() => this.refs.modalPriority.open()}> <View style={TaskStyle.assignePeopleContainer}> <Ionicons name="ios-stats" size={18} style={{ marginHorizontal: 5, }} color="#4a535b" /> <TextInput style={TaskStyle.assigneePeopleTextBox} placeholder="Priority" placeholderTextColor="#dee1e5" editable={false} autoCapitalize="none" value={this.state.PriorityName} > </TextInput> </View> </TouchableOpacity> <View style={TaskStyle.assigneePeopleTextBoxDivider}> {/* horizontal line dummy view */} </View> <View style={TaskStyle.createTaskAttachmentContainer}> <View style={TaskStyle.createTaskDueDateContainer}> <TouchableOpacity onPress={this._showDateTimePicker} style={TaskStyle.createTaskDueDateIcon}> <MaterialCommunityIcons name="clock-outline" size={18} color="#4a535b" style={{ marginHorizontal: 5, }} /> {this.state.date === "" ? <Text style={TaskStyle.createTaskDueDateText}> Due Date: </Text> : <Text style={TaskStyle.createTaskDueDateText}> {moment(this.state.date).format("DD MMMM YYYYY")} </Text> } </TouchableOpacity> <DateTimePicker isVisible={this.state.isDateTimePickerVisible} onConfirm={this._handleDatePicked} onCancel={this._hideDateTimePicker} mode={'date'} /> <View style={TaskStyle.Viewforavoid}> </View> </View> </View> </ScrollView> </View> {/* <View style={{ justifyContent: 'flex-end', }}> <View style={{ height: 50, }}> </View> <TouchableOpacity onPress={() => this.saveTask()} style={TaskStyle.createTaskSaveButtonContainer}> <Feather name="edit" size={14} style={{ marginHorizontal: 3, }} color="#ffffff"> </Feather> <Text style={TaskStyle.createTaskSaveButtonText}> POST </Text> </TouchableOpacity> </View> */} {/* </View> */} <Modal style={[TaskStyle.modalforCreateCompany1]} position={"center"} ref={"modal1"} isDisabled={this.state.isDisabled} backdropPressToClose={false} swipeToClose={false} > <View style={{ justifyContent: "space-between", flexDirection: "row" }}> <View style={{ alignItems: "flex-start" }}> </View> <View style={{ alignItems: "flex-end" }}> <TouchableOpacity onPress={() => this.refs.modal1.close()} style={{ marginLeft: 0, marginTop: 0, }}> <Image resizeMode="contain" style={{ width: 15, height: 15, marginRight: 17, marginTop: 15 }} source={require('../../../assets/images/close.png')}> </Image> </TouchableOpacity> </View> </View> <View style={TaskStyle.dblModelContent}> <ScrollView showsVerticalScrollIndicator={false} style={{ height: "80%" }}> <View style={{}} > {this.renderEmpList()} </View> </ScrollView> </View> </Modal> <Modal style={[TaskStyle.modalforCreateCompany1]} position={"center"} ref={"modalPriority"} backdropPressToClose={false} swipeToClose={false} > <View style={{ justifyContent: "space-between", flexDirection: "row" }}> <View style={{ alignItems: "flex-start" }}> </View> <View style={{ alignItems: "flex-end" }}> <TouchableOpacity onPress={() => this.refs.modalPriority.close()} style={{ marginLeft: 0, marginTop: 0, }}> <Image resizeMode="contain" style={{ width: 15, height: 15, marginRight: 17, marginTop: 15 }} source={require('../../../assets/images/close.png')}> </Image> </TouchableOpacity> </View> </View> <View style={TaskStyle.dblModelContent}> <ScrollView showsVerticalScrollIndicator={false} style={{ height: "80%" }}> <View style={{}} > {this.renderPriorityList()} </View> </ScrollView> </View> </Modal> </View > ) } } <file_sep>/hr Office/HrApp/components/Screen/notice/NoticeStyle.js import { StyleSheet, Platform } from 'react-native'; export const NoticeStyle = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f5f7fb', }, loaderIndicator: { position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, justifyContent: 'center', alignContent: 'center', }, headerContainer: { flexDirection: 'row', height: 60, paddingTop: 0, backgroundColor: 'white', shadowColor: 'rgba(181,181,181,0.02)', shadowOffset: { width: 0, height: -2 }, elevation: 10, shadowRadius: 8, shadowOpacity: 0.3, alignItems: 'center', paddingHorizontal: 10, justifyContent: 'space-between', borderBottomRightRadius: 10, borderBottomLeftRadius: 10 }, headerTitle: { alignItems: 'flex-start', flexDirection: 'row' }, headerText: { fontWeight: 'bold', fontSize: 20, color: '#141414', marginTop: 3, }, headerBar: { justifyContent: 'space-between', backgroundColor: '#fff', flexDirection: 'row', padding: 10, borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 0, height: -5 }, elevation: 10, height: 60, }, headerBarforCompany: { justifyContent: 'space-between', backgroundColor: '#fff', flexDirection: 'row', padding: 10, borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 10, height: -5 }, // elevation: 10, height: 60, }, backIcon: { justifyContent: 'flex-start', flexDirection: 'row', alignItems: 'center', }, backIconTouch: { padding: 10, flexDirection: 'row', alignItems: 'center' }, headerTitle: { backgroundColor: 'white', padding: 0, paddingLeft: 10, margin: 0, flexDirection: 'row', }, headerTitleText: { color: '#4E4E4E', marginTop: 1, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: 'center', }, createNoticeButtonContainer: { justifyContent: 'flex-end', marginRight: 0, marginLeft: 0, flexDirection: 'row', alignItems: 'center', }, createNoticeButtonTouch: { flexDirection: 'row', alignItems: 'center', padding: 3, }, createNoticeDescriptionLabel: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 13, textAlign: "left", color: "#848f98", marginBottom: 10, marginLeft: 20, }, createNoticeDescriptionTextBox: { textAlignVertical: "top", fontFamily: "OPENSANS_REGULAR", fontSize: 13, textAlign: "left", color: "#4a535b", flex: 1, flexWrap: 'wrap', height: "40%", paddingHorizontal: 7, paddingVertical: 6, backgroundColor: "#f5f7fb", borderRadius: 8, }, createNoticeSaveButtonContainer: { position: 'absolute', bottom: 0, width: "100%", justifyContent: 'center', alignItems: 'center', height: 50, flexDirection: 'row', backgroundColor: "#d9ad1e", }, createNoticeSaveButtonText: { fontFamily: "Montserrat_Bold", fontSize: 15, textAlign: "center", color: "#ffffff" }, modalfordept: { height: 300, width: "75%", borderRadius: 20, backgroundColor: '#EBEBEB', }, createnoticeheaderflexEndd: { alignItems: 'flex-end', marginRight: 10, }, createnoticecontainer: { flex: 1 }, selectContainer: { margin: 10, flexDirection: 'row', height: 90, }, opencemarTouchableopacity: { backgroundColor: '#929fbf', flex: 1, marginRight: 5, flexDirection: 'row', alignSelf: 'center', padding: 17, marginLeft: 0, borderRadius: 5, }, opencemarastle: { height: 41, width: 41, }, selectContainerview: { padding: 5, marginLeft: 9, }, selectText: { color: "#ffffff", fontSize: 10, fontFamily: 'Montserrat_SemiBold' }, addPhotoText1: { color: "#ffffff", fontSize: 10, fontFamily: 'Montserrat_SemiBold' }, openDeptTouhableOpacity: { // backgroundColor: '#99c1d4', flex: 1, marginLeft: 5, flexDirection: 'row', alignSelf: 'center', padding: 17, marginLeft: 8, borderRadius: 5, }, imageGroup: { height: 41, width: 41, }, seleectDeptContainer: { padding: 5, marginLeft: 9, }, selectDeptText: { color: "#ffffff", fontSize: 10, fontFamily: 'Montserrat_SemiBold' }, inputTextContainer: { flexDirection: 'column', flex: 2, }, inputText: { textAlignVertical: "top", marginLeft: 10, marginRight: 10, paddingTop: 3, height: 200, backgroundColor: '#f5f7fb', color: '#2c2930', padding: 0, paddingHorizontal: 10, borderRadius: 8, }, ImageTouchableOpacity: { width: 80, height: 80, borderRadius: 10, margin: 10 }, uploadImageStyle: { width: 80, height: 80, borderRadius: 10, }, ImagemodalContainer: { height: 180, width: 250, borderRadius: 20, }, modalClose: { marginLeft: 0, marginTop: 0, }, closeImage: { width:15 , height: 15,marginRight:17,marginTop:15 }, addPhotoText: { color: '#000000', fontSize: 24, textAlign: 'center', fontWeight: '500' }, cemaraImageContainer: { flexDirection: 'row', padding: 15, justifyContent: 'space-between', paddingTop: 20, }, takePhotoText: { textAlign: 'center', marginTop: 4, color: '#7a7a7a', fontSize: 10 }, departListText: { color: '#141414', fontSize: 16, textAlign: 'center', borderBottomWidth: 1, borderBottomColor: '#f5f7fb', padding: 5, fontWeight: '500' }, DoneTouchableopacity: { backgroundColor: '#3D3159', padding: 15, width: 100, alignSelf: 'center', borderRadius: 10, marginTop: "3%", alignItems: 'center' }, noticeDetailContainer: { flex: 1, backgroundColor: '#fff', }, noticeDetailHeaderContainer: { flexDirection: 'row', height: 60, paddingTop: 0, backgroundColor: '#ece3a9', shadowColor: 'rgba(181,181,181,0.02)', shadowOffset: { width: 0, height: -2 }, elevation: 10, shadowRadius: 8, shadowOpacity: 0.3, alignItems: 'center', paddingHorizontal: 10, justifyContent: 'space-between', borderBottomRightRadius: 10, borderBottomLeftRadius: 10 }, noticeDetailTextStyle: { fontFamily: "OPENSANS_REGULAR", fontSize: 16, textAlign: "left", color: "#636363" }, arrowcontainer: { alignItems: 'flex-start', flexDirection: 'row' }, arrowImage: { width: 25, height: 25 }, titleText: { fontWeight: 'bold', fontSize: 20, color: '#141414', marginTop: 3, }, headerFlexEnd: { alignItems: 'flex-end', marginRight: 10, }, detailTextStyle: { padding: 10, marginTop: 16, flex: 1, marginHorizontal: 6, }, noticelistImage: { ...Platform.select({ ios: { width: 40, height: 40, padding: 10, }, android: { width: 40, height: 40, padding: 10, }, }), }, createDateStyle: { // marginBottom: 5, textAlign: 'right', // color: '#c5cbcf', fontSize: 14, fontFamily: 'PRODUCT_SANS_BOLD' }, postedtextStyle: { // marginBottom: 5, textAlign: 'right', // color: '#c5cbcf', fontSize: 14, fontFamily: 'PRODUCT_SANS_BOLD' }, dateContainer: { flexDirection: 'row', justifyContent: 'space-between', paddingTop: 10, borderTopWidth:1, borderTopColor:"#f6f7f9" }, listContainer: { flex: 1, flexWrap: 'wrap', backgroundColor: '#ffffff', marginBottom:5,marginTop:5, borderRadius: 5, padding: 15,elevation: 2, }, listDivider: { justifyContent: 'space-between', flexDirection: 'row', borderBottomColor: 'white', borderBottomWidth: 2, paddingBottom: 10, }, noticepart: { alignItems: 'flex-start', color: '#1a1a1a', fontSize: 10, fontFamily: 'OPENSANS_REGULAR' }, ApplyButtonContainer: { justifyContent: 'flex-end', marginRight: 0, marginLeft: 0, flexDirection: 'row', alignItems: 'center', }, ApplyButtonTouch: { flexDirection: 'row', alignItems: 'center', // height: 1, }, plusButton: { // backgroundColor: "#600B74", backgroundColor: '#9d8127', alignItems: 'center', padding: 6, paddingHorizontal: 9, borderBottomLeftRadius: 6, borderTopLeftRadius: 6, }, plusButtonforCompany: { // backgroundColor: "#600B74", backgroundColor: '#2a2a2a', alignItems: 'center', padding: 6, paddingHorizontal: 9, borderBottomLeftRadius: 6, borderTopLeftRadius: 6, }, ApplyTextButton: { // backgroundColor: "#902ca8", backgroundColor: '#cea41d', alignItems: 'center', padding: 7, paddingHorizontal: 9, borderBottomRightRadius: 6, borderTopRightRadius: 6, }, ApplyTextButtonforNotice: { // backgroundColor: "#902ca8", backgroundColor: '#363E4A', alignItems: 'center', padding: 7, paddingHorizontal: 9, borderBottomRightRadius: 6, borderTopRightRadius: 6, }, ApplyButtonText: { // fontWeight: 'bold', fontSize: 12, color: '#ffffff', fontFamily: "Montserrat_Bold", }, }); <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Interfaces/ICompany.cs using TrillionBitsPortal.Common.Models; using System.Collections.Generic; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Interfaces { public interface ICompany { List<Company> GetCompanyByUserId(string userId); List<Company> GetCompanyByEmpUserId(string userId); Company Create(Company model); ResponseModel UpdateCompany(Company model); Company GetCompanyByIdentity(string userId); Company GetCompanyById(int companyId); List<CompanyListModel> GetCompanyList(); } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Mappers/CompanyMapper.cs using System; using System.Collections.Generic; using System.Data.Common; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Mappers { public static class CompanyMapper { public static List<Company> ToCompanyModel(DbDataReader readers) { if (readers == null) return null; var models = new List<Company>(); while (readers.Read()) { var model = new Company { Id = Convert.ToInt32(readers["Id"]), PortalUserId = Convert.IsDBNull(readers["PortalUserId"]) ? string.Empty : Convert.ToString(readers["PortalUserId"]), CompanyName = Convert.IsDBNull(readers["CompanyName"]) ? string.Empty : Convert.ToString(readers["CompanyName"]), Address = Convert.IsDBNull(readers["Address"]) ? string.Empty : Convert.ToString(readers["Address"]), PhoneNumber = Convert.IsDBNull(readers["PhoneNumber"]) ? string.Empty : Convert.ToString(readers["PhoneNumber"]), MaximumOfficeHours = Convert.IsDBNull(readers["MaximumOfficeHours"]) ? string.Empty : Convert.ToString(readers["MaximumOfficeHours"]), OfficeOutTime = Convert.IsDBNull(readers["OfficeOutTime"]) ? string.Empty : Convert.ToString(readers["OfficeOutTime"]), ImageFileName = Convert.IsDBNull(readers["ImageFileName"]) ? string.Empty : Convert.ToString(readers["ImageFileName"]), ImageFileId = Convert.IsDBNull(readers["ImageFileId"]) ? string.Empty : Convert.ToString(readers["ImageFileId"]), }; models.Add(model); } return models; } public static List<CompanyListModel> ToList(DbDataReader readers) { if (readers == null) return null; var models = new List<CompanyListModel>(); while (readers.Read()) { var model = new CompanyListModel { CompanyName = Convert.IsDBNull(readers["CompanyName"]) ? string.Empty : Convert.ToString(readers["CompanyName"]), Address = Convert.IsDBNull(readers["Address"]) ? string.Empty : Convert.ToString(readers["Address"]), OfficePhone = Convert.IsDBNull(readers["OfficePhone"]) ? string.Empty : Convert.ToString(readers["OfficePhone"]), ContactPerson = Convert.IsDBNull(readers["ContactPerson"]) ? string.Empty : Convert.ToString(readers["ContactPerson"]), ContactPersonMobile = Convert.IsDBNull(readers["ContactPersonMobile"]) ? string.Empty : Convert.ToString(readers["ContactPersonMobile"]), Email = Convert.IsDBNull(readers["Email"]) ? string.Empty : Convert.ToString(readers["Email"]), CreatedDate = Convert.IsDBNull(readers["CreatedDate"]) ? (DateTime?)null : Convert.ToDateTime(readers["CreatedDate"]), TotalEmployee = Convert.IsDBNull(readers["TotalEmployee"]) ? 0 : Convert.ToInt32(readers["TotalEmployee"]), }; models.Add(model); } return models; } } }<file_sep>/hr Office/HrApp/components/Screen/UserScreen/leaves/LeaveListStyle.js import { StyleSheet, Platform } from 'react-native'; export const LeaveListStyle = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f6f7f9', }, ApplyButtonContainer: { justifyContent: 'flex-end', marginRight: 0, marginLeft: 0, flexDirection: 'row', alignItems: 'center', }, headerContainer: { flexDirection: 'row', height: 60, paddingTop: 0, backgroundColor: 'white', shadowColor: 'rgba(181,181,181,0.02)', shadowOffset: { width: 0, height: -2 }, elevation: 10, shadowRadius: 8, shadowOpacity: 0.3, alignItems: 'center', paddingHorizontal: 10, justifyContent: 'space-between', borderBottomRightRadius: 10, borderBottomLeftRadius: 10 }, headerTitle: { alignItems: 'flex-start', flexDirection: 'row' }, headerText: { fontWeight: 'bold', fontSize: 20, color: '#141414', marginTop: 3, }, loaderIndicator: { position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, justifyContent: 'center', alignContent: 'center', }, daysBox: { alignItems: 'center', justifyContent: 'center', backgroundColor: "#f4f5f6", borderWidth: 0.5, padding: 4, borderRadius: 10, }, listContainer: { flexDirection: 'column', justifyContent: 'space-between', paddingTop: 2, paddingBottom: 2, padding: 15, borderRadius: 5, marginTop: 5, marginBottom: 5, backgroundColor: '#ffffff', margin: 10, elevation:2, }, listInnerContainer: { flexDirection: 'row', justifyContent: 'space-between', padding: 2 }, leaveType: { width: "60%", justifyContent: 'flex-start', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, leaveFrom: { justifyContent: 'flex-end', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, leaveReasonContainer: { flexDirection: 'row', justifyContent: 'space-between', }, leaveReasonText: { width: "60%", justifyContent: 'flex-start', fontFamily: "Montserrat_Bold", fontSize: 14, textAlign: "left", color: "#1a1a1a", fontFamily: 'Montserrat_SemiBold' }, reasonFromDate: { justifyContent: 'flex-end', fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, causeContainer: { flexDirection: 'row', justifyContent: 'space-between', padding: 2, paddingVertical: 5, }, causeText: { width: "60%", justifyContent: 'flex-start', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, leaveToText: { justifyContent: 'flex-end', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, detailsContainer: { flexDirection: 'row', justifyContent: 'space-between', paddingBottom: 10, }, HeaderContent: { justifyContent: 'space-between', backgroundColor: '#fff', flexDirection: 'row', padding: 10, borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 10, height: -5 }, elevation: 10, height: 60, }, HeaderFirstView: { justifyContent: 'flex-start', flexDirection: 'row', marginLeft: 5, alignItems: 'center', }, HeaderMenuicon: { alignItems: 'center', padding: 10, }, HeaderMenuLeft: { alignItems: 'center', }, HeaderMenuLeftStyle: { alignItems: 'center', height: 40, width: 75, }, HeaderMenuiconstyle: { width: 20, height: 20, }, HeaderTextView: { backgroundColor: 'white', padding: 0, marginLeft: 17, margin: 0, flexDirection: 'row', alignItems: 'center', }, HeaderTextstyle: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: "left", color: "#2a2a2a", }, plusButton: { backgroundColor: "#600B74", alignItems: 'center', padding: 6, paddingHorizontal: 9, borderBottomLeftRadius: 6, borderTopLeftRadius: 6, }, ApplyButtonText: { // fontWeight: 'bold', fontSize: 12, color: '#ffffff', fontFamily: "Montserrat_Bold", }, ApplyTextButton: { backgroundColor: "#902ca8", alignItems: 'center', padding: 7, paddingHorizontal: 9, borderBottomRightRadius: 6, borderTopRightRadius: 6, }, ApplyButtonTouch: { flexDirection: 'row', alignItems: 'center', // height: 1, }, detailsText: { width: "60%", justifyContent: 'flex-start', fontFamily: "PRODUCT_SANS_REGULAR", fontSize: 14, textAlign: "left", color: "#1a1a1a" }, detailsTextInner: { justifyContent: 'flex-end', fontFamily: "Montserrat_Bold", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, approvedByContainer: { flex: 1, flexDirection: 'column', justifyContent: 'space-between', padding: 2, paddingVertical: 5, borderTopWidth: 0.4, borderTopColor: "black", }, approvedByText: { // width: "60%", justifyContent: 'flex-start', // flex: 1, flexWrap: 'wrap', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, approvedAtText: { // flex: 1, flexWrap: 'wrap', justifyContent: 'flex-end', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a", marginTop: 5, }, statusButton: { flexDirection: 'row', justifyContent: 'space-between', borderTopWidth: 0.4, borderTopColor: "black", paddingTop: 5, paddingBottom: 8, alignItems: 'center', }, statusButtonInner: { flexDirection: 'row', justifyContent: 'flex-start', width: "60%", padding: 5, }, statusDate: { justifyContent: 'flex-end', fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, paddingLeft: 3, textAlign: "center", color: "#929292", marginRight: 5, }, buttonContainer: { flexDirection: 'row', justifyContent: 'flex-start', width: "60%", }, buttonTouchable: { width: 82.3, height: 22.4, borderRadius: 5, backgroundColor: "#1e8555", justifyContent: 'center' }, approveText: { fontFamily: "Montserrat_Bold", fontSize: 10, textAlign: "center", color: "#ffffff" }, rejectButtonTouchable: { width: 82.3, height: 22.4, borderRadius: 5, backgroundColor: "#c24a4a", justifyContent: 'center', marginLeft: 4, }, rejectText: { fontFamily: "Montserrat_Bold", fontSize: 10, textAlign: "center", color: "#ffffff" }, }); <file_sep>/hr Office/HrApp/components/Screen/loginForm.js import React, { Component } from 'react'; import { AsyncStorage, StyleSheet, NetInfo, Text, View, ActivityIndicator, Dimensions, TextInput, TouchableOpacity, AppState, BackHandler, Alert, Image, } from 'react-native'; import { Actions } from 'react-native-router-flux'; import * as actions from '../../common/actions'; import { Login, GetUserClaim } from '../../services/AccountService'; import { saveToStorage, storage, CurrentUserProfile } from '../../common/storage'; import { Feather, MaterialIcons, Entypo } from '@expo/vector-icons'; import { ProgressDialog, ConfirmDialog } from 'react-native-simple-dialogs'; var { width, height } = Dimensions.get('window'); export default class LoginForm extends Component { constructor(props) { super(props); this.state = { userName: this.props.phoneno, password: "", alertMessage: "", loading: false, }; console.log('ph', this.props.phoneno); } handleBackButton = () => { BackHandler.exitApp() return true; } changeUsrNameHandler = (text) => { this.setState({ userName: text }); }; changePassNameHandler = (text) => { this.setState({ password: text }); }; signUp() { Actions.register(); } componentDidMount() { BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillMount() { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } componentWillUnmount() { this.setState({ userName: '' }) } async onPressSubmitButton() { if (await NetInfo.isConnected.fetch()) { if (this.state.userName != "" && this.state.password != "") { this.setState({ loading: true }); this.onFetchLoginRecords(); } else { this.setState({ alertMessage: "Please input all field" }); this.isConfirm(); } } else { Alert.alert( "No Internet ", "Enable Wifi or Mobile Data", [ { text: 'OK', }, ], { cancelable: false } ) } } async onFetchLoginRecords() { console.log("trying login.."); try { let UserModel = { UserName: this.state.userName, Password: this.state.password, }; // if(await !NetInfo.isConnected.fetch()){ // alert("test..."); // // this.setState({alertHeading:"Invalid Phonenumber!"}) // throw "Please Connect Internet"; // } let response = await Login(UserModel); console.log('logins', response); if (response && response.isSuccess) { if (response.result.Success) { await AsyncStorage.setItem("userToken", response.result.Token); await AsyncStorage.setItem("userId", response.result.UserKey); await AsyncStorage.setItem("companyId", response.result.CompanyId.toString()); await this.getUserClaim(response.result.UserKey); this.setState({ loading: false }); } else { this.setState({ loading: false }); this.setState({ alertMessage: "User name or password is wrong" }); this.isConfirm(); } } else { this.setState({ loading: false }); this.setState({ alertMessage: "User name or password is wrong" }); this.isConfirm(); } } catch (errors) { console.log(errors); } } getUserClaim = async (userKey) => { try { await GetUserClaim(userKey) .then(res => { const ob = res.result; console.log('empInfo', ob); if (ob != null) { saveToStorage(storage, CurrentUserProfile, ob); Actions.auth(); } }) .catch(() => { console.log("error occured"); }); } catch (error) { console.log(error); } } openConfirm = (show) => { this.setState({ showConfirm: show }); } optionYes = () => { this.openConfirm(false); } optionNo = () => { this.openConfirm(false); } isConfirm() { this.openConfirm(true); } render() { return ( <View style={styles.container}> {this.state.loading ? (<ActivityIndicator size="large" color="#1B7F67" style={{ left: 0, right: 0, bottom: 0, top: 0, justifyContent: 'center', alignContent: 'center', }} />) : null} <View style={[styles.TextInputView, { marginBottom: 10 }]}> <Entypo name="old-mobile" size={20} color="#4b4b4b" style={styles.InputIcon} /> <TextInput style={styles.TextInput} keyboardType="numeric" placeholder="Your Mobile Number" placeholderTextColor="#bcbcbc" underlineColorAndroid="transparent" returnKeyType="next" autoCorrect={false} onChangeText={this.changeUsrNameHandler} value={this.state.userName} onSubmitEditing={() => this.refs.txtPassword.focus()} /> </View> <View style={styles.TextInputView}> <Feather name="lock" size={20} color="#4b4b4b" style={styles.InputIcon} /> <TextInput style={styles.TextInput} placeholder="Your Password" keyboardType="numeric" placeholderTextColor="#bcbcbc" underlineColorAndroid="transparent" onChangeText={this.changePassNameHandler} returnKeyType="go" secureTextEntry autoCorrect={false} ref={"txtPassword"} /> </View> <TouchableOpacity style={styles.LoginButton} onPress={() => this.onPressSubmitButton(this.state.userName, this.state.password)}> <View style={{ alignItems: 'flex-start', flexDirection: 'row' }}> </View> <View style={{ alignItems: 'center' }}> <Text style={styles.TextStyle}> LOGIN </Text> </View> <View style={{ alignItems: 'flex-end', marginRight: 10, }}> <Entypo name="chevron-right" size={20} color="#ffffff" /> </View> </TouchableOpacity> <View style={[styles.LoginButton, style = { backgroundColor: '#ffffff', }]}> <TouchableOpacity onPress={this.signUp} style={{ alignItems: 'center', width: (width * 66) / 100, height: "100%", justifyContent: 'center', backgroundColor: '#f1f4f6', borderRadius: 5, }}> <Text style={[styles.TextStyle, style = { color: "#6d6d6d" }]}> REGISTER </Text> </TouchableOpacity> <Image style={{ width: 40, height: 40 }} source={require('../../assets/images/RegCall.png')}> </Image> </View> <ConfirmDialog title="Message" message={this.state.alertMessage} onTouchOutside={() => this.openConfirm(false)} visible={this.state.showConfirm} positiveButton={ { title: "OK", onPress: this.optionYes, titleStyle: { color: "black", colorDisabled: "aqua", } } } /> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, TextInputView: { width: (width * 80) / 100, height: 45, backgroundColor: '#f1f4f6', borderRadius: 5, flexDirection: 'row', alignItems: 'center' }, InputIcon: { justifyContent: "flex-start", marginHorizontal: 10, }, TextInput: { flex: 1, color: "#3D6AA5", paddingRight: 3, }, LoginButton: { backgroundColor: '#316fde', borderRadius: 5, height: 45, marginTop: 20, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', width: (width * 80) / 100, }, TextStyle: { fontSize: 13, fontFamily: "Montserrat_Bold", color: "#ffffff" }, }) <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/DataAccess/DepartmentDataAccess.cs using TrillionBitsPortal.Common; using TrillionBitsPortal.Common.Models; using Microsoft.Practices.EnterpriseLibrary.Data; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using TrillionBits.DataAccess.Common; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Mappers; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.DataAccess { public class DepartmentDataAccess : BaseDatabaseHandler, IDepartment { public DepartmentDataAccess() { } public List<Department> GetDepartmentByCompanyId(string companyId) { string err = string.Empty; string sql = @"SELECT * from ResourceTracker_Department where CompanyId='" + companyId + "'"; var results = ExecuteDBQuery(sql, null, DepartmentMapper.ToDepartmentModel); return results.Any() ? results : null; } public Department Create(Department model,string userId) { var err = string.Empty; Database db = GetSQLDatabase(); var returnId = -1; using (DbConnection conn = db.CreateConnection()) { conn.Open(); DbTransaction trans = conn.BeginTransaction(); try { returnId = SaveDepartment(model, db, trans); trans.Commit(); } catch (Exception ex) { trans.Rollback(); err = ex.Message; } if ( returnId >= 1 ) { string sql = @"select * from ResourceTracker_Department where Id in (select top 1 Id from ResourceTracker_Department where CompanyId='" + model.CompanyId + "' order by Id desc)"; var results = ExecuteDBQuery( sql , null , DepartmentMapper.ToDepartmentModel ); model = results.Any() ? results.FirstOrDefault() : null; } } return model; } public ResponseModel UpdateDepartment(Department model) { var err = string.Empty; Database db = GetSQLDatabase(); using (DbConnection conn = db.CreateConnection()) { conn.Open(); DbTransaction trans = conn.BeginTransaction(); try { const string sql = @"UPDATE ResourceTracker_Department SET DepartmentName = @DepartmentName WHERE Id=@Id"; var queryParamList = new QueryParamList { new QueryParamObj { ParamName = "@DepartmentName", ParamValue = model.DepartmentName}, new QueryParamObj { ParamName = "@Id", ParamValue = model.Id} }; DBExecCommandEx(sql, queryParamList, ref err); trans.Commit(); } catch (Exception ex) { trans.Rollback(); err = ex.Message; } } return new ResponseModel { Success = string.IsNullOrEmpty(err) }; } public int SaveDepartment(Department model, Database db, DbTransaction trans) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CompanyId", ParamValue =model.CompanyId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@DepartmentName", ParamValue =model.DepartmentName}, }; const string sql = @"INSERT INTO ResourceTracker_Department(CompanyId,DepartmentName) VALUES(@CompanyId,@DepartmentName)"; return DBExecCommandExTran(sql, queryParamList, trans, db, ref errMessage); } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Common/DbUtility/ErrorLog.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.Common { public class ErrorLog : BaseModel { public string ActionName { get; set; } public string AppVersion { get; set; } public string BranchId { get; set; } public string CompanyId { get; set; } public string ControllerName { get; set; } public string ErrorCode { get; set; } public string ErrorMessage { get; set; } public string ErrorType { get; set; } public string Exception { get; set; } public int Id { get; set; } public bool IsEmailRequired { get; set; } public string ItemName { get; set; } public string MethodName { get; set; } public string ModuleName { get; set; } public DateTime RecordTime { get; set; } public string RefNumber { get; set; } public string ServiceName { get; set; } public string UserId { get; set; } public ErrorLog() { } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/ChangePasswordApiController.cs using TrillionBitsPortal.Common; using TrillionBitsPortal.Web.Models; using System.Web.Http; using TrillionBits.ResourceTracker; using TrillionBitsPortal.ResourceTracker.Interfaces; namespace TrillionBitsPortal.Web.Controllers.Api { public class ChangePasswordApiController : BaseApiController { [HttpPost] public IHttpActionResult Post(LocalPasswordModel model) { if (ModelState.IsValid) { var response = RTUnityMapper.GetInstance<IUserCredential>().ChangePassword(model.UserName, CryptographyHelper.CreateMD5Hash(model.ConfirmPassword)); return Ok(response); } return Ok(new { Success = false, Message = "Oops!try again." }); } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Mappers/NoticeBoardMapper.cs using TrillionBitsPortal.Common; using System; using System.Collections.Generic; using System.Data.Common; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Mappers { public static class NoticeBoardMapper { public static List<NoticeBoard> ToNoticeBoardModel( DbDataReader readers ) { if ( readers==null ) return null; var models = new List<NoticeBoard>(); while ( readers.Read() ) { var model = new NoticeBoard { Id=Convert.ToString( readers["Id"] ) , Details=Convert.IsDBNull( readers["Details"] ) ? string.Empty : Convert.ToString( readers["Details"] ) , PostingDate=Convert.IsDBNull( readers["PostingDate"] ) ? string.Empty : Convert.ToDateTime( readers["PostingDate"] ).ToString() , ImageFileName=Convert.IsDBNull( readers["ImageFileName"] ) ? string.Empty : Convert.ToString( readers["ImageFileName"] ) , CreatedBy=Convert.IsDBNull( readers["CreatedBy"] ) ? string.Empty : Convert.ToString( readers["CreatedBy"] ) , CreateDate=Convert.IsDBNull( readers["CreateDate"] ) ? string.Empty : Convert.ToDateTime( readers["CreateDate"] ).ToString(Constants.DateLongFormat) , }; models.Add( model ); } return models; } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Interfaces/IEmployeeTask.cs using TrillionBitsPortal.Common.Models; using System.Collections.Generic; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.Interfaces { public interface IEmployeeTask { ResponseModel SaveTaskGroup(TaskGroupModel model); ResponseModel SaveToDoTask(ToDoTaskModel model); ResponseModel ToDoTaskAsDone(string id); ResponseModel ToDoTaskShare(string taskId, List<string> userList); ResponseModel SaveTask(TaskModel model); ResponseModel SaveTaskAttachment(TaskAttachment model); List<TaskAttachment> GetTaskAttachments(string taskId); List<TaskGroupModel> GetGroups(string companyId); List<ToDoTaskModel> GetToDoList(string userId); List<TaskModel> GetTaskList(TaskModel sModel); List<TaskModel> GetRelatedToMeTaskList(string userId); ResponseModel DeleteTask(string id); TaskModel GetTaskDetails(string id); } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/PortalUserViewModel.cs namespace TrillionBitsPortal.ResourceTracker.Models { public class PortalUserViewModel { public string Id { get; set; } public string Email { get; set; } public string Gender { get; set; } public string UserName { get; set; } public string UserFullName { get; set; } public string PhoneNumber { get; set; } public string UserType { get; set; } public string LoggedOn { get; set; } public string ImageFileName { get; set; } public bool IsAutoCheckPoint { get; set; } public string AutoCheckPointTime { get; set; } public string MaximumOfficeHours { get; set; } public string OfficeOutTime { get; set; } public string ImageFileId { get; set; } public string DesignationName { get; set; } public bool IsActive { get; set; } } } <file_sep>/hr Office/HrApp/common/storage.js import Storage from 'react-native-storage'; import { AsyncStorage } from 'react-native'; export const storage = new Storage({ // maximum capacity, default 1000 size: 1000, // Use AsyncStorage for RN apps, or window.localStorage for web apps. // If storageBackend is not set, data will be lost after reload. storageBackend: AsyncStorage, // for web: window.localStorage // expire time, default: 1 day (1000 * 3600 * 24 milliseconds). // can be null, which means never expire. //defaultExpires: 60000,//1000 * 3600 * 24 * 7, defaultExpires: 1000 * 3600 * 24 * 7, // cache data in the memory. default is true. enableCache: true, // if data was not found in storage or expired data was found, // the corresponding sync method will be invoked returning // the latest data. // sync: { // // we'll talk about the details later. // } }); export const CurrentUserProfile = 'CurrentUserProfile'; export const CompanyCacheId = 'CompanyCacheId'; export const saveToStorage = (storage, key, data) => { storage.save({ key, // Note: Do not use underscore("_") in key! data }); } export const loadFromStorage = async (storage, key) => { return await storage.load({ key, // autoSync(default true) means if data not found or expired, // then invoke the corresponding sync method autoSync: true, // syncInBackground(default true) means if data expired, // return the outdated data first while invoke the sync method. // It can be set to false to always return data provided by sync method when expired.(Of course it's slower) syncInBackground: true }) .then(ret => { return ({ isSuccess: true, item: ret }) }) .catch(err => { console.log(err.message); return ({ isSuccess: false, message: err }) }); } export const removeFromStorage = (storage, key) => { storage.remove({ key }); } <file_sep>/hr Office/HrApp/common/loading.js import React from 'react'; import { ProgressDialog } from 'react-native-simple-dialogs'; const Loading = ({ showProgress }) => { return ( <ProgressDialog title="Progress." activityIndicatorColor="blue" activityIndicatorSize="large" animationType="slide" message="Please, wait..." visible={showProgress} /> ); }; export { Loading };<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/AzureService/IFileStorageService.cs using TrillionBitsPortal.Common; using System.IO; namespace TrillionBitsPortal.Web.AzureService { public interface IFileStorageService { void Upload(Stream stream, string blobName, AzureStorageContainerType type); void Delete(string blobName, AzureStorageContainerType type); bool BlobExistsOnCloud(AzureStorageContainerType type, string blobName); } } <file_sep>/hr Office/HrApp/components/Screen/attendance/DailyAttendance.js import React, { Component } from 'react'; import { loadFromStorage, storage, CurrentUserProfile } from "../../../common/storage"; import AdminTodayAttendance from '../attendance/AdminTodayAttendance'; import DailyAttendances from '../UserScreen/attendance/DailyAttendance'; export default class DailyAttendance extends Component { constructor(props) { super(props); this.state = { userType: 'admin' } } async componentDidMount() { var userDetails = await loadFromStorage(storage, CurrentUserProfile); this.setState({ userType: userDetails.item.UserType }) global.userType=userDetails.item.UserType; }; render() { if(this.state.userType=='admin'){ return (<AdminTodayAttendance/>); } else{ return (<DailyAttendances/>) } }; }<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/DataAccess/UserMapper.cs using System; using System.Collections.Generic; using System.Data.Common; using TrillionBitsPortal.Common.Models; namespace TrillionBitsPortal.ResourceTracker.DataAccess { public static class UserMapper { public static List<UserCredentialModel> ToUserFullDetails(DbDataReader readers) { if (readers == null) return null; var models = new List<UserCredentialModel>(); while (readers.Read()) { var model = new UserCredentialModel { Id = Convert.IsDBNull(readers["Id"]) ? string.Empty : Convert.ToString(readers["Id"]), FullName = Convert.IsDBNull(readers["FullName"]) ? string.Empty : Convert.ToString(readers["FullName"]), Email = Convert.IsDBNull(readers["Email"]) ? string.Empty : Convert.ToString(readers["Email"]), ContactNo = Convert.IsDBNull(readers["ContactNo"]) ? string.Empty : Convert.ToString(readers["ContactNo"]), CreatedAt = Convert.IsDBNull(readers["CreatedAt"]) ? string.Empty : Convert.ToDateTime(readers["CreatedAt"]).ToShortDateString(), UserTypeId = Convert.ToInt32(readers["UserTypeId"]), IsActive = Convert.ToBoolean(readers["IsActive"]), OrganizationId = Convert.IsDBNull(readers["OrganizationId"]) ? string.Empty : Convert.ToString(readers["OrganizationId"]), LoginID = Convert.IsDBNull(readers["LoginID"]) ? string.Empty : Convert.ToString(readers["LoginID"]), Password = Convert.IsDBNull(readers["Password"]) ? string.Empty : Convert.ToString(readers["Password"]) }; models.Add(model); } return models; } } } <file_sep>/hr Office/HrApp/components/MenuDrawer/DrawerContent.js import React, { Component } from 'react'; import { ScrollView, StatusBar, Platform, Text, View, TouchableOpacity, Image, Alert, AsyncStorage } from 'react-native'; import { Actions } from 'react-native-router-flux'; import { DrawerContentStyle } from './DrawerContentStyle'; import { Feather, } from '@expo/vector-icons'; const logOut = () => { global.DrawerContentId = 8; Alert.alert( 'Log Out' , 'Log Out From The App?', [{ text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel' }, { text: 'OK', style: 'ok', onPress: async () => { await AsyncStorage.clear(); Actions.login(); } },], { cancelable: false } ) return true; }; const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; const drawerSelectedOption = (id) => { global.DrawerContentId = id switch (id) { case 1: //Attendance global.DrawerContentId = 1; break; // case 2: //My Panel // global.DrawerContentId = 2; // break; case 2: //Tasks global.DrawerContentId = 2; break; case 3: //Board global.DrawerContentId = 3; break; case 4: //leave global.DrawerContentId = 4; break; case 6: //Reports global.DrawerContentId = 6; break; case 7: //Notice Board global.DrawerContentId = 7; break; case 8: //Leader Board global.DrawerContentId = 8; break; case 9: //Settings global.DrawerContentId = 9; break; } }; const DailyAttendanceCombo = () => { Actions.DailyAttendance(); drawerSelectedOption(1); } const TasksCombo = () => { if (userType == "admin") { Actions.TabnavigationInTasks(); drawerSelectedOption(2); } else { Actions.userTask(); drawerSelectedOption(2); } } const TasksboardCombo = () => { if (userType == "admin") { Actions.TaskBoardScreen(); drawerSelectedOption(3); } else { Actions.MyPanel(); drawerSelectedOption(3); } } const MyPanelCombo = () => { Actions.MyPanel(); drawerSelectedOption(2); } const LeavesCombo = () => { if (userType == "admin") { Actions.LeaveList(); drawerSelectedOption(4); } else { Actions.LeaveListUser(); drawerSelectedOption(4); } } const ReportsCombo = () => { Actions.ReportScreen(); drawerSelectedOption(6); } const NoticeCombo = () => { if (userType == "admin") { Actions.Notice(); drawerSelectedOption(7); } else { Actions.NoticeUser(); drawerSelectedOption(7); } } const LeaderBoardCombo = () => { Actions.LeaderBoard(); drawerSelectedOption(8); } const SettingsCombo = () => { if (userType == "admin") { Actions.SettingScreen(); drawerSelectedOption(9); } else { drawerSelectedOption(9); logOut(); } } export { DailyAttendanceCombo, TasksCombo, LeavesCombo, ReportsCombo, NoticeCombo, SettingsCombo, drawerSelectedOption, TasksboardCombo, } export default class DrawerContent extends React.Component { constructor(props) { super(props); this.state = { selectedId: 1, } } async componentDidMount() { global.DrawerContentId = 1; } getMyPanel() { if (global.userType == "user") { return (<TouchableOpacity onPress={() => MyPanelCombo()} style={ global.DrawerContentId == 2 ? DrawerContentStyle.itemContainerSelected : DrawerContentStyle.itemContainer}> <Feather name="map" size={24} color="#218f6f" style={{ transform: [{ scaleX: -1 }] }} /> <Text style={DrawerContentStyle.itemTextStyle}> My panel </Text> </TouchableOpacity>) } } render() { return ( <View style={DrawerContentStyle.container}> {/* <StatusBarPlaceHolder /> */} <View style={[DrawerContentStyle.logoImage, { marginBottom: 2, marginTop: 2, justifyContent: "flex-start", alignItems: 'center' } ]}> <Image resizeMode='contain' style={{ height: 90, }} source={require('../../assets/images/logo_ns.png')} > </Image> </View> {/* <View style={DrawerContentStyle.emptyLineStyle}> </View> <View style={{ marginBottom: 10, }}> </View> */} <ScrollView showsVerticalScrollIndicator={false}> <TouchableOpacity onPress={() => DailyAttendanceCombo()} style={ global.DrawerContentId == 1 ? DrawerContentStyle.itemContainerSelected : DrawerContentStyle.itemContainer}> <Image resizeMode='contain' style={{ width: 23, height: 23, }} source={require('../../assets/images/home.png')} > </Image> <Text style={DrawerContentStyle.itemTextStyle}> Attendance </Text> </TouchableOpacity> {/* {this.getMyPanel()} */} <TouchableOpacity onPress={() => TasksCombo()} style={ global.DrawerContentId == 2 ? DrawerContentStyle.itemContainerSelected : DrawerContentStyle.itemContainer}> <Image resizeMode='contain' style={{ width: 23, height: 23, }} source={require('../../assets/images/task.png')} > </Image> {global.userType == "admin" ? <Text style={DrawerContentStyle.itemTextStyle}> All Tasks </Text> : <Text style={DrawerContentStyle.itemTextStyle}> Tasks </Text>} </TouchableOpacity> <TouchableOpacity onPress={() => TasksboardCombo()} style={ global.DrawerContentId == 3 ? DrawerContentStyle.itemContainerSelected : DrawerContentStyle.itemContainer}> {global.userType == "admin" ? <Image resizeMode='contain' style={{ width: 23, height: 23, }} source={require('../../assets/images/Board_s.png')} > </Image> : <Feather name="map" size={24} color="#218f6f" style={{ transform: [{ scaleX: -1 }] }} /> } {global.userType == "admin" ? <Text style={DrawerContentStyle.itemTextStyle}> Task Board </Text> : <Text style={DrawerContentStyle.itemTextStyle}> My Panel </Text> } </TouchableOpacity> <TouchableOpacity onPress={() => LeavesCombo()} style={ global.DrawerContentId == 4 ? DrawerContentStyle.itemContainerSelected : DrawerContentStyle.itemContainer}> <Image resizeMode='contain' style={{ width: 23, height: 23, }} source={require('../../assets/images/leaves.png')} > </Image> <Text style={DrawerContentStyle.itemTextStyle}> Leaves </Text> </TouchableOpacity> <TouchableOpacity onPress={() => ReportsCombo()} style={ global.DrawerContentId == 6 ? DrawerContentStyle.itemContainerSelected : DrawerContentStyle.itemContainer}> <Image resizeMode='contain' style={{ width: 23, height: 23, }} source={require('../../assets/images/report.png')} > </Image> <Text style={DrawerContentStyle.itemTextStyle}> Reports </Text> </TouchableOpacity> <TouchableOpacity onPress={() => NoticeCombo()} style={ global.DrawerContentId == 7 ? DrawerContentStyle.itemContainerSelected : DrawerContentStyle.itemContainer}> <Image resizeMode='contain' style={{ width: 23, height: 23, }} source={require('../../assets/images/notice.png')} > </Image> <Text style={DrawerContentStyle.itemTextStyle}> Notice Board </Text> </TouchableOpacity> <TouchableOpacity onPress={() => LeaderBoardCombo()} style={ global.DrawerContentId == 8 ? DrawerContentStyle.itemContainerSelected : DrawerContentStyle.itemContainer}> <Feather name="activity" size={24} color="#218f6f" style={{ transform: [{ scaleX: -1 }] }} /> <Text style={DrawerContentStyle.itemTextStyle}> Leader Board </Text> </TouchableOpacity> <TouchableOpacity onPress={() => SettingsCombo()} style={ global.DrawerContentId == 9 ? DrawerContentStyle.itemContainerSelected : DrawerContentStyle.itemContainer}> {global.userType == "admin" ? <Image resizeMode='contain' style={{ width: 23, height: 23, }} source={require('../../assets/images/setting.png')} > </Image> : <Feather name="log-out" size={25} color="#c24a4a" /> } {global.userType == "admin" ? <Text style={DrawerContentStyle.itemTextStyle}> Settings </Text> : <Text style={DrawerContentStyle.itemTextStyle}> Logout </Text>} </TouchableOpacity> </ScrollView> </View > ) } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/EmployeeUser.cs namespace TrillionBitsPortal.ResourceTracker.Models { public class EmployeeUser : BaseModel { public string UserId { get; set; } public string UserName { get; set; } public string Designation { get; set; } public string PhoneNumber { get; set; } public string ImageFileName { get; set; } public string ImageFileId { get; set; } public int CompanyId { get; set; } public int DepartmentId { get; set; } public bool IsAutoCheckPoint { get; set; } public string AutoCheckPointTime { get; set; } public string MaximumOfficeHours { get; set; } public string OfficeOutTime { get; set; } public string DepartmentName { get; set; } public bool? IsActive { get; set; } } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/RTUnityMapper.cs using Microsoft.Practices.Unity; using TrillionBitsPortal.ResourceTracker.DataAccess; using TrillionBitsPortal.ResourceTracker.Interfaces; namespace TrillionBits.ResourceTracker { public class RTUnityMapper { private static IUnityContainer _container; public static void RegisterComponents(IUnityContainer container) { _container = container; container.RegisterType<IDepartment, DepartmentDataAccess>(new ContainerControlledLifetimeManager()); container.RegisterType<ICompany, CompanyDataAccess>(new ContainerControlledLifetimeManager()); container.RegisterType<IEmployee, EmployeeDataAccess>(new ContainerControlledLifetimeManager()); container.RegisterType<INoticeBoard, NoticeBoardDataAccess>(new ContainerControlledLifetimeManager()); container.RegisterType<IEmployeeLeave, EmployeeLeaveDataAccess>(new ContainerControlledLifetimeManager()); container.RegisterType<IAttendance, AttendanceDataAccess>(new ContainerControlledLifetimeManager()); container.RegisterType<IUserCredential, UserCredentialDataAccess>(new ContainerControlledLifetimeManager()); container.RegisterType<IEmployeeTask, EmployeeTaskDataAccess>(new ContainerControlledLifetimeManager()); } public static T GetInstance<T>() { try { return _container.Resolve<T>(); } catch (ResolutionFailedException exception) { } return default(T); } } } <file_sep>/hr Office/HrApp/components/Screen/UserScreen/leaves/LeaveApplyStyle.js import { StyleSheet, Dimensions } from 'react-native'; const { width, height } = Dimensions.get('window'); export const LeaveApplyStyle = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', }, headerContainer: { flexDirection: 'row', height: 60, paddingTop: 0, backgroundColor: 'white', shadowColor: 'rgba(181,181,181,0.02)', shadowOffset: { width: 0, height: -2 }, elevation: 10, shadowRadius: 8, shadowOpacity: 0.3, alignItems: 'center', paddingHorizontal: 10, justifyContent: 'space-between', borderBottomRightRadius: 10, borderBottomLeftRadius: 10 }, renderLeaveArrayListTextStyle: { textAlign: 'center', fontWeight: 'bold', fontSize: 20, color: '#535353' }, headerTitle: { alignItems: 'flex-start', flexDirection: 'row' }, headerText: { fontWeight: 'bold', fontSize: 20, color: '#141414', marginTop: 3, }, loaderIndicator: { position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, justifyContent: 'center', alignContent: 'center', }, headerTextRight: { alignItems: 'flex-end', marginRight: 10, }, mainBodyStyle: { padding: 10, flexDirection: 'column', backgroundColor: '#ffffff', }, mainBodyTopStyle: { flexDirection: 'row', justifyContent: 'flex-start', padding: 5, paddingLeft: 15, paddingRight: 15, }, fromTextStyle: { width: (width * 50) / 100, justifyContent: 'flex-start', fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#cfcfcf" }, datePickerRowStyle: { flexDirection: 'row', justifyContent: 'flex-start', padding: 5, paddingLeft: 10, paddingRight: 10, }, datePickerLeftStyle: { width: (width * 50) / 100, justifyContent: 'flex-start', }, datePickerWidth: { width: (width * 40) / 100, }, datePickerLeftdateInput: { borderRadius: 8, backgroundColor: "#f5f7fb", height: 30, width: '100%', marginRight: 25, }, datePickerLeftdateText: { color: "#848f98", fontFamily: "Montserrat_SemiBold", fontWeight: "bold", fontStyle: "normal", }, datePickerRightStyle: { width: (width * 50) / 100, justifyContent: 'flex-end', }, toTextStyle: { width: (width * 50) / 100, justifyContent: 'flex-end', fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#cfcfcf" }, leaveTypeRowStyle: { flexDirection: 'column', justifyContent: 'flex-start', padding: 5, paddingLeft: 10, width: (width * 50) / 100, }, leaveTypeRowTextStyle: { width: (width * 50) / 100, justifyContent: 'flex-start', fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#cfcfcf", }, leaveDropDownRow: { flexDirection: 'row', justifyContent: 'flex-start', padding: 5, }, leaveDropDownStyle: { width: (width * 50) / 100, height: 37, alignItems: 'center', backgroundColor: "#f5f7fb", justifyContent: 'flex-start', borderRadius: 8, padding: 0, paddingLeft: 10, margin: 0, marginTop: 4, flexDirection: 'row', }, leaveDropDownText: { width: (width * 40) / 100, justifyContent: 'flex-start', color: "#848f98", fontFamily: 'PRODUCT_SANS_BOLD', fontSize: 16, marginTop: 1, borderRightColor: "#ffffff", borderRightWidth: 1.5, }, leaveDropDownIconStyle: { marginTop: 4, marginLeft: 4, justifyContent: 'flex-end', backgroundColor: "#f5f7fb", }, leaveCauseRow: { flexDirection: 'column', justifyContent: 'flex-start', padding: 5, paddingLeft: 10, }, leaveCauseText: { width: (width * 50) / 100, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#cfcfcf", }, leaveTextInputRow: { padding: 5, height: (height * 35) / 100, }, leaveCauseTextInputStyle: { textAlignVertical: "top", fontFamily: "OPENSANS_REGULAR", fontSize: 13, textAlign: "left", height: "40%", paddingHorizontal: 7, paddingVertical: 6, borderRadius: 8, backgroundColor: '#f5f7fb', color: '#2c2930', padding: 5, }, leaveRequestRow: { justifyContent: 'flex-end', }, leaveRequestTouchStyle: { position: 'absolute', bottom: 0, width: "100%", justifyContent: 'center', alignItems: 'center', height: 50, flexDirection: 'row', backgroundColor: "#902ca8" }, leaveRequestTouchText: { justifyContent: 'center', fontSize: 18, textAlign: "center", color: "#ffffff", fontFamily: "PRODUCT_SANS_BOLD", }, dateInput: { borderRadius: 8, backgroundColor: "#f5f7fb", height: 30, width: '100%', marginRight: 25, }, dateText: { color: "#848f98", fontFamily: "Montserrat_SemiBold", fontWeight: "bold", fontStyle: "normal", }, leaveTypeModalMainStyle: { height: "60%", width: "75%", borderRadius: 20, backgroundColor: '#EBEBEB', }, causeText: { width: "60%", justifyContent: 'flex-start', opacity: 0.3, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 12, textAlign: "left", color: "#1a1a1a" }, }); <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/CommonModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrillionBitsPortal.ResourceTracker.Models { public class RowsCount { public int Rows { get; set; } } public class StringReturnModel { public string Value { get; set; } } public class SuccessModel { public bool IsSuccess { get; set; } public string Message { get; set; } } public class ValueCount { public int? TotalCount { get; set; } } } <file_sep>/hr Office/HrApp/services/Leave.js import { postApi, getApi } from "./api"; export const createLeave = async data => postApi("RtLeaveApi/CreateLeave", {}, data); export const acceptrequest = async data => postApi("RtLeaveApi/UpdateLeaveStatus", {}, data); export const GetLeaveList = async (CompanyId) => getApi("RtLeaveApi/GetLeaveByCompanyId?companyId=" + CompanyId, {}, {}); export const GetUserLeaves = async (userId) => getApi("RtLeaveApi/GetUserLeaves?&userId=" + userId, {}, {}); export const LeaveApproved = async (id, userId) => getApi("RtLeaveApi/Approved?id=" + id + "&userId=" + userId, {}, {}); export const LeaveRejected = async (id) => getApi("RtLeaveApi/Rejected?id=" + id, {}, {}); <file_sep>/hr Office/HrApp/components/Screen/reports/ReportStyle.js import { StyleSheet, Platform } from 'react-native'; export const ReportStyle = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f6f7f9', }, headerContainer: { flexDirection: 'row', height: 60, paddingTop: 0, backgroundColor: 'white', shadowColor: 'rgba(181,181,181,0.02)', shadowOffset: { width: 0, height: -2 }, // elevation: 10, shadowRadius: 8, shadowOpacity: 0.3, alignItems: 'center', paddingHorizontal: 10, justifyContent: 'space-between', borderBottomRightRadius: 10, borderBottomLeftRadius: 10 }, headerTitle: { alignItems: 'flex-start', flexDirection: 'row' }, headerText: { fontWeight: 'bold', fontSize: 20, color: '#141414', marginTop: 3, }, loaderIndicator: { position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, justifyContent: 'center', alignContent: 'center', }, headerBar: { justifyContent: 'space-between', backgroundColor: 'white', flexDirection: 'row', padding: 10, borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 0, height: -5 }, // elevation: 10, height: 60, }, backIcon: { justifyContent: 'flex-start', flexDirection: 'row', alignItems: 'center', }, backIconTouch: { padding: 10, flexDirection: 'row', alignItems: 'center' }, headerTitleText: { color: '#4E4E4E', marginTop: 1, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: 'center', }, headerTitle: { padding: 0, paddingLeft: 10, margin: 0, flexDirection: 'row', }, summaryContiner: { paddingTop: 2, paddingBottom: 2, paddingTop: 0, padding: 15, borderRadius: 5, marginBottom: 10, backgroundColor: '#ffffff', margin: 10, elevation:2, }, Summaryhead: { justifyContent: 'space-between', flexDirection: 'row', padding: 5, borderBottomWidth: 1, borderBottomColor: '#f6f7f9', paddingBottom: 8, marginTop: 10, }, SummryheadLeft: { alignItems: 'flex-start' }, SummaryText: { color: '#4b4b4b', fontSize: 12, fontFamily: "Montserrat_Bold",fontSize:16, }, CalanderIconContainer: { alignItems: 'flex-end', flexDirection: 'row', }, monthText: { fontFamily: 'PRODUCT_SANS_BOLD', color: '#4b4b4b', fontSize: 12,fontSize:16, }, valueContainer: { justifyContent: 'space-between', flexDirection: 'row', padding: 5, borderRadius: 10, }, valueContainerFirst: { alignItems: 'flex-start', marginTop: 7, marginBottom: 5,elevation:2, }, IconContainer: { flexDirection: 'row', paddingTop: 1, paddingBottom: 1, marginBottom: 5, }, receiveText: { fontFamily: 'PRODUCT_SANS_REGULAR', color: '#3b875e', marginLeft: 5,fontSize:16, }, depositeText: { fontFamily: 'PRODUCT_SANS_REGULAR', color: '#476182', marginLeft: 5,fontSize:16, }, previousText: { fontFamily: 'PRODUCT_SANS_REGULAR', color: '#919191', marginLeft: 5,fontSize:16, }, DeuBillTExt: { fontFamily: 'PRODUCT_SANS_REGULAR', color: '#c49602', marginLeft: 5,fontSize:16, }, DeuBillTExttask: { fontFamily: 'PRODUCT_SANS_REGULAR', color: 'red', marginLeft: 5,fontSize:16, }, FirstValueText: { fontFamily: 'PRODUCT_SANS_BOLD', color: '#3b875e',fontSize:16, }, SecondValueText: { fontFamily: 'PRODUCT_SANS_BOLD', color: '#476182' ,fontSize:16,}, ThirdValueText: { fontFamily: 'PRODUCT_SANS_BOLD', color: '#919191' ,fontSize:16,}, FourthvalueText: { fontFamily: 'PRODUCT_SANS_BOLD', color: '#c49602',fontSize:16, }, FourthvalueTexttask: { fontFamily: 'PRODUCT_SANS_BOLD', color: 'red',fontSize:16, }, lastpartContiner: { justifyContent: 'space-between', flexDirection: 'row', padding: 5, borderTopWidth: 1, borderTopColor: '#f6f7f9', paddingBottom: 8, }, neetodepositText: { color: '#c74444', fontSize: 12, fontFamily: "Montserrat_Bold" }, }); <file_sep>/hr Office/HrApp/helperComponents/StatusBarHelper.js import React from 'react' import { View, Platform, StatusBar} from 'react-native' const STATUS_BAR_HEIGHT = Platform.OS === 'ios' ? 20 : StatusBar.currentHeight; function StatusBarPlaceHolder() { return ( <View style={{ width: "100%", height: STATUS_BAR_HEIGHT, backgroundColor: '#F3F3F3', }}> <StatusBar/> </View> ); }<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/AzureService/AzureStorageService.cs using System.IO; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using System.Configuration; using System; using TrillionBitsPortal.Common; namespace TrillionBitsPortal.Web.AzureService { public class AzureStorageService : IFileStorageService { //http://www.c-sharpcorner.com/article/upload-download-and-delete-blob-files-in-azure-storage/ public void Upload(Stream stream, string blobName, AzureStorageContainerType type) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings[Constants.AzureBlobConnectionName]); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(type.ToString()); CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName); switch (Path.GetExtension(blobName)) { case ".doc": blockBlob.Properties.ContentType = "application/msword"; break; case ".docx": blockBlob.Properties.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; break; case ".xls": blockBlob.Properties.ContentType = "application/vnd.ms-excel"; break; case ".xlsx": blockBlob.Properties.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; break; case ".ppt": blockBlob.Properties.ContentType = "application/vnd.ms-powerpoint"; break; case ".pptx": blockBlob.Properties.ContentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; break; case ".pdf": blockBlob.Properties.ContentType = "application/pdf"; break; case ".png": blockBlob.Properties.ContentType = "image/png"; break; case ".jpg": case ".jpeg": blockBlob.Properties.ContentType = "image/jpg"; break; case ".mp4": blockBlob.Properties.ContentType = "video/mp4"; break; } blockBlob.UploadFromStream(stream); } public void Delete(string blobName, AzureStorageContainerType type) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings[Constants.AzureBlobConnectionName]); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(type.ToString()); CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName); blockBlob.Delete(); } public bool BlobExistsOnCloud(AzureStorageContainerType type, string blobName) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings[Constants.AzureBlobConnectionName]); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); return blobClient.GetContainerReference(type.ToString()).GetBlockBlobReference(blobName).Exists(); } } }<file_sep>/hr Office/TrillionBitsPortal/TrillionBitsPortal.Web/Controllers/Api/ResourceTracker/RtNoticeBoardApiController.cs using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using TrillionBits.ResourceTracker; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.Web.Controllers.Api.ResourceTracker { public class RtNoticeBoardApiController : BaseApiController { private readonly INoticeBoard _noticeBoardRepository; public RtNoticeBoardApiController() { _noticeBoardRepository = RTUnityMapper.GetInstance<INoticeBoard>(); } [HttpGet] public HttpResponseMessage GetNoticeBoardByCompanyId(int CompanyId) { var result = _noticeBoardRepository.GetNoticeBoardByCompanyId(CompanyId); return Request.CreateResponse(HttpStatusCode.OK, result); } [HttpGet] public HttpResponseMessage GetNoticeBoardById(string Id) { var result = _noticeBoardRepository.GetNoticeBoardById(Id); return Request.CreateResponse(HttpStatusCode.OK, result); } [HttpPost] public IHttpActionResult SaveNoticeBoard(JObject jObject) { dynamic json = jObject; var noticeBoard = new NoticeDepartmentVIewModel { Details = json.Details, ImageFileName = json.ImageFileName, CompanyId = json.CompanyId, CreatedBy = json.CreatedBy }; var response = _noticeBoardRepository.CreateNoticeBoard(noticeBoard); return Ok(response); } } } <file_sep>/hr Office/HrApp/components/Screen/setting/SettingStyle.js import { StyleSheet } from 'react-native'; export const SettingStyle = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f6f7f9', }, headerContainer: { height: 60, backgroundColor: '#ffffff', flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start', borderBottomLeftRadius: 10, borderBottomRightRadius: 10, }, menuStyle: { height: 20, width: 20, marginLeft: 20, marginRight: 15 }, settingText: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 20, textAlign: "center", color: "#101010" }, settingImageCotainer: { justifyContent: 'flex-start', alignItems: 'center', flexDirection: 'row', paddingLeft: 22, paddingVertical: 15, width: "100%", }, porfileImage: { height: 40, width: 40, }, profileName: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, color: '#313131', marginLeft: 15, marginTop: 2 }, middleViewContainer: { flex: 1, margin: 10, borderRadius: 15, backgroundColor: "#ffffff", marginTop: 10, padding: 10, }, lastViewContainer: { flex: 1, margin: 10, borderRadius: 15, backgroundColor: "#ffffff", padding: 10, marginTop: 2 }, profilePhone: { fontFamily: "PRODUCT_SANS_REGULAR", fontSize: 12, color: '#313131', marginLeft: 15, marginTop: 2 }, profileContainer: { justifyContent: 'space-between', flexDirection: 'row', alignItems: 'center', width: "100%", marginTop: 10, }, addPeopleBtn: { backgroundColor: '#319E67', padding: 15, width: 150, alignSelf: 'center', borderRadius: 20, marginVertical: 15, marginTop: "10%" }, inputBoxchagePass: { width: 230, height: "15%", backgroundColor: '#ebebeb', color: '#2c2930', alignSelf: 'center', borderRadius: 10, textAlign: 'center', paddingHorizontal: 10, marginVertical: 8, }, addPeopleBtnchangpass: { backgroundColor: '#3D3159', padding: 10, width: 120, alignSelf: 'center', borderRadius: 20, marginTop: "3%", alignItems: 'center', }, addPeopleBtncom: { backgroundColor: '#319E67', padding: 15, width: 150, alignSelf: 'center', borderRadius: 20, marginVertical: 15, marginTop: "7%" }, addPeopleBtn1: { backgroundColor: '#319E67', padding: 15, width: 150, borderRadius: 20, }, modal2: { height: "70%", width: "85%", borderRadius: 20, }, modalforCreateCompany: { height: "70%", width: "75%", borderRadius: 20, backgroundColor: '#EBEBEB', }, dblModelContent: { paddingVertical: 20, }, dbblModalText: { fontWeight: 'bold', fontSize: 20, color: '#535353' }, modalForEditProfile: { height: "80%", width: "85%", borderRadius: 20, }, modelContent: { alignItems: 'center', // marginBottom: 5, }, inputstyle: { width: 240, height: 40, backgroundColor: '#ddd', color: '#2c2930', paddingHorizontal: 10, alignSelf: 'center', borderRadius: 10, textAlign: 'center', marginVertical: 4, }, modal3: { height: "70%", width: "83%", borderRadius: 20, // justifyContent: 'center', //alignItems: 'center', }, addPeopleImg: { width: 200, height: 100, marginVertical: 10 }, changepassmodalToucah: { marginLeft: 0, marginTop: 0, backgroundColor: '#ddd', width: 30, height: 30, borderRadius: 30, }, editContainer: { alignItems: 'flex-end', marginTop: '3%', }, view1Image: { height: 30, width: 30, paddingLeft: 20 }, iconicToauchable: { flexDirection: 'row', // alignSelf:'center', backgroundColor: '#e3e4e8', borderRadius: 5, paddingVertical: 8, marginVertical: 0, width: 105, alignSelf: "center", marginTop: 4, marginRight: 20, }, iconocStyle: { marginLeft: 12, marginRight: 0, marginTop: 2 }, editProfle: { color: '#313131', textAlign: 'center', fontWeight: 'bold', fontSize: 10, marginTop: 3, marginLeft: 2, }, changePassModalSave: { color: 'white', fontWeight: 'bold' }, inputstylecom: { width: 100, height: 30, backgroundColor: '#ddd', color: '#2c2930', paddingHorizontal: 10, alignSelf: 'center', borderRadius: 10, textAlign: 'center', marginVertical: 8, }, view1: { flex: 1, borderBottomWidth: 1, backgroundColor: '#ffffff', borderBottomColor: '#eaeaea' }, viewchangePass: { flex: 1, backgroundColor: '#ffffff', }, view2: { flex: 1, paddingVertical: 15, width: "100%", flexDirection: 'row', justifyContent: "space-between", alignItems: 'center', }, view3: { paddingLeft: 20, justifyContent: 'flex-start', alignItems: 'center', flexDirection: 'row', }, text1: { fontFamily: "OPENSANS_BOLD", fontSize: 15, textAlign: "left", color: "#4a4a4a", alignItems: 'center', paddingLeft: 15, }, ChevronRightStyle: { justifyContent: "flex-end", alignItems: 'center' }, }) <file_sep>/hr Office/HrApp/services/UserService/settingService.js export const IsNullOrEmpty = (value)=> { if (value === null) { return true; } else if( value ==="") { return true; }else if(value ===''){ return true; } return false; };<file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/DataAccess/NoticeBoardDataAccess.cs using TrillionBitsPortal.Common; using Microsoft.Practices.EnterpriseLibrary.Data; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using TrillionBits.DataAccess.Common; using TrillionBitsPortal.ResourceTracker.Interfaces; using TrillionBitsPortal.ResourceTracker.Mappers; using TrillionBitsPortal.ResourceTracker.Models; namespace TrillionBitsPortal.ResourceTracker.DataAccess { public class NoticeBoardDataAccess : BaseDatabaseHandler, INoticeBoard { private readonly IEmployee _employee; public NoticeBoardDataAccess(IEmployee employee) { _employee = employee; } public List<NoticeBoard> GetNoticeBoardByCompanyId(int companyId) { string err = string.Empty; string sql = @"SELECT nb.* FROM [ResourceTracker_NoticeBoard] as nb WHERE NB.CompanyId=@companyId order by CreateDate Desc"; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@companyId", ParamValue =companyId,DBType=DbType.Int32}, }; var results = ExecuteDBQuery( sql , queryParamList, NoticeBoardMapper.ToNoticeBoardModel ); return results; } public NoticeBoard GetNoticeBoardById(string noticeId ) { string err = string.Empty; string sql = @"select * from ResourceTracker_NoticeBoard Where Id='" + noticeId+"'"; var results = ExecuteDBQuery( sql , null , NoticeBoardMapper.ToNoticeBoardModel ); return results.Any() ? results.FirstOrDefault() : null; } public NoticeDepartmentVIewModel CreateNoticeBoard( NoticeDepartmentVIewModel model) { var err = string.Empty; Database db = GetSQLDatabase(); var returnId = -1; using ( DbConnection conn = db.CreateConnection() ) { conn.Open(); DbTransaction trans = conn.BeginTransaction(); try { model.Id = Guid.NewGuid().ToString(); returnId = SaveToNoticeBoard( model , db , trans ); trans.Commit(); } catch ( Exception ex ) { trans.Rollback(); err = ex.Message; } } return model; } public int SaveToNoticeBoard( NoticeDepartmentVIewModel model , Database db , DbTransaction trans ) { var errMessage = string.Empty; var queryParamList = new QueryParamList { new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Id",ParamValue =model.Id ,DBType = DbType.String}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@Details",ParamValue =model.Details}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@PostingDate", ParamValue =DateTime.UtcNow, DBType=DbType.DateTime}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@ImageFileName", ParamValue =model.ImageFileName}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CreatedBy", ParamValue =model.CreatedBy}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CompanyId", ParamValue =model.CompanyId}, new QueryParamObj { ParamDirection = ParameterDirection.Input, ParamName = "@CreateDate", ParamValue =DateTime.UtcNow, DBType=DbType.DateTime}, }; const string sql = @"INSERT INTO ResourceTracker_NoticeBoard (Id, Details, PostingDate, ImageFileName, CreatedBy, CreateDate,CompanyId) VALUES( @Id, @Details, @PostingDate,@ImageFileName, @CreatedBy, @CreateDate,@CompanyId)"; return DBExecCommandExTran( sql , queryParamList , trans , db , ref errMessage ); } } } <file_sep>/hr Office/HrApp/components/Screen/attendance/DetailsContainer.js import React, { Component } from 'react'; import { View, Image, AsyncStorage } from 'react-native'; import { Router, Stack, Scene, Drawer, SideMenu, } from 'react-native-router-flux' import DailyAttendanceDetails from './DailyAttendanceDetails'; import TaskList from '../tasks/TaskList'; import DailyAttendance from './DailyAttendance'; import LeaveList from '../leaves/LeaveList'; import LandingScreen from '../../../LandingScreen/LandingScreen'; import app from '../../../AppNavigator'; export default class DetailsContainer extends Component { constructor(props) { super(props); this.state = { itemlist: {}, UserId: null, } } async componentDidMount() { await AsyncStorage.setItem("AttendanceUserId", this.props.aItem.UserId); console.log("UserId", this.props.aItem.UserId); this.setState({ itemlist: this.props.aItem }); } render() { return ( <Router> <Stack key="root" hideNavBar={true}> <Scene key="tabbar" tabs={true} tabBarStyle={{ backgroundColor: '#FFFFFF', }} labelStyle={{ fontSize: 14, padding: 5 }} activeBackgroundColor="white" activeTintColor="#26065c" inactiveBackgroundColor=" #FFFFFF" inactiveTintColor="#9e9e9e" > <Scene key="DailyAttendanceDetails" title="Location" hideNavBar={true} icon={({ focused }) => ( focused ? <Image source={require('../../../assets/images/pin_s.png')} style={{ height: 20, width: 20, marginTop: 15 }}></Image> : <Image source={require('../../../assets/images/pin.png')} style={{ height: 20, width: 20, marginTop: 15 }}></Image> )}> <Scene key="DailyAttendanceDetails" component={DailyAttendanceDetails} title="Location" initial /> </Scene> <Scene key="LeaveList" title="LEAVES" hideNavBar={true} icon={({ focused }) => ( focused ? <Image source={require('../../../assets/images/briefcase_s.png')} style={{ height: 20, width: 20, marginBottom: 5, marginTop: 15, }}></Image> : <Image source={require('../../../assets/images/briefcase.png')} style={{ height: 20, width: 20, marginBottom: 5, marginTop: 15, }}></Image> )}> <Scene key="LeaveList" component={LeaveList} title="TASKS" initial /> </Scene> </Scene> <Scene key="LandingScreen" component={LandingScreen} /> <Scene key="DailyAttendance" component={DailyAttendance} /> <Scene key="app" component={app} /> </Stack> </Router> ) } } <file_sep>/hr Office/TrillionBitsPortal/TrillionBits.ResourceTracker/Models/Department.cs using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace TrillionBitsPortal.ResourceTracker.Models { public class Department { [Key] public int Id { get; set; } public int CompanyId { get; set; } public string DepartmentName { get; set; } public string UserId { get; set; } } } <file_sep>/hr Office/HrApp/components/Screen/attendance/DailyAttendanceStyle.js import { StyleSheet, Platform, Dimensions, } from 'react-native'; const { width } = Dimensions.get('window'); export const DailyAttendanceStyle = StyleSheet.create({ container: { flex: 1, backgroundColor: '#f4f6f9', flexDirection: 'column', }, HeaderContent: { justifyContent: 'space-between', backgroundColor: '#fff', flexDirection: 'row', padding: 10, borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 10, height: -5 }, elevation: 10, height: 60, }, HeaderFirstView: { justifyContent: 'flex-start', flexDirection: 'row', marginLeft: 5, alignItems: 'center', }, HeaderMenuicon: { alignItems: 'center' }, HeaderMenuiconstyle: { width: 20, height: 20, }, HeaderTextView: { backgroundColor: 'white', padding: 0, marginLeft: 17, margin: 0, flexDirection: 'row', alignItems: 'center', }, HeaderTextstyel: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: "left", color: "#2a2a2a", }, headerBar: { justifyContent: 'space-between', backgroundColor: 'white', flexDirection: 'row', padding: 10, borderBottomLeftRadius: 10, borderBottomRightRadius: 10, borderColor: '#fff', shadowColor: "#fff", shadowRadius: 3, shadowColor: "black", shadowOpacity: 0.7, shadowOffset: { width: 0, height: -5 }, elevation: 10, height: 60, }, backIcon: { justifyContent: 'flex-start', flexDirection: 'row', alignItems: 'center', }, backIconTouch: { padding: 10, flexDirection: 'row', alignItems: 'center' }, headerTitle: { padding: 0, paddingLeft: 10, margin: 0, flexDirection: 'row', }, headerTitleText: { color: '#4E4E4E', marginTop: 1, fontFamily: "PRODUCT_SANS_BOLD", fontSize: 16, textAlign: 'center', }, ListContainer: { width: "100%", flexDirection: 'row', justifyContent: 'center', marginHorizontal: 5, marginLeft: -2, backgroundColor: "#f5f7fb", }, FlatListContainer: { backgroundColor: '#f5f6f8', flex: 4, paddingHorizontal: 5, }, FlatListTouchableOpacity: { padding: 8, paddingBottom: 13, borderWidth: 0, backgroundColor: '#fff', margin: 1, justifyContent: 'space-between', flexDirection: 'row', alignItems: 'center', borderRadius: 5, borderBottomColor: '#f3f3f3', borderBottomWidth: 2, }, FlatListTouchableOpacitywork: { padding: 15, paddingBottom: 13, borderWidth: 0, flex: 1, margin: 1, justifyContent: 'space-between', flexDirection: 'row', alignItems: 'center', borderRadius: 5, paddingRight: 0, }, FlatListLeft: { alignItems: 'flex-start', flexDirection: 'row', width:"55%" }, FlatListLeftLeave: { alignItems: 'flex-start', flexDirection: 'row', width:"40%" }, FlatListLeftwork: { alignItems: 'flex-start', flexDirection: 'row', width: "40%", flexWrap: 'wrap' }, ImageLocal: { ...Platform.select({ ios: { width: 60, height: 60, borderRadius: 30 }, android: { width: 60, height: 60, borderRadius: 800 }, }), }, ImagestyleFromServer: { ...Platform.select({ ios: { width: 60, height: 60, borderRadius: 30 }, android: { width: 60, height: 60, borderRadius: 30 }, }), }, styleForonlineOfflineIcon: { ...Platform.select({ ios: { width: 20, height: 20, marginLeft: -5, marginTop: -30, }, android: { width: 20, height: 20, marginLeft: -5, marginTop: -30, }, }), }, RightTextView: { flexDirection: 'column', marginTop: 3, flexWrap: 'wrap' }, NameText: { fontFamily: "OPENSANS_BOLD", fontSize: 14, textAlign: "left", color: "#19260c", }, DesignationText: { fontSize: 12, fontFamily: "OPENSANS_REGULAR", textAlign: "left", color: "#8f8f8f" }, DepartmentText: { fontSize: 12, fontFamily: "OPENSANS_REGULAR", textAlign: "left", color: "#b5b5b5" }, TimeContainer: { alignItems: 'flex-end', marginRight: 10, marginTop: 4 }, TimeContainerwork: { alignItems: 'flex-end', alignSelf: 'flex-start' }, TimeContent: { flexDirection: 'row', borderBottomColor: '#437098', borderBottomWidth: StyleSheet.hairlineWidth, padding: 3, }, TimeContentwork: { flexDirection: 'row', padding: 3, }, CheckintimeStyle: { paddingRight: 8, marginTop: 2 }, AntDesignstyle: { paddingRight: 2, }, CheckinTimeText: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 11, textAlign: "left", color: "#076332" }, CheckOutTimeView: { flexDirection: 'row', padding: 3, }, CheckOutTimeViewword: { flexDirection: 'row', padding: 3, }, CheckOutTimetext: { paddingRight: 8, marginTop: 2 }, CheckOutTimeIconstyle: { paddingRight: 2, }, CheckOutTimeText: { fontFamily: "PRODUCT_SANS_BOLD", fontSize: 11, textAlign: "left", color: "#717171" }, CheckOutMissingTimeText:{ fontFamily: "PRODUCT_SANS_BOLD", fontSize: 11, textAlign: "left", color: "#FF0000" }, countBoxContainer: { width: "100%", flexDirection: 'row', justifyContent: 'center', marginHorizontal: 5, marginLeft: -2, backgroundColor: "#f5f7fb", }, countBoxColumn1: { padding: 5, width: (width * 33) / 100, height: 41.1, backgroundColor: "#f5f7fb", justifyContent: 'center', borderRightColor: '#ffffff', flexDirection: 'row', alignItems: 'center', marginTop: 3, marginBottom: 3, borderRightWidth: 2, }, countBoxDetailColumn1: { padding: 5, width: (width * 50) / 100, height: 41.1, backgroundColor: "#f5f7fb", justifyContent: 'center', borderRightColor: '#ffffff', flexDirection: 'row', alignItems: 'center', marginTop: 3, marginBottom: 3, borderRightWidth: 2, }, countBoxColumn1NumberActive: { fontFamily: "Montserrat_Bold", fontSize: 20, textAlign: "center", color: "#3ab875", justifyContent: 'center' }, countBoxColumn1NumberInactive: { fontFamily: "Montserrat_Bold", fontSize: 20, fontStyle: "normal", textAlign: "left", color: "#bbc3c7", }, countBoxColumn1LabelActive: { color: "#3ab875", fontFamily: "Montserrat_Bold", fontSize: 10, fontStyle: "normal", textAlign: "left", paddingTop: 8, paddingLeft: 2, justifyContent: 'flex-start', }, countBoxColumn1LabelInactive: { fontFamily: "Montserrat_Bold", fontSize: 10, fontStyle: "normal", textAlign: "left", color: "#bbc3c7", paddingTop: 8, paddingLeft: 2, justifyContent: 'flex-start', }, countBoxColumn2: { width: (width * 33) / 100, height: 41.1, padding: 5, justifyContent: 'center', flexDirection: 'row', alignItems: 'center', backgroundColor: "#f5f7fb", marginTop: 3, marginBottom: 3, borderRightWidth: 2, borderRightColor: '#ffffff', }, countBoxColumn2NumberActive: { fontFamily: "Montserrat_Bold", fontSize: 20, color: '#6f9fc9', textAlign: 'center', justifyContent: 'center', paddingLeft: 2, fontStyle: "normal", textAlign: "center", marginTop: 1 }, countBoxColumn3NumberActive: { fontFamily: "Montserrat_Bold", fontSize: 20, // fontWeight: "bold", fontStyle: "normal", // lineHeight: 37, // letterSpacing: 0, textAlign: "center", justifyContent: 'center', color: "#e2b24e", }, countBoxColumn3NumberInactive: { fontFamily: "Montserrat_Bold", fontSize: 20, // fontWeight: "bold", fontStyle: "normal", // lineHeight: 37, // letterSpacing: 0, textAlign: "center", justifyContent: 'center', color: "#bbc3c7", }, countBoxColumn2NumberInactive: { fontFamily: "Montserrat_Bold", fontSize: 20, color: '#bbc3c7', textAlign: 'center', justifyContent: 'center', paddingLeft: 2, fontStyle: "normal", textAlign: "center", marginTop: 1 }, countBoxColumn2LabelActive: { fontFamily: "Montserrat_Bold", fontSize: 10, fontStyle: "normal", textAlign: "left", paddingTop: 8, paddingLeft: 2, justifyContent: 'center', color: "#6f9fc9", }, countBoxColumn2LabelInactive: { fontFamily: "Montserrat_Bold", fontSize: 10, fontStyle: "normal", textAlign: "left", paddingTop: 8, paddingLeft: 2, justifyContent: 'center', color: "#bbc3c7", }, countBoxColumn3: { padding: 5, width: (width * 33) / 100, height: 41.1, // backgroundColor: "#cddeee", backgroundColor: "#f5f7fb", justifyContent: 'center', flexDirection: 'row', alignItems: 'center', marginTop: 3, marginBottom: 3 }, countBoxDetailColumn3: { padding: 5, width: (width * 50) / 100, height: 41.1, // backgroundColor: "#cddeee", backgroundColor: "#f5f7fb", justifyContent: 'center', flexDirection: 'row', alignItems: 'center', marginTop: 3, marginBottom: 3 } , countBoxColumn3NumberActive: { fontFamily: "Montserrat_Bold", fontSize: 20, // fontWeight: "bold", fontStyle: "normal", // lineHeight: 37, // letterSpacing: 0, textAlign: "center", justifyContent: 'center', color: "#e2b24e", }, countBoxColumn3NumberInactive: { fontFamily: "Montserrat_Bold", fontSize: 20, // fontWeight: "bold", fontStyle: "normal", // lineHeight: 37, // letterSpacing: 0, textAlign: "center", justifyContent: 'center', color: "#bbc3c7", }, countBoxColumn3LabelActive: { fontFamily: "Montserrat_Bold", fontSize: 10, // fontWeight: "bold", fontStyle: "normal", // lineHeight: 7, // letterSpacing: 0.5, textAlign: "left", color: "#e2b24e", paddingTop: 8, paddingLeft: 1, justifyContent: 'center', paddingLeft: 2, }, countBoxColumn3LabelInactive: { fontFamily: "Montserrat_Bold", fontSize: 10, // fontWeight: "bold", fontStyle: "normal", // lineHeight: 7, // letterSpacing: 0.5, textAlign: "left", color: "#bbc3c7", paddingTop: 8, paddingLeft: 1, justifyContent: 'center', paddingLeft: 2, } })
3c9dab445997174ecbb6a4b3859061f3e0a85175
[ "JavaScript", "C#" ]
136
C#
cendydwierianto/office_HR
d6a66d15ae5de6c74670779cb54c95e8f7840258
a118438d478404b98899e332604ea92a8c903056
refs/heads/master
<file_sep>import interestsToDom from "./interestsToDom"; import buildInterestForm from "./addInterest"; buildInterestForm(); interestsToDom();
7b34ad84d6d52062614087ccd77451799e2d15f7
[ "JavaScript" ]
1
JavaScript
lindseyemaddox/C32-TernaryTraveler
7f33d3c455d0c700899777707b0eed8deb7c69f5
3218da1f1b481add97f302ce9d50ca4efa236048
refs/heads/main
<file_sep>Программа по распознаваю дорожных знаков. <file_sep>#!/usr/bin/python import cv2 import numpy as np from scipy.stats import itemfreq def get_dominant_color(image, n_colors): pixels = np.float32(image).reshape((-1, 3)) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1) flags = cv2.KMEANS_RANDOM_CENTERS flags, labels, centroids = cv2.kmeans( pixels, n_colors, None, criteria, 10, flags) palette = np.uint8(centroids) return palette[np.argmax(itemfreq(labels)[:, -1])] clicked = False def onMouse(event, x, y, flags, param): global clicked if event == cv2.EVENT_LBUTTONUP: clicked = True cameraCapture = cv2.VideoCapture(0) # идентификатор вашей камеры (/ dev / videoN) cv2.namedWindow('camera') cv2.setMouseCallback('camera', onMouse) # Чтение и обработка кадров в цикле success, frame = cameraCapture.read() while success and not clicked: cv2.waitKey(1) success, frame = cameraCapture.read() # Преобразование в серый требуется для ускорения вычислений gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Затем мы размываем весь кадр, чтобы предотвратить случайный ложный круг img = cv2.medianBlur(gray, 37) # В OpenCV встроен алгоритм поиска окружностей. # Наиболее полезным являются minDist (в данном примере это 50) # и параметр {1,2}. Первый представляет расстояние между центрами обнаруженных # кругов, поэтому у нас никогда не бывает нескольких кругов в одном месте. Тем не менее, # слишком большое увеличение этого параметра может помешать обнаружению некоторых объектов. # Увеличение param1 увеличивает количество обнаруженных кругов. Увеличение param2 # падает больше фальшивых кругов. circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 50, param1=120, param2=40) if not circles is None: circles = np.uint16(np.around(circles)) # Выбор самого большого круга max_r, max_i = 0, 0 for i in range(len(circles[:, :, 2][0])): if circles[:, :, 2][0][i] > 50 and circles[:, :, 2][0][i] > max_r: max_i = i max_r = circles[:, :, 2][0][i] x, y, r = circles[:, :, :][0][max_i] # Эта проверка предотвращает сбой программы при попытке индексации списка из # его ассортимент. На самом деле мы вырезали квадрат с целым кругом внутри. if y > r and x > r: square = frame[y-r:y+r, x-r:x+r] dominant_color = get_dominant_color(square, 2) if dominant_color[2] > 100: # Стоп красный, поэтому мы проверяем, много ли красного цвета # в кругу. print("STOP") elif dominant_color[0] > 80: # Другие знаки синего цвета. # Здесь мы вырезаем 3 зоны из круга, затем подсчитываем их # Доминирующий цвет и, наконец, сравнить. zone_0 = square[square.shape[0]*3//8:square.shape[0] * 5//8, square.shape[1]*1//8:square.shape[1]*3//8] zone_0_color = get_dominant_color(zone_0, 1) zone_1 = square[square.shape[0]*1//8:square.shape[0] * 3//8, square.shape[1]*3//8:square.shape[1]*5//8] zone_1_color = get_dominant_color(zone_1, 1) zone_2 = square[square.shape[0]*3//8:square.shape[0] * 5//8, square.shape[1]*5//8:square.shape[1]*7//8] zone_2_color = get_dominant_color(zone_2, 1) if zone_1_color[2] < 60: if sum(zone_0_color) > sum(zone_2_color): print("LEFT") else: print("RIGHT") else: if sum(zone_1_color) > sum(zone_0_color) and sum(zone_1_color) > sum(zone_2_color): print("FORWARD") elif sum(zone_0_color) > sum(zone_2_color): print("FORWARD AND LEFT") else: print("FORWARD AND RIGHT") else: print("N/A") # Рисуем все обнаруженные круги в окне for i in circles[0, :]: cv2.circle(frame, (i[0], i[1]), i[2], (0, 255, 0), 2) cv2.circle(frame, (i[0], i[1]), 2, (0, 0, 255), 3) cv2.imshow('camera', frame) cv2.destroyAllWindows() cameraCapture.release() #https://dropmefiles.com/OKMAB
3094e72fa61a215beefce7838e1d8b72d334d8c3
[ "Markdown", "Python" ]
2
Markdown
latypovvlad/ATS
c375915c2c59698f15374b87971e60c54dccaa38
c2b70366fe59280a50c690d86fbb6a89efc007f4
refs/heads/master
<repo_name>alisalim17/shooter-game<file_sep>/src/pages/game/Bullet.js import { GAME_HEIGHT, GAME_WIDTH } from "../constants"; class Bullet { angle; positionX; positionY; speed = 5; dead = false; constructor(angle, positionX, positionY) { this.angle = angle; this.positionX = positionX; this.positionY = positionY; } update = () => { const x = Math.cos(this.angle) * this.speed; const y = Math.sin(this.angle) * this.speed; this.positionX += x; this.positionY += y; if (this.positionX < 0 || this.positionX > GAME_WIDTH) { this.dead = true; } if (this.positionY < 0 || this.positionY > GAME_HEIGHT) { this.dead = true; } }; draw = (ctx) => { if (!this.dead) { ctx.beginPath(); ctx.arc(this.positionX, this.positionY, 7, 0, 2 * Math.PI); ctx.fillStyle = "#BDFF00"; ctx.fill(); ctx.lineWidth = 0.1; ctx.stroke(); } }; } export default Bullet; <file_sep>/src/pages/utils.js export const getRandomNumber = (max, min) => Math.random() * 7 * max + min; <file_sep>/src/pages/Game.js import React, { useEffect } from "react"; import Player from "./game/Player"; import Enemy from "./game/Enemy"; import { getRandomNumber } from "./utils"; import SCREEN from "./constants"; import { GAME_WIDTH, GAME_HEIGHT } from "./constants"; import Bullet from "./game/Bullet"; function Game({ setScreen, userName }) { let canvas; let ctx; let player; let enemy; let MAX_ENEMY_COUNT = 5; let lastEnemyAtSpawn = Date.now(); useEffect(() => { canvas = document.getElementById("myCanvas"); ctx = canvas.getContext("2d"); player = new Player(GAME_WIDTH / 2, GAME_HEIGHT / 2); let enemies = []; let bullets = []; const firedBulletCb = (angle, positionX, positionY) => { bullets.push(new Bullet(angle, positionX, positionY)); }; setInterval(() => { ctx.clearRect(0, 0, GAME_WIDTH, GAME_HEIGHT); if (player.health === 0) { setScreen(SCREEN.GAME_OVER); return; } player.update(firedBulletCb); player.draw(ctx); if (Date.now() - lastEnemyAtSpawn > 1500) { lastEnemyAtSpawn = Date.now(); enemies.push( new Enemy( getRandomNumber(-100, GAME_WIDTH + 100), getRandomNumber(-100, GAME_HEIGHT + 100) ) ); } enemies.forEach((enemy) => { enemy.update(ctx, player, bullets); enemy.draw(ctx); }); bullets.forEach((bullet) => { bullet.update(); bullet.draw(ctx); }); }, 1000 / 30); }); return ( <canvas id="myCanvas" width={GAME_WIDTH} height={GAME_HEIGHT} style={{ border: "1px solid #000" }} ></canvas> ); } export default Game; <file_sep>/src/App.js import React, { useState } from "react"; import "./App.css"; import Lobby from "./pages/Lobby"; import Game from "./pages/Game"; import SCREEN from "./pages/constants"; function App() { const [screen, setScreen] = useState(SCREEN.LOBBY); const [userName, setUserName] = useState(""); return screen === SCREEN.LOBBY ? ( <Lobby userName={userName} setUserName={setUserName} setScreen={setScreen} /> ) : screen === SCREEN.GAME_OVER ? ( <div style={{ color: "white" }}> <h1>Game Over! </h1> <h2 style={{ textAlign: "center" }}>Score:{window.score}</h2> <a href="/" style={{ textAlign: "center", color: "red" }}> <h3>Restart</h3> </a> </div> ) : ( <Game setScreen={setScreen} userName={userName} /> ); } export default App; <file_sep>/src/pages/game/Player.js import { GAME_WIDTH, GAME_HEIGHT } from "../constants"; import Bullet from "./Bullet"; class Player { lastFireAt = Date.now(); positionX; positionY; speed = 5; angle = 0; ammo = 100; health = 100; constructor(positionX, positionY) { this.positionX = positionX; this.positionY = positionY; } update = (firedBulletCb) => { this.angle = (this.angle - 0.1) % 360; if (window.meter) { if (window.meter.volume * 100 > 10) { if (Date.now() - this.lastFireAt > 500) { this.lastFireAt = Date.now(); firedBulletCb(this.angle, GAME_WIDTH / 2, GAME_HEIGHT / 2); } } } }; deductHealth = () => (this.health -= 10); draw = (ctx) => { ctx.beginPath(); ctx.arc(this.positionX, this.positionY, 20, 0, 2 * Math.PI); ctx.fillStyle = "cornflowerblue"; ctx.fill(); ctx.lineWidth = 0.1; ctx.stroke(); const edgeX = Math.cos(this.angle) * 50; const edgeY = Math.sin(this.angle) * 50; //burada hansinin sin ve ya cos oldugunun ferqi yoxdu //Draw Arrow ctx.stroke(); ctx.beginPath(); ctx.strokeStyle = "#fff"; drawArrow( ctx, GAME_WIDTH / 2, GAME_HEIGHT / 2, GAME_WIDTH / 2 + edgeX, GAME_HEIGHT / 2 + edgeY ); ctx.stroke(); //Draw volume-meter text // if (window.meter) { // ctx.font = "20px Arial"; // ctx.fillStyle = "#000"; // ctx.fillText( // `Volume : ${window.meter.volume * 100}`, // 20, // GAME_HEIGHT - 15 // ); // } //Draw Ammo Text ctx.font = "20px Arial"; ctx.fillStyle = "#fff"; ctx.fillText(this.health, GAME_WIDTH - 60, GAME_HEIGHT - 15); //Draw Arrow Function function drawArrow(context, fromx, fromy, tox, toy) { var headlen = 10; // length of head in pixels var dx = tox - fromx; var dy = toy - fromy; var angle = Math.atan2(dy, dx); context.lineWidth = 1; context.moveTo(fromx, fromy); context.lineTo(tox, toy); context.lineTo( tox - headlen * Math.cos(angle - Math.PI / 6), toy - headlen * Math.sin(angle - Math.PI / 6) ); context.moveTo(tox, toy); context.lineTo( tox - headlen * Math.cos(angle + Math.PI / 6), toy - headlen * Math.sin(angle + Math.PI / 6) ); } }; } export default Player;
62676c6b120877ff3f49c4d295bf48272c2c2ffe
[ "JavaScript" ]
5
JavaScript
alisalim17/shooter-game
0be0c59453a34c789c1a2be96f080a43bbfc1849
6acf1dcea72e5a20d8612ce82f8f696c631e6a16
refs/heads/master
<repo_name>AllramEst83/StatusCodeResponseService<file_sep>/StatusCodeResponseService/Helpers/ResponseServiceConstants.cs using System; using System.Collections.Generic; using System.Text; namespace StatusCodeResponseService.Helpers { public class ResponseServiceConstants { public const string Code = "Code"; public const string Description = "Description"; public const string DefaultCode = "unknow_error_occured"; public const string DefaultDescription = "An unknow error has occured, Please refresh the page"; } } <file_sep>/StatusCodeResponseService/ResponseService.cs using APIErrorHandling; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using StatusCodeResponseService.Helpers; using System; using System.Reflection; using System.Threading.Tasks; namespace StatusCodeResponseService { public static class ResponseService { public static async Task<R> GetResponse<R, T>(T _object, ModelStateDictionary modelState) { Type objectType = _object.GetType(); Type R_instanceType = typeof(R); object[] args = null; bool hasCodeProp = _object.HasProperty(ResponseServiceConstants.Code); bool hasDescriptionProp = _object.HasProperty(ResponseServiceConstants.Description); if (hasCodeProp == true && hasDescriptionProp == true) { PropertyInfo codeInfo = objectType.GetProperty(ResponseServiceConstants.Code); PropertyInfo descriptionInfo = objectType.GetProperty(ResponseServiceConstants.Description); string codeValue = codeInfo.GetValue(_object).ToString(); string descriptionValue = descriptionInfo.GetValue(_object).ToString(); args = new object[] { Errors.AddErrorToModelState(codeValue, descriptionValue, modelState) }; } else { args = new object[] { Errors.AddErrorToModelState( ResponseServiceConstants.DefaultCode, ResponseServiceConstants.DefaultDescription, modelState ) }; } R R_objectInstance = await Task.FromResult((R)Activator.CreateInstance(R_instanceType, args)); return R_objectInstance; } //Helper private static bool HasProperty(this object obj, string propertyName) { return obj.GetType().GetProperty(propertyName) != null; } } }
81df761db231977c8ea90520ba22658ca5ac2501
[ "C#" ]
2
C#
AllramEst83/StatusCodeResponseService
47df36824d1f0b0881ade30fcff6545e9506968c
ec057698f1db981ab310df62bfc98fabd98c944a
refs/heads/master
<file_sep><?php echo 'hello world from elastic-beanstalk'; echo '<h3>It will deploy with pipeline</h3>';
645fec48896e1d81f885e652ff81cf3e7d282eb6
[ "PHP" ]
1
PHP
AnowarCST/test-elastic-beanstalk
922d430bca9b06c27728441914a446ad2f283aa2
6b15138d7b02cbb2022dafcf10555bf98df0c427
refs/heads/master
<repo_name>ibrhaim13/NARCOS<file_sep>/app/Models/Favorite.php <?php namespace App\Models; use App\RecordActiviteable; use Illuminate\Database\Eloquent\Model; class Favorite extends Model { // protected $guarded = []; use RecordActiviteable; public function favorite(){ return $this->morphTo(); } } <file_sep>/app/Http/Controllers/ProfileController.php <?php namespace App\Http\Controllers; use App\Models\Activity; use App\User; use Illuminate\Http\Request; class ProfileController extends Controller { // public function show(User $user){ return view('profile.show',[ "profile"=>$user, //"threads"=>$user->thread()->paginate(5) "activites" =>Activity::feed($user) ]); } } <file_sep>/app/Http/Controllers/ThreadController.php <?php namespace App\Http\Controllers; use App\Filters\ThreadFilter; use App\Models\Channel; use App\Models\Thread; use App\User; use Illuminate\Http\Request; class ThreadController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth')->except('show','index'); } public function index(Channel $channel,ThreadFilter $filter){ // $threads = $this->getThread($channel,$filter); return view('Threads.thread',compact('threads')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // return view('Threads.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $this->validate($request,[ "title" =>"required", "body" =>"required" ]); $thread = Thread::create([ "user_id" =>auth()->user()->id, "title" => $request->title, "body" => $request->body, "channel_id" => $request->channel_id ]); return redirect($thread->path()); } /** * Display the specified resource. * * @param \App\Models\Thread $thread * @return \Illuminate\Http\Response */ public function show($channel_id,Thread $thread) { // return view('Threads.show',[ 'thread' => $thread, "replies" =>$thread->replies()->paginate(2) ]); } /** * Show the form for editing the specified resource. * * @param \App\Models\Thread $thread * @return \Illuminate\Http\Response */ public function edit(Thread $thread) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Thread $thread * @return \Illuminate\Http\Response */ public function update(Request $request, Thread $thread) { // } /** * Remove the specified resource from storage. * * @param \App\Models\Thread $thread * @return \Illuminate\Http\Response */ public function destroy(Channel $channel,Thread $thread) { // $this->authorize('update',$thread); $thread->delete(); return redirect('/home'); } /** * @param Channel $channel * @return \Illuminate\Database\Eloquent\Relations\HasMany|\Illuminate\Database\Query\Builder|static */ protected function getThread(Channel $channel,ThreadFilter $filters) { $threads = Thread::with('channel')->latest()->filter($filters); if($channel->exists){ $threads->where("channel_id",$channel->id); } return $threads->get(); } } <file_sep>/app/RecordActiviteable.php <?php /** * Created by PhpStorm. * User: m_ibr * Date: 13/10/2017 * Time: 7:46 PM */ namespace App; use App\Models\Activity; trait RecordActiviteable { protected static function bootRecordActiviteable() { if(auth()->guest()) return false; foreach (static::getTypeEvents() as $even){ static::$even(function ($model) use ($even){ $model->recordActivity($even); }); } static::deleting(function ($model) { $model->activity()->delete(); }); } protected function recordActivity($event){ $this->Activity()->create([ "user_id" =>auth()->user()->id, "type" => $this->getActivityType($event), ]); } protected static function getTypeEvents(){ return ["created"]; } protected function getActivityType($event){ return $event.'_'. strtolower((new\ReflectionClass($this))->getShortName()); } //RelactionShip public function Activity(){ return $this->morphMany('App\Models\Activity','subject'); } }<file_sep>/app/Models/Reply.php <?php namespace App\Models; use App\Favoriteable; use App\RecordActiviteable; use App\User; use Illuminate\Database\Eloquent\Model; class Reply extends Model { // use Favoriteable , RecordActiviteable; protected $guarded =[]; protected $with =["user"]; protected $appends=['isFavorite']; //RelationShip public function path(){ return "/".$this->thread->path()."#reply-".$this->id; } // RelatioShip public function user(){ return $this->belongsTo(User::class,'user_id'); } public function thread(){ return $this->belongsTo(Thread::class); } } <file_sep>/app/Favoriteable.php <?php /** * Created by PhpStorm. * User: m_ibr * Date: 21/10/2017 * Time: 10:02 AM */ namespace App; use App\Models\Favorite; trait Favoriteable { protected static function bootFavoriteable(){ static::deleting(function ($model){ $model->favorite->each->delete(); }); } public function addFavorite(){ $u=auth()->user()->id; if(!$this->favorite()->where('user_id',$u)->exists()){ return $this->favorite()->create([ "user_id" =>$u, "favorite_id" =>$this->id, "favorite_type" =>get_class($this), ]); }{ $this->favorite()->where('user_id',$u)->delete(); } } public function isFavorite(){ return $this->favorite()->where('user_id',auth()->user()->id)->exists(); } public function getIsFavoriteAttribute(){ return $this->isFavorite(); } public function favorite(){ return $this->morphMany(Favorite::class,'favorite'); } public function unFavorite(){ $attr=["user_id"=> auth()->user()->id]; return $this->favorite()->where($attr)->get()->each->delete(); } }<file_sep>/app/Models/Thread.php <?php namespace App\Models; use App\Favoriteable; use App\RecordActiviteable; use App\User; use Illuminate\Database\Eloquent\Model; class Thread extends Model { // use RecordActiviteable; protected $guarded =[]; protected $with=['user','replies']; //bootable protected static function boot() { parent::boot(); // TODO: Change the autogenerated stub static::addGlobalScope('replyCount',function ($buider){ $buider->withCount('replies'); }); static::deleting(function($thread){ $thread->replies()->delete(); }); } /// public function path(){ return "/threads/{$this->channel->slug}/".$this->id; } public function getRouteKey() { return 'title'; // TODO: Change the autogenerated stub } public function addReply($newReply){ return $this->replies()->create($newReply); } public function scopeFilter($query,$filters){ return $filters->apply($query); } //this function repliced with the global scope public function getCountReply(){ return $this->replies()->count(); } //RelationShip public function user(){ return $this->belongsTo(User::class); } public function replies(){ return $this->hasMany(Reply::class,'thread_id')->withCount('favorite'); } public function channel(){ return $this->belongsTo(Channel::class); } }
8fa2bef6eeaba4a34d32e4b87638585deb93e0ad
[ "PHP" ]
7
PHP
ibrhaim13/NARCOS
c78bcc3e114e4d6e152889dcfb297d6c8e282b92
b867dab5fd17d10f0f2972a7900c6e27147d64a7
refs/heads/master
<repo_name>shun915a/ajax_app<file_sep>/app/javascript/checked.js function check() { const posts = document.querySelectorAll(".post"); // posts配列に.post selectorの要素を格納 posts.forEach(function (post) { // posts配列の要素数分for文を実行 if (post.getAttribute("data-load") != null) { return null; } post.setAttribute("data-load", "true") // setIntervalの再読み込みで複数回呼び出さないように設定 post.addEventListener("click", () => { // クリックした時の動作を設定する const postId = post.getAttribute("data-id"); // postIdのdata-idを取得 const XHR = new XMLHttpRequest(); // XHRを生成 Ajaxを使用可能に XHR.open("GET", `/posts/${postId}`, true); // openでリクエストを初期化、メソッドやパスを指定。 XHR.responseType = "json"; // レスポンスにjson形式を指定 XHR.send(); // sendでリクエストを送信 XHR.onload = () => { // レスポンスなどを受信した時の動きをonloadで設定 if (XHR.status != 200) { // http statusを解析 200は正常な値 alert(`Error ${XHR.status}: ${XHR.statusText}`) return null; エラーをalertし処理を中断 } const item = XHR.response.post; // itemにレスポンスのデータを格納 if (item.checked === true) { // アイテムが既読かcheckedの値を確認 post.setAttribute("data-check", "true"); } else if (item.checked === false) { post.removeAttribute("data-check"); } // データを編集 } }); }); } setInterval(check, 1000); // 1000msごとにcheckを実行
39e5efcdc2a41defdb216669029f9d34b693c805
[ "JavaScript" ]
1
JavaScript
shun915a/ajax_app
9231aa489f00ab6906f0b53e58bfd8cacbe94a2a
a052d3a91d6df24d9cc10aa432b4381b9f3e732b
refs/heads/master
<repo_name>dlrjones/ReqReceipt<file_sep>/OutputManager.cs using System; using System.Collections; using System.Net.Mail; using System.IO; using KeyMaster; using LogDefault; namespace ReqReceipt { class OutputManager { #region ClassVariables private ArrayList reqItems = new ArrayList(); private ArrayList partialCCList = new ArrayList(); private string debugRecipientList = ""; private string reqNo = ""; private string reqDate = ""; private string userName = ""; private string recipientName = ""; private string costCenterManager = ""; private string recipient = ""; private string body = ""; private string attachmentPath = ""; private string extension = ""; private string helpFile = "pmmhelp.txt"; private string unameVarients = ""; private string currentAcctNo = ""; private string[] ccList; private bool debug = false; private bool trace = false; private bool addAttachment = false; private char TAB = Convert.ToChar(9); private Hashtable itemReq = new Hashtable(); private Hashtable itemReqLine = new Hashtable(); private Hashtable itemsThatChanged = new Hashtable(); private Hashtable itemItemNo = new Hashtable(); private Hashtable itemDesc = new Hashtable(); private Hashtable debugCCRecip = new Hashtable(); private Hashtable itemNoDescr = new Hashtable(); private Hashtable reqItem = new Hashtable(); //reqID - itemList (a comma seperated list of all item_no's on a given req) private Hashtable itemDescr = new Hashtable();//itemNo - descr private Hashtable itemQty = new Hashtable(); // key=itemNo valu=qty ordered private Hashtable itemUM = new Hashtable(); // key=itemNo valu=unit of measure private LogManager lm = LogManager.GetInstance(); private int fileCount = 1; #endregion #region parameters public ArrayList ReqItems { set { reqItems = value; } } public string ReqNo { set { reqNo = value; } } public string CurrentAcctNo { set { currentAcctNo = value; } } public string ReqDate { set { reqDate = value; } } public string UserName { set { userName = value; } } public string DebugRecipientList { set { debugRecipientList = value; } } public ArrayList PartialCCList { set { partialCCList = value; } } public string UnameVarients { set { unameVarients = value; } } public string AttachmentPath { set { attachmentPath = value; } } public Hashtable ItemReq { set { itemReq = value; } } public Hashtable ItemReqLine { set { itemReqLine = value; } } public Hashtable ItemsThatChanged { set { itemsThatChanged = value; } } public Hashtable ItemItemNo { set { itemItemNo = value; } } public Hashtable ItemDesc { set { itemDesc = value; } } private Hashtable reqBuyer = null; public Hashtable DebugCCRecip { set { debugCCRecip = value; } } public Hashtable ReqBuyer { set { reqBuyer = value; } } public bool Debug { set { debug = value; } } public bool Trace { set { trace = value; } } #endregion public void SendOutput() { //ProcessManager.SendOutput has a ForEach loop which invokes this method once for each recipient in the recipient list if (trace) { lm.Write("TRACE: OutputManager/SendOutput"); } FormatEmail(); SendMail(); ////////////// } //DEBUG IS OFF --- uncomment line 250 - .Send(mail) private void FormatEmail() { if (trace) { lm.Write("TRACE: OutputManager/FormatEmail"); } string desc = ""; string status = ""; string[] dateTime = reqDate.Split(" ".ToCharArray()); string[] itemList; try { recipientName = GetRecipientName(userName); costCenterManager = GetCCManager(); body = "HEMM has received Requisition # " + reqNo + ", submitted by " + recipientName + " on " + dateTime[0].ToString() + " at " + dateTime[1].ToString() + " " + dateTime[2].ToString() + ", and has started it through the approval process." + "Please contact your buyer group at " + reqBuyer[reqNo] + " if you have any questions." + Environment.NewLine + Environment.NewLine; //these next 4 lines (counting 'foreach' as one line) were added to include the item# and description for the items on each req. GetItemList(); //added to include item# and Descr (reqNo) itemList = reqItem[reqNo].ToString().Split(",".ToCharArray()); body += "ITEM #" + TAB + TAB + "QTY" + TAB + "UM" + TAB + "DESCRIPTION" + Environment.NewLine; foreach (string item in itemList) { if(item.Length > 6) body += item + TAB + itemQty[item.Trim()].ToString().Trim() + TAB + itemUM[item.Trim()].ToString().Trim() + TAB + itemDesc[item.Trim()].ToString().Trim() + Environment.NewLine; else body += item + TAB + TAB + itemQty[item.Trim()].ToString().Trim() + TAB + itemUM[item.Trim()].ToString().Trim() + TAB + itemDesc[item.Trim()].ToString().Trim() + Environment.NewLine; } } catch(Exception ex) { lm.Write("OutputManager/FormatEmail: ERROR: " + ex.Message); } if (!userName.Contains("@")) userName += "@uw.edu"; recipient = userName; } private void SendMail() { if (trace) { lm.Write("TRACE: OutputManager/SendMail"); } try { string[] dbugRecipList = null; string[] dbugCCRecip = null; string logMssg = ""; bool mailError = false; MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.uw.edu"); mail.From = new MailAddress("<EMAIL>"); if (debug) { dbugRecipList = debugRecipientList.Split(",".ToCharArray()); foreach (string recip in dbugRecipList) { if (recip.Equals(recipient)) //this conditional was added to test the app with a few specific recipients { //who would see only their reqs and not all active reqs mail.To.Add(recip); } } } else //not in debug mode { mail.To.Add(recipient); mail.To.Add(costCenterManager); mail.To.Add("<EMAIL>"); } //for certain cost centers send a receipt to the manager - this list comes from the debugCCRecip key in the app.config file if (debug) { try { foreach (object key in debugCCRecip.Keys) { if (key.ToString().Trim().Equals(currentAcctNo.Trim())) { dbugCCRecip = debugCCRecip[key].ToString().Split(",".ToCharArray()); foreach (string emailTO in dbugCCRecip) { mail.To.Add(emailTO); } } } } catch (Exception ex) { lm.Write("EmailTO Error: " + ex.Message); } } mail.Subject = "Requisition " + reqNo + " Receipt"; mail.Body = body + Environment.NewLine + Environment.NewLine + "Thanks," + Environment.NewLine + Environment.NewLine + "PMMHelp" + Environment.NewLine + "UW Medicine Harborview Medical Center" + Environment.NewLine + "Supply Chain Management Informatics" + Environment.NewLine + "206-598-0044" + Environment.NewLine + "<EMAIL>"; mail.ReplyToList.Add("<EMAIL>"); if (addAttachment) { Attachment attachment; attachment = new Attachment(attachmentPath + extension); mail.Attachments.Add(attachment); } SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("pmmhelp", GetKey()); SmtpServer.EnableSsl = true; try { //debug=true sends all emails to <EMAIL> if (!debug && mail.To.Count > 0) { SmtpServer.Send(mail); } logMssg = "OutputManager/SendMail: Sent To " + mail.To + " [Req# " + reqNo + "] mailTO count: " + mail.To.Count; if (debug && mail.To.Count > 0) { logMssg += " (for " + recipient + " " + recipientName + ")"; SmtpServer.Send(mail); //comment this out to prevent emails going to dlrjones while debug = true } } catch (SmtpException ex) { lm.Write("SendMail SmtpException: " + ex.Message + Environment.NewLine + ex.InnerException); mailError = true; } catch (Exception ex) { lm.Write("SendMail Error " + ex.Message + Environment.NewLine + ex.InnerException); mailError = true; } // } if (mailError) {//sometimes SendMail errors out with a message like "The message or signature supplied for verification has been altered" //or "The buffers supplied to a function was too small". Sending it a second time sometimes works. try { SmtpServer.Send(mail); lm.Write("SendMail mail resent: " + mail.To.ToString() + " (for " + recipient + ")"); } catch (Exception ex) { lm.Write("SendMail mailError 2 " + ex.Message + Environment.NewLine + ex.InnerException); logMssg = logMssg.Replace("Sent", "NOT Sent"); } } lm.Write(logMssg); mailError = false; } catch (Exception ex) { string mssg = ex.Message; lm.Write("OutputManager/SendMail: Exception " + mssg); } } private void GetItemList() { //retrieves the hashtables reqItem and itemDescr from the DataSet Manager if (trace) { lm.Write("TRACE: OutputManager/GetItemList"); } DataSetManager dsm = DataSetManager.GetInstance(); reqItem = dsm.ReqItem; itemDesc = dsm.ItemDescr; itemQty = dsm.ItemQty; itemUM = dsm.ItemUM; } private string GetRecipientName(string emailAddr) { string[] email = emailAddr.Split('@'); DataSetManager dsm = DataSetManager.GetInstance(); dsm.GetUserName(email[0].Trim()); return dsm.UserName.Trim(); } private string GetCCManager() { DataSetManager dsm = DataSetManager.GetInstance(); return dsm.GetManagerEmail(currentAcctNo); } private string NonCtlgCheck(string itemNo) {//filter out the non-catalog items -- may not be used if (trace) { lm.Write("TRACE: OutputManager/NonCtlgCheck"); } if (itemNo.Contains("~")) itemNo = "Non Catalog"; return itemNo; } public string GetKey() { if (trace) { lm.Write("TRACE: OutputManager/GetKey"); } //NameValueCollection ConfigData = (NameValueCollection)ConfigurationSettings.GetConfig("appSettings"); //attachmentPath = ConfigData.Get("attachmentPath"); string[] key = File.ReadAllLines(attachmentPath + helpFile); return StringCipher.Decrypt(key[0],"pmmhelp"); } } } <file_sep>/ReadMe.txt This app uses the UWM-HEBI1/uwm_BIAdmin/hmcmm_ReqItemReceipt table. Every night (12:01am or there abouts) the table is truncated (by invoking this app with a parameter of "1"). For each run of this app, with no parameters, a list of reqs submitted since midnight is compared against the hmcmm_ReqItemReceipt table. If the req is already in the table then it is ignored. If it's not in the table then it gets flagged for sending an email to the requestor (the receipt) and then inserted into the table. emails are also sent to the Cost Center managers by searching the UWM-HEBI1/uwm_BIAdmin/[HMC_DeptContactList] table. This table can be updated as needed by truncating the existing table and then importing the new data from the excel spreadsheet (HMC Dept Contact List FY2019.xlsx -- copy in \\Lapis\h_purchasing$\Purchasing\PMM IS data\HEMM Apps\SourceCode\ReqReceipt (GH)) NOTE The Dept Contact List excel file on GitHub is encrypted. Use EncryptAndHash.exe with no key to restore it. // Email Password /* The password for the SendMail portion of this app is stored in the file [attachmentPath]\pmmhelp.txt (find attachmentPath in the config file). The referenced library KeyMaster is used to decrypt the password at run time. There is another app called EncryptAndHash which provides a front end that you can use to change the password when that becomes necessary. The key to the encrypted pw file is pmmhelp and the path to EncryptAndHash is \\Lapis\h_purchasing$\Purchasing\PMM IS data\HEMM Apps\Executables\. */ <file_sep>/DataSetManager.cs using System; using System.Collections; using OleDBDataManager; using System.Data; using System.Collections.Specialized; using System.Configuration; using System.Threading; using LogDefault; namespace ReqReceipt { class DataSetManager { #region class variables private DataSet dsCurrent; private DataSet dsYesterday; private DataSet dsCurrentChangeDates; private Hashtable itemsThatChanged = new Hashtable(); private Hashtable sendReceipt = new Hashtable(); private Hashtable reqDate = new Hashtable(); private Hashtable reqCC = new Hashtable(); private Hashtable reqItem = new Hashtable(); //KEY=reqID VALU=itemList (a comma seperated list of all items on a given req) private Hashtable itemDescr = new Hashtable(); // key=itemNo valu=descr private Hashtable itemQty = new Hashtable(); // key=itemNo valu=qty ordered private Hashtable itemUM = new Hashtable(); // key=itemNo valu=unit of measure private Hashtable reqBuyer = new Hashtable(); // key=reqID valu=list of buyers // private Hashtable codeBuyerEmail = new Hashtable(); // key=buyerCode valu=email of buyer group private ArrayList partialCCList = new ArrayList(); private static string connectStrHEMM = ""; private static string connectStrBIAdmin = ""; private static string buyerTeams = ""; private static string userName = ""; private static NameValueCollection ConfigData = null; protected static ODMDataFactory ODMDataSetFactory = null; private static DataSetManager dsm = null; //rj private static LogManager lm = LogManager.GetInstance(); private static bool debug = false; private static bool trace = false; private ArrayList tableRecord = new ArrayList(); private LogManager lm = LogManager.GetInstance(); #region parameters public DataSet DsYesterday { get { return dsYesterday; } set { dsYesterday = value; } } public ArrayList PartialCCList { set { partialCCList = value; } } public DataSet DSCurrent { get { return dsCurrent; } set { dsCurrent = value; } } public DataSet DSCurrentChangeDates { get { return dsCurrentChangeDates; } set { dsCurrentChangeDates = value; } } public Hashtable SendReceipt { get { return sendReceipt; } set { sendReceipt = value; } } public Hashtable ReqDate { get { return reqDate; } set { reqDate = value; } } public Hashtable ReqBuyer { get { return reqBuyer; } set { reqBuyer = value; } } public Hashtable ReqCC { get { return reqCC; } set { reqCC = value; } } public Hashtable ReqItem { get { return reqItem; } } public Hashtable ItemDescr { get { return itemDescr; } } public Hashtable ItemQty { get { return itemQty; } } public Hashtable ItemUM { get { return itemUM; } } public Hashtable ItemsThatChanged { set { itemsThatChanged = value; } } public string UserName { get { return userName; } } public bool Debug { set { debug = value; } } public bool Trace { set { trace = value; } } public ArrayList TableRecord { get { return tableRecord; } set { tableRecord = value; } } #endregion parameters #endregion public DataSetManager() { InitDataSetManager(); } private void InitDataSetManager() { string[] buyers; string[] codeList; if (trace) { lm.Write("TRACE: DataSetManager/InitDataSetManager"); } lm.Debug = debug; ODMDataSetFactory = new ODMDataFactory(); ConfigData = (NameValueCollection)ConfigurationSettings.GetConfig("appSettings"); connectStrHEMM = ConfigData.Get("cnctHEMM_HMC"); connectStrBIAdmin = ConfigData.Get("cnctBIAdmin_HMC"); //buyerTeams = ConfigData.Get("buyerTeams"); //buyers = buyerTeams.Split(";".ToCharArray()); //foreach(string byer in buyers) //{ // codeList = byer.Split(":".ToCharArray()); // codeBuyerEmail.Add(codeList[0], codeList[1]); //} } public static DataSetManager GetInstance() { if (dsm == null) { CreateInstance(); } return dsm; } private static void CreateInstance() { Mutex configMutex = new Mutex(); configMutex.WaitOne(); dsm = new DataSetManager(); configMutex.ReleaseMutex(); } public void LoadTodaysDataSet() { if (trace) { lm.Write("TRACE: DataSetManager/LoadTodaysDataSet"); } ODMRequest Request = new ODMRequest(); Request.ConnectString = connectStrHEMM; Request.CommandType = CommandType.Text; Request.Command = "Execute ('" + BuildTodayQuery() + "')"; //if (debug) // lm.Write("DataSetManager/LoadTodaysDataSet: " + Request.Command); try { dsCurrent = ODMDataSetFactory.ExecuteDataSetBuild(ref Request); } catch (Exception ex) { lm.Write("DataSetManager/LoadTodaysDataSet: " + ex.Message); } } public void UpdateReqItems() { if (trace) { lm.Write("TRACE: DataSetManager/UpdateReqItems"); } // private Hashtable itemsThatChanged int item = 0; string status = ""; if (debug) lm.Write("DataSetManager/UpdateReqItems"); ODMRequest Request = new ODMRequest(); Request.ConnectString = connectStrBIAdmin; Request.CommandType = CommandType.Text; foreach (object key in itemsThatChanged.Keys) { try { item = Convert.ToInt32(key); status = itemsThatChanged[item].ToString(); Request.Command = "Execute ('" + BuildReqItemUpdateQuery(item, status) + "')"; ODMDataSetFactory.ExecuteDataWriter(ref Request); } catch (Exception ex) { lm.Write("DataSetManager/UpdateReqItems: " + ex.Message); } } } public void TruncateReqItemReceipt() { if (trace) { lm.Write("TRACE: DataSetManager/TruncateReqItemReceipt"); } //remove KILLED and COMPLETE reqItems from the hmcmm_ReqItemReceipt table int item = 0; string status = ""; ODMRequest Request = new ODMRequest(); Request.ConnectString = connectStrBIAdmin; Request.CommandType = CommandType.Text; Request.Command = BuildTruncateReqItemReceipt(); try { ReqReceiptCount(); //the "before" count ODMDataSetFactory.ExecuteNonQuery(ref Request); lm.Write("DataSetManager/TruncateReqItemReceipt: ENQ Complete"); ReqReceiptCount(); //the "after" count } catch (Exception ex) { lm.Write("DataSetManager/TruncateReqItemReceipt: " + ex.Message); } } public void GetUserName(string uid) { ArrayList name = new ArrayList(); ODMRequest Request = new ODMRequest(); Request.ConnectString = connectStrHEMM; Request.CommandType = CommandType.Text; Request.Command = "SELECT NAME FROM USR WHERE LOGIN_ID = '" + uid + "'"; name = ODMDataSetFactory.ExecuteDataReader(ref Request); if (name.Count > 0) userName = name[0].ToString().Trim(); } public string GetManagerEmail(string cc) { string sql = "SELECT EMAIL +'<EMAIL>' " + "FROM [uwm_BIAdmin].[dbo].[HMC_DeptContactList] " + "WHERE CCN = " + cc; // GetCC(reqNo); lm.Write("Cost Center: " + cc); ArrayList email = new ArrayList(); ODMRequest Request = new ODMRequest(); Request.ConnectString = connectStrBIAdmin; Request.CommandType = CommandType.Text; Request.Command = sql; email = ODMDataSetFactory.ExecuteDataReader(ref Request); if (email.Count == 0) email.Add(""); return email[0].ToString().Trim(); } private string GetCC(string reqNo) { string sql = "SELECT ACCT_NO " + "FROM CC " + "JOIN REQ ON REQ.CC_ID = CC.CC_ID " + "WHERE REQ_NO = '" + reqNo + "'"; ArrayList cc = new ArrayList(); ODMRequest Request = new ODMRequest(); Request.ConnectString = connectStrHEMM; Request.CommandType = CommandType.Text; Request.Command = sql; cc = ODMDataSetFactory.ExecuteDataReader(ref Request); if (cc.Count == 0) cc.Add(""); return cc[0].ToString().Trim(); } public void InsertTodaysList() { if (trace) { lm.Write("TRACE: DataSetManager/InsertTodaysList"); } try { /////////THIS IS THE LIST THAT GIVEs THE INITIAL EMAIL RECEIPTS ODMRequest Request = new ODMRequest(); Request.ConnectString = connectStrBIAdmin; Request.CommandType = CommandType.Text; foreach (DataRow drow in dsCurrent.Tables[0].Rows)//dsCurrent is loaded from Program.cs calling dsm.LoadTodaysDataSet(); { //req_id (3) & req_item_id (1) if (partialCCList[0].ToString().Length == 0 || partialCCList.Contains(drow[9].ToString().Trim())) {//if a list of cc's isn't available then do this for all cc's otherwise do it for a specific cc in the list bool goodToGo = CheckExistingRecordCount(Convert.ToInt32(drow[3]), Convert.ToInt32(drow[1])); if (goodToGo) { //insert into hmcmm_ReqItemReceipt if it is NOT already in there - goodToGo being true means //CheckExistingRecordCount found 0 records - anything being inserted here needs to have a receipt sent. //the sendReceipt Hashtable collects these req numbers/usernames if (!sendReceipt.ContainsKey(drow[3].ToString().Trim())) { sendReceipt.Add(drow[3].ToString().Trim(), drow[7]); //key=REQ_ID valu=LOGIN_ID reqDate.Add(drow[3].ToString().Trim(), drow[8]); //key=REQ_ID valu=REQ_DATE reqCC.Add(drow[3].ToString().Trim(), drow[9]); //key=REQ_ID valu=CC LoadItemDescr(drow[3].ToString().Trim()); //key=REQ_ID valu= a comma seperated list of all items on a given req } LoadBuyerList(Request, drow[3].ToString().Trim(),drow[9].ToString().Trim()); //reqBuyer.Add Request.Command = BuildReqItemInsertQuery(drow); ODMDataSetFactory.ExecuteNonQuery(ref Request); } } } lm.Write("sendReceipt Count = " + sendReceipt.Count); } catch (Exception ex) { lm.Write("DataSetManager/InsertTodaysList: " + ex.Message); } } private void LoadBuyerList(ODMRequest Request,string reqID,string cc) { ArrayList buyerCode = new ArrayList(); try { Request.Command = "SELECT EMAIL FROM [dbo].[uwm_CC_TEAM] WHERE COST_CENTER = " + cc; buyerCode = ODMDataSetFactory.ExecuteDataReader(Request); if (!(reqBuyer.ContainsKey(reqID))) reqBuyer.Add(reqID, buyerCode[0].ToString()); } catch (Exception ex) { lm.Write("DataSetManager/LoadBuyerList: " + ex.Message); } } private void LoadItemDescr(string reqID) { //this associates a reqID with the items/descr's on the req //itemDescr is a hashtable where key=itemNo valu=descr //reqItem is a hashtable where key=reqID valu=a comma seperated list of all items on a given req if (trace) { lm.Write("TRACE: DataSetManager/LoadItemDescr"); } DataSet dsItem = new DataSet(); string itemList = ""; //this is a comma seperated list of all item numbers on a given req try { dsItem = GetItemDescrQtyUM(reqID); if (dsItem.Tables[0].Rows.Count > 0) { foreach (DataRow dr in dsItem.Tables[0].Rows) { // reqItem itemDescr if (!itemDescr.ContainsKey(dr.ItemArray[0].ToString().Trim())) { itemDescr.Add(dr.ItemArray[0].ToString().Trim(), dr.ItemArray[1].ToString().Trim()); } if (!itemQty.ContainsKey(dr.ItemArray[0].ToString().Trim())) { itemQty.Add(dr.ItemArray[0].ToString().Trim(), dr.ItemArray[2].ToString().Trim()); } if (!itemUM.ContainsKey(dr.ItemArray[0].ToString().Trim())) { itemUM.Add(dr.ItemArray[0].ToString().Trim(), dr.ItemArray[3].ToString().Trim()); } if (itemList.Length > 0)//once the list gets started, add a comma between items itemList += ","; itemList += dr.ItemArray[0].ToString().Trim(); } reqItem.Add(reqID, itemList); } }catch(Exception ex) { lm.Write("DataSetManager/LoadItemDescr: " + ex.Message); } } private DataSet GetItemDescrQtyUM(string reqID) { if (trace) { lm.Write("TRACE: DataSetManager/GetItemDescr"); } DataSet dsItemDescr = new DataSet(); ODMRequest Request = new ODMRequest(); Request.ConnectString = ConfigData.Get("cnctHEMM_HMC"); Request.CommandType = CommandType.Text; Request.Command = "SELECT ITEM_NO, DESCR,QTY,RIGHT(RTRIM(UM_CD),2) " + "FROM REQ_ITEM " + "JOIN ITEM ON REQ_ITEM.ITEM_ID = ITEM.ITEM_ID " + "WHERE REQ_ID = " + reqID; try { dsItemDescr = ODMDataSetFactory.ExecuteDataSetBuild(ref Request); } catch (Exception ex) { lm.Write("DataSetManager/GetItemDescr: " + ex.Message); } return dsItemDescr; } public void LoadYesterdayList() { if (trace) { lm.Write("TRACE: DataSetManager/LoadYesterdayList"); } if (trace) { lm.Write("TRACE: DataSetManager/LoadYesterdayList"); } //select req_item_id and req_item_stat and put into to a hashtable ODMRequest Request = new ODMRequest(); Request.ConnectString = connectStrBIAdmin; Request.CommandType = CommandType.Text; Request.Command = "Execute ('" + BuildYesterdayQuery() + "')"; if (debug) lm.Write("DataSetManager/LoadYesterdayList: " + Request.Command); try { dsYesterday = ODMDataSetFactory.ExecuteDataSetBuild(ref Request); } catch (Exception ex) { lm.Write("DataSetManager/LoadYesterdayList: " + ex.Message); } } public void LoadCurrentChanges(string reqItemList) { if (trace) { lm.Write("TRACE: DataSetManager/LoadCurrentChanges"); } ODMRequest Request = new ODMRequest(); Request.ConnectString = connectStrHEMM; Request.CommandType = CommandType.Text; Request.Command = "Execute ('" + BuildCurrentQuery(reqItemList) + "')"; if (debug) lm.Write("DataSetManager/LoadTodaysDataSet: " + Request.Command); try { dsCurrentChangeDates = ODMDataSetFactory.ExecuteDataSetBuild(ref Request); } catch (Exception ex) { lm.Write("DataSetManager/LoadTodaysDataSet: " + ex.Message); } } private string BuildTodayQuery() { if (trace) { lm.Write("TRACE: DataSetManager/BuildTodayQuery"); } string query = "SELECT DISTINCT " + "RI.LINE_NO [REQ LINE NO], " + //0 "REQ_ITEM_ID, " + //1 "ITEM.DESCR, " + //2 "REQ.REQ_ID, " + //3 "ITEM.ITEM_NO, " + //4 "CASE RI.STAT " + "WHEN 1 THEN ''Open'' " + "WHEN 2 THEN ''Pend Apvl'' " + "WHEN 3 THEN ''Approved'' " + "WHEN 4 THEN ''Removed'' " + "WHEN 5 THEN ''Pending PO'' " + "WHEN 6 THEN ''Open Stock Order'' " + "WHEN 8 THEN ''Draft'' " + "WHEN 9 THEN ''On Order'' " + "WHEN 10 THEN ''Killed'' " + "WHEN 11 THEN ''Complete'' " + "WHEN 12 THEN ''Back Order'' " + "WHEN 14 THEN ''On Order'' " + "WHEN 24 THEN ''Pend Informational Apvl'' " + "ELSE CAST(RI.STAT AS VARCHAR(2)) " + "END [ITEM STAT], " + //5 "RI.STAT_CHG_DATE, " + //6 "LOGIN_ID, " + //7 "REQ.REC_CREATE_DATE, " + //8 "ACCT_NO, " + //9 "QTY, " + //10 "RIGHT(RTRIM(UM_CD),2) UM " + //11 "FROM dbo.REQ_ITEM RI " + "JOIN dbo.REQ ON REQ.REQ_ID = RI.REQ_ID " + "JOIN dbo.ITEM ON ITEM.ITEM_ID = RI.ITEM_ID " + "JOIN dbo.USR ON USR.USR_ID = REQ.REC_CREATE_USR_ID " + "JOIN CC ON CC.CC_ID = REQ.CC_ID " + "WHERE REQ.REC_CREATE_DATE BETWEEN CONVERT(DATE,GETDATE()) AND CONVERT(DATE,GETDATE() + 1) " + "AND LOGIN_ID <> ''iface'' AND REQ_TYPE IN (2) AND RI.STAT <> 8 " + "ORDER BY 8,4,1 "; //references param 7,3 and 0 above -- AND REQ_TYPE <> 3 RI.STAT = 8 = "Draft" // Req_Type changed to 8 for par forms to catch actual par form submissions return query; } private string BuildYesterdayQuery() { if (trace) { lm.Write("TRACE: DataSetManager/BuildYesterdayQuery"); } string query = "SELECT REQ_ID,REQ_ITEM_ID, STAT_CHG_DATE,[REQ LINE NO],LOGIN_ID,DESCR,ITEM_NO " + "FROM hmcmm_ReqItemReceipt " + "Order by REQ_ID,[REQ LINE NO] DESC"; return query; } private string BuildCurrentQuery(string reqItemList) { if (trace) { lm.Write("TRACE: DataSetManager/BuildCurrentQuery"); } string query = // SELECT REQ_ID,STAT_CHG_DATE,STAT // FROM REQ_ITEM // WHERE STAT_CHG_DATE > CAST('6/6/2017 12:45:00.000' AS DATETIME) // AND STAT = 2 "SELECT " + "REQ_ITEM_ID, " + //0 "CASE REQ_ITEM.STAT " + "WHEN 1 THEN ''Open'' " + "WHEN 2 THEN ''Pend Apvl'' " + "WHEN 3 THEN ''Approved'' " + "WHEN 4 THEN ''Removed'' " + "WHEN 5 THEN ''Pending PO'' " + "WHEN 6 THEN ''Open Stock Order'' " + "WHEN 8 THEN ''Draft'' " + "WHEN 9 THEN ''On Order'' " + "WHEN 10 THEN ''Killed'' " + "WHEN 11 THEN ''Complete'' " + "WHEN 12 THEN ''Back Order'' " + "WHEN 14 THEN ''On Order'' " + "WHEN 15 THEN ''Auto PO'' " + "WHEN 24 THEN ''Pend Informational Apvl'' " + "ELSE CAST(REQ_ITEM.STAT AS VARCHAR(2)) " + "END [ITEM STAT], " + //1 "REQ_ITEM.STAT_CHG_DATE " + //2 "FROM dbo.REQ_ITEM " + "WHERE REQ_ITEM_ID in ( " + reqItemList + ")"; return query; } private string BuildReqItemUpdateQuery(int reqItem, string status) { if (trace) { lm.Write("TRACE: DataSetManager/BuildReqItemUpdateQuery"); } string query = "UPDATE " + "hmcmm_ReqItemReceipt " + "SET " + "STAT_CHG_DATE = ''" + DateTime.Now + "''," + "STAT = ''" + status + "'' " + "WHERE REQ_ITEM_ID in (" + reqItem + ")"; return query; } private string BuildTruncateReqItemReceipt() { if (trace) { lm.Write("TRACE: DataSetManager/BuildTruncateReqItemReceipt"); } return "Truncate table dbo.hmcmm_ReqItemReceipt"; } private string BuildReqItemDeleteQuery() { if (trace) { lm.Write("TRACE: DataSetManager/BuildReqItemDeleteQuery"); } string[] dt = DateTime.Now.ToString().Split(" ".ToCharArray()); return "DELETE FROM dbo.hmcmm_ReqItemReceipt WHERE STAT IN ('Killed', 'Complete', 'Removed') AND STAT_CHG_DATE < CONVERT(datetime, '" + dt[0] + "', 101)"; } private string BuildReqItemCountQuery(string dateToday) { if (trace) { lm.Write("TRACE: DataSetManager/BuildReqItemCountQuery"); } return "SELECT COUNT(*) FROM dbo.hmcmm_ReqItemReceipt"; } private string BuildReqItemInsertQuery(DataRow dRow) { if (trace) { lm.Write("TRACE: DataSetManager/BuildReqItemInsertQuery"); } string query = ""; query = "INSERT INTO [dbo].[hmcmm_ReqItemReceipt] VALUES(" + dRow[0] + //REQ_LINE "," + dRow[1] + //REQ_ITEM_ID ",'" + CheckForSingleQuotes(dRow[2].ToString()) + //ITEM_DESC "'," + dRow[3] + //REQ_ID ",'" + CheckForNonCatalog(dRow[4].ToString().Trim()) + //ITEM_NO "','" + dRow[5] + //STAT "','" + dRow[6] + //STAT_CHG_DATE "','" + dRow[7].ToString().Trim() + //LOGIN_ID "','" + dRow[8] + //REQ_CREATE_DATE "')"; return query; } private bool CheckExistingRecordCount(int REQ_ID, int RI_ID) {//return TRUE when a req_id/req_item_id combination is NOT in the hmcmm_ReqItemReceipt table if (trace) { lm.Write("TRACE: DataSetManager/CheckExistingRecordCount"); } bool goodToGo = false; ArrayList reqCount = new ArrayList(); ODMRequest Request = new ODMRequest(); Request.ConnectString = connectStrBIAdmin; Request.CommandType = CommandType.Text; Request.Command = "SELECT COUNT(*) FROM [dbo].[hmcmm_ReqItemReceipt] WHERE REQ_ITEM_ID = " + RI_ID + " AND REQ_ID = " + REQ_ID; reqCount = ODMDataSetFactory.ExecuteDataReader(Request); if (Convert.ToInt32(reqCount[0]) == 0) goodToGo = true; return goodToGo; } private void ReqReceiptCount() { if (trace) { lm.Write("TRACE: DataSetManager/ReqReceiptCount"); } ArrayList count = new ArrayList(); ODMRequest Request = new ODMRequest(); string[] dtYesterday = DateTime.Now.AddDays(-1).ToString().Split(" ".ToCharArray()); //this prints yesterday's date string[] dtToday = DateTime.Now.ToString().Split(" ".ToCharArray()); //this is for the get COUNT(*) query. Request.ConnectString = connectStrBIAdmin; Request.CommandType = CommandType.Text; Request.Command = BuildReqItemCountQuery(dtToday[0]); try { count = ODMDataSetFactory.ExecuteDataReader(ref Request); //if (debug && count.Count > 0) lm.Write("Req Receipt Count for " + dtYesterday[0] + " : " + count[0]); } catch (Exception ex) { lm.Write("DataSetManager/ReqReceiptCount: " + ex.Message); } } private string CheckForSingleQuotes(string desc) { if (trace) { lm.Write("TRACE: DataSetManager/CheckForSingleQuotes"); } string[] quote = desc.Split("'".ToCharArray()); desc = ""; for (int x = 0; x < quote.Length; x++) { desc += quote[x] + "''"; } desc = desc.Substring(0, desc.Length - 2); return desc; } private string CheckForNonCatalog(string item_no) { if (trace) { lm.Write("TRACE: DataSetManager/CheckForNonCatalog"); } return item_no.Contains("~[") ? "non-catalog" : item_no; } } } <file_sep>/README.md # ReqReceipt sends a receipt acknowledgement to the originator of a requisition <file_sep>/ProcessManager.cs using System; using System.Collections; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.IO; using LogDefault; namespace ReqReceipt { class ProcessManager { #region Class Variables & Parameters private DataSet dsYesterday = new DataSet(); private DataSet dsCurrentChangeDates; private Hashtable itemChangeDate = new Hashtable(); private Hashtable itemReq = new Hashtable(); private Hashtable itemReqLine = new Hashtable(); private Hashtable itemsThatChanged = new Hashtable(); private Hashtable itemItemNo = new Hashtable(); private Hashtable itemDesc = new Hashtable(); private Hashtable itemLogin = new Hashtable(); private Hashtable receiptList = new Hashtable(); //key=REQ_ID valu=LOGIN_ID private Hashtable reqDate = new Hashtable(); private Hashtable userItems = new Hashtable(); private Hashtable debugCCRecip = new Hashtable(); private Hashtable reqCC = new Hashtable(); private DataSetManager dsm = DataSetManager.GetInstance(); private static NameValueCollection ConfigData = null; private bool debug = false; private bool trace = false; private LogManager lm = LogManager.GetInstance(); class UserNameVariant { //takes in the path to the text file containing the names of users who have an email id different from their AMC id. //each entry looks like this - username|emailname ie: mdanna|dannam Hashtable userItems = new Hashtable(); private string unamePath = ""; public string UnamePath { set { unamePath = value; } } public Hashtable UserItems { get { return userItems; } set { userItems = value; GetUserNameVariant(); } } private void GetUserNameVariant() { string[] users = File.ReadAllLines(unamePath); ArrayList tmpValu = new ArrayList(); string[] user; foreach (string name in users) { user = name.Split("|".ToCharArray()); if (user.Length > 0) { if (user.Length > 1) { //change the userItems entry for users that have a different email if (userItems.ContainsKey(user[0])) { try { tmpValu = (ArrayList)userItems[user[0]]; userItems.Remove(user[0]); userItems.Add(user[1], tmpValu); } catch (Exception ex) { (LogManager.GetInstance()).Write("ProcessManager/GetUserNameVariant: " + ex.Message); } } } } } } } public DataSet DSYesterday { get { return dsYesterday; } set { dsYesterday = value; } } public bool Debug { set { debug = value; } } public bool Trace { set { trace = value; } } #endregion public ProcessManager() { ConfigData = (NameValueCollection)ConfigurationSettings.GetConfig("appSettings"); } public void Begin() { if (trace) { lm.Write("TRACE: ProcessManager/Begin"); } CreateDebugCCRecipTable(ConfigData.Get("debugCCRecip")); StoreNewReqs(); SendOutput(); //gets instance of OutputManager } private void SendOutput() { if (trace) {lm.Write("TRACE: ProcessManager/SendOutput");} OutputManager om = new OutputManager(); om.Debug = debug; om.AttachmentPath = ConfigData.Get("attachmentPath"); om.ItemReq = itemReq; om.ItemReqLine = itemReqLine; om.ItemsThatChanged = itemsThatChanged; om.ItemItemNo = itemItemNo; om.ItemDesc = itemDesc; om.ReqBuyer = dsm.ReqBuyer; GetUserNameVariant(); int itemID = 0; try { if (debug) { om.DebugRecipientList = ConfigData.Get("debugRecipientList"); } om.DebugCCRecip = debugCCRecip; //when reciptList is empty, debug will not send emails to the debug recipients //because SendOutput is only called in this foreach loop. //this loop is what sends out the emails... foreach (DictionaryEntry de in receiptList) { om.ReqNo = de.Key.ToString(); om.UserName = de.Value.ToString().Trim(); om.ReqDate = (reqDate[de.Key]).ToString(); om.Trace = trace; om.CurrentAcctNo = (reqCC[de.Key]).ToString(); om.SendOutput(); } } catch (Exception ex) { lm.Write("ProcessManager/SendOutput: ERROR: " + ex.Message); } } private ArrayList GetCCList(string ccList) { if (trace) { lm.Write("TRACE: ProcessManager/GetCCList"); } ArrayList costCenters = new ArrayList(); string[] costCenterList = ccList.Split(",".ToCharArray()); foreach(string cc in costCenterList) { costCenters.Add(cc); } return costCenters; } //changes are made to the userItems list to replace the user names which AREN'T also the email name private void GetUserNameVariant() { if (trace) { lm.Write("TRACE: ProcessManager/GetUserNameVariant"); } UserNameVariant unv = new UserNameVariant(); unv.UnamePath = ConfigData.Get("unameVariantList"); unv.UserItems = userItems; userItems = unv.UserItems; } private void StoreNewReqs() { if (trace) { lm.Write("TRACE: ProcessManager/StoreNewReqs"); } dsm.PartialCCList = GetCCList(ConfigData.Get("partialCCList")); dsm.InsertTodaysList(); receiptList = dsm.SendReceipt; reqDate = dsm.ReqDate; reqCC = dsm.ReqCC; } private Hashtable Clone(Hashtable htInput) { if (trace) { lm.Write("TRACE: ProcessManager/Clone"); } if (debug) lm.Write("ProcessManager/Clone"); Hashtable ht = new Hashtable(); foreach (DictionaryEntry dictionaryEntry in htInput) { if (dictionaryEntry.Value is string) { ht.Add(dictionaryEntry.Key, new string(dictionaryEntry.Value.ToString().ToCharArray())); } else if (dictionaryEntry.Value is Hashtable) { ht.Add(dictionaryEntry.Key, Clone((Hashtable)dictionaryEntry.Value)); } else if (dictionaryEntry.Value is ArrayList) { ht.Add(dictionaryEntry.Key, new ArrayList((ArrayList)dictionaryEntry.Value)); } } return ht; } private void CreateDebugCCRecipTable(string ccCollection) { //ccCollection ="6074:<EMAIL>,<EMAIL>;6087:<EMAIL>;" //this allows for a test where more than one person wants to see the receipts for a req on a given cost center. if (trace) { lm.Write("TRACE: ProcessManager/CreateDebugCCRecipTable"); } string[] costCenter; string[] ccGroup = ccCollection.Split(";".ToCharArray()); foreach(string cc in ccGroup) { if (cc.Length > 0) { costCenter = cc.Split(":".ToCharArray()); if (!debugCCRecip.ContainsKey(costCenter[0])) debugCCRecip.Add(costCenter[0], costCenter[1]); } } } } } <file_sep>/Program.cs using System; using System.Collections.Specialized; using System.Configuration; using LogDefault; namespace ReqReceipt { class Program { #region class variables private static string corpName = ""; //HMC, UWMC private static string logPath = ""; private static bool debug = false; private static bool trace = false; private static bool cleanUp = false; private static LogManager lm = LogManager.GetInstance(); private static NameValueCollection ConfigData = null; #endregion static void Main(string[] args) { // check the cleanUp param if (args.Length > 0) { cleanUp = true; } ConfigData = (NameValueCollection)ConfigurationSettings.GetConfig("appSettings"); try { lm.Write("Program/Main: " + "BEGIN"); GetParameters(); LoadData(); if (cleanUp) lm.Write("Program/Main: " + "END"); else { Process(); lm.Write("Program/Main: " + "END"); } } catch (Exception ex) { lm.Write("Program/Main: " + ex.Message); } finally { Environment.Exit(1); } } private static void GetParameters() { debug = Convert.ToBoolean(ConfigData.Get("debug")); trace = Convert.ToBoolean(ConfigData.Get("trace")); lm.LogFilePath = ConfigData.Get("logFilePath"); lm.LogFile = ConfigData.Get("logFile"); lm.Debug = debug; } private static void LoadData() { DataSetManager dsm = DataSetManager.GetInstance(); //DataSetManager is a singleton so getting the instance here sets it up for the other classes in the app. dsm.Debug = debug; dsm.Trace = trace; if (cleanUp) { //cleanUp needs to be run once each day after midnight. //The initial select query (DataSetManager.BuildTodayQuery) only looks for records from the previous run through to the current run time. //To run TruncateReqItemReceipt, launch ReqItemStatus wih the number "1" as a parameter (or anything, really - as you can see above //it only looks at the number of arguments over 0). You'll probably want this on its own Scheduled Task (currently set at 12:30AM). (LogManager.GetInstance()).Write("Program/Main.LoadData: " + "CleanUp - hmcmm_ReqItemReceipt"); dsm.TruncateReqItemReceipt(); } else { dsm.LoadTodaysDataSet(); dsm.LoadYesterdayList(); } } private static void Process() { ProcessManager pm = new ProcessManager(); pm.Debug = debug; pm.Trace = trace; pm.Begin(); } } }
673a299055f78b9809a66128daff9e4833d1cb8f
[ "Markdown", "C#", "Text" ]
6
C#
dlrjones/ReqReceipt
3d2a477db50225560dbc94e469bdc91c019187cb
a5ef65b8d653e39f0f38d77f0c50010a6cb3927c
refs/heads/master
<repo_name>xlizzard/Remote-Control<file_sep>/木马服务端 server/木马服务端/main.cpp #include <winsock2.h> #include<stdio.h> #include<iostream> #include<string> #include <cstring> #include <fstream> using namespace std; #pragma comment(lib,"ws2_32.lib")//链接这个库 //TCP服务器端 void RecvFile(SOCKET sClient, string SaveFileName); int connect(); int main() { int temp = 10; while (true) { if (temp == 10) { temp = connect(); } else { } } return 0; } int connect() { //调用winsock WORD sockVersion = MAKEWORD(2, 2);//请求使用的winsock版本 WSADATA wsaData; // 实际返回的winsock版本 if (WSAStartup(sockVersion, &wsaData) != 0) { } //创建socket SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);//参数分别为协议族,类型,协议号 AF_INET代表TCP/IP if (slisten == INVALID_SOCKET)//异常处理 { printf("scoket error!\n"); return 10; } //bind sockaddr_in sin; //服务器端点地址 sin.sin_family = AF_INET; //协议族 sin.sin_port = htons(8888); //端口号, htons函数将本地字节顺序变为网络字节顺序(16位) sin.sin_addr.S_un.S_addr = INADDR_ANY;//服务器bind时需要使用地址通配 if (bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)//LPSOCKADDR是类型强制转换 { printf("bind error !\n"); return 10; } //listen if (listen(slisten, 5) == SOCKET_ERROR)//5为queuesize,缓存区大小 { printf("listen error !\n"); return 10; } //由于使用的是TCP ,socket stream,要循环接收数据 SOCKET sClient;//声明变量 sockaddr_in remoteAddr; int nAddrlen = sizeof(remoteAddr); char revData[1024];//buffer printf("waiting for connect...\n\n"); while (true) { printf("command:"); string data; getline(cin, data);//键盘读入数据 const char* sendData; sendData = data.c_str(); //string变为const char* sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);//accept会新建一个socket if (sClient == INVALID_SOCKET) { printf("accept error !"); continue;//重新开始循环 } printf("someone ip: %s\r\n", inet_ntoa(remoteAddr.sin_addr)); //inet将ip地址结构转成字符串 , \r是回车 //发送数据 send(sClient, sendData, strlen(sendData), 0); //接收数据 //接收文件 if (data.find("pass") != string::npos)//pass-D:\\001.txt-D:\\002.txt { string savepath = data.substr(data.find_last_of("-") + 1); RecvFile(sClient, savepath); } //接收字符串 else { int ret = recv(sClient, revData, 1024, 0); printf("feedback:\n"); while (true) { if (ret > 0) { revData[ret] = 0x00; printf(revData); ret = recv(sClient, revData, 1024, 0); } break; } printf("\n\n"); } closesocket(sClient); } closesocket(slisten); WSACleanup(); } void RecvFile(SOCKET sClient, string SaveFileName) { cout << "receive start" << endl; const int bufferSize = 1024; char buffer[bufferSize] = { 0 }; int readLen = 0; //string SaveFileName ; //这是服务器要接收的文件的保存路径 ofstream desFile; desFile.open(SaveFileName.c_str(), ios::binary); if (!desFile) { return; } do { readLen = recv(sClient, buffer, bufferSize, 0); if (readLen == 0) { break; } else { desFile.write(buffer, readLen); cout << "receiving" << endl; } } while (true); cout << "receive over\n\n" << endl; desFile.close(); }<file_sep>/README.md # Remote-Control just Remote-Control with C/C++ <file_sep>/木马客户端 clinet/木马客户端/main.cpp #include<stdio.h> #include<iostream> #include<cstring> #include<string> #include <tchar.h> #include <io.h> #include <sstream> #include <afxwin.h> #include <windows.h> #include <cstring> #include <fstream> #include <winsock2.h> #include <Urlmon.h> using namespace std; #pragma comment(lib,"ws2_32.lib")//windowssock库 #pragma comment(lib,"Urlmon.lib") //加入文件传输库 #pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" ) // 这就是最重要的一个隐藏程序的代码 //TCP客户端 #define _CRT_SECURE_NO_WARNINGS void SendFile(SOCKET sclient, string srcFileName); LPCWSTR stringToLPCWSTR(std::string orig); void download(string dourl, string a); string dir(string path); string deal(string things); int connect(); void Screen(char filename[]); int main() { int temp = 10; while (true) { if (temp = 10) { temp = connect(); } else { break; } } return 0; } void SendFile(SOCKET sclient, string srcFileName) { int haveSend = 0; const int bufferSize = 1024; char buffer[bufferSize] = { 0 }; int readLen = 0; //string srcFileName ; //这是用户端要发送的路径 ifstream srcFile; srcFile.open(srcFileName.c_str(), ios::binary); if (!srcFile){ return; } while (!srcFile.eof()){ srcFile.read(buffer, bufferSize); readLen = srcFile.gcount(); send(sclient, buffer, readLen, 0); haveSend += readLen; } srcFile.close(); cout << "send: " << haveSend << "B" << endl; } LPCWSTR stringToLPCWSTR(std::string orig) { size_t origsize = orig.length() + 1; const size_t newsize = 100; size_t convertedChars = 0; wchar_t *wcstring = (wchar_t *)malloc(sizeof(wchar_t)*(orig.length() - 1)); mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCATE); return wcstring; } void download(string dourl, string a) { LPCWSTR url = stringToLPCWSTR(dourl); printf("downurl: %S\n", url); TCHAR path[MAX_PATH]; GetCurrentDirectory(MAX_PATH, path); LPCWSTR savepath = stringToLPCWSTR(a); wsprintf(path, savepath, path); printf("savepath: %S\n", path); HRESULT res = URLDownloadToFile(NULL, url, path, 0, NULL); if (res == S_OK) { printf("downover\n"); } else if (res == E_OUTOFMEMORY) { printf("recvlength has something wrong or dont set recvlength\n"); } else if (res == INET_E_DOWNLOAD_FAILURE) { printf("url has something wrong\n"); } else { printf("unkonwn error\n", res); } } string dir(string path) { string result; long hFile = 0; struct _finddata_t fileInfo; string pathName, exdName; // \\* 代表要遍历所有的类型,如改成\\*.jpg表示遍历jpg类型文件 if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -1) { } do { result = result + "\n" + fileInfo.name; } while (_findnext(hFile, &fileInfo) == 0); _findclose(hFile); return result; } string deal(string things) { //分析命令 if (things.find("dir") != string::npos)/* dir-D:\\ */ { string result = things.substr(things.find_first_of("-") + 1); string temp = dir(result); cout << temp << endl; return temp; } else if (things.find("down") != string::npos)//down-http://www.anyeur.club-D:index.php { string downurl = things.substr(things.find_first_of("-") + 1, things.find_last_of("-") - things.find_first_of("-") - 1); string savepath = things.substr(things.find_last_of("-") + 1); download(downurl, savepath); return "download over!"; } else if (things.find("pass") != string::npos)//pass-D:\\001.txt-D:\\002.txt { string sendfile = things.substr(things.find_first_of("-") + 1, things.find_last_of("-") - things.find_first_of("-") - 1); return "pass-" + sendfile; } else if (things.find("screen") != string::npos)//screen-D:\\001.jpg { string savepat = things.substr(things.find_last_of("-") + 1); char savepath[20]; strcpy(savepath, savepat.c_str()); Screen(savepath); return "screen over!"; } else { return "nothing"; } } int connect() { WORD sockVersion = MAKEWORD(2, 2); WSADATA data; if (WSAStartup(sockVersion, &data) != 0) { printf("initialization failed!\n"); return 10; } while (true) { SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sclient == INVALID_SOCKET) { printf("invalid socket!\n"); return 10; } sockaddr_in serAddr; //要连接的服务器端 的 端点地址 serAddr.sin_family = AF_INET; serAddr.sin_port = htons(8888); serAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //将ip变为地址结构 //客户端程序不需要bind本机端点地址,系统会自动完成 if (connect(sclient, (sockaddr*)&serAddr, sizeof(serAddr)) == SOCKET_ERROR) { printf("connect error!\n"); closesocket(sclient); return 10; } char recData[1024]; string a; int ret = recv(sclient, recData, 1024, 0); if (ret>0) { recData[ret] = 0x00; cout << "command:" << recData << endl; string CMD(recData); a = deal(CMD); } if (a.find("pass") != string::npos) { string sendfile = a.substr(a.find_last_of("-") + 1); SendFile(sclient, sendfile); closesocket(sclient); } else { string data; data = a; const char* sendData; sendData = data.c_str(); //string21变为const char* cout << strlen(sendData) << endl; send(sclient, sendData, strlen(sendData), 0); closesocket(sclient); } } WSACleanup(); } void Screen(char filename[]) { CDC *pDC;//屏幕DC pDC = CDC::FromHandle(GetDC(NULL));//获取当前整个屏幕DC int BitPerPixel = pDC->GetDeviceCaps(BITSPIXEL);//获得颜色模式 int Width = pDC->GetDeviceCaps(HORZRES); int Height = pDC->GetDeviceCaps(VERTRES); printf("当前屏幕色彩模式为%d位色彩\n", BitPerPixel); printf("屏幕宽度:%d\n", Width); printf("屏幕高度:%d\n", Height); CDC memDC;//内存DC memDC.CreateCompatibleDC(pDC); CBitmap memBitmap, *oldmemBitmap;//建立和屏幕兼容的bitmap memBitmap.CreateCompatibleBitmap(pDC, Width, Height); oldmemBitmap = memDC.SelectObject(&memBitmap);//将memBitmap选入内存DC memDC.BitBlt(0, 0, Width, Height, pDC, 0, 0, SRCCOPY);//复制屏幕图像到内存DC //以下代码保存memDC中的位图到文件 BITMAP bmp; memBitmap.GetBitmap(&bmp);//获得位图信息 FILE *fp = fopen(filename, "w+b"); BITMAPINFOHEADER bih = { 0 };//位图信息头 bih.biBitCount = bmp.bmBitsPixel;//每个像素字节大小 bih.biCompression = BI_RGB; bih.biHeight = bmp.bmHeight;//高度 bih.biPlanes = 1; bih.biSize = sizeof(BITMAPINFOHEADER); bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;//图像数据大小 bih.biWidth = bmp.bmWidth;//宽度 BITMAPFILEHEADER bfh = { 0 };//位图文件头 bfh.bfOffBits = sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);//到位图数据的偏移量 bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;//文件总的大小 bfh.bfType = (WORD)0x4d42; fwrite(&bfh, 1, sizeof(BITMAPFILEHEADER), fp);//写入位图文件头 fwrite(&bih, 1, sizeof(BITMAPINFOHEADER), fp);//写入位图信息头 byte * p = new byte[bmp.bmWidthBytes * bmp.bmHeight];//申请内存保存位图数据 GetDIBits(memDC.m_hDC, (HBITMAP)memBitmap.m_hObject, 0, Height, p, (LPBITMAPINFO)&bih, DIB_RGB_COLORS);//获取位图数据 fwrite(p, 1, bmp.bmWidthBytes * bmp.bmHeight, fp);//写入位图数据 delete[] p; fclose(fp); memDC.SelectObject(oldmemBitmap); }
90945314ca70c7edf9a1beaad13bee9e0d2d198f
[ "Markdown", "C++" ]
3
C++
xlizzard/Remote-Control
c624bfce829a5bfec757e9eb673f4d7723ce3e0e
b7bf6c868816b98a1845f4ba902755f71292e0f5
refs/heads/master
<file_sep>const { Blockchain, Transaction } = require("./blockchain"); const EC = require("elliptic").ec; const ec = new EC("secp256k1"); const myKey = ec.keyFromPrivate("0e7f07a52f695a09a6b167d74ab3f4598a32377e321e977d5031828ebab5bcee"); const myWalletAddress = myKey.getPublic("hex"); let ayaCoin = new Blockchain(); const tx1 = new Transaction(myWalletAddress, "someones wallet address", 10); tx1.signTransaction(myKey); ayaCoin.addTransaction(tx1); console.log("start mining...") ayaCoin.minePendingTransactions(myWalletAddress); ayaCoin.minePendingTransactions(myWalletAddress); console.log("Balance of ayako is...", ayaCoin.getBalanceOfAddress(myWalletAddress)); console.log("Is chain valid", ayaCoin.isChainValid());<file_sep># ayaCoin I've created ayaCoin which is a blockchain with JavaScript. ** I coded along with "Building a blockchain with Javascript" on YouTube.** The link is: https://youtube.com/playlist?list=PLzvRQMJ9HDiTqZmbtFisdXFxul5k0F-Q4
093fe3483c129a5780a630439397ef38b03a2dbd
[ "JavaScript", "Markdown" ]
2
JavaScript
usuajiayako/ayaCoin
6c1de922bbde11e0ee7f278281cba97abc52f022
928ceab8d57d6ca5458226c5d5e5b3969fc6effe
refs/heads/master
<file_sep>from django.views import generic from django.utils import timezone from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.shortcuts import render, get_object_or_404, redirect from django.template import RequestContext, loader from projects.models import Project, Issue from projects.forms import ProjectForm, IssueForm class IndexView(generic.ListView): template_name = 'projects/index.html' context_object_name = 'projects_list' def get_queryset(self): return Project.objects.order_by('-start_date') class DetailView(generic.DetailView): model = Project template_name = 'projects/detail.html' def get_queryset(self): return Project.objects.all() class CreateProjectView(generic.CreateView): model = Project form_class = ProjectForm class AddProjectView(generic.RedirectView): def post(self, request, *args, **kwargs): project_form = ProjectForm(request.POST) if project_form.is_valid(): project_form.save() return super(AddProjectView, self).post(request, *args, **kwargs) else: # Redisplay the create project form. return render(request, 'projects/project_form.html', { 'form': ProjectForm, #'error_message': project_form.errors, 'error_message': 'All the fields are required.', }) class CreateIssueView(generic.CreateView): model = Issue form_class = IssueForm def get(self, request, *args, **kwargs): project = get_object_or_404(Project, pk=kwargs['pk']) template = loader.get_template('projects/issue_form.html') context = RequestContext(request, { 'project_id': project.id, 'form': IssueForm, }) return HttpResponse(template.render(context)) class AddIssueView(generic.RedirectView): def post(self, request, *args, **kwargs): issue_form = IssueForm(request.POST) if issue_form.is_valid(): issue = issue_form.save(commit=False) issue.project = Project.objects.all().get(pk=int(kwargs['pk'])) issue_form.save() return render(request, 'projects/detail.html', { 'project': issue.project }) else: project_id = Project.objects.all().get(pk=kwargs['pk']).id # Redisplay the create issue form return render(request, 'projects/issue_form.html', { 'form': IssueForm, 'project_id': project_id, 'error_message': 'All the fields are required', }) class DetailIssueView(generic.DetailView): model = Issue template_name = 'projects/issue.html' class StartIssueView(generic.View): def post(self, request, *args, **kwargs): issue = Issue.objects.all().get(pk=kwargs['pk']) if issue.status == 'OPEN' or issue.status == 'RESOLVED': issue.status = 'IN_PROGRESS' issue.start_time = timezone.now() issue.save() return HttpResponseRedirect('/projects/' + str(issue.project.id)) class StopIssueView(generic.View): def post(self, request, *args, **kwargs): issue = Issue.objects.all().get(pk=kwargs['pk']) if issue.status == 'IN_PROGRESS' or 'REOPENED': issue.status = 'RESOLVED' issue.save() return HttpResponseRedirect('/projects/' + str(issue.project.id)) class CloseIssueView(generic.View): def post(self, request, *args, **kwargs): issue = Issue.objects.all().get(pk=kwargs['pk']) issue.status = 'CLOSED' issue.save() return HttpResponseRedirect('/projects/' + str(issue.project.id)) <file_sep>from django import forms from projects.models import Project, Issue class ProjectForm(forms.ModelForm): class Meta: model = Project exclude = ('start_date') class IssueForm(forms.ModelForm): class Meta: model = Issue exclude = ('project', 'status') <file_sep>import datetime from django.utils import timezone from django.test import TestCase from django.core.urlresolvers import reverse from projects.models import Project def create_project(title, days, lead, project_type): """ Creates a project with the given `title`, `lead` and `project_type` started the given number of `days` offset to now (negative number). """ return Project.objects.create(title=title, start_date=timezone.now() + datetime.timedelta(days=days), lead=lead, project_type=project_type) class ProjectsIndexViewTests(TestCase): def test_index_view_with_no_projects(self): """ If no projects exist, an appropriate message should be displayed. """ response = self.client.get(reverse('projects:index')) self.assertContains(response, 'No projects available yet.', status_code=200) self.assertQuerysetEqual(response.context['projects_list'], []) def test_index_view_with_one_project(self): """ One project should be displayed on the index page. """ create_project(title='Blank project', days=-1, lead='<NAME>', project_type='BLANK_PROJECT') response = self.client.get(reverse('projects:index')) self.assertQuerysetEqual( response.context['projects_list'], ['<Project: Blank project>'] ) def test_index_view_with_more_projects(self): """ Projects should be displayed on the index page. """ create_project(title='Agile Kanban project', days=-5, lead='<NAME>', project_type='AGILE_KANBAN') create_project(title='Blank project', days=-2, lead='<NAME>', project_type='BLANK_PROJECT') create_project(title='Agile Scrum project', days=-1, lead='<NAME>', project_type='AGILE_SCRUM') response = self.client.get(reverse('projects:index')) self.assertQuerysetEqual( response.context['projects_list'], ['<Project: Agile Scrum project>', '<Project: Blank project>', '<Project: Agile Kanban project>'] ) class ProjectDetailViewTests(TestCase): def test_detail_view_with_nonexistent_project(self): """ The detail view of nonexistent project should return a 404 not found. """ response = self.client.get(reverse('projects:detail', args=(1,))) self.assertEqual(response.status_code, 404) def test_detail_view_of_project(self): """ The detail view of a project should display the project's title. """ project = create_project(title='Project title', days=-1, lead='<NAME>', project_type='DEMO_PROJECT') response = self.client.get(reverse('projects:detail', args=(project.id,))) self.assertContains(response, project.title, status_code=200) class CreateProjectViewTests(TestCase): def test_create_project_view(self): """ The create project view should display Title: Lead: Project type: Create """ response = self.client.get(reverse('projects:create')) self.assertContains(response, 'Title:', status_code=200) self.assertContains(response, 'Lead:', status_code=200) self.assertContains(response, 'Project type:', status_code=200) self.assertContains(response, 'Create', status_code=200) class AddProjectViewTest(TestCase): def test_add_a_project_valid_form(self): """ If the form is valid, the project must be saved to the database. """ self.assertEqual(Project.objects.all().count(), 0) response = self.client.post(reverse('projects:add'), {'title': 'Project title', 'lead': 'Project lead', 'project_type': 'AGILE_KANBAN'}, follow=True) self.assertEqual(Project.objects.all().count(), 1) def test_add_a_project_with_no_title(self): """ If the form is invalid, the view should return the create project view with error message 'This field is required.'. """ response = self.client.post(reverse('projects:add'), {'title': '', 'lead': 'Project lead', 'project_type': 'AGILE_KANBAN'}, follow=True) self.assertEqual(Project.objects.all().count(), 0) def test_add_a_project_with_no_project_type(self): """ If the form is invalid, the view should return the create project view with error message 'This field is required.'. """ response = self.client.post(reverse('projects:add'), {'title': 'Project Title', 'lead': 'Project lead', 'project_type': ''}, follow=True) self.assertEqual(Project.objects.all().count(), 0) def test_add_a_project_with_no_lead(self): """ If the form is invalid, the view should return the create project view with error message 'This field is required.'. """ response = self.client.post(reverse('projects:add'), {'title': 'Project Title', 'lead': '', 'project_type': 'AGILE_KANBAN'}, follow=True) self.assertEqual(Project.objects.all().count(), 0) class CreateIssueViewTests(TestCase): def test_create_issue_view_for_existent_project(self): """ The create issue view for existent project should display Issue type: Summary: Priority: Assignee: Reporter: Description: Create """ create_project(title='Blank project', days=-1, lead='<NAME>', project_type='BLANK_PROJECT') response = self.client.get(reverse('projects:create_issue', args=(1,))) self.assertContains(response, 'Issue type:', status_code=200) self.assertContains(response, 'Summary:', status_code=200) self.assertContains(response, 'Priority:', status_code=200) self.assertContains(response, 'Assignee:', status_code=200) self.assertContains(response, 'Reporter:', status_code=200) self.assertContains(response, 'Description:', status_code=200) self.assertContains(response, 'Create', status_code=200) def test_create_issue_view_for_nonexistent_project(self): """ The create issue view for nonexistent project should return a 404 not found. """ response = self.client.get(reverse('projects:create_issue', args=(1,))) self.assertEqual(response.status_code, 404) class AddIssueViewTest(TestCase): def test_add_an_issue_valid_form(self): """ If the form is valid, the issue must be saved to the database. """ create_project(title='Project management project', days=-1, lead='<NAME>', project_type='PROJECT_MANAGEMENT') self.assertEqual(Project.objects.all().get(pk=1).issue_set.count(), 0) response = self.client.post(reverse('projects:add_issue', args=(1,)), {'issue_type': 'BUG', 'summary': 'Issue summary', 'priority': 'MAJOR', 'assignee': '<NAME>', 'reporter': '<NAME>', 'description': 'Bug description'}, follow=True) self.assertEqual(Project.objects.all().get(pk=1).issue_set.count(), 1) def test_add_an_issue_invalid_form_no_issue_type(self): """ If the form is invalid, the view should redisplay the create issue view. """ create_project(title='Software development project', days=-1, lead='<NAME>', project_type='SOTWARE_DEVELOPMENT') self.assertEqual(Project.objects.all().get(pk=1).issue_set.count(), 0) response = self.client.post(reverse('projects:add_issue', args=(1,)), {'issue_type': '', 'summary': 'Issue summary', 'priority': 'MAJOR', 'assignee': '<NAME>', 'reporter': '<NAME>', 'description': 'Bug description'}, follow=True) self.assertEqual(Project.objects.all().get(pk=1).issue_set.count(), 0) def test_add_an_issue_invalid_form_no_summary(self): """ If the form is invalid, the view should redisplay the create issue view. """ create_project(title='Blank project', days=-1, lead='<NAME>', project_type='BLANK_PROJECT') self.assertEqual(Project.objects.all().get(pk=1).issue_set.count(), 0) response = self.client.post(reverse('projects:add_issue', args=(1,)), {'issue_type': '', 'summary': 'Issue summary', 'priority': 'MAJOR', 'assignee': '<NAME>', 'reporter': '<NAME>', 'description': 'Bug description'}, follow=True) self.assertEqual(Project.objects.all().get(pk=1).issue_set.count(), 0) <file_sep>TARDIS Bug tracking system for the course "Programming with Python" License Copyright (C) 2013 <NAME> <file_sep>from django.conf.urls import patterns, url, include from projects import views urlpatterns = patterns('', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), url(r'^create_project/$', views.CreateProjectView.as_view(), name='create'), url(r'^add/$', views.AddProjectView.as_view(url='/projects'), name='add'), url(r'^create_issue/(?P<pk>\d+)/$', views.CreateIssueView.as_view(), name='create_issue'), url(r'^add_issue/(?P<pk>\d+)/$', views.AddIssueView.as_view(url='/projects'), name='add_issue'), url(r'^issue/(?P<pk>\d+)/$', views.DetailIssueView.as_view(), name='issue'), url(r'^start/(?P<pk>\d+)/$', views.StartIssueView.as_view(), name='start'), url(r'^stop/(?P<pk>\d+)/$', views.StopIssueView.as_view(), name='stop'), url(r'^close/(?P<pk>\d+)/$', views.CloseIssueView.as_view(), name='close'), ) <file_sep>from django.db import models from django.contrib.auth.models import User class Project(models.Model): title = models.CharField(max_length=50, blank=False) start_date = models.DateTimeField('date started', blank=False, auto_now_add=True) lead = models.CharField(max_length=50, blank=False) BUG_TRACKING = 'BUG_TRACKING' PROJECT_MANAGEMENT = 'PROJECT_MANAGEMENT' AGILE_KANBAN = 'AGILE_KANBAN' SOTWARE_DEVELOPMENT = 'SOTWARE_DEVELOPMENT' AGILE_SCRUM = 'AGILE_SCRUM' BLANK_PROJECT = 'BLANK_PROJECT' DEMO_PROJECT = 'DEMO_PROJECT' TYPE_OF_PROJECTS = ( (BUG_TRACKING, 'Bug Tracking'), (PROJECT_MANAGEMENT, 'Project Management'), (AGILE_KANBAN, 'Agile Kanban'), (SOTWARE_DEVELOPMENT, 'Software Development'), (AGILE_SCRUM, 'Agile Scrum'), (BLANK_PROJECT, 'Blank Project'), (DEMO_PROJECT, 'Demo Project'), ) project_type = models.CharField(max_length=19, choices=TYPE_OF_PROJECTS, default=BLANK_PROJECT) def __str__(self): return self.title class Issue(models.Model): project = models.ForeignKey(Project) BUG = 'BUG' NEW_FEATURE = 'NEW_FEATURE' TASK = 'TASK' IMPROVEMENT = 'IMPROVEMENT' TYPE_OF_ISSUES = ( (BUG, 'Bug'), (NEW_FEATURE, 'New feature'), (TASK, 'Task'), (IMPROVEMENT, 'Improvement'), ) issue_type = models.CharField(max_length=11, choices=TYPE_OF_ISSUES, default=BUG) summary = models.CharField(max_length=100, blank=False) MAJOR = 'MAJOR' BLOCKER = 'BLOCKER' CRITICAL = 'CRITICAL' MINOR = 'MINOR' TRIVIAL = 'TRIVIAL' PRIORITY_TYPES = ( (MAJOR, 'Major'), (BLOCKER, 'Blocker'), (CRITICAL, 'Critical'), (MINOR, 'Minor'), (TRIVIAL, 'Trivial'), ) priority = models.CharField(max_length=8, choices=PRIORITY_TYPES, default=MAJOR) assignee = models.CharField(max_length=50, blank=False) reporter = models.CharField(max_length=50, blank=False) description = models.TextField(blank=False) due_date = models.DateField(auto_now_add=True) OPEN = 'OPEN' IN_PROGRESS = 'IN_PROGRESS' RESOLVED = 'RESOLVED' REOPENED = 'REOPENED' CLOSED = 'CLOSED' STATUS_TYPES = ( (OPEN, 'Open'), (IN_PROGRESS, 'In progress'), (RESOLVED, 'Resolved'), (REOPENED, 'Reopened'), (CLOSED, 'Closed'), ) status = models.CharField(max_length=11, choices=STATUS_TYPES, default=OPEN) def __str__(self): return self.summary <file_sep>from django.contrib import admin from projects.models import Project, Issue class IssueInline(admin.TabularInline): model = Issue extra = 3 class ProjectAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['title']}), (None, {'fields': ['lead']}), (None, {'fields': ['project_type']}), ] inlines = [IssueInline] list_display = ('title', 'start_date', 'lead', 'project_type') list_filter = ['start_date', 'project_type', 'lead'] search_fields = ['title', 'lead'] date_hierarchy = 'start_date' admin.site.register(Project, ProjectAdmin)
fe00aacc9cf7b6eaf0f0617c4ebde475bcd1a4bf
[ "Markdown", "Python" ]
7
Python
nelly-hateva/tardis
b44917493359b80036df6cbfc009d862448f51ed
5064611fb9f527fde1f03ccf9dfd16375fa08c13
refs/heads/master
<repo_name>Honest-Team/vue3-vite-admin<file_sep>/src/store/index.js // 已通过app.config.globalProperties挂载,让vue实例可以访问 // 在模板中 <div>{{ $store.state.user.name }}</div> 快速使用 export default { state: { user: '', }, getter: {}, } <file_sep>/src/views/dashboard/components/cards.js export { default as WeChat } from './WeChatWallet/index.vue' export { default as Bilibili } from './BilibiliState/index.vue' export { default as Earning } from './EarningPosition/index.vue' export { default as Github } from './GithubState/index.vue' <file_sep>/src/api/sysUserService/index.js import request from '/src/utils/request' export function getCurrentUser() { return request.get('/sysUserService/getCurrentUser') } export function queryByCondition(data) { return request.get('/sysUserService/queryByCondition', {params: data}) } export function getUser(data) { return request.get('/sysUserService/' + data) } export function save(data) { return request.post('/sysUserService/save', data) } export function update(data) { return request.post('/sysUserService/update', data) } export function deleteByIds(data) { return request.post('/sysUserService/deleteByIds', data) } export function updatePassword(data) { return request.post('/sysUserService/updatePassword', data) } <file_sep>/README.md # Vuejs3+Vite2+ElementPlus 后台管理系统模板 ## 简介 一个免费开源的后台管理系统模板。使用最新的主流技术开发,开箱即用(主要还是用于学习参考!),主要向以下两个高 star 的后台管理系统模板进行学习,并根据需求进行取舍和优化改进。 - [vue-vben-admin](https://github.com/anncwb/vue-vben-admin) 使用了最新的`vue3`,`vite2`,`TypeScript`,`antdv`等主流技术开发 (代码量非常庞大和复杂...) 没有 TypeScript!!!! 没有 Vuex !!!!!! 不支持 IE:v::v::v::v::v: ## 技术 (列出来方便写报告呢!) - [Vue.js 3](https://v3.cn.vuejs.org/) : 一套用于构建用户界面的**渐进式框架** - [Vite 2](https://cn.vitejs.dev/) :基于`ESM` 的新型前端构建工具,能够显著提升前端开发体验 - [Vue Router 4](https://next.router.vuejs.org/zh/) :Vue.js 的官方路由。它与 Vue.js 核心深度集成 - [Element Plus](https://element-plus.gitee.io/) :基于 Vue 3.0 的桌面端组件库 (目前仍是 beta 版) - [axios](https://echarts.apache.org/zh/index.html) :基于`promise`的 HTTP 请求库 - [echarts](https://axios-http.com/zh/) :基于 JavaScript 的开源可视化图表库 - [mockjs](http://mockjs.com/) :生成随机数据,拦截 Ajax 请求,配合 [vite-plugin-mock](https://github.com/anncwb/vite-plugin-mock) 插提高开发效率 - [SCSS](https://www.sass.hk/docs/) :动态样式语言,是强化 CSS 的辅助工具 (SCSS 是 Sass 3 引入新的语法) - [prettier](https://prettier.io/) :可配置化的代码格式化工具,支持多种语言,(往往与 ESLint 一起使用,但...) ## 特性 - 使最新的前端主流技术栈进行开发 - **没有 TypeScript** 让代码更加轻量级也便于快速上手 (对于初学者,代码多了难看下去) - **没有 Vuex** 这个用起来是真的麻烦!在 vue3 中更没必要加入它(个人看法) - **详细的代码注释** 注释多多益善,有总比没有好(个人看法) - **少依赖** 能减少依赖项就尽量减少,能自己实现就自己实现,依赖多了安装都可能出问题 - 常用组件 组件源码内自带详细的使用案例 - Mock 数据 - 权限功能 - TODO ## 功能 **TODO** ### 待加入 - [ ] 组件-页面内标题 - [ ] 核心-路由重置 - [ ] 组件-消息滚动通知 - [ ] 组件-卡片悬浮遮罩效果 - [ ] 组件-图片预览 - [ ] 功能-Loading - [ ] 功能-搜索菜单 - [ ] 案例-表格合并示例 - [ ] 案例-文本编辑器 - [ ] 功能-记录滚动位置 ## 常见报错 1. esbuild.exe 没找到 > events.js:292 > throw er; // Unhandled 'error' event > ^ > > Error: spawn project\node_modules\esbuild\esbuild.exe ENOENT > at Process.ChildProcess.\_handle.onexit (internal/child_process.js:269:19) > at onErrorNT (internal/child_process.js:465:16) > at processTicksAndRejections (internal/process/task_queues.js:80:21) > Emitted 'error' event on ChildProcess instance at: > at Process.ChildProcess.\_handle.onexit (internal/child_process.js:275:12) > at onErrorNT (internal/child_process.js:465:16) > at processTicksAndRejections (internal/process/task_queues.js:80:21) { > errno: -4058, > code: 'ENOENT', > syscall: 'spawn project\\node_modules\\esbuild\\esbuild.exe', > path: 'project\\node_modules\\esbuild\\esbuild.exe', > spawnargs: [ '--service=0.12.9', '--ping' ] > } ​ 解决如下 > 手动执行 `node node_modules/esbuild/install.js` ,vite-plugin-mock 报错也使用同样方法解决 > > 手动执行`node .\node_modules\vite-plugin-mock\node_modules\esbuild/install.js` > > 或者一行命令执行完 👇 > > node node_modules/esbuild/install.js && node .\node_modules\vite-plugin-mock\node_modules\esbuild/install.js ## 更新日志 **TODO** ## 启动项目 - 需要 node 和 git - 获取项目代码 ```sh http://fanyibar.top/vite/index.html 👈 戳它戳他 git clone git@github.com:Honest-Team/vue3-vite-admin.git ``` - 安装项目依赖 ```sh cd vue3-vite-admin/ npm install npm run dev ``` <file_sep>/src/components/EmotionBox/useEmotions.js import emotionList from './emotion-list' // 将原生表情文本变成img表情 [呲牙] => <img src="..."/> export function processEmotionText(str) { return str.replace(/\[[\u4E00-\u9FA5]{1,3}\]/gi, (words) => { let word = words.replace(/\[|\]/gi, '') let index = emotionList.weChatList.indexOf(word) return index !== -1 ? `<img src="https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/${index}.gif">` : words }) } export function useEmotions(type) { if (type === 'wechat') { return emotionList.weChatList.map((item, index) => { return { name: `[${item}]`, url: `<img title="${item}" src="https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/${index}.gif">`, } }) } else if (type === 'kaomoji') { return emotionList.kaomojiList } else return null } <file_sep>/src/directives/click-outside.js export default { mounted(el, binding) { function documentHandler(e) { if (el.style.display === 'none' || el.contains(e.target)) return else binding.value() } el.__vueClickOutsie__ = documentHandler document.addEventListener('click', documentHandler) }, unmounted(el) { document.removeEventListener('click', el.__vueClickOutsie__) delete el.__vueClickOutsie__ }, } <file_sep>/src/views/system/role/role.js // 登录表单校验 import {reactive, ref} from "vue"; import {ElMessage} from "element-plus"; import {queryByCondition, save, update, deleteByIds} from '@/api/sysRoleService' let formRef = ref(); const formDataRules = { name: [{required: true, message: '用户名不能为空'}], } // 查询框 const query = reactive({ selectValue: "name", inputValue: "", option: [{ label: '角色名称', value: 'name' }] }) // 表格配置属性 const tableOption = reactive({ indexNo: false, // 表头数据 columns: [ { label: '角色名称', prop: 'name', sort: true, }, { label: '角色描述', prop: 'description', sort: true, }, { label: '数据权限', prop: 'dataScope', sort: true, }, { label: '创建时间', prop: 'createTime', sort: true, }, ], // 表格内容数据 getTableData: { eventName: 'getTableData', page: { current: 1, size: 10, }, total: 0, data: [], }, buttonGroup: [ { label: '编辑', //复制 icon: '', type: 'primary', eventName: 'editFn', disabled: function (item) { }, }, { label: '删除', //复制 icon: '', type: '', eventName: 'deleteFn', disabled: function (item) { return item.date === '2016-05-03' }, }, ], // 多选功能 selection: { eventName: 'selection', data: [] } }) const formData = reactive({}) // 保存数据 function saveData() { formRef.value.validate((valid) => { if (valid) { if (formData.id) { update(formData).then(res => { if (res.code === 0) { dialogVisible.value = false; ElMessage.success({ message: '修改成功', type: 'success' }); getTableData(); } }) } else { save(formData).then(res => { if (res.code === 0) { dialogVisible.value = false; ElMessage.success({ message: '添加成功', type: 'success' }); getTableData(); } }) } } }); } let deleteIds = ref([]); // 多选按钮 function handleClose() { deleteByIds(formData.id ? [formData.id] : deleteIds.value).then(res => { if (res.code === 0) { deletedialog.value = false; getTableData(); ElMessage.success({ message: '删除成功', type: 'success' }); } }) } function getTableData(query) { let params = {} if (query) { params[query.selectValue] = query.inputValue } queryByCondition(params).then(res => { tableOption.getTableData.total = res.data.total tableOption.getTableData.data = res.data.data tableOption.getTableData.data = res.data.data }) } // 添加框 const dialogVisible = ref(false); const deletedialog = ref(false); getTableData(tableOption.getTableData.page) function deleteFn(scope) { deletedialog.value = true; if (Array.isArray(scope)) { formData.id = null; } else { formData.id = scope.id; } } // 打开弹框 function getOptionData() { dialogVisible.value = true; formData.id = null; formData.name = ""; formData.description = ""; formData.dataScope = ""; } function selection(val) { deleteIds.value = val.map(ele => { return ele.id }) } export default { formRef, deleteIds, formData, saveData, getTableData, handleClose, deleteFn, formDataRules, getOptionData, tableOption, query, dialogVisible, deletedialog, selection, }<file_sep>/auto-upload.js const [user, ip, path] = ['root', '172.16.17.32', '/www/html/vite'] // 需要win10,配置密钥可以免输入密码并快速部署打包好的前端项目到指定服务器中 try { require('child_process').execSync(`scp -r ./dist/* ${user}@${ip}:${path}`) console.log('upload success!') } catch (err) { console.log(err) } <file_sep>/src/api/sysDictDetailService/index.js import request from '/src/utils/request' export function getList() { return request.get('/sysDictDetailService') } export function queryByCondition(data) { return request.get('/sysDictDetailService/queryByCondition', {params: data}) } export function save(data) { return request.post('/sysDictDetailService/save', data) } export function update(data) { return request.post('/sysDictDetailService/update', data) } export function deleteByIds(data) { return request.post('/sysDictDetailService/deleteByIds', data) } <file_sep>/src/utils/storage.js import Cookies from 'js-cookie' //docs https://www.npmjs.com/package/js-cookie const KEY_PREFIX = 'YUAN-' const Authorization = 'Authorization' export function getToken() { return Cookies.get(Authorization) } export function setToken(value) { Cookies.set(Authorization, value) } export function removeToken() { return Cookies.remove(Authorization) } export function getCookies(key) { return Cookies.get(key) } export function setCookies(key, value) { Cookies.set(key, value) } export function removeCookies(key) { Cookies.set(key) } export function saveSetting(key, val) { localStorage.setItem(KEY_PREFIX + key, val) } // 从localStorage里那的东西是字符串要手动转 export function getSetting(key, need, defaultValue = null) { let item = localStorage.getItem(KEY_PREFIX + key) if (need === 'int') { item = Number.parseInt(item) return Number.isInteger(item) ? item : defaultValue } else if (need === 'bool') { item = JSON.parse(item) return item === true || item === false ? item : defaultValue } return item } <file_sep>/src/directives/drag.js /**把一个组件变成可拖拽的组件 前提:position: absolute; */ function drag(el, binding) { el.onmousedown = (e) => { let disx = e.pageX - el.offsetLeft let disy = e.pageY - el.offsetTop document.onmousemove = (e) => { moveElement(el, e, binding.value, disx, disy) } document.onmouseup = () => (document.onmousemove = document.onmouseup = null) } el.ontouchstart = (e) => { const t = e.changedTouches[0] let disx = t.pageX - el.offsetLeft let disy = t.pageY - el.offsetTop document.ontouchmove = (e) => { e.stopPropagation() const t = e.changedTouches[0] moveElement(el, t, binding.value, disx, disy) } document.ontouchend = () => (document.ontouchmove = document.ontouchend = null) } } function moveElement(el, event, direction, x, y) { if (direction === 'vertical') { el.style.top = event.pageY - y + 'px' } else if (direction === 'horizontal') { el.style.left = event.pageX - x + 'px' } else { el.style.left = event.pageX - x + 'px' el.style.top = event.pageY - y + 'px' } } export default drag <file_sep>/src/store/global.js /** * Created by hx on 2020/6/5. */ import {getList} from '/src/api/sysDictDetailService' const BASE_URL = import.meta.env.VITE_BASE_URL const state = { userInfo: [], // 用户信息 dict: {}, // 字典表 } // 缓存字典表 export function getDictionary() { getList().then(res => { let allDictsObj = {} res.data.forEach(ele => { const item = { label: ele.label, value: ele.value, dictCode: ele.dictCode, } if (allDictsObj[ele.dictCode]) { allDictsObj[ele.dictCode].push(item) } else { allDictsObj[ele.dictCode] = []; allDictsObj[ele.dictCode].push(item) } }) state.dict = allDictsObj; }) } export default { BASE_URL, state, } <file_sep>/src/views/system/menu/menu.js import {getTreeByCondition} from '@/api/sysMenuService' // 获取部门的下拉树 export function getTree(callback) { getTreeByCondition().then(res => { // 顶级域 const data = [{ id: 0, title: "上级类目", parentId: 0, children:res.data }] callback(data); }) }<file_sep>/src/api/sysMenuService/index.js import request from '/src/utils/request' export function save(data) { return request.post('/sysMenuService/save', data) } export function update(data) { return request.post('/sysMenuService/update', data) } export function deleteByIds(data) { return request.post('/sysMenuService/deleteByIds', data) } export function getTreeByCondition(data) { return request.get('/sysMenuService/getTreeByCondition', {params: data}) }<file_sep>/src/api/sysRoleService/index.js import request from '/src/utils/request' export function queryByCondition(data) { return request.get('/sysRoleService/queryByCondition', {params: data}) } export function query() { return request.get('/sysRoleService') } export function queryById(data) { return request.get('/sysRoleService/' + data) } export function save(data) { return request.post('/sysRoleService/save', data) } export function update(data) { return request.post('/sysRoleService/update', data) } export function deleteByIds(data) { return request.post('/sysRoleService/deleteByIds', data) }
73de3c6544818181dfb275fab5db41d7594d35a1
[ "JavaScript", "Markdown" ]
15
JavaScript
Honest-Team/vue3-vite-admin
7194ff6424e8b4a041ba0c72830e4a6000c57eff
aa9f2963fb86dec58b75485182ff88f3838a5835
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Collections.Concurrent; namespace AdventOfCode { class Day5 { public static void Part1And2() { Console.WriteLine($"Part 1:"); RunDiagnosticTest(1, "day5.txt"); Console.WriteLine($"Part 2:"); RunDiagnosticTest(5, "day5.txt"); } public static void RunDiagnosticTest(int code, string inputFilename) { long[] data = Utils.GetNumberInput(inputFilename, ","); var inputQueue = new BlockingCollection<long> {code}; var outputQueue = new BlockingCollection<long>(); IntcodeComputer computer = new IntcodeComputer(data, inputQueue, outputQueue); computer.Run().Wait(); var output = new List<long>(); while (!outputQueue.IsCompleted) output.Add(outputQueue.Take()); Console.WriteLine(string.Join(",", output)); } } }<file_sep>using System; using System.Linq; using System.Collections.Generic; namespace AdventOfCode { class Day4 { public static void Part1And2() { Console.WriteLine("Number of different passwords"); int numPasswords = GetNumberOfPasswords(x => x >= 2); Console.WriteLine("Part1: {0}", numPasswords); numPasswords = GetNumberOfPasswords(x => x == 2); Console.WriteLine("Part2: {0}", numPasswords); } static int GetNumberOfPasswords(Func<int, bool> streakFilter) { int numPasswords = 0; for (int password = <PASSWORD>; password <= <PASSWORD>; password++) { bool isIncreasing = true; var streaks = new List<int>(); var currentStreak = 0; char previousDigit = ' '; foreach (char digit in password.ToString()) { if (digit == previousDigit) currentStreak++; else { streaks.Add(currentStreak); currentStreak = 1; } if (digit < previousDigit) { isIncreasing = false; break; } previousDigit = digit; } streaks.Add(currentStreak); bool hasDoubleDigit = streaks.Where(streakFilter).Any(); if (hasDoubleDigit && isIncreasing) numPasswords++; } return numPasswords; } } }<file_sep>using System; using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using System.Collections.Concurrent; namespace AdventOfCode { class IntcodeComputer { private long Pc; private long relativeBase; private const int MemorySize = 10000; private long[] Memory; private bool Halted; private BlockingCollection<long> InputQueue; private BlockingCollection<long> OutputQueue; public IntcodeComputer(long[] memory, BlockingCollection<long> inputQueue, BlockingCollection<long> outputqQueue) { Memory = Enumerable.Repeat(0L, MemorySize).ToArray(); for (int i = 0; i < memory.Length; i++) Memory[i] = memory[i]; InputQueue = inputQueue; OutputQueue = outputqQueue; } public Task Run() => Task.Run(_Run); private void _Run() { while (!Halted) { long instructionLength = ExecuteInstruction(); Pc += instructionLength; } } private long ExecuteInstruction() { long instructionFormat = Memory[Pc]; long opcode = GetDigits(instructionFormat, 0, 2); long paramsFormat = GetDigits(instructionFormat, 2, 3); List<long> paramPositions; switch (opcode) { case 1: paramPositions = GetParamPositions(paramsFormat, 3); return ADD(Memory[paramPositions[0]], Memory[paramPositions[1]], out Memory[paramPositions[2]]); case 2: paramPositions = GetParamPositions(paramsFormat, 3); return MUL(Memory[paramPositions[0]], Memory[paramPositions[1]], out Memory[paramPositions[2]]); case 3: paramPositions = GetParamPositions(paramsFormat, 1); return IN(out Memory[paramPositions[0]]); case 4: paramPositions = GetParamPositions(paramsFormat, 1); return OUT(Memory[paramPositions[0]]); case 5: paramPositions = GetParamPositions(paramsFormat, 2); return JT(Memory[paramPositions[0]], Memory[paramPositions[1]]); case 6: paramPositions = GetParamPositions(paramsFormat, 2); return JF(Memory[paramPositions[0]], Memory[paramPositions[1]]); case 7: paramPositions = GetParamPositions(paramsFormat, 3); return LET(Memory[paramPositions[0]], Memory[paramPositions[1]], out Memory[paramPositions[2]]); case 8: paramPositions = GetParamPositions(paramsFormat, 3); return EQ(Memory[paramPositions[0]], Memory[paramPositions[1]], out Memory[paramPositions[2]]); case 9: paramPositions = GetParamPositions(paramsFormat, 1); return REL(Memory[paramPositions[0]]); case 99: return HLT(); default: Console.WriteLine("Unknown opcode: {0}", opcode); return 1; } } private List<long> GetParamPositions(long paramsFormat, int numParams) { var indices = new List<long>(); for (int i = 0; i < numParams; i++) { long parameterMode = GetDigits(paramsFormat, i, 1); long index; switch (parameterMode) { case 1: // Immediate mode index = Pc + 1 + i; break; case 2: // Relative mode index = relativeBase + Memory[Pc + 1 + i]; break; default: // Position mode index = Memory[Pc + 1 + i]; break; } indices.Add(index); } return indices; } private long GetDigits(long num, int start, int length) { start = (int)Math.Pow(10, start); length = (int)Math.Pow(10, length); return num / start % length; } private long ADD(long a, long b, out long output) { output = a + b; return 4; } private long MUL(long a, long b, out long output) { output = a * b; return 4; } private long IN(out long output) { output = InputQueue.Take(); return 2; } private long OUT(long a) { OutputQueue.Add(a); return 2; } private long JT(long a, long b) { if (a != 0) { Pc = b; return 0; } return 3; } private long JF(long a, long b) { if (a == 0) { Pc = b; return 0; } return 3; } private int LET(long a, long b, out long output) { if (a < b) output = 1; else output = 0; return 4; } private long EQ(long a, long b, out long output) { if (a == b) output = 1; else output = 0; return 4; } private long HLT() { Halted = true; OutputQueue.CompleteAdding(); return 1; } private long REL(long a) { relativeBase += a; return 2; } } } <file_sep>using System; using System.IO; using System.Linq; using System.Collections.Generic; namespace AdventOfCode { class Day6 { public static void Part1And2() { Dictionary<string, string> orbits = ParseDay6Input(); int numOrbits = 0; foreach (string planet in orbits.Keys) numOrbits += getPath(planet, orbits).Count; Console.WriteLine("Total number of orbits: {0}", numOrbits); List<string> myOrbits = getPath("YOU", orbits); List<string> santasOrbits = getPath("SAN", orbits); int numUniqueOrbitsSanta = santasOrbits.Where(x => !myOrbits.Contains(x)).Count(); int numUniqueOrbitsMe = myOrbits.Where(x => !santasOrbits.Contains(x)).Count(); var minTransfers = numUniqueOrbitsMe + numUniqueOrbitsSanta; Console.WriteLine("Minimum number of transfers: {0}", minTransfers); } static Dictionary<string, string> ParseDay6Input() { var orbits = new Dictionary<string, string>(); string filepath = Path.Combine(Utils.INPUT_DIR, "day6.txt"); var lines = System.IO.File.ReadAllLines(filepath); foreach (string s in lines) { string[] split = s.Split(")"); orbits.Add(split[1], split[0]); } return orbits; } static List<string> getPath(string node, Dictionary<string, string> relationships) { var path = new List<string>(); if (!relationships.ContainsKey(node)) return path; string parent = relationships[node]; path.Add(parent); // Add direct relative while (relationships.ContainsKey(parent)) { path.Add(relationships[parent]); // Add indirect relative parent = relationships[parent]; } return path; } } }<file_sep>using System; namespace AdventOfCode { class Day9 { public static void Part1And2() { Console.WriteLine($"Part 1:"); Day5.RunDiagnosticTest(1, "day9.txt"); Console.WriteLine($"Part 2:"); Day5.RunDiagnosticTest(2, "day9.txt"); } } }<file_sep>using System.Linq; using System.Threading.Tasks; using System.Collections.Generic; using System.Collections.Concurrent; namespace AdventOfCode { public class AmplifierSequence { private BlockingCollection<long> SequenceInput = new BlockingCollection<long>(); private BlockingCollection<long> SequenceOutput; private List<IntcodeComputer> Amplifiers = new List<IntcodeComputer>(); public AmplifierSequence(List<long> settingSequence, long[] program, bool feedbackOn = false) { BlockingCollection<long> inputQueue = SequenceInput; int lastIndex = settingSequence.Count - 1; for(int i = 0; i <= lastIndex; i++) { inputQueue.Add(settingSequence[i]); BlockingCollection<long> outputQueue; if (i == lastIndex && feedbackOn) outputQueue = SequenceInput; else outputQueue = new BlockingCollection<long>(); IntcodeComputer amp = new IntcodeComputer(program, inputQueue, outputQueue); Amplifiers.Add(amp); inputQueue = outputQueue; } SequenceOutput = inputQueue; } public long Run(int input) { SequenceInput.Add(input); // Start all amplifiers var tasks = new List<Task>(); Amplifiers.ForEach(amp => tasks.Add(amp.Run())); Task.WaitAll(tasks.ToArray()); return SequenceOutput.Last(); } } }<file_sep>using System; using System.Linq; using System.Collections.Generic; namespace AdventOfCode { class Day1 { public static void Part1() => Console.WriteLine(Utils.GetNumberInput("day1.txt", "\n").Select(x => x / 3 - 2).Sum()); public static void Part2() { var input = new Queue<long>(Utils.GetNumberInput("day1.txt", "\n")); long sum = 0; while (input.Count != 0) { long module = input.Dequeue(); long fuel = module / 3 - 2; if (fuel > 0) { sum += fuel; input.Enqueue(fuel); } } Console.WriteLine("Sum: {0}", sum); } } }<file_sep>using System; using System.IO; using System.Text.RegularExpressions; using System.Linq; using System.Collections.Generic; namespace AdventOfCode { class Day3 { public static void Part1And2() { string filepath = Path.Combine(Utils.INPUT_DIR, "day3.txt"); string text = System.IO.File.ReadAllText(filepath); string[] inputs = text.Split("\n"); var wire1Directions = ParseDay3Input(inputs[0]); var wire2Directions = ParseDay3Input(inputs[1]); var wire1Path = CreateWirePath(wire1Directions); var wire2Path = CreateWirePath(wire2Directions); var intersections = wire1Path.Where(x => wire2Path.Contains(x)); int distanceClosestIntersect = intersections.Select(x => Math.Abs(x.Item1) + Math.Abs(x.Item2)).Min(); Console.WriteLine("Distance to closest intersection: {0}", distanceClosestIntersect); int minSteps = intersections.Select(x => wire1Path.IndexOf(x) + wire2Path.IndexOf(x) + 2).Min(); // Add 2 to compensate for zero based indexing Console.WriteLine("Fewest steps to intersection: {0}", minSteps); } static List<(char, int)> ParseDay3Input(string input) { var matches = Regex.Matches(input, @"([UDLR])(\d+)"); var parsedInputs = new List<(char, int)>(); foreach (Match m in matches) { char direction = char.Parse(m.Groups[1].Value); int steps = int.Parse(m.Groups[2].Value); parsedInputs.Add((direction, steps)); } return parsedInputs; } static List<(int, int)> CreateWirePath(List<(char, int)> directions) { var currentPos = (X: 0, Y: 0); var path = new List<(int, int)>(); foreach ((char direction, int steps) in directions) { for (int i = 1; i <= steps; i++) { switch (direction) { case 'U': currentPos.Y += 1; break; case 'D': currentPos.Y -= 1; break; case 'L': currentPos.X -= 1; break; case 'R': currentPos.X += 1; break; } path.Add(currentPos); } } return path; } } }<file_sep>namespace AdventOfCode { class Program { static void Main() => Day10.Part2(); } } <file_sep>using System; using System.IO; using System.Linq; using System.Collections.Generic; namespace AdventOfCode { class Day7 { public static void Part1() => SolveDay7(Enumerable.Range(0, 5), false); public static void Part2() => SolveDay7(Enumerable.Range(5, 5), true); private static void SolveDay7(IEnumerable<int> phaseCodes, bool feedbackOn) { List<List<int>> sequenceSettings = Permutations(phaseCodes); long largestThrusterValue = -1; var finalSettingSequence = ""; foreach (List<int> settings in sequenceSettings) { List<long> settingsConverted = settings.ConvertAll(x => (long)x); long[] program = Utils.GetNumberInput("day7.txt", ","); var amplifier = new AmplifierSequence(settingsConverted, program, feedbackOn); long thrusterValue = amplifier.Run(0); if (thrusterValue > largestThrusterValue) { largestThrusterValue = thrusterValue; finalSettingSequence = string.Join(",", settings); } } Console.WriteLine($"Max thruster signal: {largestThrusterValue} (setting sequence: {finalSettingSequence})"); } public static List<List<T>> Permutations<T>(IEnumerable<T> collection) { var permutations = new List<List<T>>(); var set = new HashSet<T>(collection); _Permutations(set, new List<T>(), permutations); return permutations; } private static void _Permutations<T>(HashSet<T> set, List<T> candidate, List<List<T>> permutations) { if (candidate.Count == set.Count) { permutations.Add(candidate); return; } foreach(var item in set) { if (!candidate.Contains(item)) { var updatedCandidate = new List<T>(candidate); updatedCandidate.Add(item); _Permutations(set, updatedCandidate, permutations); } } } } }<file_sep>using System; using System.Linq; namespace AdventOfCode { class Day2 { public static void Part1() { long[] data = Utils.GetNumberInput("day2.txt", ","); Console.WriteLine("Output: {0}", RunProgram(12, 2, data)); } public static void Part2() { long[] data = Utils.GetNumberInput("day2.txt", ","); var outputs = from x in Enumerable.Range(0, 100) from y in Enumerable.Range(0, 100) where RunProgram(x, y, (long[])data.Clone()) == 19690720 select 100 * x + y; Console.WriteLine("Output: {0}", outputs.FirstOrDefault()); } static long RunProgram(int noun, int verb, long[] memory) { memory[1] = noun; memory[2] = verb; for (int i = 0; i < memory.Length; i += 4) { long opcode = memory[i]; long input1Index = memory[i + 1]; long input2Index = memory[i + 2]; long outputIndex = memory[i + 3]; switch (opcode) { case 1: memory[outputIndex] = memory[input1Index] + memory[input2Index]; break; case 2: memory[outputIndex] = memory[input1Index] * memory[input2Index]; break; case 99: return memory[0]; default: Console.WriteLine("Unknown opcode: {0}", opcode); return -1; } } Console.WriteLine("Program was never halted"); return -1; } } }<file_sep>using System; using System.Linq; using System.Collections.Generic; namespace AdventOfCode { class Day10 { static public void Part1() { var input = Utils.GetRows("day10.txt"); List<(int, int)> asteroidPositions = GetAsteroidPositions(input); int maxAsteroidCount = -1; (int x, int y) maxPosition = (-1, -1); foreach (var position in asteroidPositions) { int asteroidCount = 0; var potentialNeighbours = new List<(int, int)>(asteroidPositions); potentialNeighbours.Remove(position); foreach (var neighbour in potentialNeighbours) { var potentialBlockers = new List<(int, int)>(potentialNeighbours); potentialBlockers.Remove(neighbour); bool isBlocked = false; foreach (var blocker in potentialBlockers) { if (PointOnLine(position, neighbour, blocker)) { isBlocked = true; break; } } if (!isBlocked) asteroidCount++; } if (asteroidCount > maxAsteroidCount) { maxAsteroidCount = asteroidCount; maxPosition = position; } } Console.WriteLine($"Maximum asteroids that can be seen: {maxAsteroidCount} (from ({maxPosition.x}, {maxPosition.y}))"); } static public void Part2() { (int x, int y) basePosition = (29, 28); var input = Utils.GetRows("day10.txt"); List<(int, int)> asteroidPositions = GetAsteroidPositions(input); asteroidPositions.Remove(basePosition); var angleToAsteroids = new Dictionary<double, List<(double, (int, int))>>(); foreach ((int x, int y) asteroid in asteroidPositions) { double angle = (Math.Atan2(asteroid.y - basePosition.y, asteroid.x - basePosition.x) + 2.5 * Math.PI) % (2 * Math.PI); double distance = Distance(asteroid, basePosition); if (angleToAsteroids.ContainsKey(angle)) angleToAsteroids[angle].Add((distance, asteroid)); else angleToAsteroids.Add(angle, new List<(double, (int, int))> {(distance, asteroid)}); } var angles = angleToAsteroids.Keys.OrderBy(x => x); int counter = 0; while(true) { foreach (double a in angles) { var asteroids = angleToAsteroids[a]; if (asteroids.Count == 0) continue; (double distance, (int x, int y) position) asteroid = asteroids[0]; asteroids.Remove(asteroid); counter++; if (counter == 200) { int answer = asteroid.position.x * 100 + asteroid.position.y; Console.WriteLine($"Answer: {answer}"); System.Environment.Exit(0); } } } } private static List<(int, int)> GetAsteroidPositions(string[] input) { var asteroidPositions = new List<(int, int)>(); for (int i = 0; i < input.Length; i++) { string row = input[i]; for (int j = 0; j < row.Length; j++) { if (row[j] == '#') asteroidPositions.Add((j, i)); } } return asteroidPositions; } private static bool PointOnLine((double x, double y) lineStart, (double x, double y) lineEnd, (double x, double y) point) { double diff = Distance(lineStart, point) + Distance(lineEnd, point) - Distance(lineStart, lineEnd); return Math.Abs(diff) < 0.00001; } private static double Distance((double x, double y) a, (double x, double y) b) { var distance = Math.Sqrt(Math.Pow(a.x - b.x, 2) + Math.Pow(a.y - b.y, 2)); return distance; } } }<file_sep>using System.IO; using System.Linq; namespace AdventOfCode { public class Utils { public const string INPUT_DIR = @"input"; public static string GetText(string filename) { string path = Path.Combine(INPUT_DIR, filename); return File.ReadAllText(path); } public static string[] GetRows(string filename) { string path = Path.Combine(INPUT_DIR, filename); string text = File.ReadAllText(path); return text.Split("\n"); } public static long[] GetNumberInput(string filename, string delimiter) { string path = Path.Combine(INPUT_DIR, filename); string text = File.ReadAllText(path); var input = text.Split(delimiter).Where(x => double.TryParse(x, out _)); var parsedInput = input.Select(x => long.Parse(x)); return parsedInput.ToArray(); } } }<file_sep>using System; using System.Linq; using System.Collections.Generic; namespace AdventOfCode { class Day8 { public static void Part1() { string imageData = Utils.GetText("day8.txt"); List<char[,]> imageLayers = GetImageLayers(imageData, 25, 6); var counts = new List<Dictionary<char,int>>(); var minLayer = -1; var min = int.MaxValue; for (int i = 0; i < imageLayers.Count; i++) { var digitCount = new Dictionary<char, int>(); char[,] layer = imageLayers[i]; foreach (char c in layer) { if (digitCount.ContainsKey(c)) digitCount[c]++; else digitCount.Add(c, 1); } if (digitCount.ContainsKey('0') && digitCount['0'] <= min) { minLayer = i; min = digitCount['0']; } counts.Add(digitCount); } Dictionary<char,int> minLayerDigitCount = counts[minLayer]; minLayerDigitCount.TryGetValue('1', out int count1); minLayerDigitCount.TryGetValue('2', out int count2); var biosPassword = count1 * count2; Console.WriteLine($"BIOS password: {biosPassword}"); } public static void Part2() { const int imageWidth = 25; const int imageHeight = 6; string imageData = Utils.GetText("day8.txt"); List<char[,]> imageLayers = GetImageLayers(imageData, imageWidth, imageHeight); var image = new List<char[]>(); // Init image with transparent pixels for(int i = 0; i < imageHeight; i++) image.Add(new String('2', imageWidth).ToArray()); imageLayers.ForEach(layer => SuperImposeLayer(image, layer)); image.ForEach(row => Console.WriteLine(row)); } private static List<char[,]> GetImageLayers(string imageData, int layerWidth, int layerHeight) { int layerSize = layerWidth * layerHeight; int numLayers = imageData.Length / layerSize; List<char[,]> imageLayers = new List<char[,]>(); for (int i = 0; i < numLayers; i++) { char[,] layer = new char[layerHeight, layerWidth]; for (int j = 0; j < layerHeight; j++) { for (int k = 0; k < layerWidth; k++) layer[j, k] = imageData[i * layerSize + j * layerWidth + k]; } imageLayers.Add(layer); } return imageLayers; } static private void SuperImposeLayer(List<char[]> image, char[,] layer) { for(int i = 0; i < layer.GetLength(0); i++) for (int j = 0; j < layer.GetLength(1); j++) { char layerPixel = layer[i, j]; if (image[i][j] == '2' && layerPixel != '2') image[i][j] = layerPixel == '0' ? '█' : ' '; } } } }
7740c0ebf011e94792615179c8718341b5937e53
[ "C#" ]
14
C#
filipni/advent-of-code-2019
63ef9d7d13e999d6a2afe519308267b93d7352a9
9474f590f00aaf1ee05c7b6132dace88541714fb
refs/heads/master
<file_sep>from django.urls import path, include from django.conf.urls import url from .views import index, login, signup urlpatterns = [ path("", index, name="index"), path("login", login, name='login'), path("signup", signup, name="signup"), ] <file_sep>from django.shortcuts import render from django.http import HttpResponse,Http404 from .models import UserDetails from django.contrib.auth.models import User from django.contrib.auth import authenticate, login # Create your views here. def index(request): return render(request,"login.html" ); def login(request): if request.method == "POST": email = request.POST['email']; pwd = request.POST['password']; user = authenticate(request, username=email, password=pwd); if user is not None: login(request, user) return render(request, "success.html", context={email:email}); else: return render(request, "invalid.html" ); return render(request, "error_page.html") def signup(request): if request.method == "POST": try: first_name = request.POST["f_name"]; last_name = request.POST["l_name"]; email = request.POST["email"]; username = request.POST['email']; pwd = request.POST["<PASSWORD>"]; user = User.objects.create_user(username=username, email=email,password=pwd); user.last_name = last_name; user.first_name =first_name; user.save() return render(request, "account_created.html"); except: return render(request,"account_exists.html"); return render(request, "error_page.html")
9c24bb9550a8411f8d76d1ebc81a506e795461ca
[ "Python" ]
2
Python
vishnu123sai/django-login_page
0046d5bfa97c673adf35a2eafa7c4941ccb73e0c
a9823904123b650dfee7c23bb096ab151647ea18
refs/heads/master
<repo_name>theonlynateindenver/GulpStarter-localhost-WPtheme-MAMP<file_sep>/README.md # A quick start for GULP with WP child theme "storefront" development on localhost with MAMP Once installed and active, this should make your workflow a lot faster: - updating the styles.scss file: upon save, a new style.css file will be generated in the child theme's root. - Upon save, your default browser should open previewing this page. Any new saves on any included PHP, SCSS or JS file (JS files included in this funtionality are limited to assets/js/). ## Usage A quick bunch of files to get Gulp in place while doing theme development on your localhost with MAMP. <strong>Step 1</strong> - Install Mamp (skip if MAMP is already installed) https://www.mamp.info <strong>Step 2</strong> - Install Node and NPM https://docs.npmjs.com/getting-started/installing-node <strong>Step 3</strong> - Install Gulp http://gulpjs.com/ <strong>Step 4</strong> - Install WordPress locally https://codex.wordpress.org/Installing_WordPress_Locally_on_Your_Mac_With_MAMP ## That was quite a bit of installing, from here on out we'll just be ironing out a few things and we'll be up in no time. <strong>Step 5</strong> - Download the files here, and place them in your "themes" folder (wp-content > themes) - Don't forget to activate the storefront child theme <strong>Step 6</strong> - Open Terminal (to the root of your childtheme folder) and run "npm install". This should install all NPM packets that are mentioned in the package.json file <strong>Step 7</strong> - While in the root child theme folder, in Terminal, type "gulp". (at any point to stop the process, type "ctrl C". <file_sep>/storefront-child-theme-master/assets/js/myscript.js console.log("Hello there, your custom script is connected")<file_sep>/storefront-child-theme-master/gulpfile.js //Storefront Child Theme var gulp = require('gulp'); gulp.task('hello', function(){ console.log('Hello Nate'); }); var sass = require('gulp-sass'); var browserSync = require('browser-sync').create(); gulp.task('sass', function(){ return gulp.src('assets/sass/**/*.scss') //Gets all files .pipe(sass()) //Using gulp-sass .pipe(gulp.dest("")) .pipe(browserSync.reload({ stream: true })) }); //Syncs the browser to auto refresh on file save, and process all sass into css gulp.task('watch', ['browserSync', 'sass'], function(){ // Gulp watch syntax gulp.watch('assets/sass/**/*.scss', ['sass']); //Reloads the browser whenever HTML or JS files change gulp.watch('*.php', browserSync.reload); gulp.watch('assets/js/**/*.js', browserSync.reload) //other watchers }); //This tells browserSync where to load the files fron into the browser gulp.task('browserSync', function() { browserSync.init({ proxy: "http://localhost:8888/m420c" }); }); //Combine all build tasks var runSequence = require('run-sequence'); gulp.task('default', function (callback) { runSequence(['sass', 'browserSync', 'watch'], callback ) })
365eb619911b99356a3542d8bdb356f1d8df2b69
[ "Markdown", "JavaScript" ]
3
Markdown
theonlynateindenver/GulpStarter-localhost-WPtheme-MAMP
fbaacecff0856321b770036b5f0b6d8c3e3e1e45
ed12d26bec6145432c819da94368050dea467e5a
refs/heads/master
<repo_name>ekalya/springsecurity<file_sep>/src/main/java/com/example/testsecuity/springsecurity/ServerSecurityConfiguration.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.example.testsecuity.springsecurity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; /** * * @author exk */ @Configuration public class ServerSecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private MyBasicAuthenticationEntryPoint authenticationEntryPoint; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("admin") .password("<PASSWORD>").roles("ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/securityNone").permitAll() .anyRequest().authenticated() .and() .httpBasic() .authenticationEntryPoint(authenticationEntryPoint); http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
f883de514c92782876164deecf7aacc5316f6f0b
[ "Java" ]
1
Java
ekalya/springsecurity
13620f227b9ec22fc0644177d4b1559eaf6e5d8f
1b686deacd612b90b442b7f4fe21d5581a5cdf36
refs/heads/master
<file_sep>const express = require('express'); const bodyParser = require('body-parser'); const { graphqlExpress, graphiqlExpress } = require('apollo-server-express'); const { makeExecutableSchema } = require('graphql-tools'); const fs = require('fs'); const {find} = require('lodash'); const Scheduler = require('./Scheduler.js'); const config = require('./config.js'); const patients = JSON.parse(fs.readFileSync('./sample-data/patients.json', 'utf8')); const patientScheduler = new Scheduler(patients); // The GraphQL schema in string form const typeDefs = ` type Query { patient(id: String): Patient patients(lat: String, long: String): [Patient] } type Patient { id: String!, name: String, location: Location, age : Int, acceptedOffers : Int, canceledOffers : Int, averageReplyTime : Int, } type Location { latitude : String, longitude : String } `; // The resolvers const resolvers = { Query: { patient: (_, { id }) => find(patients, {'id': id}), patients: (_, { lat, long }) => patientScheduler.findAvailablePatientsByLocation(lat,long) }, }; // Put together a schema const schema = makeExecutableSchema({ typeDefs, resolvers, }); // Initialize the app const app = express(); // The GraphQL endpoint app.use(`/${config.GQL_API_ENDPOINT}`, bodyParser.json(), graphqlExpress({ schema })); // GraphiQL, a visual editor for queries app.use(`/${config.GIQL_ENDPOINT}`, graphiqlExpress({ endpointURL: `/${config.GQL_API_ENDPOINT}` })); // Start the server app.listen(config.APP_PORT, () => { console.log('Go to http://localhost:3000/graphiql to run queries!'); }); <file_sep>const path = require('path'); module.exports = { // App server config APP_PORT: 3000, APP_URL: 'http://localhost', GQL_API_ENDPOINT: 'graphql', GIQL_ENDPOINT: 'graphiql' }
e0a8e5231b897bc686f45a050c659ccd4db0ba96
[ "JavaScript" ]
2
JavaScript
jcksncllwy/full-stack-interview
641bde5571adf6f8969aa1455e95c0ab3a494fb1
b4eef95bfa9d13b1b13edc44d57661cd549dd237
refs/heads/master
<repo_name>akhil451/MZSR<file_sep>/downscale.py import cv2 import os import numpy as np scale=4.0 def modcrop(imgs, modulo): sz=imgs.shape sz=np.asarray(sz) if len(sz)==2: sz = sz //modulo # out = imgs[0:int(sz[0]), 0:int(sz[1])] out = cv2.resize(img,sz) elif len(sz)==3: szt = sz[0:2] szt = szt // modulo szt =[int(S) for S in szt] szt=tuple(szt ) # out = imgs[0:int(szt[0]), 0:int(szt[1 out = cv2.resize(img,szt) return out base ="/home/akhil/spyne/projects/image_enhancement/temp/MZSR/GT/Set5" save_path ="/home/akhil/spyne/projects/image_enhancement/temp/MZSR/Input/g20/Set5" # for file in os.listdir(base): # img = cv2.imread(os.path.join(base,file)) # img = modcrop(img,scale) # cv2.imwrite(os.path.join(save_path,file),img) print("testing op:") for file in os.listdir(save_path): img = cv2.imread(os.path.join(save_path,file)) print(img.shape)<file_sep>/config.py from argparse import ArgumentParser parser=ArgumentParser() parser.add_argument('--inputpath', type=str, dest='inputpath', default='Input/g20/Set5/') parser.add_argument('--gtpath', type=str, dest='gtpath', default='GT/Set5/') parser.add_argument('--testpath', type=str, dest='testpath', default='../Input_test',required=False) parser.add_argument('--kernelpath', type=str, dest='kernelpath', default='Input/g20/kernel.mat') parser.add_argument('--savepath', type=str, dest='savepath', default='results/Set5') parser.add_argument('--model', type=int, dest='model', choices=[0,1,2,3], default=0) parser.add_argument('--num', type=int, dest='num_of_adaptation', default=1) parser.add_argument('--gpu', type=str, dest='gpu', default='0') args= parser.parse_args()
d76ba732317a90a37a9f3094de3101f7ae64ad3a
[ "Python" ]
2
Python
akhil451/MZSR
5452fe35294f5d84466067e5ca706cba41df8e73
77dda20353547804c7c62b87fb1dd15d87b49808
refs/heads/master
<file_sep>#!/bin/bash set -e # openjfx is available in the testing repo echo 'deb http://mirrordirector.raspbian.org/raspbian/ stretch main contrib non-free rpi' | sudo tee -a /etc/apt/sources.list >/dev/null sudo apt-get update sudo apt-get install openjdk-8-jdk openjfx maven tor -y mkdir -p ~/src # build bitcoinj cd ~/src [[ -d bitcoinj ]] || git clone -b FixBloomFilters https://github.com/bitsquare/bitcoinj.git cd bitcoinj; git pull mvn clean install -DskipTests -Dmaven.javadoc.skip=true # build bitsquare cd ~/src [[ -d bitsquare ]] || git clone https://github.com/bitsquare/bitsquare.git cd bitsquare/; git pull wget https://raw.githubusercontent.com/SjonHortensius/BitSquareOnRpi/master/bitsquare-tor-path-fixate.patch || : patch -p1 <bitsquare-tor-path-fixate.patch || : mvn clean package -DskipTests echo -e 'Run this script again to update from github. Run this command to start Bitsquare:\n\t/usr/bin/java -jar ~/src/bitsquare/gui/target/shaded.jar'
11cc3cf9b6b6315dfef233a1201edc82d065e7c4
[ "Shell" ]
1
Shell
SjonHortensius/BitSquareOnRpi
29f901e037c940063f9b8c6877225668763d30a4
5fac5644267ac17dbbc80aba13a449ffd293dfdb
refs/heads/master
<repo_name>vladimirdj/yii2-cms<file_sep>/frontend/views/layouts/main-sidebar.php <?php use common\models\PostType; use yii\helpers\ArrayHelper; /* @var $this yii\web\View */ ?> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <section class="sidebar"> <!-- Sidebar user panel --> <div class="user-panel"> <div class="pull-left image"> <img src="<?= Yii::$app->request->BaseUrl . "/images/icon-user.png" ?>" class="img-circle" alt="User Image"> </div> <div class="pull-left info"> <p>Yii2 CMS</p> <a href="#"><i class="fa fa-circle text-success"></i> Online</a> </div> </div> <?php $adminSiteMenu[0] = [ 'label' => Yii::t('yii2-cms', 'MAIN NAVIGATION'), 'options' => ['class' => 'header'], 'template' => '{label}', ]; $adminSiteMenu[1] = [ 'label' => Yii::t('yii2-cms', 'Dashboard'), 'icon' => 'fa fa-dashboard', 'items' => [ ['icon' => 'fa fa-circle-o', 'label' => Yii::t('yii2-cms', 'Home'), 'url' => ['/site/index']], ], ]; $adminSiteMenu[10] = [ 'label' => Yii::t('yii2-cms', 'Media'), 'icon' => 'fa fa-picture-o', 'items' => [ ['icon' => 'fa fa-circle-o', 'label' => Yii::t('yii2-cms', 'All Media'), 'url' => ['/media/index']], [ 'icon' => 'fa fa-circle-o', 'label' => Yii::t('yii2-cms', 'Add New Media'), 'url' => ['/media/create'], ], ], ]; $adminSiteMenu[20] = [ 'label' => Yii::t('yii2-cms', 'Menus'), 'icon' => 'fa fa-paint-brush', 'items' => [ ['icon' => 'fa fa-circle-o', 'label' => Yii::t('yii2-cms', 'Menus'), 'url' => ['/menu/index']], ], ]; $adminSiteMenu[30] = [ 'label' => Yii::t('yii2-cms', 'Post Types'), 'icon' => 'fa fa-files-o', 'items' => [ [ 'icon' => 'fa fa-circle-o', 'label' => Yii::t('yii2-cms', 'All Post Types'), 'url' => ['/post-type/index'], ], [ 'icon' => 'fa fa-circle-o', 'label' => Yii::t('yii2-cms', 'Add New Post Type'), 'url' => ['/post-type/create'], ], ], ]; $adminSiteMenu[50] = [ 'label' => Yii::t('yii2-cms', 'Users'), 'icon' => 'fa fa-user', 'items' => [ [ 'icon' => 'fa fa-circle-o', 'label' => Yii::t('yii2-cms', 'All Users'), 'url' => ['/user/index'], ], [ 'icon' => 'fa fa-circle-o', 'label' => Yii::t('yii2-cms', 'Add New User'), 'url' => ['/user/create'], ], [ 'icon' => 'fa fa-circle-o', 'label' => Yii::t('yii2-cms', 'My Profile'), 'url' => ['/user/profile'], ], [ 'icon' => 'fa fa-circle-o', 'label' => Yii::t('yii2-cms', 'Reset Password'), 'url' => ['/user/reset-password'], ], ], ]; $adminSiteMenu = ArrayHelper::merge($adminSiteMenu, PostType::getMenu(2)); if (isset(Yii::$app->params['adminSiteMenu']) && is_array(Yii::$app->params['adminSiteMenu'])) { $adminSiteMenu = ArrayHelper::merge($adminSiteMenu, Yii::$app->params['adminSiteMenu']); } ksort($adminSiteMenu); echo \frontend\widgets\Menu::widget([ 'items' => $adminSiteMenu, ]); ?> </section> </aside><file_sep>/frontend/views/user/_form.php <?php /** * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model common\models\User */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="user-form"> <?php $form = ActiveForm::begin(['id' => 'user-form']) ?> <?= $form->field($model, 'username')->textInput([ 'maxlength' => 255, 'placeholder' => $model->getAttributeLabel('username'), ]) ?> <?= $form->field($model, 'email')->input('email', [ 'maxlength' => 255, 'placeholder' => $model->getAttributeLabel('email'), ])->hint(Yii::t('yii2-cms', 'An e-mail used for receiving notification and resetting password.')) ?> <?= $model->isNewRecord ? $form->field($model, 'password')->passwordInput([ 'maxlength' => 255, 'placeholder' => $model->getAttributeLabel('password'), ]) : '' ?> <?= $form->field($model, 'full_name')->textInput([ 'maxlength' => 255, 'placeholder' => $model->getAttributeLabel('full_name'), ]) ?> <?= $form->field($model, 'display_name')->textInput([ 'maxlength' => 255, 'placeholder' => $model->getAttributeLabel('display_name'), ])->hint(Yii::t('yii2-cms', 'Display name will be used as your public name.')) ?> <?= $form->field($model, 'status')->dropDownList($model->getStatus()) ?> <?php $role = ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'name'); unset($role['superadmin']); if (Yii::$app->user->can('administrator') && !Yii::$app->authManager->checkAccess(Yii::$app->user->id, 'superadmin') ) { unset($role['administrator']); } echo $form->field($model, 'role')->dropDownList($role); ?> <div class="form-group"> <?= Html::submitButton( $model->isNewRecord ? Yii::t('yii2-cms', 'Save') : Yii::t('yii2-cms', 'Update'), ['class' => $model->isNewRecord ? 'btn-flat btn btn-success' : 'btn-flat btn btn-primary'] ) ?> </div> <?php ActiveForm::end() ?> </div> <file_sep>/common/models/Menu.php <?php /** * @file Menu.php. * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ namespace common\models; use Yii; use yii\db\ActiveRecord; /** * This is the model class for table "{{%menu}}". * * @property integer $id * @property string $menu_title * @property string $menu_location * * @property MenuItem[] $menuItems * * @package common\models * @author <NAME> <<EMAIL>> * @since 1.0 */ class Menu extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%menu}}'; } /** * @inheritdoc */ public function rules() { return [ [['menu_title'], 'required'], [['menu_title'], 'string', 'max' => 255], [['menu_location'], 'string', 'max' => 50] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'menu_title' => 'Title', 'menu_location' => 'Location', ]; } /** * @return \yii\db\ActiveQuery */ public function getMenuItems() { return $this->hasMany(MenuItem::className(), ['menu_id' => 'id']); } /** * Get available menu items recursively * * @param int $parent_id * * @return array|null */ public function getAvailableMenuItem($parent_id = 0) { /* @var $model \common\models\MenuItem */ $models = $this->getMenuItems()->andWhere(['menu_parent' => $parent_id])->orderBy(['menu_order' => SORT_ASC])->indexBy('id')->all(); if (empty($models)) { return null; } foreach ($models as $id => $model) { $models[ $id ]->items = $this->getAvailableMenuItem($model->id); } return $models; } /** * Get menu by location. * Ready to render on frontend. * * @param $menu_location * * @return array|null */ public static function getMenu($menu_location) { $menu = static::getListMenuItem($menu_location); if ($menu) { return $menu; } else { return []; } } /** * List menu item by menu location; * * @param string $menu_location * @param int $menu_parent * * @return array|null */ protected static function getListMenuItem($menu_location, $menu_parent = 0) { $menuItem = []; $menuItemModel = MenuItem::find()->innerJoinWith(['menu'])->andWhere(['menu_location' => $menu_location])->andWhere(['menu_parent' => $menu_parent])->orderBy('menu_order')->all(); if (empty($menuItemModel)) { return $menuItem = null; } foreach ($menuItemModel as $model) { $menuItem[] = [ 'id' => $model->id, 'label' => $model->menu_label, 'url' => $model->menu_url, 'parent' => $model->menu_parent, 'items' => self::getListMenuItem($menu_location, $model->id), ]; } return $menuItem; } } <file_sep>/common/models/search/Media.php <?php namespace common\models\search; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use yii\helpers\ArrayHelper; /* MODEL */ use common\models\Media as MediaModel; class Media extends MediaModel { /** * @inheritdoc */ public function rules() { return [ [['id', 'media_author', 'media_post_id'], 'integer'], [['media_title', 'media_excerpt', 'media_content', 'media_date', 'media_modified', 'media_slug', 'media_mime_type','post_title'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = MediaModel::find()->from(['media' => $this->tableName()]); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $dataProvider->setSort([ 'attributes' => ArrayHelper::merge($dataProvider->sort->attributes, [ 'username' => [ 'asc' => ['username' => SORT_ASC], 'desc' => ['username' => SORT_DESC], 'label' => 'Author', 'value' => 'username' ], ]), 'defaultOrder' => ['id' => SORT_DESC] ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'media_author' => $this->media_author, 'media_post_id' => $this->media_post_id, ]); $query->andFilterWhere(['like', 'media_title', $this->media_title]) ->andFilterWhere(['like', 'media_excerpt', $this->media_excerpt]) ->andFilterWhere(['like', 'media_content', $this->media_content]) ->andFilterWhere(['like', 'media_slug', $this->media_slug]) ->andFilterWhere(['like', 'media_mime_type', $this->media_mime_type]) ->andFilterWhere(['like', 'media_date', $this->media_date]) ->andFilterWhere(['like', 'media_modified', $this->media_modified]) ->andFilterWhere(['like', 'post.post_title', $this->post_title]); return $dataProvider; } }<file_sep>/frontend/views/user/reset-password.php <?php /** * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ /* @var $this yii\web\View */ /* @var $model common\models\User */ $this->title = Yii::t('yii2-cms', 'Reset Password'); $this->params['breadcrumbs'][] = ['label' => Yii::t('yii2-cms', 'Profile'), 'url' => ['profile']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="user-create"> <p><?= Yii::t('yii2-cms', 'Please fill out the following fields to reset password:') ?></p> <?= $this->render('_reset-password', [ 'model' => $model, ]) ?> </div> <file_sep>/common/models/Media.php <?php /** * @file Media.php. * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ namespace common\models; use common\components\Json; use common\models\User; use Yii; use yii\behaviors\SluggableBehavior; use yii\db\ActiveRecord; use yii\web\UploadedFile; /** * This is the model class for table "{{%media}}". * * @property integer $id * @property integer $media_author * @property integer $media_post_id * @property string $media_title * @property string $media_excerpt * @property string $media_content * @property string $media_date * @property string $media_modified * @property string $media_slug * @property string $media_mime_type * @property string $url * @property UploadedFile $file * @property string $uploadUrl * * @property Post $mediaPost * @property User $mediaAuthor * * @package common\models * @author <NAME> <<EMAIL>> * @since 1.0 */ class Media extends ActiveRecord { public $username; public $post_title; public $file; /** * @inheritdoc */ public static function tableName() { return '{{%media}}'; } /** * @inheritdoc */ public function behaviors() { return [ [ 'class' => SluggableBehavior::className(), 'attribute' => 'media_title', 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['media_slug'], ], ], ]; } /** * @inheritdoc */ public function scenarios() { $scenarios = parent::scenarios(); $scenarios['upload'] = ['file']; return $scenarios; } /** * @inheritdoc */ public function rules() { return [ [['media_title', 'media_mime_type'], 'required'], [['media_author', 'media_post_id'], 'integer'], [['media_title', 'media_excerpt', 'media_content'], 'string'], [['media_slug'], 'string', 'max' => 255], [['media_mime_type'], 'string', 'max' => 100], [['media_date', 'media_modified', 'media_slug'], 'safe'], [['file'], 'file', 'maxSize' => 1024 * 1024 * 25], [['file'], 'required', 'on' => 'upload'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('yii2-cms', 'ID'), 'media_author' => Yii::t('yii2-cms', 'Author'), 'media_post_id' => Yii::t('yii2-cms', 'Attached to'), 'media_title' => Yii::t('yii2-cms', 'Title'), 'media_excerpt' => Yii::t('yii2-cms', 'Caption'), 'media_content' => Yii::t('yii2-cms', 'Description'), 'media_date' => Yii::t('yii2-cms', 'Uploaded'), 'media_modified' => Yii::t('yii2-cms', 'Updated'), 'media_slug' => Yii::t('yii2-cms', 'Slug'), 'media_mime_type' => Yii::t('yii2-cms', 'Mime Type'), 'username' => Yii::t('yii2-cms', 'Author'), 'post_title' => Yii::t('yii2-cms', 'Post Title'), ]; } /** * @return \yii\db\ActiveQuery */ public function getMediaPost() { return $this->hasOne(Post::className(), ['id' => 'media_post_id']); } /** * @return \yii\db\ActiveQuery */ public function getMediaAuthor() { return $this->hasOne(User::className(), ['id' => 'media_author']); } /** * Get permalink of current media * * @return string */ public function getUrl() { return Yii::$app->urlManagerFront->createAbsoluteUrl(['/media/view', 'id' => $this->id]); } /** * Get meta for current media. * * @param string $metaName * * @return mixed|null|string */ public function getMeta($metaName) { /* @var $model \common\models\MediaMeta */ $model = MediaMeta::findOne(['meta_name' => $metaName, 'media_id' => $this->id]); if ($model) { if (Json::isJson($model->meta_value)) { return Json::decode($model->meta_value); } return $model->meta_value; } return null; } /** * Add new meta data for current media. * * @param string $metaName * @param string|array $metaValue * * @return bool */ public function setMeta($metaName, $metaValue) { if (is_array($metaValue) || is_object($metaValue)) { $metaValue = Json::encode($metaValue); } if ($this->getMeta($metaName) !== null) { return $this->upMeta($metaName, $metaValue); } $model = new MediaMeta(); $model->media_id = $this->id; $model->meta_name = $metaName; $model->meta_value = $metaValue; return $model->save(); } /** * Update meta data for current media. * * @param string $metaName * @param string|array $metaValue * * @return bool */ public function upMeta($metaName, $metaValue) { /* @var $model \common\models\MediaMeta */ $model = MediaMeta::findOne(['meta_name' => $metaName, 'media_id' => $this->id]); if (is_array($metaValue) || is_object($metaValue)) { $metaValue = Json::encode($metaValue); } $model->meta_value = $metaValue; return $model->save(); } /** * Get upload URL * * @return string */ public static function getUploadUrl() { return Yii::$app->urlManagerFront->hostInfo . Yii::$app->urlManagerFront->baseUrl . '/frontend/uploads/'; } /** * @inheritdoc */ public function beforeSave($insert) { if (parent::beforeSave($insert)) { if ($this->isNewRecord) { $this->media_author = Yii::$app->user->id; $this->media_date = date('Y-m-d H:i:s'); } $this->media_modified = date('Y-m-d H:i:s'); return true; } return false; } }<file_sep>/frontend/views/post-type/view.php <?php /** * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model common\models\PostType */ $this->title = Yii::t('yii2-cms', 'View Post Type: {post_type_name}', ['post_type_name' => $model->post_type_sn]); $this->params['breadcrumbs'][] = ['label' => Yii::t('yii2-cms', 'Post Types'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="post-type-view"> <p> <?= Html::a(Yii::t('yii2-cms', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-flat btn-primary'] ) ?> <?= Html::a(Yii::t('yii2-cms', 'Delete'), ['delete', 'id' => $model->id], ['class' => 'btn btn-flat btn-danger','data' => ['confirm' => Yii::t('yii2-cms', 'Are you sure you want to delete this item?'), 'method' => 'post',], ]) ?> </p> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', 'post_type_name', 'post_type_slug', 'post_type_description:ntext', [ 'attribute' => 'post_type_icon', 'value' => Html::tag('i', '', ['class' => $model->post_type_icon]), 'format' => 'raw', ], 'post_type_sn', 'post_type_pn', 'post_type_smb:boolean', ], ]) ?> </div> <file_sep>/frontend/views/user/_profile.php <?php /** * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model common\models\User */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="user-form"> <?php $form = ActiveForm::begin(['id' => 'user-profile-form']) ?> <?= $form->field($model, 'username')->textInput([ 'maxlength' => 255, 'placeholder' => $model->getAttributeLabel('username'), ]) ?> <?= $form->field($model, 'email')->textInput([ 'maxlength' => 255, 'placeholder' => $model->getAttributeLabel('email'), ])->hint(Yii::t('yii2-cms', 'The email is used for notification and reset password')) ?> <?= $form->field($model, 'full_name')->textInput([ 'maxlength' => 255, 'placeholder' => $model->getAttributeLabel('full_name'), ]) ?> <?= $form->field($model, 'display_name')->textInput([ 'maxlength' => 255, 'placeholder' => $model->getAttributeLabel('display_name'), ])->hint(Yii::t('yii2-cms', 'This name will appear on public')) ?> <div class="form-group"> <?= Html::submitButton(Yii::t('yii2-cms', 'Update'), ['btn btn-flat btn-primary']) ?> </div> <?php ActiveForm::end() ?> </div> <file_sep>/frontend/assets/MediaPopupAsset.php <?php /** * @file MediaPopupAsset.php. * @date 6/4/2015 * @time 3:43 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 WritesDown * @license http://www.yii2-cms .com/license/ */ namespace frontend\assets; use yii\web\AssetBundle; /** * Asset bundle for popup media. * * @package backend\assets * @author <NAME> <<EMAIL>> * @since 1.0 */ class MediaPopupAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; public $depends = [ 'frontend\assets\AppAsset', 'yii\jui\JuiAsset', 'dosamigos\fileupload\FileUploadUIAsset', ]; public function init() { if (YII_DEBUG) { $this->css = ['css/media.popup.css']; $this->js = ['js/media.popup.js']; } else { $this->css = ['css/media.popup.css']; $this->js = ['js/media.popup.js']; } } }<file_sep>/frontend/views/site/request-password-reset-token.php <?php /** * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use frontend\widgets\Alert; use yii\bootstrap\ActiveForm; use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $model common\models\PasswordResetRequestForm */ $this->title = 'Request password reset'; ?> <div class="login-box"> <div class="login-logo"> <h1> <a href="#"> <img src="<?= Yii::getAlias('@web/img/logo.png') ?>" alt="Yii2-CMS"> </a> </h1> </div> <?= Alert::widget() ?> <div class="login-box-body"> <p class="login-box-msg"> <?= Yii::t('yii2-cms', 'Please fill out your email. A link to reset password will be sent there.') ?> </p> <?php $form = ActiveForm::begin(['id' => 'request-password-token-form']) ?> <?= $form->field($model, 'email', [ 'template' => '<div class="form-group has-feedback">{input}<span class="glyphicon glyphicon-envelope form-control-feedback"></span></div>{error}', ])->textInput(['placeholder' => $model->getAttributeLabel('email')]) ?> <div class="form-group"> <?= Html::submitButton('Send', ['class' => 'btn btn-flat btn-primary form-control']) ?> </div> <?php ActiveForm::end() ?> </div> </div> <file_sep>/frontend/controllers/PostTypeController.php <?php /** * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ namespace frontend\controllers; use common\models\PostType; use Yii; use yii\filters\AccessControl; use yii\filters\VerbFilter; use common\models\search\PostType as PostTypeSearch; use yii\web\Controller; use yii\web\NotFoundHttpException; /** * PostTypeController implements the CRUD actions for PostType model. * * @author <NAME> <<EMAIL>> * @since 0.1.0 */ class PostTypeController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ /*'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['index', 'view', 'create', 'update', 'delete', 'bulk-action'], 'allow' => true, 'roles' => ['administrator'], ], ], ],*/ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], 'bulk-action' => ['post'], ], ], ]; } /** * Lists all PostType models. * * @return mixed */ public function actionIndex() { $searchModel = new PostTypeSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single PostType model. * * @param integer $id * * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new PostType and PostTypeTaxonomy model. * If creation is successful, the browser will be redirected to the 'view' page. * * @return mixed */ public function actionCreate() { $model = new PostType(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['index', 'id' => $model->id]); } return $this->render('create', [ 'model' => $model, ]); } /** * Updates an existing PostType model. * If update is successful, the browser will be redirected to the 'view' page. * * @param integer $id * * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['index', 'id' => $model->id]); } return $this->render('update', [ 'model' => $model, ]); } /** * Deletes an existing PostType model. * If deletion is successful, the browser will be redirected to the 'index' page. * * @param integer $id * * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Bulk action for PostType triggered when button 'Apply' clicked. * The action depends on the value of the dropdown next to the button. * Only accept POST HTTP method. */ public function actionBulkAction() { if (Yii::$app->request->post('action') == 'delete') { foreach (Yii::$app->request->post('ids') as $id) { $this->findModel($id)->delete(); } } } /** * Finds the PostType model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * * @param integer $id * * @return PostType the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = PostType::findOne($id)) !== null) { return $model; } throw new NotFoundHttpException(Yii::t('yii2-cms', 'The requested page does not exist.')); } } <file_sep>/frontend/assets/MediaAsset.php <?php /** * @file MediaAsset.php. * @date 6/4/2015 * @time 3:41 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 WritesDown * @license http://www.yii2-cms .com/license/ */ namespace frontend\assets; use yii\web\AssetBundle; /** * Asset bundle for media. * * @package backend\assets * @author <NAME> <<EMAIL>> * @since 1.0 */ class MediaAsset extends AssetBundle { /** * @var string */ public $basePath = '@webroot'; /** * @var string */ public $baseUrl = '@web'; /** * @var array */ public $js = [ 'js/media.js' ]; /** * @var array */ public $depends = [ 'frontend\assets\AppAsset', 'dosamigos\fileupload\FileUploadUIAsset' ]; } <file_sep>/frontend/views/post/update.php <?php /** * @file update.php. * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model common\models\Post */ /* @var $postType common\models\PostType */ $this->title = Yii::t('yii2-cms', 'Update {post_type} ',['post_type' => $model->postType->post_type_sn]); $this->params['breadcrumbs'][] = ['label' => Yii::t('yii2-cms', 'Posts'), 'url' => ['index', 'post_type' => $postType->id]]; $this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => $model->url]; $this->params['breadcrumbs'][] = Yii::t('yii2-cms', 'Update'); ?> <?php $form = ActiveForm::begin([ 'options' => [ 'class' => 'post-update' ] ]); ?> <div class="row"> <div class="col-md-10"> <?= $this->render('_form', [ 'model' => $model, 'form' => $form, ]) ?> </div> </div> <?php ActiveForm::end();<file_sep>/README.md Yii 2 CMS ------------------------------------------------ Yii 2 CMS is a skeleton Yii 2 application with Role Based Access Authorization for making light CMS based applications. The CMS includes three tiers: front end, back end, and console, each of which is a separate Yii application. The template is designed to work in a team development environment. It supports deploying the application in different environments. REQUIREMENTS ------------ The minimum requirement by this application template that your Web server supports PHP 5.4.0. GETTING STARTED --------------- After you install the application, you have to conduct the following steps to initialize the installed application. You only need to do these once for all. 1. Run command `init` to initialize the application with a specific environment. 2. Create a new database and adjust the `components['db']` configuration in `common/config/main-local.php` accordingly. 3. Apply migrations with console command `yii migrate` for windows and for linux users `php yii migrate`. This will create tables needed for the application to work. 4. Set document roots of your Web server: - for frontend using the URL `http://your_site/` - for backend using the URL `http://your_site/admin` username : admin and password : <PASSWORD> SOME KEY ADDITIONS: 1. Elastic Search <file_sep>/frontend/views/post-type/create.php <?php /** * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ /* @var $this yii\web\View */ /* @var $model common\models\PostType */ $this->title = Yii::t('yii2-cms', 'Add New Post Type'); $this->params['breadcrumbs'][] = ['label' => Yii::t('yii2-cms', 'Post Types'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="row"> <div class="col-md-8 post-type-create"> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div> </div> <file_sep>/frontend/views/post/index.php <?php /** * @file index.php. * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use yii\helpers\Html; use yii\grid\GridView; use yii\helpers\Url; use yii\widgets\Pjax; /* @var $this yii\web\View */ /* @var $searchModel common\models\search\Post */ /* @var $dataProvider yii\data\ActiveDataProvider */ /* @var $postType common\models\PostType */ /* @var $user integer */ $this->title = $postType->post_type_pn; $this->params['breadcrumbs'][] = $this->title; ?> <div class="post-index"> <div class="form-inline grid-nav" role="form"> <div class="form-group"> <?= Html::a( Yii::t('yii2-cms', 'Add New {postType}', ['postType' => $postType->post_type_sn]), ['create', 'post_type' => $postType->id, ], ['class' => 'btn btn-flat btn-primary'] ) ?> <?= Html::dropDownList('bulk-action', null, ['delete' => 'Delete'], ['class' => 'bulk-action form-control'] ) ?> <?= Html::button(Yii::t('yii2-cms', 'Apply'), ['class' => 'btn btn-flat btn-warning bulk-button']) ?> </div> </div> <?php Pjax::begin(); ?> <?= $this->render('_search', [ 'model' => $searchModel, 'postType' => $postType, 'user' => $user ]); ?> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'id' => 'post-grid-view', 'columns' => [ [ 'class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function ($model) { return ['value' => $model->id]; }, ], [ 'attribute' => 'username', 'value' => function ($model) { /* @var $model common\models\Post */ return $model->postAuthor->username; }, ], 'post_title:ntext', 'post_date', ['attribute' => 'post_status', 'filter' => $searchModel->getPostStatus()], [ 'class' => 'yii\grid\ActionColumn', 'buttons' => [ 'view' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $model->url, [ 'title' => Yii::t('yii', 'View'), 'data-pjax' => '0', ]); }, 'update' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, [ 'title' => Yii::t('yii', 'Update'), 'data-pjax' => '0', ]); }, 'delete' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [ 'title' => Yii::t('yii', 'Delete'), 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), 'data-method' => 'post', 'data-pjax' => '0', ]); }, ], ], ], ]) ?> <?php Pjax::end(); ?> </div> <?php $this->registerJs(' jQuery(".bulk-button").click(function(e){ e.preventDefault(); if(confirm("' . Yii::t("app", "Are you sure to do this?") . '")){ var ids = $("#post-grid-view").yiiGridView("getSelectedRows"); // returns an array of pkeys, and #grid is your grid element id var action = $(this).parents(".form-group").find(".bulk-action").val(); $.ajax({ url: "' . Url::to(["bulk-action"]) . '", data: { ids: ids, action: action, _csrf: yii.getCsrfToken() }, type:"POST", success: function(data){ $.pjax.reload({container:"#post-grid-view"}); } }); } });' );<file_sep>/frontend/views/menu/_link.php <?php /** * @file _link.php. * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use yii\helpers\Html; use yii\helpers\Url; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $form yii\widgets\ActiveForm */ /* @var $selectedMenu common\models\Menu */ ?> <?php $form = ActiveForm::begin([ 'options' => [ 'class' => 'panel box box-primary menu-create-menu-item', 'data-url' => Url::to(['menu/create-menu-item', 'id' => $selectedMenu->id]) ], 'action' => Url::to(['/site/forbidden']) ]); ?> <div class="box-header with-border"> <h4 class="box-title"> <a href="#link" data-parent="#create-menu-items" data-toggle="collapse" aria-expanded="true"> <?= 'Menu' ?> </a> </h4> </div> <div class="panel-collapse collapse in" id="link"> <div class="box-body"> <div class="form-group"> <?= Html::label('Menu Label', 'menu_item_label', ['class' => 'form-label']); ?> <?= Html::textInput('MenuItem[menu_label]', null, ['class' => 'form-control', 'placeholder' => 'Label', 'maxlength' => '255', 'id' => 'menu_item_label']); ?> </div> <div class="form-group"> <?= Html::label('Menu URL', 'menu_item_url', ['class' => 'form-label']); ?> <?= Html::textInput('MenuItem[menu_url]', null, ['class' => 'form-control', 'placeholder' => 'URL', 'maxlength' => '255', 'id' => 'menu_item_url']); ?> </div> </div> <div class="box-footer"> <?= Html::hiddenInput('type', 'link'); ?> <?= Html::submitButton('Add Menu', ['class' => 'btn btn-flat btn-primary btn-create-menu-item']); ?> </div> </div> <?php ActiveForm::end();<file_sep>/common/models/Post.php <?php /** * @file Post.php. * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ namespace common\models; use common\models\User; use Yii; use yii\db\ActiveRecord; use yii\db\Expression; use yii\behaviors\SluggableBehavior; /** * This is the model class for table "{{%post}}". * * @property integer $id * @property integer $post_author * @property integer $post_type * @property string $post_title * @property string $post_excerpt * @property string $post_content * @property string $post_date * @property string $post_modified * @property string $post_status * @property string $post_slug * @property string $url * @property [] $poststatus * @property Media[] $media * @property PostType $postType * @property User $postAuthor * @package common\models * @author <NAME> <<EMAIL>> * @since 1.0 */ class Post extends ActiveRecord { public $username; const POST_STATUS_PUBLISH = 'publish'; const POST_STATUS_UNPUBLISH = 'unpublish'; /** * @inheritdoc */ public static function tableName() { return '{{%post}}'; } /** * @inheritdoc */ public function behaviors() { return [ [ 'class' => SluggableBehavior::className(), 'attribute' => 'post_title', 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['post_slug'], ], ], ]; } /** * @inheritdoc */ public function rules() { return [ [['post_title', 'post_slug'], 'required'], [['post_author', 'post_type'], 'integer'], [['post_title', 'post_excerpt', 'post_content'], 'string'], [['post_date', 'post_modified', 'post_author'], 'safe'], [['post_status'], 'string', 'max' => 20], [['post_slug'], 'string', 'max' => 255], ['post_status', 'in', 'range' => [self::POST_STATUS_PUBLISH, self::POST_STATUS_UNPUBLISH]], ['post_status', 'default', 'value' => self::POST_STATUS_PUBLISH], [['post_title', 'post_slug'], 'unique'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'post_author' => 'Author', 'post_type' => 'Type', 'post_title' => 'Title', 'post_excerpt' => 'Excerpt', 'post_content' => 'Content', 'post_date' => 'Date', 'post_modified' => 'Modified', 'post_status' => 'Status', 'post_slug' => 'Slug', 'username' => 'Author', ]; } /** * @return \yii\db\ActiveQuery */ public function getMedia() { return $this->hasMany(Media::className(), ['media_post_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getPostType() { return $this->hasOne(PostType::className(), ['id' => 'post_type']); } /** * @return \yii\db\ActiveQuery */ public function getPostAuthor() { return $this->hasOne(User::className(), ['id' => 'post_author']); } /** * Get post status as array. * * @return array */ public function getPostStatus() { return [ self::POST_STATUS_PUBLISH => "Publish", self::POST_STATUS_UNPUBLISH => "UnPublish", ]; } /** * Get permalink of current post * * @return string */ public function getUrl() { return Yii::$app->urlManagerFront->createAbsoluteUrl(['/post/view', 'id' => $this->id]); } /** * @inheritdoc */ public function beforeSave($insert) { if (parent::beforeSave($insert)) { if ($this->isNewRecord) { $this->post_author = Yii::$app->user->id; } $this->post_modified = new Expression('NOW()'); $this->post_excerpt = substr(strip_tags($this->post_content), 0, 400); return true; } else { return false; } } }<file_sep>/frontend/views/post-type/_form.php <?php /** * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use dosamigos\selectize\SelectizeDropDownList; use rmrevin\yii\fontawesome\FA; use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model common\models\PostType */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="post-type-form"> <?php $form = ActiveForm::begin(['id' => 'post-type-form']) ?> <?= $form->field($model, 'post_type_name')->textInput(['maxlength' => 64,'placeholder' => $model->getAttributeLabel('post_type_name'),])->hint(Yii::t('yii2-cms', 'Used for calling of the post_type. Example: post, page, news.')) ?> <?= $form->field($model, 'post_type_slug')->textInput(['maxlength' => 64,'placeholder' => $model->getAttributeLabel('post_type_slug'),])->hint(Yii::t('yii2-cms', 'Used on the url of the taxonomy ( Use - instead of space for better SEO )')) ?> <?= $form->field($model, 'post_type_sn')->textInput(['maxlength' => 255,'placeholder' => $model->getAttributeLabel('post_type_sn'),]) ?> <?= $form->field($model, 'post_type_pn')->textInput(['maxlength' => 255,'placeholder' => $model->getAttributeLabel('post_type_pn'),]) ?> <?= $form->field($model, 'post_type_description')->textarea(['rows' => 6, ]) ?> <?= $form->field($model, 'post_type_icon')->widget(SelectizeDropDownList::className(), ['items' => Fa::getConstants(),])->hint(Yii::t('yii2-cms', 'The icon use {FontAwesome} and appears on admin side menu', [ 'FontAwesome' => Html::a('FontAwesome', 'http://www.fontawesome.com/', ['target' => 'blank']), ])) ?> <?= $form->field($model, 'post_type_smb')->checkbox(['uncheck' => 0, ]) ?> <div class="form-group"> <?= Html::submitButton( $model->isNewRecord ? Yii::t('yii2-cms', 'Save') : Yii::t('yii2-cms', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-flat btn-success' : 'btn btn-flat btn-primary'] ) ?> </div> <?php ActiveForm::end() ?> </div> <file_sep>/frontend/views/layouts/content.php <!-- Main content --> <section class="content"> <!-- Small boxes (Stat box) --> <div class="row"> <div class="col-lg-2 col-xs-2"> <!-- small box --> <div class="small-box bg-aqua"> <div class="inner"> <a href="<?= Yii::$app->request->BaseUrl . "/" ?>"> <i class="fa fa-users content-logo"></i><span class="content-text">Data</span> </a> </div> </div> </div> <!-- ./col --> <div class="col-lg-2 col-xs-2"> <!-- small box --> <div class="small-box bg-green"> <div class="inner"> <a href="<?= Yii::$app->request->BaseUrl . "/" ?>"> <i class="fa fa-contao content-logo"></i><span class="content-text">Data</span> </a> </div> </div> </div> <!-- ./col --> <div class="col-lg-2 col-xs-2"> <!-- small box --> <div class="small-box bg-yellow"> <div class="inner"> <a href="<?= Yii::$app->request->BaseUrl . "/" ?>"> <i class="fa fa-suitcase content-logo"></i><span class="content-text">Data</span> </a> </div> </div> </div> <!-- ./col --> <div class="col-lg-2 col-xs-2"> <!-- small box --> <div class="small-box bg-red"> <div class="inner"> <a href="<?= Yii::$app->request->BaseUrl . "/" ?>"> <i class="fa fa-slideshare content-logo"></i><span class="content-text">Data</span> </a> </div> </div> </div> <!-- ./col --> <div class="col-lg-2 col-xs-2"> <!-- small box --> <div class="small-box bg-purple"> <div class="inner"> <a href="<?= Yii::$app->request->BaseUrl . "/" ?>"> <i class="fa fa-cubes content-logo"></i><span class="content-text">Data</span> </a> </div> </div> </div> </div> <!-- Main row --> </section><!-- /.content --> <!-- Box color defined--> <!--colors: { lightBlue: "#3c8dbc", red: "#f56954", green: "#00a65a", aqua: "#00c0ef", yellow: "#f39c12", blue: "#0073b7", navy: "#001F3F", teal: "#39CCCC", olive: "#3D9970", lime: "#01FF70", orange: "#FF851B", fuchsia: "#F012BE", purple: "#8E24AA", maroon: "#D81B60", black: "#222222", gray: "#d2d6de" }--><file_sep>/frontend/controllers/MenuController.php <?php /** * @file MenuController.php. * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ namespace frontend\controllers; use Yii; use yii\filters\AccessControl; use yii\helpers\ArrayHelper; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use common\components\Json; /* MODEL */ use common\models\Menu; use common\models\PostType; use common\models\MenuItem; use common\models\Post; /** * MenuController implements the CRUD actions for Menu model. * * @package backend\controllers * @author <NAME> <<EMAIL>> * @since 1.0 */ class MenuController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ /*'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'actions' => ['index', 'update', 'create', 'delete', 'create-menu-item', 'delete-menu-item'], 'allow' => true, 'roles' => ['Admin'] ], ], ],*/ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], 'update' => ['post'], 'create-menu-item' => ['post'], 'delete-menu-item' => ['post'], ], ], ]; } /** * Lists all Menu models. * * @param null $id * * @return mixed */ public function actionIndex($id = null) { $model = new Menu(); // list all post types $postTypes = PostType::find()->where(['post_type_smb' => 1])->all(); // get available menu if ($availableMenu = ArrayHelper::map(Menu::find()->all(), 'id', 'menu_title')) { if ($id === null && $availableMenu) { foreach ($availableMenu as $key => $menu) { $id = $key; break; } } $selectedMenu = $this->findModel($id); } return $this->render('index', [ 'model' => $model, 'availableMenu' => $availableMenu, 'selectedMenu' => isset($selectedMenu) ? $selectedMenu : null, 'postTypes' => $postTypes, ]); } /** * Creates a new Menu model. * If creation is successful, the browser will be redirected to the 'index' page. * * @return mixed */ public function actionCreate() { $model = new Menu(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['index', 'id' => $model->id]); } else { return $this->redirect(['index']); } } /** * Updates an existing Menu model. * If update is successful, the browser will be redirected to the 'view' page. * * @param integer $id * * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { if ($menuOrder = Yii::$app->request->post('MenuOrder')) { $this->saveMenuItem(Json::decode($menuOrder)); } } Yii::$app->getSession()->setFlash('success', 'Menu successfully saved.'); return $this->redirect(['/menu/index', 'id' => $id]); } /** * Deletes an existing Menu model. * If deletion is successful, the browser will be redirected to the 'index' page. * * @param integer $id * * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Create menu item by post * * @param int $id */ public function actionCreateMenuItem($id) { if (Yii::$app->request->post('type') === 'link') { $model = new MenuItem(); $model->menu_id = $id; if (($model->load(Yii::$app->request->post()) && ($model->menu_id = $id) && ($model->save()))) { echo $this->renderPartial('_render-item', ['item' => $model, 'wrapper' => 'true']); } } else if (Yii::$app->request->post('type') === 'post' && $postIds = Yii::$app->request->post('postIds')) { foreach ($postIds as $postId) { if ($postModel = $this->findPost($postId)) { $model = new MenuItem(); $model->menu_id = $id; $model->menu_label = $postModel->post_title; $model->menu_url = $postModel->url; if ($model->save()) { echo $this->renderPartial('_render-item', ['item' => $model, 'wrapper' => 'true']); } } } } } /** * Delete menu item via ajax post. * * @throws NotFoundHttpException * @throws \Exception */ public function actionDeleteMenuItem() { /* @var $child \common\models\MenuItem */ if ($id = Yii::$app->request->post('id')) { $model = $this->findMenuItem($id); if ($model && $model->delete()) { $children = MenuItem::find()->where(['menu_parent' => $model->id])->all(); foreach ($children as $child) { $child->menu_parent = $model->menu_parent; $child->save(); } } else { throw new NotFoundHttpException('yii2-cms', 'The requested page does not exist.'); } } } /** * Save menu item recursively based on parent and child. * * @param $menuOrder * @param int $menuParent */ protected function saveMenuItem($menuOrder, $menuParent = 0) { foreach ($menuOrder as $key => $order) { $menuItem = Yii::$app->request->post('MenuItem')[ $order['id'] ]; if ($model = $this->findMenuItem($order['id'])) { $model->setAttributes($menuItem); $model->menu_parent = $menuParent; $model->menu_order = $key; if ($model->save()) { if (isset($order['items'])) { $this->saveMenuItem($order['items'], $model->id); } } } } } /** * Finds the Menu model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * * @param integer $id * * @return Menu the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Menu::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } /** * Finds the Post model based on its primary key value. * If the model is not found, it will return false. * * @param integer $id * * @return MenuItem|bool|null|static */ protected function findMenuItem($id) { if (($model = MenuItem::findOne($id)) !== null) { return $model; } else { return false; } } /** * Finds the Post model based on its primary key value. * If the model is not found, it will return false. * * @param integer $id * * @return Post|bool|null|static */ protected function findPost($id) { if (($model = Post::findOne($id)) !== null) { return $model; } else { return false; } } } <file_sep>/frontend/views/post/_form.php <?php /** * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use codezeen\yii2\tinymce\TinyMce; use dosamigos\datetimepicker\DateTimePicker; use yii\helpers\Html; use yii\helpers\Url; /* @var $this yii\web\View */ /* @var $model common\models\Post */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="post-form"> <?= $form->field($model, 'post_title', ['template' => '{input}{error}'])->textInput([ 'placeholder' => $model->getAttributeLabel('post_title'), ]) ?> <?= $form->field($model, 'post_slug', [ 'template' => '<span class="input-group-addon">' . $model->getAttributeLabel('post_slug') . '</span>{input}', 'options' => [ 'class' => 'input-group form-group input-group-sm', ], ])->textInput(['maxlength' => 255, 'placeholder' => $model->getAttributeLabel('post_slug')]) ?> <div class="form-group"> <?= Html::button('<i class="fa fa-folder-open"></i> ' . Yii::t('yii2-cms', 'Open Media'), [ 'data-url' => Url::to(['/media/popup', 'post_id' => $model->id, 'editor' => true]), 'class' => 'open-editor-media btn btn-default btn-flat', ]) ?> </div> <?= $form->field($model, 'post_content', ["template" => "{input}\n{error}"])->widget( TinyMce::className(), [ 'settings' => [ 'menubar' => false, 'skin_url' => Url::base(true) . '/editor-skins/editor-theme', 'toolbar_items_size' => 'medium', 'toolbar' => 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter ' . 'alignright alignjustify | bullist numlist outdent indent | link image | code fullscreen', 'formats' => [ 'alignleft' => [ 'selector' => 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', 'classes' => 'align-left', ], 'aligncenter' => [ 'selector' => 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', 'classes' => 'align-center', ], 'alignright' => [ 'selector' => 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', 'classes' => 'align-right', ], 'alignfull' => [ 'selector' => 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li,table,img', 'classes' => 'align-full', ], ], ], 'options' => [ 'id' => 'post-post_content', 'style' => 'height:400px;', ], ] ) ?> <?= $form->field($model, 'post_date', ['template'=>'{input}'])->widget(DateTimePicker::className(), [ 'size' => 'sm', 'template' => '{reset}{button}{input}', 'pickButtonIcon' => 'glyphicon glyphicon-time', 'options' => [ 'value'=>$model->isNewRecord? date('M d, Y h:i:s'): Yii::$app->formatter->asDatetime($model->post_date, 'php:M d, Y h:i:s') ], 'clientOptions' => [ 'autoclose' => true, 'format' => 'M dd, yyyy hh:ii:ss', 'todayBtn' => true, ] ]); ?> <?= Html::submitButton('Publish', ['class' => 'btn btn-sm btn-flat btn-primary']) ?> <?= !$model->isNewRecord ? Html::a('Delete', ['delete', 'id' => $model->id], [ 'class' => 'btn btn-wd-post btn-sm btn-flat btn-danger pull-right', 'data' => [ 'confirm' => 'Are you sure you want to delete this item?', ], ]) : '' ?> </div> <?php $this->registerJs('$(function () { "use strict"; $(".open-editor-media ").click(function (e) { e.preventDefault(); var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName("body")[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w.innerHeight|| e.clientHeight|| g.clientHeight; tinyMCE.activeEditor.windowManager.open({ file : $(this).data("url"), title : "Filemanager", width : x * 0.95, height : y * 0.9, resizable : "yes", inline : "yes", close_previous : "no" }); }); });') ?> <file_sep>/frontend/views/layouts/main-header.php <?php /** * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use yii\helpers\Html; /* @var $this yii\web\View */ ?> <header class="main-header"> <a href="<?= Yii::$app->urlManagerFront->createUrl(['/site/index']) ?>" class="logo"> <span class="logo-mini"><?= Html::img(Yii::getAlias('@web/img/logo-mini.png')) ?></span> <span class="logo-lg"><b>Yii2</b>CMS</span> </a> <nav class="navbar navbar-static-top"> <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> </a> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <?php if (!Yii::$app->user->isGuest): ?> <li class="dropdown user user-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <span class="hidden-xs"><?= Yii::$app->user->identity->username ?></span> </a> <ul class="dropdown-menu"> <li class="user-header"> <p> <?= Yii::$app->user->identity->username ?> <small> <?= Yii::t('yii2-cms', 'Member since {date}', [ 'date' => Yii::$app ->formatter ->asDate(Yii::$app->user->identity->created_at, 'php:F d, Y'), ]) ?> </small> </p> </li> <li class="user-footer"> <div class="pull-left"> <?= Html::a( Yii::t('yii2-cms', 'Profile'), ['/user/profile'], ['class' => 'btn btn-default btn-flat'] ) ?> </div> <div class="pull-right"> <?= Html::a( Yii::t('yii2-cms', 'Sign Out'), ['/site/logout'], ['class' => 'btn btn-default btn-flat', 'data-method' => 'post'] ) ?> </div> </li> </ul> </li> <?php endif ?> </ul> </div> </nav> </header> <file_sep>/frontend/views/site/login.php <?php /** * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use frontend\widgets\Alert; use yii\bootstrap\ActiveForm; use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $model \common\models\LoginForm */ $this->title = Yii::t('yii2-cms', 'Sign In'); ?> <div class="login-box"> <div class="login-logo"> <h1> <a href="#"> <img src="<?= Yii::getAlias('@web/img/logo.png') ?>" alt="Yii2 CMS"> </a> </h1> </div> <?= Alert::widget() ?> <div class="login-box-body"> <p class="login-box-msg"><?= Yii::t('yii2-cms', 'Sign in to start your session') ?></p> <?php $form = ActiveForm::begin(['id' => 'login-form']) ?> <?= $form->field($model, 'username', [ 'template' => '<div class="form-group has-feedback">{input}<span class="glyphicon glyphicon-user form-control-feedback"></span></div>{error}', ])->textInput(['placeholder' => $model->getAttributeLabel('username')]) ?> <?= $form->field($model, 'password', [ 'template' => '<div class="form-group has-feedback">{input}<span class="glyphicon glyphicon-lock form-control-feedback"></span></div>{error}', ])->passwordInput(['placeholder' => $model->getAttributeLabel('password')]) ?> <div class="row"> <div class="col-xs-8"> <?= $form->field($model, 'rememberMe')->checkbox() ?> </div> <div class="col-xs-4"> <?= Html::submitButton('Signin', [ 'class' => 'btn btn-primary btn-block btn-flat', 'name' => 'signin-button', ]) ?> </div> </div> <?php ActiveForm::end() ?> <?= Html::a(Yii::t('yii2-cms', 'Reset Password'), ['/site/request-password-reset']) ?><br/> </div> <br/> </div> <file_sep>/common/models/MenuItem.php <?php /** * @file MenuItem.php. * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ namespace common\models; use Yii; use yii\db\ActiveRecord; /** * This is the model class for table "{{%menu_item}}". * * @property integer $id * @property integer $menu_id * @property string $menu_label * @property string $menu_url * @property string $menu_description * @property integer $menu_order * @property integer $menu_parent * @property string $menu_options * * @property Menu $menu * * @package common\models * @author <NAME> <<EMAIL>> * @since 1.0 */ class MenuItem extends ActiveRecord { public $items; /** * @inheritdoc */ public static function tableName() { return '{{%menu_item}}'; } /** * @inheritdoc */ public function rules() { return [ [['menu_id', 'menu_label', 'menu_url'], 'required'], [['menu_id', 'menu_order', 'menu_parent'], 'integer'], [['menu_url', 'menu_description', 'menu_options'], 'string'], [['menu_label'], 'string', 'max' => 255], [['menu_url'], 'string', 'max' => 255] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'menu_id' => 'Menu ID', 'menu_label' => 'Label', 'menu_url' => 'URL', 'menu_description' => 'Description', 'menu_order' => 'Order', 'menu_parent' => 'Parent', 'menu_options' => 'Options', ]; } /** * @return \yii\db\ActiveQuery */ public function getMenu() { return $this->hasOne(Menu::className(), ['id' => 'menu_id']); } } <file_sep>/frontend/views/menu/_create.php <?php /** * @file _create.php. * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ use yii\helpers\Html; use yii\helpers\Url; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $form yii\widgets\ActiveForm */ /* @var $model common\models\Menu */ $form = ActiveForm::begin([ 'action' => Url::to(['/menu/create']) ]); ?> <div class="input-group"> <?= $form->field($model, 'menu_title', ['template' => '{input}'])->textInput(['placeholder' => $model->getAttributeLabel('menu_title')]) ?> <div class="input-group-btn"> <?= Html::submitButton('Add New Menu', ['class' => 'btn btn-flat btn-primary']); ?> </div> </div> <?php ActiveForm::end();<file_sep>/common/models/PostType.php <?php /** * @file PostType.php. * @date 23/2/2016 * @time 5:03 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 Yii2-cms * @license http://www.yii2-cms.com/license/ */ namespace common\models; use Yii; use yii\db\ActiveRecord; use yii\behaviors\SluggableBehavior; /** * This is the model class for table "{{%post_type}}". * * @property integer $id * @property string $post_type_name * @property string $post_type_slug * @property string $post_type_description * @property string $post_type_icon * @property string $post_type_sn * @property string $post_type_pn * @property integer $post_type_smb * * @property Post[] $posts * @package common\models * @author <NAME> <<EMAIL>> * @since 1.0 */ class PostType extends ActiveRecord { const SMB = 1; const NON_SMB = 0; /** * @inheritdoc */ public static function tableName() { return '{{%post_type}}'; } /** * @inheritdoc */ public function behaviors() { return [ [ 'class' => SluggableBehavior::className(), 'attribute' => 'post_type_name', 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['post_type_slug'], ], ], ]; } /** * @inheritdoc */ public function rules() { return [ [['post_type_name', 'post_type_slug', 'post_type_sn', 'post_type_pn'], 'required'], [['post_type_description'], 'string'], [['post_type_smb'], 'integer'], ['post_type_smb', 'in', 'range' => [self::SMB, self::NON_SMB]], ['post_type_smb', 'default', 'value' => self::NON_SMB], [['post_type_name', 'post_type_slug'], 'string', 'max' => 64], [['post_type_icon', 'post_type_sn', 'post_type_pn'], 'string', 'max' => 255], [['post_type_name', 'post_type_slug'], 'unique'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('yii2-cms', 'ID'), 'post_type_name' => Yii::t('yii2-cms', 'Name'), 'post_type_slug' => Yii::t('yii2-cms', 'Slug'), 'post_type_description' => Yii::t('yii2-cms', 'Description'), 'post_type_icon' => Yii::t('yii2-cms', 'Icon'), 'post_type_sn' => Yii::t('yii2-cms', 'Singular Name'), 'post_type_pn' => Yii::t('yii2-cms', 'Plural Name'), 'post_type_smb' => Yii::t('yii2-cms', 'Show Menu Builder'), ]; } /** * @return \yii\db\ActiveQuery */ public function getPosts() { return $this->hasMany(Post::className(), ['post_type' => 'id']); } /** * Get array of smb hierarchical for label or dropdown. * SMB is abbreviation from Show Menu Builder. * * @return array */ public function getSmb() { return [ self::SMB => "Yes", self::NON_SMB => "No" ]; } /** * Get all post type which post_type_smb is true. * The return value will be used in admin sidebar menu. * * @param int $position Position of post type in admin site menu * * @return array */ public static function getMenu($position = 2) { /* @var $model \common\models\PostType */ $models = static::find()->all(); $adminSiteMenu = []; foreach ($models as $model) { $adminSiteMenu[$position] = [ 'label' => $model->post_type_pn, 'icon' => $model->post_type_icon, 'items' => static::getTaxonomyMenu($model), ]; $position++; } return $adminSiteMenu; } /** * Get all taxonomies in postType to show as submenu. * * @param \common\models\PostType $postType * * @return array */ protected static function getTaxonomyMenu($postType) { $adminSiteSubmenu = []; $adminSiteSubmenu[] = [ 'icon' => 'fa fa-circle-o', 'label' => Yii::t('app', 'All {post_type_name}', ['post_type_name' => $postType->post_type_pn]), 'url' => ['/post/index/', 'post_type' => $postType->id], ]; $adminSiteSubmenu[] = [ 'icon' => 'fa fa-circle-o', 'label' => Yii::t('app', 'Add New {post_type_name}', ['post_type_name' => $postType->post_type_sn]), 'url' => ['/post/create/', 'post_type' => $postType->id], ]; return $adminSiteSubmenu; } }<file_sep>/backend/views/site/index.php <?php echo 'Welcome to FrontEnd'; <file_sep>/frontend/assets/MenuAsset.php <?php /** * @file MenuAsset.php. * @date 6/4/2015 * @time 3:45 AM * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2015 WritesDown * @license http://www.yii2-cms .com/license/ */ namespace frontend\assets; use yii\web\AssetBundle; /** * Asset bundle for menu. * * @package backend\assets * @author <NAME> <<EMAIL>> * @since 1.0 */ class MenuAsset extends AssetBundle{ /** * @var string */ public $basePath = '@webroot'; /** * @var string */ public $baseUrl = '@web'; /** * @var array */ public $css = [ 'css/menu.css' ]; /** * @var array */ public $js = [ 'js/menu.js' ]; /** * @var array */ public $depends = [ 'frontend\assets\AppAsset', ]; }<file_sep>/frontend/config/params.php <?php return [ 'bodyClass' => 'skin-blue sidebar-mini', ]; <file_sep>/frontend/views/layouts/main.php <?php use frontend\widgets\Alert; /* @var $this yii\web\View */ /* @var $content string */ ?> <?php $this->beginContent('@frontend/views/layouts/blank.php') ?> <div class="wrapper"> <?= $this->render('main-header') ?> <?= $this->render('main-sidebar') ?> <div class="content-wrapper"> <section class="content"> <?= Alert::widget() ?> <?= $this->render('content') ?> <?= $content ?> </section> </div> <?= $this->render('main-footer') ?> </div> <?php $this->endContent() ?> <file_sep>/frontend/views/layouts/main-footer.php <?php /* @var $this yii\web\View */ ?> <footer class="main-footer "> <div class="pull-right hidden-xs"> <b>Version</b> 1.0.0 </div> <strong>Copyright &copy; 2014-2015 <a href="#">Yii2 CMS</a>.</strong> All rights reserved. </footer>
cd703e070ef0ab26f2ed41536fdbc199e1fd8723
[ "Markdown", "PHP" ]
32
PHP
vladimirdj/yii2-cms
1a53ac02deec3f86d33af4f416d96e76c7e5d31c
7bec846e241cffe19d50232e8e674d927a7aeb5b
refs/heads/master
<file_sep># HappyNewYear [![Codacy Badge](https://api.codacy.com/project/badge/Grade/a3e8534912904ed180b1978b37f04a5f)](https://www.codacy.com/app/fedevitale99/happynewyear?utm_source=github.com&utm_medium=referral&utm_content=Rawnly/happynewyear&utm_campaign=badger) **HappyNewYear** is a *nodeJs* client module who provides to check if in the current day is a [festivity](https://github.com/Rawnly/festivities.json). <p align="center"> <img src="https://cloud.githubusercontent.com/assets/16429579/21469060/835eb0c4-ca37-11e6-9f67-11d8078868dc.png" alt="img1" /> </p> > Get the same setup [here](https://github.com/Rawnly/dot-files) > **Note**: Add it to your `.zshrc` or `.bashrc` to get the same result of the screenshot on top ## Installation #### NPM To install `happynewyear` you must use **npm** and install it as global. ```bash # Maybe needs sudo npm install -g happynewyear-cli ``` #### Clone You can also clone this repo and install it manually, ```bash # Cloning git clone https://github.com/Rawnly/happynewyear.git # Installation cd happynewyear && npm test # If no errors npm intall -g ``` ## Usage Good! Then to check festivity simply digit `happynewyear` in your `shell` <p align="center"> <img src="https://cloud.githubusercontent.com/assets/16429579/21469066/c9526dfa-ca37-11e6-8f88-d94ae8ed8d8e.gif" alt="mini" /> </p> --- ## All Festivities ![animated3](https://cloud.githubusercontent.com/assets/16429579/21469069/daf4a3f2-ca37-11e6-8060-f47161c4fb03.gif) <file_sep>#!/usr/bin/env node 'use strict'; const ora = require('ora'); const chalk = require('chalk'); const colors = require('colors'); const open = require('opener'); const emoji = require('node-emoji'); // Used italian language for these two var // to avoid var conflicts // Month const mese = require('./libs/month'); // Festivity const festa = require('./libs/festivity'); // Declaring var d, today, year; // Asssigning d = new Date(); today = d.getDate(); year = d.getFullYear(); var spinner = new ora({ text: 'Getting festivities...', spinner: 'dots', color: 'yellow' }); spinner.start(); // Start Checking | Maybe a switch() was better. if ( mese() == festa('christmas').month && today == festa('christmas').day ) { setTimeout(function () { spinner.text = "🎅🏼 Ho! Ho! Ho!" + " It's " + "Christmas! ".bold; spinner.succeed() }, 500); } else if ( mese() == festa('halloween').month && today == festa('halloween').day) { setTimeout(function () { spinner.text = "👻💀" + " It's HALLOWEEN! " + "💀👻"; spinner.succeed() }, 500); } else if ( mese() == festa('valentines').month && today == festa('valentines').day) { setTimeout(function () { spinner.text = "Love is in the air... 💝" ; spinner.succeed(); }, 500); } else if ( mese() == festa('epifany').month && today == festa('epifany').day) { setTimeout(function () { spinner.text = "📯 It's epifany! 📯"; spinner.succeed(); }, 500); } else if ( mese() == festa('newyear').month && today == festa('newyear').day) { setTimeout(function () { spinner.text = "Happy new year! It's " + year + "!!!"; spinner.succeed(); }, 500); } else { spinner.text = emoji.get('sweat') + " Oh no... It's a common day..."; spinner.fail() }
7816dd390932b0e65c8f5a3dc35f50437193cd57
[ "Markdown", "JavaScript" ]
2
Markdown
rawnly/happynewyear
e831286aa21013423760b4b99804811e979cf5d5
420911bcc57732e8b24bcf3bf931f4a703763af0
refs/heads/master
<file_sep>#include <stdio.h> int main() { int qian = 0; printf("jingruqianbaoguanlixitong\n"); while (1) { printf("1--cunqian\n"); printf("2--quqian\n"); printf("3--yue\n"); printf("4--tuichu\n"); int code = 0; printf("qingshuruxinagxingdegongnengbianhao:\n"); scanf("%d", &code); if (code == 1) { printf("qingshurunidecunkuanjine:\n"); int cun; scanf("%d", &cun); char x; qian += cun; printf("cunruchenggong,dianjihuichejixu\n"); scanf("%c", &x); scanf("%c", &x); } if (code == 2) { printf("qingchuruqukuanjinge:\n"); int qu; scanf("%d", &qu); if (qu > qian) { printf("xuebuzu,qukuanshibai,dianjihuichejixu\n"); char x; scanf("%c", &x); scanf("%c", &x); } else { qian-=qu; printf("quchuchenggong,dianjihuichejixu\n"); char x; scanf("%c", &x); scanf("%c", &x); } qian -= qu; } if (code == 3) { printf("dangqianyueewei:\n"); printf("%d\n", qian); } if (code == 4) { } } return 0; }
3ea49b908545729c353271243f00d2e4166b6cb1
[ "C" ]
1
C
litte21boy/c1
d5a5ea184890b7658c1d2b62bd677aba824e72a8
03578907f6552506aed69ffead9f2d08873c78e2
refs/heads/master
<file_sep>import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ParseTable { private static final String PATH_OF_CSV_FILE = "src/data/movementList.csv"; static List<Double> incomeList = new ArrayList<>(); static List<Double> expensesList = new ArrayList<>(); static Map<String,Double> expensesOperationMap = new HashMap<>(); static Map<String,Double> incomeOperationMap = new HashMap<>(); public static void parseColumns() { try { Reader reader = Files.newBufferedReader(Paths.get(PATH_OF_CSV_FILE)); CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT .withFirstRecordAsHeader() .withIgnoreHeaderCase() .withTrim()); for (CSVRecord record : csvParser) { String operations = record.get("Описание операции"); operations = operations.substring((operations.indexOf("\\")+1)|(operations.indexOf("/")+1),60).trim(); double income = Double.parseDouble(record.get("Приход")); double expenses =Double.parseDouble(record.get("Расход").replaceAll(",",".")); incomeList.add(income); expensesList.add(expenses); expensesOperationMap = Operation.expensesOperations(operations,expenses); incomeOperationMap = Operation.incomeOperations(operations,income); } } catch (IOException e) { e.printStackTrace(); } } @Override public String toString() { return "ParseTable{}" + "\n"; } }
9351a3645009f4a5510e01da1fd83b0c4e93e126
[ "Java" ]
1
Java
KilJoy59/CSVparseBlock9
9dc831f7af4fb099082e6d18c1c533b4b9eb36d7
a25da3150f5a0f87c9b33ff527c858770844aa76
refs/heads/main
<repo_name>jadenbh13/trashDrone<file_sep>/requirements.txt cycler kiwisolver matplotlib numpy Pillow pyparsing python-dateutil six torch tqdm <file_sep>/bags.py import torch import cv2 import numpy as np from torch.autograd import Variable from darknet import Darknet from util import process_result, load_images, resize_image, cv_image2tensor, transform_result import pickle as pkl import argparse import math import random import os.path as osp import os import sys from datetime import datetime from tqdm import tqdm from time import sleep import threading from testProc import callFunc, callFunc3 import serial boxList = [] def load_classes(namesfile): fp = open(namesfile, "r") names = fp.read().split("\n") return names def parse_args(): fil = "pic.png" parser = argparse.ArgumentParser(description='YOLOv3 object detection') parser.add_argument('-i', '--input', default=fil, help='input image or directory or video') parser.add_argument('-t', '--obj-thresh', type=float, default=0.5, help='objectness threshold, DEFAULT: 0.5') parser.add_argument('-n', '--nms-thresh', type=float, default=0.4, help='non max suppression threshold, DEFAULT: 0.4') parser.add_argument('-o', '--outdir', default='output', help='output directory, DEFAULT: detection/') parser.add_argument('-v', '--video', action='store_true', default=False, help='flag for detecting a video input') parser.add_argument('-w', '--webcam', action='store_true', default=False, help='flag for detecting from webcam. Specify webcam ID in the input. usually 0 for a single webcam connected') parser.add_argument('--cuda', action='store_true', default=False, help='flag for running on GPU') parser.add_argument('--no-show', action='store_true', default=False, help='do not show the detected video in real time') args = parser.parse_args() return args def create_batches(imgs, batch_size): num_batches = math.ceil(len(imgs) // batch_size) batches = [imgs[i*batch_size : (i+1)*batch_size] for i in range(num_batches)] return batches def draw_bbox(imgs, bbox, colors, classes,read_frames,output_path): img = imgs[int(bbox[0])] label = classes[int(bbox[-1])] confidence = int(float(bbox[6])*100) label = label+' '+str(confidence)+'%' #print(label) p1 = tuple(bbox[1:3].int()) p2 = tuple(bbox[3:5].int()) if 'privacy' in classes[int(bbox[-1])]: topLeft = p1 bottomRight = p2 x, y = topLeft[0], topLeft[1] w, h = bottomRight[0] - topLeft[0], bottomRight[1] - topLeft[1] # Grab ROI with Numpy slicing and blur ROI = img[y:y+h, x:x+w] blur = cv2.GaussianBlur(ROI, (51,51), 0) # Insert ROI back into image img[y:y+h, x:x+w] = blur else: color = colors[int(bbox[-1])] cv2.rectangle(img, p1, p2, color, 4) text_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1, 1)[0] p3 = (p1[0], p1[1] - text_size[1] - 4) p4 = (p1[0] + text_size[0] + 4, p1[1]) cv2.rectangle(img, p3, p4, color, -1) cv2.putText(img, label, p1, cv2.FONT_HERSHEY_SIMPLEX, 1, [225, 255, 255], 1) def detect_image(model, args): l = 0 sep = threading.Thread(target=callFunc, args=(1,)) sep.start() while l == 0: try: #print('Loading input image(s)...') input_size = [int(model.net_info['height']), int(model.net_info['width'])] batch_size = int(model.net_info['batch']) imlist, imgs = load_images(args.input) #print('Input image(s) loaded') img_batches = create_batches(imgs, batch_size) # load colors and classes colors = pkl.load(open("pallete", "rb")) classes = load_classes("we/garb.names") #print(classes) if not osp.exists(args.outdir): os.makedirs(args.outdir) start_time = datetime.now() for batchi, img_batch in tqdm(enumerate(img_batches)): img_tensors = [cv_image2tensor(img, input_size) for img in img_batch] img_tensors = torch.stack(img_tensors) img_tensors = Variable(img_tensors) if args.cuda: img_tensors = img_tensors.cuda() detections = model(img_tensors, args.cuda).cpu() detections = process_result(detections, args.obj_thresh, args.nms_thresh) ins = open("run.txt", "r") v = ins.read() print(v) if "Land" in v: print("Break") print("Break") l += 1 break if len(detections) == 0: print("Nothing") continue detections = transform_result(detections, img_batch, input_size) for detection in detections: labe = classes[int(detection[-1])] con = int(float(detection[6])*100) print(labe) print(con) boxList.append(labe) #print(boxList) draw_bbox(img_batch, detection, colors, classes,0,args.outdir) for i, img in enumerate(img_batch): save_path = osp.join(args.outdir, osp.basename(imlist[batchi*batch_size + i])) cv2.imwrite(save_path, img) cv2.imshow("output", img) key = cv2.waitKey(1) & 0xFF if key == ord("q"): l += 1 break #print(save_path, 'saved') end_time = datetime.now() #print('Detection finished in %s' % (end_time - start_time)) except Exception as e: print(e) return def main(): args = parse_args() if args.cuda and not torch.cuda.is_available(): #print("ERROR: cuda is not available, try running on CPU") sys.exit(1) #print('Loading network...') model = Darknet("we/yolov3_garb_test.cfg") model.load_weights('we/garb.weights') if args.cuda: model.cuda() model.eval() #print('Network loaded') print('Detecting...') detect_image(model, args) def runs(): with open('run.txt', 'w') as filetowrite: filetowrite.write('Start') sleep(1) main() print(boxList) try: s = serial.Serial('/dev/ttyUSB0', 115200, timeout=3) for x in boxList: if x == 'Plastic_bag': s.write(b'0') elif x == 'cardboard': s.write(b'1') elif x == 'container_small': s.write(b'2') except: print("No serial port found") cv2.destroyAllWindows() runs() <file_sep>/test.js const readline = require('readline'); var arDrone = require('ar-drone'); var client = arDrone.createClient(); client.createRepl(); var yaw; var inYaw; readline.emitKeypressEvents(process.stdin); process.stdin.setRawMode(true); keyName = null; async function run() { // everything below is guaranteed to run after the "sleep" client.on('navdata', (data)=>{ yaw = data.demo.rotation.yaw; console.log(inYaw); console.log(yaw); if (inYaw != undefined) { var t = inYaw; var u = t + 0.3; var l = t - 0.3; if (yaw > u) { client.counterClockwise(0.07); console.log("Turn left"); } else if (yaw < l) { client.clockwise(0.07); console.log("Turn right"); } else { console.log("Reached angle"); client.stop(); } } }); setTimeout(function(){ inYaw = yaw; }, 5000); } process.stdin.on('keypress', (str, key) => { if (key.ctrl && key.name === 'c') { process.exit(); } else { console.log(key.name); if(key.name == 't') { client.takeoff(); client.stop(); run(); } if(key.name == 'l') { client.land(); } if(key.name == 'w') { client.front(0.1); client.after(200, function() { this.stop(); }); } if(key.name == 's') { client.back(0.1); client.after(200, function() { this.stop(); }); } if(key.name == 'd') { client.right(0.1); client.after(200, function() { this.stop(); }); } if(key.name == 'a') { client.left(0.1); client.after(200, function() { this.stop(); }); } } }); console.log('Initialized'); <file_sep>/ulSave.py import os import requests def saveIm(): url = "http://www.digimouth.com/news/media/2011/09/google-logo.jpg" page = requests.get(url) f_name = "local.jpg" with open(f_name, 'wb') as f: f.write(page.content) saveIm() <file_sep>/testProc.py from datetime import datetime import json import os import re import sys import subprocess from Naked.toolshed.shell import execute_js, muterun_js def callFunc(name): result = execute_js('drone.js') if result: print(result) else: print("err") def caller(): import center def callFunc2(): result = execute_js('emer.js') if result: print(result) else: print("err") def callFunc3(nm): result = execute_js('png.js') if result: print(result) else: print("err") <file_sep>/readPy.py import serial from time import sleep import threading import multiprocessing from bags import runs import os from time import sleep from testProc import callFunc2 h = False numbList = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] def onlyNumbs(arg): retStr = "" for i in arg: if i in numbList: retStr += i return retStr x = threading.Thread(target=runs) se1 = False se2 = False se3 = False while True: try: s = serial.Serial('/dev/ttyUSB0', 115200, timeout=3) reds = s.readline().decode() red = onlyNumbs(reds) print(reds) if red == '1': x.start() if red == '0': print("Option 2") with open('run.txt', 'w') as filetowrite: filetowrite.write('Land') print("runLand") #callFunc2() except Exception as e: print(e)
21ff8259fd281d781404f9d13501d15cc02707c0
[ "JavaScript", "Python", "Text" ]
6
Text
jadenbh13/trashDrone
dff17f07cc8fd0e4f94bb5708b9cfeed2904041e
72062fbbf69642f41e58cefa681fc85be752575a
refs/heads/master
<file_sep><?php use HyperDown\Parser; use Intervention\Image\Facades\Image; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Auth; if(!funcition_exits('ajax_return')){ /** * ajax返回数据 * * @param string $data 需要返回的数据 * @param int $status_code * @return \Illuminate\Http\JsonResponse */ function ajax_return($status_code=200, $data=''){ //如果是错误信息,返回错误信息 if($status_code == !200){ $data = [ 'status_code'=>$status_code, 'message'=>$data ]; return response()->json($data, $status_code); } //如果是对象,先转成数组 if(is_object($data)){ $data = $data->toArray(); } /** *数组递归,转成字符串 * @param array $arr 需要转的数组 * @return array 转换后的数组 **/ function to_string($arr){ //app 禁止使用和为了统一字段做的判断 $reserved_word = []; foreach($arr as $k=>$v){ //如果是对象先转为数组 if(is_object($v)){ $v = $v->toArray(); } //如果是数组,则递归转字符串 if(is_array($v)){ $v = to_string($v); }else{ //判断是否有移动端禁止使用的字段 in_array($k, $reserved_word, true) && die('不容许使用【'.$ke.'】这个键名--此提示是help.php中的ajaxReturn函数返回的'); $arr[$k] = strval($v); } } return $arr; } //判断是否有返回的数据 if(is_array($arr)){ //先把所有字段转为字符串形式 $data = to_string($arr); } return response()->json($data, $status_code); } } if ( !function_exists('send_email') ) { /** * 发送邮件函数 * * @param $email 收件人邮箱 如果群发 则传入数组 * @param $name 收件人名称 * @param $subject 标题 * @param array $data 邮件模板中用的变量 示例:['name'=>'帅白','phone'=>'110'] * @param string $template 邮件模板 * @return array 发送状态 */ function send_email($email, $name, $subject, $data = [], $template = 'emails.test') { Mail::send($template, $data, function($message) use ($email, $name, $subject) { if(is_array($email)){ foreach($email as $k => $v){ $message = to($v, $name)->subject($subject); } }else{ $message = to($email, $name) -> subject($subject); } }); if(count(MaileFail) > 0){ $data = array('message' => '发送失败', 'status_code' => 500); }else{ $data = array('message' => '发送成功', 'status_code' => 200); } return $data; } } if ( !function_exists('upload') ) { /** * 上传文件函数 * * @param $file 表单的name名 * @param string $path 上传的路径 * @param bool $childPath 是否根据日期生成子目录 * @return array 上传的状态 */ function upload($file, $path='upload', $childPath = true){ //判断请求中是否包含name=file 的上传文件 if(!request()->hasFile()){ $data = ['message'=>'上传文件为空', 'status_code'=>500]; return $data; } $file = request()->file($file); if(!$file->isValid){ $data = ['message'=>'文件上传出错', 'status_code'=>500]; return $data; } //兼容性的路径处理问题 if($childPath == true){ $path = './'.trim($path, './').'/'.date('Ymd').'/'; }else{ $path = './'.trim($path, './').'/'; } //如果没有目录则新建目录 if(!is_dir($path)){ mkdir($path, 0755, true); } //获取上传的文件名 $oldName = $file -> getClientOriginalExtension(); //上传失败 if (!$file->move($path, $newName)) { $data = ['status_code' => 500, 'message' => '保存文件失败']; return $data; } //上传成功 $data = ['status_code' => 200, 'message' => '上传成功', 'data' => ['old_name' => $oldName, 'new_name' => $newName, 'path' => trim($path, '.')]]; return $data; } }
b245ccdca6b1dd7a3455cc57dd908941ed32b0d0
[ "PHP" ]
1
PHP
webofrxy/laravel-admin
3acd258b24980d59eaea26da5ce65d04cd84e167
66cb9afdff59f525ac7f8fd6b3f9b1826e0e9972
refs/heads/master
<repo_name>nividata-consultancy/qrcode-scanner<file_sep>/README.md # qrcode-scanner This is an app that scans one-dimensional code (Barcode) and two-dimensional code (QR code) <file_sep>/qr_code_scanner/ios/Runner/AppDelegate.swift import UIKit import Flutter @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) guard let controller = window.rootViewController as? FlutterViewController else { fatalError("Invalid root view controller") } return super.application(application, didFinishLaunchingWithOptions: launchOptions) } }
6ee0f822d32db7fdc502371775bea1da50e9559c
[ "Markdown", "Swift" ]
2
Markdown
nividata-consultancy/qrcode-scanner
eb602001a43dc608c69b2a70130174b4956d17c3
17899bb61ba247e5dd9adf98f264290d4f7c65dd
refs/heads/master
<file_sep># 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Address.delete_all Address.create(name:'<NAME>', office_phone:'240-354-9895', home_phone:'240-635-4242', email: '<EMAIL>') Address.create(name:'<NAME>', office_phone:'240-354-9895', home_phone: '301-657-4356', email: '<EMAIL>') Address.create(name:'<NAME>', office_phone:'240-354-9895', home_phone: '240-456-1209', email: '<EMAIL>') Address.create(name:'<NAME>', office_phone:'240-354-9895', home_phone: '301-653-0913', email: '<EMAIL>') Address.create(name:'<NAME>', office_phone:'240-354-9895', home_phone: '410-653-0189', email: '<EMAIL>') Address.create(name:'<NAME>', office_phone:'240-354-9895', home_phone: '301-345-6732', email: '<EMAIL>') Address.create(name:'<NAME>', office_phone:'240-354-9895', home_phone: '240-145-0123', email: '<EMAIL>')
99b9984b6e1fc2978a2c2f8728faccbcd56b6a62
[ "Ruby" ]
1
Ruby
jimmybowens/WEB
aa4c269544376599b8506473e86b1e188401a7e2
4a5701fd08e8aca344119c7a17e3d260beacc7f5
refs/heads/master
<repo_name>aagusti/osipkd-pdpt<file_sep>/osipkd/views/anggaran/kegiatan_item.py import os import uuid from osipkd.tools import row2dict, xls_reader from datetime import datetime from sqlalchemy import not_, func, or_, cast, BigInteger from pyramid.view import (view_config,) from pyramid.httpexceptions import ( HTTPFound, ) import colander from deform import (Form, widget, ValidationFailure, ) from osipkd.models import DBSession from osipkd.models.apbd_anggaran import Kegiatan, KegiatanSub, KegiatanItem from osipkd.models.pemda_model import Rekening from datatables import ColumnDT, DataTables from osipkd.views.base_view import BaseViews SESS_ADD_FAILED = 'Tambah ag-kegiatan-sub gagal' SESS_EDIT_FAILED = 'Edit ag-kegiatan-sub gagal' def deferred_jv_type(node, kw): values = kw.get('jv_type', []) return widget.SelectWidget(values=values) JV_TYPE = ( ('lra', 'LRA'), ('lo', 'LO'), ('ju', 'Jurnal Umum'), ) class view_ak_jurnal(BaseViews): @view_config(route_name="ag-kegiatan-item", renderer="templates/ag-kegiatan-item/list.pt") def view_list(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict kegiatan_sub_id = url_dict['kegiatan_sub_id'] row = KegiatanSub.query_id(kegiatan_sub_id).filter(KegiatanSub.unit_id==ses['unit_id']).first() rek_head = 5 return dict(project='OSIPKD', row = row, rek_head=rek_head) ########## # Action # ########## def get_row_item(self): return DBSession.query(KegiatanItem.id, KegiatanItem.rekening_id, Rekening.kode.label('rekening_kd'), Rekening.nama.label('rekening_nm'), KegiatanItem.nama, KegiatanItem.no_urut, (KegiatanItem.vol_1_1*KegiatanItem.vol_1_2*KegiatanItem.hsat_1).label('amount_1'), (KegiatanItem.vol_2_1*KegiatanItem.vol_2_2*KegiatanItem.hsat_2).label('amount_2'), (KegiatanItem.vol_3_1*KegiatanItem.vol_3_2*KegiatanItem.hsat_3).label('amount_3'), (KegiatanItem.vol_4_1*KegiatanItem.vol_4_2*KegiatanItem.hsat_4).label('amount_4')).join(Rekening) @view_config(route_name='ag-kegiatan-item-act', renderer='json', permission='read') def ak_jurnal_act(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict if url_dict['act']=='grid': ag_step_id = ses['ag_step_id'] kegiatan_sub_id = 'kegiatan_sub_id' in params and params['kegiatan_sub_id'] or 0 columns = [] columns.append(ColumnDT('id')) columns.append(ColumnDT('rekening_kd')) columns.append(ColumnDT('no_urut')) columns.append(ColumnDT('nama')) columns.append(ColumnDT('amount_%s' %ag_step_id, filter=self._number_format)) columns.append(ColumnDT('rekening_nm')) columns.append(ColumnDT('rekening_id')) query = self.get_row_item().filter(KegiatanItem.kegiatan_sub_id==kegiatan_sub_id ).order_by(Rekening.kode.asc()) rowTable = DataTables(req, KegiatanItem, query, columns) return rowTable.output_result() elif url_dict['act']=='headofnama': term = 'term' in params and params['term'] or '' kegiatan_sub_id = 'kegiatan_sub_id' in params and params['kegiatan_sub_id'] or 0 q = DBSession.query(KegiatanItem.id, Rekening.kode, KegiatanItem.nama, cast(KegiatanItem.hsat_4*KegiatanItem.vol_4_1*KegiatanItem.vol_4_2,BigInteger).label('amount') )\ .join(Rekening)\ .join(KegiatanSub)\ .filter(KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id == ses['tahun'], KegiatanItem.kegiatan_sub_id==kegiatan_sub_id, or_(KegiatanItem.nama.ilike('%%%s%%' % term), Rekening.kode.ilike('%%%s%%' % term))) rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['value'] = ''.join([k[1],'-',str(k[2])]) d['kode'] = ''.join([k[1]]) d['nama'] = k[2] d['amount'] = k[3] r.append(d) return r elif url_dict['act']=='headofkode1': term = 'term' in params and params['term'] or '' kegiatan_sub = 'kegiatan_sub_id' in params and params['kegiatan_sub_id'] or 0 q = DBSession.query(KegiatanItem.id, Kegiatan.kode.label('kegiatan_kd'), Kegiatan.nama.label('kegiatan_nm'), KegiatanSub.no_urut.label('kegiatan_no'), Rekening.kode.label('rekening_kd'), Rekening.nama.label('rekening_nm'), KegiatanItem.no_urut.label('item_no'), cast(KegiatanItem.hsat_4*KegiatanItem.vol_4_1*KegiatanItem.vol_4_2,BigInteger).label('amount') ).\ join(KegiatanSub, Rekening).\ outerjoin(Kegiatan).\ filter(KegiatanItem.kegiatan_sub_id==KegiatanSub.id, #KegiatanSub.id==kegiatan_sub, KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id == ses['tahun'], KegiatanSub.kegiatan_id==Kegiatan.id, KegiatanItem.rekening_id==Rekening.id, #Kegiatan.kode=='0.00.00.10', Rekening.kode.ilike('%%%s%%' % term))\ rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['value'] = '{kegiatan_kd}-{kegiatan_no}-{rekening_kd}-{item_no}'.\ format(kegiatan_kd=k[1], kegiatan_no=k[3], rekening_kd=k[4], item_no=k[6]) d['kode'] = '{kegiatan_kd}-{kegiatan_no}-{rekening_kd}-{item_no}'.\ format(kegiatan_kd=k[1], kegiatan_no=k[3], rekening_kd=k[4], item_no=k[6]) d['nama'] = k[5] d['amount'] = k[7] r.append(d) return r elif url_dict['act']=='headofnama3': term = 'term' in params and params['term'] or '' q = DBSession.query(KegiatanItem.id, KegiatanItem.nama.label('ap_kegiatankd'),KegiatanSub.id,KegiatanSub.nama).\ join(KegiatanSub).\ outerjoin(Kegiatan).\ filter(KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id == ses['tahun'], KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.kode!='0.00.00.10', Kegiatan.kode!='0.00.00.21', Kegiatan.kode!='0.00.00.31', Kegiatan.kode!='0.00.00.32', KegiatanItem.nama.ilike('%%%s%%' % term))\ rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['value'] = k[1] d['nama'] = k[1] d['nama1'] = k[3] r.append(d) print "XCXCXCXC",r return r ############### # Tambah Data# ############### @view_config(route_name='ag-kegiatan-item-add-fast', renderer='json', permission='add') def ak_kegiatan_item_add_fast(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict kegiatan_sub_id = 'kegiatan_sub_id' in params and params['kegiatan_sub_id'] or None rekening_id = 'rekening_id' in params and params['rekening_id'] or None kegiatan_item_id = 'kegiatan_item_id' in params and params['kegiatan_item_id'] or None if not kegiatan_item_id: row = KegiatanItem() row_dict = {} else: row = DBSession.query(KegiatanItem).filter(KegiatanItem.id==kegiatan_item_id).first() if not row: return {'success':False, 'msg':'Data Tidak Ditemukan'} row_dict = row.to_dict() row_dict['no_urut'] = 'no_urut' in params and params['no_urut'] or \ KegiatanItem.max_no_urut(kegiatan_sub_id,rekening_id)+1 row_dict['kegiatan_sub_id'] = kegiatan_sub_id row_dict['rekening_id'] = rekening_id row_dict['nama'] = 'nama' in params and params['nama'] or None row_dict['kode'] = 'kode' in params and params['kode'] or None ag_step_id = ses['ag_step_id'] amount = 'amount' in params and params['amount'].replace('.', '') or 0 if ag_step_id<2: row_dict['hsat_1'] = amount if ag_step_id<3: row_dict['hsat_2'] = amount if ag_step_id<4: row_dict['hsat_3'] = amount if ag_step_id<5: row_dict['hsat_4'] = amount row.from_dict(row_dict) DBSession.add(row) DBSession.flush() return {"success": True, 'id': row.id, "msg":'Success Tambah Data'} try: pass except: return {'success':False, 'msg':'Gagal Tambah Data'} ####### # Add # ####### def form_validator(form, value): def err_kegiatan(): raise colander.Invalid(form, 'Kegiatan dengan no urut tersebut sudah ada') class AddSchema(colander.Schema): kegiatan_sub_id = colander.SchemaNode( colander.String(), ) rekening_id = colander.SchemaNode( colander.String(), oid="rekening_id" ) rekening_kd = colander.SchemaNode( colander.String(), title="Rekening", oid="rekening_kd" ) rekening_nm = colander.SchemaNode( colander.String(), oid="rekening_nm" ) kode = colander.SchemaNode( colander.String(), missing=colander.drop, ) nama = colander.SchemaNode( colander.String(), oid="nama", ) no_urut = colander.SchemaNode( colander.String(), missing=colander.drop, title="No.Urut", ) header_id = colander.SchemaNode( colander.String(), missing=colander.drop, ) vol_1_1 = colander.SchemaNode( colander.Float(), missing=colander.drop, default=1, oid="vol_1_1", title="Volume 1" ) sat_1_1 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Satuan 2" ) vol_1_2 = colander.SchemaNode( colander.Float(), missing=colander.drop, default=1, oid="vol_1_2", title="Volume 2") sat_1_2 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Satuan 2" ) hsat_1 = colander.SchemaNode( colander.String(), missing=colander.drop, default=0, oid="hsat_1", title="Harga") vol_2_1 = colander.SchemaNode( colander.Float(), missing=colander.drop, default=1, oid="vol_2_1", title="Volume 1") sat_2_1 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Satuan 1" ) vol_2_2 = colander.SchemaNode( colander.Float(), missing=colander.drop, default=1, oid="vol_2_2", title="Volume 2") sat_2_2 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Satuan 2" ) hsat_2 = colander.SchemaNode( colander.String(), missing=colander.drop, default=0, oid="hsat_2", title="Harga") vol_3_1 = colander.SchemaNode( colander.Float(), missing=colander.drop, default=1, oid="vol_3_1", title="Volume 1") sat_3_1 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Satuan 1" ) vol_3_2 = colander.SchemaNode( colander.Float(), missing=colander.drop, default=1, oid="vol_3_2", title="Volume 2") sat_3_2 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Satuan 2" ) hsat_3 = colander.SchemaNode( colander.String(), missing=colander.drop, default=0, oid="hsat_3", title="Harga") vol_4_1 = colander.SchemaNode( colander.Float(), missing=colander.drop, default=1, oid="vol_4_1", title="Volume 1") sat_4_1 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Satuan 1" ) vol_4_2 = colander.SchemaNode( colander.Float(), missing=colander.drop, default=1, oid="vol_4_2", title="Volume 2") sat_4_2 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Satuan 2" ) hsat_4 = colander.SchemaNode( colander.String(), missing=colander.drop, default=0, oid="hsat_4", title="Harga") pelaksana = colander.SchemaNode( colander.String(), missing=colander.drop, ) mulai = colander.SchemaNode( colander.String(), missing=colander.drop, ) selesai = colander.SchemaNode( colander.String(), missing=colander.drop, ) bln01 = colander.SchemaNode( colander.Integer(), missing=colander.drop, oid="bln01", default=0, title="Jan") bln02 = colander.SchemaNode( colander.Integer(), missing=colander.drop, oid="bln02", default=0, title="Feb") bln03 = colander.SchemaNode( colander.Integer(), missing=colander.drop, oid="bln03", default=0, title="Mar") bln04 = colander.SchemaNode( colander.Integer(), oid="bln04", missing=colander.drop, default=0, title="Apr") bln05 = colander.SchemaNode( colander.Integer(), oid="bln05", missing=colander.drop, default=0, title="Mei") bln06 = colander.SchemaNode( colander.Integer(), missing=colander.drop, oid="bln06", default=0, title="Jun") bln07 = colander.SchemaNode( colander.Integer(), missing=colander.drop, oid="bln07", default=0, title="Jul") bln08 = colander.SchemaNode( colander.Integer(), oid="bln08", missing=colander.drop, default=0, title="Agt") bln09 = colander.SchemaNode( colander.Integer(), oid="bln09", missing=colander.drop, default=0, title="Sep") bln10 = colander.SchemaNode( colander.Integer(), oid="bln10", missing=colander.drop, default=0, title="Okt") bln11 = colander.SchemaNode( colander.Integer(), oid="bln11", missing=colander.drop, default=0, title="Nov") bln12 = colander.SchemaNode( colander.Integer(), missing=colander.drop, oid="bln12", default=0, title="Des") ssh_id = colander.SchemaNode( colander.String(), missing=colander.drop, ) is_summary = colander.SchemaNode( colander.String(), missing=colander.drop, ) is_apbd = colander.SchemaNode( colander.String(), missing=colander.drop, ) keterangan = colander.SchemaNode( colander.String(), missing=colander.drop, ) class EditSchema(AddSchema): id = colander.SchemaNode( colander.Integer(), oid="id") def get_form(request, class_form): schema = class_form(validator=form_validator) schema = schema.bind() schema.request = request return Form(schema, buttons=('simpan','batal')) def save(values, request, row=None): if not row: row = KegiatanItem() ag_step_id = request.session['ag_step_id'] if ag_step_id<2: values['vol_2_1'] = values['vol_%s_1' % ag_step_id] values['vol_2_2'] = values['vol_%s_2' % ag_step_id] values['sat_2_1'] = values['sat_%s_1' % ag_step_id] values['sat_2_2'] = values['sat_%s_2' % ag_step_id] values['hsat_2'] = values['hsat_%s' % ag_step_id] if ag_step_id<4: values['vol_3_1'] = values['vol_%s_1' % ag_step_id] values['vol_3_2'] = values['vol_%s_2' % ag_step_id] values['sat_3_1'] = values['sat_%s_1' % ag_step_id] values['sat_3_2'] = values['sat_%s_2' % ag_step_id] values['hsat_3'] = values['hsat_%s' % ag_step_id] if ag_step_id<5: values['vol_4_1'] = values['vol_%s_1' % ag_step_id] values['vol_4_2'] = values['vol_%s_2' % ag_step_id] values['sat_4_1'] = values['sat_%s_1' % ag_step_id] values['sat_4_2'] = values['sat_%s_2' % ag_step_id] values['hsat_4'] = values['hsat_%s' % ag_step_id] row.from_dict(values) if not row.no_urut: row.no_urut = KegiatanItem.max_no_urut(values['kegiatan_sub_id'],values['rekening_id'])+1; DBSession.add(row) DBSession.flush() return row def save_request(values, request, row=None): if 'id' in request.matchdict: values['id'] = request.matchdict['id'] #values["vol_1_1"]=values["vol_1_1"].replace('.','') #values["vol_1_2"]=values["vol_1_2"].replace('.','') values["hsat_1"]=values["hsat_1"].replace('.','') #values["vol_2_1"]=values["vol_2_1"].replace('.','') #values["vol_2_2"]=values["vol_2_2"].replace('.','') values["hsat_2"]=values["hsat_2"].replace('.','') #values["vol_3_1"]=values["vol_3_1"].replace('.','') #values["vol_3_2"]=values["vol_3_2"].replace('.','') values["hsat_3"]=values["hsat_3"].replace('.','') #values["vol_4_1"]=values["vol_4_1"].replace('.','') #values["vol_4_2"]=values["vol_4_2"].replace('.','') values["hsat_4"]=values["hsat_4"].replace('.','') row = save(values, request, row) request.session.flash('Kegiatan sudah disimpan.') def route_list(request, kegiatan_sub_id): kegiatan_sub_id q = DBSession.query(Kegiatan.kode.label('kegiatan_kd')).join(KegiatanSub, KegiatanItem, Kegiatan).filter(Kegiatan.id==KegiatanSub.kegiatan_id, KegiatanItem.kegiatan_sub_id==kegiatan_sub_id) rows = q.all() for k in rows: a =k[0] if a =='0.00.00.10': return HTTPFound(location=request.route_url('ag-pendapatan',kegiatan_sub_id=kegiatan_sub_id)) elif a =='0.00.00.21': return HTTPFound(location=request.route_url('ag-btl',kegiatan_sub_id=kegiatan_sub_id)) elif a =='0.00.00.31': return HTTPFound(location=request.route_url('ag-penerimaan',kegiatan_sub_id=kegiatan_sub_id)) elif a =='0.00.00.32': return HTTPFound(location=request.route_url('ag-pengeluaran',kegiatan_sub_id=kegiatan_sub_id)) #elif a =='0.00.00.20': #return HTTPFound(location=request.route_url('ag-kegiatan-item',kegiatan_sub_id=kegiatan_sub_id)) return HTTPFound(location=request.route_url('ag-kegiatan-item',kegiatan_sub_id=kegiatan_sub_id)) def session_failed(request, session_name): r = dict(form=request.session[session_name]) del request.session[session_name] return r @view_config(route_name='ag-kegiatan-item-add', renderer='templates/ag-kegiatan-item/add.pt', permission='add') def view_add(request): form = get_form(request, AddSchema) kegiatan_sub_id = request.matchdict['kegiatan_sub_id'] ses = request.session rows = KegiatanSub.query_id(kegiatan_sub_id).filter(KegiatanSub.unit_id == ses['unit_id']).first() if request.POST: if 'simpan' in request.POST: controls = request.POST.items() controls_dicted = dict(controls) b = form.validate(controls) vol_1_1 = b['vol_1_1'] vol_1_2 = b['vol_1_2'] hsat_1 = b['hsat_1'].replace('.','') vol_2_1 = b['vol_2_1'] vol_2_2 = b['vol_2_2'] hsat_2 = b['hsat_2'].replace('.','') vol_3_1 = b['vol_3_1'] vol_3_2 = b['vol_3_2'] hsat_3 = b['hsat_3'].replace('.','') vol_4_1 = b['vol_4_1'] vol_4_2 = b['vol_4_2'] hsat_4 = b['hsat_3'].replace('.','') bln01 = b['bln01'] bln02 = b['bln02'] bln03 = b['bln03'] bln04 = b['bln04'] bln05 = b['bln05'] bln06 = b['bln06'] bln07 = b['bln07'] bln08 = b['bln08'] bln09 = b['bln09'] bln10 = b['bln10'] bln11 = b['bln11'] bln12 = b['bln12'] rka = (vol_1_1*vol_1_2)*int(hsat_1) rka1 = int(float(rka)) dpa = (vol_2_1*vol_2_2)*int(hsat_2) dpa1 = int(float(dpa)) rpka = (vol_3_1*vol_3_2)*int(hsat_3) rpka1 = int(float(rpka)) dppa = (vol_4_1*vol_4_2)*int(hsat_4) dppa1 = int(float(rpka)) bln = bln01+bln02+bln03+bln04+bln05+bln06+bln07+bln08+bln09+bln10+bln11+bln12 ag_step_id = request.session['ag_step_id'] if ag_step_id==1: if bln>rka1: request.session.flash('Tidak boleh melebihi jumlah RKA', 'error') return HTTPFound(location=request.route_url('ag-kegiatan-item-add',kegiatan_sub_id=kegiatan_sub_id)) elif ag_step_id==2: if bln>dpa1: request.session.flash('Tidak boleh melebihi jumlah DPA', 'error') return HTTPFound(location=request.route_url('ag-kegiatan-item-add',kegiatan_sub_id=kegiatan_sub_id)) elif ag_step_id==3: if bln>rpka1: request.session.flash('Tidak boleh melebihi jumlah RPKA', 'error') return HTTPFound(location=request.route_url('ag-kegiatan-item-add',kegiatan_sub_id=kegiatan_sub_id)) elif ag_step_id==4: if bln>dppa1: request.session.flash('Tidak boleh melebihi jumlah DPPA', 'error') return HTTPFound(location=request.route_url('ag-kegiatan-item-add',kegiatan_sub_id=kegiatan_sub_id)) #return dict(form=form.render(appstruct=controls_dicted)) try: c = form.validate(controls) except ValidationFailure, e: return dict(form=form, row=rows, rek_head=5) #request.session[SESS_ADD_FAILED] = e.render() #return HTTPFound(location=request.route_url('ag-kegiatan-item-add')) save_request(controls_dicted, request) return route_list(request,kegiatan_sub_id) elif SESS_ADD_FAILED in request.session: del request.session[SESS_ADD_FAILED] #return session_failed(request, SESS_ADD_FAILED) return dict(form=form, row=rows, rek_head=5) ######## # Edit # ######## def query_id(request): return DBSession.query(KegiatanItem).filter(KegiatanItem.id==request.matchdict['id'], KegiatanItem.kegiatan_sub_id==request.matchdict['kegiatan_sub_id']) def id_not_found(request,kegiatan_sub_id): msg = 'ITEM ID %s not found.' % request.matchdict['id'] request.session.flash(msg, 'error') return route_list(request,kegiatan_sub_id) @view_config(route_name='ag-kegiatan-item-edit', renderer='templates/ag-kegiatan-item/add.pt', permission='edit') def view_edit(request): ses = request.session kegiatan_sub_id = request.matchdict['kegiatan_sub_id'] row = query_id(request).first() i=row.id if not row: return id_not_found(request,kegiatan_sub_id) form = get_form(request, EditSchema) rows = KegiatanSub.query_id(kegiatan_sub_id).filter(KegiatanSub.unit_id==ses['unit_id']).first() if request.POST: if 'simpan' in request.POST: controls = request.POST.items() a = form.validate(controls) vol_1_1 = a['vol_1_1'] vol_1_2 = a['vol_1_2'] hsat_1 = a['hsat_1'].replace('.','') vol_2_1 = a['vol_2_1'] vol_2_2 = a['vol_2_2'] hsat_2 = a['hsat_2'].replace('.','') vol_3_1 = a['vol_3_1'] vol_3_2 = a['vol_3_2'] hsat_3 = a['hsat_3'].replace('.','') vol_4_1 = a['vol_4_1'] vol_4_2 = a['vol_4_2'] hsat_4 = a['hsat_3'].replace('.','') bln01 = a['bln01'] bln02 = a['bln02'] bln03 = a['bln03'] bln04 = a['bln04'] bln05 = a['bln05'] bln06 = a['bln06'] bln07 = a['bln07'] bln08 = a['bln08'] bln09 = a['bln09'] bln10 = a['bln10'] bln11 = a['bln11'] bln12 = a['bln12'] rka = (vol_1_1*vol_1_2)*int(hsat_1) rka1 = int(float(rka)) dpa = (vol_2_1*vol_2_2)*int(hsat_2) dpa1 = int(float(dpa)) rpka = (vol_3_1*vol_3_2)*int(hsat_3) rpka1 = int(float(rpka)) dppa = (vol_4_1*vol_4_2)*int(hsat_4) dppa1 = int(float(rpka)) bln = bln01+bln02+bln03+bln04+bln05+bln06+bln07+bln08+bln09+bln10+bln11+bln12 ag_step_id = request.session['ag_step_id'] if ag_step_id==1: if bln>rka1: request.session.flash('Tidak boleh melebihi jumlah RKA', 'error') return HTTPFound(location=request.route_url('ag-kegiatan-item-edit',kegiatan_sub_id=row.kegiatan_sub_id,id=row.id)) elif ag_step_id==2: if bln>dpa1: request.session.flash('Tidak boleh melebihi jumlah DPA', 'error') return HTTPFound(location=request.route_url('ag-kegiatan-item-edit',kegiatan_sub_id=row.kegiatan_sub_id,id=row.id)) elif ag_step_id==3: if bln>rpka1: request.session.flash('Tidak boleh melebihi jumlah RPKA', 'error') return HTTPFound(location=request.route_url('ag-kegiatan-item-edit',kegiatan_sub_id=row.kegiatan_sub_id,id=row.id)) elif ag_step_id==4: if bln>dppa1: request.session.flash('Tidak boleh melebihi jumlah DPPA', 'error') return HTTPFound(location=request.route_url('ag-kegiatan-item-edit',kegiatan_sub_id=row.kegiatan_sub_id,id=row.id)) try: c = form.validate(controls) except ValidationFailure, e: return dict(form=form, row=rows, rek_head=5) save_request(dict(controls), request, row) return route_list(request,kegiatan_sub_id) elif SESS_EDIT_FAILED in request.session: del request.session[SESS_EDIT_FAILED] return dict(form=form) values = row.to_dict() #dict(zip(row.keys(), row)) values['rekening_kd']=row.rekenings.kode values['rekening_nm']=row.rekenings.nama form.set_appstruct(values) return dict(form=form, row=rows, rek_head=5) ########## # Delete # ########## @view_config(route_name='ag-kegiatan-item-delete', renderer='templates/ag-kegiatan-item/delete.pt', permission='delete') def view_delete(request): q = query_id(request) row = q.first() kegiatan_sub_id = request.matchdict['kegiatan_sub_id'] if not row: return {'success':False, "msg":self.id_not_found()} form = Form(colander.Schema(), buttons=('hapus','cancel')) values= {} if request.POST: if 'hapus' in request.POST: msg = 'Data sudah dihapus' DBSession.query(KegiatanItem).filter(KegiatanItem.id==request.matchdict['id']).delete() DBSession.flush() request.session.flash(msg) return route_list(request,kegiatan_sub_id) return dict(row=row,form=form.render()) <file_sep>/osipkd/views/tu_skpd/ap_invoice_skpd.py import os import uuid from osipkd.tools import row2dict, xls_reader from datetime import datetime from sqlalchemy import not_, func from pyramid.view import (view_config,) from pyramid.httpexceptions import ( HTTPFound, ) import colander from deform import (Form, widget, ValidationFailure, ) from osipkd.models import DBSession from osipkd.models.apbd_anggaran import Kegiatan, KegiatanSub, KegiatanItem from osipkd.models.pemda_model import Unit, Rekening, RekeningSap, Sap from osipkd.models.apbd_tu import APInvoice, APInvoiceItem, SppItem, Spp, AkJurnal, AkJurnalItem from datatables import ColumnDT, DataTables from osipkd.views.base_view import BaseViews SESS_ADD_FAILED = 'Tambah ap-invoice-skpd gagal' SESS_EDIT_FAILED = 'Edit ap-invoice-skpd gagal' def deferred_ap_type(node, kw): values = kw.get('ap_type', []) return widget.SelectWidget(values=values) AP_TYPE = ( ('1', 'UP'), ('2', 'TU'), ('3', 'GU'), ('4', 'LS'), ) def deferred_kontrak_type(node, kw): values = kw.get('kontrak_type', []) return widget.SelectWidget(values=values) KONTRAK_TYPE = ( ('1', 'PT / NV'), ('2', 'CV'), ('3', 'FIRMA'), ('4', 'Lain-lain'), ) def deferred_bayar(node, kw): values = kw.get('is_bayar', []) return widget.SelectWidget(values=values) IS_BAYAR = ( ('0', 'Lunas'), ('1', 'Cicilan'), ) class view_ap_invoice_skpd(BaseViews): @view_config(route_name="ap-invoice-skpd", renderer="templates/ap-invoice-skpd/list.pt") def view_list(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict return dict(project='EIS', ) ########## # Action # ########## @view_config(route_name='ap-invoice-skpd-act', renderer='json', permission='read') def view_act(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict if url_dict['act']=='grid': pk_id = 'id' in params and params['id'] and int(params['id']) or 0 if url_dict['act']=='grid': # defining columns columns = [] columns.append(ColumnDT('id')) columns.append(ColumnDT('kode')) columns.append(ColumnDT('jenis')) columns.append(ColumnDT('tanggal', filter=self._DTstrftime)) columns.append(ColumnDT('kegiatan_sub_nm')) columns.append(ColumnDT('nama')) columns.append(ColumnDT('amount')) columns.append(ColumnDT('posted')) columns.append(ColumnDT('status_spp')) query = DBSession.query(APInvoice.id, APInvoice.kode, APInvoice.jenis, APInvoice.tanggal, KegiatanSub.nama.label('kegiatan_sub_nm'), APInvoice.nama, APInvoice.amount, APInvoice.posted, APInvoice.status_spp, ).outerjoin(APInvoiceItem ).filter(APInvoice.tahun_id==ses['tahun'], APInvoice.unit_id==ses['unit_id'], APInvoice.kegiatan_sub_id==KegiatanSub.id, ).order_by(APInvoice.no_urut.desc() ).group_by(APInvoice.id, APInvoice.kode, APInvoice.jenis, APInvoice.tanggal, KegiatanSub.nama.label('kegiatan_sub_nm'), APInvoice.nama, APInvoice.amount, APInvoice.posted, APInvoice.status_spp, ) rowTable = DataTables(req, APInvoice, query, columns) return rowTable.output_result() elif url_dict['act']=='headofnama': query = DBSession.query(APInvoice.id, APInvoice.no_urut, APInvoice.nama, func.sum(APInvoiceItem.amount).label('amount'), func.sum(APInvoiceItem.ppn).label('ppn'), func.sum(APInvoiceItem.pph).label('pph'), )\ .filter(APInvoice.tahun_id==ses['tahun'], APInvoice.unit_id==ses['unit_id'], APInvoice.disabled==0)\ .join(APInvoiceItem)\ .group_by(APInvoice.id, APInvoice.no_urut, APInvoice.nama) rows = query.all() r = [] for k in rows: d={} d['id'] = k[0] d['value'] = ''.join([str(k[1]),' - ',str(k[2])]) d['amount'] = int(k[3]) d['ppn'] = int(k[4]) d['pph'] = int(k[5]) r.append(d) print r return r elif url_dict['act']=='headofkode1': term = 'term' in params and params['term'] or '' #jenis = 'jenis' in params and params['jenis'] or '' #jenis1= "%d" % jenis q = DBSession.query(APInvoice.id, APInvoice.kode.label('kode1'), APInvoice.nama.label('nama1'), APInvoice.amount.label('amount1'), APInvoice.no_bku.label('nbku'), APInvoice.tgl_bku.label('tbku'), )\ .filter(APInvoice.unit_id == ses['unit_id'], APInvoice.tahun_id == ses['tahun'], APInvoice.status_spp == 0, APInvoice.amount != 0, #APInvoice.jenis == jenis1, APInvoice.kode.ilike('%s%%' % term)) rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['value'] = k[1] d['kode'] = k[1] d['nama'] = k[2] d['amount'] = k[3] d['no_bku'] = k[4] d['tgl_bku'] = "%s" % k[5] r.append(d) print '---****----',r return r ####### # Add # ####### def form_validator(form, value): def err_kegiatan(): raise colander.Invalid(form, 'Kegiatan dengan no urut tersebut sudah ada') class AddSchema(colander.Schema): unit_id = colander.SchemaNode( colander.String(), oid = "unit_id") tahun_id = colander.SchemaNode( colander.String(), oid = "tahun_id", title="Tahun") no_urut = colander.SchemaNode( colander.Integer(), oid = "no_urut", missing=colander.drop) kode = colander.SchemaNode( colander.String(), missing=colander.drop, title="No Utang") jenis = colander.SchemaNode( colander.String(), missing=colander.drop, widget=widget.SelectWidget(values=AP_TYPE), oid="jenis", title="Jenis") is_bayar = colander.SchemaNode( colander.String(), missing=colander.drop, widget=widget.SelectWidget(values=IS_BAYAR), oid="is_bayar", title="Dibayar") tanggal = colander.SchemaNode( colander.Date()) kegiatan_sub_id = colander.SchemaNode( colander.Integer(), oid="kegiatan_sub_id") kegiatan_kd = colander.SchemaNode( colander.String(), title = "Kegiatan", oid="kegiatan_kd") kegiatan_nm = colander.SchemaNode( colander.String(), oid="kegiatan_nm") nama = colander.SchemaNode( colander.String(), title="Uraian") """ ap_nomor = colander.SchemaNode( colander.String(), title="No.Kwitansi") ap_tanggal = colander.SchemaNode( colander.Date(), title="Tgl. Kwitansi") """ ap_nama = colander.SchemaNode( colander.String(), title="Nama") ap_rekening = colander.SchemaNode( colander.String(), title="Rekening") ap_npwp = colander.SchemaNode( colander.String(), title="NPWP") amount = colander.SchemaNode( colander.String(), default=0, oid="jml_total", title="Jml. Tagihan") no_bast = colander.SchemaNode( colander.String(), missing=colander.drop, title="No. BAST") tgl_bast = colander.SchemaNode( colander.Date(), missing=colander.drop, title="Tgl. BAST") no_bku = colander.SchemaNode( colander.String(), missing=colander.drop, oid="no_bku", title="No. BKU") tgl_bku = colander.SchemaNode( colander.Date(), missing=colander.drop, oid="tgl_bku", title="Tgl. BKU") ap_bentuk = colander.SchemaNode( colander.String(), widget=widget.SelectWidget(values=KONTRAK_TYPE), title="Bentuk" ) ap_alamat = colander.SchemaNode( colander.String(), missing=colander.drop, title="Alamat" ) ap_pemilik = colander.SchemaNode( colander.String(), missing=colander.drop, title="Pemimpin Perusahaan" ) ap_kontrak = colander.SchemaNode( colander.String(), missing=colander.drop, title="No Kontrak" ) ap_waktu = colander.SchemaNode( colander.String(), missing=colander.drop, title="Waktu" ) ap_nilai = colander.SchemaNode( colander.Integer(), oid="ap_nilai", missing=colander.drop, title="Nilai Kontrak", default=0 ) ap_tgl_kontrak = colander.SchemaNode( colander.Date(), missing=colander.drop, title="Tgl Kontrak" ) """ ap_kegiatankd = colander.SchemaNode( colander.String(), missing=colander.drop, oid="ap_kegiatankd" ) ap_kegiatannm = colander.SchemaNode( colander.String(), missing=colander.drop, oid="ap_kegiatannm", title="Kegiatan" ) """ ap_uraian = colander.SchemaNode( colander.String(), missing=colander.drop, title="Pekerjaan" ) ap_bap_no = colander.SchemaNode( colander.String(), missing=colander.drop, title="No BAP" ) ap_bap_tgl = colander.SchemaNode( colander.Date(), missing=colander.drop, title="Tgl BAP" ) ap_kwitansi_no = colander.SchemaNode( colander.String(), missing=colander.drop, title="No.Kwitansi" ) ap_kwitansi_tgl = colander.SchemaNode( colander.Date(), missing=colander.drop, title="Tgl Kwitansi" ) ap_kwitansi_nilai = colander.SchemaNode( colander.Integer(), oid="ap_kwitansi_nilai", missing=colander.drop, title="Nilai Kwitansi", default=0 ) class EditSchema(AddSchema): id = colander.SchemaNode( colander.Integer(), oid="id") def get_form(request, class_form): schema = class_form(validator=form_validator) schema = schema.bind(kontrak_type=KONTRAK_TYPE,is_bayar=IS_BAYAR) schema.request = request return Form(schema, buttons=('simpan','batal')) def save(request, values, row=None): if not row: row = APInvoice() row.from_dict(values) if not row.no_urut: row.no_urut = APInvoice.max_no_urut(row.tahun_id,row.unit_id)+1; if not row.kode: tahun = request.session['tahun'] unit_kd = request.session['unit_kd'] no_urut = row.no_urut no = "0000%d" % no_urut nomor = no[-5:] row.kode = "%d" % tahun + "-%s" % unit_kd + "-%s" % nomor j='3' j1 = row.jenis if j1 != j: row.no_bku = None row.tgl_bku = None DBSession.add(row) DBSession.flush() return row def save_request(values, request, row=None): if 'id' in request.matchdict: values['id'] = request.matchdict['id'] values["amount"]=values["amount"].replace('.','') row = save(request, values, row) request.session.flash('Tagihan sudah disimpan.') return row def route_list(request): return HTTPFound(location=request.route_url('ap-invoice-skpd')) def session_failed(request, session_name): r = dict(form=request.session[session_name]) del request.session[session_name] return r @view_config(route_name='ap-invoice-skpd-add', renderer='templates/ap-invoice-skpd/add.pt', permission='add') def view_add(request): form = get_form(request, AddSchema) if request.POST: if 'simpan' in request.POST: controls = request.POST.items() controls_dicted = dict(controls) #Cek Kode Sama ato tidak if not controls_dicted['kode']=='': a = form.validate(controls) b = a['kode'] c = "%s" % b cek = DBSession.query(APInvoice).filter(APInvoice.kode==c).first() if cek : request.session.flash('Kode Invoice sudah ada.', 'error') return HTTPFound(location=self.request.route_url('ap-invoice-skpd-add')) try: c = form.validate(controls) except ValidationFailure, e: return dict(form=form) row = save_request(controls_dicted, request) return HTTPFound(location=request.route_url('ap-invoice-skpd-edit',id=row.id)) return route_list(request) elif SESS_ADD_FAILED in request.session: del request.session[SESS_ADD_FAILED] return dict(form=form) ######## # Edit # ######## def query_id(request): return DBSession.query(APInvoice).filter(APInvoice.id==request.matchdict['id']) def id_not_found(request): msg = 'User ID %s not found.' % request.matchdict['id'] request.session.flash(msg, 'error') return route_list(request) @view_config(route_name='ap-invoice-skpd-edit', renderer='templates/ap-invoice-skpd/add.pt', permission='edit') def view_edit(request): row = query_id(request).first() uid = row.id kode = row.kode if not row: return id_not_found(request) if row.status_spp: request.session.flash('Data sudah di SPP', 'error') return route_list(request) if row.posted: request.session.flash('Data sudah diposting', 'error') return route_list(request) form = get_form(request, EditSchema) if request.POST: if 'simpan' in request.POST: controls = request.POST.items() #Cek Kode Sama ato tidak a = form.validate(controls) b = a['kode'] c = "%s" % b cek = DBSession.query(APInvoice).filter(APInvoice.kode==c).first() if cek: kode1 = DBSession.query(APInvoice).filter(APInvoice.id==uid).first() d = kode1.kode if d!=c: request.session.flash('Kode Invoice sudah ada', 'error') return HTTPFound(location=request.route_url('ap-invoice-skpd-edit',id=row.id)) try: c = form.validate(controls) except ValidationFailure, e: return dict(form=form) save_request(dict(controls), request, row) return route_list(request) elif SESS_EDIT_FAILED in request.session: del request.session[SESS_EDIT_FAILED] return dict(form=form) values = row.to_dict() #Ketika pas edit, kode sama nama muncul sesuai id kegiatansub values['kegiatan_nm']=row.kegiatansubs.nama kd=row.kegiatansubs.kode ur=row.kegiatansubs.no_urut values['kegiatan_kd']="%s" % kd + "-%d" % ur """ if values['ap_kegiatankd']: r = DBSession.query(Kegiatan).filter(Kegiatan.id==values['ap_kegiatankd']).first() nama = r.nama values['ap_kegiatannm']=nama """ form.set_appstruct(values) return dict(form=form) ########## # Delete # ########## @view_config(route_name='ap-invoice-skpd-delete', renderer='templates/ap-invoice-skpd/delete.pt', permission='delete') def view_delete(request): q = query_id(request) row = q.first() if not row: return id_not_found(request) if row.posted: request.session.flash('Data sudah diposting', 'error') return route_list(request) if row.status_spp: request.session.flash('Data sudah di SPP', 'error') return route_list(request) if row.amount: request.session.flash('Data tidak bisa dihapus, karena memiliki data items') return route_list(request) form = Form(colander.Schema(), buttons=('hapus','cancel')) values= {} if request.POST: if 'hapus' in request.POST: msg = '%s dengan kode %s telah berhasil.' % (request.title, row.kode) DBSession.query(APInvoice).filter(APInvoice.id==request.matchdict['id']).delete() DBSession.flush() request.session.flash(msg) return route_list(request) return dict(row=row, form=form.render()) ########### # Posting # ########### def save_request2(request, row=None): row = APInvoice() request.session.flash('Tagihan sudah diposting dan dibuat Jurnalnya.') return row @view_config(route_name='ap-invoice-skpd-posting', renderer='templates/ap-invoice-skpd/posting.pt', permission='posting') def view_edit_posting(request): row = query_id(request).first() id_inv = row.id g = row.jenis if not row: return id_not_found(request) if g == 1: request.session.flash('Data tidak dapat diposting, karena bukan tipe GU / LS.', 'error') return route_list(request) if g == 2: request.session.flash('Data tidak dapat diposting, karena bukan tipe GU / LS.', 'error') return route_list(request) if not row.amount: request.session.flash('Data tidak dapat diposting, karena bernilai 0.', 'error') return route_list(request) if row.posted: request.session.flash('Data sudah diposting', 'error') return route_list(request) form = Form(colander.Schema(), buttons=('posting','cancel')) if request.POST: if 'posting' in request.POST: #Update posted pada APInvoice row.posted=1 save_request2(request, row) #Tambah ke Jurnal SKPD nama = row.nama kode = row.kode tanggal = row.tanggal tipe = APInvoice.get_tipe(row.id) periode = APInvoice.get_periode(row.id) row = AkJurnal() row.created = datetime.now() row.create_uid = request.user.id row.updated = datetime.now() row.update_uid = request.user.id row.tahun_id = request.session['tahun'] row.unit_id = request.session['unit_id'] row.nama = "Dibayar Tagihan %s" % tipe + " %s" % nama row.notes = nama row.periode = periode row.posted = 0 row.disabled = 0 row.is_skpd = 1 row.jv_type = 2 row.source = "Tagihan-%s" % tipe row.source_no = kode row.tgl_source = tanggal row.tanggal = datetime.now() row.tgl_transaksi = datetime.now() if not row.kode: tahun = request.session['tahun'] unit_kd = request.session['unit_kd'] is_skpd = row.is_skpd tipe = AkJurnal.get_tipe(row.jv_type) no_urut = AkJurnal.get_norut(row.id)+1 no = "0000%d" % no_urut nomor = no[-5:] row.kode = "%d" % tahun + "-%s" % is_skpd + "-%s" % unit_kd + "-%s" % tipe + "-%s" % nomor DBSession.add(row) DBSession.flush() jui = row.id rows = DBSession.query(KegiatanItem.rekening_id.label('rekening_id1'), KegiatanItem.nama.label('nama1'), KegiatanItem.kegiatan_sub_id.label('kegiatan_sub_id1'), APInvoiceItem.amount.label('nilai1'), RekeningSap.db_lo_sap_id.label('sap1'), RekeningSap.db_lra_sap_id.label('sap2'), RekeningSap.neraca_sap_id.label('sap3'), ).join(APInvoiceItem, KegiatanSub, ).outerjoin(KegiatanItem,Rekening,RekeningSap ).filter(APInvoice.id==id_inv, APInvoice.kegiatan_sub_id==KegiatanSub.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanItem.rekening_id==Rekening.id, RekeningSap.rekening_id==Rekening.id, ).group_by(KegiatanItem.rekening_id.label('rekening_id1'), KegiatanItem.nama.label('nama1'), KegiatanItem.kegiatan_sub_id.label('kegiatan_sub_id1'), APInvoiceItem.amount.label('nilai1'), RekeningSap.db_lo_sap_id.label('sap1'), RekeningSap.db_lra_sap_id.label('sap2'), RekeningSap.neraca_sap_id.label('sap3'), ).all() n=0 for row in rows: ji = AkJurnalItem() ji.ak_jurnal_id = "%d" % jui ji.kegiatan_sub_id = row.kegiatan_sub_id1 ji.rekening_id = row.rekening_id1 ji.sap_id = row.sap1 ji.amount = row.nilai1 ji.notes = row.nama1 n = n + 1 DBSession.add(ji) DBSession.flush() return route_list(request) return dict(row=row, form=form.render()) ############# # UnPosting # ############# def save_request3(request, row=None): row = APInvoice() request.session.flash('Tagihan sudah di UnPosting.') return row @view_config(route_name='ap-invoice-skpd-unposting', renderer='templates/ap-invoice-skpd/unposting.pt', permission='unposting') def view_edit_unposting(request): row = query_id(request).first() if not row: return id_not_found(request) if not row.posted: request.session.flash('Data tidak dapat di Unposting, karena belum diposting.', 'error') return route_list(request) if row.disabled: request.session.flash('Data jurnal Tagihan sudah diposting.', 'error') return route_list(request) form = Form(colander.Schema(), buttons=('unposting','cancel')) if request.POST: if 'unposting' in request.POST: #Update status posted pada UTANG row.posted=0 save_request3(request, row) r = DBSession.query(AkJurnal.id).filter(AkJurnal.source_no==row.kode).first() #Menghapus Item Jurnal DBSession.query(AkJurnalItem).filter(AkJurnalItem.ak_jurnal_id==r).delete() DBSession.flush() #Menghapus UTANG yang sudah menjadi jurnal DBSession.query(AkJurnal).filter(AkJurnal.source_no==row.kode).delete() DBSession.flush() return route_list(request) return dict(row=row, form=form.render()) <file_sep>/osipkd/views/tu_skpd/ak_tbp.py import os import uuid from osipkd.tools import row2dict, xls_reader from datetime import datetime from sqlalchemy import not_, func from pyramid.view import (view_config,) from pyramid.httpexceptions import ( HTTPFound, ) import colander from deform import (Form, widget, ValidationFailure, ) from osipkd.models import DBSession from osipkd.models.apbd import ARPaymentItem from osipkd.models.pemda_model import Unit, Rekening, Sap, RekeningSap from osipkd.models.apbd_tu import AkJurnal, AkJurnalItem from osipkd.models.apbd_anggaran import Kegiatan, KegiatanSub, KegiatanItem from datatables import ColumnDT, DataTables from osipkd.views.base_view import BaseViews SESS_ADD_FAILED = 'Tambah ak-tbp gagal' SESS_EDIT_FAILED = 'Edit ak-tbp gagal' def deferred_sumber_id(node, kw): values = kw.get('sumber_id', []) return widget.SelectWidget(values=values) SUMBER_ID = ( (1, 'Manual'), (2, 'PBB'), (3, 'BPHTB'), (4, 'PADL')) class view_ar_payment_item(BaseViews): ######## # List # ######## @view_config(route_name='ak-tbp', renderer='templates/ak-tbp/list.pt', permission='read') def view_list(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict return dict(project='EIS') ########## # Action # ########## @view_config(route_name='ak-tbp-act', renderer='json', permission='read') def ar_payment_item_act(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict kegiatan_sub_id = 'kegiatan_sub_id' in params and params['kegiatan_sub_id'] or 0 if url_dict['act']=='grid': columns = [] columns.append(ColumnDT('id')) columns.append(ColumnDT('kode')) columns.append(ColumnDT('nama')) columns.append(ColumnDT('ref_kode')) columns.append(ColumnDT('ref_nama')) columns.append(ColumnDT('tanggal', filter=self._DTstrftime)) columns.append(ColumnDT('amount', filter=self._number_format)) columns.append(ColumnDT('posted')) query = DBSession.query(ARPaymentItem).filter(ARPaymentItem.tahun == ses['tahun'], ARPaymentItem.unit_id == ses['unit_id'], ARPaymentItem.tanggal == ses['tanggal'], ) rowTable = DataTables(req, ARPaymentItem, query, columns) return rowTable.output_result() def route_list(self): return HTTPFound(location=self.request.route_url('ak-tbp') ) def session_failed(self, session_name): del self.session[session_name] def query_id(self): return DBSession.query(ARPaymentItem).filter_by(id=self.request.matchdict['id']) def id_not_found(self): msg = 'TBP ID %s Tidak Ditemukan.' % self.request.matchdict['id'] request.session.flash(msg, 'error') return route_list() ########### # Posting # ########### def save_request2(self, row=None): row = ARPaymentItem() self.request.session.flash('TBP sudah diposting dan dibuat Jurnalnya.') return row @view_config(route_name='ak-tbp-posting', renderer='templates/ak-tbp/posting.pt', permission='posting') def view_edit_posting(self): request = self.request row = self.query_id().first() id_tbp = row.id nama = row.ref_nama kode = row.ref_kode tanggal = row.tanggal if not row: return id_not_found(request) if not row.amount: request.session.flash('Data tidak dapat diposting jurnal, karena bernilai 0.', 'error') return route_list() if row.posted: request.session.flash('Data sudah diposting jurnal.', 'error') return self.route_list() form = Form(colander.Schema(), buttons=('jurnal','cancel')) if request.POST: if 'jurnal' in request.POST: #Update posted pada TBP row.posted=1 self.save_request2(row) #Tambah ke Jurnal LO SKPD periode = ARPaymentItem.get_periode(row.id) row = AkJurnal() row.created = datetime.now() row.create_uid = self.request.user.id row.updated = datetime.now() row.update_uid = self.request.user.id row.tahun_id = self.session['tahun'] row.unit_id = self.session['unit_id'] row.nama = "Diterima TBP %s" % nama row.notes = nama row.periode = periode row.posted = 0 row.disabled = 0 row.is_skpd = 1 row.jv_type = 1 row.source = "TBP" row.source_no = kode row.tgl_source = tanggal row.tanggal = datetime.now() row.tgl_transaksi = datetime.now() if not row.kode: tahun = self.session['tahun'] unit_kd = self.session['unit_kd'] is_skpd = row.is_skpd tipe = AkJurnal.get_tipe(row.jv_type) no_urut = AkJurnal.get_norut(row.tahun_id,row.unit_id)+1 no = "0000%d" % no_urut nomor = no[-5:] row.kode = "%d" % tahun + "-%s" % is_skpd + "-%s" % unit_kd + "-%s" % tipe + "-%s" % nomor DBSession.add(row) DBSession.flush() jui = row.id rows = DBSession.query(KegiatanItem.rekening_id.label('rekening_id1'), Sap.nama.label('nama1'), KegiatanItem.kegiatan_sub_id.label('kegiatan_sub_id1'), ARPaymentItem.amount.label('nilai1'), RekeningSap.db_lo_sap_id.label('sap1'), Rekening.id.label('rek'), ).join(Rekening ).outerjoin(KegiatanItem,RekeningSap,KegiatanSub, ).filter(ARPaymentItem.id==id_tbp, ARPaymentItem.rekening_id==KegiatanItem.rekening_id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanItem.rekening_id==RekeningSap.rekening_id, RekeningSap.rekening_id==Rekening.id, RekeningSap.db_lo_sap_id==Sap.id ).group_by(KegiatanItem.rekening_id.label('rekening_id1'), Sap.nama.label('nama1'), KegiatanItem.kegiatan_sub_id.label('kegiatan_sub_id1'), ARPaymentItem.amount.label('nilai1'), RekeningSap.db_lo_sap_id.label('sap1'), Rekening.id.label('rek'), ).all() n=0 for row in rows: ji = AkJurnalItem() ji.ak_jurnal_id = "%d" % jui ji.kegiatan_sub_id = row.kegiatan_sub_id1 ji.rekening_id = 0 x=DBSession.query(Sap.id).filter(Sap.kode=='1.1.1.02.01').first() ji.sap_id = x ji.amount = row.nilai1 ji.notes = "" n = n + 1 DBSession.add(ji) DBSession.flush() n=0 for row in rows: ji2 = AkJurnalItem() ji2.ak_jurnal_id = "%d" % jui ji2.kegiatan_sub_id = row.kegiatan_sub_id1 ji2.rekening_id = row.rek ji2.sap_id = row.sap1 n = row.nilai1 ji2.amount = n * -1 ji2.notes = "" n = n + 1 DBSession.add(ji2) DBSession.flush() #Tambah ke Jurnal LRA SKPD periode2 = ARPaymentItem.get_periode2(id_tbp) row = AkJurnal() row.created = datetime.now() row.create_uid = self.request.user.id row.updated = datetime.now() row.update_uid = self.request.user.id row.tahun_id = self.session['tahun'] row.unit_id = self.session['unit_id'] row.nama = "Diterima TBP %s" % nama row.notes = nama row.periode = periode2 row.posted = 0 row.disabled = 0 row.is_skpd = 1 row.jv_type = 1 row.source = "TBP" row.source_no = kode row.tgl_source = tanggal row.tanggal = datetime.now() row.tgl_transaksi = datetime.now() if not row.kode: tahun = self.session['tahun'] unit_kd = self.session['unit_kd'] is_skpd = row.is_skpd tipe = AkJurnal.get_tipe(row.jv_type) no_urut = AkJurnal.get_norut(row.tahun_id,row.unit_id)+1 no = "0000%d" % no_urut nomor = no[-5:] row.kode = "%d" % tahun + "-%s" % is_skpd + "-%s" % unit_kd + "-%s" % tipe + "-%s" % nomor DBSession.add(row) DBSession.flush() jui = row.id rows = DBSession.query(KegiatanItem.rekening_id.label('rekening_id1'), Sap.nama.label('nama1'), KegiatanItem.kegiatan_sub_id.label('kegiatan_sub_id1'), ARPaymentItem.amount.label('nilai1'), RekeningSap.db_lra_sap_id.label('sap1'), RekeningSap.kr_lra_sap_id.label('sap2'), Rekening.id.label('rek'), ).join(Rekening ).outerjoin(KegiatanItem,RekeningSap,KegiatanSub, ).filter(ARPaymentItem.id==id_tbp, ARPaymentItem.rekening_id==KegiatanItem.rekening_id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanItem.rekening_id==RekeningSap.rekening_id, RekeningSap.rekening_id==Rekening.id, RekeningSap.db_lra_sap_id==Sap.id ).group_by(KegiatanItem.rekening_id.label('rekening_id1'), Sap.nama.label('nama1'), KegiatanItem.kegiatan_sub_id.label('kegiatan_sub_id1'), ARPaymentItem.amount.label('nilai1'), RekeningSap.db_lra_sap_id.label('sap1'), RekeningSap.kr_lra_sap_id.label('sap2'), Rekening.id.label('rek'), ).all() n=0 for row in rows: ji3 = AkJurnalItem() ji3.ak_jurnal_id = "%d" % jui ji3.kegiatan_sub_id = row.kegiatan_sub_id1 ji3.rekening_id = 0 ji3.sap_id = row.sap1 ji3.amount = row.nilai1 ji3.notes = "" n = n + 1 DBSession.add(ji3) DBSession.flush() n=0 for row in rows: ji4 = AkJurnalItem() ji4.ak_jurnal_id = "%d" % jui ji4.kegiatan_sub_id = row.kegiatan_sub_id1 ji4.rekening_id = row.rek ji4.sap_id = row.sap2 n = row.nilai1 ji4.amount = n * -1 ji4.notes = "" n = n + 1 DBSession.add(ji4) DBSession.flush() return self.route_list() return dict(row=row, form=form.render()) ############# # UnPosting # ############# def save_request4(self, row=None): row = ARPaymentItem() self.request.session.flash('TBP sudah di Unposting jurnal.') return row @view_config(route_name='ak-tbp-unposting', renderer='templates/ak-tbp/unposting.pt', permission='unposting') def view_edit_unposting(self): request = self.request row = self.query_id().first() kode = row.ref_kode if not row: return id_not_found(request) if not row.posted: request.session.flash('Data tidak dapat di Unposting jurnal, karena belum diposting jurnal.', 'error') return self.route_list() if row.disabled: request.session.flash('Data jurnal TBP sudah diposting.', 'error') return self.route_list() form = Form(colander.Schema(), buttons=('un-jurnal','cancel')) if request.POST: if 'un-jurnal' in request.POST: #Update status posted pada TBP row.posted=0 self.save_request4(row) r = DBSession.query(AkJurnal.id.label('di')).filter(AkJurnal.source_no==row.ref_kode,AkJurnal.source=='TBP').all() for row in r: #Menghapus Item Jurnal DBSession.query(AkJurnalItem).filter(AkJurnalItem.ak_jurnal_id==row.di).delete() DBSession.flush() #Menghapus TBP yang sudah menjadi jurnal DBSession.query(AkJurnal).filter(AkJurnal.source_no==kode,AkJurnal.source=='TBP').delete() DBSession.flush() return self.route_list() return dict(row=row, form=form.render()) <file_sep>/osipkd/views/anggaran/kegiatan_sub.py import os import uuid from osipkd.tools import row2dict, xls_reader from datetime import datetime from sqlalchemy import not_, func, cast, BigInteger, or_, join from pyramid.view import (view_config,) from pyramid.httpexceptions import ( HTTPFound, ) import colander from deform import (Form, widget, ValidationFailure, ) from osipkd.models import DBSession from osipkd.models.apbd_anggaran import Program, Kegiatan, KegiatanSub, KegiatanItem from osipkd.models.pemda_model import Urusan from osipkd.models.apbd_tu import Spd, SpdItem from datatables import ColumnDT, DataTables from osipkd.views.base_view import BaseViews SESS_ADD_FAILED = 'Tambah ag-kegiatan-sub gagal' SESS_EDIT_FAILED = 'Edit ag-kegiatan-sub gagal' def deferred_sdana(node, kw): values = kw.get('sdana', []) return widget.SelectWidget(values=values) SDANA = ( ('PAD', 'PAD'), ('DAU', 'DAU'), ('DAK', 'DAK'), ('APBD Provinsi', 'APBD Provinsi'), ('APBN', 'APBN'), ('LOAN', 'LOAN'), ('Bagi Hasil', 'Bagi Hasil'), ) class view_kegiatan_sub(BaseViews): @view_config(route_name="ag-bl", renderer="templates/ag-bl/list.pt") def view_list(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict #row = {} #row['rekening_kd'] = '0.00.00.21' #row['rekening_nm'] = 'BELANJA TIDAK LANGSUNG' #row['rekeninghead'] = 52 return dict(project='EIS', #row = row ) ########## # Action # ########## @view_config(route_name='ag-bl-act', renderer='json', permission='read') def view_act(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict if url_dict['act']=='grid': pk_id = 'id' in params and params['id'] and int(params['id']) or 0 if url_dict['act']=='grid': # defining columns columns = [] columns.append(ColumnDT('id')) columns.append(ColumnDT('kode')) columns.append(ColumnDT('no_urut')) columns.append(ColumnDT('nama')) columns.append(ColumnDT('prg_nm')) columns.append(ColumnDT('rka')) columns.append(ColumnDT('dpa')) columns.append(ColumnDT('rpka')) columns.append(ColumnDT('dppa')) #columns.append(ColumnDT('pegawai_nama')) query = DBSession.query(KegiatanSub.id, KegiatanSub.kode, KegiatanSub.no_urut, KegiatanSub.nama, #PegawaiModel.nama.label('pegawai_nama'), Program.nama.label('prg_nm'), func.sum(KegiatanItem.vol_1_1*KegiatanItem.vol_1_2* KegiatanItem.hsat_1).label('rka'), func.sum(KegiatanItem.vol_2_1*KegiatanItem.vol_2_2* KegiatanItem.hsat_2).label('dpa'), func.sum(KegiatanItem.vol_3_1*KegiatanItem.vol_3_2* KegiatanItem.hsat_3).label('rpka'), func.sum(KegiatanItem.vol_4_1*KegiatanItem.vol_4_2* KegiatanItem.hsat_4).label('dppa'))\ .join(Kegiatan)\ .join(Program)\ .join(Urusan)\ .outerjoin(KegiatanItem)\ .filter( KegiatanSub.unit_id==self.unit_id, KegiatanSub.tahun_id==self.tahun, KegiatanSub.tahun_id==self.tahun, #KegiatanSub.ttd1nip==PegawaiModel.kode, Program.kode<>'0.00.00')\ .group_by(KegiatanSub.id, KegiatanSub.no_urut, KegiatanSub.nama, Program.kode, Program.nama, Kegiatan.kode, Urusan.kode, #PegawaiModel.kode, PegawaiModel.nama ) rowTable = DataTables(req, KegiatanSub, query, columns) # returns what is needed by DataTable #session.query(Table.column, func.count(Table.column)).group_by(Table.column).all() return rowTable.output_result() elif url_dict['act']=='reload': #if not kegiatan_kd: # return {'success':False} query = DBSession.query(KegiatanSub).join(Kegiatan).join(Program).filter( KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id == ses['tahun'], Program.kode<>'0.00.00' ).first() #if not query: # return {'success':False, 'msg':'Data Kegiatan Tidak Ditemukan'} return {"success": True} @view_config(route_name='ag-kegiatan-sub-act', renderer='json', permission='read') def view_act2(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict if url_dict['act']=='reload': kegiatan_kd = 'kegiatan_kd' in params and params['kegiatan_kd'] or None if not kegiatan_kd: return {'success':False} query = DBSession.query(KegiatanSub).join(Kegiatan).filter( KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id == ses['tahun'], Kegiatan.kode == kegiatan_kd ).first() if not query: return {'success':False, 'msg':'Data Sub Kegiatan Tidak Ditemukan'} return {"success": True, 'kegiatan_sub_id': query.id, 'msg':''} elif url_dict['act']=='headofkode': term = 'term' in params and params['term'] or '' q = DBSession.query(KegiatanSub.id, Kegiatan.kode, KegiatanSub.no_urut, KegiatanSub.nama ).join(Kegiatan).filter(KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id==ses['tahun'], Kegiatan.kode.ilike('%%%s%%' % term)) rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['value'] = ''.join([k[1],'-',str(k[2])]) d['kode'] = ''.join([k[1],'-',str(k[2])]) d['nama'] = k[3] r.append(d) return r elif url_dict['act']=='headofnama': term = 'term' in params and params['term'] or '' q = DBSession.query(KegiatanSub.id, Kegiatan.kode, KegiatanSub.no_urut, KegiatanSub.nama).join(Kegiatan).filter( KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id==ses['tahun'], Kegiatan.nama.ilike('%%%s%%' % term)) rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['value'] = k[3] d['kode'] = ''.join([k[1],'-',str(k[2])]) d['nama'] = k[3] r.append(d) return r elif url_dict['act']=='headofkode1': term = 'term' in params and params['term'] or '' q = DBSession.query(KegiatanSub.id, Kegiatan.kode, KegiatanSub.no_urut, KegiatanSub.nama ).join(Kegiatan ).filter(KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id==ses['tahun'], Kegiatan.kode!='0.00.00.10', Kegiatan.kode!='0.00.00.31', Kegiatan.kode!='0.00.00.32', Kegiatan.kode.ilike('%%%s%%' % term)) rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['value'] = ''.join([k[1],'-',str(k[2])]) d['kode'] = k[1] d['nama'] = k[3] r.append(d) print '****----****',r return r elif url_dict['act']=='headofnama1': term = 'term' in params and params['term'] or '' q = DBSession.query(KegiatanSub.id, Kegiatan.kode, KegiatanSub.no_urut, KegiatanSub.nama ).join(Kegiatan ).filter(KegiatanSub.unit_id ==ses['unit_id'], KegiatanSub.tahun_id==ses['tahun'], Kegiatan.kode!='0.00.00.10', Kegiatan.kode!='0.00.00.31', Kegiatan.kode!='0.00.00.32', KegiatanSub.nama.ilike('%%%s%%' % term)) rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['value'] = k[3] d['kode'] = ''.join([k[1],'-',str(k[2])]) d['nama'] = k[3] r.append(d) print '****----****',r return r elif url_dict['act']=='headofkode2': term = 'term' in params and params['term'] or '' q = DBSession.query(KegiatanSub.id, Kegiatan.kode, KegiatanSub.no_urut, KegiatanSub.nama ).join(Kegiatan).filter(KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id==ses['tahun'], KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.kode.ilike('%%%s%%' % term)) rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['value'] = k[1] d['kode'] = k[1] d['nama'] = k[3] r.append(d) print '****----****',r return r elif url_dict['act']=='headofnama2': term = 'term' in params and params['term'] or '' q = DBSession.query(KegiatanSub.id, Kegiatan.kode, KegiatanSub.no_urut, KegiatanSub.nama).join(Kegiatan).filter( KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id==ses['tahun'], Kegiatan.kode=='0.00.00.10', Kegiatan.nama.ilike('%%%s%%' % term)) rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['value'] = k[3] d['kode'] = ''.join([k[1],'-',str(k[2])]) d['nama'] = k[3] r.append(d) return r elif url_dict['act']=='headofkode3': term = 'term' in params and params['term'] or '' ap_spd_id = 'ap_spd_id' in params and params['ap_spd_id'] or 0 q = DBSession.query(KegiatanSub.id.label('kegiatan_sub_id'), Kegiatan.kode.label('kode'), KegiatanSub.nama.label('nama'), func.sum(KegiatanItem.vol_4_1*KegiatanItem.vol_4_2*KegiatanItem.hsat_4).label('anggaran'), func.sum(KegiatanItem.bln01+KegiatanItem.bln02+KegiatanItem.bln03).label('trw1'), func.sum(KegiatanItem.bln04+KegiatanItem.bln05+KegiatanItem.bln06).label('trw2'), func.sum(KegiatanItem.bln07+KegiatanItem.bln08+KegiatanItem.bln09).label('trw3'), func.sum(KegiatanItem.bln10+KegiatanItem.bln11+KegiatanItem.bln12).label('trw4') ).join(Kegiatan).join(KegiatanItem ).filter(KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id==ses['tahun'], Kegiatan.kode.ilike('%%%s%%' % term) ).group_by(KegiatanSub.id, Kegiatan.kode, KegiatanSub.nama) rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['kode'] = k[1] d['nama'] = k[2] d['anggaran'] = k[3] spds = DBSession.query(Spd).filter(Spd.id==ap_spd_id).first() spd_tanggal = spds.tanggal rows2 = DBSession.query(func.sum(SpdItem.nominal).label('lalu') ).join(Spd ).filter(SpdItem.kegiatan_sub_id==d['id'], Spd.tanggal<=spd_tanggal).first() d['lalu'] = rows2.lalu or 0 d['nominal'] = spds.triwulan_id==1 and k[4] or\ spds.triwulan_id==2 and k[5] or\ spds.triwulan_id==3 and k[6] or\ spds.triwulan_id==4 and k[7] if d['nominal']==0: d['nominal'] = d['anggaran'] // 4 d['value'] = d['kode'] d['kode'] = d['kode'] d['nama'] = d['nama'] d['anggaran'] = "%d" % d['anggaran'] d['lalu'] = "%d" % d['lalu'] d['nominal'] = "%d" % d['nominal'] r.append(d) print '****----****',r return r elif url_dict['act']=='headofnama3': term = 'term' in params and params['term'] or '' ap_spd_id = 'ap_spd_id' in params and params['ap_spd_id'] or 0 q = DBSession.query(KegiatanSub.id.label('kegiatan_sub_id'), Kegiatan.kode.label('kode'), KegiatanSub.nama.label('nama'), func.sum(KegiatanItem.vol_4_1*KegiatanItem.vol_4_2*KegiatanItem.hsat_4).label('anggaran'), func.sum(KegiatanItem.bln01+KegiatanItem.bln02+KegiatanItem.bln03).label('trw1'), func.sum(KegiatanItem.bln04+KegiatanItem.bln05+KegiatanItem.bln06).label('trw2'), func.sum(KegiatanItem.bln07+KegiatanItem.bln08+KegiatanItem.bln09).label('trw3'), func.sum(KegiatanItem.bln10+KegiatanItem.bln11+KegiatanItem.bln12).label('trw4') ).join(Kegiatan).join(KegiatanItem ).filter(KegiatanSub.unit_id == ses['unit_id'], KegiatanSub.tahun_id==ses['tahun'], KegiatanSub.nama.ilike('%%%s%%' % term) ).group_by(KegiatanSub.id, Kegiatan.kode, KegiatanSub.nama) rows = q.all() r = [] for k in rows: d={} d['id'] = k[0] d['kode'] = k[1] d['nama'] = k[2] d['anggaran'] = k[3] spds = DBSession.query(Spd).filter(Spd.id==ap_spd_id).first() spd_tanggal = spds.tanggal rows2 = DBSession.query(func.sum(SpdItem.nominal).label('lalu') ).join(Spd ).filter(SpdItem.kegiatan_sub_id==d['id'], Spd.tanggal<=spd_tanggal).first() d['lalu'] = rows2.lalu or 0 d['nominal'] = spds.triwulan_id==1 and k[4] or\ spds.triwulan_id==2 and k[5] or\ spds.triwulan_id==3 and k[6] or\ spds.triwulan_id==4 and k[7] if d['nominal']==0: d['nominal'] = d['anggaran'] // 4 d['value'] = d['nama'] d['kode'] = d['kode'] d['nama'] = d['nama'] d['anggaran'] = "%d" % d['anggaran'] d['lalu'] = "%d" % d['lalu'] d['nominal'] = "%d" % d['nominal'] r.append(d) print '****----****',r return r ############### # Tambah Data# ############### @view_config(route_name='ag-kegiatan-sub-add-fast', renderer='json', permission='add') def ak_kegiatan_sub_add_fast(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict kegiatan_kd = 'kegiatan_kd' in params and params['kegiatan_kd'] or None kegiatan = DBSession.query(Kegiatan).filter(Kegiatan.kode==kegiatan_kd).first() if not kegiatan: return {"success": False, 'msg':'Kegiatan tidak ditemukan'} row = KegiatanSub() row.kegiatan_id = kegiatan.id row.nama = kegiatan.nama row.created = datetime.now() row.tahun_id = ses['tahun'] row.unit_id = ses['unit_id'] row.no_urut = 1 try: DBSession.add(row) DBSession.flush() return {"success": True, 'id': row.id, "msg":'Success Tambah Kegiatan'} except: return {'success':False, 'msg':'Gagal Tambah Kegiatan'} ####### # Add # ####### def form_validator(form, value): def err_kegiatan(): raise colander.Invalid(form, 'Kegiatan dengan no urut tersebut sudah ada') class AddSchema(colander.Schema): kegiatan_widget = widget.AutocompleteInputWidget( size=60, values = '/kegiatan/act/headofkode', min_length=1) kegiatannm_widget = widget.AutocompleteInputWidget( size=60, values = '/kegiatan/act/headofnama', min_length=1) tahun_id = colander.SchemaNode( colander.String(), oid = "tahun_id", title="Tahun") unit_id = colander.SchemaNode( colander.String(), oid = "unit_id") unit_kd = colander.SchemaNode( colander.String(), title="SKPD", oid = "unit_kd") unit_nm = colander.SchemaNode( colander.String(), oid = "unit_nm") kegiatan_id = colander.SchemaNode( colander.Integer(), oid="kegiatan_id") kode = colander.SchemaNode( colander.String(), widget = kegiatan_widget, oid="kode", title="Kegiatan") kegiatan_nm = colander.SchemaNode( colander.String(), widget = kegiatannm_widget, oid="kegiatan_nm",) no_urut = colander.SchemaNode( colander.Integer(), missing=colander.drop) nama = colander.SchemaNode( colander.String(), title="Uraian", oid = "nama") lokasi = colander.SchemaNode( colander.String(), missing=colander.drop) sifat = colander.SchemaNode( colander.String(), missing=colander.drop) bagian = colander.SchemaNode( colander.String(), missing=colander.drop) kondisi = colander.SchemaNode( colander.String(), missing=colander.drop) waktu = colander.SchemaNode( colander.String(), missing=colander.drop, title = 'Waktu Pelaks.') amt_lalu = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = 'Anggaran Lalu') amt_yad = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = 'Anggaran YAD') sdana = colander.SchemaNode( colander.String(), widget=widget.SelectWidget(values=SDANA), missing=colander.drop, title = 'Sumber Dana') ttd1nip = colander.SchemaNode( colander.String(), missing=colander.drop, title="Pejabat 1") ttd2nip = colander.SchemaNode( colander.String(), missing=colander.drop, title="Pejabat 2") notes = colander.SchemaNode( colander.String(), missing=colander.drop, title="Catatan") target = colander.SchemaNode( colander.String(), missing=colander.drop,) sasaran = colander.SchemaNode( colander.String(), missing=colander.drop,) perubahan = colander.SchemaNode( colander.String(), missing=colander.drop, title="Alasan Perubahan") ppa = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = 'PPA',) ppas = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = 'PPAS',) ppa_rev = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = 'Perubahan PPA',) ppas_rev = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = 'Perubahan PPAS',) volume = colander.SchemaNode( colander.String(), missing=colander.drop,) tgl_bahas_1 = colander.SchemaNode( colander.Date(), missing=colander.drop, title="Tanggal RKA") tgl_bahas_2 = colander.SchemaNode( colander.Date(), missing=colander.drop, title="Tanggal DPA") tgl_bahas_3 = colander.SchemaNode( colander.Date(), missing=colander.drop, title="Tanggal RPKA") tgl_bahas_4 = colander.SchemaNode( colander.Date(), missing=colander.drop, title="Tanggal DPPA") catatan_1 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Catatan") catatan_2 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Catatan") catatan_3 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Catatan") catatan_4 = colander.SchemaNode( colander.String(), missing=colander.drop, title="Catatan") pending = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, ) tahunke = colander.SchemaNode( colander.Integer(), missing=colander.drop, ) h0yl = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = "Anggaran 1" ) p0yl = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = "Perubahan 1",) r0yl = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = "Realisasi 1",) h1yl = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = "Anggaran 1",) p1yl = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = "Perubahan 2",) r1yl = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = "Realisasi 2",) h2yl = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = "Anggaran 3",) p2yl = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = "Perubahan 3",) r2yl = colander.SchemaNode( colander.Integer(), default = 0, missing=colander.drop, title = "Realisasi 3",) disabled = colander.SchemaNode( colander.Boolean(), default = 0, missing=colander.drop,) class EditSchema(AddSchema): id = colander.SchemaNode( colander.Integer(),) def get_form(request, class_form): schema = class_form(validator=form_validator) schema = schema.bind(sdana=SDANA) schema.request = request return Form(schema, buttons=('simpan','batal')) def save(values, row=None): if not row: row = KegiatanSub() row.from_dict(values) if not row.no_urut: row.no_urut = KegiatanSub.max_no_urut(row.tahun_id,row.unit_id,row.kegiatan_id)+1; DBSession.add(row) DBSession.flush() return row def save_request(values, request, row=None): if 'id' in request.matchdict: values['id'] = request.matchdict['id'] row = save(values, row) request.session.flash('Kegiatan sudah disimpan.') def route_list(request): return HTTPFound(location=request.route_url('ag-bl')) def session_failed(request, session_name): r = dict(form=request.session[session_name]) del request.session[session_name] return r @view_config(route_name='ag-bl-add', renderer='templates/ag-bl/add.pt', permission='add') def view_add(request): form = get_form(request, AddSchema) if request.POST: if 'simpan' in request.POST: controls = request.POST.items() controls_dicted = dict(controls) #return dict(form=form.render(appstruct=controls_dicted)) try: c = form.validate(controls) except ValidationFailure, e: return dict(form=form) #request.session[SESS_ADD_FAILED] = e.render() #return HTTPFound(location=request.route_url('ag-bl-add')) save_request(controls_dicted, request) return route_list(request) elif SESS_ADD_FAILED in request.session: del request.session[SESS_ADD_FAILED] #return session_failed(request, SESS_ADD_FAILED) return dict(form=form) ######## # Edit # ######## def query_id(request): return DBSession.query(KegiatanSub).filter(KegiatanSub.id==request.matchdict['id']) def id_not_found(request): msg = 'User ID %s not found.' % request.matchdict['id'] request.session.flash(msg, 'error') return route_list(request) @view_config(route_name='ag-bl-edit', renderer='templates/ag-bl/add.pt', permission='edit') def view_edit(request): row = query_id(request).first() if not row: return id_not_found(request) form = get_form(request, EditSchema) if request.POST: if 'simpan' in request.POST: controls = request.POST.items() try: c = form.validate(controls) except ValidationFailure, e: print e.render() return dict(form=form) #request.session[SESS_EDIT_FAILED] = e.render() #return HTTPFound(location=request.route_url('ag-bl-edit', # id=row.id)) save_request(dict(controls), request, row) return route_list(request) elif SESS_EDIT_FAILED in request.session: del request.session[SESS_EDIT_FAILED] return dict(form=form) values = row.to_dict() #dict(zip(row.keys(), row)) values['kegiatan_nm']=row.kegiatans.nama form.set_appstruct(values) return dict(form=form) ########## # Delete # ########## @view_config(route_name='ag-bl-delete', renderer='templates/ag-bl/delete.pt', permission='delete') def view_delete(request): q = query_id(request) row = q.first() if not row: return id_not_found(request) form = Form(colander.Schema(), buttons=('hapus','cancel')) values= {} if request.POST: if 'hapus' in request.POST: msg = '%s Kode %s No. %s %s sudah dihapus.' % (request.title, row.kode, row.no_urut, row.nama) DBSession.query(KegiatanSub).filter(KegiatanSub.id==request.matchdict['id']).delete() DBSession.flush() request.session.flash(msg) return route_list(request) return dict(row=row, form=form.render()) <file_sep>/README.md # osipkd-pdpt <file_sep>/osipkd/views/tu_skpd/ap_invoice_skpd_item.py import os import uuid from osipkd.tools import row2dict, xls_reader from datetime import datetime from sqlalchemy import not_, func, cast, BigInteger from pyramid.view import (view_config,) from pyramid.httpexceptions import ( HTTPFound, ) import colander from deform import (Form, widget, ValidationFailure, ) from osipkd.models import DBSession from osipkd.models.apbd_anggaran import Kegiatan, KegiatanSub, KegiatanItem from osipkd.models.pemda_model import Unit, Rekening from osipkd.models.apbd_tu import APInvoice, APInvoiceItem from datatables import ColumnDT, DataTables from osipkd.views.base_view import BaseViews SESS_ADD_FAILED = 'Tambah ap-invoice-skpd-item gagal' SESS_EDIT_FAILED = 'Edit ap-invoice-skpd-item gagal' class view_ap_invoice_skpd_item(BaseViews): ########## # Action # ########## @view_config(route_name='ap-invoice-skpd-item-act', renderer='json', permission='read') def view_act(self): ses = self.request.session req = self.request params = req.params url_dict = req.matchdict if url_dict['act']=='grid': pk_id = 'id' in params and params['id'] and int(params['id']) or 0 if url_dict['act']=='grid': # defining columns ap_invoice_id = url_dict['ap_invoice_id'].isdigit() and url_dict['ap_invoice_id'] or 0 columns = [] columns.append(ColumnDT('id')) columns.append(ColumnDT('no_urut')) columns.append(ColumnDT('nama')) columns.append(ColumnDT('kode_rek')) columns.append(ColumnDT('amount',filter=self._number_format)) columns.append(ColumnDT('ppn',filter=self._number_format)) columns.append(ColumnDT('pph',filter=self._number_format)) columns.append(ColumnDT('vol_1')) columns.append(ColumnDT('vol_2')) columns.append(ColumnDT('harga')) columns.append(ColumnDT('nama_kegiatan')) columns.append(ColumnDT('kegiatan_item_id')) columns.append(ColumnDT('nilai')) query = DBSession.query(APInvoiceItem.id, APInvoiceItem.no_urut, APInvoiceItem.nama, Rekening.kode.label('kode_rek'), APInvoiceItem.amount, APInvoiceItem.ppn, APInvoiceItem.pph, APInvoiceItem.vol_1, APInvoiceItem.vol_2, APInvoiceItem.harga, KegiatanItem.nama.label('nama_kegiatan'), APInvoiceItem.kegiatan_item_id, cast(KegiatanItem.hsat_4*KegiatanItem.vol_4_1*KegiatanItem.vol_4_2,BigInteger).label('nilai')).\ join(KegiatanItem).\ outerjoin(Rekening).\ filter(APInvoiceItem.ap_invoice_id==ap_invoice_id) rowTable = DataTables(req, APInvoiceItem, query, columns) return rowTable.output_result() ####### # Add # ####### @view_config(route_name='ap-invoice-skpd-item-add', renderer='json', permission='add') def view_add(request): req = request ses = req.session params = req.params url_dict = req.matchdict ap_invoice_id = 'ap_invoice_id' in url_dict and url_dict['ap_invoice_id'] or 0 controls = dict(request.POST.items()) ap_invoice_item_id = 'ap_invoice_item_id' in controls and controls['ap_invoice_item_id'] or 0 #Cek dulu ada penyusup gak dengan mengecek sessionnya ap_invoice = DBSession.query(APInvoice)\ .filter(APInvoice.unit_id==ses['unit_id'], APInvoice.id==ap_invoice_id).first() if not ap_invoice: return {"success": False, 'msg':'Invoice tidak ditemukan'} #Cek lagi ditakutkan skpd ada yang iseng inject script if ap_invoice_item_id: row = DBSession.query(APInvoiceItem)\ .join(APInvoice)\ .filter(APInvoiceItem.id==ap_invoice_item_id, APInvoice.unit_id==ses['unit_id'], APInvoiceItem.ap_invoice_id==ap_invoice_id).first() if not row: return {"success": False, 'msg':'Invoice tidak ditemukan'} else: row = APInvoiceItem() row.ap_invoice_id = ap_invoice_id row.kegiatan_item_id = controls['kegiatan_item_id'] if not controls['no_urut1'] or controls['no_urut1'].split()=='': controls['no_urut1'] = APInvoiceItem.max_no_urut(ap_invoice_id)+1 row.no_urut = controls['no_urut1'] row.nama = controls['nama'] row.vol_1 = controls['vol_1'].replace('.','') row.vol_2 = controls['vol_2'].replace('.','') row.harga = controls['harga'].replace('.','') row.ppn = controls['ppn'].replace('.','') row.pph = controls['pph'].replace('.','') row.amount = float(controls['vol_1'].replace('.',''))*float(controls['vol_2'].replace('.',''))*float(controls['harga'].replace('.','')) DBSession.add(row) DBSession.flush() amount = "%d" % APInvoice.get_nilai(row.ap_invoice_id) return {"success": True, 'id': row.id, "msg":'Success Tambah Item Invoice', 'jml_total':amount} ######## # Edit # ######## def route_list(request): return HTTPFound(location=request.route_url('ap-invoice-skpd')) def query_id(request): return DBSession.query(APInvoiceItem).filter(APInvoiceItem.id==request.matchdict['id'], APInvoiceItem.ap_invoice_id==request.matchdict['ap_invoice_id']) def id_not_found(request): msg = 'User ID %s not found.' % request.matchdict['id'] request.session.flash(msg, 'error') return route_list(request) @view_config(route_name='ap-invoice-skpd-item-edit', renderer='json', permission='edit') def view_edit(request): row = query_id(request).first() if not row: return id_not_found(request) form = get_form(request, EditSchema) if request.POST: if 'simpan' in request.POST: controls = request.POST.items() try: c = form.validate(controls) except ValidationFailure, e: return dict(form=form) save_request(dict(controls), request, row) return route_list(request) elif SESS_EDIT_FAILED in request.session: del request.session[SESS_EDIT_FAILED] return dict(form=form) values = row.to_dict() values['kegiatan_nm']=row.kegiatan_subs.nama values['kegiatan_kd']=row.kegiatan_subs.kode form.set_appstruct(values) return dict(form=form) ########## # Delete # ########## @view_config(route_name='ap-invoice-skpd-item-delete', renderer='json', permission='delete') def view_delete(request): q = query_id(request) row = q.first() if not row: return {'success':False, "msg":self.id_not_found()} msg = 'Data sudah dihapus' query_id(request).delete() DBSession.flush() amount = "%s" % APInvoice.get_nilai(row.ap_invoice_id) return {'success':True, "msg":msg, 'jml_total':amount}<file_sep>/osipkd/scripts/sync/sync_psppt.py #!/usr/bin/python from base import * from sync_osipkd import ARInvoice, ARPayment, Rekening, Unit, Sync from datetime import timedelta import sys import requests import json import hmac import hashlib import base64 import urllib from datetime import datetime def import_pbb(tanggal): utc_date = datetime.utcnow() tStamp = utc_date-datetime.strptime('1970-01-01 00:00:00','%Y-%m-%d %H:%M:%S'); value = "DISPENDAAKUNTANSI&%s" % int(tStamp.total_seconds()); key = "SISMIOP2015"; signature = hmac.new(key, msg=value, digestmod=hashlib.sha256).digest() encodedSignature = base64.encodestring(signature).replace('\n', '') data = {"commandCount":1, "command": [ { "cmd":"trx.tgl", "paramCount":1, "param": [tanggal.strftime('%Y-%m-%d')] } ] } print data jsondata=json.dumps(data, ensure_ascii=False) headers = {'f-client':'DISPENDAAKUNTANSI', 'f-signature':encodedSignature, 'f-key':int(tStamp.total_seconds())} #url = "http://192.168.56.5:6543/test" url = "http://192.168.168.5:8181/pbbws/sismiop/trxlive" rows = requests.post(url, data=jsondata,headers=headers) datas = json.loads(rows.text) # Loop through the result. tahun = tanggal.year rekening = Rekening.get_by_kode(pbb['rekening_kd']) denda = Rekening.get_by_kode(pbb['denda_kd']) if 'trx.tgl' not in datas: print datas return -1 i = 0 for row in datas['trx.tgl']: odata = ARPayment.get_by_ref_kode(tahun,''.join([row['nop'],'-',row['thn_pajak_sppt'],'-',str(row['pembayaran_sppt_ke'])])) if not odata: odata = ARPayment() odata.unit_id = Unit.get_by_kode(pbb['unit_kd']).id odata.kode = rekening.kode odata.disabled = 0 odata.created = tanggal odata.create_uid = 1 odata.nama = 'Setoran PBB WP' odata.tahun = tahun odata.amount = row['pokok'] odata.rekening_id = rekening.id odata.ref_kode = ''.join([row['nop'],'-',row['thn_pajak_sppt'],'-',str(row['pembayaran_sppt_ke'])]) odata.ref_nama = row['nama_wp'] odata.tanggal = row['tgl_pembayaran_sppt'] #Y-m-d odata.sumber_data = 'PBB' odata.sumber_id = 2 odata.posted = 0 osipkd_Session.add(odata) osipkd_Session.flush() if row['jumlah']-row['pokok']>0: odata = ARPayment.get_by_ref_kode(tahun,''.join([row['nop'],'-',row['thn_pajak_sppt'],'-', str(row['pembayaran_sppt_ke']),'D'])) if not odata: odata = ARPayment() odata.unit_id = Unit.get_by_kode(pbb['unit_kd']).id odata.kode = denda.kode odata.disabled = 0 odata.created = tanggal odata.create_uid = 1 odata.nama = 'Setoran Denda PBB WP' odata.tahun = tahun odata.amount = row['jumlah']-row['pokok'] odata.rekening_id = denda.id odata.ref_kode = ''.join([row['nop'],'-',row['thn_pajak_sppt'],'-',str(row['pembayaran_sppt_ke']),'D']) odata.ref_nama = row['nama_wp'] odata.tanggal = row['tgl_pembayaran_sppt'] #Y-m-d odata.sumber_data = 'PBB' odata.sumber_id = 2 odata.posted = 0 osipkd_Session.add(odata) osipkd_Session.flush() odata = ARInvoice.get_by_ref_kode(tahun,''.join([row['nop'],'-',row['thn_pajak_sppt'],'-', str(row['pembayaran_sppt_ke']),'D'])) """if not odata: odata = ARInvoice() odata.unit_id = Unit.get_by_kode(pbb['unit_kd']).id odata.kode = denda.kode odata.disabled = 0 odata.created = tanggal odata.create_uid = 1 odata.nama = 'Ketetapan Denda PBB WP' odata.tahun = tahun odata.amount = row['pokok'] odata.rekening_id = denda.id odata.ref_kode = ''.join([row['nop'],'-',row['thn_pajak_sppt'],'-',str(row['pembayaran_sppt_ke']),'D']) odata.ref_nama = row['nama_wp'] odata.tanggal = row['tgl_pembayaran_sppt'] #Y-m-d odata.sumber_data = 'PBB' odata.sumber_id = 2 odata.posted = 0 osipkd_Session.add(odata) osipkd_Session.flush()""" #odata.updated = #odata.update_uid = i += 1 if i/100 == i/100.0: print 'Commit ', i osipkd_Session.commit() osipkd_Session.commit() return True if __name__ == '__main__': print sys.argv osipkd_Base.metadata.create_all() if len(sys.argv)>1: tanggal = datetime.strptime(sys.argv[1],'%Y%m%d') import_pbb(tanggal) else: #tanggal = date.today() + timedelta(days=1) tanggal = datetime.combine(date.today(), datetime.min.time()) qdata = osipkd_Session.query(Sync).first() if not qdata: qdata = Sync() qdata.pbb = datetime.strptime('2015-01-01','%Y-%m-%d') if not qdata.pbb: qdata.pbb = datetime.strptime('2015-01-01','%Y-%m-%d') old = qdata.pbb print 'old', old while old < tanggal+timedelta(days=1): if import_pbb(old)==-1: print old print 'Koneksi Error' sys.exit() qdata.pbb = old old = old + timedelta(days=1) print tanggal, old, old + timedelta(days=-1) #qdata.pbb = old #+timedelta(days=-1) osipkd_Session.add(qdata) osipkd_Session.flush() osipkd_Session.commit() <file_sep>/osipkd/scripts/sync/sync_bphtb_tangkab.py #!/usr/bin/python from base import * from sync_osipkd import ARInvoice, ARPayment, Rekening, Unit, Sync,osipkd_eng from datetime import timedelta class BphtbBank(bphtb_Base, base): __tablename__ ='bphtb_bank' __table_args__ = {'extend_existing':True, 'schema' :'bphtb','autoload':True} @classmethod def query(cls): return bphtb_Session.query(cls) @classmethod def get_by_kode(cls,kode): return cls.query().filter_by(kode=kode).first() @classmethod def import_data(cls, tanggal=datetime.now()): #Tanggal = datetime.now() print tanggal tahun = tanggal.year rows = cls.query().filter_by(tanggal=datetime.date(tanggal)).all() if not rows: print 'data tidak ditemukan' rekening = Rekening.get_by_kode(bphtb['rekening_kd']) i = 0 for row in rows: odata = ARPayment.get_by_ref_kode(row.tahun,''.join([row.transno,'/',str(row.seq)])) if not odata: odata = ARPayment() odata.unit_id = Unit.get_by_kode(bphtb['unit_kd']) odata.kode = rekening.kode odata.disabled = 0 odata.created = tanggal odata.create_uid = 1 odata.nama = 'Setoran BPHTB WP' odata.tahun = row.tahun odata.amount = row.bayar odata.unit_id = Unit.get_by_kode(bphtb['unit_kd']).id odata.rekening_id = Rekening.get_by_kode(bphtb['rekening_kd']).id odata.ref_kode = '%s/%s' % (row.transno,row.seq) odata.ref_nama = row.wpnama odata.tanggal = row.tanggal odata.sumber_data = 'BPHTB' odata.sumber_id = 3 odata.posted = 0 osipkd_Session.add(odata) osipkd_Session.flush() #odata = ARInvoice.get_by_ref_kode(row.tahun,''.join([row.transno,'/',str(row.seq)])) #if not odata: # odata = ARInvoice() # odata.unit_id = Unit.get_by_kode(bphtb['unit_kd']) # odata.kode = rekening.kode # odata.disabled = 0 # odata.created = tanggal # odata.create_uid = 1 # odata.nama = 'Setoran BPHTB WP' # odata.tahun = row.tahun # odata.amount = row.bayar # odata.unit_id = Unit.get_by_kode(bphtb['unit_kd']).id # odata.rekening_id = Rekening.get_by_kode(bphtb['rekening_kd']).id # odata.ref_kode = '%s/%s' % (row.transno,row.seq) # odata.ref_nama = row.wpnama # odata.tanggal = row.tanggal # odata.sumber_data = 'BPHTB' # odata.sumber_id = 3 # odata.posted = 0 # osipkd_Session.add(odata) # osipkd_Session.flush() i += 1 if i/100 == i/100.0: print 'Commit ', i osipkd_Session.commit() osipkd_Session.commit() if __name__ == '__main__': print sys.argv osipkd_Base.metadata.create_all() if len(sys.argv)>1: tanggal = datetime.strptime(sys.argv[1],'%Y%m%d') BphtbBank.import_data(tanggal) #print tanggal.year else: tanggal = datetime.combine(date.today(), datetime.min.time()) qdata = osipkd_Session.query(Sync).first() if not qdata: qdata = Sync() qdata.bphtb = datetime.strptime('2015-01-01','%Y-%m-%d') if not qdata.bphtb: qdata.bphtb = datetime.strptime('2015-01-01','%Y-%m-%d') old = qdata.bphtb while old < tanggal+timedelta(days=1): BphtbBank.import_data(old) old = old +timedelta(days=1) qdata.bphtb = tanggal osipkd_Session.add(qdata) osipkd_Session.flush() osipkd_Session.commit() <file_sep>/osipkd/views/tu_skpd/report.py import os import unittest import os.path import uuid import urlparse from osipkd.tools import row2dict, xls_reader from datetime import datetime #from sqlalchemy import not_, func, case from sqlalchemy import * from sqlalchemy.sql.expression import literal_column from pyramid.view import (view_config,) from pyramid.httpexceptions import ( HTTPFound, ) import colander from deform import (Form, widget, ValidationFailure, ) from osipkd.models import DBSession from osipkd.models.apbd_anggaran import Kegiatan, KegiatanSub, KegiatanItem from datatables import ColumnDT, DataTables from osipkd.views.base_view import BaseViews from pyjasper import (JasperGenerator) from pyjasper import (JasperGeneratorWithSubreport) import xml.etree.ElementTree as ET from pyramid.path import AssetResolver from osipkd.models.base_model import * from osipkd.models.pemda_model import * from osipkd.models.apbd import * from osipkd.models.apbd_anggaran import * from osipkd.models.apbd_tu import * from datetime import datetime """import unittest import os.path from pyramid.httpexceptions import HTTPFound from pyramid.httpexceptions import HTTPForbidden from pyramid.httpexceptions import HTTPNotFound from pyramid.view import view_config from pyramid.security import remember from pyramid.security import forget from pyramid.security import has_permission from sqlalchemy import * from sqlalchemy import distinct from sqlalchemy.sql.functions import concat from sqlalchemy.exc import DBAPIError from osipkd.views.views import * from osipkd.models.model_base import * from osipkd.models.apbd_rka_models import * from osipkd.models.apbd_admin_models import (TahunModel, UserApbdModel,Unit, Urusan, RekeningModel, ProgramModel, KegiatanModel) from osipkd.models.apbd_tu_models import * from datetime import datetime import os from pyramid.renderers import render_to_response from anggaran import AnggaranBaseViews from pyjasper import (JasperGenerator) from pyjasper import (JasperGeneratorWithSubreport) import xml.etree.ElementTree as ET from pyramid.path import AssetResolver """ def get_rpath(filename): a = AssetResolver('osipkd') resolver = a.resolve(''.join(['reports/',filename])) return resolver.abspath() angka = {1:'satu',2:'dua',3:'tiga',4:'empat',5:'lima',6:'enam',7:'tujuh',\ 8:'delapan',9:'sembilan'} b = ' puluh ' c = ' ratus ' d = ' ribu ' e = ' juta ' f = ' milyar ' g = ' triliun ' def Terbilang(x): y = str(x) n = len(y) if n <= 3 : if n == 1 : if y == '0' : return '' else : return angka[int(y)] elif n == 2 : if y[0] == '1' : if y[1] == '1' : return 'sebelas' elif y[0] == '0': x = y[1] return Terbilang(x) elif y[1] == '0' : return 'sepuluh' else : return angka[int(y[1])] + ' belas' elif y[0] == '0' : x = y[1] return Terbilang(x) else : x = y[1] return angka[int(y[0])] + b + Terbilang(x) else : if y[0] == '1' : x = y[1:] return 'seratus ' + Terbilang(x) elif y[0] == '0' : x = y[1:] return Terbilang(x) else : x = y[1:] return angka[int(y[0])] + c + Terbilang(x) elif 3< n <=6 : p = y[-3:] q = y[:-3] if q == '1' : return 'seribu' + Terbilang(p) elif q == '000' : return Terbilang(p) else: return Terbilang(q) + d + Terbilang(p) elif 6 < n <= 9 : r = y[-6:] s = y[:-6] return Terbilang(s) + e + Terbilang(r) elif 9 < n <= 12 : t = y[-9:] u = y[:-9] return Terbilang(u) + f + Terbilang(t) else: v = y[-12:] w = y[:-12] return Terbilang(w) + g + Terbilang(v) class ViewTUSKPDLap(BaseViews): def __init__(self, context, request): global customer global logo BaseViews.__init__(self, context, request) self.app = 'tuskpd' #if 'app' in request.params and request.params['app'] == self.app and self.logged: row = DBSession.query(Tahun.status_apbd).filter(Tahun.tahun==self.tahun).first() self.session['status_apbd'] = row and row[0] or 0 self.status_apbd = 'status_apbd' in self.session and self.session['status_apbd'] or 0 #self.status_apbd_nm = status_apbd[str(self.status_apbd)] self.all_unit = 'all_unit' in self.session and self.session['all_unit'] or 0 self.unit_id = 'unit_id' in self.session and self.session['unit_id'] or 0 self.unit_kd = 'unit_kd' in self.session and self.session['unit_kd'] or "X.XX.XX" self.unit_nm = 'unit_nm' in self.session and self.session['unit_nm'] or "Pilih Unit" self.keg_id = 'keg_id' in self.session and self.session['keg_id'] or 0 self.datas['status_apbd'] = self.status_apbd #self.datas['status_apbd_nm'] = self.status_apbd_nm self.datas['all_unit'] = self.all_unit self.datas['unit_kd'] = self.unit_kd self.datas['unit_nm'] = self.unit_nm self.datas['unit_id'] = self.unit_id self.cust_nm = 'cust_nm' in self.session and self.session['cust_nm'] or '' customer = self.cust_nm ##o = "http://"+str(urlparse.urlparse(self.request.url).netloc) logo = self.request.static_url('osipkd:static/img/logo.png') print "KKKKKKKKKKKKKKKKKKKKKKKKKKKKK", logo # PENDAPATAN @view_config(route_name="ar-report-skpd", renderer="templates/report-skpd/pendapatan.pt", permission="read") def ar_report_skpd(self): params = self.request.params return dict(datas=self.datas,) @view_config(route_name="ar-report-skpd-act", renderer="json", permission="read") def ar_report_skpd_act(self): req = self.request params = req.params url_dict = req.matchdict tipe = 'tipe' in params and params['tipe'] and int(params['tipe']) or 0 mulai = 'mulai' in params and params['mulai'] or 0 selesai = 'selesai' in params and params['selesai'] or 0 ### LAPORAN INVOICE if url_dict['act']=='1' : query = DBSession.query(ARInvoice.tahun_id.label('tahun'), Unit.nama.label('unit_nm'), ARInvoice.kode, ARInvoice.tgl_terima, ARInvoice.tgl_validasi, ARInvoice.penyetor, ARInvoice.nama.label('uraian'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), ARInvoiceItem.nilai.label('jumlah' )).filter(ARInvoice.unit_id==Unit.id, ARInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, ARInvoiceItem.ar_invoice_id==ARInvoice.id, ARInvoice.unit_id==self.session['unit_id'], ARInvoice.tahun_id==self.session['tahun'], ARInvoice.tgl_terima.between(mulai,selesai) ).order_by(ARInvoice.tgl_terima) generator = b101r001Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response # INVOICE elif url_dict['act']=='arinvoice' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(ARInvoice.tahun_id.label('tahun'), Unit.nama.label('unit_nm'), Unit.alamat.label('unit_alamat'), ARInvoice.id.label('arinvoice_id'), ARInvoice.kode, ARInvoice.nama.label('arinvoice_nm'), ARInvoice.tgl_terima, ARInvoice.tgl_validasi, ARInvoice.bendahara_nm, ARInvoice.bendahara_nip, ARInvoice.penyetor, ARInvoice.alamat, KegiatanSub.nama.label('kegiatan_nm'), func.sum(ARInvoiceItem.nilai).label('nilai') ).filter(ARInvoice.unit_id==Unit.id, ARInvoice.kegiatan_sub_id==KegiatanSub.id, ARInvoiceItem.ar_invoice_id==ARInvoice.id, ARInvoice.unit_id==self.session['unit_id'], ARInvoice.tahun_id==self.session['tahun'], ARInvoice.id==pk_id ).group_by(ARInvoice.tahun_id, Unit.nama, Unit.alamat, ARInvoice.id, ARInvoice.kode, ARInvoice.nama, ARInvoice.tgl_terima, ARInvoice.tgl_validasi, ARInvoice.bendahara_nm, ARInvoice.bendahara_nip, ARInvoice.penyetor, ARInvoice.alamat, KegiatanSub.nama ) generator = b102r002Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### AR PAYMENT elif url_dict['act']=='ar-sts' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Sts ).filter(Sts.unit_id==Unit.id, Sts.unit_id==self.session['unit_id'], Sts.tahun_id==self.session['tahun'], Sts.id==pk_id ) generator = b102r003Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### LAPORAN STS if url_dict['act']=='2' : if tipe==0 : query = DBSession.query(Sts.tahun_id.label('tahun'), Unit.kode.label('unit_kd'),Unit.nama.label('unit_nm'), Sts.kode, Sts.tgl_sts, Sts.tgl_validasi, Sts.jenis, Sts.nama.label('uraian'), Sts.nominal, literal_column('0').label('tipe') ).filter(Sts.unit_id==Unit.id, Sts.unit_id==self.session['unit_id'], Sts.tahun_id==self.session['tahun'], Sts.tgl_sts.between(mulai,selesai) ).order_by(Sts.tgl_sts) elif tipe==1 : query = DBSession.query(Sts.tahun_id.label('tahun'), Unit.kode.label('unit_kd'),Unit.nama.label('unit_nm'), Sts.kode, Sts.tgl_sts, Sts.tgl_validasi, Sts.jenis, Sts.nama.label('uraian'), Sts.nominal, literal_column('1').label('tipe') ).filter(Sts.unit_id==Unit.id, Sts.jenis==1, Sts.unit_id==self.session['unit_id'], Sts.tahun_id==self.session['tahun'], Sts.tgl_sts.between(mulai,selesai) ).order_by(Sts.tgl_sts) elif tipe==2 : query = DBSession.query(Sts.tahun_id.label('tahun'), Unit.kode.label('unit_kd'),Unit.nama.label('unit_nm'), Sts.kode, Sts.tgl_sts, Sts.tgl_validasi, Sts.jenis, Sts.nama.label('uraian'), Sts.nominal, literal_column('2').label('tipe') ).filter(Sts.unit_id==Unit.id, Sts.jenis==2, Sts.unit_id==self.session['unit_id'], Sts.tahun_id==self.session['tahun'], Sts.tgl_sts.between(mulai,selesai) ).order_by(Sts.tgl_sts) elif tipe==3 : query = DBSession.query(Sts.tahun_id.label('tahun'), Unit.kode.label('unit_kd'),Unit.nama.label('unit_nm'), Sts.kode, Sts.tgl_sts, Sts.tgl_validasi, Sts.jenis, Sts.nama.label('uraian'), Sts.nominal, literal_column('3').label('tipe') ).filter(Sts.unit_id==Unit.id, Sts.jenis==3, Sts.unit_id==self.session['unit_id'], Sts.tahun_id==self.session['tahun'], Sts.tgl_sts.between(mulai,selesai) ).order_by(Sts.tgl_sts) generator = b101r002Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response # LAPORAN @view_config(route_name="ak-report-skpd", renderer="templates/report-skpd/ak-report-skpd.pt", permission="read") def ak_report_skpd(self): params = self.request.params return dict(datas=self.datas,) # BELANJA @view_config(route_name="ap-report-skpd", renderer="templates/report-skpd/belanja.pt", permission="read") def ap_report_skpd(self): params = self.request.params return dict(datas=self.datas,) @view_config(route_name="ap-report-skpd-act", renderer="json", permission="read") def ap_report_skpd_act(self): global bulan req = self.request params = req.params url_dict = req.matchdict tipe = 'tipe' in params and params['tipe'] and int(params['tipe']) or 0 mulai = 'mulai' in params and params['mulai'] or 0 selesai = 'selesai' in params and params['selesai'] or 0 ### LAPORAN AP INVOICE if url_dict['act']=='1' : if tipe==0 : query = DBSession.query(APInvoice.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), APInvoice.tanggal.label('tgl_invoice'), case([(APInvoice.jenis==1,"UP"),(APInvoice.jenis==2,"TU"),(APInvoice.jenis==3,"GU"), (APInvoice.jenis==4,"LS")], else_="").label('jenis'), APInvoice.kode.label('invoice_kd'), KegiatanSub.nama.label('kegiatan_nm'), Rekening.kode.label('rek_kd'),Rekening.nama.label('rek_nm'), func.sum(APInvoiceItem.amount).label('jumlah') ).filter(APInvoice.unit_id==Unit.id, APInvoice.kegiatan_sub_id==KegiatanSub.id, APInvoice.id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, APInvoice.unit_id==self.session['unit_id'], APInvoice.tahun_id==self.session['tahun'], APInvoice.tanggal.between(mulai,selesai) ).group_by(APInvoice.tahun_id, Unit.kode, Unit.nama, APInvoice.tanggal, case([(APInvoice.jenis==1,"UP"),(APInvoice.jenis==2,"TU"),(APInvoice.jenis==3,"GU"), (APInvoice.jenis==4,"LS")], else_=""), APInvoice.kode, KegiatanSub.nama, Rekening.kode,Rekening.nama ).order_by(APInvoice.tanggal).all() else: query = DBSession.query(APInvoice.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), APInvoice.tanggal.label('tgl_invoice'), case([(APInvoice.jenis==1,"UP"),(APInvoice.jenis==2,"TU"),(APInvoice.jenis==3,"GU"), (APInvoice.jenis==4,"LS")], else_="").label('jenis'), APInvoice.kode.label('invoice_kd'), KegiatanSub.nama.label('kegiatan_nm'), Rekening.kode.label('rek_kd'),Rekening.nama.label('rek_nm'), func.sum(APInvoiceItem.amount).label('jumlah') ).filter(APInvoice.unit_id==Unit.id, APInvoice.kegiatan_sub_id==KegiatanSub.id, APInvoice.id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, APInvoice.unit_id==self.session['unit_id'], APInvoice.tahun_id==self.session['tahun'], APInvoice.jenis==tipe, APInvoice.tanggal.between(mulai,selesai) ).group_by(APInvoice.tahun_id, Unit.kode, Unit.nama, APInvoice.tanggal, case([(APInvoice.jenis==1,"UP"),(APInvoice.jenis==2,"TU"),(APInvoice.jenis==3,"GU"), (APInvoice.jenis==4,"LS")], else_=""), APInvoice.kode, KegiatanSub.nama, Rekening.kode,Rekening.nama ).order_by(APInvoice.tanggal).all() generator = b104r000Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### AP INVOICE elif url_dict['act']=='apinvoice' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(APInvoice.tahun_id.label('tahun'), Unit.nama.label('unit_nm'), Unit.alamat, case([(APInvoice.jenis==1,"UP"),(APInvoice.jenis==2,"TU"),(APInvoice.jenis==3,"GU"), (APInvoice.jenis==4,"LS")], else_="").label('jenis'), APInvoice.id.label('invoice_id'), APInvoice.nama.label('invoice_nm'), APInvoice.tanggal.label('tgl_invoice'),APInvoice.kode, APInvoice.ap_nama, APInvoice.ap_rekening, APInvoice.ap_npwp, KegiatanSub.nama.label('kegiatan_nm'), func.sum(APInvoiceItem.amount).label('nilai') ).filter(APInvoice.unit_id==Unit.id, APInvoice.kegiatan_sub_id==KegiatanSub.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoice.unit_id==self.session['unit_id'], APInvoice.tahun_id==self.session['tahun'], APInvoice.id==pk_id ).group_by(APInvoice.tahun_id, Unit.nama, Unit.alamat, case([(APInvoice.jenis==1,"UP"),(APInvoice.jenis==2,"TU"),(APInvoice.jenis==3,"GU"), (APInvoice.jenis==4,"LS")], else_=""), APInvoice.id, APInvoice.nama, APInvoice.tanggal,APInvoice.kode, APInvoice.ap_nama, APInvoice.ap_rekening, APInvoice.ap_npwp, KegiatanSub.nama ) generator = b103r001Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### LAPORAN SPP 1 elif url_dict['act']=='21' : if tipe ==0 : query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),"LS")], else_="").label('jenis'), Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), Spp.tanggal.label('tgl_spp'), Spm.kode.label('spm_kd'), Spm.tanggal.label('tgl_spm'), Sp2d.kode.label('sp2d_kd'), Sp2d.tanggal.label('tgl_sp2d'), #Kegiatan.kode.label('keg_kd'), func.sum(APInvoiceItem.amount).label('nominal') ).filter(SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, #KegiatanItem.kegiatan_sub_id==KegiatanSub.id, #KegiatanSub.kegiatan_id==Kegiatan.id, Spp.unit_id==Unit.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.tanggal.between(mulai,selesai) ).outerjoin(Spm,Spm.ap_spp_id==Spp.id ).outerjoin(Sp2d,Sp2d.ap_spm_id==Spm.id ).group_by(Spp.tahun_id, Unit.kode, Unit.nama, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),"LS")], else_=""), Spp.kode, Spp.nama, Spp.tanggal, Spm.kode, Spm.tanggal, Sp2d.kode, Sp2d.tanggal #, Kegiatan.kode ).order_by(Spp.tanggal).all() else: query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),"LS")], else_="").label('jenis'), Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), Spp.tanggal.label('tgl_spp'), Spm.kode.label('spm_kd'), Spm.tanggal.label('tgl_spm'), Sp2d.kode.label('sp2d_kd'), Sp2d.tanggal.label('tgl_sp2d'), #Kegiatan.kode.label('keg_kd'), func.sum(APInvoiceItem.amount).label('nominal') ).filter(SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, #KegiatanItem.kegiatan_sub_id==KegiatanSub.id, #KegiatanSub.kegiatan_id==Kegiatan.id, Spp.unit_id==Unit.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.jenis==tipe, Spp.tanggal.between(mulai,selesai) ).outerjoin(Spm,Spm.ap_spp_id==Spp.id ).outerjoin(Sp2d,Sp2d.ap_spm_id==Spm.id ).group_by(Spp.tahun_id, Unit.kode, Unit.nama, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),"LS")], else_="").label('jenis'), Spp.kode, Spp.nama, Spp.tanggal, Spm.kode, Spm.tanggal, Sp2d.kode, Sp2d.tanggal #, Kegiatan.kode ).order_by(Spp.tanggal).all() generator = b104r1001Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### LAPORAN SPP 2 elif url_dict['act']=='22' : if tipe ==0 : query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Spp.tanggal.label('tgl_spp'), Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),"LS")], else_="").label('jenis'), func.sum(case([(Spp.jenis==1,APInvoiceItem.amount)], else_=0)).label('UP'), func.sum(case([(Spp.jenis==2,APInvoiceItem.amount)], else_=0)).label('TU'), func.sum(case([(Spp.jenis==3,APInvoiceItem.amount)], else_=0)).label('GU'), func.sum(case([(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),APInvoiceItem.amount)], else_=0)).label('LS_GJ'), func.sum(case([(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),APInvoiceItem.amount)], else_=0)).label('LS') ).filter(SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, #, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, #KegiatanSub.kegiatan_id==Kegiatan.id, Spp.unit_id==Unit.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.tanggal.between(mulai,selesai) ).group_by(Spp.tahun_id, Unit.kode, Unit.nama, Spp.tanggal, Spp.kode, Spp.nama, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),"LS")], else_=""), ).order_by(Spp.tanggal).all() else: query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Spp.tanggal.label('tgl_spp'), Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),"LS")], else_="").label('jenis'), func.sum(case([(Spp.jenis==1,APInvoiceItem.amount)], else_=0)).label('UP'), func.sum(case([(Spp.jenis==2,APInvoiceItem.amount)], else_=0)).label('TU'), func.sum(case([(Spp.jenis==3,APInvoiceItem.amount)], else_=0)).label('GU'), func.sum(case([(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),APInvoiceItem.amount)], else_=0)).label('LS_GJ'), func.sum(case([(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),APInvoiceItem.amount)], else_=0)).label('LS') ).filter(SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, #KegiatanItem.kegiatan_sub_id==KegiatanSub.id, #KegiatanSub.kegiatan_id==Kegiatan.id, Spp.unit_id==Unit.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.jenis==tipe, Spp.tanggal.between(mulai,selesai) ).group_by(Spp.tahun_id, Unit.kode, Unit.nama, Spp.tanggal, Spp.kode, Spp.nama, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),"LS")], else_=""), ).order_by(Spp.tanggal).all() generator = b104r1002Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Pengantar UP/TU/GU-LSB elif url_dict['act']=='spp11' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Urusan.nama.label('urusan_nm'), Unit.id.label('unit_id'),Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Tahun.no_perkdh, Tahun.tgl_perkdh, Spp.id.label('spp_id'),Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), Spp.tanggal.label('spp_tgl'), Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, func.substr(Rekening.kode,1,5).label('kode'), func.sum(APInvoiceItem.amount).label('nominal') ).filter(Spp.unit_id==Unit.id, Tahun.id==Spp.tahun_id, Urusan.id==Unit.urusan_id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, Rekening.id==KegiatanItem.rekening_id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by(Spp.tahun_id, Urusan.nama, Unit.id,Unit.kode, Unit.nama, Tahun.no_perkdh, Tahun.tgl_perkdh, Spp.id,Spp.kode, Spp.nama, Spp.tanggal, Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, func.substr(Rekening.kode,1,5)) generator = b103r021Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Pengantar LSG elif url_dict['act']=='spp21' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Urusan.nama.label('urusan_nm'), Unit.id.label('unit_id'),Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Tahun.no_perkdh, Tahun.tgl_perkdh, Spp.id.label('spp_id'),Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), Spp.tanggal.label('spp_tgl'), Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, func.substr(Rekening.kode,1,5).label('kode'), func.sum(APInvoiceItem.amount).label('nominal') ).filter(Spp.unit_id==Unit.id, Tahun.id==Spp.tahun_id, Urusan.id==Unit.urusan_id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, Rekening.id==KegiatanItem.rekening_id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by(Spp.tahun_id, Urusan.nama, Unit.id,Unit.kode, Unit.nama, Tahun.no_perkdh, Tahun.tgl_perkdh, Spp.id,Spp.kode, Spp.nama, Spp.tanggal, Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, func.substr(Rekening.kode,1,5)) generator = b103r022Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Pengantar LS elif url_dict['act']=='spp51' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Urusan.nama.label('urusan_nm'), Unit.id.label('unit_id'),Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Tahun.no_perkdh, Tahun.tgl_perkdh, Spp.id.label('spp_id'),Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), Spp.tanggal.label('spp_tgl'), Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, func.substr(Rekening.kode,1,5).label('kode'), func.sum(APInvoiceItem.amount).label('nominal') ).filter(Spp.unit_id==Unit.id, Tahun.id==Spp.tahun_id, Urusan.id==Unit.urusan_id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, Rekening.id==KegiatanItem.rekening_id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by(Spp.tahun_id, Urusan.nama, Unit.id,Unit.kode, Unit.nama, Tahun.no_perkdh, Tahun.tgl_perkdh, Spp.id,Spp.kode, Spp.nama, Spp.tanggal, Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, func.substr(Rekening.kode,1,5)) generator = b103r025Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Ringkasan UP/TU elif url_dict['act']=='spp12' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Urusan.nama.label('urusan_nm'), Unit.id.label('unit_id'),Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Tahun.no_perkdh, Tahun.tgl_perkdh, Spp.id.label('spp_id'),Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), Spp.tanggal.label('spp_tgl'), Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, func.substr(Rekening.kode,1,5).label('kode'), func.sum(APInvoiceItem.amount).label('nominal') ).filter(Spp.unit_id==Unit.id, Tahun.id==Spp.tahun_id, Urusan.id==Unit.urusan_id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, Rekening.id==KegiatanItem.rekening_id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by(Spp.tahun_id, Urusan.nama, Unit.id,Unit.kode, Unit.nama, Tahun.no_perkdh, Tahun.tgl_perkdh, Spp.id,Spp.kode, Spp.nama, Spp.tanggal, Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, func.substr(Rekening.kode,1,5)) generator = b103r031Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Ringkasan // LS.G elif url_dict['act']=='spp32' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Urusan.nama.label('urusan_nm'), Unit.id.label('unit_id'),Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Tahun.no_perkdh, Tahun.tgl_perkdh, Tahun.tanggal_2, Tahun.tanggal_4, Spp.id.label('spp_id'),Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), Spp.tanggal.label('spp_tgl'), Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, func.substr(Rekening.kode,1,5).label('kode'), func.sum(APInvoiceItem.amount).label('nominal'), func.sum(KegiatanItem.vol_4_1*KegiatanItem.vol_4_2*KegiatanItem.hsat_4).label('anggaran') ).filter(Spp.unit_id==Unit.id, Tahun.id==Spp.tahun_id, Urusan.id==Unit.urusan_id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, Rekening.id==KegiatanItem.rekening_id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by(Spp.tahun_id, Urusan.nama, Unit.id,Unit.kode, Unit.nama, Tahun.no_perkdh, Tahun.tgl_perkdh, Tahun.tanggal_2, Tahun.tanggal_4, Spp.id,Spp.kode, Spp.nama, Spp.tanggal, Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, func.substr(Rekening.kode,1,5)) generator = b103r033Generator()#b103r0021_2Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Ringkasan GU / LSB elif url_dict['act']=='spp42' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 subq = DBSession.query(Spd.unit_id, Spd.tahun_id, Spd.tanggal, SpdItem.nominal ).filter(Spd.id==SpdItem.ap_spd_id).subquery() query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.id.label('unit_id'),Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Tahun.tanggal_2, Tahun.tanggal_4, Spp.id.label('spp_id'),Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), Spp.tanggal.label('spp_tgl'), Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.nominal, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, APInvoice.ap_waktu, APInvoice.ap_uraian, APInvoice.ap_pemilik, APInvoice.ap_alamat, APInvoice.ap_bentuk, APInvoice.ap_kontrak, Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), KegiatanSub.no_urut, Program.nama.label('prg_nm'), func.sum(KegiatanItem.vol_4_1*KegiatanItem.vol_4_2*KegiatanItem.hsat_4).label('anggaran'), func.sum(subq.c.nominal).label('tot_spd') ).filter(Spp.unit_id==Unit.id, Tahun.id==Spp.tahun_id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoice.id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, Kegiatan.id==KegiatanSub.kegiatan_id, Program.id==Kegiatan.program_id, subq.c.unit_id==Unit.id, subq.c.tahun_id==Spp.tahun_id, subq.c.tanggal<=Spp.tanggal, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by( Spp.tahun_id, Unit.id,Unit.kode, Unit.nama, Tahun.tanggal_2, Tahun.tanggal_4, Spp.id,Spp.kode, Spp.nama, Spp.tanggal, Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.nominal, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, APInvoice.ap_waktu, APInvoice.ap_uraian, APInvoice.ap_pemilik, APInvoice.ap_alamat, APInvoice.ap_bentuk, APInvoice.ap_kontrak, Kegiatan.kode, Kegiatan.nama, KegiatanSub.no_urut, Program.nama ) generator = b103r034Generator()#b103r0021_1Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Ringkasan // LS elif url_dict['act']=='spp52' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 subq = DBSession.query(Spd.unit_id, Spd.tahun_id, Spd.tanggal, SpdItem.nominal ).filter(Spd.id==SpdItem.ap_spd_id).subquery() query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.id.label('unit_id'),Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Tahun.tanggal_2, Tahun.tanggal_4, Spp.id.label('spp_id'),Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), Spp.tanggal.label('spp_tgl'), Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.nominal, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, APInvoice.ap_waktu, APInvoice.ap_uraian, APInvoice.ap_pemilik, APInvoice.ap_alamat, APInvoice.ap_bentuk, APInvoice.ap_kontrak, Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), KegiatanSub.no_urut, Program.nama.label('prg_nm'), func.sum(KegiatanItem.vol_4_1*KegiatanItem.vol_4_2*KegiatanItem.hsat_4).label('anggaran'), func.sum(subq.c.nominal).label('tot_spd') ).filter(Spp.unit_id==Unit.id, Tahun.id==Spp.tahun_id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoice.id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, Kegiatan.id==KegiatanSub.kegiatan_id, Program.id==Kegiatan.program_id, subq.c.unit_id==Unit.id, subq.c.tahun_id==Spp.tahun_id, subq.c.tanggal<=Spp.tanggal, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by( Spp.tahun_id, Unit.id,Unit.kode, Unit.nama, Tahun.tanggal_2, Tahun.tanggal_4, Spp.id,Spp.kode, Spp.nama, Spp.tanggal, Spp.ttd_nip, Spp.ttd_nama, Spp.ttd_jab, Spp.jenis, Spp.pptk_nip, Spp.pptk_nama, Spp.nominal, Spp.ap_nama, Spp.ap_bank, Spp.ap_rekening, APInvoice.ap_waktu, APInvoice.ap_uraian, APInvoice.ap_pemilik, APInvoice.ap_alamat, APInvoice.ap_bentuk, APInvoice.ap_kontrak, Kegiatan.kode, Kegiatan.nama, KegiatanSub.no_urut, Program.nama ) generator = b103r035Generator()#b103r0021_2Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Rincian // UP elif url_dict['act']=='spp13' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Urusan.kode.label('urusan_kd'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), Program.kode.label('prg_kd'),Program.nama.label('prg_nm'), Spp.kode.label('spp_kd'), Spp.nama, Spp.tanggal, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"), (Spp.jenis==4,"LS")], else_="").label('jenis'), Spp.unit_id.label('unit_id'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), Spp.ttd_nip, Spp.ttd_nama, func.sum(APInvoiceItem.amount).label('amount') ).filter(Spp.unit_id==Unit.id, Unit.urusan_id==Urusan.id, Spp.id==SppItem.ap_spp_id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.program_id== Program.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by(Spp.tahun_id, Unit.kode, Urusan.kode, Unit.nama, Kegiatan.kode, Kegiatan.nama, Program.nama, Program.kode, Spp.ttd_nip, Spp.ttd_nama, Spp.kode, Spp.nama, Spp.tanggal, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"), (Spp.jenis==4,"LS")], else_=""), Spp.unit_id, Rekening.kode, Rekening.nama ).order_by(Rekening.kode) generator = b103r041Generator()#b103r0022Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Rincian // TU elif url_dict['act']=='spp23' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Urusan.kode.label('urusan_kd'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), Program.kode.label('prg_kd'),Program.nama.label('prg_nm'), Spp.kode.label('spp_kd'), Spp.nama, Spp.tanggal, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"), (Spp.jenis==4,"LS")], else_="").label('jenis'), Spp.unit_id.label('unit_id'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), Spp.ttd_nip, Spp.ttd_nama, Spp.pptk_nip, Spp.pptk_nama, func.sum(APInvoiceItem.amount).label('amount') ).filter(Spp.unit_id==Unit.id, Unit.urusan_id==Urusan.id, Spp.id==SppItem.ap_spp_id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.program_id== Program.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by(Spp.tahun_id, Unit.kode, Urusan.kode, Unit.nama, Kegiatan.kode, Kegiatan.nama, Program.nama, Program.kode, Spp.ttd_nip, Spp.ttd_nama, Spp.pptk_nip, Spp.pptk_nama, Spp.kode, Spp.nama, Spp.tanggal, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"), (Spp.jenis==4,"LS")], else_=""), Spp.unit_id, Rekening.kode, Rekening.nama ).order_by(Rekening.kode) generator = b103r042Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Rincian // LS.G elif url_dict['act']=='spp33' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Urusan.kode.label('urusan_kd'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), Program.kode.label('prg_kd'),Program.nama.label('prg_nm'), Spp.kode.label('spp_kd'), Spp.nama, Spp.tanggal, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"), (Spp.jenis==4,"LS")], else_="").label('jenis'), Spp.unit_id.label('unit_id'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), Spp.ttd_nip, Spp.ttd_nama, Spp.pptk_nip, Spp.pptk_nama, func.sum(APInvoiceItem.amount).label('amount') ).filter(Spp.unit_id==Unit.id, Unit.urusan_id==Urusan.id, Spp.id==SppItem.ap_spp_id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.program_id== Program.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by(Spp.tahun_id, Unit.kode, Urusan.kode, Unit.nama, Kegiatan.kode, Kegiatan.nama, Program.nama, Program.kode, Spp.ttd_nip, Spp.ttd_nama, Spp.pptk_nip, Spp.pptk_nama, Spp.kode, Spp.nama, Spp.tanggal, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"), (Spp.jenis==4,"LS")], else_=""), Spp.unit_id, Rekening.kode, Rekening.nama ).order_by(Rekening.kode) generator = b103r043Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Rincian // GU/LSB elif url_dict['act']=='spp43' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Urusan.kode.label('urusan_kd'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), Program.kode.label('prg_kd'),Program.nama.label('prg_nm'), Spp.kode.label('spp_kd'), Spp.nama, Spp.tanggal, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"), (Spp.jenis==4,"LS")], else_="").label('jenis'), Spp.unit_id.label('unit_id'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), Spp.ttd_nip, Spp.ttd_nama, Spp.pptk_nip, Spp.pptk_nama, func.sum(APInvoiceItem.amount).label('amount') ).filter(Spp.unit_id==Unit.id, Unit.urusan_id==Urusan.id, Spp.id==SppItem.ap_spp_id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.program_id== Program.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by(Spp.tahun_id, Unit.kode, Urusan.kode, Unit.nama, Kegiatan.kode, Kegiatan.nama, Program.nama, Program.kode, Spp.ttd_nip, Spp.ttd_nama, Spp.pptk_nip, Spp.pptk_nama, Spp.kode, Spp.nama, Spp.tanggal, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"), (Spp.jenis==4,"LS")], else_=""), Spp.unit_id, Rekening.kode, Rekening.nama ).order_by(Rekening.kode) generator = b103r044Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPP Rincian // LS.G elif url_dict['act']=='spp53' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Urusan.kode.label('urusan_kd'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), Program.kode.label('prg_kd'),Program.nama.label('prg_nm'), Spp.kode.label('spp_kd'), Spp.nama, Spp.tanggal, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"), (Spp.jenis==4,"LS")], else_="").label('jenis'), Spp.unit_id.label('unit_id'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), Spp.ttd_nip, Spp.ttd_nama, Spp.pptk_nip, Spp.pptk_nama, func.sum(APInvoiceItem.amount).label('amount') ).filter(Spp.unit_id==Unit.id, Unit.urusan_id==Urusan.id, Spp.id==SppItem.ap_spp_id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.program_id== Program.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.id==pk_id ).group_by(Spp.tahun_id, Unit.kode, Urusan.kode, Unit.nama, Kegiatan.kode, Kegiatan.nama, Program.nama, Program.kode, Spp.ttd_nip, Spp.ttd_nama, Spp.pptk_nip, Spp.pptk_nama, Spp.kode, Spp.nama, Spp.tanggal, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"), (Spp.jenis==4,"LS")], else_=""), Spp.unit_id, Rekening.kode, Rekening.nama ).order_by(Rekening.kode) generator = b103r045Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### LAPORAN SPM 1 elif url_dict['act']=='31' : if tipe ==0 : query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'),Unit.nama.label('unit_nm'), case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=="5.1.1"),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!="5.1.1"),"LS")], else_="").label('jenis'), Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), Spp.tanggal.label('tgl_spp'), Spm.kode.label('spm_kd'), Spm.tanggal.label('tgl_spm'), Sp2d.kode.label('sp2d_kd'), Sp2d.tanggal.label('tgl_sp2d'), func.sum(APInvoiceItem.amount).label('nominal') ).filter(SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, Spp.unit_id==Unit.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spm.tanggal.between(mulai,selesai) ).outerjoin(Spm,Spm.ap_spp_id==Spp.id ).outerjoin(Sp2d,Sp2d.ap_spm_id==Spm.id ).group_by(Spp.tahun_id, Unit.kode, Unit.nama, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=="5.1.1"),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!="5.1.1"),"LS")], else_=""), Spp.kode, Spp.nama, Spp.tanggal, Spm.kode, Spm.tanggal, Sp2d.kode, Sp2d.tanggal ).order_by(Spp.tanggal).all() else: query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'),Unit.nama.label('unit_nm'), case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=="5.1.1"),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!="5.1.1"),"LS")], else_="").label('jenis'), Spp.kode.label('spp_kd'), Spp.nama.label('spp_nm'), Spp.tanggal.label('tgl_spp'), Spm.kode.label('spm_kd'), Spm.tanggal.label('tgl_spm'), Sp2d.kode.label('sp2d_kd'), Sp2d.tanggal.label('tgl_sp2d'), func.sum(APInvoiceItem.amount).label('nominal') ).filter(SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, Spp.unit_id==Unit.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.jenis==tipe, Spm.tanggal.between(mulai,selesai) ).outerjoin(Spm,Spm.ap_spp_id==Spp.id ).outerjoin(Sp2d,Sp2d.ap_spm_id==Spm.id ).group_by(Spp.tahun_id, Unit.kode, Unit.nama, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=="5.1.1"),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!="5.1.1"),"LS")], else_=""), Spp.kode, Spp.nama, Spp.tanggal, Spm.kode, Spm.tanggal, Sp2d.kode, Sp2d.tanggal, ).order_by(Spp.tanggal).all() generator = b104r2001Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### LAPORAN SPM 2 elif url_dict['act']=='32' : if tipe ==0 : query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Spm.tanggal.label('tgl_spp'), Spm.kode.label('spp_kd'), Spm.nama.label('spp_nm'), case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=="5.1.1"),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!="5.1.1"),"LS")], else_="").label('jenis'), func.sum(case([(Spp.jenis==1,APInvoiceItem.amount)], else_=0)).label('UP'), func.sum(case([(Spp.jenis==2,APInvoiceItem.amount)], else_=0)).label('TU'), func.sum(case([(Spp.jenis==3,APInvoiceItem.amount)], else_=0)).label('GU'), func.sum(case([(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),APInvoiceItem.amount)], else_=0)).label('LS_GJ'), func.sum(case([(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),APInvoiceItem.amount)], else_=0)).label('LS') ).filter(SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, Spp.unit_id==Unit.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spm.tanggal.between(mulai,selesai) ).outerjoin(Spm,Spm.ap_spp_id==Spp.id ).outerjoin(Sp2d,Sp2d.ap_spm_id==Spm.id ).group_by(Spp.tahun_id, Unit.kode, Unit.nama, Spm.tanggal, Spm.kode, Spm.nama, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=="5.1.1"),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!="5.1.1"),"LS")], else_=""), ).order_by(Spm.tanggal).all() else: query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Spm.tanggal.label('tgl_spp'), Spm.kode.label('spp_kd'), Spm.nama.label('spp_nm'), case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=="5.1.1"),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!="5.1.1"),"LS")], else_="").label('jenis'), func.sum(case([(Spp.jenis==1,APInvoiceItem.amount)], else_=0)).label('UP'), func.sum(case([(Spp.jenis==2,APInvoiceItem.amount)], else_=0)).label('GU'), func.sum(case([(Spp.jenis==3,APInvoiceItem.amount)], else_=0)).label('TU'), func.sum(case([(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),APInvoiceItem.amount)], else_=0)).label('LS_GJ'), func.sum(case([(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!='5.1.1'),APInvoiceItem.amount)], else_=0)).label('LS') ).outerjoin(Spm,Spm.ap_spp_id==Spp.id ).outerjoin(Sp2d,Sp2d.ap_spm_id==Spm.id ).filter(SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, Spp.unit_id==Unit.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spp.jenis==tipe, Spm.tanggal.between(mulai,selesai) ).group_by(Spp.tahun_id, Unit.kode, Unit.nama, Spm.tanggal, Spm.kode, Spm.nama, case([(Spp.jenis==1,"UP"),(Spp.jenis==2,"TU"),(Spp.jenis==3,"GU"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=="5.1.1"),"LS-GJ"),(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)!="5.1.1"),"LS")], else_=""), ).order_by(Spm.tanggal).all() generator = b104r2002Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // Pengantar elif url_dict['act']=='spm01' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Unit.alamat, Spm.id.label('spm_id'),Spm.kode.label('spm_kd'), Spm.nama.label('spm_nm'), Spm.tanggal.label('spm_tgl'), Spm.ttd_nip, Spm.ttd_nama, Spp.id.label('spp_id'),Spp.jenis.label('jenis'), func.substr(Rekening.kode,1,5).label('kode'), Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), Program.kode.label('prg_kd'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), APInvoiceItem.amount ).filter(Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.program_id==Program.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spm.id==pk_id ) generator = b103r003_1Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // Pernyataan elif url_dict['act']=='spm02' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Unit.alamat, Spm.id.label('spm_id'),Spm.kode.label('spm_kd'), Spm.nama.label('spm_nm'), Spm.tanggal.label('spm_tgl'), Spm.ttd_nip, Spm.ttd_nama, Spp.id.label('spp_id'),Spp.jenis.label('jenis'), Spp.nominal.label('amount') ).filter(Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spm.id==pk_id ) generator = b103r003_2Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // Pernyataan TU elif url_dict['act']=='spm12' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Unit.alamat, Spm.id.label('spm_id'),Spm.kode.label('spm_kd'), Spm.nama.label('spm_nm'), Spm.tanggal.label('spm_tgl'), Spm.ttd_nip, Spm.ttd_nama, Spp.jenis.label('jenis'), Spp.nominal, Spp.nama.label('spp_nm'), Kegiatan.kode, ).filter(Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoice.kegiatan_sub_id==KegiatanSub.id, Kegiatan.id==KegiatanSub.kegiatan_id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spm.id==pk_id ) generator = b103r003_12Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // Format SPM elif url_dict['act']=='spm03' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Spm.id.label('spm_id'), Spm.kode.label('spm_kd'), Spm.nama.label('spm_nm'), Spm.tanggal.label('spm_tgl'), Spm.ttd_nip, Spm.ttd_nama, Spp.id.label('spp_id'), Spp.kode.label('spp_kd'), Spp.jenis.label('jenis'), Spp.tanggal.label('spp_tgl'), Spp.ap_bank, Spp.ap_rekening, Spp.ap_npwp, Spp.ap_nama, Spp.nama.label('spp_nm'), Spd.kode.label('spd_kd'), Spd.tanggal.label('spd_tgl'), Kegiatan.kode.label('keg_kd'), APInvoice.id.label('ap_invoice_id'), Program.kode.label('program_kd'),Spp.nominal #).join(Spm).join(Unit).join(Spd).join(SppItem).join(APInvoice).join(KegiatanSub).join(Kegiatan).join(Program ).filter( Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, Spd.id==Spp.ap_spd_id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoice.kegiatan_sub_id==KegiatanSub.id, Kegiatan.id==KegiatanSub.kegiatan_id, Program.id==Kegiatan.program_id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spm.id==pk_id ) generator = b103r003Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // Checklist elif url_dict['act']=='spm11' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Spp.tahun_id.label('tahun'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Unit.alamat, Spm.kode.label('spm_kd'), Spm.nama.label('spm_nm'), Spm.tanggal.label('spm_tgl'), Spm.ttd_nip, Spm.ttd_nama, Spp.jenis.label('jenis'), Kegiatan.kode, KegiatanSub.nama ).filter(Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoice.kegiatan_sub_id==KegiatanSub.id, Kegiatan.id==KegiatanSub.kegiatan_id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'], Spm.id==pk_id ) generator = b103r003_11Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // SPTJM LS Pihak Ketiga 1 elif url_dict['act']=='spm04' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Unit.alamat, Spm.kode, Spm.tanggal, Spm.ttd_nip, Spm.ttd_nama, APInvoice.amount, Spp.tahun_id, Spp.jenis, APInvoice.ap_bap_no, APInvoice.ap_bap_tgl, APInvoice.ap_nilai, APInvoice.ap_kontrak, APInvoice.ap_tgl_kontrak, APInvoice.ap_nama, APInvoice.ap_pemilik, ).filter(Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, Spm.id==pk_id ) generator = b103r003_4Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // SPTJM LS Pihak Ketiga 2 elif url_dict['act']=='spm05' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Unit.alamat, Spm.kode, Spm.tanggal, Spm.ttd_nip, Spm.ttd_nama, APInvoice.amount, Spp.tahun_id, Spp.jenis, APInvoice.ap_bap_no, APInvoice.ap_bap_tgl, APInvoice.ap_nilai, APInvoice.ap_kontrak, APInvoice.ap_tgl_kontrak, APInvoice.ap_nama, APInvoice.ap_pemilik, APInvoice.ap_kwitansi_nilai, APInvoice.ap_kwitansi_no, APInvoice.ap_kwitansi_tgl ).filter(Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, Spm.id==pk_id ) generator = b103r003_5Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // SPTJM LS elif url_dict['act']=='spm06' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Unit.alamat, Spm.kode, Spm.tanggal, Spm.ttd_nip, Spm.ttd_nama, Spp.tahun_id, Spp.jenis ).filter(Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, Spm.id==pk_id ) generator = b103r003_6Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // SPTJM GU elif url_dict['act']=='spm07' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Unit.alamat, Spm.kode, Spm.tanggal, Spm.ttd_nip, Spm.ttd_nama, Spp.tahun_id, Spp.jenis ).filter(Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, Spm.id==pk_id ) generator = b103r003_7Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // SPTJB UP - GU elif url_dict['act']=='spm08' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Unit.alamat, Program.kode.label('program_kd'), Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), APInvoiceItem.amount, APInvoiceItem.pph, APInvoiceItem.ppn, APInvoice.ap_kwitansi_no, APInvoice.ap_kwitansi_tgl, APInvoice.ap_nama, Spm.tanggal, APInvoice.no_bku, APInvoice.tgl_bku, Spp.tahun_id, Spp.jenis, Spm.kode, Spm.ttd_nip, Spm.ttd_nama ).filter(Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.program_id==Program.id, Spm.id==pk_id ) generator = b103r003_8Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // SPTJB LS elif url_dict['act']=='spm09' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Unit.alamat, Program.kode.label('program_kd'), Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), APInvoiceItem.amount, APInvoiceItem.pph, APInvoiceItem.ppn, APInvoice.ap_kwitansi_no, APInvoice.ap_kwitansi_tgl, APInvoice.ap_nama, Spm.tanggal, Spp.tahun_id, Spp.jenis, Spm.kode, Spm.ttd_nip, Spm.ttd_nama ).filter(Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.program_id==Program.id, Spm.id==pk_id ) generator = b103r003_9Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPM // SPTJB LS PIHAK KETIGA elif url_dict['act']=='spm10' : pk_id = 'id' in params and params['id'] and int(params['id']) or 0 query = DBSession.query(Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Unit.alamat, Program.kode.label('program_kd'), Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), APInvoiceItem.amount, APInvoiceItem.pph, APInvoiceItem.ppn, APInvoice.ap_kwitansi_no, APInvoice.ap_kwitansi_tgl, APInvoice.ap_nama, Spm.tanggal, Spp.tahun_id, Spp.jenis, Spm.kode, Spm.ttd_nip, Spm.ttd_nama ).filter(Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, SppItem.ap_spp_id==Spp.id, SppItem.ap_invoice_id==APInvoice.id, APInvoiceItem.ap_invoice_id==APInvoice.id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.program_id==Program.id, Spm.id==pk_id ) generator = b103r003_10Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPJ Fungsional elif url_dict['act']=='4' : bulan = 'bulan' in params and params['bulan'] and int(params['bulan']) or 0 subq = DBSession.query(Urusan.kode.label('urusan_kd'), Unit.id.label('unit_id'),Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Program.kode.label('program_kd'), Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), Spp.tahun_id.label('tahun'), Sp2d.tanggal.label('tanggal'), Spp.jenis.label('jenis'), (KegiatanItem.vol_4_1*KegiatanItem.vol_4_2*KegiatanItem.hsat_4).label('anggaran'), APInvoiceItem.amount.label('nilai') ).filter(Sp2d.ap_spm_id==Spm.id, Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, Spp.id==SppItem.ap_spp_id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, Unit.urusan_id==Urusan.id, KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.program_id==Program.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'] ).subquery() query = DBSession.query(subq.c.urusan_kd, subq.c.unit_id, subq.c.unit_kd, subq.c.unit_nm, subq.c.program_kd, subq.c.keg_kd, subq.c.keg_nm, subq.c.rek_kd, subq.c.rek_nm, subq.c.tahun, func.sum(subq.c.anggaran).label('anggaran'), func.sum(case([(and_(extract('month',subq.c.tanggal)<bulan, subq.c.jenis==4,func.substr(subq.c.rek_kd,1,5)=='5.2.1'),subq.c.nilai)], else_=0)).label('LSG_lalu'), func.sum(case([(and_(extract('month',subq.c.tanggal)==bulan, subq.c.jenis==4,func.substr(subq.c.rek_kd,1,5)=='5.2.1'),subq.c.nilai)], else_=0)).label('LSG_kini'), func.sum(case([(and_(extract('month',subq.c.tanggal)<bulan, subq.c.jenis==4,not_(func.substr(subq.c.rek_kd,1,5)=='5.2.1')),subq.c.nilai)], else_=0)).label('LS_lalu'), func.sum(case([(and_(extract('month',subq.c.tanggal)==bulan, subq.c.jenis==4,not_(func.substr(subq.c.rek_kd,1,5)=='5.2.1')),subq.c.nilai)], else_=0)).label('LS_kini'), func.sum(case([(and_(extract('month',subq.c.tanggal)<bulan, not_(subq.c.jenis==4)),subq.c.nilai)], else_=0)).label('Lain_lalu'), func.sum(case([(and_(extract('month',subq.c.tanggal)==bulan, not_(subq.c.jenis==4)),subq.c.nilai)], else_=0)).label('Lain_kini'), ).group_by(subq.c.urusan_kd, subq.c.unit_id, subq.c.unit_kd, subq.c.unit_nm, subq.c.program_kd, subq.c.keg_kd, subq.c.keg_nm, subq.c.rek_kd, subq.c.rek_nm, subq.c.tahun ).order_by(subq.c.keg_kd ) generator = b104r300Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response ### SPJ Administratif elif url_dict['act']=='5' : bulan = 'bulan' in params and params['bulan'] and int(params['bulan']) or 0 subq = DBSession.query(Urusan.kode.label('urusan_kd'), Unit.id.label('unit_id'), Unit.kode.label('unit_kd'), Unit.nama.label('unit_nm'), Program.kode.label('program_kd'), Kegiatan.kode.label('keg_kd'), Kegiatan.nama.label('keg_nm'), Rekening.kode.label('rek_kd'), Rekening.nama.label('rek_nm'), Spp.tahun_id.label('tahun'), Sp2d.tanggal.label('tanggal'), Spp.jenis.label('jenis'), (KegiatanItem.vol_4_1*KegiatanItem.vol_4_2*KegiatanItem.hsat_4).label('anggaran'), APInvoiceItem.amount.label('nilai') ).filter(Sp2d.ap_spm_id==Spm.id, Spm.ap_spp_id==Spp.id, Spp.unit_id==Unit.id, Spp.id==SppItem.ap_spp_id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, KegiatanItem.kegiatan_sub_id==KegiatanSub.id, Unit.urusan_id==Urusan.id, KegiatanSub.kegiatan_id==Kegiatan.id, Kegiatan.program_id==Program.id, Spp.unit_id==self.session['unit_id'], Spp.tahun_id==self.session['tahun'] ).subquery() query = DBSession.query(subq.c.urusan_kd, subq.c.unit_id, subq.c.unit_kd, subq.c.unit_nm, subq.c.program_kd, subq.c.keg_kd, subq.c.keg_nm, subq.c.rek_kd, subq.c.rek_nm, subq.c.tahun, func.sum(subq.c.anggaran).label('anggaran'), func.sum(case([(and_(extract('month',subq.c.tanggal)<bulan, subq.c.jenis==4,func.substr(subq.c.rek_kd,1,5)=='5.2.1'),subq.c.nilai)], else_=0)).label('LSG_lalu'), func.sum(case([(and_(extract('month',subq.c.tanggal)==bulan, subq.c.jenis==4,func.substr(subq.c.rek_kd,1,5)=='5.2.1'),subq.c.nilai)], else_=0)).label('LSG_kini'), func.sum(case([(and_(extract('month',subq.c.tanggal)<bulan, subq.c.jenis==4,not_(func.substr(subq.c.rek_kd,1,5)=='5.2.1')),subq.c.nilai)], else_=0)).label('LS_lalu'), func.sum(case([(and_(extract('month',subq.c.tanggal)==bulan, subq.c.jenis==4,not_(func.substr(subq.c.rek_kd,1,5)=='5.2.1')),subq.c.nilai)], else_=0)).label('LS_kini'), func.sum(case([(and_(extract('month',subq.c.tanggal)<bulan, not_(subq.c.jenis==4)),subq.c.nilai)], else_=0)).label('Lain_lalu'), func.sum(case([(and_(extract('month',subq.c.tanggal)==bulan, not_(subq.c.jenis==4)),subq.c.nilai)], else_=0)).label('Lain_kini'), ).group_by(subq.c.urusan_kd, subq.c.unit_id, subq.c.unit_kd, subq.c.unit_nm, subq.c.program_kd, subq.c.keg_kd, subq.c.keg_nm, subq.c.rek_kd, subq.c.rek_nm, subq.c.tahun ).order_by(subq.c.keg_kd ) generator = b104r400Generator() pdf = generator.generate(query) response=req.response response.content_type="application/pdf" response.content_disposition='filename=output.pdf' response.write(pdf) return response #Laporan AR Invoice class b101r001Generator(JasperGenerator): def __init__(self): super(b101r001Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R101001.jrxml') self.xpath = '/apbd/arinvoice' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'arinvoice') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "tgl_terima").text = unicode(row.tgl_terima) ET.SubElement(xml_greeting, "tgl_validasi").text = unicode(row.tgl_validasi) ET.SubElement(xml_greeting, "penyetor").text = row.penyetor ET.SubElement(xml_greeting, "uraian").text = row.uraian ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "jumlah").text = unicode(row.jumlah) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root #Laporan AR Sts class b101r002Generator(JasperGenerator): def __init__(self): super(b101r002Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R101002.jrxml') self.xpath = '/apbd/arinvoice' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'arinvoice') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "tgl_sts").text = unicode(row.tgl_sts) ET.SubElement(xml_greeting, "tgl_validasi").text = unicode(row.tgl_validasi) ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "uraian").text = row.uraian ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "tipe").text = unicode(row.tipe) ET.SubElement(xml_greeting, "logo").text = logo return self.root #TBP-Generator class b102r002Generator(JasperGenerator): def __init__(self): super(b102r002Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R102002.jrxml') self.xpath = '/apbd/arinvoice' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'arinvoice') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "unit_alamat").text = row.unit_alamat ET.SubElement(xml_greeting, "arinvoice_id").text = unicode(row.arinvoice_id) ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "arinvoice_nm").text = row.arinvoice_nm ET.SubElement(xml_greeting, "tgl_terima").text = unicode(row.tgl_terima) ET.SubElement(xml_greeting, "tgl_validasi").text = unicode(row.tgl_validasi) ET.SubElement(xml_greeting, "bendahara_nm").text = row.bendahara_nm ET.SubElement(xml_greeting, "bendahara_nip").text = row.bendahara_nip ET.SubElement(xml_greeting, "penyetor").text = row.penyetor ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "kegiatan_nm").text = row.kegiatan_nm ET.SubElement(xml_greeting, "nilai").text = unicode(row.nilai) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root #STS-Generator class b102r003Generator(JasperGenerator): def __init__(self): super(b102r003Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R102003.jrxml') self.xpath = '/apbd/sts' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'sts') ET.SubElement(xml_greeting, "tahun_id").text = unicode(row.tahun_id) ET.SubElement(xml_greeting, "unit_nm").text = row.units.nama ET.SubElement(xml_greeting, "id").text = unicode(row.id) ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "nama").text = row.nama ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "tgl_sts").text = unicode(row.tgl_sts) ET.SubElement(xml_greeting, "tgl_validasi").text = unicode(row.tgl_validasi) ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "bank_nama").text = row.bank_nama ET.SubElement(xml_greeting, "bank_account").text = row.bank_account ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root class b103r001Generator(JasperGenerator): def __init__(self): super(b103r001Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R103001.jrxml') self.xpath = '/apbd/invoice' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'invoice') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "invoice_id").text = unicode(row.invoice_id) ET.SubElement(xml_greeting, "invoice_nm").text = row.invoice_nm ET.SubElement(xml_greeting, "tgl_invoice").text = unicode(row.tgl_invoice) ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "ap_rekening").text = row.ap_rekening ET.SubElement(xml_greeting, "ap_npwp").text = row.ap_npwp ET.SubElement(xml_greeting, "kegiatan_nm").text = row.kegiatan_nm ET.SubElement(xml_greeting, "nilai").text = unicode(row.nilai) ET.SubElement(xml_greeting, "terbilang").text = Terbilang(row.nilai) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPP Pengantar UP/TU/GU-LSB class b103r021Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103021.jrxml') self.subreportlist = [] self.subreportlist.append(get_rpath('apbd/tuskpd/R103021_subreport1.jrxml')) self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "no_perkdh").text = row.no_perkdh ET.SubElement(xml_greeting, "tgl_perkdh").text = unicode(row.tgl_perkdh) ET.SubElement(xml_greeting, "urusan_nm").text = row.urusan_nm ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "spp_id").text = unicode(row.spp_id) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "spp_tgl").text = unicode(row.spp_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "ttd_jab").text = row.ttd_jab ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "ap_bank").text = row.ap_bank ET.SubElement(xml_greeting, "ap_rekening").text = row.ap_rekening ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "pptk_nip").text = row.pptk_nip ET.SubElement(xml_greeting, "pptk_nama").text = row.pptk_nama ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo ET.SubElement(xml_greeting, "terbilang_nominal").text = Terbilang(row.nominal) subq = DBSession.query(APInvoice.kegiatan_sub_id ).filter(APInvoice.unit_id==row.unit_id, APInvoice.tahun_id==row.tahun, SppItem.ap_invoice_id==APInvoice.id, SppItem.ap_spp_id==row.spp_id).subquery() rowspd = DBSession.query(func.coalesce(func.sum(SpdItem.nominal),0).label('jml_spd') ).filter(Spd.id==SpdItem.ap_spd_id, Spd.unit_id==row.unit_id, Spd.tahun_id==row.tahun, Spd.tanggal<=row.spp_tgl, SpdItem.kegiatan_sub_id==subq.c.kegiatan_sub_id ) for row1 in rowspd : ET.SubElement(xml_greeting, "jml_spd").text = unicode(row1.jml_spd) rowsp2d = DBSession.query(func.coalesce(func.sum(APInvoiceItem.amount),0).label('jml_apinvoice_lalu') ).filter(APInvoice.id==APInvoiceItem.ap_invoice_id, SppItem.ap_invoice_id==APInvoice.id, Spp.id==SppItem.ap_spp_id, APInvoice.unit_id==row.unit_id, APInvoice.tahun_id==row.tahun, Spp.id!=row.spp_id, APInvoice.kegiatan_sub_id==subq.c.kegiatan_sub_id ) for row2 in rowsp2d : ET.SubElement(xml_greeting, "jml_apinvoice_lalu").text = unicode(row2.jml_apinvoice_lalu) ET.SubElement(xml_greeting, "terbilang_sisa").text = Terbilang(row1.jml_spd-row2.jml_apinvoice_lalu) rows1 = DBSession.query(Spd.id, Spd.kode.label('spd_kd'), Spd.tanggal.label('spd_tgl'), func.sum(SpdItem.anggaran).label('anggaran'),func.sum(SpdItem.nominal).label('nilai'),func.sum(SpdItem.lalu).label('lalu'), ).filter(Spd.unit_id==row.unit_id, Spd.tahun_id==row.tahun, Spd.tanggal<=row.spp_tgl, SpdItem.kegiatan_sub_id==subq.c.kegiatan_sub_id ).group_by(Spd.id, Spd.kode, Spd.tanggal ).order_by(Spd.tanggal) for row3 in rows1 : xml_a = ET.SubElement(xml_greeting, "spd") ET.SubElement(xml_a, "spd_kd").text = row3.spd_kd ET.SubElement(xml_a, "spd_tgl").text = unicode(row3.spd_tgl) ET.SubElement(xml_a, "anggaran").text = unicode(row3.anggaran) ET.SubElement(xml_a, "nilai").text = unicode(row3.nilai) ET.SubElement(xml_a, "lalu").text = unicode(row3.lalu) return self.root ### SPP Pengantar LSG class b103r022Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103022.jrxml') self.subreportlist = [] self.subreportlist.append(get_rpath('apbd/tuskpd/R103022_subreport1.jrxml')) self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "no_perkdh").text = row.no_perkdh ET.SubElement(xml_greeting, "tgl_perkdh").text = unicode(row.tgl_perkdh) ET.SubElement(xml_greeting, "urusan_nm").text = row.urusan_nm ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "spp_id").text = unicode(row.spp_id) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "spp_tgl").text = unicode(row.spp_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "ttd_jab").text = row.ttd_jab ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "ap_bank").text = row.ap_bank ET.SubElement(xml_greeting, "ap_rekening").text = row.ap_rekening ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "pptk_nip").text = row.pptk_nip ET.SubElement(xml_greeting, "pptk_nama").text = row.pptk_nama ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo ET.SubElement(xml_greeting, "terbilang_nominal").text = Terbilang(row.nominal) rowspd = DBSession.query(func.coalesce(func.sum(SpdItem.nominal),0).label('jml_spd') ).filter(Spd.id==SpdItem.ap_spd_id, Spd.unit_id==row.unit_id, Spd.tahun_id==row.tahun, Spd.tanggal<=row.spp_tgl ) for row1 in rowspd : ET.SubElement(xml_greeting, "jml_spd").text = unicode(row1.jml_spd) rowsp2d = DBSession.query(func.coalesce(func.sum(Spp.nominal),0).label('jml_sp2d') ).filter(Spp.id==Spm.ap_spp_id, Spm.id==Sp2d.ap_spm_id, Spp.unit_id==row.unit_id, Spp.tahun_id==row.tahun, Sp2d.tanggal<=row.spp_tgl ) for row2 in rowsp2d : ET.SubElement(xml_greeting, "jml_sp2d").text = unicode(row2.jml_sp2d) ET.SubElement(xml_greeting, "terbilang_sisa").text = Terbilang(row1.jml_spd-row2.jml_sp2d) rows1 = DBSession.query(Spd.id, Spd.kode.label('spd_kd'), Spd.tanggal.label('spd_tgl'), func.sum(SpdItem.anggaran).label('anggaran'),func.sum(SpdItem.nominal).label('nilai'),func.sum(SpdItem.lalu).label('lalu'), ).filter(Spd.unit_id==row.unit_id, Spd.tahun_id==row.tahun, Spd.tanggal<=row.spp_tgl ).group_by(Spd.id, Spd.kode, Spd.tanggal ).order_by(Spd.tanggal) for row3 in rows1 : xml_a = ET.SubElement(xml_greeting, "spd") ET.SubElement(xml_a, "spd_kd").text = row3.spd_kd ET.SubElement(xml_a, "spd_tgl").text = unicode(row3.spd_tgl) ET.SubElement(xml_a, "anggaran").text = unicode(row3.anggaran) ET.SubElement(xml_a, "nilai").text = unicode(row3.nilai) ET.SubElement(xml_a, "lalu").text = unicode(row3.lalu) return self.root ### SPP Pengantar LS class b103r025Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103025.jrxml') self.subreportlist = [] self.subreportlist.append(get_rpath('apbd/tuskpd/R103025_subreport1.jrxml')) self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "no_perkdh").text = row.no_perkdh ET.SubElement(xml_greeting, "tgl_perkdh").text = unicode(row.tgl_perkdh) ET.SubElement(xml_greeting, "urusan_nm").text = row.urusan_nm ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "spp_id").text = unicode(row.spp_id) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "spp_tgl").text = unicode(row.spp_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "ttd_jab").text = row.ttd_jab ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "ap_bank").text = row.ap_bank ET.SubElement(xml_greeting, "ap_rekening").text = row.ap_rekening ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "pptk_nip").text = row.pptk_nip ET.SubElement(xml_greeting, "pptk_nama").text = row.pptk_nama ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo ET.SubElement(xml_greeting, "terbilang_nominal").text = Terbilang(row.nominal) subq = DBSession.query(APInvoice.kegiatan_sub_id ).filter(APInvoice.unit_id==row.unit_id, APInvoice.tahun_id==row.tahun, SppItem.ap_invoice_id==APInvoice.id, SppItem.ap_spp_id==row.spp_id).subquery() rowspd = DBSession.query(func.coalesce(func.sum(SpdItem.nominal),0).label('jml_spd') ).filter(Spd.id==SpdItem.ap_spd_id, Spd.unit_id==row.unit_id, Spd.tahun_id==row.tahun, Spd.tanggal<=row.spp_tgl, SpdItem.kegiatan_sub_id==subq.c.kegiatan_sub_id ) for row1 in rowspd : ET.SubElement(xml_greeting, "jml_spd").text = unicode(row1.jml_spd) rowsp2d = DBSession.query(func.coalesce(func.sum(APInvoiceItem.amount),0).label('jml_apinvoice_lalu') ).filter(APInvoice.id==APInvoiceItem.ap_invoice_id, SppItem.ap_invoice_id==APInvoice.id, Spp.id==SppItem.ap_spp_id, APInvoice.unit_id==row.unit_id, APInvoice.tahun_id==row.tahun, Spp.id!=row.spp_id, APInvoice.kegiatan_sub_id==subq.c.kegiatan_sub_id ) for row2 in rowsp2d : ET.SubElement(xml_greeting, "jml_apinvoice_lalu").text = unicode(row2.jml_apinvoice_lalu) ET.SubElement(xml_greeting, "terbilang_sisa").text = Terbilang(row1.jml_spd-row2.jml_apinvoice_lalu) rows1 = DBSession.query(Spd.id, Spd.kode.label('spd_kd'), Spd.tanggal.label('spd_tgl'), func.sum(SpdItem.anggaran).label('anggaran'),func.sum(SpdItem.nominal).label('nilai'),func.sum(SpdItem.lalu).label('lalu'), ).filter(Spd.unit_id==row.unit_id, Spd.tahun_id==row.tahun, Spd.tanggal<=row.spp_tgl, SpdItem.kegiatan_sub_id==subq.c.kegiatan_sub_id ).group_by(Spd.id, Spd.kode, Spd.tanggal ).order_by(Spd.tanggal) for row3 in rows1 : xml_a = ET.SubElement(xml_greeting, "spd") ET.SubElement(xml_a, "spd_kd").text = row3.spd_kd ET.SubElement(xml_a, "spd_tgl").text = unicode(row3.spd_tgl) ET.SubElement(xml_a, "anggaran").text = unicode(row3.anggaran) ET.SubElement(xml_a, "nilai").text = unicode(row3.nilai) ET.SubElement(xml_a, "lalu").text = unicode(row3.lalu) return self.root ### SPP Ringkasan UP/TU class b103r031Generator(JasperGenerator): def __init__(self): super(b103r031Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R103031.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "no_perkdh").text = row.no_perkdh ET.SubElement(xml_greeting, "tgl_perkdh").text = unicode(row.tgl_perkdh) ET.SubElement(xml_greeting, "urusan_nm").text = row.urusan_nm ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "spp_id").text = unicode(row.spp_id) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "spp_tgl").text = unicode(row.spp_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "ttd_jab").text = row.ttd_jab ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "ap_bank").text = row.ap_bank ET.SubElement(xml_greeting, "ap_rekening").text = row.ap_rekening ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "pptk_nip").text = row.pptk_nip ET.SubElement(xml_greeting, "pptk_nama").text = row.pptk_nama ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo ET.SubElement(xml_greeting, "terbilang").text = Terbilang(row.nominal) return self.root ### SPP Ringkasan LS class b103r035Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103035.jrxml') self.subreportlist = [] self.subreportlist.append(get_rpath('apbd/tuskpd/R103035_subreport1.jrxml')) self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "tanggal_2").text = unicode(row.tanggal_2) ET.SubElement(xml_greeting, "tanggal_4").text = unicode(row.tanggal_4) ET.SubElement(xml_greeting, "spp_id").text = unicode(row.spp_id) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "spp_tgl").text = unicode(row.spp_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "ttd_jab").text = row.ttd_jab ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "pptk_nip").text = row.pptk_nip ET.SubElement(xml_greeting, "pptk_nama").text = row.pptk_nama ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "ap_bank").text = row.ap_bank ET.SubElement(xml_greeting, "ap_rekening").text = row.ap_rekening ET.SubElement(xml_greeting, "ap_waktu").text = row.ap_waktu ET.SubElement(xml_greeting, "ap_uraian").text = row.ap_uraian ET.SubElement(xml_greeting, "ap_pemilik").text = row.ap_pemilik ET.SubElement(xml_greeting, "ap_alamat").text = row.ap_alamat ET.SubElement(xml_greeting, "ap_bentuk").text = row.ap_bentuk ET.SubElement(xml_greeting, "ap_kontrak").text = row.ap_kontrak ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "no_urut").text = unicode(row.no_urut) ET.SubElement(xml_greeting, "prg_nm").text = row.prg_nm ET.SubElement(xml_greeting, "anggaran").text = unicode(row.anggaran) ET.SubElement(xml_greeting, "tot_spd").text = unicode(row.tot_spd) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo rows = DBSession.query(Spd.id, Spd.kode.label('spd_kd'), Spd.tanggal.label('spd_tgl'), func.sum(SpdItem.nominal).label('nominal'), ).filter(Spd.id==SpdItem.ap_spd_id, Spd.unit_id==row.unit_id, Spd.tahun_id==row.tahun, Spd.tanggal<=row.spp_tgl ).group_by(Spd.id, Spd.kode, Spd.tanggal ).order_by(Spd.tanggal) for row3 in rows: xml_a = ET.SubElement(xml_greeting, "spd") ET.SubElement(xml_a, "kode").text = row3.spd_kd ET.SubElement(xml_a, "tanggal").text = unicode(row3.spd_tgl) ET.SubElement(xml_a, "nominal").text = unicode(row3.nominal) return self.root ### SPP Ringkasan LS.G class b103r033Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103033.jrxml') self.subreportlist = [] self.subreportlist.append(get_rpath('apbd/tuskpd/R103033_subreport1.jrxml')) self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "urusan_nm").text = row.urusan_nm ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "no_perkdh").text = row.no_perkdh ET.SubElement(xml_greeting, "tgl_perkdh").text = unicode(row.tgl_perkdh) ET.SubElement(xml_greeting, "tanggal_2").text = unicode(row.tanggal_2) ET.SubElement(xml_greeting, "tanggal_4").text = unicode(row.tanggal_4) ET.SubElement(xml_greeting, "spp_id").text = unicode(row.spp_id) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "spp_tgl").text = unicode(row.spp_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "ttd_jab").text = row.ttd_jab ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "pptk_nip").text = row.pptk_nip ET.SubElement(xml_greeting, "pptk_nama").text = row.pptk_nama ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "ap_bank").text = row.ap_bank ET.SubElement(xml_greeting, "ap_rekening").text = row.ap_rekening ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "anggaran").text = unicode(row.anggaran) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo ET.SubElement(xml_greeting, "terbilang").text = Terbilang(row.nominal) subq = DBSession.query(APInvoice.kegiatan_sub_id ).filter(APInvoice.unit_id==row.unit_id, APInvoice.tahun_id==row.tahun, SppItem.ap_invoice_id==APInvoice.id, SppItem.ap_spp_id==row.spp_id).subquery() rowspd = DBSession.query(func.coalesce(func.sum(SpdItem.nominal),0).label('jml_spd') ).filter(Spd.id==SpdItem.ap_spd_id, Spd.unit_id==row.unit_id, Spd.tahun_id==row.tahun, Spd.tanggal<=row.spp_tgl, SpdItem.kegiatan_sub_id==subq.c.kegiatan_sub_id ) for row1 in rowspd : ET.SubElement(xml_greeting, "jml_spd").text = unicode(row1.jml_spd) rowsp2d = DBSession.query(func.coalesce(func.sum(APInvoiceItem.amount),0).label('jml_apinvoice_lalu') ).filter(APInvoice.id==APInvoiceItem.ap_invoice_id, SppItem.ap_invoice_id==APInvoice.id, Spp.id==SppItem.ap_spp_id, APInvoice.unit_id==row.unit_id, APInvoice.tahun_id==row.tahun, Spp.id!=row.spp_id, APInvoice.kegiatan_sub_id==subq.c.kegiatan_sub_id ) for row2 in rowsp2d : ET.SubElement(xml_greeting, "jml_apinvoice_lalu").text = unicode(row2.jml_apinvoice_lalu) ET.SubElement(xml_greeting, "terbilang_sisa").text = Terbilang(row1.jml_spd-row2.jml_apinvoice_lalu) rows1 = DBSession.query(Spd.id, Spd.kode.label('spd_kd'), Spd.tanggal.label('spd_tgl'), func.sum(SpdItem.anggaran).label('anggaran'),func.sum(SpdItem.nominal).label('nilai'),func.sum(SpdItem.lalu).label('lalu'), ).filter(Spd.unit_id==row.unit_id, Spd.tahun_id==row.tahun, Spd.tanggal<=row.spp_tgl, SpdItem.kegiatan_sub_id==subq.c.kegiatan_sub_id ).group_by(Spd.id, Spd.kode, Spd.tanggal ).order_by(Spd.tanggal) for row3 in rows1 : xml_a = ET.SubElement(xml_greeting, "spd") ET.SubElement(xml_a, "spd_kd").text = row3.spd_kd ET.SubElement(xml_a, "spd_tgl").text = unicode(row3.spd_tgl) ET.SubElement(xml_a, "anggaran").text = unicode(row3.anggaran) ET.SubElement(xml_a, "nilai").text = unicode(row3.nilai) ET.SubElement(xml_a, "lalu").text = unicode(row3.lalu) return self.root ### SPP Ringkasan GU / LSB class b103r034Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103034.jrxml') self.subreportlist = [] self.subreportlist.append(get_rpath('apbd/tuskpd/R103034_subreport1.jrxml')) self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "tanggal_2").text = unicode(row.tanggal_2) ET.SubElement(xml_greeting, "tanggal_4").text = unicode(row.tanggal_4) ET.SubElement(xml_greeting, "spp_id").text = unicode(row.spp_id) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "spp_tgl").text = unicode(row.spp_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "ttd_jab").text = row.ttd_jab ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "pptk_nip").text = row.pptk_nip ET.SubElement(xml_greeting, "pptk_nama").text = row.pptk_nama ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "ap_bank").text = row.ap_bank ET.SubElement(xml_greeting, "ap_rekening").text = row.ap_rekening ET.SubElement(xml_greeting, "ap_waktu").text = row.ap_waktu ET.SubElement(xml_greeting, "ap_uraian").text = row.ap_uraian ET.SubElement(xml_greeting, "ap_pemilik").text = row.ap_pemilik ET.SubElement(xml_greeting, "ap_alamat").text = row.ap_alamat ET.SubElement(xml_greeting, "ap_bentuk").text = row.ap_bentuk ET.SubElement(xml_greeting, "ap_kontrak").text = row.ap_kontrak ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "no_urut").text = unicode(row.no_urut) ET.SubElement(xml_greeting, "prg_nm").text = row.prg_nm ET.SubElement(xml_greeting, "anggaran").text = unicode(row.anggaran) ET.SubElement(xml_greeting, "tot_spd").text = unicode(row.tot_spd) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo rows = DBSession.query(Spd.id, Spd.kode.label('spd_kd'), Spd.tanggal.label('spd_tgl'), func.sum(SpdItem.nominal).label('nominal'), ).filter(Spd.id==SpdItem.ap_spd_id, Spd.unit_id==row.unit_id, Spd.tahun_id==row.tahun, Spd.tanggal<=row.spp_tgl ).group_by(Spd.id, Spd.kode, Spd.tanggal ).order_by(Spd.tanggal) for row3 in rows: xml_a = ET.SubElement(xml_greeting, "spd") ET.SubElement(xml_a, "kode").text = row3.spd_kd ET.SubElement(xml_a, "tanggal").text = unicode(row3.spd_tgl) ET.SubElement(xml_a, "nominal").text = unicode(row3.nominal) return self.root ### SPP Rincian // UP class b103r041Generator(JasperGenerator): def __init__(self): super(b103r041Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R103041.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "urusan_kd").text = row.urusan_kd ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "prg_kd").text = row.prg_kd ET.SubElement(xml_greeting, "prg_nm").text = row.prg_nm ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "nama").text = row.nama ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPP Rincian // TU class b103r042Generator(JasperGenerator): def __init__(self): super(b103r042Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R103042.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "urusan_kd").text = row.urusan_kd ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "prg_kd").text = row.prg_kd ET.SubElement(xml_greeting, "prg_nm").text = row.prg_nm ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "nama").text = row.nama ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "pptk_nip").text = row.pptk_nip ET.SubElement(xml_greeting, "pptk_nama").text = row.pptk_nama ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPP Rincian // LS class b103r045Generator(JasperGenerator): def __init__(self): super(b103r045Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R103045.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "urusan_kd").text = row.urusan_kd ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "prg_kd").text = row.prg_kd ET.SubElement(xml_greeting, "prg_nm").text = row.prg_nm ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "nama").text = row.nama ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "pptk_nip").text = row.pptk_nip ET.SubElement(xml_greeting, "pptk_nama").text = row.pptk_nama ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPP Rincian // GU/LSB class b103r043Generator(JasperGenerator): def __init__(self): super(b103r043Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R103043.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "urusan_kd").text = row.urusan_kd ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "prg_kd").text = row.prg_kd ET.SubElement(xml_greeting, "prg_nm").text = row.prg_nm ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "nama").text = row.nama ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "pptk_nip").text = row.pptk_nip ET.SubElement(xml_greeting, "pptk_nama").text = row.pptk_nama ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPP Rincian // LS.G class b103r044Generator(JasperGenerator): def __init__(self): super(b103r044Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R103044.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "urusan_kd").text = row.urusan_kd ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "prg_kd").text = row.prg_kd ET.SubElement(xml_greeting, "prg_nm").text = row.prg_nm ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "nama").text = row.nama ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "pptk_nip").text = row.pptk_nip ET.SubElement(xml_greeting, "pptk_nama").text = row.pptk_nama ET.SubElement(xml_greeting, "logo").text = logo return self.root class b103r0023Generator(JasperGenerator): def __init__(self): super(b103r0023Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R1030023.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "kegiatan_nm").text = row.kegiatan_nm ET.SubElement(xml_greeting, "no_perkdh").text = row.no_perkdh ET.SubElement(xml_greeting, "tgl_perkdh").text = unicode(row.tgl_perkdh) ET.SubElement(xml_greeting, "urusan_nm").text = row.urusan_nm ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "nama").text = row.nama ET.SubElement(xml_greeting, "bank_nama").text = row.bank_nama ET.SubElement(xml_greeting, "bank_account").text = row.bank_account ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "spd_kd").text = row.spd_kd ET.SubElement(xml_greeting, "tgl_spd").text = unicode(row.tgl_spd) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPM // Format SPM class b103r003Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003.jrxml') self.subreportlist = [] self.subreportlist.append(get_rpath('apbd/tuskpd/R103003_subreport1.jrxml')) self.subreportlist.append(get_rpath('apbd/tuskpd/R103003_subreport2.jrxml')) #self.subreportlist.append(get_rpath('apbd/tuskpd/R103003_subreport3.jrxml')) self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "spm_id").text = unicode(row.spm_id) ET.SubElement(xml_greeting, "spm_kd").text = row.spm_kd ET.SubElement(xml_greeting, "spm_nm").text = row.spm_nm ET.SubElement(xml_greeting, "spm_tgl").text = unicode(row.spm_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "spp_id").text = unicode(row.spp_id) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "spp_tgl").text = unicode(row.spp_tgl) ET.SubElement(xml_greeting, "ap_bank").text = row.ap_bank ET.SubElement(xml_greeting, "ap_rekening").text = row.ap_rekening ET.SubElement(xml_greeting, "ap_npwp").text = row.ap_npwp ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "spd_kd").text = row.spd_kd ET.SubElement(xml_greeting, "spd_tgl").text = unicode(row.spd_tgl) ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "prg_kd").text = row.program_kd ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "ap_invoice_id").text = unicode(row.ap_invoice_id) ET.SubElement(xml_greeting, "logo").text = logo ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "terbilang_nominal").text = Terbilang(row.nominal) rowpot = DBSession.query(func.coalesce(func.sum(SpmPotongan.nilai),0).label('nilai_pot') ).filter(SpmPotongan.ap_spm_id==row.spm_id) for row4 in rowpot : ET.SubElement(xml_greeting, "nilai_pot").text = unicode(row4.nilai_pot) ET.SubElement(xml_greeting, "terbilang").text = Terbilang(row.nominal-row4.nilai_pot) rowppn = DBSession.query(func.coalesce(func.sum(APInvoiceItem.ppn),0).label('ppn'), func.coalesce(func.sum(APInvoiceItem.pph),0).label('pph') ).filter(APInvoiceItem.ap_invoice_id==row.ap_invoice_id) for row5 in rowppn : ET.SubElement(xml_greeting, "ppn").text = unicode(row5.ppn) ET.SubElement(xml_greeting, "pph").text = unicode(row5.pph) rows = DBSession.query(Rekening.kode, Rekening.nama, Unit.kode.label('unit_kd'), Kegiatan.kode.label('keg_kd'), func.sum(APInvoiceItem.amount).label('jumlah') ).filter(Rekening.id==KegiatanItem.rekening_id, KegiatanItem.id==APInvoiceItem.kegiatan_item_id, KegiatanSub.id==KegiatanItem.kegiatan_sub_id, KegiatanSub.kegiatan_id==Kegiatan.id, Program.id==Kegiatan.program_id, Unit.id==KegiatanSub.unit_id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, SppItem.ap_spp_id==row.spp_id, func.substr(Rekening.kode,1,1)=='5' ).group_by(Rekening.kode, Rekening.nama, Unit.kode, Kegiatan.kode ).order_by(Rekening.kode) for row2 in rows : xml_a = ET.SubElement(xml_greeting, "rekening") ET.SubElement(xml_a, "rek_kd").text =row2.kode ET.SubElement(xml_a, "rek_nm").text =row2.nama ET.SubElement(xml_a, "unit_kd").text =row2.unit_kd ET.SubElement(xml_a, "keg_kd").text =row2.keg_kd ET.SubElement(xml_a, "jumlah").text =unicode(row2.jumlah) rows1 = DBSession.query(Rekening.kode, Rekening.nama, (SpmPotongan.nilai).label('jumlah') ).filter(Rekening.id==SpmPotongan.rekening_id, SpmPotongan.ap_spm_id==row.spm_id ).order_by(Rekening.kode) for row3 in rows1 : xml_b = ET.SubElement(xml_greeting, "potongan") ET.SubElement(xml_b, "rek_kd").text =row3.kode ET.SubElement(xml_b, "rek_nm").text =row3.nama ET.SubElement(xml_b, "jumlah").text =unicode(row3.jumlah) return self.root ### SPM // Pengantar class b103r003_1Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003_1.jrxml') self.subreportlist = [] #self.subreportlist.append(get_rpath('apbd/tuskpd/R103003_1_subreport1.jrxml')) self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "spm_id").text = unicode(row.spm_id) ET.SubElement(xml_greeting, "spm_kd").text = row.spm_kd ET.SubElement(xml_greeting, "spm_nm").text = row.spm_nm ET.SubElement(xml_greeting, "spm_tgl").text = unicode(row.spm_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "spp_id").text = unicode(row.spp_id) ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "prg_kd").text = row.prg_kd ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPM // Pernyataan class b103r003_2Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003_2.jrxml') self.subreportlist = [] #self.subreportlist.append(get_rpath('apbd/tuskpd/R103003_subreport1.jrxml')) self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "spm_id").text = unicode(row.spm_id) ET.SubElement(xml_greeting, "spm_kd").text = row.spm_kd ET.SubElement(xml_greeting, "spm_nm").text = row.spm_nm ET.SubElement(xml_greeting, "spm_tgl").text = unicode(row.spm_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "spp_id").text = unicode(row.spp_id) ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "terbilang").text = Terbilang(row.amount) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo rows = DBSession.query(case([(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),"-GJ")], else_=" ").label('kode') ).filter(Spp.id==SppItem.ap_spp_id, SppItem.ap_invoice_id==APInvoiceItem.ap_invoice_id, APInvoiceItem.kegiatan_item_id==KegiatanItem.id, KegiatanItem.rekening_id==Rekening.id, Spp.id==row.spp_id ).group_by(case([(and_(Spp.jenis==4,func.substr(Rekening.kode,1,5)=='5.1.1'),"-GJ")], else_=" ")) for row1 in rows: ET.SubElement(xml_greeting, "kode").text = row1.kode return self.root ### SPM // Pernyataan class b103r003_12Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003_12.jrxml') self.subreportlist = [] #self.subreportlist.append(get_rpath('apbd/tuskpd/R103003_subreport1.jrxml')) self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "spm_id").text = unicode(row.spm_id) ET.SubElement(xml_greeting, "spm_kd").text = row.spm_kd ET.SubElement(xml_greeting, "spm_nm").text = row.spm_nm ET.SubElement(xml_greeting, "spm_tgl").text = unicode(row.spm_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "nilai").text = unicode(row.nominal) ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPM // SPTJM LS Pihak Ketiga 1 class b103r003_4Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003_4.jrxml') self.subreportlist = [] self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun_id) ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "ap_bap_no").text = row.ap_bap_no ET.SubElement(xml_greeting, "ap_bap_tgl").text = unicode(row.ap_bap_tgl) ET.SubElement(xml_greeting, "nilai").text = unicode(row.ap_nilai) ET.SubElement(xml_greeting, "ap_kontrak").text = row.ap_kontrak ET.SubElement(xml_greeting, "ap_tgl_kontrak").text = unicode(row.ap_tgl_kontrak) ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "ap_pemilik").text = row.ap_pemilik ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPM // SPTJM LS Pihak Ketiga 1 class b103r003_5Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003_5.jrxml') self.subreportlist = [] self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun_id) ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "ap_bap_no").text = row.ap_bap_no ET.SubElement(xml_greeting, "ap_bap_tgl").text = row.ap_bap_tgl ET.SubElement(xml_greeting, "nilai").text = unicode(row.ap_nilai) ET.SubElement(xml_greeting, "ap_kontrak").text = row.ap_kontrak ET.SubElement(xml_greeting, "ap_tgl_kontrak").text = row.ap_tgl_kontrak ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "ap_pemilik").text = row.ap_pemilik ET.SubElement(xml_greeting, "ap_kwitansi_nilai").text = unicode(row.ap_kwitansi_nilai) ET.SubElement(xml_greeting, "ap_kwitansi_no").text = row.ap_kwitansi_no ET.SubElement(xml_greeting, "ap_kwitansi_tgl").text = unicode(row.ap_kwitansi_tgl) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPM // SPTJM LS class b103r003_6Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003_6.jrxml') self.subreportlist = [] self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun_id) ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPM // SPTJM GU class b103r003_7Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003_7.jrxml') self.subreportlist = [] self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun_id) ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPM // SPTJB GU class b103r003_8Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003_8.jrxml') self.subreportlist = [] #self.subreportlist.append(get_rpath('apbd/tuskpd/R103003_subreport1.jrxml')) self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "prg_kd").text = row.program_kd ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "pph").text = unicode(row.pph) ET.SubElement(xml_greeting, "ppn").text = unicode(row.ppn) ET.SubElement(xml_greeting, "ap_kwitansi_no").text = row.ap_kwitansi_no ET.SubElement(xml_greeting, "ap_kwitansi_tgl").text = unicode(row.ap_kwitansi_tgl) ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "no_bku").text = row.no_bku ET.SubElement(xml_greeting, "tgl_bku").text = unicode(row.tgl_bku) ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun_id) ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPM // SPTJB LS class b103r003_9Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003_9.jrxml') self.subreportlist = [] #self.subreportlist.append(get_rpath('apbd/tuskpd/R103003_5_subreport1.jrxml')) self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "prg_kd").text = row.program_kd ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "pph").text = unicode(row.pph) ET.SubElement(xml_greeting, "ppn").text = unicode(row.ppn) ET.SubElement(xml_greeting, "ap_kwitansi_no").text = row.ap_kwitansi_no ET.SubElement(xml_greeting, "ap_kwitansi_tgl").text = unicode(row.ap_kwitansi_tgl) ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun_id) ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPM // SPTJB LS Pihak Ketiga class b103r003_10Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003_10.jrxml') self.subreportlist = [] #self.subreportlist.append(get_rpath('apbd/tuskpd/R103003_subreport1.jrxml')) self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "prg_kd").text = row.program_kd ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "amount").text = unicode(row.amount) ET.SubElement(xml_greeting, "pph").text = unicode(row.pph) ET.SubElement(xml_greeting, "ppn").text = unicode(row.ppn) ET.SubElement(xml_greeting, "ap_kwitansi_no").text = row.ap_kwitansi_no ET.SubElement(xml_greeting, "ap_kwitansi_tgl").text = unicode(row.ap_kwitansi_tgl) ET.SubElement(xml_greeting, "ap_nama").text = row.ap_nama ET.SubElement(xml_greeting, "tanggal").text = unicode(row.tanggal) ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun_id) ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root ### SPM // Checklist class b103r003_11Generator(JasperGeneratorWithSubreport): def __init__(self): self.mainreport = get_rpath('apbd/tuskpd/R103003_11.jrxml') self.subreportlist = [] #self.subreportlist.append(get_rpath('apbd/tuskpd/R103003_subreport1.jrxml')) self.xpath = '/apbd/spm' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spm') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "alamat").text = row.alamat ET.SubElement(xml_greeting, "spm_kd").text = row.spm_kd ET.SubElement(xml_greeting, "spm_nm").text = row.spm_nm ET.SubElement(xml_greeting, "spm_tgl").text = unicode(row.spm_tgl) ET.SubElement(xml_greeting, "ttd_nip").text = row.ttd_nip ET.SubElement(xml_greeting, "ttd_nama").text = row.ttd_nama ET.SubElement(xml_greeting, "jenis").text = unicode(row.jenis) ET.SubElement(xml_greeting, "kode").text = row.kode ET.SubElement(xml_greeting, "kegiatan").text = row.nama ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root class b104r000Generator(JasperGenerator): def __init__(self): super(b104r000Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R104000.jrxml') self.xpath = '/apbd/invoice' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'invoice') ET.SubElement(xml_greeting, "tahun_id").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "tgl_invoice").text = unicode(row.tgl_invoice) ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "invoice_kd").text = row.invoice_kd ET.SubElement(xml_greeting, "kegiatan_nm").text = row.kegiatan_nm ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "jumlah").text = unicode(row.jumlah) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root class b104r1001Generator(JasperGenerator): def __init__(self): super(b104r1001Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R1041001.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "tgl_spp").text = unicode(row.tgl_spp) ET.SubElement(xml_greeting, "spm_kd").text = row.spm_kd ET.SubElement(xml_greeting, "tgl_spm").text = unicode(row.tgl_spm) ET.SubElement(xml_greeting, "sp2d_kd").text = row.sp2d_kd ET.SubElement(xml_greeting, "tgl_sp2d").text = unicode(row.tgl_sp2d) ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root class b104r1002Generator(JasperGenerator): def __init__(self): super(b104r1002Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R1041002.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "tgl_spp").text = unicode(row.tgl_spp) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "UP").text = unicode(row.UP) ET.SubElement(xml_greeting, "GU").text = unicode(row.GU) ET.SubElement(xml_greeting, "TU").text = unicode(row.TU) ET.SubElement(xml_greeting, "LS_GJ").text = unicode(row.LS_GJ) ET.SubElement(xml_greeting, "LS").text = unicode(row.LS) ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root class b104r1003Generator(JasperGenerator): def __init__(self): super(b104r1003Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R1041003.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "tgl_spp").text = unicode(row.tgl_spp) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "UP").text = unicode(row.UP) ET.SubElement(xml_greeting, "GU").text = unicode(row.GU) ET.SubElement(xml_greeting, "TU").text = unicode(row.TU) ET.SubElement(xml_greeting, "LS").text = unicode(row.LS) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root class b104r1004Generator(JasperGenerator): def __init__(self): super(b104r1004Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R1041004.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "tgl_spm").text = unicode(row.tgl_spm) ET.SubElement(xml_greeting, "spm_kd").text = row.spm_kd ET.SubElement(xml_greeting, "spm_nm").text = row.spm_nm ET.SubElement(xml_greeting, "BRUTO").text = unicode(row.BRUTO) ET.SubElement(xml_greeting, "POTONGAN").text = unicode(row.POTONGAN) ET.SubElement(xml_greeting, "NETTO").text = unicode(row.NETTO) ET.SubElement(xml_greeting, "INFORMASI").text = unicode(row.INFORMASI) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root class b104r2001Generator(JasperGenerator): def __init__(self): super(b104r2001Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R1042001.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "tgl_spp").text = unicode(row.tgl_spp) ET.SubElement(xml_greeting, "spm_kd").text = row.spm_kd ET.SubElement(xml_greeting, "tgl_spm").text = unicode(row.tgl_spm) ET.SubElement(xml_greeting, "sp2d_kd").text = row.sp2d_kd ET.SubElement(xml_greeting, "tgl_sp2d").text = unicode(row.tgl_sp2d) ET.SubElement(xml_greeting, "nominal").text = unicode(row.nominal) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root class b104r2002Generator(JasperGenerator): def __init__(self): super(b104r2002Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R1042002.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "jenis").text = row.jenis ET.SubElement(xml_greeting, "tgl_spp").text = unicode(row.tgl_spp) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "UP").text = unicode(row.UP) ET.SubElement(xml_greeting, "GU").text = unicode(row.GU) ET.SubElement(xml_greeting, "TU").text = unicode(row.TU) ET.SubElement(xml_greeting, "LS_GJ").text = unicode(row.LS_GJ) ET.SubElement(xml_greeting, "LS").text = unicode(row.LS) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root class b104r2003Generator(JasperGenerator): def __init__(self): super(b104r2003Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R1042003.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "tgl_spp").text = unicode(row.tgl_spp) ET.SubElement(xml_greeting, "spp_kd").text = row.spp_kd ET.SubElement(xml_greeting, "spp_nm").text = row.spp_nm ET.SubElement(xml_greeting, "UP").text = unicode(row.UP) ET.SubElement(xml_greeting, "GU").text = unicode(row.GU) ET.SubElement(xml_greeting, "TU").text = unicode(row.TU) ET.SubElement(xml_greeting, "LS").text = unicode(row.LS) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root class b104r2004Generator(JasperGenerator): def __init__(self): super(b104r2004Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R1042004.jrxml') self.xpath = '/apbd/spp' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spp') ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "tgl_spm").text = unicode(row.tgl_spm) ET.SubElement(xml_greeting, "spm_kd").text = row.spm_kd ET.SubElement(xml_greeting, "spm_nm").text = row.spm_nm ET.SubElement(xml_greeting, "BRUTO").text = unicode(row.BRUTO) ET.SubElement(xml_greeting, "POTONGAN").text = unicode(row.POTONGAN) ET.SubElement(xml_greeting, "NETTO").text = unicode(row.NETTO) ET.SubElement(xml_greeting, "INFORMASI").text = unicode(row.INFORMASI) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo return self.root class b104r300Generator(JasperGenerator): def __init__(self): super(b104r300Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R104300.jrxml') self.xpath = '/apbd/spj' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spj') ET.SubElement(xml_greeting, "urusan_kd").text = row.urusan_kd ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "program_kd").text = row.program_kd ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "anggaran").text = unicode(row.anggaran) ET.SubElement(xml_greeting, "LSG_lalu").text = unicode(row.LSG_lalu) ET.SubElement(xml_greeting, "LSG_kini").text = unicode(row.LSG_kini) ET.SubElement(xml_greeting, "LS_lalu").text = unicode(row.LS_lalu) ET.SubElement(xml_greeting, "LS_kini").text = unicode(row.LS_kini) ET.SubElement(xml_greeting, "Lain_lalu").text = unicode(row.Lain_lalu) ET.SubElement(xml_greeting, "Lain_kini").text = unicode(row.Lain_kini) ET.SubElement(xml_greeting, "bulan").text = unicode(bulan) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo rows = DBSession.query(Pegawai.nama.label('pa_nama') ).filter(Pejabat.pegawai_id==Pegawai.id, Pejabat.jabatan_id==Jabatan.id, Pejabat.unit_id==row.unit_id, Jabatan.id==7) for row2 in rows : ET.SubElement(xml_greeting, "pa_nama").text = row2.pa_nama rows2 = DBSession.query(Pegawai.nama.label('bend_nama') ).filter(Pejabat.pegawai_id==Pegawai.id, Pejabat.jabatan_id==Jabatan.id, Pejabat.unit_id==row.unit_id, Jabatan.id==13) for row3 in rows2 : ET.SubElement(xml_greeting, "bend_nama").text = row3.bend_nama return self.root class b104r400Generator(JasperGenerator): def __init__(self): super(b104r400Generator, self).__init__() self.reportname = get_rpath('apbd/tuskpd/R104400.jrxml') self.xpath = '/apbd/spj' self.root = ET.Element('apbd') def generate_xml(self, tobegreeted): for row in tobegreeted: xml_greeting = ET.SubElement(self.root, 'spj') ET.SubElement(xml_greeting, "urusan_kd").text = row.urusan_kd ET.SubElement(xml_greeting, "unit_id").text = unicode(row.unit_id) ET.SubElement(xml_greeting, "unit_kd").text = row.unit_kd ET.SubElement(xml_greeting, "unit_nm").text = row.unit_nm ET.SubElement(xml_greeting, "program_kd").text = row.program_kd ET.SubElement(xml_greeting, "keg_kd").text = row.keg_kd ET.SubElement(xml_greeting, "keg_nm").text = row.keg_nm ET.SubElement(xml_greeting, "rek_kd").text = row.rek_kd ET.SubElement(xml_greeting, "rek_nm").text = row.rek_nm ET.SubElement(xml_greeting, "tahun").text = unicode(row.tahun) ET.SubElement(xml_greeting, "anggaran").text = unicode(row.anggaran) ET.SubElement(xml_greeting, "LSG_lalu").text = unicode(row.LSG_lalu) ET.SubElement(xml_greeting, "LSG_kini").text = unicode(row.LSG_kini) ET.SubElement(xml_greeting, "LS_lalu").text = unicode(row.LS_lalu) ET.SubElement(xml_greeting, "LS_kini").text = unicode(row.LS_kini) ET.SubElement(xml_greeting, "Lain_lalu").text = unicode(row.Lain_lalu) ET.SubElement(xml_greeting, "Lain_kini").text = unicode(row.Lain_kini) ET.SubElement(xml_greeting, "bulan").text = unicode(bulan) ET.SubElement(xml_greeting, "customer").text = customer ET.SubElement(xml_greeting, "logo").text = logo rows = DBSession.query(Pegawai.nama.label('pa_nama') ).filter(Pejabat.pegawai_id==Pegawai.id, Pejabat.jabatan_id==Jabatan.id, Pejabat.unit_id==row.unit_id, Jabatan.id==7) for row2 in rows : ET.SubElement(xml_greeting, "pa_nama").text = row2.pa_nama rows2 = DBSession.query(Pegawai.nama.label('bend_nama') ).filter(Pejabat.pegawai_id==Pegawai.id, Pejabat.jabatan_id==Jabatan.id, Pejabat.unit_id==row.unit_id, Jabatan.id==13) for row3 in rows2 : ET.SubElement(xml_greeting, "bend_nama").text = row3.bend_nama return self.root
4fc6fdad6c0f52ff0f15186e411b106b7500fd4d
[ "Markdown", "Python" ]
9
Python
aagusti/osipkd-pdpt
130abc77292f2f3023da6f8b785fb7ccf337a374
03e01e327d7df26da4f4dcdd82a35ba8cfa1ce40
refs/heads/master
<file_sep>#ifndef FUNCTIONTIMER_H #define FUNCTIONTIMER_H #include <iostream> #include <limits> #include <sys/time.h> class FunctionStats { private: int64_t longest_time = 0; // the longest function running time int64_t shortest_time = std::numeric_limits<int>::max(); // the shortest function running time int64_t total_time = 0; int64_t count = 0; // number of times the function being called std::string time_unit; public: FunctionStats(std::string time_unit_): time_unit(time_unit_){} void update_time(int running_time) { ++count; total_time += running_time; if (running_time > longest_time) longest_time = running_time; if (running_time < shortest_time) shortest_time = running_time; } void print_stats() const{ std::cout << "=========================================================" << std::endl; std::cout << "this function has run " << count << " times" << std::endl; std::cout << "average function running time: " << (int64_t)(total_time / count) << time_unit << std::endl; std::cout << "longest function running time: " << longest_time << time_unit << std::endl; std::cout << "shortest function running time: " << shortest_time << time_unit << std::endl; std::cout << "=========================================================" << std::endl; } }; // time the function for running once, default unit is millisecond class FunctionTimer { private: timeval start; timeval end; public: void start_timer () { gettimeofday(&start, NULL); } void calculate_time() { gettimeofday(&end, NULL); } int64_t get_elapsed_time_in_milliseconds() const { return (end.tv_usec - start.tv_usec) / 1000; } int64_t get_elapsed_time_in_microseconds() const { return end.tv_usec - start.tv_usec; } }; #endif <file_sep>#include <iostream> #include "FunctionTimer.h" using namespace std; FunctionStats STAT("u"); void func() { int x = 0; for (int i = 0; i < 1000000; ++i) { x += 1; } } int main() { FunctionTimer timer(1000000); cout << "Program starts" << endl; for (int i = 0; i < 10; ++i) { timer.start_timer(); func(); timer.calculate_time(); STAT.update_time(timer.get_elapsed_time()); } STAT.print_stats(); return 0; } <file_sep>CC=g++ main: main.cpp ${CC} -o $@ $^ clean: rm -f main
9eecacddd81dcd1b285f336605727071d6b523e0
[ "Makefile", "C++" ]
3
C++
jimmyyzr/FunctionTimer
7c161f22cc25772627e98f0bb317e443795620e9
3ec95407fef189f458d0a903d9300c5aa2285e26
refs/heads/master
<file_sep>## Put comments here that give an overall description of what your ## functions do # ## These functions are used to invert a matrix in an efficient way. ## Inverting matrices can be time consuming for computers. This function ## is more efficient because it first checks to see if the inversion has ## already been calculated and stored in cache. If so, it does not ## recalculate; it simply retrieves it from the cache. # ## This function uses the ginv() function from the MASS package ## Write a short comment describing this function # ## The first function creates a special object. The special object contains a matrix, ## its inversion, and four functions related to the matrix and its inversion. ## The four functions are used to 'get' and 'set' the matrix and its inversion. makeCacheMatrix <- function(our_matrix = matrix()) { ## initialize object 'our_matrix' as empty matrix our_inversion <- NULL ## initialize object 'our_inversion' as NULL set_our_matrix <- function(y) { ## create function 'set_our_matrix' our_matrix <<- y ## set object 'our_matrix' to be 'y' our_inversion <<- NULL ## reset object 'our_inversion' to be NULL } get_our_matrix <- function() our_matrix ## returns our matrix set_our_inversion <- function(inv) our_inversion <<- inv ## sets the inversion of the matrix get_our_inversion <- function() our_inversion ## returns the inversion list(set_our_matrix = set_our_matrix, ## creates a list that gives names to our above functions get_our_matrix = get_our_matrix, ## the list allows use of $ to extract functions set_our_inversion = set_our_inversion, get_our_inversion = get_our_inversion) } ## Write a short comment describing this function # ## The second function returns the inverted matrix from the special object ## that we create with makeCacheMatrix(). First it checks to see if the ## special object already contains the inverted matrix. If so, it does not ## recalculate the inversion. It just displays it. If the special object ## does not contain the inversion, then the function calculates it, sets it ## within the special object, and returns it. cacheSolve <- function(our_special_matrix, ...) { ## Return a matrix that is the inverse of our special matrix object our_inversion <- our_special_matrix$get_our_inversion() ## retrieve inversion value from our special matrix object if(!is.null(our_inversion)) { ## checks if the inversion is already cached or not message("getting cached data") ## notifies it's getting cached data (if cached) return(our_inversion) ## returns the value from cache (if cached) } ## if not cached, then... data <- our_special_matrix$get_our_matrix() ## gets the actual matrix from our special matrix our_inversion <- ginv(data, ...) ## calculate the inversion of our matrix (requires MASS package to be loaded) our_special_matrix$set_our_inversion(our_inversion) ## sets inversion in in our special matrix object so it's not NULL our_inversion ## outputs the actual inversion }
d0cc0ee8616dbd0080711c397254989a5ee7ff82
[ "R" ]
1
R
jgbond/ProgrammingAssignment2
f7067f3e7a6fb3bea98d58c6fb7801ac2608a4c2
7fa61673d0dea47eb4407f668d906492954469f4
refs/heads/master
<file_sep>const submissions = [ {name: "Jane", score: 95, date: "2020-01-24", passed: true}, {name: "Joe", score: 77, date: "2018-05-14", passed: true}, {name: "Jack", score: 59, date: "2019-07-05", passed: false}, {name: "Jill", score: 88, date: "2020-04-22", passed: true} ]; function addSubmission(array, newName, newScore, newDate){ let newObject = {name: newName, score: newScore, date: newDate}; if (newScore >= 60){ newObject.passed = true; } else { newObject.passed = false; } array.push(newObject); } addSubmission(submissions, "Gerard", 100, "1988-01-30") console.log(submissions) function deleteSubmissionByIndex(array, index){ array.splice(index, 1); } deleteSubmissionByIndex(submissions, 1) console.log(submissions) function deleteSubmissionByName(array, name){ let nameIndex = array.findIndex((item) => item.name === name); array.splice(nameIndex, 1); } deleteSubmissionByName(submissions, "Jane") console.log(submissions) function editSubmission(array, index, score){ array[index].score = score; array[index].passed = score >= 60; } editSubmission(submissions, 2, 35) console.log(submissions) function findSubmissionByName(array, name){ let person = array.find((people) => people.name === name); return person; } findSubmissionByName(submissions, "Gerard") console.log(findSubmissionByName(submissions, "Gerard")) function findLowestScore(array){ let lowestScore = array[0]; array.forEach((item) => { if (item.score < lowestScore.score) { lowestScore = item; } }); return lowestScore; } console.log(findLowestScore(submissions)) function findAverageScore(array){ let total = 0; for (let item of array) { total += item.score; } return total / array.length; } console.log(findAverageScore(submissions)) function filterPassing(array){ let passing = array.filter((item) => item.passed); return passing; } console.log(filterPassing(submissions)) function filter90AndAbove(array){ let above90 = array.filter((item) => item.score >= 90); return above90; } console.log(filter90AndAbove(submissions))
b06ec0bad2bb1c1c8e57a9c70f4925150e93c254
[ "JavaScript" ]
1
JavaScript
GerardD1/Lab-3-Javascript
d590aa17a19a86f618c1985af5c93ad498ed392a
17a72be795b22e5298a0fc12e0592709a97b72ac
refs/heads/master
<repo_name>Germonda/backup<file_sep>/Documents/RSem/code/tools.py import numpy as np import scipy import struct import sys def saveWeights(J, fname): wdata = np.ndarray((J.shape[0] * J.shape[1])) idx=0 for cc in range(J.shape[1]): for rr in range(J.shape[0]): wdata[idx] = J[rr, cc] idx += 1 myfile=open(fname, 'wb') # don't know yet how to do this in Python: if not( myfile.write(struct.pack(str(idx)+'f', *wdata)) # don't know yet how to do this in Python: raise NameError("Error while saving matrix of weights.\n"); myfile.close() def readWeights(J, fname): wdata= np.ndarray((J.shape[0] * J.shape[1])) idx=0 print("Reading weights from file ",fname) myfile=open(fname, 'rb') #myfile.read(wstruct); # don't know yet how to do this in Python: if not( wdata=np.asarray(struct.unpack(str(wdata.shape[0])+'f', myfile.read())); # don't know yet how to do this in Python: raise NameError("Error while reading matrix of weights.\n"); myfile.close() for cc in range(J.shape[1]): for rr in range(J.shape[0]): J[rr, cc] = wdata[idx] idx += 1 print("Done!") # C++ void randVec(VectorXd& M) def randVec(M): for nn in range(M.shape): M.data()[nn] = -1.0 + 2.0 * np.random.random(1) return M def randVecGaussian(M): for nn in range(M.shape): M.data()[nn] = -1.0 + 2.0 * np.random.normal(1) def randMat(M): for nn in range(M.shape): M.data()[nn] = -1.0 + 2.0 * np.random.random(1) def randJ(J, PROBACONN, G): for rr in range(J.shape[0]): for cc in range(J.shape[1]): if (np.random.random(1) < PROBACONN): J[rr, cc] = G * np.random.normal(0,1,1) / np.sqrt(PROBACONN * J.shape[1]) else: J[rr, cc] = 0.0 return J<file_sep>/Documents/MLiP/Kaggle/scripts/reading_images.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Feb 14 14:55:08 2017 @author: germonda """ # import libraries needed for this assignment import os import numpy as np from PIL import Image # function to get a list of file of a given extension, both the absolute path and the filename def get_file_list(path,ext='',queue=''): if ext != '': return [os.path.join(path,f) for f in os.listdir(path) if f.endswith(''+queue+'.'+ext+'')], [f for f in os.listdir(path) if f.endswith(''+queue+'.'+ext+'')] else: return [os.path.join(path,f) for f in os.listdir(path)] tra_img_dir = './data/train/ALB' tes_img_dir = './data/test_stg1/ALB' tra_imgs = sorted(get_file_list(tra_img_dir, 'j[pg')[0]) tes_img = sorted(get_file_list(tra_msk_dir, 'jpg')[0]) def show_image(idx, imgs, msks, lbls): img = np.asarray(Image.open(imgs[idx])) msk = np.asarray(Image.open(msks[idx])) lbl = np.asarray(Image.open(lbls[idx])) img_g = img[:,:,1].squeeze().astype(float) plt.subplot(1,3,1) plt.imshow(img); plt.title('RGB image {}'.format(idx+1)) plt.subplot(1,3,2) plt.imshow(msk, cmap='gray'); plt.title('Mask {}'.format(idx+1)) plt.subplot(1,3,3) plt.imshow(lbl, cmap='gray'); plt.title('Manual annotation {}'.format(idx+1)) plt.show() for i in range(len(tra_imgs)): show_image(i, tra_imgs, tes_img) <file_sep>/Documents/RSem/code/main.py import numpy as np import scipy import struct import sys import matplotlib.pyplot as plt from reservoir import Reservoir from tools import randJ from tools import readWeights from tools import saveWeights from ploterr_single import ploterr_single from decodetomdist import decodetomdist from plotdecode import plotdecode from plotpca import plotpca from ploterr_single_2back import ploterr_single_2back from decodetomdist_2back import decodetomdist_2back from plotdecode_2back import plotdecode_2back from plotpca_2back import plotpca_2back import params np.random.seed(0) NBNEUR = 200 NBIN = 3 # Number of inputs. Input 0 is reserved for a 'go' signal that is not used here. NBOUT = 1 # Only 1 output neuron TRIALTIME = 1000 # 200 timesteps longer patterns TASK=params.TWOBACK if (TASK == params.ONEBACK): NBTRIALS = 1007 # ~10K trials sufficient to get good convergence (95% correct on a binary criterion is reached within ~1000 trials, but performance keeps improving after that). Should really be 100K if you have time. NBPATTERNS = 4 STARTSTIM1 = 1 ; TIMESTIM1 = 200 STARTSTIM2 = 400; TIMESTIM2 = 200 elif (TASK == params.TWOBACK): NBTRIALS = 20407 # ~10K trials sufficient to get good convergence (95% correct on a binary criterion is reached within ~1000 trials, but performance keeps improving after that). Should really be 100K if you have time. NBPATTERNS = 8 STARTSTIM1 = 1 ; TIMESTIM1 = 200 STARTSTIM2 = 200; TIMESTIM2 = 200 STARTSTIM3 = 400; TIMESTIM3 = 200 patterns=np.zeros((NBPATTERNS, NBIN, TRIALTIME)) tgtresps=np.zeros((NBPATTERNS, TRIALTIME)) # Remember that input channel 0 is reserved for the (unused) 'go' signal # Here we define the inputs to be fed to the network, and the expected response, for each condition. # For the sequential-XOR problem (NBPATTERNS to 4, TRIALTIME and eval. time as appropriate): # We encode the input patterns as matrices with NBIN rows and TRIALTIME columns, which we fill with the appropriate input values at every time step and for each input channel if (TASK == params.ONEBACK): patterns[0][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[0][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1 # AA r=-1 patterns[1][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[1][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1 # AB r=1 patterns[2][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[2][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1 # BA r=1 patterns[3][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[3][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1 # BB r=-1 # Target responses - what the network ought to produce (note that only the last EVALTIME timesteps are actually relevant - see below) tgtresps[0][:]=-.98 tgtresps[1][:]=.98 tgtresps[2][:]=.98 tgtresps[3][:]=-.98 elif (TASK == params.TWOBACK): patterns[0][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[0][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[0][1,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # AAA r=-1 patterns[1][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[1][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[1][1,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # ABA r=-1 patterns[2][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[2][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[2][1,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # BAA r=1 patterns[3][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[3][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[3][1,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # BBA r=1 patterns[4][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[4][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[4][2,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # AAB r=1 patterns[5][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[5][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[5][2,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # ABB r=1 patterns[6][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[6][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[6][2,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # BAB r=-1 patterns[7][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[7][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[7][2,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # BBB r=-1 # Target responses - what the network ought to produce (note that only the last EVALTIME timesteps are actually relevant - see below) tgtresps[0][:]=-.98 tgtresps[1][:]=-.98 tgtresps[2][:]=.98 tgtresps[3][:]=.98 tgtresps[4][:]=.98 tgtresps[5][:]=.98 tgtresps[6][:]=-.98 tgtresps[7][:]=-.98 # Define RNN following Sompolinksy (Sompolinky et al, 'Chaos in random neural networks', 1988) rnn_model=Reservoir(N=NBNEUR, Nin=NBIN, tau=30.) print(rnn_model.J[0,0]," ",rnn_model.win[1,1]) train_patterns=np.zeros((NBTRIALS, rnn_model.Nin, TRIALTIME)) # NBTRIALS = n * NBPATTERNS e.g. 0:1000 = 125 * 0:7 train_tgtresps=np.zeros((NBTRIALS, TRIALTIME)) for numtrial in range(NBTRIALS): trialtype=numtrial%NBPATTERNS train_patterns[numtrial,:]=patterns[trialtype] train_tgtresps[numtrial,:]=tgtresps[trialtype] params.tau = rnn_model.tau params.SUFFIX = "_G" + str(params.G) + "_MAXDW" + str(params.MAXDW) + "_ETA" + str(params.ETA) + "_ALPHAMODUL" + str(params.ALPHAMODUL) + "_PROBAMODUL" + str(params.PROBAMODUL) + "_SQUARING" +str(params.SQUARING) + "_MODULTYPE-" + params.MODULTYPE + \ "_ALPHATRACE" + str(params.ALPHATRACE) + "_METHOD-" + params.METHOD + "_ATRACEEXC" + str(params.ALPHATRACEEXC) + "_TAU" + str(params.tau) + \ "_RNGSEED" + \ str(params.RNGSEED) #"_INPUTMULT" +str(INPUTMULT) + print(params.SUFFIX) # Run the RNN with Miconi's learning rules (Miconi, 'Flexible decision making in recurrent neural networks trained with a biologically plausible rule', 2016) error = rnn_model.runHebbian(train_patterns, train_tgtresps, NBPATTERNS, PHASE=params.LEARNING) if (TASK == params.ONEBACK): ploterr_single(NBTRIALS-1) elif (TASK == params.TWOBACK): ploterr_single_2back(NBTRIALS-1) # For the TESTING phase, read the weights from a previously saved file: readWeights(rnn_model.J, "J" + params.SUFFIX + ".dat") readWeights(rnn_model.win, "win" + params.SUFFIX + ".dat") # win doesn't change over time. # Less patterns for testing NBTRIALS = 20*NBPATTERNS test_patterns=np.zeros((NBTRIALS, rnn_model.Nin, TRIALTIME)) # NBTRIALS = n * NBPATTERNS e.g. 0:1000 = 125 * 0:7 test_tgtresps=np.zeros((NBTRIALS, TRIALTIME)) for numtrial in range(NBTRIALS): trialtype=numtrial%NBPATTERNS test_patterns[numtrial,:]=patterns[trialtype] test_tgtresps[numtrial,:]=tgtresps[trialtype] # Test the RNN, using the same RNN setup as in the learning phase apart from the learning rules error = rnn_model.runHebbian(test_patterns, test_tgtresps, NBPATTERNS, PHASE=params.TESTING) # Postprocessing analysis plots if (TASK == params.ONEBACK): decodetomdist() plotdecode() plotpca() elif (TASK == params.TWOBACK): decodetomdist_2back() plotdecode_2back() plotpca_2back() #rnn_model.learnConceptor(X) # Learn Conceptor from recorded neuron activity patterns X <file_sep>/Documents/RSem/code/reservoir.py import functions as fun import numpy as np import scipy from tools import randJ from tools import readWeights from tools import saveWeights import params ''' Reservoir Class ''' class Reservoir: ''' Constructor @param numInputDims: number of input dimensions @param N: number of neurons @param alpha ''' def __init__(self, N=100, Nin=3, tau=1.): self.N = N self.Nin = Nin self.win = np.random.random((N, Nin)) * 2 - 1; self.win[0,:] = 0; # Input weights are uniformly chosen between -1 and 1, except possibly for output cell (not even necessary). No plasticity for input weights. self.J= np.zeros((self.N, self.N)); randJ(self.J, params.PROBACONN, params.G); # Randomize recurrent weight matrix, according to the Sompolinsky method (Gaussian(0,1), divided by sqrt(ProbaConn*N) and multiplied by G - see definition of randJ() below). self.tau = tau #def __init__(self, numInputDims, N = 100, alpha = 10, NetSR = 1.2, biasScale = 1, inpScale = 1): # # self.N = N # self.alpha = alpha # self.NetSR = NetSR # self.biasScale = biasScale # self.inpScale = inpScale # self.numInputDims = numInputDims # # self.W_raw = fun.sprandn(self.N,self.N,0.1) # specRad = fun.getSpecRad(self.W_raw) # self.W_raw /= specRad / self.NetSR # self.W_bias = self.biasScale*np.random.randn(self.N,1) # self.W_in = self.inpScale*np.random.randn(self.N,self.numInputDims) # self.tau = 1 ''' Run Reservoir by driving it with patterns @param patterns: stimuli to drive the network @param t_learn: number of time steps to collect network states @param t_wash: number of time steps to drive the network withput collecting states @param alpha_wout: weight for ridge regression of output weights @param alpha_wload: weight for ridge regression of network weights after pattern loading @param load: flag whether to learn conceptors for patterns @return network states per pattern and inputs per pattern ''' def run(self, patterns, t_learn=1000, t_wash=100, alpha_wout=0.01, alpha_wload=0.0001, load=True): self.numPatts = len(patterns) self.C = [] patternStates = np.zeros((self.N, self.numPatts * t_learn)) patternPreviousStates = np.zeros((self.N, self.numPatts * t_learn)) patternInputs = np.zeros((self.numInputDims, self.numPatts * t_learn)) I = np.eye(self.N) # Iterate over different stimuli for i, p in enumerate(patterns): x = np.zeros((self.N, 1)) xs = np.zeros((self.N, t_learn)) us = np.zeros((self.numInputDims, t_learn)) # Run network dynamics for t in range(t_learn + t_wash): u = p[t] # Update network state x = np.tanh(np.dot(self.W_raw, x) + np.dot(self.W_in, u[:, None]) + self.W_bias) # If time over washout period collect states if (t >= t_wash): xs[:, t - t_wash] = x.T us[:, t - t_wash] = u.T # Load Conceptor if load: R = np.dot(xs, xs.T) / t_learn U, S, V = np.linalg.svd(R, full_matrices=True) S = np.diag(S) Snew = (np.dot(S, np.linalg.inv(S + (self.alpha ** -2) * I))) self.C.append(np.dot(U, np.dot(Snew, V))) xPrevious = np.zeros((self.N, t_learn)) xPrevious[:, 1:] = xs[:, 0:-1] patternStates[:, i * t_learn:(i + 1) * t_learn] = xs patternPreviousStates[:, i * t_learn:(i + 1) * t_learn] = xPrevious patternInputs[:, i * t_learn:(i + 1) * t_learn] = us """ Output Training """ self.W_out = fun.ridgeRegression(patternStates.T, patternInputs.T, alpha_wout) """ Loading """ target = np.arctanh(patternStates.clip(-.99999999, .99999999)) - np.tile(self.W_bias, (1, self.numPatts * t_learn)) self.W = fun.ridgeRegression(patternPreviousStates.T, target.T, alpha_wload).T patternStates = np.reshape(patternStates, [self.numPatts, self.N, t_learn]) patternInputs = np.reshape(patternInputs, [self.numPatts, self.numInputDims, t_learn]) return patternStates, patternInputs ''' Use Conceptors to recall learned patterns @param t_recall: length of recalled patterns @return recalled signal per learned pattern ''' def recall(self, t_recall = 200): recalls = [] #Per stored pattern for i in range(self.numPatts): Cc = self.C[i] #seed network x = 0.5*np.random.randn(self.N,1) recall = np.zeros((t_recall, self.numInputDims)) #Apply Conceptor for t in range(t_recall): x = np.tanh(np.dot(self.W,x)+self.W_bias) x = np.dot(Cc,x) y = np.dot(x.T,self.W_out) recall[t]=y recalls.append(recall) return recalls ''' Run Reservoir by driving it with patterns and learn random feature conceptors @param patterns: stimuli to drive the network @param t_learn: number of time steps to collect network states @param t_wash: number of time steps to drive the network withput collecting states @param alpha_wout: weight for ridge regression of output weights @param alpha_wload: weight for ridge regression of network weights after pattern loading @return network states per pattern and inputs per pattern ''' def runRF(self, patterns, t_learn = 1000, t_wash = 0, alpha_wout = 1., alpha_wload = 0.1): self.numPatts = len(patterns) self.K = 5 * self.N self.F = np.random.randn(self.K, self.N) self.G = np.random.randn(self.N, self.K) sr = np.max(np.abs(scipy.linalg.eigvals(np.dot(self.F,self.G)))) self.F *= np.sqrt(self.NetSR)/np.sqrt(sr) self.G *= np.sqrt(self.NetSR)/np.sqrt(sr) """ Regularization of G """ t_init = 2000 t_start = t_init//5 Zs = np.zeros((self.K, t_init-t_start)) z = np.zeros((self.K,1)) r = np.zeros((self.N,1)) for t in range(t_init): u = 2.*np.random.rand(self.numInputDims,1) - 1 zPrevious = z r = np.tanh(np.dot(self.G,z) + np.dot(self.W_in,u) +self.W_bias) z = np.dot(self.F,r) if (t > t_start): Zs[:,t-t_start] = zPrevious.squeeze() self.G = fun.ridgeRegression(Zs.T,np.dot(self.G,Zs).T,0.1,False).T self.C = [] self.Z_list = [] patternStates = np.zeros((self.N,self.numPatts*t_learn)) patternStatesPrevious = np.zeros((self.K,self.numPatts*t_learn)) patternInputs = np.zeros((self.numInputDims,self.numPatts*t_learn)) #Iterate over different stimuli for i,p in enumerate(patterns): z = np.zeros((self.K,1)) rs = np.zeros((self.N,t_learn)) zPreviousColl = np.zeros((self.K,t_learn)) us = np.zeros((self.numInputDims,t_learn)) c = np.ones((self.K,1)) for t in range(t_learn + t_wash): u = p[t] r = np.tanh(np.dot(self.G,z) + np.dot(self.W_in,u[:,None]) + self.W_bias) zPrevious = z z = c*np.dot(self.F,r) if (t > t_wash): zPreviousColl[:, t - t_wash] = zPrevious.squeeze() rs[:, t - t_wash] = r.squeeze() us[:, t - t_wash] = u.squeeze() c = np.mean(zPreviousColl**2, axis = 1)*(np.mean(zPreviousColl**2, axis = 1)+np.ones(self.K)*3**-2)**-1 self.C.append(c) self.Z_list.append(zPreviousColl) patternStates[:,i*t_learn:(i+1)*t_learn] = rs patternStatesPrevious[:,i*t_learn:(i+1)*t_learn] = zPreviousColl patternInputs[:,i*t_learn:(i+1)*t_learn] = us """ Output Training """ self.W_out = fun.ridgeRegression(patternStates.T, patternInputs.T, alpha_wout).T self.G = fun.ridgeRegression(patternStatesPrevious.T,np.dot(self.G,patternStatesPrevious).T,alpha_wload,False).T """ Loading """ self.D = fun.ridgeRegression(patternStatesPrevious.T,patternInputs.T,alpha_wload,False).T return patternStates, patternInputs ''' Use Random Feature Conceptors to recall learned patterns @param t_recall: length of recalled patterns @return recalled signal per learned pattern ''' def recallRF(self, t_recall = 200): recalls = [] t_wash = 10 for i in range(self.numPatts): z = np.zeros((self.K,1)) recall = np.zeros((t_recall, self.numInputDims)) Cc = self.C[i] for t in range(t_recall + t_wash): r = np.tanh(np.dot(self.G,z) + np.dot(self.W_in,np.dot(self.D,z)) + self.W_bias) z = Cc[:,None]*np.dot(self.F,r) if t > t_wash: recall[t-t_wash]= np.dot(self.W_out,r).squeeze() recalls.append(recall) return recalls ''' Run Reservoir by driving it with patterns and learn neuron-neuron recurrent weight matrix @param patterns: stimuli to drive the network @param tgtresps: target response for the network @param J: recurrent weight matrix @param w_in: input weights @param w_out: output weights @return error over training ''' def runTRIAL(self, pattern, rs, PHASE=params.TESTING): dtdivtau = 1 / self.tau TRIALTIME=pattern.shape[1] x_trace = np.zeros(self.N) modul = np.zeros(self.N) modulmarker = np.zeros(self.N) # We use native-C array hebbmat for fast computations within the loop, then transfer it back to Eigen matrix hebb for plasticity computations hebb = np.zeros((self.N, self.N)) r = np.zeros(self.N) input = np.zeros(self.Nin) hebb[:, :] = 0 r[:] = 0 # Initialization of network activity with moderate random noise. Decreases performance a bit, but more realistic. x = np.random.random(self.N) * 2 - 1 x *= .1 x[1] = 1.0 x[10] = 1.0 x[11] = -1.0 # x(12) = 1.0; # Biases for nn in range(self.N): r[nn] = np.tanh(x[nn]) for numiter in range(TRIALTIME): input[:] = 0; #input[1] = patterns[trialtype][1, numiter]; #input[2] = patterns[trialtype][2, numiter]; input[1] = pattern[1, numiter] input[2] = pattern[2, numiter] if input[1] > 0: inp1 = 1 if input[2] > 0: inp2 = 1 rprev = r lateral_input = self.J.dot(r) total_exc = lateral_input + self.win.dot(input) # Exploratory perturbations modul[:] = 0 if params.MODULTYPE == "UNIFORM": # Apply a modulation to the entire network with probability PROBAMODUL - Not used for these simulations. if (np.random.random(1) < params.PROBAMODUL) & (numiter > 3): randVec(modul) modul *= params.ALPHAMODUL total_exc += modul modulmarker[:] = 1 else: modulmarker[:] = 0 elif params.MODULTYPE == "DECOUPLED": # Perturb each neuron independently with probability PROBAMODUL modulmarker[:] = 0 for nn in range(self.N): if (np.random.random(1) < params.PROBAMODUL) and (numiter > 3): modulmarker[nn] = 1 modul[nn] = (-1.0 + 2.0 * np.random.random(1)) modul *= params.ALPHAMODUL total_exc += modul else: raise ValueError("Which modulation type?") '''EQUATION 1: Ecitations update''' # Compute network activations x += dtdivtau * (-x + total_exc) x[1] = 1.0 x[10] = 1.0 x[11] = -1.0 # x(12) = 1.0; # Biases # Actual responses = tanh(activations) '''EQUATION 2: Response''' r = np.tanh(x) rs[:, numiter] = r # Okay, now for the actual plasticity. # First, compute the fluctuations of neural activity (detrending / high-pass filtering) delta_x = x - x_trace; # delta_x_sq = delta_x.array() * delta_x.array().abs(); # delta_x_cu = delta_x.array() * delta_x.array() * delta_x.array(); x_trace = params.ALPHATRACEEXC * x_trace + (1.0 - params.ALPHATRACEEXC) * x if params.DEBUG > 0: if modulmarker.any() or (DEBUG == 2): print(delta_x_sq.norm(), " ", modul.norm(), " ", total_exc.norm(), " ", x.norm(), " ", (total_exc - x).norm(), \ " Alignment deltax/total_exc (inc. modul):", delta_x.dot(total_exc) / (delta_x.norm() * total_exc.norm()), \ " Alignment deltax/modul:", delta_x.dot(modul) / (delta_x.norm() * modul.norm()), \ " Align deltax_sq/modul:", delta_x_sq.dot(modul) / (delta_x_sq.norm() * modul.norm())) # Compute the Hebbian increment to be added to the eligibility trace (i.e. potential weight change) for this time step, based on inputs and fluctuations of neural activity if (PHASE == params.LEARNING) & (numiter > 2): if params.METHOD == 'DELTAX': # Method from the paper. Slow, but biologically plausible (-ish). # # The Hebbian increment at every timestep is the inputs (i.e. rprev) times the (cubed) fluctuations in activity for each neuron. # More plausible, but slower and requires a supralinear function to be applied to the fluctuations (here cubing, but sign-preserving square also works) '''EQUATION 3: Hebbian eligibility''' incr = np.outer(rprev, delta_x) hebb += incr * incr * incr elif (params.METHOD == "NODEPERT"): # Node-perturbation. # # The Hebbian increment is the inputs times the # perturbation itself. Node-perturbation method, similar to # Fiete & Seung 2006. Much faster # because you only compute the Hebbian # increments in the few timesteps at which a # perturbation actually occurs. for n2 in range(NBNEUR): if modulmarker[n2] != 0: for n1 in range(NBNEUR): hebb[n1][n2] += rprev[n1] * modul[n2] else: print("Which method??") # return -1; # Trial finished! return hebb, rs ''' Run Reservoir by driving it with patterns and learn neuron-neuron recurrent weight matrix @param patterns: stimuli to drive the network @param tgtresps: target response for the network @param J: recurrent weight matrix @param w_in: input weights @param w_out: output weights @return error over training ''' def runHebbian(self, patterns, tgtresps, NBPATTERNS, PHASE=params.TESTING): NBTRIALS=patterns.shape[0] NBIN=patterns.shape[1] TRIALTIME=patterns.shape[2] dJ = np.zeros((self.N, self.N)) meanerrs = np.zeros(NBTRIALS) rs = np.zeros((self.N, TRIALTIME)) meanerrtrace = np.zeros(NBPATTERNS) for numtrial in range(NBTRIALS): trialtype = numtrial % NBPATTERNS hebb, rs = self.runTRIAL(patterns[trialtype], rs, PHASE=PHASE) # Compute error for this trial EVALTIME = 200 err = rs[0] - tgtresps[trialtype][0] err = err[(TRIALTIME - EVALTIME):TRIALTIME] # Error is only computed over the response period, i.e. the last EVALTIME ms. meanerr = sum(abs(err)) / float(EVALTIME) # Compute the actual weight change, based on eligibility trace and the relative error for this trial: if (PHASE == params.LEARNING) & (numtrial > 100): # Note that the weight change is the summed Hebbian increments, multiplied by the relative error, AND the mean of recent errors for this trial type - this last multiplication may help to stabilize learning. '''EQUATION 4: Weight change''' # Minimum and maximum change, learning rate, eligibility trace, current Hebbian eligibility dJ = np.maximum(-params.MAXDW * np.ones((self.N, self.N)), np.minimum(params.MAXDW * np.ones((self.N, self.N)), np.transpose( -params.ETA * meanerrtrace[trialtype] * hebb * (meanerr - meanerrtrace[trialtype]) ))) self.J += dJ '''EQUATION 5: Expected reward''' meanerrtrace[trialtype] = params.ALPHATRACE * meanerrtrace[trialtype] \ + (1.0 - params.ALPHATRACE) * meanerr; # eligibility trace EQUATION 3 meanerrs[numtrial] = meanerr # Display stuff, save files. if PHASE == params.LEARNING: if numtrial % 3000 < 8: myfile = open("rs" + str((numtrial / 2) % 4) + ".txt", 'w') np.savetxt(myfile, rs.transpose()) myfile.close() # myfile.write(rs.transpose()) myfile = open("rs" + str(trialtype) + ".txt", 'w') np.savetxt(myfile, rs.transpose()) myfile.close() # myfile.write(rs.transpose()) myfile = open("rs" + str(numtrial % 3000) + ".txt", 'w') np.savetxt(myfile, rs.transpose()) myfile.close() # myfile.write(rs.transpose()) if (numtrial % 1000 == 0) or (numtrial == NBTRIALS - 1): if numtrial == 0: # Store the initial (random) weights. myfile = open("J_" + str(numtrial) + params.SUFFIX + ".txt", 'w') myfile.write(self.J) myfile.close() saveWeights(self.J, "J_" + str(numtrial) + params.SUFFIX + ".dat") myfile = open("J" + params.SUFFIX + ".txt", 'w') myfile.write(self.J) myfile.close() myfile = open("win" + params.SUFFIX + ".txt", 'w') myfile.write(self.win) myfile.close() saveWeights(self.J, "J" + params.SUFFIX + ".dat") saveWeights(self.win, "win" + params.SUFFIX + ".dat") # win doesn't change over time. myfile = open("errs" + params.SUFFIX + ".txt", 'w') np.savetxt(myfile, meanerrs[0:numtrial]) myfile.close(); # myfile.write(meanerrs[0:numtrial]) # if (numtrial % (NBPATTERNS * 100) < 2*NBPATTERNS) if numtrial % 200 < 2 * NBPATTERNS: print numtrial, "- trial type: " + str(trialtype), # print(", responses : ", zout); # print(", time-avg responses for each pattern: ", zouttrace); # print(", sub(abs(wout)): ", sum(abs(wout))); print ", hebb(0,1:3): " + str(hebb[0:3, 0].transpose()), print ", meanerr: " + str(meanerr), # print(", wout(0,1:3): ",wout[0,0:4]) print ", r(0,1:6): " + str(rs[0:5,TRIALTIME-1].transpose()), print ", dJ(0,1:4): " + str(dJ[0, 0:3]) elif PHASE == params.TESTING: print "- trial type: " + str(trialtype), print " r[0]: " + str(rs[0][TRIALTIME-1]) israndw = "" if (params.RANDW): israndw = "_RANDW" myfile = open( "rs_long" + israndw + "_type" + str(trialtype) + "_" + str(int(numtrial / NBPATTERNS)) + params.SUFFIX + ".txt", 'w') # np.savetxt(myfile, "\n") np.savetxt(myfile, rs.transpose()) # myfile.write(rs.transpose()) myfile.close() # myfile.open("rs_long_type"+trialtype+"_"+int(numtrial/NBPATTERNS) + ".txt", ios::trunc | ios::out); myfile << endl << rs.transpose() << endl; myfile.close() print("Done learning ...") print(np.mean(self.J), " ", sum(abs(self.J)), " ", np.amax(self.J)) # print(mean(wout) << " ",sum(abs(J))," ",wout.maxCoeff()) return meanerrs <file_sep>/Documents/RSem/code/force_simple_examples/force_external_feedback_loop.py import numpy as np import scipy import struct import sys import matplotlib.pyplot as plt from tools import randJ # FORCE.py # # This function generates the sum of 4 sine waves in figure 2D using the architecture of figure 1A with the RLS # learning rule. # # written by <NAME> plt.isinteractive() np.random.seed(0) #linewidth = 3; #fontsize = 14; #fontweight = 'bold'; N = 1000 p = 0.1 g = 1.5 # g greater than 1 leads to chaotic networks. alpha = 1.0 nsecs = 1440 dt = 0.1 learn_every = 2 force=1 # on = 1, off = 0 reset=0 # on = 1, off = 0 symmetric=0 # on = 1, off = 0 #scale = 1.0/np.sqrt(p*N) W=np.zeros((N,N)) W = randJ(W,p,g) if symmetric: for i in range(N): for j in range(i,N): W[i,j]=W[j,i] wo = 2.0*(np.random.uniform(0,1,(N,1))-0.5)/np.sqrt(p*N) # np.zeros((N,1)) dw = np.zeros((N,1)) wf = force*2.0*(np.random.uniform(0,1,(N,1))-0.5) # range -1.0-1.0 ? print(' N: ', N) print(' g: ', g) print(' p: ', p) print(' alpha: ', alpha) print(' learn_every: ', learn_every) simtime = np.arange(0, nsecs-dt, dt) #0:dt:nsecs-dt; simtime_len = simtime.shape[0] simtime2 = np.arange(1*nsecs, 2*nsecs-dt, dt) #1*nsecs:dt:2*nsecs-dt; amp = 1.3 freq = 1/60. ft = (amp/1.0)*np.sin(1.0*np.pi*freq*simtime) + \ (amp/2.0)*np.sin(2.0*np.pi*freq*simtime) + \ (amp/6.0)*np.sin(3.0*np.pi*freq*simtime) + \ (amp/3.0)*np.sin(4.0*np.pi*freq*simtime) ft = force*ft/1.5 ft2 = (amp/1.0)*np.sin(1.0*np.pi*freq*simtime2) + \ (amp/2.0)*np.sin(2.0*np.pi*freq*simtime2) + \ (amp/6.0)*np.sin(3.0*np.pi*freq*simtime2) + \ (amp/3.0)*np.sin(4.0*np.pi*freq*simtime2) ft2 = force*ft2/1.5 xt = np.zeros((N, simtime_len)) rt = np.zeros((N, simtime_len)) zt = np.zeros(simtime_len).T xpt = np.zeros((N, simtime_len)) rpt = np.zeros((N, simtime_len)) zpt = np.zeros(simtime_len).T wot = np.zeros(simtime_len) dwt = np.zeros(simtime_len) x0 = 0.5*np.random.normal(0, 1, (N, 1)) z0 = 0.5*np.random.normal(0, 1, (1, 1)) x = x0 r = np.tanh(x) z = z0 fig, axes = plt.subplots(ncols=2, nrows=3, figsize=(35, 20)) ax00 = plt.subplot2grid((3,4), (0,0), colspan=2) ax10 = plt.subplot2grid((3,4), (1,0), colspan=2) ax20 = plt.subplot2grid((3,4), (2,0)) ax21 = plt.subplot2grid((3,4), (2,1)) ax02 = plt.subplot2grid((3,4), (0,2), colspan=2) ax12 = plt.subplot2grid((3,4), (1,2), colspan=2) ax22 = plt.subplot2grid((3,4), (2,2)) ax23 = plt.subplot2grid((3,4), (2,3)) ax00.plot(simtime, ft) ax02.plot(simtime2, ft2) ti = -1 P = force*(1.0/alpha)*np.eye(N) for t in simtime: ti = ti+1 # simulation timestep, so x(t) and r(t) are created. x = (1.0-dt)*x + np.dot(W,(r*dt)) + wf*(z*dt) r = np.tanh(x) z = np.dot(wo.T,r) if np.mod(ti, learn_every) == 0: # RLS rule: update inverse correlation matrix k = np.dot(P,r) kT = np.dot(r.T,P) rPr = np.dot(r.T,k) c = 1.0/(1.0 + rPr) dP = np.outer(k,kT)*c P = P - dP # update the error for the linear readout e = z-ft[ti] # update the output weights dw = -e*np.dot(P,r) #-e*k*c wo = wo + dw # Store the output of the system zt[ti] = z xt[:,ti] = np.squeeze(x) rt[:,ti] = np.squeeze(r) wot[ti] = np.sqrt(np.dot(wo.T,wo)) dwt[ti] = np.sqrt(np.dot(dw.T,dw))#/np.dot(wo.T,wo)) # printing results if np.mod(ti, nsecs/2) == 0 or ti == simtime_len-1: print('time: ', t, '.') ax00.plot(simtime, zt, 'ro') #ax00.set_ylim([-2,2]) ax10.plot(simtime, dwt) plt.show(block=False) plt.pause(0.5) error_avg = sum(abs(zt-ft))/simtime_len print 'Training MAE: ', error_avg print 'Calculating statistics' cortime_len=np.int(200/dt) # last x seconds used for correlations x_auto = np.zeros((N, np.int(cortime_len))) x_cross = np.zeros((N, N)) r_auto = np.zeros((N, np.int(cortime_len))) r_cross = np.zeros((N, N)) x_norm_auto = np.zeros((N, np.int(cortime_len))) x_norm_cross = np.zeros((N, N)) r_norm_auto = np.zeros((N, np.int(cortime_len))) r_norm_cross = np.zeros((N, N)) for i in range(N): if np.mod(i, 100) == 0: print 'neuron', i for tau in range(np.int(cortime_len)): x_auto[i, tau] = np.dot(xt[i, ti-2*cortime_len:ti], np.roll(xt[i, ti-2*cortime_len:ti], tau).T) r_auto[i, tau] = np.dot(rt[i, ti-2*cortime_len:ti], np.roll(rt[i, ti-2*cortime_len:ti], tau).T) for j in range(N): x_cross[i, j] = np.dot(xt[i, ti-2*cortime_len:ti], xt[j, ti-2*cortime_len:ti].T) r_cross[i, j] = np.dot(rt[i, ti-2*cortime_len:ti], rt[j, ti-2*cortime_len:ti].T) x_norm_auto[i, :] = x_auto[i, :] / x_auto[i, 0] r_norm_auto[i, :] = r_auto[i, :] / r_auto[i, 0] x_norm_cross[i, :] = x_cross[i, :] / x_cross[i, i] r_norm_cross[i, :] = r_cross[i, :] / r_cross[i, i] x_sum_auto=np.sum(x_auto, axis=0) r_sum_auto=np.sum(r_auto, axis=0) x_avg_auto=x_sum_auto/x_sum_auto[0] r_avg_auto=r_sum_auto/r_sum_auto[0] ax20.plot(simtime[0:np.int(cortime_len)], x_norm_auto.T) ax20.plot(simtime[0:np.int(cortime_len)], x_avg_auto.T, 'ro') ax21.matshow(x_norm_cross, cmap='gray') plt.show(block=False) plt.pause(0.5) #plt.savefig('figure_sim.png', bbox_inches='tight', dpi=300) print 'Now testing... please wait.' if reset: x0 = 0.5*np.random.normal(0, 1, (N, 1)) z0 = 0.5*np.random.normal(0, 1, (1, 1)) x = x0 r = np.tanh(x) z = z0 # Now test. ti = -1 #ti_test=ti for t in simtime: ti = ti+1 # sim, so x(t) and r(t) are created. x = (1.0-dt)*x + np.dot(W,(r*dt)) + np.dot(wf,(z*dt)) r = np.tanh(x) z = np.dot(wo.T,r) zpt[ti] = z xpt[:,ti] = np.squeeze(x) rpt[:,ti] = np.squeeze(r) if np.mod(ti, nsecs / 2) == 0 or ti == simtime_len-1: print('time: ', t, '.') ax02.plot(simtime2, zpt, 'bo') plt.show(block=False) plt.pause(0.5) error_avg = sum(abs(zpt[0:]-ft2))/simtime_len print 'Testing MAE: ', error_avg print 'Calculating statistics' cortime_len=np.int(200/dt) # last x seconds used for correlations xp_auto = np.zeros((N, np.int(cortime_len))) xp_cross = np.zeros((N, N)) rp_auto = np.zeros((N, np.int(cortime_len))) rp_cross = np.zeros((N, N)) xp_norm_auto = np.zeros((N, np.int(cortime_len))) xp_norm_cross = np.zeros((N, N)) rp_norm_auto = np.zeros((N, np.int(cortime_len))) rp_norm_cross = np.zeros((N, N)) for i in range(N): if np.mod(i, 100) == 0: print 'neuron', i for tau in range(np.int(cortime_len)): xp_auto[i, tau] = np.dot(xpt[i, ti-2*cortime_len:ti], np.roll(xpt[i, ti-2*cortime_len:ti], tau).T) rp_auto[i, tau] = np.dot(rpt[i, ti-2*cortime_len:ti], np.roll(rpt[i, ti-2*cortime_len:ti], tau).T) for j in range(N): xp_cross[i, j] = np.dot(xpt[i, ti-2*cortime_len:ti], xpt[j, ti-2*cortime_len:ti].T) rp_cross[i, j] = np.dot(rpt[i, ti-2*cortime_len:ti], rpt[j, ti-2*cortime_len:ti].T) xp_norm_auto[i, :] = xp_auto[i, :] / xp_auto[i, 0] rp_norm_auto[i, :] = rp_auto[i, :] / rp_auto[i, 0] xp_norm_cross[i, :] = xp_cross[i, :] / xp_cross[i, i] rp_norm_cross[i, :] = rp_cross[i, :] / rp_cross[i, i] xp_sum_auto=np.sum(xp_auto, axis=0) rp_sum_auto=np.sum(rp_auto, axis=0) xp_avg_auto=xp_sum_auto/xp_sum_auto[0] rp_avg_auto=rp_sum_auto/rp_sum_auto[0] ax22.plot(simtime[0:np.int(cortime_len)], xp_norm_auto.T) ax22.plot(simtime[0:np.int(cortime_len)], xp_avg_auto.T, 'ro') ax23.matshow(xp_norm_cross, cmap='gray') plt.show(block=False) plt.pause(0.5) plt.savefig('figure_sim.png', bbox_inches='tight', dpi=300) tt=3 <file_sep>/Documents/RSem/code/v0py/main.py import numpy as np import scipy import struct import sys import matplotlib.pyplot as plt from reservoir import Reservoir from tools import randJ from tools import readWeights from tools import saveWeights from ploterr_single import ploterr_single from decodetomdist import decodetomdist from plotdecode import plotdecode from plotpca import plotpca import params np.random.seed(0) NBNEUR = 200 NBIN = 3 # Number of inputs. Input 0 is reserved for a 'go' signal that is not used here. NBOUT = 1 # Only 1 output neuron NBTRIALS = 1007 #20407; # ~10K trials sufficient to get good convergence (95% correct on a binary criterion is reached within ~1000 trials, but performance keeps improving after that). Should really be 100K if you have time. TRIALTIME = 1000 # 200 timesteps longer patterns STARTSTIM1 = 1; TIMESTIM1 = 200 STARTSTIM2 = 400; TIMESTIM2 = 200 # s-back version #STARTSTIM2 = 200; TIMESTIM2 = 200 #STARTSTIM3 = 400; TIMESTIM3 = 200 NBPATTERNS = 4 patterns=np.zeros((NBPATTERNS, NBIN, TRIALTIME)) tgtresps=np.zeros((NBPATTERNS, TRIALTIME)) # Remember that input channel 0 is reserved for the (unused) 'go' signal # Here we define the inputs to be fed to the network, and the expected response, for each condition. # For the sequential-XOR problem (NBPATTERNS to 4, TRIALTIME and eval. time as appropriate): # We encode the input patterns as matrices with NBIN rows and TRIALTIME columns, which we fill with the appropriate input values at every time step and for each input channel patterns[0][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[0][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1 # AA r=-1 patterns[1][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[1][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1 # AB r=1 patterns[2][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[2][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1 # BA r=1 patterns[3][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[3][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1 # BB r=-1 # Target responses - what the network ought to produce (note that only the last EVALTIME timesteps are actually relevant - see below) tgtresps[0][:]=-.98 tgtresps[1][:]=.98 tgtresps[2][:]=.98 tgtresps[3][:]=-.98 # 2-back version #patterns[0][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[0][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[0][1,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # AAA r=-1 #patterns[1][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[1][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[1][1,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # ABA r=-1 #patterns[2][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[2][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[2][1,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # BAA r=1 #patterns[3][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[3][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[3][1,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # BBA r=1 #patterns[4][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[4][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[4][2,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # AAB r=1 #patterns[5][1,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[5][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[5][2,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # ABB r=1 #patterns[6][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[6][1,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[6][2,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # BAB r=-1 #patterns[7][2,STARTSTIM1: STARTSTIM1+TIMESTIM1]=1; patterns[7][2,STARTSTIM2: STARTSTIM2+TIMESTIM2]=1; patterns[7][2,STARTSTIM3: STARTSTIM3+TIMESTIM3]=1 # BBB r=-1 # Target responses - what the network ought to produce (note that only the last EVALTIME timesteps are actually relevant - see below) #tgtresps[0][:]=-.98 #tgtresps[1][:]=-.98 #tgtresps[2][:]=.98 #tgtresps[3][:]=.98 #tgtresps[4][:]=.98 #tgtresps[5][:]=.98 #tgtresps[6][:]=-.98 #tgtresps[7][:]=-.98 # Define RNN following Sompolinksy (Sompolinky et al, 'Chaos in random neural networks', 1988) rnn_model=Reservoir(N=NBNEUR, Nin=NBIN, tau=30.) print(rnn_model.J[0,0]," ",rnn_model.win[1,1]) train_patterns=np.zeros((NBTRIALS, rnn_model.Nin, TRIALTIME)) # NBTRIALS = n * NBPATTERNS e.g. 0:1000 = 125 * 0:7 train_tgtresps=np.zeros((NBTRIALS, TRIALTIME)) for numtrial in range(NBTRIALS): trialtype=numtrial%NBPATTERNS train_patterns[numtrial,:]=patterns[trialtype] train_tgtresps[numtrial,:]=tgtresps[trialtype] params.tau = rnn_model.tau params.SUFFIX = "_G" + str(params.G) + "_MAXDW" + str(params.MAXDW) + "_ETA" + str(params.ETA) + "_ALPHAMODUL" + str(params.ALPHAMODUL) + "_PROBAMODUL" + str(params.PROBAMODUL) + "_SQUARING" +str(params.SQUARING) + "_MODULTYPE-" + params.MODULTYPE + \ "_ALPHATRACE" + str(params.ALPHATRACE) + "_METHOD-" + params.METHOD + "_ATRACEEXC" + str(params.ALPHATRACEEXC) + "_TAU" + str(params.tau) + \ "_RNGSEED" + \ str(params.RNGSEED) #"_INPUTMULT" +str(INPUTMULT) + print(params.SUFFIX) # Run the RNN with Miconi's learning rules (Miconi, 'Flexible decision making in recurrent neural networks trained with a biologically plausible rule', 2016) error = rnn_model.runHebbian(train_patterns, train_tgtresps, NBPATTERNS, PHASE=params.LEARNING) ploterr_single(NBTRIALS-1) # For the TESTING phase, read the weights from a previously saved file: readWeights(rnn_model.J, "J" + params.SUFFIX + ".dat") readWeights(rnn_model.win, "win" + params.SUFFIX + ".dat") # win doesn't change over time. # Less patterns for testing NBTRIALS = 20*NBPATTERNS test_patterns=np.zeros((NBTRIALS, rnn_model.Nin, TRIALTIME)) # NBTRIALS = n * NBPATTERNS e.g. 0:1000 = 125 * 0:7 test_tgtresps=np.zeros((NBTRIALS, TRIALTIME)) for numtrial in range(NBTRIALS): trialtype=numtrial%NBPATTERNS test_patterns[numtrial,:]=patterns[trialtype] test_tgtresps[numtrial,:]=tgtresps[trialtype] # Test the RNN, using the same RNN setup as in the learning phase apart from the learning rules error = rnn_model.runHebbian(test_patterns, test_tgtresps, NBPATTERNS, PHASE=params.TESTING) # Postprocessing analysis plots decodetomdist() plotdecode() plotpca() #rnn_model.learnConceptor(X) # Learn Conceptor from recorded neuron activity patterns X <file_sep>/Documents/RSem/code/v0py/params.py TESTING = 777 LEARNING = 666 #NBPATTERNS = 8 # 2-back # Here you choose which learning method to use: # For faster, but less biologically plausible method (simple node-perturbation # method, similar to Fiete & Seung 2006), uncomment this: # It is faster because you only compute the # Hebbian increment on the few timesteps where a perturbation actually # occurs. # RNN parameters PROBACONN = 1.0; # Dense connectivity G = 1.5; # Early chaotic regime. Chaos ma non troppo. tau=30. # Update rule prameters # For slower, but more biologically plausible method (as described in the paper, see http:#biorxiv.org/content/early/2016/06/07/057729 ): METHOD = 'DELTAX'; # 'NODEPERT'; ETA = .1; # Learning rate MODULTYPE = 'DECOUPLED'; # Modulations (exploratory perturbations) are applied independently to each neuron. ALPHAMODUL = 16.0; # Note that TAU = 30ms, so the real ALPHAMODUL is 16.0 * dt / TAU ~= .5 MAXDW = 3e-4; PROBAMODUL = .003; RNGSEED = 0; DEBUG = 0; ALPHATRACE = .75; ALPHATRACEEXC = 0.05; SQUARING = 1; RANDW = 0; # Suffix for output files SUFFIX = "_G" + str(G) + "_MAXDW" + str(MAXDW) + "_ETA" + str(ETA) + "_ALPHAMODUL" + str(ALPHAMODUL) + "_PROBAMODUL" + str(PROBAMODUL) + "_SQUARING" +str(SQUARING) + "_MODULTYPE-" + MODULTYPE + \ "_ALPHATRACE" + str(ALPHATRACE) + "_METHOD-" + METHOD + "_ATRACEEXC" + str(ALPHATRACEEXC) + "_TAU" + str(tau) + \ "_RNGSEED" + \ str(RNGSEED); <file_sep>/Documents/RSem/code/v0py/functions.py import numpy as np import scipy.sparse import scipy.linalg from PIL import Image, ImageDraw ''' Get all data indices for a given digit @param labels: dict of targets @param digit: number to be found @return indices ''' def getDigit(labels, digit): return [i for i,v in enumerate(labels) if np.where(v==1)[0][0] == digit] ''' Concatenate data sequences @param data @param indx: indices of data to be concatenated @return stacked data ''' def concatDigits(data, indx): stacked = np.vstack((data[indx[0]],data[indx[0]])) for i in indx[2:]: stacked = np.vstack((stacked,data[i])) return stacked ''' Draw interpolated digit @param data: interpolated digit @return image ''' def paintInterpolated(data): img = np.zeros((28,28)) im = Image.new('RGB', (28, 28), (255, 255, 255)) draw = ImageDraw.Draw(im) for i in range(data.shape[0]-1): draw.line([(data[i+1][0],data[i+1][1]), (data[i][0],data[i][1])], fill=0) return im ''' Separate Digits at separation marker @param data @return separated digits ''' def separateDigits(data): separated = [] digit = [] for i,row in enumerate(data): digit.append(row) if i%12==0: separated.append(np.array(digit)) digit = [] return separated ''' Transform data sequence into image @param data: mnist sequence @return img: mnist image ''' def imgSequence(data): img = np.zeros((28,28)) coordinates = data[:,0:2] loc = [0,0] for coordinate in coordinates: loc += coordinate img[loc[1],loc[0]] = 1 return img ''' Downsample data by interpolation. Removes last to dimensions as all digits now have the same length. @param data @param length: Number of final points @return interpolated data ''' def interpolDigits(data,length): newData = [] for d in data: d = d[:,0:2] l = round(d.shape[0] / length) new = [d[0]] for i in range(1,d.shape[0],l): row = np.array(new[-1]) for j in range(l): if i+j < d.shape[0]: row += d[i+j] new.append(row) new = np.array(new) while new.shape[0] < length: new = np.append(new,new[-1][None,:], axis=0) if new.shape[0] > length: new = new[:length] delimiter = np.zeros((new.shape[0],1)) delimiter[-1] = 1 newData.append(np.concatenate((new,delimiter),axis=1)) return newData ''' Create sparse random connectivity matrix @param m: number of rows @param n: number of columns @param density: defines sparseness of the matrix @return sparse random matrix ''' def sprandn(m, n, density): #Number of non-zero elements has to be positive #but can be at most the number of matrix entries nnz = max(0, min(int(m*n*density), m*n)) seq = np.random.permutation(m*n)[:nnz] data = np.random.randn(nnz) return scipy.sparse.csr_matrix((data, (seq/m,seq%n)), shape=(m,n)).todense() ''' Compute the spectral radius, i.e. largest absolute eigenvalue, of a matrix @param m: matrix @return spectral radius ''' def getSpecRad(m): specRad, largestEigenvec = np.abs(scipy.linalg.eigh(m,eigvals=(m.shape[0]-1, m.shape[0]-1))) return specRad[0] ''' Implement regression with Tikhonov regularization @param A: design Matrix @param b: targets @param alpha: regularization @return regression weights ''' def ridgeRegression(A, b, alpha, inv=True): aI = alpha * np.eye(A.shape[1]) if inv: first = np.linalg.inv(np.dot(A.T, A) + aI) else: first = np.linalg.pinv(np.dot(A.T, A) + aI) return np.dot(first , np.dot(A.T, b)) ''' Calculate root mean squared error @param output @param targets @return rmse ''' def RMSE(output, target): error = target - output rmse = np.sqrt(np.mean(error**2, axis=1)) return rmse ''' Calculate logical AND between two Conceptor matrices. Calculations are done according to <NAME>'s technical report page 53. @param C: Conceptor Matrix @param B: Conceptor Matrix @return C and B ''' def AND(C,B): #Add noise for numerical stability of SVD C = C + np.random.normal(0,1e-6,C.shape) B = B + np.random.normal(0,1e-6,B.shape) epsilon = 1e-12 Uc,Sc,Vc = np.linalg.svd(C, full_matrices=True) Ub,Sb,Vb = np.linalg.svd(B, full_matrices=True) #Determine number of non-zero singular values RankC = np.linalg.matrix_rank(C,epsilon) RankB = np.linalg.matrix_rank(B,epsilon) #Get zero dimensions UcZeroDim = Uc[:, RankC:].squeeze() UbZeroDim = Uc[:, RankB:].squeeze() #Get Matrix with Columns that form orthonormal basis of R(C) and R(B) Br = np.dot(UcZeroDim,UcZeroDim.T) + np.dot(UbZeroDim,UbZeroDim.T) W,Sig,Wt = np.linalg.svd(B, full_matrices=True) RankSig = np.linalg.matrix_rank(Br, epsilon) W = W[:, RankSig:] #Calculate C + B - I arg = np.linalg.pinv(C,epsilon)+np.linalg.pinv(B,epsilon)-np.eye(len(C)) #Calculate W * (W' * (C + B - I) * W)^-1 * W' return np.dot(np.dot(W,np.linalg.inv(np.dot(W.T,np.dot(arg,W)))),W.T) ''' Calculate logical NOT of a Conceptor Matrix @param C: Conceptor @return I - C ''' def NOT(C): return np.eye(len(C)) - C ''' Calculate logical OR between two Conceptor Matrices. OR is calculated according to de Morgan's rule. @param C: Conceptor Matrix @param B: Conceptor Matrix @return C or B <==> -(-C and -B) ''' def OR(C,B): return NOT(AND(NOT(C), NOT(B)))
ab4af6a3163cc2c8550adbe7fe4cb217345c6b43
[ "Python" ]
8
Python
Germonda/backup
4a7877fd3e17241b2a9d381ba3f4fdb9780ce75e
953a1490027b129d2f162535318bd2c1144644a9
refs/heads/master
<repo_name>CypHry/MLP<file_sep>/makefile CXXFLAGS=-g -Iinc -Wall -pedantic -std=c++14 __start__: MLP ./MLP MLP: obj obj/main.o obj/layer.o obj/mlp.o g++ obj/main.o obj/layer.o obj/mlp.o -o MLP obj: mkdir obj/ obj/main.o: src/main.cpp inc/mlp.h g++ -c ${CXXFLAGS} -o obj/main.o src/main.cpp obj/layer.o: src/layer.cpp inc/layer.h g++ -c ${CXXFLAGS} -o obj/layer.o src/layer.cpp obj/mlp.o: src/mlp.cpp inc/mlp.h inc/training_item.h inc/neuron.h inc/layer.h g++ -c ${CXXFLAGS} -o obj/mlp.o src/mlp.cpp clean: rm -rf obj/ src/*~ inc/*~ MLP<file_sep>/src/main.cpp #include <iostream> #include <cassert> #include "mlp.h" const unsigned int MAX_ITERATIONS = 30; void XOR_training(mlp& mlp_) { std::cout << "XOR training started" << std::endl; std::vector<training_item> training_set = { training_item({0, 0}, 0), training_item({1, 0}, 1), training_item({0, 1}, 1), training_item({1, 1}, 0) }; } int main() { mlp mlp_(2,{2}, 1, {1, 1}); mlp_.fill(); mlp_.get_all_weights(); std::vector<double> result = mlp_.feedforward({1, 0}); std::cout<<result[0]<<std::endl; }<file_sep>/src/mlp.cpp #include "mlp.h" mlp::mlp(const unsigned int number_of_inputs, const std::vector<unsigned int> number_of_hidden_neurons, const unsigned int number_of_outputs, std::vector<double> biases, const double learning_rate) { if(!number_of_hidden_neurons.empty()) { std::vector<double> input_weights(number_of_hidden_neurons[0]); neuron input_neuron(input_weights); std::vector<neuron> input_neurons(number_of_inputs, input_neuron); std::shared_ptr<layer> input_layer = std::make_shared<layer>(input_neurons, biases[0]); layers.push_back(input_layer); for(unsigned int i = 0; i < number_of_hidden_neurons.size()-1; i++) { std::vector<double> hidden_weights(number_of_hidden_neurons[i+1]); neuron hidden_neuron(hidden_weights); std::vector<neuron> hidden_neurons(number_of_hidden_neurons[i], hidden_neuron); std::shared_ptr<layer> hidden_layer = std::make_shared<layer>(hidden_neurons, biases[i+1]); layers.push_back(hidden_layer); } std::vector<double> hidden_weights(number_of_outputs); neuron hidden_neuron(hidden_weights); std::vector<neuron> hidden_neurons(number_of_hidden_neurons.back(), hidden_neuron); std::shared_ptr<layer> hidden_layer = std::make_shared<layer>(hidden_neurons, biases[biases.size()-1]); layers.push_back(hidden_layer); } else { std::vector<double> input_weights(number_of_outputs); neuron input_neuron(input_weights); std::vector<neuron> input_neurons(number_of_inputs, input_neuron); std::shared_ptr<layer> input_layer = std::make_shared<layer>(input_neurons, biases[0]); layers.push_back(input_layer); } neuron output_neuron({1}); std::vector<neuron> output_neurons(number_of_outputs, output_neuron); std::shared_ptr<layer> output_layer = std::make_shared<layer>(output_neurons); layers.push_back(output_layer); } double mlp::dot_product(const std::vector<double>& vec1, const std::vector<double>& vec2) const { return std::inner_product(vec1.begin(), vec1.end(), vec2.begin(), 0.0); } const std::vector<double> mlp::feedforward(const std::vector<double>& input) { layers[0]->set_outputs(input); std::vector<double> outputs; double weighted_sum; for(unsigned int i = 1; i < layers.size(); i++) { for(unsigned int j = 0; j < layers[i]->get_neurons().size(); j++) { weighted_sum = dot_product(layers[i-1]->get_weights_vec(j), layers[i-1]->get_outputs()) + layers[i-1]->get_bias(); outputs.push_back(sigmoid(weighted_sum)); } layers[i]->set_outputs(outputs); make_empty(outputs); } return layers.back()->get_outputs(); } void mlp::train(const std::vector<training_item>& training_set) { std::vector<std::vector<double>> outputs_set; for(auto& item : training_set) outputs_set.push_back(feedforward(item.get_input())); } std::vector<double> mlp::squared_errors(const std::vector<double>& outputs, const std::vector<double>& expected_outputs) { std::vector<double> errors; for(unsigned int i = 0; i < outputs.size(); i++) errors.push_back(squared_error(outputs[i], expected_outputs[i])); return errors; } double mlp::hidden_error_derivative(const unsigned int& layer_index, const unsigned int& neuron_index) const noexcept { double weight_error_product = dot_product(layers[layer_index+1]->get_errors(), layers[layer_index]->get_neurons()[neuron_index]->get_weights_d()); return layers[layer_index]->get_neurons()[neuron_index]->get_output() * (1-layers[layer_index]->get_neurons()[neuron_index]->get_output()) * weight_error_product; } double mlp::output_error_derivative(const unsigned int& neuron_index, const double& expected_output) const noexcept { double output = layers.back()->get_neurons()[neuron_index]->get_output(); return (output - expected_output) * output * (1 - output); } double mlp::loss_function(const std::vector<double>& errors) const { double loss = 0.0; for(auto error : errors) loss += error; return loss/errors.size(); } void mlp::get_all_weights() const { for(auto layer_ : layers) { for(unsigned int i = 0; i < layer_->get_neurons().size(); i++) { for(unsigned int j = 0; j < layer_->get_neurons()[i]->get_weights().size(); j++) std::cout<<layer_->get_neurons()[i]->get_weights_d()[j]<<" "; std::cout<<std::endl; } } } <file_sep>/inc/layer.h #ifndef MLP_LAYER_H #define MLP_LAYER_H #include "neuron.h" class layer { public: layer(const std::vector<neuron>& neurons, const double bias = 0.0); ~layer() {while(!neurons.empty()) neurons.pop_back();} const std::vector<std::shared_ptr<neuron>>& get_neurons() const {return neurons;} void set_neurons(const std::vector<std::shared_ptr<neuron>>& neurons) {this->neurons = neurons;} const std::vector<double> get_errors() const; void set_errors(const std::vector<double>& errors); const std::vector<double> get_weights_vec(const unsigned int output_index) const; void set_outputs(const std::vector<double>& output); const std::vector<double> get_outputs() const; const double& get_bias() const {return bias;} void set_bias(const double& bias) {this->bias = bias;} void fill_with_rand_weights() {for(auto neuron_ : neurons) neuron_->fill_with_rand_weights();} private: std::vector<std::shared_ptr<neuron>> neurons; double bias; }; #endif //MLP_LAYER_H <file_sep>/README.md # MLP multilayer perceptron / c++ <file_sep>/src/layer.cpp #include "layer.h" layer::layer(const std::vector<neuron>& neurons, const double bias) : bias(bias) { for(auto neuron_ : neurons) this->neurons.push_back(std::make_shared<neuron>(neuron_)); } const std::vector<double> layer::get_weights_vec(const unsigned int output_index) const { std::vector<double> weights; for(unsigned int i = 0; i < neurons.size(); i++) weights.push_back(neurons[i]->get_weight(output_index)); return weights; } void layer::set_outputs(const std::vector<double>& output) { for(unsigned int i = 0; i < neurons.size(); i++) neurons[i]->set_output(output[i]); } const std::vector<double> layer::get_outputs() const { std::vector<double> outputs; for(unsigned int i = 0; i < neurons.size(); i++) outputs.push_back(neurons[i]->get_output()); return outputs; } const std::vector<double> layer::get_errors() const { std::vector<double> errors; for(auto neuron_ : neurons) errors.push_back(neuron_->get_error()); return errors; } void layer::set_errors(const std::vector<double>& errors) { for(unsigned int i = 0; i < neurons.size(); i++) neurons[i]->set_error(errors[i]); } <file_sep>/inc/training_item.h #ifndef MLP_TRAINING_ITEM_H #define MLP_TRAINING_ITEM_H #include <vector> class training_item { public: training_item(const std::vector<double> input, const double output) : output(output), input(input) {}; void set_output(const std::vector<double>& output) {this->output = output;} const std::vector<double>& get_output() const {return output;} void set_input(const std::vector<double>& input) {this->input = input;} const std::vector<double>& get_input() const {return input;} private: std::vector<double> output; std::vector<double> input; }; #endif //MLP_TRAINING_ITEM_H <file_sep>/inc/mlp.h #ifndef MLP_MLP_H #define MLP_MLP_H #include <cmath> #include <numeric> #include "training_item.h" #include "layer.h" class mlp { public: mlp(const unsigned int number_of_inputs, const std::vector<unsigned int> hidden_neurons, const unsigned int number_of_outputs, const std::vector<double> biases, const double learning_rate = 0.1); ~mlp() {while(!layers.empty()) layers.pop_back();} const std::vector<double> feedforward(const std::vector<double>& input); void train(const std::vector<training_item>& training_set); void fill() {for(auto layer_ : layers) layer_->fill_with_rand_weights();} const std::vector<std::shared_ptr<layer>> get_layers() const {return layers;} void get_all_weights() const; private: double sigmoid(double x) const {return 1 / (1 + exp(-x));} double sigmoid_derivative(double x) const {return sigmoid(x)*(1-sigmoid(x));} double dot_product(const std::vector<double>& vec1, const std::vector<double>& vec2) const; template <typename T> void make_empty(std::vector<T>& vec) const noexcept {while(!vec.empty()) vec.pop_back();} double squared_error(const double& output, const double& expected_output) const {return std::pow(expected_output - output, 2)/2;} std::vector<double> squared_errors(const std::vector<double>& outputs, const std::vector<double>& expected_outputs); double hidden_error_derivative(const unsigned int& layer_index, const unsigned int& neuron_index) const noexcept; double output_error_derivative(const unsigned int& neuron_index, const double& expected_output) const noexcept; double loss_function(const std::vector<double>& errors) const; double learning_rate; std::vector< std::shared_ptr<layer> > layers; }; #endif //MLP_MLP_H <file_sep>/inc/neuron.h #ifndef MLP_NEURON_H #define MLP_NEURON_H #include <vector> #include <cstdlib> #include <limits> #include <ctime> #include <iostream> #include <memory> class neuron { std::vector<std::shared_ptr<double>> weights; double output; double error; public: neuron(const std::vector<double>& weights) {for(auto weight : weights) this->weights.push_back(std::make_shared<double>(weight));} ~neuron() {while(!weights.empty()) weights.pop_back();} const std::vector<std::shared_ptr<double>>& get_weights() const {return weights;} const std::vector<double> get_weights_d() const {std::vector<double> weights; for(auto weight : this->weights) weights.push_back(*weight); return weights;} void set_weights(const std::vector<std::shared_ptr<double>>& weights) {this->weights = weights;} const double& get_weight(const unsigned int weight_index) const {return *weights[weight_index];} void set_weight(const unsigned int& weight_index, const double& new_weight) {*weights[weight_index] = new_weight;} const double& get_output() const {return output;} void set_output(const double& output) {this->output = output;} const double& get_error() const {return error;} void set_error(const double& error) {this->error = error;} void fill_with_rand_weights() {std::srand((unsigned)std::time(NULL)); for(unsigned int i=0; i < weights.size(); i++){set_weight(i, 2);}} }; #endif //MLP_NEURON_H
cb98ff801628ed63e883942f39d67d182e44cd91
[ "Markdown", "Makefile", "C++" ]
9
Makefile
CypHry/MLP
f348e415fc6e277eb860a63245ca8f4033ebe842
32d8edcde6c1e50155485227654f977cee614ba6
refs/heads/master
<file_sep>from math import * from random import * class Archer: """Records an archer's minimum, maximum, and average score for each end.""" def __init__(self, qual_score): self.max_end = 30 self.average_end = round((qual_score / 24),2) self.qual_score = qual_score self.min_end = self.determineMin() self.match_ends = [] self.end_average = 0 self.shootoff_wins = 0 def determineMin(self): if self.qual_score < 500: self.min_end = self.average_end - 12 elif self.qual_score < 600: self.min_end = self.average_end - 8 elif self.qual_score < 620: self.min_end = self.average_end - 6 elif self.qual_score < 640: self.min_end = self.average_end - 5 elif self.qual_score < 660: self.min_end = self.average_end - 4 elif self.qual_score >= 660: self.min_end = self.average_end - 3 return floor(self.min_end) class MatchData: def __init__(self, num_matches): self.num_matches = num_matches self.a1_wins = 0 self.a2_wins = 0 self.shootoffs = 0 def get_a1_wins(self): return self.a1_wins def get_a2_wins(self): return self.a2_wins def get_a1_percent(self): return self.a1_win_percentage def get_a2_percent(self): return self.a2_win_percentage def getMatches(self): return self.num_matches def getShootoffs(self): return self.shootoffs def printIntro(): print('This program will take the qualification score of two archers and simulate') print("any number of matches between them. It will then report the statistics") print('of the matches.') def getQuals(): qual_one = int(input('Enter the qualification score of first archer: ')) qual_two = int(input('Enter the qualification score of second archer: ')) return qual_one, qual_two def getMatches(): num_matches = int(input('How many matches will be simulated? ')) return num_matches def generateData(match, archer1, archer2): for i in range(match.getMatches()): match, winner, archer1, archer2 = simOneMatch(match,archer1, archer2) if winner == 'a1': match.a1_wins += 1 if winner == 'a2': match.a2_wins += 1 archer1.end_average = sum(archer1.match_ends) / len(archer1.match_ends) archer2.end_average = sum(archer2.match_ends) / len(archer2.match_ends) return match, archer1, archer2 def simOneMatch(match, archer1, archer2): a1_end_list = [] a2_end_list = [] a1_points = 0 a2_points = 0 a1_scores, a2_scores = generateEndScores(archer1, archer2) while a1_points < 6 and a2_points < 6: if a1_points == 5 and a2_points == 5: match.shootoffs += 1 winner = simOneArrow(archer1, archer2) return match, winner, archer1, archer2 else: a1_end = getEnd(a1_scores) a2_end = getEnd(a2_scores) archer1.match_ends.append(a1_end) archer2.match_ends.append(a2_end) if a1_end > a2_end: a1_points += 2 elif a2_end > a1_end: a2_points += 2 elif a1_end == a2_end: a1_points += 1 a2_points += 1 if a1_points >= 6: winner = 'a1' return match, winner, archer1, archer2 elif a2_points >= 6: winner = 'a2' return match, winner, archer1, archer2 def generateEndScores(archer1, archer2): a1_scores = generateScores(archer1) a2_scores = generateScores(archer2) a1_scores_fixed = fixAverage(archer1, a1_scores) a2_scores_fixed = fixAverage(archer2, a2_scores) return a1_scores_fixed, a2_scores_fixed def generateScores(archer): a_scores = [] for i in range(50): a_end = randint(archer.min_end, archer.max_end) a_scores.append(a_end) return a_scores def fixAverage(archer, a_scores): a_average, list_average, average_gap = averageGap(archer, a_scores) while not (a_average - .1) < list_average < (a_average + .1): if average_gap > 0: list_index = randint(0, (len(a_scores)-1)) if archer.max_end > a_scores[list_index]: a_scores[list_index] = a_scores[list_index] + 1 a_average, list_average, average_gap = averageGap(archer, a_scores) else: continue elif average_gap < 0: list_index = randint(0, len(a_scores)-1) if a_scores[list_index] > archer.min_end: a_scores[list_index] = a_scores[list_index] - 1 a_average, list_average,average_gap = averageGap(archer, a_scores) else: continue return a_scores def getEnd(a_scores): rand_index = randint(0, len(a_scores)-1) end_score = a_scores[rand_index] return end_score def simOneArrow(archer1, archer2): a1_arrow = getArrow(archer1) a2_arrow = getArrow(archer2) if a1_arrow > a2_arrow: archer1.shootoff_wins += 1 return 'a1' elif a2_arrow > a1_arrow: archer2.shootoff_wins += 1 return 'a2' elif a1_arrow == a2_arrow: return simOneArrow(archer1, archer2) def getArrow(archer): if archer.qual_score < 500: arrow = randint(4,10) elif 500 <= archer.qual_score < 550: arrow = randint(5,10) elif 550 <= archer.qual_score < 620: arrow = randint(6,10) elif 620 <= archer.qual_score < 650: arrow = randint(7,10) elif 650 <= archer.qual_score < 670: arrow = randint(8,10) else: arrow = randint(9,10) return arrow def averageGap(archer, a_scores): a_average = archer.average_end list_average = sum(a_scores) / len(a_scores) average_gap = a_average * len(a_scores) - sum(a_scores) return a_average, list_average, average_gap def displayData(archer1, archer2, match): print("\n{0:>15}: {1} \n".format('Number of matches', match.getMatches())) print("{0:^40}\n".format('Archer 1')) print('Archer 1 qualification score: {0}'.format(archer1.qual_score)) print('Archer 1 match wins: {0} ({1:0.2f}%)'.format(match.get_a1_wins(), (match.get_a1_wins()/match.getMatches()*100))) print('Archer 1 arrow average: {0:0.3f}'.format(archer1.end_average)) print("Archer 1 shootoff wins: {0}\n".format(archer1.shootoff_wins)) print("{0:^40}\n".format('Archer 2')) print('Archer 2 qualification score: {0}'.format(archer2.qual_score)) print('Archer 2 match wins: {0} ({1:0.2f}%)'.format(match.get_a2_wins(), (match.get_a2_wins() / match.getMatches()*100))) print('Archer 2 arrow average: {0:0.3f}:'.format(archer2.end_average)) print('Archer 2 shootoff wins: {0}\n'.format(archer2.shootoff_wins)) def main(): printIntro() qual_one, qual_two = getQuals() num_matches = getMatches() match = MatchData(num_matches) archer1 = Archer(qual_one) archer2 = Archer(qual_two) match, archer1, archer2= generateData(match, archer1, archer2) displayData(archer1, archer2, match) if "__name__" == "__main__": main() #def test(qual_one, qual_two, num_matches): # match = MatchData(num_matches) # archer1 = Archer(qual_one) # archer2 = Archer(qual_two) #match, archer1, archer2= generateData(match, archer1, archer2) #displayData(archer1, archer2, match) <file_sep># Match_Simulation This is a class-based python script to predict the outcomes of elimination matches depending on the qualification score of each archer. This script runs on the command line currently, although it may be expanded to include a GUI at a later date. The purpose of writing this script was two-fold. The initial impetus was the need to practice writing class-based programs, but I was also curious about my ability to effectively model match play in archery. To accomplish this, I created an archer class that stores the performance information about two archers when provided the archer's qualification score as a calling argument. Based on the qualification score, an array of 50 3-arrow ends is generated and for each archer and normalized around their average arrow value from the qualification round. Since lower scoring archers are less consistent, lower qualification scores yield a wider range of possible end scores, but the average across all of the ends matches their qualification average. To simulate a match, ends are picked at random from each archer's array of possible ends and scored based on World Archery match play scoring criteria, which is as follows: - The higher scoring archer for each three arrow end gets 2 points. - If the archers have the same end score, each archer gets 1 point. - The first archer to achieve 6 or seven points wins the match. - If both archers end up at 5 points, the match goes to a one arrow shoot off. Given these rules, the script will simulate the number of matches input at the beginning of the script, and provide output in the terminal with the number of matches simulated, the number of matches each archer won, the number of ties, the win percentage of each archer, and the average end of each archer. I was pleasantly surprised that the modeling in this script produces results that are similar to my personal experience competing on an international level.
71fa11da8f14d6549a500b7291e8dc598d2a9a62
[ "Markdown", "Python" ]
2
Python
AlexLB97/Match_Simulation
e340b02ac726120bce25562e85d057ff6d83f3fc
bf25bb6421c28ad8b4a8d67ff6e81aafe26b5061
refs/heads/master
<repo_name>wangalangg/Tetris<file_sep>/src/com/wangalangg/tetris/CycleManager.java package com.wangalangg.tetris; public class CycleManager { private long time; private double timePassed; private boolean isCycleFinished; public CycleManager() { time = System.nanoTime(); isCycleFinished = false; } public void setCurrentTime(long currentTime) { timePassed = (currentTime - time) / 1000000000.0; } public void restartTimer() { time = System.nanoTime(); } public double getTimePassed() { return timePassed; } public boolean didTimeExceed(double time) { return timePassed > time; } public boolean isCycleFinished() { return isCycleFinished; } public void requestNextCycle() { isCycleFinished = true; } public void finishCycle() { isCycleFinished = false; } } <file_sep>/src/com/wangalangg/tetris/controllers/MainController.java package com.wangalangg.tetris.controllers; import com.wangalangg.tetris.ui.UIManager; import javafx.event.ActionEvent; public class MainController implements ScreenChangeable { private UIManager uiManager; @Override public void setUIManager(UIManager uiManager) { this.uiManager = uiManager; } public void showSinglePlayer(ActionEvent event) { uiManager.showSinglePlayer(); } public void showMultiPlayer(ActionEvent event) { uiManager.showMultiPlayer(); } } <file_sep>/src/com/wangalangg/tetris/gamemechanics/SPGame.java package com.wangalangg.tetris.gamemechanics; import com.wangalangg.tetris.CycleManager; import com.wangalangg.tetris.gamemechanics.blocks.BlockManager; import com.wangalangg.tetris.gamemechanics.blocks.Blocks; import com.wangalangg.tetris.gamemechanics.matrix.BlockInfo; import com.wangalangg.tetris.gamemechanics.matrix.Matrix; import com.wangalangg.tetris.gamemechanics.matrix.Score; import com.wangalangg.tetris.gamemechanics.ui.ImageLoader; import com.wangalangg.tetris.gamemechanics.ui.UIHandler; import com.wangalangg.tetris.gamemechanics.utils.LevelInfo; import javafx.animation.AnimationTimer; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; /** * Responsibilities: * - Generating the next blocks * - Keep track of current holding block * - Send the next block to the matrix object * - Keep track of game time * - UI control */ public class SPGame { private Matrix matrix; private BlockInfo currentBlock; private CycleManager gameCycle; private boolean holdUsed = false; private BlockManager blockManager; private UIHandler uiHandler; private AnimationTimer rotateLeftTimer, rotateRightTimer, shiftLeftTimer, shiftRightTimer, softDropTimer; private int restingBlockCounter = 0; private Score score; public SPGame(GridPane tetrisGrid, ImageView holdBlockImage, ImageLoader images, ImageView[] nextBlocksImages, Text points, Text level, Text linesLeft) { gameCycle = new CycleManager(); blockManager = new BlockManager(); currentBlock = new BlockInfo(); matrix = new Matrix(currentBlock, gameCycle); this.score = new Score(points, level, linesLeft); uiHandler = new UIHandler(tetrisGrid, holdBlockImage, images, nextBlocksImages, matrix, blockManager, this.score); softDropTimer = createSoftDropTimer(() -> matrix.handleSoftDrop()); rotateLeftTimer = createRotateTimer(() -> matrix.handleRotateLeft()); rotateRightTimer = createRotateTimer(() -> matrix.handleRotateRight()); shiftLeftTimer = createShiftTimer(() -> matrix.handleShiftLeft()); shiftRightTimer = createShiftTimer(() -> matrix.handleShiftRight()); createGameTimer(); addBlockToMatrix(blockManager.getCurrentBlock()); } private void createGameTimer() { new AnimationTimer() { boolean canStepFrame = true; @Override public void handle(long now) { // Keep track of game cycle gameCycle.setCurrentTime(now); if (gameCycle.getTimePassed() > LevelInfo.STEP_TIME[score.getLevel() - 1] || gameCycle.isCycleFinished()) { gameCycle.restartTimer(); if (matrix.doesCurrentBlockExist()) { canStepFrame = matrix.stepFrame(); } // If block hit bottom, give 2 cycles for the player to finalize their decision // or move the piece under other pieces if (matrix.doesCurrentBlockExist() && !canStepFrame && restingBlockCounter < 1) { restingBlockCounter++; } // Block has fallen else if (matrix.doesCurrentBlockExist() && !canStepFrame) { onBlockFallen(); } gameCycle.finishCycle(); } uiHandler.update(); } }.start(); } private AnimationTimer createSoftDropTimer(Runnable action) { CycleManager shiftCycle = new CycleManager(); return new AnimationTimer() { boolean isFirstShift = true; @Override public void handle(long now) { shiftCycle.setCurrentTime(now); // Process is done backwards to ensure everything runs once // e.g. if shifted first, isFirstShift will become false, making delay2Secs // method run, making isSecondShift true, making the shiftEvery1Sec run, // shifting the block twice // Shift every 0.05 sec if (!isFirstShift && shiftCycle.didTimeExceed(0.05)) { shiftDown(); } // Shift first if (isFirstShift) { isFirstShift = false; shiftDown(); } } private void shiftDown() { shiftCycle.restartTimer(); action.run(); gameCycle.restartTimer(); score.softDrop(); } }; } private AnimationTimer createShiftTimer(Runnable shiftAction) { CycleManager shiftCycle = new CycleManager(); return new AnimationTimer() { boolean isFirstShift = true; boolean isSecondShift = false; @Override public void handle(long now) { shiftCycle.setCurrentTime(now); // Process is done backwards to ensure everything runs once // e.g. if shifted first, isFirstShift will become false, making delay2Secs // method run, making isSecondShift true, making the shiftEvery1Sec run, // shifting the block twice // Shift every 1 sec if (isSecondShift && shiftCycle.didTimeExceed(0.05)) { shiftCycle.restartTimer(); shiftAction.run(); } // Delay 2 secs if (!isFirstShift && shiftCycle.didTimeExceed(0.2)) { shiftCycle.restartTimer(); isSecondShift = true; } // Shift first if (isFirstShift) { isFirstShift = false; shiftCycle.restartTimer(); shiftAction.run(); } } @Override public void stop() { super.stop(); isFirstShift = true; isSecondShift = false; } }; } private AnimationTimer createRotateTimer(Runnable rotate) { CycleManager rotateCycle = new CycleManager(); return new AnimationTimer() { boolean isFirstRotation = true; @Override public void handle(long now) { rotateCycle.setCurrentTime(now); // Rotate first and don't rotate again if (isFirstRotation) { rotate.run(); rotateCycle.restartTimer(); isFirstRotation = false; } } @Override public void stop() { super.stop(); isFirstRotation = true; } }; } private void onBlockFallen() { determinePoints(matrix.onBlockFallen()); restingBlockCounter = 0; holdUsed = false; blockManager.nextBlock(); addBlockToMatrix(blockManager.getCurrentBlock()); } private void determinePoints(int linesCleared) { switch (linesCleared) { case 1: score.single(); break; case 2: score.duhble(); break; case 3: score.triple(); break; case 4: score.tetris(); break; default: break; } } public void onPressed(KeyCode input) { if (matrix.doesCurrentBlockExist()) { switch (input) { case DOWN: softDropTimer.start(); break; case Z: case CONTROL: rotateLeftTimer.start(); break; case X: case UP: rotateRightTimer.start(); break; case RIGHT: shiftRightTimer.start(); break; case LEFT: shiftLeftTimer.start(); break; case SPACE: score.hardDrop(matrix.handleHardDrop()); onBlockFallen(); break; case C: case SHIFT: holdBlock(); default: break; } } } public void onReleased(KeyCode input) { if (matrix.doesCurrentBlockExist()) { switch (input) { case DOWN: softDropTimer.stop(); break; case Z: case CONTROL: rotateLeftTimer.stop(); break; case X: case UP: rotateRightTimer.stop(); break; case LEFT: shiftLeftTimer.stop(); break; case RIGHT: shiftRightTimer.stop(); default: break; } } } private void holdBlock() { if (!holdUsed) { currentBlock.takeOutOfPlay(); blockManager.holdBlock(); holdUsed = true; addBlockToMatrix(blockManager.getCurrentBlock()); gameCycle.restartTimer(); } } public void addBlockToMatrix(Blocks block) { currentBlock.setBlock(block); matrix.getGhostBlock().update(); matrix.checkNewBlockInMatrix(); } } <file_sep>/src/com/wangalangg/tetris/controllers/MPController.java package com.wangalangg.tetris.controllers; import com.wangalangg.tetris.gamemechanics.MPGame; import com.wangalangg.tetris.gamemechanics.SPGame; import com.wangalangg.tetris.gamemechanics.ui.ImageLoader; import com.wangalangg.tetris.ui.UIManager; import java.net.URISyntaxException; import javafx.fxml.FXML; import javafx.scene.image.ImageView; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; public class MPController extends SPController implements ScreenChangeable { @FXML private GridPane player2Grid; public MPController() { } @FXML public void initialize() { ImageView[] blocks = {block1, block2, block3, block4, block5}; MPGame mpGame = new MPGame(tetrisGrid, player2Grid, holdBlock, new ImageLoader(), blocks, points, level, linesLeft); } @Override public void setUIManager(UIManager uiManager) { this.uiManager = uiManager; } } <file_sep>/README.md #Tetris Me remaking tetris. *** This repository is outdated. *** Click here for the newer version: https://github.com/wangalangg/Tetris-MP/tree/master The new repository has Gradle support in order to use dependencies like socket.io. <file_sep>/src/com/wangalangg/tetris/gamemechanics/matrix/Score.java package com.wangalangg.tetris.gamemechanics.matrix; import javafx.scene.text.Text; public class Score { private int points, level; private int linesLeft; private Text pointsDisplay, levelDisplay, linesLeftDisplay; public Score(Text pointsDisplay, Text levelDisplay, Text linesLeftDisplay) { points = 0; level = 1; linesLeft = 5; this.pointsDisplay = pointsDisplay; this.levelDisplay = levelDisplay; this.linesLeftDisplay = linesLeftDisplay; } public void update() { linesLeftDisplay.setText(Integer.toString(linesLeft)); pointsDisplay.setText(Integer.toString(points)); levelDisplay.setText(Integer.toString(level)); } public int getLevel() { return level; } public void softDrop() { points++; } public void hardDrop(int lines) { points += lines * 2; } public void single() { linesLeft--; points += 100 * level; checkLevelUp(); } public void duhble() { linesLeft -= 3; points += 300 * level; checkLevelUp(); } public void triple() { linesLeft -= 4; points += 500 * level; checkLevelUp(); } public void tetris() { linesLeft -= 5; points += 800 * level; checkLevelUp(); } // Tspin that clears no lines public void tSpin() { linesLeft -= 4; points += 400 * level; checkLevelUp(); } public void tSpinSingle() { linesLeft -= 8; points += 800 * level; checkLevelUp(); } public void tSpinDouble() { linesLeft -= 12; points += 1200 * level; checkLevelUp(); } public void tSpinTriple() { linesLeft -= 16; points += 1600 * level; checkLevelUp(); } public void tSpinMini() { linesLeft -= 1; points += 100 * level; checkLevelUp(); } public void tSpinMiniSingle() { linesLeft -= 2; points += 200 * level; checkLevelUp(); } public void backToBack() { // todo stub } private void checkLevelUp() { if (linesLeft <= 0) { level++; linesLeft = level * 5; } } }
2c91f6d53c8c0b3c9ab18c88abd7ed1d86a0d451
[ "Markdown", "Java" ]
6
Java
wangalangg/Tetris
a467f3778c83f356953a8da1fbac8e3ea72f87b1
cd6fe93ee56e4be25e9dd1955b0f0ce404cc0ae1
refs/heads/master
<repo_name>mvnaidu8/jenkins-test<file_sep>/src/master/Hello.java package master; public class Hello { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Hello From Jenkins"); System.out.println("If you are seeing this means it's working"); System.out.println("Automated Build Using Github WebHook"); } } <file_sep>/README.md # Jenkins-Test Learning DevOps - Test Repo for Jenkins
83b53a2525ca6cfef403e5d4a92a740b20347a88
[ "Markdown", "Java" ]
2
Java
mvnaidu8/jenkins-test
e857522a397a371551185f418873db9a28ca7c88
5a7764496f72110ca6e4096b004a1eb344aa1e31
refs/heads/master
<file_sep># Time from time import time big_start = time() # Selenium imports from selenium import webdriver from selenium.webdriver.common.keys import Keys # Import Getpass from getpass import getpass # Get facebook username and password from the user usr = raw_input("Type your Facebook email, then press enter:") pwd = getpass() # Set up a new firefox profile with CSS, Image loading, and Flash disabled firefox_profile = webdriver.FirefoxProfile() firefox_profile.set_preference('permissions.default.stylesheet', 2) firefox_profile.set_preference('permissions.default.image', 2) firefox_profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false') driver = webdriver.Firefox(firefox_profile=firefox_profile) driver.get("http://www.facebook.com") # navigate to Facebook elem = driver.find_element_by_id("email") # form element containing email field elem.send_keys(usr) elem = driver.find_element_by_id("pass") # form element containing password field elem.send_keys(pwd) elem.send_keys(Keys.RETURN) driver.add_cookie(driver.get_cookies()) # loads call results into cookies for later navigation driver.get("http://m.facebook.com/me") # go to mobile version of profile all_buttons = driver.find_elements_by_tag_name("a") # find the link that points to my friends for bu in all_buttons: if bu.text == 'Friends': elem = bu break # extract my facebook username from the link starting_user = elem.get_attribute('href').split('/')[-1].split('?')[0] all_friends = {} from Queue import Queue q = Queue() q.put(starting_user) crawl = True analytics = {} # while there are still friends to crawl while not q.empty(): little_start = time() # load the next friend to get friends of friends = [] current = q.get() # navigate to their friends driver.get('http://m.facebook.com/' + current + '?v=friends') print 'Fetching ' + current + "'s friends..." batch_count = 0 try: while True: batch_count += 1 # add all of the friends batch = [tab.find_element_by_tag_name('a').get_attribute('href').split('/')[-1].split('?')[0] for tab in driver.find_element_by_id('root').find_elements_by_tag_name('table')] friends.extend(batch) # try to click the see more button, if it's not there, break, you're done with the friends try: link = driver.find_element_by_id("m_more_friends").find_element_by_tag_name('a') link.click() except: break except: continue # prevents going a level deeper (friends of friends of friends) if crawl: # if first time crawling it's the starting user map(q.put, friends) # add their friends to the queue crawl = False # don't do this again all_friends[current] = friends elapsed = str(time() - little_start) print '...Done. Took ' + elapsed + ' seconds' analytics[current] = {'friends' : len(friends), 'time' : elapsed, 'batch count' : batch_count} driver.close() import json # write the results to results.json out = open('results.json', 'w') out.write(json.dumps(all_friends)) out.close() # write the speed report to analytics.json out = open('analytics.json', 'w') out.write(json.dumps(analytics)) out.close() print 'The whole process took ' + str(time() - big_start) + ' seconds'
e20c2ca7d7491517f1bae37b7e04e2bd8fe3efce
[ "Python" ]
1
Python
RestoreDemocracy/selenium-friends-scraper
f9403b72cc3ad76279869aac6852c6cdafddab5c
4557d274ee6627504ed23d047ca4a631ace2dd2a
refs/heads/master
<file_sep>package com.catlerina.android.newsviewer; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import com.catlerina.android.newsviewer.fragments.ArticleFragment; import com.catlerina.android.newsviewer.fragments.NewsListFragment; import com.catlerina.android.newsviewer.interfaces.OnNewsItemClickListener; import com.catlerina.android.newsviewer.model.Article; public class MainActivity extends AppCompatActivity implements OnNewsItemClickListener { private FragmentManager fragmentManager; private NewsListFragment newsListFragment; private ArticleFragment articleFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_masterdetail); fragmentManager = getSupportFragmentManager(); newsListFragment = NewsListFragment.newInstance(); if(fragmentManager.findFragmentById(R.id.ll_fragment_container)==null){ fragmentManager.beginTransaction() .add(R.id.ll_fragment_container, newsListFragment) .commit(); } } @Override public void onItemClick(View view, int position, Article a) { String url = a.getArticleLink().toString(); if (findViewById(R.id.detailed_fragment_container) == null) {//it is phone articleFragment = ArticleFragment.newInstance(url); fragmentManager.beginTransaction() .replace(R.id.ll_fragment_container, articleFragment) .addToBackStack(null) .commit(); } else { // it is tablet if (articleFragment == null) { articleFragment = ArticleFragment.newInstance(url); fragmentManager.beginTransaction() .add(R.id.detailed_fragment_container, articleFragment) .commit(); } else articleFragment.loadUrl(url); } } } <file_sep>package com.catlerina.android.newsviewer.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebResourceRequest; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import com.catlerina.android.newsviewer.R; public class ArticleFragment extends Fragment { private static final String URL_ARG = "uriRes"; private WebView webArticle; private ProgressBar articleLoadProgress; public static ArticleFragment newInstance(String url){ ArticleFragment fragment = new ArticleFragment(); Bundle args = new Bundle(); args.putString(URL_ARG, url); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_article_web, container, false); webArticle = (WebView) view.findViewById(R.id.wv_article); articleLoadProgress = (ProgressBar) view.findViewById(R.id.pb_article_page_load); articleLoadProgress.setMax(100); articleLoadProgress.setVisibility(View.VISIBLE); webArticle.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return false; } }); webArticle.setWebChromeClient(new WebChromeClient(){ @Override public void onProgressChanged(WebView view, int newProgress) { if(newProgress == 100){ articleLoadProgress.setVisibility(View.GONE); } else { articleLoadProgress.setVisibility(View.VISIBLE); articleLoadProgress.setProgress(newProgress); } } }); webArticle.loadUrl(getArguments().getString(URL_ARG)); webArticle.getSettings().setJavaScriptEnabled(true); return view; } public void loadUrl(String url){ webArticle.loadUrl(url); } } <file_sep>package com.catlerina.android.newsviewer.storage; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.CursorWrapper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.net.Uri; import com.catlerina.android.newsviewer.model.Article; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class Database { private DBHelper helper; private Context context; private SQLiteDatabase database; public Database(Context context) { this.context = context; } public void open(){ helper = new DBHelper(context, DBStructure.DB_NAME, null, DBStructure.DB_VERSION); database = helper.getWritableDatabase(); } public void close(){ if (database!=null) database.close(); if (helper!=null) helper.close(); } public void insertArticles(List<Article> articles){ if(articles.size()!=0){ for(Article article:articles){ database.insert(DBStructure.DB_TBL_ARTICLE, null, getContentValues(article)); } } } private ContentValues getContentValues(Article article){ ContentValues cv = new ContentValues(); cv.put(DBStructure.DB_COL_ID, article.getId()); cv.put(DBStructure.DB_COL_TITLE, article.getTitle()); cv.put(DBStructure.DB_COL_DESCRIPTION, article.getDescription()); cv.put(DBStructure.DB_COL_AUTHOR, article.getAuthor()); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = null; if(article.getDate()!=null) date = format.format(article.getDate()); cv.put(DBStructure.DB_COL_DATE, date); cv.put(DBStructure.DB_COL_URL, article.getArticleLink().toString()); cv.put(DBStructure.DB_COL_IMAGE_URL, article.getImageLink().toString()); return cv; } public ArrayList<Article> getArticles(){ ArrayList<Article> articles = new ArrayList<>(); NewsCursorWrapper cursor = articlesQuery(); try { cursor.moveToFirst(); while (!cursor.isAfterLast()){ articles.add(cursor.getArticle()); cursor.moveToNext(); } } finally { cursor.close(); } return articles; } private NewsCursorWrapper articlesQuery(){ Cursor cursor = database.query(DBStructure.DB_TBL_ARTICLE, null,null,null,null,null,DBStructure.DB_COL_DATE +" desc"); return new NewsCursorWrapper(cursor); } public class DBHelper extends SQLiteOpenHelper{ public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DBStructure.CREATE_ARTICLE_TBL); db.execSQL(DBStructure.CREATE_TRIGGER_ON_ARTICLE_INSERT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(DBStructure.TBLS_DELETE); onCreate(db); } } public class NewsCursorWrapper extends CursorWrapper { public NewsCursorWrapper(Cursor cursor) { super(cursor); } public Article getArticle(){ int id = getInt(getColumnIndex(DBStructure.DB_COL_ID)); String title = getString(getColumnIndex(DBStructure.DB_COL_TITLE)); String description = getString(getColumnIndex(DBStructure.DB_COL_DESCRIPTION)); String author = getString(getColumnIndex(DBStructure.DB_COL_AUTHOR)); Date date = null; try { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String stringDate = getString(getColumnIndex(DBStructure.DB_COL_DATE)); if (stringDate != null) { date = format.parse(stringDate); } } catch (ParseException e) { e.printStackTrace(); } Uri articleURL = Uri.parse(getString(getColumnIndex(DBStructure.DB_COL_URL))); Uri imageURL = Uri.parse(getString(getColumnIndex(DBStructure.DB_COL_IMAGE_URL))); return new Article(id, author, title, description, imageURL, articleURL, date); } } }
b6f45a7a4f868021e9276e8794bb7331a8f2e6d3
[ "Java" ]
3
Java
KatarinaLenskaya/NewsViewer
2a01f5e6abced86479c649d1c1d74a1b55ab8af0
80ef819be7944e19ed9aefafd93968ee7c7b4e3d
refs/heads/master
<repo_name>konrad-komisarczyk/dziki_zachod<file_sep>/src/dzikizachod/WidokGracza.java package dzikizachod; import dzikizachod.gracz.KlasaPostaci; import dzikizachod.gracz.PrzekroczenieLimituPunktowZycia; public class WidokGracza { private int zasieg; private int maxPunktyZycia; private int punktyZycia; private KlasaPostaci klasaPostaci; private int numer; public WidokGracza(int punktyZycia, KlasaPostaci klasaPostaci) { this.numer = -1; this.zasieg = 1; this.punktyZycia = punktyZycia; this.maxPunktyZycia = punktyZycia; this.klasaPostaci = klasaPostaci; } public WidokGracza(int zasieg, int punktyZycia, int maxPunktyZycia, KlasaPostaci klasaPostaci) { assert zasieg >= 1; assert punktyZycia <= maxPunktyZycia; assert punktyZycia >= 0; this.numer = -1; this.zasieg = zasieg; this.punktyZycia = punktyZycia; this.maxPunktyZycia = maxPunktyZycia; this.klasaPostaci = klasaPostaci; } public int getMaxPunktyZycia() { return maxPunktyZycia; } public int getPunktyZycia() { return punktyZycia; } public void setPunktyZycia(int punktyZycia) throws PrzekroczenieLimituPunktowZycia { if (punktyZycia >= maxPunktyZycia) { this.punktyZycia = maxPunktyZycia; throw new PrzekroczenieLimituPunktowZycia(punktyZycia); } else if (punktyZycia < 0) { this.punktyZycia = 0; throw new PrzekroczenieLimituPunktowZycia(punktyZycia); } else { this.punktyZycia = punktyZycia; } } public int getZasieg() { return zasieg; } public void setZasieg(int zasieg) { this.zasieg = zasieg; } public KlasaPostaci getKlasaPostaci() { return klasaPostaci; } /** * Ustawia numer gracza. * Można go ustawić tylko raz. * @param numer numers */ public void ustawNumer(int numer) { if (this.numer == -1) { assert numer >= 0; this.numer = numer; } } public Boolean isMartwy() { return getPunktyZycia() == 0; } public Boolean czyWPelniZdrowy() { return getPunktyZycia() == getMaxPunktyZycia(); } @Override public String toString() { if (isMartwy()) { return "X (" + getKlasaPostaci().toString() + ")"; } else { return getKlasaPostaci().toString() + " (liczba żyć: " + getPunktyZycia() + ")"; } } } <file_sep>/src/dzikizachod/Kolko.java package dzikizachod; import dzikizachod.gracz.KlasaPostaci; import java.util.ArrayList; import java.util.Collections; /** * Klasa reprezentująca graczy (lub widoki graczy) siedzących w kółku. * @param <E> widok gracza */ public class Kolko<E extends WidokGracza> extends ArrayList<E> { /** * Następny żywy gracz na prawo od danego. * @param a nr na kółku danego gracza * @return numer kolejnego żywego gracza */ public int nastepnyZywy(int a) { int i = (a + 1) % size(); while (get(i).isMartwy()) { i = (i + 1) % size(); } return i; } /** * Następny żywy gracz na lewo od danego. * @param a nr na kółku danego gracza * @return numer poprzedniego żywego gracza */ public int poprzedniZywy(int a) { int i = (a - 1 + size()) % size(); while (get(i).isMartwy()) { i = (i - 1 + size()) % size(); } return i; } /** * Zlicza żywych graczy idąc w prawo od jednego do drugiego * @param a nr na kółku jednego gracza * @param b nr na kółku drugiego gracza, musi być żywy * @return ile żywych graczy jest pomiędzy danymi graczami idąc w prawo */ private int odlegloscRosnaco(int a, int b) { assert !get(b).isMartwy(); int odl = 0; while (a != b) { a = nastepnyZywy(a); odl ++; } return odl; } public int znajdzSzeryfa() throws BrakSzeryfa { for(int i = 0; i < size(); i++) { if (get(i).getKlasaPostaci() == KlasaPostaci.SZERYF) { return i; } } throw new BrakSzeryfa(); } /** * @param a nr na kółku pierwszego gracza, musi być żywy * @param b nr na kółku drugiego gracza, musi być żywy * @return ile conajmniej żywych graczy jest pomiędzy danymi graczami */ private int odleglosc(int a, int b) { return Math.min(odlegloscRosnaco(a, b), odlegloscRosnaco(b, a)); } /** * @param a nr na kółku pierwszego gracza, musi być żywy * @param b nr na kółku drugiego gracza, musi być żywy * @return czy gracze są sąsiadami */ public Boolean czySasiedzi(int a, int b) { return (odleglosc(a, b) == 1); } /** * @param a nr na kółku pierwszego gracza, musi być żywy * @param cel nr na kółku drugiego gracza, musi być żywy * @return czy drugi gracz znajuje sie w zasięgu pierwszego */ public Boolean czyWZasiegu(int a, int cel) { return (odleglosc(a, cel) <= this.get(a).getZasieg()); } /** * Drukuje listę graczy * @param printer obiekt klasy Printer */ void print(Printer printer) { printer.println("Gracze:"); printer.zwiekszWciecie(2); for (int i = 0; i < this.size(); i++) { printer.println((i+1) + ": " + this.get(i).toString()); } printer.zwiekszWciecie(-2); } /** * Losowo zmienia kolejność graczy na kółku. */ void ustawLosowo() { Collections.shuffle(this); } } <file_sep>/src/dzikizachod/BrakSzeryfa.java package dzikizachod; public class BrakSzeryfa extends Exception { } <file_sep>/src/dzikizachod/strategia/StrategiaBandytySprytna.java package dzikizachod.strategia; import dzikizachod.Kolko; import dzikizachod.gracz.PulaGracza; import dzikizachod.WidokGracza; import dzikizachod.Wydarzenie; public class StrategiaBandytySprytna extends StrategiaBandyty { @Override public void zobaczWydarzenie(Wydarzenie wydarzenie) { } @Override protected Wydarzenie ruch(Kolko<WidokGracza> widok, PulaGracza karty) { return null; } } <file_sep>/src/dzikizachod/Zwyciestwo.java package dzikizachod; public class Zwyciestwo extends Throwable { private Druzyna druzyna; public Zwyciestwo(Druzyna druzyna) { this.druzyna = druzyna; } public String komunikatZwyciestwa() { return druzyna.toString(); } } <file_sep>/src/dzikizachod/Printer.java package dzikizachod; public class Printer { private int wciecie; Printer() { this.wciecie = 0; } public void setWciecie(int wciecie) { assert (wciecie >= 0); this.wciecie = wciecie; } public void zwiekszWciecie(int delta) { setWciecie(wciecie + delta); } public void println(String s) { for(int i = 0; i < wciecie; i++) { System.out.print(" "); } System.out.println(s); } public void println() { println(""); } } <file_sep>/src/dzikizachod/gracz/KlasaPostaci.java package dzikizachod.gracz; public enum KlasaPostaci { SZERYF("Szeryf"), BANDYTA("Bandyta"), POMOCNIK("<NAME>"), NIEZNANA(""); private String nazwa; KlasaPostaci(String nazwa) { this.nazwa = nazwa; } @Override public String toString() { return nazwa; } } <file_sep>/src/dzikizachod/gracz/PulaGracza.java package dzikizachod.gracz; import dzikizachod.Akcja; import java.util.Collection; import java.util.Comparator; import java.util.PriorityQueue; /** * Klasa reprezentująca karty znajdujące sie w ręce gracza. * Jest kolejką priorytetową z ograniczoną liczbą elementów. * Kolejność elementów w kolejce jest tą, w jakiej gracze wykonują akcje. */ public class PulaGracza extends PriorityQueue<Akcja> { private static int MAX_KART = 5; public PulaGracza() { super(new Comparator<Akcja>() { private int priorytet(Akcja a) { switch (a) { case ULECZ: return 1; case ZASIEG_PLUS_DWA: return 2; case ZASIEG_PLUS_JEDEN: return 2; case STRZEL: return 3; case DYNAMIT: return 4; default: return 0; } } @Override public int compare(Akcja akcja, Akcja t1) { return priorytet(akcja) - priorytet(t1); } }); } public Boolean isPrzepelniona() { return size() >= MAX_KART; } @Override public boolean add(Akcja akcja) { assert (size() + 1 <= MAX_KART); return super.add(akcja); } @Override public boolean addAll(Collection<? extends Akcja> collection) { assert (size() + collection.size() <= MAX_KART); return super.addAll(collection); } public PulaGracza kopia() { try { return (PulaGracza) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } } <file_sep>/src/dzikizachod/strategia/StrategiaSzeryfa.java package dzikizachod.strategia; import dzikizachod.Strategia; public abstract class StrategiaSzeryfa extends Strategia { } <file_sep>/src/dzikizachod/gracz/Bandyta.java package dzikizachod.gracz; import dzikizachod.Gracz; import dzikizachod.WidokGracza; import dzikizachod.strategia.StrategiaBandyty; import dzikizachod.strategia.StrategiaBandytyDomyslna; import java.util.Random; public class Bandyta extends Gracz { private StrategiaBandyty strategia; public Bandyta(Class rodzajStrategii) throws IllegalAccessException, InstantiationException { super((new Random()).nextInt(1) + 3, KlasaPostaci.BANDYTA); this.strategia = (StrategiaBandyty) rodzajStrategii.newInstance(); } public Bandyta() throws InstantiationException, IllegalAccessException { this(StrategiaBandytyDomyslna.class); } @Override public WidokGracza widok(Gracz patrzacy) { if (isMartwy() || (patrzacy instanceof Bandyta)) { return new WidokGracza(getZasieg(), getPunktyZycia(), getMaxPunktyZycia(), getKlasaPostaci()); } else { return new WidokGracza(getZasieg(), getPunktyZycia(), getMaxPunktyZycia(), KlasaPostaci.NIEZNANA); } } } <file_sep>/src/dzikizachod/Akcja.java package dzikizachod; public enum Akcja { ULECZ, ZASIEG_PLUS_JEDEN, ZASIEG_PLUS_DWA, STRZEL, DYNAMIT } <file_sep>/src/dzikizachod/Druzyna.java package dzikizachod; public enum Druzyna { BANDYCI("bandyci"), SZERYF_I_POMOCNICY("szeryf i pomocnicy"); private String nazwa; Druzyna(String nazwa) { this.nazwa = nazwa; } @Override public String toString() { return nazwa; } }<file_sep>/src/dzikizachod/wydarzenie/WydarzenieUlecz.java package dzikizachod.wydarzenie; import dzikizachod.*; import dzikizachod.Gracz; import dzikizachod.gracz.PrzekroczenieLimituPunktowZycia; public class WydarzenieUlecz extends Wydarzenie { public WydarzenieUlecz(int zleceniodawcaNr, int celNr) { super(zleceniodawcaNr, celNr, Akcja.ULECZ); } @Override protected WydarzenieUlecz kopia() { return new WydarzenieUlecz(getZleceniodawcaNr(), getCelNr()); } @Override public Boolean czyPoprawne(Gracze gracze) { return (getCelNr() < gracze.size()) && (getZleceniodawcaNr() < gracze.size()) && !gracze.get(getCelNr()).isMartwy() && !gracze.get(getZleceniodawcaNr()).isMartwy() && !gracze.get(getCelNr()).czyWPelniZdrowy() && (gracze.czySasiedzi(getZleceniodawcaNr(), getCelNr())); } @Override public void obsluz(Gra gra, int aktualnyGracz) throws NiepoprawneWydarzenie { Gracze gracze = gra.getGracze(); if (this.czyPoprawne(gracze)) { Gracz cel = gracze.get(getCelNr()); try { cel.setPunktyZycia(cel.getPunktyZycia() + 1); } catch (PrzekroczenieLimituPunktowZycia e) { e.printStackTrace(); } } else { throw new NiepoprawneWydarzenie(); } } public String toString() { return getTyp().toString() + " " + ((getZleceniodawcaNr() == getCelNr()) ? "" : getCelNr()); } } <file_sep>/src/dzikizachod/Gracze.java package dzikizachod; /** * Klasa reprezentująca graczy siedzących w kółku. */ public class Gracze extends Kolko<Gracz> { /** * Zwraca, jak dany gracz widzi to kółko * @param patrzacy gracz należacy do kółka * @return widok kółka graczy z perspektywy danego gracza */ Kolko<WidokGracza> widok(Gracz patrzacy) { Kolko<WidokGracza> w = new Kolko<>(); for(Gracz gracz : this) { w.add(gracz.widok(patrzacy)); } return w; } }
fd69ddaceae574d681c881025f272a653c5f46a7
[ "Java" ]
14
Java
konrad-komisarczyk/dziki_zachod
1dc019cca8b3158532519a7fd4dc446c06131506
fddce1aaf09bbe87f91494b13c6f92dd6be94e00