language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
9,471
1.726563
2
[]
no_license
package com.nbcuni.test.cms.backend.tvecms.pages.panelizer; import com.nbcuni.test.cms.backend.tvecms.pages.MainRokuAdminPage; import com.nbcuni.test.cms.elements.Button; import com.nbcuni.test.cms.elements.DropDownList; import com.nbcuni.test.cms.elements.Link; import com.nbcuni.test.cms.elements.TextField; import com.nbcuni.test.cms.elements.table.Table; import com.nbcuni.test.cms.elements.table.TableCell; import com.nbcuni.test.cms.elements.table.TableRow; import com.nbcuni.test.cms.utils.AppLib; import com.nbcuni.test.webdriver.CustomWebDriver; import com.nbcuni.test.webdriver.Utilities; import org.openqa.selenium.By; import org.openqa.selenium.support.FindBy; import java.util.List; public class PanelizerManagerPage extends MainRokuAdminPage { private final String ACTION_LINK = ".//*[@class='ctools-link']//a"; private Link addLink = new Link(webDriver, By.linkText("Add")); private Link importLink = new Link(webDriver, By.linkText("Import")); private DropDownList storage = new DropDownList(webDriver, By.id("edit-storage")); private DropDownList enabling = new DropDownList(webDriver, By.id("edit-disabled")); private DropDownList sorting = new DropDownList(webDriver, By.id("edit-order")); private DropDownList ordering = new DropDownList(webDriver, By.id("edit-sort")); private TextField search = new TextField(webDriver, By.id("edit-search")); private Button apply = new Button(webDriver, By.xpath("//input[@value='Apply']")); private Button delteConfirmation = new Button(webDriver, By.xpath(".//*[@id='edit-submit']")); private Button reset = new Button(webDriver, By.xpath("//input[@value='Reset']")); @FindBy(xpath = "//table[@id='ctools-export-ui-list-items']") private Table table; public PanelizerManagerPage(CustomWebDriver webDriver, AppLib aid) { super(webDriver, aid); } public AddPanelizerPage clickAddPanelizer() { Utilities.logInfoMessage("Click on link 'Add' to add panelizer"); addLink.click(); return new AddPanelizerPage(webDriver, aid); } public ImportPanelizerPage clickImportPanelizer() { Utilities.logInfoMessage("Click on link 'Import' to import panelizer"); importLink.click(); return new ImportPanelizerPage(webDriver, aid); } public void selectStorage(Storage value) { Utilities.logInfoMessage("Select storage: " + value); storage.selectFromDropDown(value.toString()); } public void selectEnable(Enable value) { Utilities.logInfoMessage("Select enabling: " + value); enabling.selectFromDropDown(value.toString()); } public void selectSorting(Sort value) { Utilities.logInfoMessage("Select sorting by: " + value); sorting.selectFromDropDown(value.getValue()); } public void selectOrdering(Order value) { Utilities.logInfoMessage("Select ordering by: " + value); ordering.selectFromDropDown(value.toString()); } public void apply() { Utilities.logInfoMessage("Click Apply"); apply.click(); } public void reset() { Utilities.logInfoMessage("Click Reset"); reset.click(); } /** * Method to show how possible to Open any configuration panelizer page * by clicking on action link next to panelizer Name * * @param panelizerName - name of pre-setup panelizer on each action will be performed */ public void clickContentForPanelizer(String panelizerName) { Utilities.logInfoMessage("Open Content Page for panelizer: " + panelizerName); getActionsCell(panelizerName).element().findElement(By.xpath(ACTION_LINK)).click(); getActionsCell(panelizerName).clickLinkByName(Operations.CONTENT.getValue()); } /** * Method to show how possible to Open any configuration panelizer page * by clicking on action link next to panelizer Name * * @param panelizerName - name of pre-setup panelizer on each action will be performed * @return SettingsPanelizerPage */ public SettingsPanelizerPage clickSettingForPanelizer(String panelizerName) { Utilities.logInfoMessage("Open Settings Page for panelizer: " + panelizerName); getActionsCell(panelizerName).clickLinkByName(Operations.SETTINGS.getValue()); return new SettingsPanelizerPage(webDriver, aid); } /** * Method to show how possible to Open any configuration panelizer page * by clicking on action link next to panelizer Name * * @param panelizerName - name of pre-setup panelizer on each action will be performed * @return LayoutPanelizerPage */ public LayoutPanelizerPage clickLayoutForPanelizer(String panelizerName) { Utilities.logInfoMessage("Open Layout Page for panelizer: " + panelizerName); getActionsCell(panelizerName).element().findElement(By.xpath(ACTION_LINK)).click(); getActionsCell(panelizerName).clickLinkByName(Operations.LAYOUT.getValue()); return new LayoutPanelizerPage(webDriver, aid); } /** * Method to delete panelizer * * @param panelizerName - name of pre-setup panelizer on each action will be performed */ public void deletePanelizer(String panelizerName) { Utilities.logInfoMessage("Delete panelizer: " + panelizerName); getActionsCell(panelizerName).element().findElement(By.xpath(ACTION_LINK)).click(); getActionsCell(panelizerName).clickLinkByName(Operations.DELETE.getValue()); delteConfirmation.click(); } /** * Method to clone panelizer * * @param panelizerName - name of pre-setup panelizer on each action will be performed * @return LayoutPanelizerPage */ public AddPanelizerPage clonePanelizer(String panelizerName) { Utilities.logInfoMessage("Delete panelizer: " + panelizerName); getActionsCell(panelizerName).element().findElement(By.xpath(ACTION_LINK)).click(); getActionsCell(panelizerName).clickLinkByName(Operations.CLONE.getValue()); return new AddPanelizerPage(webDriver, aid); } /** * Method to disable panelizer * * @param panelizerName - name of pre-setup panelizer on each action will be performed */ public void disablePanelizer(String panelizerName) { Utilities.logInfoMessage("Delete panelizer: " + panelizerName); getActionsCell(panelizerName).element().findElement(By.xpath(ACTION_LINK)).click(); getActionsCell(panelizerName).clickLinkByName(Operations.DISABLE.getValue()); } /** * Method to enable panelizer * * @param panelizerName - name of pre-setup panelizer on each action will be performed */ public void enablePanelizer(String panelizerName) { Utilities.logInfoMessage("Delete panelizer: " + panelizerName); getActionsCell(panelizerName).element().findElement(By.xpath(ACTION_LINK)).click(); getActionsCell(panelizerName).clickLinkByName(Operations.ENABLE.getValue()); } /** * Method to get Action cell for particular panelizer name * * @param panelizerName - name of pre-setup panelizer of each action cell will be return * @return */ private TableCell getActionsCell(String panelizerName) { Utilities.logInfoMessage("Get Cell for panelizer: " + panelizerName + " with action links"); TableRow row = table.getRowByTextInColumn(panelizerName, Columns.TITLE.toString()); return row.getCellByColumnTitle(Columns.OPERATIONS.toString()); } public void inputSearch(String searchCriteria) { Utilities.logInfoMessage("Search panelizer by criteria: " + searchCriteria); search.enterText(searchCriteria); } public boolean isPanelizerExist(String panelizerName) { Utilities.logInfoMessage("Check rather panelizer :" + panelizerName + " is present at the list"); List<String> panelizers = table.getValuesFromColumn(Columns.TITLE.toString()); return panelizers.contains(panelizerName); } public boolean isAddPanelizerLinkExist() { Utilities.logInfoMessage("Check rather Add panelizer link is present"); return addLink.isPresent() && addLink.isEnable(); } public boolean isImportPanelizerLinkExist() { Utilities.logInfoMessage("Check rather Import panelizer link is present"); return importLink.isPresent() && importLink.isEnable(); } private enum Columns { TITLE, NAME, STORAGE, OPERATIONS } private enum Operations { SETTINGS("Settings"), CONTEXT("Context"), LAYOUT("Layout"), CONTENT("Content"), ACCESS("Access"), DISABLE("Disable"), ENABLE("Enable"), CLONE("Clone"), DELETE("Delete"), EXPORT("Export"); private String value; Operations(String value) { this.value = value; } public String getValue() { return this.value; } } private enum Storage { NORMAL, DEFAULT, OVERRIDDEN } private enum Enable { ENABLED, DISABLED } private enum Order { DOWN, UP } private enum Sort { ENABLE_TITLE("Enabled, title"), TITLE("Title"), NAME("Name"), STORAGE("Storage"); private String value; Sort(String value) { this.value = value; } public String getValue() { return this.value; } } }
Python
UTF-8
582
3.203125
3
[]
no_license
import pandas as pd import numpy as np import matplotlib.pyplot as plt s = pd.Series([1,3,5,np.nan,6,8]) print(s) print('\n') dates = pd.date_range('20170101',periods=100) print(dates) print('\n') col_name = ['A', 'B', 'C', 'D'] df = pd.DataFrame(np.random.randn(100,4),index=dates,columns=col_name) print(df) print(df.head()) print(df.tail(3)) print(df.describe()) print('\n') df = pd.DataFrame(np.random.randn(100,4),index=dates,columns=col_name) df = df.cumsum() plt.figure() df.plot() plt.legend(loc='best') print('\n') df.to_csv('foo.csv') print(pd.read_csv('foo.csv'))
Java
UTF-8
3,079
2.375
2
[ "MIT" ]
permissive
package org.jasonxiao.demo.service; import org.jasonxiao.demo.exception.user.UserAlreadyExistException; import org.jasonxiao.demo.exception.user.UserNotFoundException; import org.jasonxiao.demo.model.User; import org.jasonxiao.demo.repository.UserRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.Assert; import java.util.List; import java.util.Optional; /** * @author Jason Xiao */ @Service @Transactional(propagation = Propagation.SUPPORTS, readOnly = true) public class UserServiceImpl implements UserService { private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); private final UserRepository userRepository; @Autowired public UserServiceImpl(UserRepository userRepository) { this.userRepository = userRepository; } @Override @Cacheable(value = "all_users") public List<User> getAllUsers() { logger.info("Start to fetch users from repository"); // throw new Exception("Some Error"); return userRepository.findAll(); } @Override @Cacheable(value = "user") public User getUser(Long id) throws UserNotFoundException { logger.info("Start to fetch user with id: {}", id); if (!userRepository.exists(id)) { throw new UserNotFoundException(); } return userRepository.findOne(id); } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) public User create(User user) throws UserAlreadyExistException { logger.info("Start to create user {}", user.toString()); return userRepository.save(user); } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) @CachePut(value = "user", key = "#id") public User update(Long id, User user) throws UserNotFoundException { Assert.notNull(id, "id cannot be null"); Assert.notNull(user, "user cannot be null"); User toBeUpdated = userRepository.findOne(id); if (toBeUpdated == null) throw new UserNotFoundException(); BeanUtils.copyProperties(user, toBeUpdated, "id"); if (id == 2) throw new RuntimeException("SOME ERROR!!!"); return userRepository.save(toBeUpdated); } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) @CacheEvict("user") public void delete(Long id) { userRepository.delete(id); } @Override @CacheEvict(cacheNames = {"all_users", "user"}, allEntries = true) public void evictCache() { logger.info("Evicted all cache!"); } }
Python
UTF-8
1,194
4.125
4
[]
no_license
''' process a list of numbers and return each pair of numbers that adds up to zero ''' ex = [0,-1,5,0,3,1] def sum_zero(ex): pairs = [] for index, elem in enumerate(ex): # for i in range(len(ex[index+1:])): for i in ex[index+1:]: if (elem + i) == 0: pairs.append((elem, i)) return pairs print sum_zero(ex) ''' recusive example - question on whether this works ''' # pairs = [] # l = [0,-1,5,3,1] # def sum_recursive(l): # if len(l) < 2: # return # elif (len(l) == 2) and (l[0] + l[1] == 0): # return (l[0],l[1]) # else: # return l[0] + sum_recursive(l[1:]) == 0 # len(l) = 5 # l[0] = 0 # l[1] = -1 # l[1:] = [-1, 5, 3, 1] # l[0] + sum_recursive = ? # len(l) = 4 # target = 0 # pick and hold 1 element and loop through the rest of the list and add to compare if works def return_list(l): pairs = [] for index, val in enumerate(l): pairs.append(compare_val(val, l[index+1:])) return pairs def compare_val(target,sub_list): for i in sub_list: if sum_zero(target,i): return (target, i) def sum_zero(num_1, num_2): return (num_1 + num_2 == 0)
JavaScript
UTF-8
148
2.84375
3
[ "MIT" ]
permissive
const flattenDeep = (arrs) => arrs.reduce( (acc, cur) => Array.isArray(cur) ? [...acc, ...flattenDeep(cur)] : [...acc, cur], [] )
Java
UTF-8
5,205
2.828125
3
[]
no_license
/** * Java Image Science Toolkit (JIST) * * Image Analysis and Communications Laboratory & * Laboratory for Medical Image Computing & * The Johns Hopkins University * * http://www.nitrc.org/projects/jist/ * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at * your option) any later version. The license is available for reading at: * http://www.gnu.org/copyleft/lgpl.html * */ package edu.jhu.ece.iacl.jist.pipeline.parameter; import org.w3c.dom.Document; import org.w3c.dom.Element; // TODO: Auto-generated Javadoc /** * Number Parameter storage. * * @author Blake Lucas */ public abstract class ParamNumber extends ParamModel<Number> { /** The Constant MAX_DOUBLE_VALUE. */ public static final double MAX_DOUBLE_VALUE = 1E20; /** The Constant MAX_FLOAT_VALUE. */ public static final float MAX_FLOAT_VALUE = 1E20f; /** The Constant MAX_INT_VALUE. */ public static final int MAX_INT_VALUE = 1000000000; /** The Constant MAX_LONG_VALUE. */ public static final long MAX_LONG_VALUE = 1000000000; /** The Constant MIN_DOUBLE_VALUE. */ public static final double MIN_DOUBLE_VALUE = -1E20; /** The Constant MIN_FLOAT_VALUE. */ public static final float MIN_FLOAT_VALUE = -1E20f; /** The Constant MIN_INT_VALUE. */ public static final int MIN_INT_VALUE = -1000000000; /** The Constant MIN_LONG_VALUE. */ public static final long MIN_LONG_VALUE = -1000000000; /** The max. */ protected Number max; /** The min. */ protected Number min; /** The value. */ protected Number value; /* (non-Javadoc) * @see edu.jhu.ece.iacl.jist.pipeline.parameter.ParamModel#probeDefaultValue() */ @Override public String probeDefaultValue() { return getValue().toString(); } /** * Get the number value. * * @return number value */ @Override public Number getValue() { return value; } /* * (non-Javadoc) * * @see edu.jhu.ece.iacl.jist.pipeline.parameter.ParamModel#clone() */ @Override public abstract ParamNumber clone(); /* (non-Javadoc) * @see edu.jhu.ece.iacl.jist.pipeline.parameter.ParamModel#equals(edu.jhu.ece.iacl.jist.pipeline.parameter.ParamModel) */ @Override public boolean equals(ParamModel<Number> model) { Number value1 = this.getValue(); Number value2 = model.getValue(); if (value1 == null && value2 == null) { return true; } if (value1 == null || value2 == null) { return false; } if (value1.doubleValue() == value2.doubleValue()) { return true; } else { System.err.println(getClass().getCanonicalName() + "NUMBER " + this.getLabel() + ": " + value1 + " NOT EQUAL TO " + model.getLabel() + ": " + value2); return false; } } /** * Get the number value as double. * * @return double value */ public double getDouble() { return value.doubleValue(); } /** * Get the number value as float. * * @return float value */ public float getFloat() { return value.floatValue(); } /** * Get the number value as int. * * @return integer value */ public int getInt() { return value.intValue(); } /** * Get the number value as long. * * @return long value */ public long getLong() { return value.longValue(); } /** * Get maximum possible value. * * @return the max */ public Number getMax() { return max; } /** * Get minimum possible value. * * @return the min */ public Number getMin() { return min; } /** * Set the parameter. The value must be of Number type. * * Now institutes type-safe censoring (clamping).(12/2008 bl) * * @param value * number value */ @Override public void setValue(Number value) { if (value.doubleValue() > max.doubleValue()) { value = max; } else if (value.doubleValue() < min.doubleValue()) { value = min; } this.value = value; } /** * Set the parameter. The value can be a String * * @param str * the str */ public abstract void setValue(String str); /* * (non-Javadoc) * * @see edu.jhu.ece.iacl.jist.pipeline.parameter.ParamModel#toString() */ @Override public String toString() { return String.format("%6f", value.doubleValue()); } /* (non-Javadoc) * @see edu.jhu.ece.iacl.jist.pipeline.parameter.ParamModel#xmlEncodeParam(org.w3c.dom.Document, org.w3c.dom.Element) */ @Override public boolean xmlEncodeParam(Document document, Element parent) { super.xmlEncodeParam(document, parent); Element em; em = document.createElement("value"); em.appendChild(document.createTextNode(value + "")); parent.appendChild(em); em = document.createElement("min"); em.appendChild(document.createTextNode(min + "")); parent.appendChild(em); em = document.createElement("max"); em.appendChild(document.createTextNode(max + "")); parent.appendChild(em); return true; } }
JavaScript
UTF-8
4,632
2.546875
3
[ "MIT" ]
permissive
// @flow import { createPortal } from 'react-dom'; import { PureComponent, createElement } from 'react'; import type MapboxMap from 'mapbox-gl/src/ui/map'; import type MapboxMarker from 'mapbox-gl/src/ui/marker'; import type LngLat from 'mapbox-gl/src/geo/lng_lat'; import type { PointLike } from '@mapbox/point-geometry'; import MapContext from '../MapContext'; import mapboxgl from '../../utils/mapbox-gl'; type Props = { /** Marker content */ children: React$Node, /** * A string indicating the part of the Marker * that should be positioned closest to the coordinate */ anchor: | 'center' | 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right', /** The longitude of the center of the marker. */ longitude: number, /** The latitude of the center of the marker. */ latitude: number, /** * The offset in pixels as a `PointLike` object to apply * relative to the element's center. Negatives indicate left and up. */ offset?: PointLike, /** * Boolean indicating whether or not a marker is able to be dragged * to a new position on the map. */ draggable?: boolean, /** * The rotation angle of the marker in degrees, relative to its * respective `rotationAlignment` setting. A positive value will * rotate the marker clockwise. */ rotation: number, /** * map aligns the `Marker` to the plane of the map. `viewport` * aligns the Marker to the plane of the viewport. `auto` automatically * matches the value of `rotationAlignment`. */ pitchAlignment: string, /** * map aligns the `Marker`'s rotation relative to the map, maintaining * a bearing as the map rotates. `viewport` aligns the `Marker`'s rotation * relative to the viewport, agnostic to map rotations. * `auto` is equivalent to `viewport`. */ rotationAlignment: string, /** Fired when the marker is clicked */ onClick?: () => any, /** Fired when the marker is finished being dragged */ onDragEnd?: (lngLat: LngLat) => any, /** Fired when the marker is finished being dragged */ onDragStart?: (lngLat: LngLat) => any, /** Fired when the marker is dragged */ onDrag?: (lngLat: LngLat) => any }; class Marker extends PureComponent<Props> { _map: MapboxMap; _el: HTMLDivElement; _marker: MapboxMarker; static displayName = 'Marker'; static defaultProps = { anchor: 'center', offset: null, draggable: false, rotation: 0, pitchAlignment: 'auto', rotationAlignment: 'auto' }; constructor(props: Props) { super(props); this._el = document.createElement('div'); } componentDidMount() { const { longitude, latitude, onClick, onDragEnd, onDragStart, onDrag } = this.props; this._marker = new mapboxgl.Marker({ element: this._el, anchor: this.props.anchor, draggable: this.props.draggable, offset: this.props.offset, rotation: this.props.rotation, pitchAlignment: this.props.pitchAlignment, rotationAlignment: this.props.rotationAlignment }); this._marker.setLngLat([longitude, latitude]).addTo(this._map); if (onClick) { this._el.addEventListener('click', onClick); } if (onDragEnd) { this._marker.on('dragend', this._onDragEnd); } if (onDragStart) { this._marker.on('dragstart', this._onDragStart); } if (onDrag) { this._marker.on('drag', this._onDrag); } } componentDidUpdate(prevProps: Props) { const positionChanged = prevProps.latitude !== this.props.latitude || prevProps.longitude !== this.props.longitude; if (positionChanged) { this._marker.setLngLat([this.props.longitude, this.props.latitude]); } } componentWillUnmount() { if (!this._map || !this._map.getStyle()) { return; } if (this.props.onClick) { this._el.removeEventListener('click', this.props.onClick); } this._marker.remove(); } getMarker() { return this._marker; } _onDragEnd = (): void => { // $FlowFixMe this.props.onDragEnd(this._marker.getLngLat()); }; _onDragStart = (): void => { // $FlowFixMe this.props.onDragStart(this._marker.getLngLat()); }; _onDrag = (): void => { // $FlowFixMe this.props.onDrag(this._marker.getLngLat()); }; render() { return createElement(MapContext.Consumer, {}, (map) => { if (map) { this._map = map; } return createPortal(this.props.children, this._el); }); } } export default Marker;
JavaScript
UTF-8
783
2.53125
3
[]
no_license
// Son kiritish var num1 = +prompt("1-sonni kiriting") var num2 = +prompt("2-sonni kiriting") var num3 = +prompt("3-sonni kiriting") // Shartlar va Javoblar if (num1 > num2 && num1 < num3 || num1 > num3 && num1 < num2) { alert('Siz kiritgan sonlar: ' + num1 + ', ' + num2 + ', ' + num3 + '.\nBularning ichida o`rta qiymatalisi: ' + num1) } else if (num2 > num1 && num2 < num3 || num2 > num3 && num2 < num1) { alert('Siz kiritgan sonlar: ' + num1 + ', ' + num2 + ', ' + num3 + '.\nBularning ichida o`rta qiymatalisi: ' + num2) } else if (num3 > num1 && num3 < num2 || num3 > num2 && num3 < num1) { alert('Siz kiritgan sonlar: ' + num1 + ', ' + num2 + ', ' + num3 + '.\nBularning ichida o`rta qiymatalisi: ' + num3) } else { alert("UPS!!! Nimadir xato ketti...") }
Java
ISO-8859-1
2,523
1.984375
2
[]
no_license
package fr.intervia.controller; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import fr.intervia.dao.CompteExploitationDAO; import fr.intervia.dao.CompteMensuelDAO; import fr.intervia.dao.ConsultantDAO; import fr.intervia.dao.MoisCampagneDAO; import fr.intervia.domaine.CompteExploitation; import fr.intervia.domaine.CompteMensuel; import fr.intervia.domaine.Consultant; import fr.intervia.domaine.MoisCampagne; import fr.intervia.service.CompteExploitationService; import fr.intervia.service.CompteMensuelService; import fr.intervia.service.MoisCampagneService; @Controller public class CompteMensuelController { @Autowired private CompteMensuelDAO faDAO; @Autowired private MoisCampagneDAO moisDAO; @Autowired private ConsultantDAO consultantDAO; @Autowired private CompteMensuelService fService; @Autowired private MoisCampagneService moisService; @Autowired private CompteExploitationService ceService; @GetMapping("/consultant/{id}/flux") public String flux(Model model, @PathVariable("id") int id) { //On initialise les infos sur le consultant Consultant consultant = consultantDAO.find(id); // On rccupre les infos sur le mois List<MoisCampagne> listeMois= moisDAO.loadMois(); MoisCampagne moisCourant= moisService.getMoisCourant(listeMois); // On rcupre les comptes mensuels List<CompteMensuel> fa = faDAO.findByCode(consultant.getCodeConsultant()); // o n identifie le compte courant CompteMensuel cmCourant = fService.getCompte(fa, moisCourant); Map<String,Float> cumuls = fService.calculerCumul(fa, moisCourant); Map<String,Double> cumulPaie = ceService.calculerCum(fa, moisCourant); model.addAttribute("consultant", consultant); model.addAttribute("fluxActivite", fa);; model.addAttribute("fluxCumul", cumuls); //Donnes ncessaire au compte d'exploitation model.addAttribute("factureHT", fService.calculerFactureHT(fa, moisCourant)); model.addAttribute("commission", fService.calculerCommission(fa)); model.addAttribute("moisCourant", moisCourant); model.addAttribute("cmCourant", cmCourant); model.addAttribute("sousTotal", ceService.calculerSousTotal(cmCourant.getComptes())); model.addAttribute("cumulPaie", cumulPaie); return "compteMensuel"; } }
C
UTF-8
513
3.1875
3
[]
no_license
#include "3-calc.h" #include <stdio.h> #include <stdlib.h> /** *main - description *@ac: count the elements *@av: put the arguments *Return: 0 **/ int main(int ac, char *av[]) { if (ac != 4) { printf("Error\n"); exit(98); } if ((av[2][0] == '/' || av[2][0] == '%') && av[2][1] == '\0' && av[3][0] == '0') { printf("Error\n"); exit(100); } if (get_op_func(av[2]) == NULL) { printf("Error\n"); exit(99); } printf("%d\n", get_op_func(av[2])(atoi(av[1]), atoi(av[3]))); return (0); }
Java
UTF-8
27,694
2.578125
3
[]
no_license
package AntMe.Simulation; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.Random; import java.util.ResourceBundle; /// <summary> /// Abstrakte Basisklasse für alle Insekten. /// </summary> /// <author>Wolfgang Gallo (wolfgang@antme.net)</author> public abstract class CoreInsect implements ICoordinate { /// <summary> /// Die Id des nächste erzeugten Insekts. /// </summary> private static int neueId = 0; ResourceBundle bundle = ResourceBundle.getBundle("package.Resource", Locale.getDefault()); /// <summary> /// Speichert die Markierungen, die das Insekt schon gesehen hat. Das /// verhindert, daß das Insekt zwischen Markierungen im Kreis läuft. /// </summary> private ArrayList<CoreMarker> smelledMarker = new ArrayList<CoreMarker>(); ArrayList<CoreMarker> getSmelledMarker() { return smelledMarker; } private boolean reached = false; private int antCount = 0; private int casteCount = 0; private int colonyCount = 0; private int bugCount = 0; private int teamCount = 0; private CoreFruit getragenesObst; /// <summary> /// Die Id die das Insekt w�hrend eines Spiels eindeutig indentifiziert. /// </summary> private int id; int getId() { return id; } /// <summary> /// Die Position des Insekts auf dem Spielfeld. /// </summary> private CoreCoordinate koordinate; CoreCoordinate getKoordinate() { return koordinate; } /// <summary> /// Legt fest, ob das Insekt Befehle entgegen nimmt. /// </summary> private boolean nimmBefehleEntgegen = false; boolean isNimmBefehleEntgegen() { return nimmBefehleEntgegen; } private int restStreckeI; private int restWinkel = 0; /// <summary> /// Der Index der Kaste des Insekts in der Kasten-Struktur des Spielers. /// </summary> private int casteIndexBase; int getCasteIndexBase() { return casteIndexBase; } void setCasteIndexBase(int value) { casteIndexBase = value; } /// <summary> /// Das Volk zu dem das Insekts geh�rt. /// </summary> private CoreColony colony; public CoreColony getColony() { return colony; } public void setColony(CoreColony value) { colony = value; } private ICoordinate ziel = null; private int zurueckgelegteStreckeI; CoreInsect() { } /// <summary> /// Die Kaste des Insekts. /// </summary> public String getKasteBase() { return colony.getPlayer().getCastes().get(getCasteIndexBase()).getName(); } /// <summary> /// Die Anzahl von Wanzen in Sichtweite des Insekts. /// </summary> public int getBugsInViewrange() { return bugCount; } public void setBugsInViewrange(int value) { bugCount = value; } /// <summary> /// Die Anzahl feindlicher Ameisen in Sichtweite des Insekts. /// </summary> public int getForeignAntsInViewrange() { return antCount; } public void setForeignAntsInViewrange(int value) { antCount = value; } /// <summary> /// Die Anzahl befreundeter Ameisen in Sichtweite des Insekts. /// </summary> public int getFriendlyAntsInViewrange() { return colonyCount; } public void setFriendlyAntsInViewrange(int value) { colonyCount = value; } /// <summary> /// Die Anzahl befreundeter Ameisen der selben Kaste in Sichtweite des /// Insekts. /// </summary> public int getFriendlyAntsFromSameCasteInViewrange() { return casteCount; } public void setFriendlyAntsFromSameCasteInViewrange(int value) { casteCount = value; } /// <summary> /// Anzahl Ameisen aus befreundeten V�lkern in sichtweite des Insekts. /// </summary> public int getTeamAntsInViewrange() { return teamCount; } public void setTeamAntsInViewrange(int value) { teamCount = value; } /// <summary> /// Die Richtung in die das Insekt gedreht ist. /// </summary> public int getRichtungBase() { return koordinate.getRichtung(); } /// <summary> /// Die Strecke die die Ameise zur�ckgelegt hat, seit sie das letzte Mal in /// einem Ameisenbau war. /// </summary> public int getZurueckgelegteStreckeBase() { return zurueckgelegteStreckeI / SimulationEnvironment.PLAYGROUND_UNIT; } /// <summary> /// Die Strecke die die Ameise zur�ckgelegt hat, seit sie das letzte Mal in /// einem Ameisenbau war in der internen Einheit. /// </summary> public int getZurueckgelegteStreckeI() { return zurueckgelegteStreckeI; } public void setZurueckgelegteStreckeI(int value) { zurueckgelegteStreckeI = value; } /// <summary> /// Die Strecke die das Insekt geradeaus gehen wird, bevor das n�chste Mal /// Wartet() aufgerufen wird bzw. das Insekt sich zu seinem Ziel ausrichtet. /// </summary> public int getRestStreckeBase() { return restStreckeI / SimulationEnvironment.PLAYGROUND_UNIT; } /// <summary> /// Die Strecke die das Insekt geradeaus gehen wird, bevor das n�chste /// Mal Wartet() aufgerufen wird bzw. das Insekt sich zu seinem Ziel /// ausrichtet in der internen Einheit. /// </summary> public int getRestStreckeI() { return restStreckeI; } public void setRestStreckeI(int value) { restStreckeI = value; } /// <summary> /// Der Winkel um den das Insekt sich noch drehen mu�, bevor es wieder /// geradeaus gehen kann. /// </summary> public int getRestWinkelBase() { return restWinkel; } public void setRestWinkelBase(int value) { // TODO: Modulo? restWinkel = value; while (restWinkel > 180) { restWinkel -= 360; } while (restWinkel < -180) { restWinkel += 360; } } /// <summary> /// Das Ziel auf das das Insekt zugeht. /// </summary> public ICoordinate getZielBase() { return ziel; } public void setZielBase(ICoordinate value) { if (ziel != value || value == null) { ziel = value; restWinkel = 0; restStreckeI = 0; } } /// <summary> /// Liefert die Entfernung in Schritten zum n�chsten Ameisenbau. /// </summary> public int getEntfernungZuBauBase() { int aktuelleEntfernung; int gemerkteEntfernung = Integer.MAX_VALUE; for (CoreAnthill bau : colony.getAntHills()) { aktuelleEntfernung = CoreCoordinate.bestimmeEntfernungI(getCoordinateBase(), bau.getCoordinateBase()); if (aktuelleEntfernung < gemerkteEntfernung) { gemerkteEntfernung = aktuelleEntfernung; } } return gemerkteEntfernung / SimulationEnvironment.PLAYGROUND_UNIT; } /// <summary> /// Gibt das Obst zur�ck, das das Insekt gerade tr�gt. /// </summary> public CoreFruit getGetragenesObstBase() { return getragenesObst; } public void setGetragenesObstBase(CoreFruit value) { getragenesObst = value; } /// <summary> /// Gibt zur�ck on das Insekt bei seinem Ziel angekommen ist. /// </summary> public boolean getAngekommenBase() { return reached; } private Random randomBase; public Random getRandomBase() { return randomBase; } private void setRandomBase(Random value) { randomBase = value; } /// <summary> /// Die Position des Insekts auf dem Spielfeld. /// </summary> public CoreCoordinate getCoordinateBase() { return koordinate; } void setCoordinateBase(CoreCoordinate value) { koordinate = value; } /// <summary> /// Der abstrakte Insekt-Basiskonstruktor. /// </summary> /// <param name="colony">Das Volk zu dem das neue Insekt geh�rt.</param> /// <param name="vorhandeneInsekten">Hier unbenutzt!</param> void init(CoreColony colony, Random random, HashMap<String, Integer> vorhandeneInsekten) { id = neueId; neueId++; this.colony = colony; this.randomBase = random; koordinate.setRichtung(randomBase.nextInt(359)); // Zuf�llig auf dem Spielfeldrand platzieren. if (colony.getAntHills().size() == 0) // Am oberen oder unteren Rand platzieren. { if (randomBase.nextInt(2) == 0) { koordinate.setX(randomBase.nextInt(colony.getPlayground().getWidth()) * SimulationEnvironment.PLAYGROUND_UNIT); if (randomBase.nextInt(2) == 0) { koordinate.setY(0); } else { koordinate.setY(colony.getPlayground().getHeight() * SimulationEnvironment.PLAYGROUND_UNIT); } } // Am linken oder rechten Rand platzieren. else { if (randomBase.nextInt(2) == 0) { koordinate.setX(0); } else { koordinate.setX(colony.getPlayground().getWidth() * SimulationEnvironment.PLAYGROUND_UNIT); } koordinate.setY(randomBase.nextInt(colony.getPlayground().getHeight())*SimulationEnvironment.PLAYGROUND_UNIT); } } // In einem zuf�lligen Bau platzieren. else { int i = randomBase.nextInt(colony.getAntHills().size()); koordinate.setX(colony.getAntHills().get(i).getCoordinateBase().getX() + SimulationEnvironment.cosinus( colony.getAntHills().get(i).getCoordinateBase().getRadius(), koordinate.getRichtung())); koordinate.setY(colony.getAntHills().get(i).getCoordinateBase().getY() + SimulationEnvironment.sinus( colony.getAntHills().get(i).getCoordinateBase().getRadius(), koordinate.getRichtung())); } } /// <summary> /// Gibt an, ob weitere Insekten ben�tigt werden, um ein St�ck Obst zu /// tragen. /// </summary> /// <param name="obst">Obst</param> /// <returns></returns> boolean brauchtNochTraeger(CoreFruit obst) { return obst.brauchtNochTraeger(colony); } /// <summary> /// Dreht das Insekt um den angegebenen Winkel. Die maximale Drehung betr�gt /// -180 Grad (nach links) bzw. 180 Grad (nach rechts). Gr��ere Werte werden /// abgeschnitten. /// </summary> /// <param name="winkel">Winkel</param> void dreheUmWinkelBase(int winkel) { if (!nimmBefehleEntgegen) { return; } setRestWinkelBase(winkel); } /// <summary> /// Dreht das Insekt in die angegebene Richtung (Grad). /// </summary> /// <param name="richtung">Richtung</param> void dreheInRichtungBase(int richtung) { if (!nimmBefehleEntgegen) { return; } dreheInRichtung(richtung); } private void dreheInRichtung(int richtung) { setRestWinkelBase(richtung - koordinate.getRichtung()); } /// <summary> /// Dreht das Insekt in die Richtung des angegebenen Ziels. /// </summary> /// <param name="ziel">Ziel</param> void dreheZuZielBase(ICoordinate ziel) { dreheInRichtungBase(CoreCoordinate.bestimmeRichtung(this, ziel)); } /// <summary> /// Dreht das Insekt um 180 Grad. /// </summary> void dreheUmBase() { if (!nimmBefehleEntgegen) { return; } if (restWinkel > 0) { restWinkel = 180; } else { restWinkel = -180; } } /// <summary> /// L�sst das Insekt unbegrenzt geradeaus gehen. /// </summary> void geheGeradeausBase() { if (!nimmBefehleEntgegen) { return; } restStreckeI = Integer.MAX_VALUE; } /// <summary> /// L�sst das Insekt die angegebene Entfernung in Schritten geradeaus gehen. /// </summary> /// <param name="entfernung">Die Entfernung.</param> void geheGeradeausBase(int entfernung) { if (!nimmBefehleEntgegen) { return; } restStreckeI = entfernung * SimulationEnvironment.PLAYGROUND_UNIT; } /// <summary> /// L�sst das Insekt auf ein Ziel zugehen. Das Ziel darf sich bewegen. /// Wenn das Ziel eine Wanze ist, wird dieser angegriffen. /// </summary> /// <param name="ziel">Das Ziel.</param> void geheZuZielBase(ICoordinate ziel) { if (!nimmBefehleEntgegen) { return; } setZielBase(ziel); } /// <summary> /// L�sst das Insekt ein Ziel angreifen. Das Ziel darf sich bewegen. /// In der aktuellen Version kann das Ziel nur eine Wanze sein. /// </summary> /// <param name="ziel">Ziel</param> void greifeAnBase(CoreInsect ziel) { if (!nimmBefehleEntgegen) { return; } setZielBase(ziel); } /// <summary> /// L�sst das Insekt von der aktuellen Position aus entgegen der Richtung zu /// einer Quelle gehen. Wenn die Quelle ein Insekt eines anderen Volkes ist, /// befindet sich das Insekt auf der Flucht. /// </summary> /// <param name="quelle">Die Quelle.</param> void geheWegVonBase(ICoordinate quelle) { dreheInRichtungBase(CoreCoordinate.bestimmeRichtung(this, quelle) + 180); geheGeradeausBase(); } /// <summary> /// L�sst das Insekt von der aktuellen Position aus die angegebene /// Entfernung in Schritten entgegen der Richtung zu einer Quelle gehen. /// Wenn die Quelle ein Insekt eines anderen Volkes ist, befindet sich das /// Insekt auf der Flucht. /// </summary> /// <param name="quelle">Die Quelle.</param> /// <param name="entfernung">Die Entfernung in Schritten.</param> void geheWegVonBase(ICoordinate quelle, int entfernung) { dreheInRichtungBase(CoreCoordinate.bestimmeRichtung(this, quelle) + 180); geheGeradeausBase(entfernung); } /// <summary> /// L�sst das Insekt zum n�chsten Bau gehen. /// </summary> void geheZuBauBase() { if (!nimmBefehleEntgegen) { return; } int aktuelleEntfernung; int gemerkteEntfernung = Integer.MAX_VALUE; CoreAnthill gemerkterBau = null; for (CoreAnthill bau : colony.getAntHills()) { aktuelleEntfernung = CoreCoordinate.bestimmeEntfernungI(getCoordinateBase(), bau.getCoordinateBase()); if (aktuelleEntfernung < gemerkteEntfernung) { gemerkterBau = bau; gemerkteEntfernung = aktuelleEntfernung; } } geheZuZielBase(gemerkterBau); } /// <summary> /// L�sst das Insekt anhalten. Dabei geht sein Ziel verloren. /// </summary> void bleibStehenBase() { if (!nimmBefehleEntgegen) { return; } setZielBase(null); restStreckeI = 0; restWinkel = 0; } /// <summary> /// L�sst das Insekt Zucker von einem Zuckerhaufen nehmen. /// </summary> /// <param name="zucker">Zuckerhaufen</param> void nimmBase(CoreSugar zucker) { if (!nimmBefehleEntgegen) { return; } int entfernung = CoreCoordinate.bestimmeEntfernungI(getCoordinateBase(), zucker.getCoordinateBase()); if (entfernung <= SimulationEnvironment.PLAYGROUND_UNIT) { int menge = Math.min(getMaximaleLastBase() - aktuelleLast, zucker.getMenge()); setAktuelleLastBase(getAktuelleLastBase()+menge); zucker.setMenge(zucker.getMenge()-menge); } else { try { Thread.sleep(0); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /// <summary> /// L�sst das Insekt ein Obstst�ck nehmen. /// </summary> /// <param name="obst">Das Obstst�ck.</param> void nimmBase(CoreFruit obst) { if (!nimmBefehleEntgegen) { return; } if (getGetragenesObstBase() == obst) { return; } if (getGetragenesObstBase() != null) { lasseNahrungFallenBase(); } int entfernung = CoreCoordinate.bestimmeEntfernungI(getCoordinateBase(), obst.getCoordinateBase()); if (entfernung <= SimulationEnvironment.PLAYGROUND_UNIT) { bleibStehenBase(); setGetragenesObstBase(obst); obst.getTragendeInsekten().add(this); setAktuelleLastBase(colony.getLast()[casteIndexBase]); } } /// <summary> /// L�sst das Insekt die aktuell getragene Nahrung fallen. Das Ziel des /// Insekts geht dabei verloren. /// </summary> void lasseNahrungFallenBase() { if (!isNimmBefehleEntgegen()) { return; } setAktuelleLastBase(0); setZielBase(null); if (getGetragenesObstBase() != null) { getGetragenesObstBase().getTragendeInsekten().remove(this); setGetragenesObstBase(null); } } /// <summary> /// L�sst die Ameise eine Markierung spr�hen. Die Markierung enth�lt die /// angegebene Information und breitet sich um die angegebene Anzahl an /// Schritten weiter aus. Je weiter sich eine Markierung ausbreitet, desto /// k�rzer bleibt sie aktiv. /// </summary> /// <param name="information">Die Information.</param> /// <param name="ausbreitung">Die Ausbreitung in Schritten.</param> void sprueheMarkierungBase(int information, int ausbreitung) throws AiException { if (!isNimmBefehleEntgegen()) { return; } // Check for unsupported markersize if (ausbreitung < 0) { throw new AiException(String.format("{0}: {1}", colony.getPlayer().getGuid(), bundle.getString("SimulationCoreNegativeMarkerSize"))); } CoreMarker markierung = new CoreMarker(koordinate, ausbreitung, colony.getId()); markierung.setInformation(information); colony.getNewMarker().add(markierung); smelledMarker.add(markierung); } /// <summary> /// L�sst die Ameise eine Markierung spr�hen. Die Markierung enth�lt die /// angegebene Information und breitet sich nicht aus. So hat die Markierung /// die maximale Lebensdauer. /// </summary> /// <param name="information">Die Information.</param> void sprueheMarkierungBase(int information) throws AiException { if (!isNimmBefehleEntgegen()) { return; } sprueheMarkierungBase(information, 0); } /// <summary> /// Berechnet die Bewegung des Insekts. /// </summary> void bewegen() { reached = false; // Insekt dreht sich. if (restWinkel != 0) { // Zielwinkel wird erreicht. if (Math.abs(restWinkel) < colony.getDrehgeschwindigkeit()[casteIndexBase]) { koordinate.setRichtung(koordinate.getRichtung() + restWinkel); restWinkel = 0; } // Insekt dreht sich nach rechts. else if (restWinkel >= colony.getDrehgeschwindigkeit()[casteIndexBase]) { koordinate.setRichtung(koordinate.getRichtung() + colony.getDrehgeschwindigkeit()[casteIndexBase]); setRestWinkelBase(getRestWinkelBase() - colony.getDrehgeschwindigkeit()[casteIndexBase]); } // Insekt dreht sich nach links. else if (restWinkel <= -colony.getDrehgeschwindigkeit()[casteIndexBase]) { koordinate.setRichtung(koordinate.getRichtung() - colony.getDrehgeschwindigkeit()[casteIndexBase]); setRestWinkelBase(getRestWinkelBase() + colony.getDrehgeschwindigkeit()[casteIndexBase]); } } // Insekt geht. else if (restStreckeI > 0) { if (getGetragenesObstBase() == null) { int strecke = Math.min(restStreckeI, aktuelleGeschwindigkeitI); restStreckeI -= strecke; zurueckgelegteStreckeI += strecke; koordinate.setX(koordinate.getX()+SimulationEnvironment.Cos[strecke][koordinate.getRichtung()]); koordinate.setY(koordinate.getY()+SimulationEnvironment.Sin[strecke][koordinate.getRichtung()]); } } // Insekt geht auf Ziel zu. else if (ziel != null) { int entfernungI; if (getZielBase().getClass() == CoreMarker.class) { entfernungI = CoreCoordinate.bestimmeEntfernungDerMittelpunkteI(koordinate, ziel.getCoordinateBase()); } else { entfernungI = CoreCoordinate.bestimmeEntfernungI(koordinate, ziel.getCoordinateBase()); } reached = entfernungI <= SimulationEnvironment.PLAYGROUND_UNIT; if (!reached) { int richtung = CoreCoordinate.bestimmeRichtung(koordinate, ziel.getCoordinateBase()); // Ziel ist in Sichtweite oder Insekt tr�gt Obst. if (entfernungI < colony.getSichtweiteI()[casteIndexBase] || getragenesObst != null) { restStreckeI = entfernungI; } // Ansonsten Richtung verf�lschen. else { richtung += getRandomBase().nextInt(36)-18; restStreckeI = colony.getSichtweiteI()[casteIndexBase]; } dreheInRichtung(richtung); } } // Koordinaten links begrenzen. if (koordinate.getX() < 0) { koordinate.setX(-koordinate.getX()); if (koordinate.getRichtung() > 90 && koordinate.getRichtung() <= 180) { koordinate.setRichtung(180 - koordinate.getRichtung()); } else if (koordinate.getRichtung() > 180 && koordinate.getRichtung() < 270) { koordinate.setRichtung(540 - koordinate.getRichtung()); } } // Koordinaten rechts begrenzen. else if (koordinate.getX() > colony.getBreiteI()) { koordinate.setX(colony.getBreiteI2() - koordinate.getX()); if (koordinate.getRichtung() >= 0 && koordinate.getRichtung() < 90) { koordinate.setRichtung(180 - koordinate.getRichtung()); } else if (koordinate.getRichtung() > 270 && koordinate.getRichtung() < 360) { koordinate.setRichtung(540 - koordinate.getRichtung()); } } // Koordinaten oben begrenzen. if (koordinate.getY() < 0) { koordinate.setY(-koordinate.getY()); if (koordinate.getRichtung() > 180 && koordinate.getRichtung() < 360) { koordinate.setRichtung(360 - koordinate.getRichtung()); } } // Koordinaten unten begrenzen. else if (koordinate.getY() > colony.getHoeheI()) { koordinate.setY(colony.getHoeheI2() - koordinate.getY()); if (koordinate.getRichtung() > 0 && koordinate.getRichtung() < 180) { koordinate.setRichtung(360 - koordinate.getRichtung()); } } } /// <summary> /// Die aktuelle Geschwindigkeit des Insekts in der internen Einheit. /// </summary> int aktuelleGeschwindigkeitI; /// <summary> /// Die aktuelle Geschwindigkeit des Insekts in Schritten. Wenn das Insekt /// seine maximale Last tr�gt, halbiert sich seine Geschwindigkeit. /// </summary> int getAktuelleGeschwindigkeitBase() { return aktuelleGeschwindigkeitI / SimulationEnvironment.PLAYGROUND_UNIT; } /// <summary> /// Die maximale Geschwindigkeit des Insekts. /// </summary> int getMaximaleGeschwindigkeitBase() { return colony.getGeschwindigkeitI()[casteIndexBase] / SimulationEnvironment.PLAYGROUND_UNIT; } /// <summary> /// Die Drehgeschwindigkeit des Insekts in Grad pro Runde. /// </summary> int getDrehgeschwindigkeitBase() { return colony.getDrehgeschwindigkeit()[casteIndexBase]; } private int aktuelleLast = 0; /// <summary> /// Die Last die die Ameise gerade tr�gt. /// </summary> int getAktuelleLastBase() { return aktuelleLast; } void setAktuelleLastBase(int value) { aktuelleLast = value >= 0 ? value : 0; aktuelleGeschwindigkeitI = colony.getGeschwindigkeitI()[casteIndexBase]; aktuelleGeschwindigkeitI -= aktuelleGeschwindigkeitI * aktuelleLast / colony.getLast()[casteIndexBase] / 2; } /// <summary> /// Die maximale Last die das Insekt tragen kann. /// </summary> int getMaximaleLastBase() { return colony.getLast()[casteIndexBase]; } /// <summary> /// Die Sichtweite des Insekts in Schritten. /// </summary> int getSichtweiteBase() { return colony.getSichtweiteI()[casteIndexBase] / SimulationEnvironment.PLAYGROUND_UNIT; } /// <summary> /// Die Sichtweite des Insekts in der internen Einheit. /// </summary> int getSichtweiteI() { return colony.getSichtweiteI()[casteIndexBase]; } /// <summary> /// Die Reichweite des Insekts in Schritten. /// </summary> int getReichweiteBase() { return colony.getReichweiteI()[casteIndexBase] / SimulationEnvironment.PLAYGROUND_UNIT; } /// <summary> /// Die Reichweite des Insekts in der internen Einheit. /// </summary> int getReichweiteI() { return colony.getReichweiteI()[casteIndexBase]; } private int aktuelleEnergie; /// <summary> /// Die verbleibende Energie des Insekts. /// </summary> int getAktuelleEnergieBase() { return aktuelleEnergie; } void setAktuelleEnergieBase(int value) { aktuelleEnergie = value >= 0 ? value : 0; } /// <summary> /// Die maximale Energie des Insetks. /// </summary> int getMaximaleEnergieBase() { return colony.getEnergie()[casteIndexBase]; } private int angriff; /// <summary> /// Die Angriffst�rke des Insekts. Wenn das Insekt Last tr�gt ist die /// Angriffst�rke gleich Null. /// </summary> int getAngriffBase() { return aktuelleLast == 0 ? angriff : 0; } void setAngriffBase(int value) { angriff = value >= 0 ? value : 0; } String debugMessage; void denkeCore(String message) { debugMessage = message.length() > 100 ? message.substring(0, 100) : message; } }
Python
UTF-8
12,659
2.65625
3
[ "MIT" ]
permissive
import numpy as np from numpy.random import Generator, PCG64 import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patches import Patch from modpy.stats import metropolis_hastings from modpy.stats._core import auto_correlation, auto_correlation_time from modpy.plot.plot_util import cm_parula, default_color, set_font_sizes from modpy.illustration.illustration_util import STATS_PATH def _plot_MH_1D(): # example from: http://www.mit.edu/~ilkery/papers/MetropolisHastingsSampling.pdf seed = 1234 gen = Generator(PCG64(seed)) n = 150 samples = 100000 mu = np.array([0., 0.]) rho = 0.45 sigma = np.array([(1., rho), [rho, 1.]]) x1, x2 = gen.multivariate_normal(mu, sigma, n).T rho_emp = np.corrcoef(x1, x2)[0, 1] # arbitrary symmetrical distribution def proposal(rho_): return np.atleast_1d(gen.uniform(rho_ - 0.07, rho_ + 0.07)) # bi-variate normal distribution with mu1=mu2=0 and sigma1=sigma2=1 def log_like(rho_): p = 1. / (2. * np.pi * np.sqrt(1. - rho_ ** 2.)) * np.exp(-1. / (2. * (1. - rho_ ** 2.)) * (x1 ** 2 - 2. * rho_ * x1 * x2 + x2 ** 2.)) return np.sum(np.log(p)) # Jeffreys prior def log_prior(rho_): return np.log((1. / (1. - rho_ ** 2.)) ** 1.5) rho0 = np.array([0.]) res = metropolis_hastings(rho0, proposal, log_like, log_prior, samples, burn=100, seed=seed, keep_path=True) xp = res.x # calculate auto-correlation and determine lag-time until independence. lags = 100 auto_corr = auto_correlation(xp.flatten(), lags) tau = auto_correlation_time(xp.flatten()) # sub-sample only uncorrelated samples xp_ind = xp[::tau] samples_ind = np.arange(0, samples, tau) rho_sam = np.mean(xp_ind) # plot problem plots ----------------------------------------------------------------------------------------------- # # plot observations # ax1.scatter(x1, x2, s=20, color=default_color(0)) # ax1.set_xlabel('$x_1$') # ax1.set_ylabel('$x_2$') # ax1.grid(True) # ax1.set_title('Data') # set_font_sizes(ax1, 12) # # plot the log-likelihood over the domain [-1, 1] # k = 500 # rhos = np.linspace(-0.999, 0.999, k) # L = np.array([log_like(r) for r in rhos]) # # ax4.plot(rhos, L, color=default_color(0)) # ax4.set_xlabel('$\\rho$') # ax4.set_ylabel('$\log(f(\\rho | x, y))$') # ax4.grid(True) # ax4.set_title('Log-Likelihood') # set_font_sizes(ax4, 12) # # # plot the log-prior probability # ax5.plot(rhos, log_prior(rhos), color=default_color(0)) # ax5.set_xlabel('$\\rho$') # ax5.set_ylabel('$\log(f(\\rho))$') # ax5.grid(True) # ax5.set_title('Log-Prior Probability') # set_font_sizes(ax5, 12) # plot HMC behaviour plots ----------------------------------------------------------------------------------------- # plot fig, axes = plt.subplots(2, 3, figsize=(20, 14)) ax1, ax2, ax3, ax4 , ax5, ax6 = axes.flatten() # plot markov chain ax1.plot(np.arange(samples), xp, color=default_color(0), label='Full') ax1.plot(samples_ind, xp_ind, color=default_color(1), label='Thinned') ax1.plot([0, samples], [rho, rho], 'k', label='True $\\rho$') ax1.plot([0, samples], [rho_emp, rho_emp], color='m', label='Empirical $\\rho$') ax1.plot([0, samples], [rho_sam, rho_sam], lw=2, color='orange', label='Sampled $\\rho$') ax1.set_xlim([0, samples]) ax1.set_ylim([0.2, 0.7]) ax1.set_xlabel('Samples') ax1.set_ylabel('$\\rho$') ax1.legend(loc='upper right') ax1.grid(True) ax1.set_title('Markov Chain') set_font_sizes(ax1, 12) # plot histogram of rho hist = ax2.hist(xp, 50, facecolor=default_color(0)) # , edgecolor='k', linewidth=0.2 freq = hist[0] max_freq = np.amax(freq) * 1.1 ax2.plot([rho, rho], [0, max_freq], color='k', label='True $\\rho$') ax2.plot([rho_emp, rho_emp], [0, max_freq], color='m', label='Empirical $\\rho$') ax2.plot([rho_sam, rho_sam], [0, max_freq], lw=2, color='orange', label='Sampled $\\rho$') ax2.set_xlim([0.2, 0.7]) ax2.set_ylim([0., max_freq]) ax2.set_xlabel('$\\rho$') ax2.set_ylabel('Frequency (ind.)') ax2.grid(True) ax2.set_title('Posterior Distribution') set_font_sizes(ax2, 12) ax2_1 = ax2.twinx() ax2_1.hist(xp_ind, 50, facecolor=default_color(1), alpha=0.35) # , edgecolor='k', linewidth=0.2 ax2_1.set_ylabel('Frequency') set_font_sizes(ax2_1, 12) ax2.legend(handles=(Patch(color=default_color(0), label='Full'), Patch(color=default_color(1), label='Thinned'), Line2D([], [], color='k', label='True $\\rho$'), Line2D([], [], color='m', label='Empirical $\\rho$'), Line2D([], [], color='orange', label='Sampled $\\rho$'))) # plot the autocorrelation ax3.plot(np.arange(lags), auto_corr, color=default_color(0), label='Auto-correlation') ax3.plot([tau, tau], [-1., 1.], 'k--', label='Lag-time, $\\tau}$') ax3.set_xlim([0., lags]) ax3.set_ylim([-0.1, 1.]) ax3.set_xlabel('Lag') ax3.set_ylabel('Auto-Correlation') ax3.legend() ax3.grid(True) ax3.set_title('Auto-Correlation') set_font_sizes(ax3, 12) # plot the acceptance probability ax4.plot(np.arange(res.path.accept.size), res.path.accept, color=default_color(0)) # , label='$\delta$' #ax4.plot([0, res.path.accept.size], [0.65, 0.65], 'k--', label='$\delta_{target}$') ax4.set_xlim([0, res.path.accept.size]) ax4.set_ylim([0., 1.]) ax4.set_xlabel('Samples (incl. burn-in)') ax4.set_ylabel('Acceptance Ratio, $\delta$') ax4.grid(True) #ax4.legend() ax4.set_title('Acceptance Ratio') set_font_sizes(ax4, 12) fig.savefig(STATS_PATH + '1D_performance_metropolis.png') def _plot_MH_2D(): seed = 1234 gen = Generator(PCG64(seed)) n = 150 samples = 100000 mu = np.array([0., 0.]) sigma1 = 3. sigma2 = 2. rho = 0.9 cov = rho * sigma1 * sigma2 sigma = np.array([(sigma1 ** 2., cov), [cov, sigma2 ** 2.]]) x1, x2 = gen.multivariate_normal(mu, sigma, n).T s1_emp = np.std(x1) s2_emp = np.std(x2) # arbitrary symmetrical distribution def proposal(sigma_): return np.array([gen.uniform(sigma_[0] - 0.25, sigma_[0] + 0.25), gen.uniform(sigma_[1] - 0.25, sigma_[1] + 0.25)]) # bi-variate normal distribution with mu1=mu2=0, known rho and unknown sigma1 and sigma2 def log_like(sigma_): s1, s2 = sigma_ p = 1. / (2. * np.pi * s1 * s2 * np.sqrt(1. - rho ** 2.)) * np.exp(-1. / (2. * (1. - rho ** 2.)) * ((x1 / s1) ** 2 - 2. * rho * (x1 / s1) * (x2 / s2) + (x2 / s2) ** 2.)) return np.sum(np.log(p)) # bi-variate normal distribution with mu1=mu2=0, rho=0.0 def log_prior(sigma_): s1, s2 = sigma_ p = 1. / (2. * np.pi * s1 * s2) * np.exp(-1. / 2 * ((x1 / s1) ** 2 + (x2 / s2) ** 2.)) return np.sum(np.log(p)) rho0 = np.array([1., 1.]) bounds = ((1., None), (1., None)) res = metropolis_hastings(rho0, proposal, log_like, log_prior, samples, burn=100, bounds=bounds, seed=seed, keep_path=True) xp = res.x # calculate auto-correlation and determine lag-time until independence. lags = 100 auto_corr1 = auto_correlation(xp[:, 0], lags) auto_corr2 = auto_correlation(xp[:, 1], lags) tau1 = auto_correlation_time(xp[:, 0]) tau2 = auto_correlation_time(xp[:, 1]) tau = np.maximum(tau1, tau2) # sub-sample only uncorrelated samples xp_ind = xp[::tau, :] s1_sam = np.mean(xp_ind[:, 0]) s2_sam = np.mean(xp_ind[:, 1]) # plot problem plots ----------------------------------------------------------------------------------------------- # r, c = 2, 3 # fig = plt.figure(figsize=(20, 14)) # plot observations # ax1 = fig.add_subplot(r, c, 1) # ax1.scatter(x1, x2, s=20, color=default_color(0)) # ax1.set_xlabel('$x_1$') # ax1.set_ylabel('$x_2$') # ax1.grid(True) # ax1.set_title('Data') # set_font_sizes(ax1, 12) # # plot the likelihood over the domain # ng = 250 # ng2 = ng ** 2 # s1_ = np.linspace(1., 5., ng) # s2_ = np.linspace(1., 5., ng) # S1, S2 = np.meshgrid(s1_, s2_) # S = [S1.flatten(), S2.flatten()] # # # calculate likelihood # L = np.zeros((ng2,)) # for i in range(ng2): # L[i] = log_like([S[0][i], S[1][i]]) # # L = np.reshape(L, (ng, ng)) # # ax4 = fig.add_subplot(r, c, 4, projection='3d') # ax4.plot_surface(S1, S2, L, cmap=cm_parula, edgecolors='k', lw=0.2) # # ax4.set_xlabel('$\sigma_1$') # ax4.set_ylabel('$\sigma_2$') # ax4.set_zlabel('$\log(f(\\rho | x, y))$') # ax4.grid(True) # ax4.set_title('Log-Likelihood') # ax4.ticklabel_format(axis="z", style="sci", scilimits=(0, 0)) # set_font_sizes(ax4, 12) # # # calculate prior probability # pri = np.zeros((ng2,)) # for i in range(ng2): # pri[i] = log_prior([S[0][i], S[1][i]]) # # pri = np.reshape(pri, (ng, ng)) # # ax5 = fig.add_subplot(r, c, 5, projection='3d') # ax5.plot_surface(S1, S2, pri, cmap=cm_parula, edgecolors='k', lw=0.2) # # ax5.set_xlabel('$\sigma_1$') # ax5.set_ylabel('$\sigma_2$') # ax5.set_zlabel('$\log(f(\\rho))$') # ax5.grid(True) # ax5.set_title('Log-Prior Probability') # ax5.ticklabel_format(axis="z", style="sci", scilimits=(0, 0)) # set_font_sizes(ax5, 12) # plot HMC behaviour plots ----------------------------------------------------------------------------------------- fig, axes = plt.subplots(2, 3, figsize=(20, 14)) ax1, ax2, ax3, ax4, ax5, ax6 = axes.flatten() # plot markov chain ax1.plot(xp[:, 0], xp[:, 1], color=default_color(0), label='Full MCMC') ax1.plot(xp_ind[:, 0], xp_ind[:, 1], color=default_color(1), label='Ind. MCMC') ax1.plot(sigma1, sigma2, color='k', marker='o', ls='', ms=8, label='True $(\sigma_1, \sigma_2)$') ax1.plot(s1_emp, s2_emp, color='m', marker='o', ls='', ms=8, label='Empirical $(\sigma_1, \sigma_2)$') ax1.plot(s1_sam, s2_sam, color='g', marker='o', ls='', ms=8, label='Sampled $(\sigma_1, \sigma_2)$') ax1.set_xlim([2., 4.5]) ax1.set_ylim([1.4, 2.7]) ax1.set_xlabel('$\sigma_1$') ax1.set_ylabel('$\sigma_2$') ax1.grid(True) ax1.legend() ax1.set_title('Markov Chain') set_font_sizes(ax1, 12) # plot histogram of rho cmap = cm_parula ax2.hist2d(xp[:, 0], xp[:, 1], 100, cmap=cmap, range=[[2., 4.5], [1.4, 2.7]]) ax2.plot(sigma1, sigma2, color='k', marker='o', ls='', ms=8) ax2.plot(s1_emp, s2_emp, color='m', marker='o', ls='', ms=8) ax2.plot(s1_sam, s2_sam, color='g', marker='o', ls='', ms=8) ax2.set_xlim([2., 4.5]) ax2.set_ylim([1.4, 2.7]) ax2.set_xlabel('$\sigma_1$') ax2.set_ylabel('$\sigma_2$') ax2.grid(True) ax2.set_title('Posterior Distribution') set_font_sizes(ax2, 12) # plot the autocorrelation ax3.plot(np.arange(lags), auto_corr1, color=default_color(0), label='Auto-correlation, $\sigma_1$') ax3.plot(np.arange(lags), auto_corr2, color=default_color(1), label='Auto-correlation, $\sigma_2$') ax3.plot([tau, tau], [-1., 1.], 'k--', label='Lag-time, $\\tau$') ax3.set_xlim([0, lags]) ax3.set_ylim([-0.1, 1.]) ax3.set_xlabel('Lag') ax3.set_ylabel('Auto-Correlation') ax3.grid(True) ax3.legend() ax3.set_title('Auto-Correlation') set_font_sizes(ax3, 12) # plot the acceptance probability ax4.plot(np.arange(res.path.accept.size), res.path.accept, color=default_color(0)) # , label='$\delta$' # ax4.plot([0, res.path.accept.size], [0.65, 0.65], 'k--', label='$\delta_{target}$') ax4.set_xlim([0, res.path.accept.size]) ax4.set_ylim([0., 1.]) ax4.set_xlabel('Samples (incl. burn-in)') ax4.set_ylabel('Acceptance Ratio, $\delta$') ax4.grid(True) #ax4.legend() ax4.set_title('Acceptance Ratio') set_font_sizes(ax4, 12) fig.savefig(STATS_PATH + '2D_performance_metropolis.png') if __name__ == '__main__': _plot_MH_1D() _plot_MH_2D()
Shell
UTF-8
581
2.96875
3
[ "BSD-3-Clause", "MIT" ]
permissive
#!/bin/sh ### BEGIN INIT INFO # Provides: unrealircd # Required-Start: $local_fs # Required-Stop: $local_fs # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # X-Interactive: false # Short-Description: Init script for unrealircd # Description: Start/stop unrealircd ### END INIT INFO DESC="unrealircd" NAME=unrealircd #DAEMON= do_start() { sudo -u boba_fett /opt/unrealircd/Unreal3.2/unreal start } do_stop() { /opt/unrealircd/Unreal3.2/unreal stop } case "$1" in start) do_start ;; stop) do_stop ;; esac exit 0
Java
UTF-8
1,131
3.484375
3
[]
no_license
import java.util.*; public class TestBoard { public static void main(String[] args) { //Piece colorBlanco = Piece.Color.WHITE; //Color color = Color.WHITE; Board myboard = new Board(8,8); System.out.println(myboard.drawBoard()); myboard.boardToLetters(); //System.out.println(myboard.drawBoard()); // myboard.boardToFigures(); // System.out.println(myboard.drawBoard()); System.out.println("------------------- Movimientos Posibles"); //myboard.obtenerPiezasPorColor(); Coordinate coordinate = new Coordinate(4,3); Piece pieza = myboard.obtenerPiezaCoordenadas(coordinate); Movimientos movimientos = new Movimientos(pieza, myboard); ArrayList<Coordinate> listaMovimientos = new ArrayList<>(movimientos.obtenerMovimientos()); //System.out.println(piece.toString()); for(Coordinate coordenadas : listaMovimientos) { System.out.println(coordenadas.toString()); } if(listaMovimientos.isEmpty()) { System.out.println("Esta vacia"); } } }
Java
UTF-8
335
1.773438
2
[]
no_license
package com.edu.sxue.injector.component; import android.support.v4.app.Fragment; import com.edu.sxue.injector.module.FragmentModule; import dagger.Component; /** * 王少岩 在 2017/3/15 创建了它 */ @Component(modules = FragmentModule.class) public interface FragmentComponent { // provide Fragment getFragMent(); }
Java
UTF-8
509
2.6875
3
[]
no_license
package com.company; public class Main { public static void main(String[] args) { LinkedList ll = new LinkedList(); System.out.println(ll.getSize()); ll.add(8); System.out.println(ll.getSize()); ll.add(17); ll.add(5); ll.add(10); System.out.println(ll.find(17).getData()); ll.remove(5); System.out.println(ll.getSize()); System.out.println(ll.find(5)); } } }
Python
UTF-8
4,657
3.34375
3
[]
no_license
import re from jsonpointer import resolve_pointer def list_pointers(input_data, pointer=None): """ Recursive function which lists all available pointers in a json structure :param input_data: the input data to search :param pointer: the current pointer :return: generator of the json pointer paths """ if isinstance(input_data, dict) and input_data: for k, v in input_data.items(): yield pointer + "/" + k if pointer else "/" + k yield from list_pointers(v, pointer + "/" + k if pointer else "/" + k) elif isinstance(input_data, list) and input_data: for index, item in enumerate(input_data): yield f"{pointer}/{index}" if pointer else f"/{index}" yield from list_pointers(item, f"{pointer}/{index}") def find_pointers_containing(input_data, search_key, pointer=None): """ Recursive function which lists pointers which contain a search key :param input_data: the input data to search :param search_key: the key to search for :param pointer: the current pointer :return: generator of the json pointer paths """ if isinstance(input_data, dict): if pointer and search_key in input_data: yield pointer for k, v in input_data.items(): yield from find_pointers_containing( v, search_key, f"{pointer}/{k}" if pointer else f"/{k}" ) elif isinstance(input_data, list): for index, item in enumerate(input_data): yield from find_pointers_containing(item, search_key, f"{pointer}/{index}") def find_pointers_to(input_data, search_key): """ Find pointers to a particular search key :param input_data: the input data to search :param search_key: the key to search for :return: list of the json pointer paths """ root_pointers = [f"/{search_key}"] if search_key in input_data else [] pointer_iterator = find_pointers_containing(input_data, search_key) return root_pointers + [f"{pointer}/{search_key}" for pointer in pointer_iterator] def get_parent_schema_object(input_data, json_pointer, parent_property): """ Get the parent schema object identified by parent_property in the json pointer. If the parent schema object is an array then the matching array item is returned. :param input_data: the input data to search :param json_pointer: the pointer being searched :param parent_property: the parent property to search for :return: schema object identified by parent_property """ pointer_parts = json_pointer.split("/") pointer_index = pointer_parts.index(parent_property) parent_pointer = "/".join(pointer_parts[: pointer_index + 1]) schema_object = resolve_pointer(input_data, parent_pointer) if isinstance(schema_object, list): return schema_object[int(pointer_parts[pointer_index + 1])] return schema_object def json_path_to_json_pointer(json_path): """ Convert a json path string into a json pointer string. :param json_path: the input data to search :return: json pointer equivalent to the json path """ json_pointer = json_path.replace("[", "").replace("]", "").replace(".", "/") return f"/{json_pointer}" def dumb_to_smart_quotes(string): """Takes a string and returns it with dumb quotes, single and double, replaced by smart quotes. Accounts for the possibility of HTML tags within the string. From https://gist.github.com/davidtheclark/5521432""" # Find dumb single quotes coming directly after letters or punctuation, # and replace them with right single quotes. string = re.sub(r"([\w.,?!;:\"\'])\'", r"\1’", string) # Find any remaining dumb single quotes and replace them with # left single quotes. string = string.replace("'", "‘") # Reverse: Find any SMART quotes that have been (mistakenly) placed around HTML # attributes (following =) and replace them with dumb quotes. string = re.sub(r"=‘(.*?)’", r"='\1'", string) # Now repeat the steps above for double quotes # pylint: disable=invalid-string-quote string = re.sub(r'([\w.,?!;:\\"\'])\"', r"\1”", string) string = string.replace('"', "“") string = re.sub(r"=“(.*?)”", r"='\1'", string) return string def get_message_id(content): if isinstance(content, dict): return content.get("one"), content.get("other") return content def get_plural_forms_for_language(language_code): mappings = { "en": ["one"], "cy": ["zero", "one", "two", "few", "many"], } return mappings[language_code] + ["other"]
C++
UTF-8
412
2.515625
3
[ "MIT" ]
permissive
bool checksequenece(char large[] , char*small) { if(small[0] == '\0'){ return true; }else{ if(large[0] == '\0'){ return false; } } int i = 0; while(large[i] != '\0' && large[i] != small[0]){ i++; } if(large[i] == '\0'){ return false; } bool smallOutput = checksequenece(large+i+1, small+1); return smallOutput; }
Shell
UTF-8
143
3.015625
3
[]
no_license
#/bin/bash if [ $# -eq 0 ] then echo "Please enter the container name" exit fi sudo docker run -ti --name $1 csvworkshop /bin/bash
Java
UTF-8
5,360
1.765625
2
[]
no_license
package net.minecraft.world.level.levelgen; import com.mojang.serialization.Codec; import com.mojang.serialization.DataResult; import com.mojang.serialization.codecs.RecordCodecBuilder; import java.util.BitSet; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.LongStream; import javax.annotation.Nullable; import net.minecraft.core.BlockPosition; import net.minecraft.core.Holder; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.resources.ResourceKey; import net.minecraft.world.level.LevelHeightAccessor; import net.minecraft.world.level.biome.BiomeBase; import net.minecraft.world.level.biome.BiomeResolver; import net.minecraft.world.level.biome.Biomes; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.chunk.ChunkStatus; import net.minecraft.world.level.chunk.IChunkAccess; import net.minecraft.world.level.chunk.ProtoChunk; public final class BelowZeroRetrogen { private static final BitSet EMPTY = new BitSet(0); private static final Codec<BitSet> BITSET_CODEC = Codec.LONG_STREAM.xmap((longstream) -> { return BitSet.valueOf(longstream.toArray()); }, (bitset) -> { return LongStream.of(bitset.toLongArray()); }); private static final Codec<ChunkStatus> NON_EMPTY_CHUNK_STATUS = BuiltInRegistries.CHUNK_STATUS.byNameCodec().comapFlatMap((chunkstatus) -> { return chunkstatus == ChunkStatus.EMPTY ? DataResult.error(() -> { return "target_status cannot be empty"; }) : DataResult.success(chunkstatus); }, Function.identity()); public static final Codec<BelowZeroRetrogen> CODEC = RecordCodecBuilder.create((instance) -> { return instance.group(BelowZeroRetrogen.NON_EMPTY_CHUNK_STATUS.fieldOf("target_status").forGetter(BelowZeroRetrogen::targetStatus), BelowZeroRetrogen.BITSET_CODEC.optionalFieldOf("missing_bedrock").forGetter((belowzeroretrogen) -> { return belowzeroretrogen.missingBedrock.isEmpty() ? Optional.empty() : Optional.of(belowzeroretrogen.missingBedrock); })).apply(instance, BelowZeroRetrogen::new); }); private static final Set<ResourceKey<BiomeBase>> RETAINED_RETROGEN_BIOMES = Set.of(Biomes.LUSH_CAVES, Biomes.DRIPSTONE_CAVES); public static final LevelHeightAccessor UPGRADE_HEIGHT_ACCESSOR = new LevelHeightAccessor() { @Override public int getHeight() { return 64; } @Override public int getMinBuildHeight() { return -64; } }; private final ChunkStatus targetStatus; private final BitSet missingBedrock; private BelowZeroRetrogen(ChunkStatus chunkstatus, Optional<BitSet> optional) { this.targetStatus = chunkstatus; this.missingBedrock = (BitSet) optional.orElse(BelowZeroRetrogen.EMPTY); } @Nullable public static BelowZeroRetrogen read(NBTTagCompound nbttagcompound) { ChunkStatus chunkstatus = ChunkStatus.byName(nbttagcompound.getString("target_status")); return chunkstatus == ChunkStatus.EMPTY ? null : new BelowZeroRetrogen(chunkstatus, Optional.of(BitSet.valueOf(nbttagcompound.getLongArray("missing_bedrock")))); } public static void replaceOldBedrock(ProtoChunk protochunk) { boolean flag = true; BlockPosition.betweenClosed(0, 0, 0, 15, 4, 15).forEach((blockposition) -> { if (protochunk.getBlockState(blockposition).is(Blocks.BEDROCK)) { protochunk.setBlockState(blockposition, Blocks.DEEPSLATE.defaultBlockState(), false); } }); } public void applyBedrockMask(ProtoChunk protochunk) { LevelHeightAccessor levelheightaccessor = protochunk.getHeightAccessorForGeneration(); int i = levelheightaccessor.getMinBuildHeight(); int j = levelheightaccessor.getMaxBuildHeight() - 1; for (int k = 0; k < 16; ++k) { for (int l = 0; l < 16; ++l) { if (this.hasBedrockHole(k, l)) { BlockPosition.betweenClosed(k, i, l, k, j, l).forEach((blockposition) -> { protochunk.setBlockState(blockposition, Blocks.AIR.defaultBlockState(), false); }); } } } } public ChunkStatus targetStatus() { return this.targetStatus; } public boolean hasBedrockHoles() { return !this.missingBedrock.isEmpty(); } public boolean hasBedrockHole(int i, int j) { return this.missingBedrock.get((j & 15) * 16 + (i & 15)); } public static BiomeResolver getBiomeResolver(BiomeResolver biomeresolver, IChunkAccess ichunkaccess) { if (!ichunkaccess.isUpgrading()) { return biomeresolver; } else { Set set = BelowZeroRetrogen.RETAINED_RETROGEN_BIOMES; Objects.requireNonNull(set); Predicate<ResourceKey<BiomeBase>> predicate = set::contains; return (i, j, k, climate_sampler) -> { Holder<BiomeBase> holder = biomeresolver.getNoiseBiome(i, j, k, climate_sampler); return holder.is(predicate) ? holder : ichunkaccess.getNoiseBiome(i, 0, k); }; } } }
C++
UTF-8
259
2.53125
3
[]
no_license
#include "Entry.hpp" class Nonet { public: Nonet(void); void insertEntry(int place, int value); Entry* getEntry(int place); void checkForLonersAndSolveThemIfTheyExist(); void removeChoices(); bool isSolved(); private: Entry* entries[9]; };
C++
UTF-8
1,487
2.78125
3
[]
no_license
#include <stdio.h> #include <string.h> #include <ctype.h> #include <string> using namespace std; char in[1000000]; int inx; char buf[100000]; bool parse(string tag, bool has_tag) { while (in[inx]) { if (in[inx] < 32 || in[inx] > 127) return false; if (in[inx] == '>') return false; if (in[inx] == '&') { inx++; // consumes the '&' if (in[inx] == 'l' && in[inx+1] == 't' && in[inx+2] == ';') { inx += 3; continue; } else if (in[inx] == 'g' && in[inx+1] == 't' && in[inx+2] == ';') { inx += 3; continue; } else if (in[inx] == 'a' && in[inx+1] == 'm' && in[inx+2] == 'p' && in[inx+3] == ';') { inx += 4; continue; } else if (in[inx] != 'x') return false; inx++; int count = 0; for (; in[inx] && isxdigit(in[inx]); inx++) count++; if (count % 2) return false; if (in[inx] != ';') return false; inx++; continue; } if (in[inx] == '<') { inx++; bool close = in[inx] == '/'; if (close) inx++; int n; sscanf(in+inx, "%[a-z0-9]%n", buf, &n); inx += n; bool sole = in[inx] == '/'; if (close && sole) return false; if (sole) inx++; if (in[inx] != '>') return false; inx++; if (close) return has_tag == true && strcmp(buf, tag.c_str()) == 0; if (sole) continue; if (!parse(buf, true)) return false; continue; } inx++; } return has_tag == false; } int main() { while (gets(in)) { inx = 0; if (parse("", false)) printf("valid\n"); else printf("invalid\n"); } return 0; }
SQL
UTF-8
9,746
2.8125
3
[]
no_license
# ************************************************************ # Sequel Pro SQL dump # Version 3408 # # http://www.sequelpro.com/ # http://code.google.com/p/sequel-pro/ # # Host: 127.0.0.1 (MySQL 5.5.31-0ubuntu0.12.04.1) # Database: dclarke # Generation Time: 2014-03-22 16:09:08 +0000 # ************************************************************ /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; # Dump of table tbl_dvd # ------------------------------------------------------------ DROP TABLE IF EXISTS `tbl_dvd`; CREATE TABLE `tbl_dvd` ( `fld_id` bigint(20) NOT NULL AUTO_INCREMENT, `fld_name` varchar(100) NOT NULL DEFAULT '', `fld_discs` tinyint(4) NOT NULL DEFAULT '1', `fld_year` int(11) NOT NULL DEFAULT '2004', `fld_added` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `fld_format` tinyint(4) unsigned NOT NULL DEFAULT '1', `fld_burned` tinyint(3) unsigned NOT NULL DEFAULT '0', PRIMARY KEY (`fld_id`), UNIQUE KEY `fld_name` (`fld_name`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; LOCK TABLES `tbl_dvd` WRITE; /*!40000 ALTER TABLE `tbl_dvd` DISABLE KEYS */; INSERT INTO `tbl_dvd` (`fld_id`, `fld_name`, `fld_discs`, `fld_year`, `fld_added`, `fld_format`, `fld_burned`) VALUES (1,'American Wedding',1,2003,'2004-05-22 05:09:40',1,0), (2,'American Beauty (The Awards Edition)',1,2000,'2004-05-22 05:10:37',1,0), (3,'28 Days Later',1,2003,'2004-05-22 05:58:56',1,0), (4,'A Beautiful Mind (Awards Edition)',2,2002,'2004-05-22 05:59:37',1,0), (5,'Almost Famous',1,2001,'2004-05-22 06:00:06',1,0), (6,'Amelie',2,2001,'2004-05-22 06:00:24',1,0), (7,'American Pie (Collectors Edition)',1,1999,'2004-05-22 06:00:59',1,0), (8,'American Pie 2 (Unrated Version)',1,2002,'2004-05-22 06:01:26',1,0), (9,'Animatrix, The (inc. CD Soundtrack)',1,2003,'2004-05-22 06:02:36',1,0), (10,'Austin Powers: International Man of Mystery',1,1997,'2004-05-22 06:05:46',1,0), (11,'Austin Powers: The Spy Who Shagged Me',1,1999,'2004-05-22 06:06:11',1,0), (12,'Austin Powers: Goldmember',1,2002,'2004-05-22 06:06:43',1,0), (13,'Avengers, The',1,1998,'2004-05-22 06:07:16',1,0), (14,'Basic Instinct (Unrated w/ Ice Pick)',1,1992,'2004-05-22 06:08:48',1,0), (15,'Bend it like Beckham',1,2003,'2004-05-22 06:09:20',1,0), (16,'Big Daddy',1,1999,'2004-05-22 06:09:51',1,0), (17,'Blair Witch Project, The (Special Edition)',1,1999,'2004-05-22 06:10:39',0,0), (18,'Blue Streak (Special Edition)',1,1999,'2004-05-22 06:12:01',1,0), (19,'Bone Collector, The',1,2000,'2004-05-22 06:12:39',1,0), (20,'Braveheart',1,1995,'2004-05-22 06:13:07',1,0), (21,'Can\'t Hardly Wait',1,1998,'2004-05-22 06:13:30',1,0), (22,'Charlies Angels (Special Edition)',1,2000,'2004-05-22 06:13:55',1,0), (23,'Chasing Amy (The Criterion Collection)',1,1997,'2004-05-22 06:14:54',1,0), (24,'Contact (Special Edition)',1,1997,'2004-05-22 06:15:23',1,0), (25,'Count of Monte Cristo, The',1,2002,'2004-05-22 06:17:08',1,0), (26,'Crouching Tiger, Hidden Dragon',1,2000,'2004-05-22 06:17:54',1,0), (27,'Cruel Intentions (Collectors Edition)',1,1999,'2004-05-22 06:18:50',1,0), (28,'Dead Man Walking',1,1999,'2004-05-22 06:19:17',1,0), (29,'Eight Millimeter (8mm)',1,1999,'2004-05-22 06:19:56',1,0), (30,'Enemy of the State',1,1998,'2004-05-22 06:21:02',1,0), (31,'Entrapment',1,1999,'2004-05-22 06:21:30',1,0), (32,'Flatliners',1,1990,'2004-05-22 06:22:23',1,0), (33,'Gangs of New York',2,2003,'2004-05-22 06:22:52',1,0), (34,'Ferris Buellers Day Off',1,1986,'2004-05-22 06:23:27',1,0), (35,'Gone in 60 Seconds',1,2000,'2004-05-22 06:24:21',1,0), (36,'Good Morning Vietnam',1,1987,'2004-05-22 06:25:07',1,0), (37,'Green Mile, The',1,1999,'2004-05-22 06:25:48',1,0), (38,'Hackers',1,1995,'2004-05-22 06:26:16',1,0), (39,'How to Lose a Guy in 10 Days',1,2003,'2004-05-22 06:27:34',1,0), (40,'Indiana Jones and the Raiders of the Lost Ark',1,1981,'2004-05-22 06:29:17',1,0), (41,'Indiana Jones and the Temple of Doom',1,1984,'2004-05-22 06:29:32',1,0), (42,'Indiana Jones and the Last Crusade (Plus Bonus Material)',2,1989,'2004-05-22 06:29:58',1,0), (43,'Instinct',1,1999,'2004-05-22 06:30:40',1,0), (44,'Kiss The Girls',1,1997,'2004-05-22 06:30:56',1,0), (45,'Lara Croft: Tomb Raider',1,2001,'2004-05-22 06:31:31',1,0), (46,'Lethal Weapon',1,1987,'2004-05-22 06:34:20',1,0), (47,'Lethal Weapon 2',1,1989,'2004-05-22 06:34:34',1,0), (48,'Lethal Weapon 3',1,1992,'2004-05-22 06:34:54',1,0), (49,'Lethal Weapon 4',1,1998,'2004-05-22 06:35:07',1,0), (50,'Lock Stock and Two Smoking Barrels',1,1998,'2004-05-22 06:35:44',1,0), (51,'Matrix',1,1999,'2004-05-22 06:35:58',1,0), (52,'Matrix Revolutions',2,2003,'2004-05-22 06:36:31',1,0), (53,'Matrix Reloaded',2,2003,'2004-05-22 06:36:54',1,0), (54,'Maverick',1,1994,'2004-05-22 06:37:41',1,0), (55,'Monsters Inc.',2,2001,'2004-05-22 06:38:23',1,0), (56,'Night Shift',1,1982,'2004-05-22 06:39:15',1,0), (57,'Pi (Faith in Chaos)',1,1997,'2004-05-22 06:39:53',1,0), (58,'Princess Bride, The',1,1987,'2004-05-22 06:40:08',1,0), (59,'Pump Up The Volume',1,1990,'2004-05-22 06:40:56',1,0), (60,'Reservoir Dogs',1,1992,'2004-05-22 06:41:54',1,0), (61,'Rock, The',1,1996,'2004-05-22 06:42:31',1,0), (62,'Ronin',1,1998,'2004-05-22 06:42:48',1,0), (63,'Shining, The',1,1980,'2004-05-22 06:43:57',0,0), (64,'Shrek',1,2001,'2004-05-22 06:44:39',0,0), (65,'Sixth Sense, The',1,1999,'2004-05-22 06:45:14',1,0), (66,'Snatch (Special Edition)',2,2000,'2004-05-22 06:45:55',1,0), (67,'Spaceballs',1,1987,'2004-05-22 06:46:10',1,0), (68,'Spawn (Directors Cut)',1,1997,'2004-05-22 06:47:02',1,0), (69,'Spiderman (Special Edition)',2,2002,'2004-05-22 06:47:32',1,0), (70,'Sleepy Hollow',1,1999,'2004-05-22 06:47:50',1,0), (71,'There\'s Something About Mary (Special Edition)',1,1999,'2004-05-22 06:49:15',1,0), (72,'Transformers: The Movie (Special Collectors Edition)',1,1986,'2004-05-22 06:50:37',0,0), (73,'Unbreakable',2,2000,'2004-05-22 06:52:10',1,0), (74,'Underworld (Special Edition)',1,2004,'2004-05-22 06:52:42',1,0), (75,'National Lampoons: Van Wilder (Unrated Version)',2,2002,'2004-05-22 06:53:36',1,0), (76,'Virgin Suicides, The',1,2000,'2004-05-22 06:54:22',1,0), (77,'Waterboy, The',1,1998,'2004-05-22 06:54:58',1,0), (78,'Way of the Gun, The',1,2000,'2004-05-22 06:55:51',1,0), (84,'X-Men',2,2000,'2004-05-22 07:00:58',1,0), (80,'Whipped',1,2000,'2004-05-22 06:57:23',0,0), (81,'XXX (Special Edition)',1,2002,'2004-05-22 06:58:36',0,0), (82,'Lord of the Rings: The Fellowship of the Ring',2,2001,'2004-05-22 06:59:45',1,0), (83,'Lord of the Rings: The Two Towers',2,2002,'2004-05-22 06:59:59',1,0), (85,'X-Men 2: X-Men United',2,2003,'2004-05-22 07:01:06',1,0), (87,'Lord of the Rings: Return of the King',2,2003,'2004-05-26 12:29:22',1,0), (88,'Whole Nine Yards, The',1,2000,'2004-06-21 18:46:46',1,0), (89,'Lara Croft: Tomb Raider: The Cradle of Life',1,2003,'2004-06-21 18:48:55',1,0), (90,'Italian Job, The',1,2003,'2004-06-22 08:39:39',1,0), (91,'About a Boy',1,2002,'2004-06-22 08:40:27',1,0), (92,'Monsoon Wedding',1,2002,'2004-06-22 08:42:21',1,0), (93,'12 Monkeys',1,1998,'2004-06-22 08:43:27',1,0), (94,'Kill Bill: Volume 1',1,2004,'2004-07-16 14:41:44',1,0), (95,'Grosse Pointe Blank',1,1997,'2004-07-16 14:44:33',1,0), (96,'High Fidelity',1,2000,'2004-07-16 14:45:53',1,0), (97,'Shrek 2',1,2004,'2004-12-26 08:59:57',0,0), (98,'Shrek 3D',1,2004,'2004-12-26 09:00:06',1,0), (99,'Hero',1,2004,'2004-12-26 09:03:06',1,0), (100,'Spiderman 2',2,2004,'2004-12-26 09:03:14',1,0), (101,'Kill Bill Volume 2',1,2004,'2005-01-30 20:37:35',1,0), (102,'Signs',1,2002,'2005-01-30 20:38:55',1,0), (103,'Mask of Zorro, The',2,1998,'2005-01-30 20:39:26',1,0), (104,'Harold & Kumar go to White Castle',1,2004,'2005-01-30 20:40:16',1,0), (105,'Dawn of the Dead',1,2004,'2005-02-15 03:49:32',1,0), (106,'School of Rock',1,2003,'2005-02-15 03:49:56',1,0), (107,'Shaun of the Dead',1,2004,'2005-02-15 03:50:39',1,0), (108,'Back to the Future Trilogy',3,1985,'2005-02-15 03:52:02',1,0), (109,'Family Guy Volume I (Season 1 and 2)',4,2003,'2005-02-15 03:52:27',0,0), (111,'Incredibles, The',2,2005,'2005-03-28 21:34:08',1,0), (112,'Family Guy Volume II (Season 3)',3,2005,'2005-04-29 07:39:52',0,0), (113,'Hitch',1,2005,'2005-07-05 17:30:57',1,0), (114,'Minority Report',2,2002,'2005-08-06 11:52:49',1,0), (115,'Collateral',2,2004,'2005-08-06 11:53:00',1,0), (116,'Bourne Supremacy, The',1,2004,'2005-08-06 11:53:27',1,0), (117,'Bourne Identity, The',1,2002,'2005-08-06 11:54:20',1,0), (118,'Napoleon Dynamite',1,2004,'2005-08-06 11:54:49',1,0), (119,'Girl Next Door, The',1,2004,'2005-08-06 11:55:06',1,0), (120,'Dodgeball',1,2004,'2005-08-06 11:55:22',1,0), (121,'Office Space',1,1999,'2005-08-06 11:55:54',1,0), (122,'Sanglish',1,2004,'2005-09-17 17:40:20',1,0), (123,'Saint, The',1,1998,'2005-09-17 17:40:37',1,0), (124,'Clue',1,1985,'2005-09-17 17:40:49',1,0), (125,'Tron',2,1982,'2006-10-08 19:13:49',1,0), (126,'Monty Python and the Holy Grail',2,1975,'2006-10-08 19:14:31',1,0); /*!40000 ALTER TABLE `tbl_dvd` ENABLE KEYS */; UNLOCK TABLES; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Python
UTF-8
1,909
2.8125
3
[]
no_license
# IPPP Final Project - Regression Analysis ### Long-term Health Impact ### # outcome vars are: sick(dummy for person sick), days sick, import pandas as pd import numpy as np import statsmodels.api as sm #read investment data investments = pd.DataFrame(pd.read_stata("investments_data.dta", convert_categoricals=False)) #mask wave 7 to get 2003 data and drop obvs with no consumption data investments = investments.loc[(investments['wave']==7) & (investments['consumo_pp_ae']!=0)] investments.dropna(subset=['consumo_pp_ae'], inplace = True) #mask out 1 (poorest hh) ntile and 200 (richest hh) ntile of consumption iinvestments = investments.loc[(investments['consumo_pp_ae2'] > 22.2066) & (investments['consumo_pp_ae2'] < 1118.53)] #read morbidity data morbidity = pd.DataFrame(pd.read_stata("adults_morbidity_03.dta",convert_categoricals=False)) # create age squared morbidity['age_sq'] = morbidity['age']**2 #sorting the columns for joining morbidity.sort_values(by=['folio', 'state', 'muni', 'local', 'wave'], ascending=[True, True, True, True, True]) investments.sort_values(by=['folio', 'state', 'muni', 'local', 'wave'], ascending=[True, True, True, True, True]) #merge investment and morbidity data invest_morbi=pd.merge(investments, morbidity, on=('folio', 'state', 'muni', 'local', 'wave'), how='inner') #mask age invest_morbi = invest_morbi.loc[(invest_morbi['age']<65)] #dropna from health outcome variables and regressors invest_morbi.dropna(subset=['t2_c1_op','nbani197', 'nbani297','ha97', 'sick','inactivity', 'days_sick', 'days_inactivity', 'female'], inplace=True) #regressions loop health_outcomes= ['sick','days_sick', 'inactivity', 'days_inactivity'] for v in health_outcomes: x = invest_morbi[['t2_c1_op', 'nbani197', 'nbani297', 'ha97', 'age','age_sq', 'female']] y= invest_morbi[[v]] x = sm.add_constant(x) est = sm.OLS(y, x).fit() print(est.summary())
Java
UTF-8
315
1.632813
2
[ "MIT" ]
permissive
package com.babyspeak.speechtracker.models.data; import com.babyspeak.speechtracker.models.nWordsFinal; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface NwordsFinalRepository extends CrudRepository<nWordsFinal, Integer> { }
Markdown
UTF-8
3,971
2.6875
3
[ "MIT" ]
permissive
# Arduino based 433MHz transmitter This Arduino sketch imitates an RF remote that uses OOK (On Off Keying). Specifically it was meant to clone a Dooya DC1602 remote for shades. It is meant to be linked to this Homebridge plugin for control of shades. ### [Homebridge Dooya Plugin](https://github.com/rjcarlson49/homebridge-dooya-0) ## Hardware The main hardware is an [Arduino Uno rev3](https://store.arduino.cc/usa/arduino-uno-rev3). Attached to that you need a 433 MHz transmitter. 433 MHz transmitters and receivers are sold in pairs. I bought this pair, [RioRand](https://amazon.com/gp/product/B00HEDRHG6/ref=ppx_yo_dt_b_asin_title_o04_s00?ie=UTF8&psc=1), from Amazon and discarded the receiver. The transmitter is tiny and has 4 pins. Two are ground and VCC. These connect to the GND and 5V pins on the Arduino. The data pin connects to the pin 12 on the Arduino. The AN pin, antenna I just connected a loose piece of wire to. ## Encoding The basic technology is [On-Off Keying with Pulse Width Modulation](https://en.wikipedia.org/wiki/On%E2%80%93off_keying). The transmitter sends a signal at 433.92 MHz. Sending the signal is ON, not sending it is OFF. Various combinations of an ON length and an OFF length encode the message. In the DC1602, a zero is encoded by a 720 µs transmission (ON) followed by a 360 µs non-transmission (OFF). A one is 360 µs on, 720 µs off. The Arduino simply turns on pin 12 to transmit and turns it off to pause tranmission. DC1602 messages are grouped in "rows". Each row is 40 zero or one bits, preceeded by a beginning of row marker (4740 µs, 6220 µs). The end of a row is marked by a 9000 µs OFF and the end of a message is marked by a further 6000 µs OFF. In my DC1602 at least, the 40 bit rows consist of a 28 bit fixed part (bit 0..27) that is the same in all rows. Bits 28-31 are the channel numbers. The last 8 bits are command bits (bits 32-39). Open and Close for some reason have two command codes that are sent. Each command is sent multiple times as rows in a message. The commands Command | Coding | Transmissions -------- |:---------:|:------: Open | EE | 3 . | E1 | 5 Stop | AA | 3 Close | CC | 3 . | C3 | 5 The channels are numbered oddly, F is channel 0, E is channel 1, etc. So, if the fixed part is A1B2C3D, then a close message for channel 3 would consist of * A1B2C3DCEE 3 times * A1B2C3DCE1 5 times I found that the number of retransmissions (3, 5) is not fixed. I increased the retransmissions to (5, 5) in my installation to increase reliability. ## Decoding Your Remote It is pretty certain that your remote does not use the same coding that mine does. To decode yours you need a software defined radio and a decoding program. I used the program [rtl_433](https://github.com/merbanan/rtl_433). A radio is required. I used the [NooElec NESDR](https://amazon.com/gp/product/B01GDN1T4S/ref=ppx_yo_dt_b_asin_title_o09_s00?ie=UTF8&psc=1). It plugs into a USB port. First try this Flex Decoder spec. Start up rtl_433 with this command and then operate your remote. rtl_433 -R 0 -X 'n=Dooya,s=360,l=720,r=14844,g=0,t=0,y=4740' ` If it decodes the messages, you will see the rows displayed in hex and binary. Do this for enough of your remote commands for you to figure out the fixed part, the channel number and the commands. If the spec above does not work for you, then you need to run an analysis first. ## RTL_433 Analysis Use the "-A -R 0" options to discover the basic structure of the messages, the on-off timings and rows. After setting up the program and radio, run the program with -A and -R 0, operate the remote and it will spit out the specs for the OOK encoding. Using that information, use rtl_433 as above to decode the messages from your remote and find the command and channel encodings. A Flex Decoder can be used either with -R 0 -X <spec> or it can be put into the rtl_433.conf file like this decoder 'n=Dooya,s=360,l=720,r=14844,g=0,t=0,y=4740'
Python
UTF-8
1,384
2.765625
3
[]
no_license
# Copyright 2014 WUSTL ZPLAB # Erik Hvatum (ice.rikh@gmail.com) from PyQt5 import QtCore import serial from acquisition.device import Device class BrightfieldLed(Device): enabledChanged = QtCore.pyqtSignal(bool) powerChanged = QtCore.pyqtSignal(int) def __init__(self, parent=None, deviceName='Brightfield LED Driver Controller', serialPortDescriptor='/dev/ttyIOTool'): super().__init__(parent, deviceName) self._serialPort = serial.Serial(serialPortDescriptor, 9600, timeout=0.1) self._serialPort.write(b'\x80\xFF\n') # disable echo self._serialPort.read(2) # read back last echo self.enabled = False self.power = 255 @QtCore.pyqtProperty(bool, notify=enabledChanged) def enabled(self): return self._enabled @enabled.setter def enabled(self, enabled): self._enabled = bool(enabled) if enabled: self._serialPort.write(b'sh E6\n') else: self._serialPort.write(b'sl E6\n') self.enabledChanged.emit(self._enabled) @QtCore.pyqtProperty(int, notify=powerChanged) def power(self): return self._power @power.setter def power(self, power): assert 0 <= power <= 255 self._power = int(power) self._serialPort.write(bytes('pm D7 {:d}\n'.format(power), encoding='ascii')) self.powerChanged.emit(self._power)
C#
UTF-8
3,066
2.640625
3
[]
no_license
using System; using System.Windows.Forms; namespace PF_Downtime { /// <summary> /// Allows user to edit Organization information /// </summary> public partial class OrgDisplay : Form { /// <summary> /// Instantiates /// </summary> public OrgDisplay() { InitializeComponent(); } /// <summary> /// Loads information to the screen /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OrgDisplay_Load(object sender, EventArgs e) { PopulateLimitCombo(); PopulateBMCombo(); PopulateSettlementInfo(); if (Data.Organization.Parallel) { ParallelCheck.CheckState = CheckState.Checked; } } /// <summary> /// Populates the Settlement combo /// </summary> private void PopulateLimitCombo() { Settlement_Combo.DataSource = Data.SettlementList; Settlement_Combo.DisplayMember = "Info"; Settlement_Combo.ValueMember = null; } /// <summary> /// Populates the BlackMarket combo /// </summary> private void PopulateBMCombo() { BlackMarketCombo.DataSource = Data.BlackMarketList; BlackMarketCombo.DisplayMember = "Info"; BlackMarketCombo.ValueMember = null; } /// <summary> /// Populates Settlement info to the screen /// </summary> private void PopulateSettlementInfo() { Location_Text.Text = Data.Organization.Settlement.Location; Settlement_Combo.SelectedIndex = (Int32)Data.Organization.Settlement.Settlement.Limit_ID; BlackMarketCombo.SelectedIndex = (Int32)Data.Organization.Settlement.BlackMarket.Limit_ID; Notes_Text.Text = Data.Organization.Notes; } /// <summary> /// Shows the manager popup /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Manager_Button_Click(object sender, EventArgs e) { ManagerDisplay Manager = new ManagerDisplay(); Manager.ShowDialog(); } /// <summary> /// Saves user editable information back to the organization record /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Save_Button_Click(object sender, EventArgs e) { Data.Organization.Settlement.Location = Location_Text.Text; Data.Organization.Settlement.Settlement = (Models.BaseSettlement)Settlement_Combo.SelectedValue; Data.Organization.Settlement.BlackMarket = (Models.BaseBlackMarket)BlackMarketCombo.SelectedValue; Data.Organization.Settlement.Notes = Notes_Text.Text; Data.Organization.Parallel = ParallelCheck.Checked; Close(); } } }
C#
UTF-8
874
2.953125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem_2 { class Program { static void Main(string[] args) { Dictionary<int, string> students = new Dictionary<int, string>(); //Adding to a dictionary students.Add(1234567, "Apisada Sompong"); //students.Add(1234567, "AA"); //checking if a key exist if(students.ContainsKey(1234567)) { Console.WriteLine($"{1234567} already exists"); students[1234567] = "aa"; } else { Console.WriteLine("Key doesn't exist"); } //Getting a value Console.WriteLine(students[1234567]); Console.ReadKey(); } } ]
C#
UTF-8
701
3.6875
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2_circleAreaPerimeter { class Program { static void Main() { Console.WriteLine("Enter radius:"); double radius = float.Parse(Console.ReadLine()); if (radius > 0) { double area = Math.PI * radius * radius; double perimeter = Math.PI * radius * 2; Console.WriteLine("The perimeter is: {0}",perimeter); Console.WriteLine("The area is: {0}", area); } else Console.WriteLine("Incorrect value!"); } } }
PHP
UTF-8
7,586
2.75
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Yuri * Date: 08/11/2017 * Time: 14:32 */ namespace Guiageeks\lib; class ferramentas { public static function SetConfigPath(){ /*Diretorio raiz do servidor*/ define('ROOT', $_SERVER['DOCUMENT_ROOT']); /*Raiz do projeto */ // define('ROOT_APP', ''); define('ROOT_APP', 'guiageeks'); /*Caminhos absolutos* / /*Caminho absoluto da aplicação*/ define('SERVER', 'http://' . $_SERVER["HTTP_HOST"]); /*Caminho absuluto da pasta que contem os arquivos web: html, css, js e etc*/ define('WEB_URL', SERVER . '/' . ROOT_APP . '/public'); /*Caminhos absolutos diretorio*/ /*Caminho absuluto da pasta que contem os arquivos web: html, css, js e etc*/ define('WEB', ROOT . '/' . ROOT_APP . '/public'); /*Caminho absuluto da pasta que contem as bibliotecas*/ define('LIB', ROOT . '/' . ROOT_APP . '/lib'); /*Caminho absuluto da pasta que contem as aplicações (paginas, lending, dashboard e etc)*/ define('APP', ROOT . '/' . ROOT_APP . '/app'); /*Caminho absuluto da pasta que contem as sqls*/ define('SQL', ROOT . '/' . ROOT_APP . '/sql'); } /*Tenta remover codigos maliciosos da string*/ public static function remover_coding_injection($str) { $str = str_replace(" union ", "", $str); $str = str_replace(" all ", "", $str); $str = str_replace(" select ", "", $str); $str = str_replace(" -- ", "", $str); $str = str_replace(" OR 1=1", "", $str); $str = str_replace(" and ", "", $str); $str = str_replace(" ascii ", "", $str); $str = str_replace(" information_schema ", "", $str); $str = str_replace(" database ", "", $str); $str = str_replace(" DATABASE ", "", $str); $str = str_replace(" if ", "", $str); $str = str_replace(" Length ", "", $str); $str = str_replace(" IF ", "", $str); $str = str_replace(" waitfor ", "", $str); $str = str_replace(" delay ", "", $str); $str = str_replace(" + ", "", $str); $str = str_replace(" table ", "", $str); $str = str_replace(" tables ", "", $str); $str = str_replace(" char ", "", $str); $str = str_replace(" CHAR ", "", $str); $search=array("\\","\0","\n","\r","\x1a","'",'"'); $replace=array("\\\\","\\0","\\n","\\r","\Z","\'",'\"'); return str_replace($search,$replace,$str); } /*Torna o array $_POST seguro*/ public static function safe_posts() { foreach ($_POST as $key => $value) { $_POST[$key] = self::remover_coding_injection($value); } } /*Torna o array $_GET seguro*/ public static function safe_gets() { foreach ($_GET as $key => $value) { $_GET[$key] = self::remover_coding_injection($value); } } /*Torna o array $_REQUEST seguro*/ public static function safe_requests() { foreach ($_REQUEST as $key => $value) { $_REQUEST[$key] = self::ScapeString($value); } } /** * Retorna o valor passado em extenso * @param int $valor * @param bool $bolExibirMoeda * @param bool $bolPalavraFeminina * @return string */ public static function valorPorExtenso($valor = 0, $bolExibirMoeda = true, $bolPalavraFeminina = false) { $valor = self::removerFormatacaoNumero($valor); $singular = null; $plural = null; if($bolExibirMoeda) { $singular = array("centavo", "real", "mil", "milhão", "bilhão", "trilhão", "quatrilhão"); $plural = array("centavos", "reais", "mil", "milhões", "bilhões", "trilhões","quatrilhões"); } else { $singular = array("", "", "mil", "milhão", "bilhão", "trilhão", "quatrilhão"); $plural = array("", "", "mil", "milhões", "bilhões", "trilhões","quatrilhões"); } $c = array("", "cem", "duzentos", "trezentos", "quatrocentos","quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"); $d = array("", "dez", "vinte", "trinta", "quarenta", "cinquenta","sessenta", "setenta", "oitenta", "noventa"); $d10 = array("dez", "onze", "doze", "treze", "quatorze", "quinze","dezesseis", "dezesete", "dezoito", "dezenove"); $u = array("", "um", "dois", "três", "quatro", "cinco", "seis","sete", "oito", "nove"); if($bolPalavraFeminina) { if ($valor == 1) { $u = array("", "uma", "duas", "três", "quatro", "cinco", "seis","sete", "oito", "nove"); } else { $u = array("", "um", "duas", "três", "quatro", "cinco", "seis","sete", "oito", "nove"); } $c = array("", "cem", "duzentas", "trezentas", "quatrocentas","quinhentas", "seiscentas", "setecentas", "oitocentas", "novecentas"); } $z = 0; $valor = number_format( $valor, 2, ".", "." ); $inteiro = explode( ".", $valor ); for ($i = 0; $i < count( $inteiro ); $i++) { for ( $ii = mb_strlen( $inteiro[$i] ); $ii < 3; $ii++ ) { $inteiro[$i] = "0" . $inteiro[$i]; } } // $fim identifica onde que deve se dar junção de centenas por "e" ou por "," ;) $rt = null; $fim = count($inteiro) - ($inteiro[count($inteiro) - 1] > 0 ? 1 : 2); for($i = 0; $i < count($inteiro); $i++) { $valor = $inteiro[$i]; $rc = (($valor > 100) && ($valor < 200)) ? "cento" : $c[$valor[0]]; $rd = ($valor[1] < 2) ? "" : $d[$valor[1]]; $ru = ($valor > 0) ? (($valor[1] == 1) ? $d10[$valor[2]] : $u[$valor[2]]) : ""; $r = $rc . (($rc && ($rd || $ru)) ? " e " : "") . $rd . (($rd && $ru) ? " e " : "") . $ru; $t = count( $inteiro ) - 1 - $i; $r .= $r ? " " . ($valor > 1 ? $plural[$t] : $singular[$t]) : ""; if ( $valor == "000") $z++; elseif ( $z > 0 ) $z--; if(($t == 1) && ($z > 0) && ($inteiro[0] > 0)) { $r .= ( ($z > 1) ? " de " : "") . $plural[$t]; } if($r) { $rt = $rt . ((($i > 0) && ($i <= $fim) && ($inteiro[0] > 0) && ($z < 1)) ? ( ($i < $fim) ? ", " : " e ") : " ") . $r; } } $rt = mb_substr($rt, 1); return($rt ? trim($rt) : "zero"); } /** * Retira toda a formatação do número * * @access public/static * @param string $strNumero * @return string */ public static function removerFormatacaoNumero($strNumero) { $strNumero = trim( str_replace( "R$", null, $strNumero ) ); $vetVirgula = explode( ",", $strNumero ); if ( count( $vetVirgula ) == 1 ) { $acentos = array("."); $resultado = str_replace( $acentos, "", $strNumero ); return $resultado; } else if ( count( $vetVirgula ) != 2 ) { return $strNumero; } $strNumero = $vetVirgula[0]; $strDecimal = mb_substr( $vetVirgula[1], 0, 2 ); $acentos = array("."); $resultado = str_replace( $acentos, "", $strNumero ); $resultado = $resultado . "." . $strDecimal; return $resultado; } }
C++
UTF-8
3,741
2.734375
3
[ "BSD-3-Clause" ]
permissive
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2023, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include <gtest/gtest.h> #include <mrpt/core/format.h> #include <mrpt/math/poly_roots.h> #include <cmath> using namespace std; const double eps = 1e-9; TEST(poly_roots, solve_poly2) { // `a*x^2 + b*x + c = 0` // Table: // coefs (a,b,c) num_real_roots root1 root2 double coefs_roots[][6] = { {1, -2, 1, 2, 1.0, 1.0}, {1, 0, -1, 2, -1.0, 1.0}, {1, -1, -56, 2, -7.0, 8.0}, {5.0, 0, 1, 0, 0, 0}, {2.0, 0, 0, 2, 0, 0}}; for (auto& coefs_root : coefs_roots) { const double a = coefs_root[0], b = coefs_root[1], c = coefs_root[2]; const int num_roots_good = static_cast<int>(coefs_root[3]); const double r1_good = coefs_root[4], r2_good = coefs_root[5]; double r1, r2; int num_roots = mrpt::math::solve_poly2(a, b, c, r1, r2); const std::string sTestStr = mrpt::format( "\nSolving: %.02f * x^2 + %.02f * x + %.02f = 0\n", a, b, c); EXPECT_EQ(num_roots, num_roots_good); if (num_roots >= 1) { EXPECT_NEAR(r1, r1_good, eps) << sTestStr; } if (num_roots >= 2) { EXPECT_NEAR(r2, r2_good, eps) << sTestStr; } } } TEST(poly_roots, solve_poly3) { // `x^3+ a*x^2 + b*x + c = 0` // Table: // coefs (a,b,c) num_real_roots root1 root2 double coefs_roots[][7] = { {-6, 11, -6, 3, 1.0, 2.0, 3.0}, {2, 3, 4, 1, -1.650629191439386, 0, 0}, {0, -91, -90, 3, -1.0, -9.0, 10.0}}; for (auto& coefs_root : coefs_roots) { const double a = coefs_root[0], b = coefs_root[1], c = coefs_root[2]; const int num_roots_good = static_cast<int>(coefs_root[3]); const double roots_good[3] = { coefs_root[4], coefs_root[5], coefs_root[6]}; double roots[3]; int num_roots = mrpt::math::solve_poly3(roots, a, b, c); const std::string sTestStr = mrpt::format( "\nSolving: x^3 + %.02f * x^2 + %.02f * x + %.02f = 0\n", a, b, c); EXPECT_EQ(num_roots, num_roots_good); for (int k = 0; k < num_roots; k++) { bool match = false; for (int j = 0; j < num_roots; j++) if (std::abs(roots[k] - roots_good[j]) < eps) match = true; EXPECT_TRUE(match) << sTestStr << "k: " << k << std::endl; } } } TEST(poly_roots, solve_poly4) { // `x^4 * a*x^3+ b*x^2 + c*x + d = 0` // Table: // coefs (a,b,c) num_real_roots roots double coefs_roots[][9] = { {-10, 35, -50, 24, 4, 1.0, 2.0, 3.0, 4.0}, {-14, 35, 50, 0, 4, -1, 0, 5, 10}}; for (auto& coefs_root : coefs_roots) { const double a = coefs_root[0], b = coefs_root[1], c = coefs_root[2], d = coefs_root[3]; const int num_roots_good = static_cast<int>(coefs_root[4]); const double roots_good[4] = { coefs_root[5], coefs_root[6], coefs_root[7], coefs_root[8]}; double roots[4]; int num_roots = mrpt::math::solve_poly4(roots, a, b, c, d); const std::string sTestStr = mrpt::format( "\nSolving: x^4 + %.02f * x^3 + %.02f * x^2 + %.02f * x + %.02f = " "0\n", a, b, c, d); EXPECT_EQ(num_roots, num_roots_good); for (int k = 0; k < num_roots; k++) { bool match = false; for (int j = 0; j < num_roots; j++) if (std::abs(roots[k] - roots_good[j]) < eps) match = true; EXPECT_TRUE(match) << sTestStr << "k: " << k << std::endl; } } }
JavaScript
UTF-8
3,283
2.609375
3
[]
no_license
/* Canvas2D效果对象构造器 */ void function (TeaJs) { "use strict"; function C2Effect() { /// <summary>Canvas2D效果对象构造器</summary> /// <returns type="Canvas2DEffect">Canvas2D效果对象</returns> if (!arguments.length) return; constructor(this, arguments); } // 创建Canvas2D效果构造器 var constructor = new TeaJs.Function(); constructor.add([TeaJs.Renderer, String], function (renderer, type) { /// <summary>Canvas2D效果对象构造函数</summary> /// <param name="renderer" type="CanvasRenderer">Canvas渲染器</param> /// <param name="type" type="String">插件类型</param> /// <returns type="Canvas2DEffect">Canvas2D效果对象</returns> // 渲染器对象 this.renderer = renderer; // 插件类型 this.type = type; // 是否启用 this.isEnable = false; renderer.plugins.push(this); }); // 缓存插件原型对象 var plugin = C2Effect.prototype; // 处理函数 plugin.begin = new Function(); plugin.end = new Function(); plugin.process = new Function(); plugin.destroy = function () { /// <summary>销毁插件对象</summary> var plugins = this.renderer.plugins; if (this.renderer) { for (var i = plugins.length; i--;) { if (plugins[i] == this) { this.renderer.plugins = plugins.remove(i); return; } } } }; plugin.convolutionMatrix = function (inputData, w, h, matrix, divisor, offset) { /// <summary>计算卷积矩阵</summary> /// <param name="input" type="ImageData">像素数据</param> /// <param name="matrix" type="Array">矩阵</param> /// <param name="divisor" type="Number">除数</param> /// <param name="offset" type="Number">偏移量</param> /// <returns type="ImageData">像素数据</returns> // 拷贝一份源数据 var bufferData = new Uint8Array(inputData); var m = matrix; var currentPoint = 0; var wb = (w << 2); // 对除了边缘的点之外的内部点的 RGB 进行操作 for (var y = 1; y < h - 1; y += 1) { for (var x = 1; x < w - 1; x += 1) { currentPoint = ((y * w + x) << 2); // 如果为全透明则跳过该像素 if (inputData[currentPoint + 3] == 0) { continue; } // 进行计算 for (var c = 0; c < 3; c += 1) { var i = currentPoint + c; inputData[i] = offset + (m[0] * bufferData[i - wb - 4] + m[1] * bufferData[i - wb] + m[2] * bufferData[i - wb + 4] + m[3] * bufferData[i - 4] + m[4] * bufferData[i] + m[5] * bufferData[i + 4] + m[6] * bufferData[i + wb - 4] + m[7] * bufferData[i + wb] + m[8] * bufferData[i + wb + 4]) / divisor; } inputData[currentPoint + 3] = bufferData[currentPoint + 3]; } } }; TeaJs.C2Effect = C2Effect; }(TeaJs);
Java
UTF-8
217
1.507813
2
[]
no_license
package com.abhishek.app.repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.abhishek.app.entities.User; public interface UserRepository extends JpaRepository<User, Long> { }
Python
UTF-8
1,610
2.71875
3
[]
no_license
import ipdb from app.exceptions.posts_exceptions import InvalidPost, PostNotFound from flask import Flask, request, jsonify from app.models.post_model import Post def init_app(app: Flask): @app.post('/create-post') def create_post(): data = request.json try: post = Post(**data) new_post = post.save() return new_post, 201 except InvalidPost: return {'message': 'Dados inválidos para a criação da publicação'}, 400 @app.get('/get-posts') def get_all_posts(): posts_list = Post.get_all_posts() return jsonify(posts_list), 200 @app.get('/get-post/<int:id>') def get_post_by_id(id: int): try: post = Post.get_by_id(id) return post, 200 except PostNotFound: return {'message': 'Publicação não encontrada'}, 404 @app.patch('/update-post/<int:id>') def update_post_by_id(id: int): data = request.json try: post = Post.get_by_id(id) post_update = Post.update(post, data) return post_update, 200 except PostNotFound: return {'message': 'Publicação não encontrada'}, 404 except TypeError: return {'message': 'Dados inválidos para a atualização da publicação'}, 400 @app.delete('/delete-post/<int:id>') def delete_post_by_id(id: int): try: post = Post.delete(id) return post, 200 except PostNotFound: return {'message': 'Publicação não encontrada'}, 404
SQL
UTF-8
38,004
2.953125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.7.7 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Apr 25, 2018 at 05:27 PM -- Server version: 5.6.38 -- PHP Version: 7.2.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- -- Database: `spoc` -- -- -------------------------------------------------------- -- -- Table structure for table `addresses` -- CREATE TABLE `addresses` ( `id` int(10) UNSIGNED NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `carousels` -- CREATE TABLE `carousels` ( `id` int(10) UNSIGNED NOT NULL, `img` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `ar_title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `en_title` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `carousels` -- INSERT INTO `carousels` (`id`, `img`, `ar_title`, `en_title`, `created_at`, `updated_at`) VALUES (1, '1_1515891670sffQE.png', '', '', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (2, 'slide1233.jpg', 'سير ذاتية للعاملين', '', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (3, 'slide2.png', 'تواصل دائم و متابعة مستمرة', '', '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -------------------------------------------------------- -- -- Table structure for table `cities` -- CREATE TABLE `cities` ( `id` int(10) UNSIGNED NOT NULL, `ar_name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `en_name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `contacts` -- CREATE TABLE `contacts` ( `id` int(10) UNSIGNED NOT NULL, `name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `phone` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `countries` -- CREATE TABLE `countries` ( `id` int(10) UNSIGNED NOT NULL, `ar_name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `en_name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `curriculas` -- CREATE TABLE `curriculas` ( `id` int(10) UNSIGNED NOT NULL, `ar_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `en_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `curriculas` -- INSERT INTO `curriculas` (`id`, `ar_name`, `en_name`, `created_at`, `updated_at`) VALUES (1, '', 'Saudian', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (2, '', 'American', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (3, '', 'French', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (4, '', 'Algerian', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (5, '', 'English', '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -------------------------------------------------------- -- -- Table structure for table `curricula_teaching_choice` -- CREATE TABLE `curricula_teaching_choice` ( `id` int(10) UNSIGNED NOT NULL, `curricula_id` int(10) UNSIGNED DEFAULT NULL, `teaching_choice_id` int(10) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `deals` -- CREATE TABLE `deals` ( `id` int(10) UNSIGNED NOT NULL, `student_id` int(10) UNSIGNED DEFAULT NULL, `teacher_id` int(10) UNSIGNED DEFAULT NULL, `begin_date` datetime DEFAULT NULL, `end_date` datetime DEFAULT NULL, `price` int(11) DEFAULT NULL, `state` enum('pending','available','canceled') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'pending', `paymentMethod` enum('masterCard','visaCard','paypal') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'paypal', `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `fees` -- CREATE TABLE `fees` ( `id` int(10) UNSIGNED NOT NULL, `normal_by_hour` int(11) DEFAULT NULL, `normal_by_day` int(11) DEFAULT NULL, `online_by_hour` int(11) DEFAULT NULL, `online_by_day` int(11) DEFAULT NULL, `currency` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `high_school_stages` -- CREATE TABLE `high_school_stages` ( `id` int(10) UNSIGNED NOT NULL, `ar_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `en_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `high_school_stages` -- INSERT INTO `high_school_stages` (`id`, `ar_name`, `en_name`, `created_at`, `updated_at`) VALUES (1, '', 'primary', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (2, '', 'medium', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (3, '', 'high', '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -------------------------------------------------------- -- -- Table structure for table `high_school_stage_teaching_choice` -- CREATE TABLE `high_school_stage_teaching_choice` ( `id` int(10) UNSIGNED NOT NULL, `high_school_stage_id` int(10) UNSIGNED DEFAULT NULL, `teaching_choice_id` int(10) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `messages` -- CREATE TABLE `messages` ( `id` int(10) UNSIGNED NOT NULL, `message` text COLLATE utf8mb4_unicode_ci NOT NULL, `subject` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `sender` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `read` tinyint(1) NOT NULL DEFAULT '0', `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `id` int(10) UNSIGNED NOT NULL, `migration` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (35, '2014_10_12_000000_create_users_table', 1), (36, '2014_10_12_100000_create_password_resets_table', 1), (37, '2017_10_25_152003_create_messages_table', 1), (38, '2017_10_30_221338_create_contacts_table', 1), (39, '2017_10_31_112641_create_template_s_m_s_table', 1), (40, '2017_12_07_001127_create_principal_settings_table', 1), (41, '2017_12_10_105044_create_notifications_table', 1), (42, '2018_01_04_164306_create_sms_sendeds_table', 1), (43, '2018_01_13_235417_create_carousels_table', 1), (44, '2018_03_12_101024_create_students_table', 1), (45, '2018_03_12_101046_create_teachers_table', 1), (46, '2018_03_12_183611_create_school_stage_choices_table', 1), (47, '2018_03_12_183617_create_school_stages_table', 1), (48, '2018_03_12_183854_create_teaching_types_table', 1), (49, '2018_03_12_183910_create_specializations_table', 1), (50, '2018_03_12_183926_create_high_school_stages_table', 1), (51, '2018_03_13_203910_create_s_parents_table', 1), (52, '2018_03_16_144827_create_countries_table', 1), (53, '2018_03_16_145056_create_cities_table', 1), (54, '2018_03_16_145123_create_addresses_table', 1), (55, '2018_03_16_145149_create_subjects_table', 1), (56, '2018_03_16_145214_create_curriculas_table', 1), (57, '2018_03_16_145233_create_teaching_options_table', 1), (58, '2018_03_25_171206_create_providers_table', 1), (59, '2018_03_25_233508_create_deals_table', 1), (60, '2018_04_01_114004_create_school_stage_teaching_choice__table', 1), (61, '2018_04_01_114314_create_high_school_stage_teaching_choice__table', 1), (62, '2018_04_01_115037_create_specialization_teaching_choice__table', 1), (63, '2018_04_01_115114_create_curricula_teaching_choice__table', 1), (64, '2018_04_01_144401_create_teaching_choices_table', 1), (65, '2018_04_01_184043_create_fees_table', 1), (66, '2018_04_02_145003_create_subject_teaching_choice_table', 1), (67, '2018_04_02_152534_create_teaching_choice_teaching_option_table', 1), (68, '2018_04_02_152614_create_teaching_choice_teaching_type_table', 1); -- -------------------------------------------------------- -- -- Table structure for table `notifications` -- CREATE TABLE `notifications` ( `id` char(36) COLLATE utf8mb4_unicode_ci NOT NULL, `type` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `notifiable_id` int(10) UNSIGNED NOT NULL, `notifiable_type` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `data` text COLLATE utf8mb4_unicode_ci NOT NULL, `read_at` timestamp NULL DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `password_resets` -- CREATE TABLE `password_resets` ( `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `principal_settings` -- CREATE TABLE `principal_settings` ( `id` int(10) UNSIGNED NOT NULL, `office_en_name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `office_ar_name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `phone` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `ar_address` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `en_address` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `website_email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `logo` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `en_about` text COLLATE utf8mb4_unicode_ci, `ar_about` text COLLATE utf8mb4_unicode_ci, `en_privacy_term` text COLLATE utf8mb4_unicode_ci, `ar_privacy_term` text COLLATE utf8mb4_unicode_ci, `en_questions` text COLLATE utf8mb4_unicode_ci, `ar_questions` text COLLATE utf8mb4_unicode_ci, `ar_teacher_terms` text COLLATE utf8mb4_unicode_ci, `en_teacher_terms` text COLLATE utf8mb4_unicode_ci, `ar_student_terms` text COLLATE utf8mb4_unicode_ci, `en_student_terms` text COLLATE utf8mb4_unicode_ci, `ar_parent_terms` text COLLATE utf8mb4_unicode_ci, `en_parent_terms` text COLLATE utf8mb4_unicode_ci, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `principal_settings` -- INSERT INTO `principal_settings` (`id`, `office_en_name`, `office_ar_name`, `phone`, `ar_address`, `en_address`, `website_email`, `logo`, `en_about`, `ar_about`, `en_privacy_term`, `ar_privacy_term`, `en_questions`, `ar_questions`, `ar_teacher_terms`, `en_teacher_terms`, `ar_student_terms`, `en_student_terms`, `ar_parent_terms`, `en_parent_terms`, `created_at`, `updated_at`) VALUES (1, 'Modaras kas', 'مدرس خاص', '0664421310', 'السعودية', 'Saudia', 'modaraskas@gmail.com', 'logo', 'about us', 'حولنا', 'privacy terms', 'شروط الخصوصية', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -------------------------------------------------------- -- -- Table structure for table `providers` -- CREATE TABLE `providers` ( `id` int(10) UNSIGNED NOT NULL, `provider_id` int(11) NOT NULL, `provider` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `user_id` int(11) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `school_stages` -- CREATE TABLE `school_stages` ( `id` int(10) UNSIGNED NOT NULL, `ar_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `en_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `school_stages` -- INSERT INTO `school_stages` (`id`, `ar_name`, `en_name`, `created_at`, `updated_at`) VALUES (1, '', 'primary', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (2, '', 'medium', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (3, '', 'high', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (4, '', 'international', '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -------------------------------------------------------- -- -- Table structure for table `school_stage_choices` -- CREATE TABLE `school_stage_choices` ( `id` int(10) UNSIGNED NOT NULL, `student_id` int(10) UNSIGNED DEFAULT NULL, `school_stage_id` int(10) UNSIGNED DEFAULT NULL, `specialization_id` int(10) UNSIGNED DEFAULT NULL, `teaching_type_id` int(10) UNSIGNED DEFAULT NULL, `high_school_stage_id` int(10) UNSIGNED DEFAULT NULL, `school` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `school_stage_teaching_choice` -- CREATE TABLE `school_stage_teaching_choice` ( `id` int(10) UNSIGNED NOT NULL, `school_stage_id` int(10) UNSIGNED DEFAULT NULL, `teaching_choice_id` int(10) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `sms_sendeds` -- CREATE TABLE `sms_sendeds` ( `id` int(10) UNSIGNED NOT NULL, `content` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `phone` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `user_id` int(10) UNSIGNED NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `specializations` -- CREATE TABLE `specializations` ( `id` int(10) UNSIGNED NOT NULL, `ar_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `en_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `specializations` -- INSERT INTO `specializations` (`id`, `ar_name`, `en_name`, `created_at`, `updated_at`) VALUES (1, '', 'mathimatic', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (2, '', 'physic', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (3, '', 'computer science', '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -------------------------------------------------------- -- -- Table structure for table `specialization_teaching_choice` -- CREATE TABLE `specialization_teaching_choice` ( `id` int(10) UNSIGNED NOT NULL, `specialization_id` int(10) UNSIGNED DEFAULT NULL, `teaching_choice_id` int(10) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `students` -- CREATE TABLE `students` ( `id` int(10) UNSIGNED NOT NULL, `user_id` int(10) UNSIGNED DEFAULT NULL, `school_stage_choice_id` int(10) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `students` -- INSERT INTO `students` (`id`, `user_id`, `school_stage_choice_id`, `created_at`, `updated_at`) VALUES (1, 13, NULL, '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -------------------------------------------------------- -- -- Table structure for table `subjects` -- CREATE TABLE `subjects` ( `id` int(10) UNSIGNED NOT NULL, `ar_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `en_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `subject_teaching_choice` -- CREATE TABLE `subject_teaching_choice` ( `id` int(10) UNSIGNED NOT NULL, `subject_id` int(10) UNSIGNED DEFAULT NULL, `teaching_choice_id` int(10) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `s_parents` -- CREATE TABLE `s_parents` ( `id` int(10) UNSIGNED NOT NULL, `user_id` int(10) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `s_parents` -- INSERT INTO `s_parents` (`id`, `user_id`, `created_at`, `updated_at`) VALUES (1, 12, '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -------------------------------------------------------- -- -- Table structure for table `teachers` -- CREATE TABLE `teachers` ( `id` int(10) UNSIGNED NOT NULL, `user_id` int(10) UNSIGNED DEFAULT NULL, `teaching_choice_id` int(10) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `teachers` -- INSERT INTO `teachers` (`id`, `user_id`, `teaching_choice_id`, `created_at`, `updated_at`) VALUES (1, 2, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (2, 3, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (3, 4, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (4, 5, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (5, 6, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (6, 7, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (7, 8, NULL, '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (8, 9, NULL, '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (9, 10, NULL, '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (10, 11, NULL, '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -------------------------------------------------------- -- -- Table structure for table `teaching_choices` -- CREATE TABLE `teaching_choices` ( `id` int(10) UNSIGNED NOT NULL, `teacher_id` int(10) UNSIGNED DEFAULT NULL, `testPeriod` int(11) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `teaching_choice_teaching_option` -- CREATE TABLE `teaching_choice_teaching_option` ( `id` int(10) UNSIGNED NOT NULL, `teaching_option_id` int(10) UNSIGNED DEFAULT NULL, `teaching_choice_id` int(10) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `teaching_choice_teaching_type` -- CREATE TABLE `teaching_choice_teaching_type` ( `id` int(10) UNSIGNED NOT NULL, `teaching_type_id` int(10) UNSIGNED DEFAULT NULL, `teaching_choice_id` int(10) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `teaching_options` -- CREATE TABLE `teaching_options` ( `id` int(10) UNSIGNED NOT NULL, `ar_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `en_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `teaching_options` -- INSERT INTO `teaching_options` (`id`, `ar_name`, `en_name`, `created_at`, `updated_at`) VALUES (1, '', 'Teaching one student at the appropriate student location', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (2, '', 'Teaching to the student group at the appropriate student location', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (3, '', 'Teaching one student at the appropriate teacher location', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (4, '', 'Teaching a group of students at the appropriate teacher location', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (5, '', 'Teaching a student online', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (6, '', 'Teaching a group of students online', '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -------------------------------------------------------- -- -- Table structure for table `teaching_types` -- CREATE TABLE `teaching_types` ( `id` int(10) UNSIGNED NOT NULL, `ar_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `en_name` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `teaching_types` -- INSERT INTO `teaching_types` (`id`, `ar_name`, `en_name`, `created_at`, `updated_at`) VALUES (1, '', 'Normal', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (2, '', 'Online', '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (3, '', 'Both', '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -------------------------------------------------------- -- -- Table structure for table `template_s_m_ss` -- CREATE TABLE `template_s_m_ss` ( `id` int(10) UNSIGNED NOT NULL, `subject` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `message` text COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(10) UNSIGNED NOT NULL, `name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `firstName` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `lastName` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL, `gender` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'male', `type` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'student', `mobile` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `country` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `city` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `activationCode` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `avatar` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'default-avatar.png', `address` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `active` int(11) NOT NULL DEFAULT '0', `age` int(11) DEFAULT NULL, `lat` int(11) DEFAULT NULL, `lng` int(11) DEFAULT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `firstName`, `lastName`, `email`, `password`, `gender`, `type`, `mobile`, `country`, `city`, `activationCode`, `avatar`, `address`, `active`, `age`, `lat`, `lng`, `remember_token`, `created_at`, `updated_at`) VALUES (1, 'admin', NULL, NULL, 'admin@admin.com', '$2y$10$fs7Rnvl9Ot5cPB9Cqch4defvy6zhhPSJDyiSiobTYVHyx9yNPeEbi', 'male', 'admin', NULL, NULL, NULL, NULL, 'default-avatar.png', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (2, 'teacher 1', NULL, NULL, 'teacher1@gmail.com', '$2y$10$2tQGhWmADCTAJZHpx75/IODQABsjcM3EnEDBsydC3lUgkTNnMP6dC', 'male', 'teacher', NULL, 'Algeria', 'Chlef Province', NULL, '1.jpg', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (3, 'teacher 2', NULL, NULL, 'teacher2@gmail.com', '$2y$10$Jna8azPEXjxKDOn5Q21fPuSsNA1AUELLMC9hJL0gvyx.8N7MHBE1C', 'male', 'teacher', NULL, 'Algeria', 'Chlef Province', NULL, '2.jpg', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (4, 'teacher 3', NULL, NULL, 'teacher3@gmail.com', '$2y$10$60Uw/tEH4T0HT2h3NvQNxefomCX7QOsvdXBf1ZyZJz0GBk4WFV1Fu', 'male', 'teacher', NULL, 'Algeria', 'Chlef Province', NULL, '3.jpg', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (5, 'teacher 4', NULL, NULL, 'teacher4@gmail.com', '$2y$10$KkXfUjP1htVez9bWQJ1RS.LA9LAcGES54dyL8UGR.gzkId9zTBoam', 'male', 'teacher', NULL, 'Algeria', 'Chlef Province', NULL, '4.jpg', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (6, 'teacher 5', NULL, NULL, 'teacher5@gmail.com', '$2y$10$NRY4TqwgrMhzge.eHr1v..aMw8.wYr8a2o9LWUTNJ4y7rvlvMIzUW', 'male', 'teacher', NULL, 'Algeria', 'Chlef Province', NULL, '5.jpg', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (7, 'teacher 6', NULL, NULL, 'teacher6@gmail.com', '$2y$10$tJVdIyakIrSVWZUJHnG3CuM6ajMiiEfppzKP3jzxpV8G6opuiRXiG', 'male', 'teacher', NULL, 'Algeria', 'Chlef Province', NULL, '6.jpg', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:41', '2018-04-25 09:37:41'), (8, 'teacher 7', NULL, NULL, 'teacher7@gmail.com', '$2y$10$MXoUS8fCeCqK34P34FyM.OMbF3uOHmpsuqD4ornLjEYXCBE26iWQa', 'male', 'teacher', NULL, 'Algeria', 'Chlef Province', NULL, '7.jpg', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (9, 'teacher 8', NULL, NULL, 'teacher8@gmail.com', '$2y$10$lV4vrlAZE/3X4VW1bT2A4.D15J2qIY3uZOUJCtOdrKcQN0gZYpGFa', 'male', 'teacher', NULL, 'Algeria', 'Chlef Province', NULL, '8.jpg', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (10, 'teacher 9', NULL, NULL, 'teacher9@gmail.com', '$2y$10$eo/vG0/LwtUKWDSl4y4lJeIvIQ3fTyXUKj3O.duYmNmsU2pChhds.', 'male', 'teacher', NULL, 'Algeria', 'Chlef Province', NULL, '9.jpg', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (11, 'teacher 10', NULL, NULL, 'teacher10@gmail.com', '$2y$10$A1Str6Bv94qxN1oCvW9XCe4I2k3oiQrCr1LR4vovCgxTBmXgk5i72', 'male', 'teacher', NULL, 'Algeria', 'Chlef Province', NULL, '10.jpg', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (12, 'parent', NULL, NULL, 'parent@gmail.com', '$2y$10$Mou.e03la6blRE.kXk4VQ.EzutMiueFWIl8O73tPpBMOaK6j6QNWK', 'male', 'parent', NULL, NULL, NULL, NULL, 'default-avatar.png', NULL, 1, NULL, NULL, NULL, NULL, '2018-04-25 09:37:42', '2018-04-25 09:37:42'), (13, 'student', NULL, NULL, 'student@gmail.com', '$2y$10$nybh6Ir6BKIDlDG.IWL6GepJbFy.Jtfad95073hgHuBRAS7rdtYke', 'male', 'student', NULL, NULL, NULL, NULL, 'student.png', NULL, 1, NULL, NULL, NULL, 'VHdjhHEtmXLgexTLBIKvYAilIzSFbhZ0fDQS8SzdOT8q21GX2RLHz6fcXmjr', '2018-04-25 09:37:42', '2018-04-25 09:37:42'); -- -- Indexes for dumped tables -- -- -- Indexes for table `addresses` -- ALTER TABLE `addresses` ADD PRIMARY KEY (`id`); -- -- Indexes for table `carousels` -- ALTER TABLE `carousels` ADD PRIMARY KEY (`id`); -- -- Indexes for table `cities` -- ALTER TABLE `cities` ADD PRIMARY KEY (`id`); -- -- Indexes for table `contacts` -- ALTER TABLE `contacts` ADD PRIMARY KEY (`id`); -- -- Indexes for table `countries` -- ALTER TABLE `countries` ADD PRIMARY KEY (`id`); -- -- Indexes for table `curriculas` -- ALTER TABLE `curriculas` ADD PRIMARY KEY (`id`); -- -- Indexes for table `curricula_teaching_choice` -- ALTER TABLE `curricula_teaching_choice` ADD PRIMARY KEY (`id`); -- -- Indexes for table `deals` -- ALTER TABLE `deals` ADD PRIMARY KEY (`id`); -- -- Indexes for table `fees` -- ALTER TABLE `fees` ADD PRIMARY KEY (`id`); -- -- Indexes for table `high_school_stages` -- ALTER TABLE `high_school_stages` ADD PRIMARY KEY (`id`); -- -- Indexes for table `high_school_stage_teaching_choice` -- ALTER TABLE `high_school_stage_teaching_choice` ADD PRIMARY KEY (`id`); -- -- Indexes for table `messages` -- ALTER TABLE `messages` ADD PRIMARY KEY (`id`); -- -- Indexes for table `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indexes for table `notifications` -- ALTER TABLE `notifications` ADD PRIMARY KEY (`id`), ADD KEY `notifications_notifiable_id_notifiable_type_index` (`notifiable_id`,`notifiable_type`); -- -- Indexes for table `password_resets` -- ALTER TABLE `password_resets` ADD KEY `password_resets_email_index` (`email`); -- -- Indexes for table `principal_settings` -- ALTER TABLE `principal_settings` ADD PRIMARY KEY (`id`); -- -- Indexes for table `providers` -- ALTER TABLE `providers` ADD PRIMARY KEY (`id`); -- -- Indexes for table `school_stages` -- ALTER TABLE `school_stages` ADD PRIMARY KEY (`id`); -- -- Indexes for table `school_stage_choices` -- ALTER TABLE `school_stage_choices` ADD PRIMARY KEY (`id`); -- -- Indexes for table `school_stage_teaching_choice` -- ALTER TABLE `school_stage_teaching_choice` ADD PRIMARY KEY (`id`); -- -- Indexes for table `sms_sendeds` -- ALTER TABLE `sms_sendeds` ADD PRIMARY KEY (`id`), ADD KEY `sms_sendeds_user_id_foreign` (`user_id`); -- -- Indexes for table `specializations` -- ALTER TABLE `specializations` ADD PRIMARY KEY (`id`); -- -- Indexes for table `specialization_teaching_choice` -- ALTER TABLE `specialization_teaching_choice` ADD PRIMARY KEY (`id`); -- -- Indexes for table `students` -- ALTER TABLE `students` ADD PRIMARY KEY (`id`); -- -- Indexes for table `subjects` -- ALTER TABLE `subjects` ADD PRIMARY KEY (`id`); -- -- Indexes for table `subject_teaching_choice` -- ALTER TABLE `subject_teaching_choice` ADD PRIMARY KEY (`id`); -- -- Indexes for table `s_parents` -- ALTER TABLE `s_parents` ADD PRIMARY KEY (`id`); -- -- Indexes for table `teachers` -- ALTER TABLE `teachers` ADD PRIMARY KEY (`id`); -- -- Indexes for table `teaching_choices` -- ALTER TABLE `teaching_choices` ADD PRIMARY KEY (`id`); -- -- Indexes for table `teaching_choice_teaching_option` -- ALTER TABLE `teaching_choice_teaching_option` ADD PRIMARY KEY (`id`); -- -- Indexes for table `teaching_choice_teaching_type` -- ALTER TABLE `teaching_choice_teaching_type` ADD PRIMARY KEY (`id`); -- -- Indexes for table `teaching_options` -- ALTER TABLE `teaching_options` ADD PRIMARY KEY (`id`); -- -- Indexes for table `teaching_types` -- ALTER TABLE `teaching_types` ADD PRIMARY KEY (`id`); -- -- Indexes for table `template_s_m_ss` -- ALTER TABLE `template_s_m_ss` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `addresses` -- ALTER TABLE `addresses` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `carousels` -- ALTER TABLE `carousels` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `cities` -- ALTER TABLE `cities` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `contacts` -- ALTER TABLE `contacts` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `countries` -- ALTER TABLE `countries` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `curriculas` -- ALTER TABLE `curriculas` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `curricula_teaching_choice` -- ALTER TABLE `curricula_teaching_choice` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `deals` -- ALTER TABLE `deals` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `fees` -- ALTER TABLE `fees` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `high_school_stages` -- ALTER TABLE `high_school_stages` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `high_school_stage_teaching_choice` -- ALTER TABLE `high_school_stage_teaching_choice` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `messages` -- ALTER TABLE `messages` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `migrations` -- ALTER TABLE `migrations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=69; -- -- AUTO_INCREMENT for table `principal_settings` -- ALTER TABLE `principal_settings` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `providers` -- ALTER TABLE `providers` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `school_stages` -- ALTER TABLE `school_stages` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `school_stage_choices` -- ALTER TABLE `school_stage_choices` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `school_stage_teaching_choice` -- ALTER TABLE `school_stage_teaching_choice` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `sms_sendeds` -- ALTER TABLE `sms_sendeds` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `specializations` -- ALTER TABLE `specializations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `specialization_teaching_choice` -- ALTER TABLE `specialization_teaching_choice` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `students` -- ALTER TABLE `students` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `subjects` -- ALTER TABLE `subjects` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `subject_teaching_choice` -- ALTER TABLE `subject_teaching_choice` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `s_parents` -- ALTER TABLE `s_parents` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `teachers` -- ALTER TABLE `teachers` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT for table `teaching_choices` -- ALTER TABLE `teaching_choices` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `teaching_choice_teaching_option` -- ALTER TABLE `teaching_choice_teaching_option` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `teaching_choice_teaching_type` -- ALTER TABLE `teaching_choice_teaching_type` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `teaching_options` -- ALTER TABLE `teaching_options` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT for table `teaching_types` -- ALTER TABLE `teaching_types` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `template_s_m_ss` -- ALTER TABLE `template_s_m_ss` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- Constraints for dumped tables -- -- -- Constraints for table `sms_sendeds` -- ALTER TABLE `sms_sendeds` ADD CONSTRAINT `sms_sendeds_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE;
PHP
UTF-8
7,262
2.8125
3
[]
no_license
<?php /** * Description of Mark *create table Mark(Markid varchar(10) primary key,Assignment int(5) default '0',Paper int(5) default '0',Empty varchar(3) default 'T',RegistrationId varchar(10) references Student (RegistrationId),Examid varchar(10) references Exam(Examid)); * @author Kanishka */ include_once("Connection.php"); require_once("Student.php"); require_once("ExaSubject.php"); class Mark { public $Markid; public $Shy; public $Assignment; public $Paper; public $Empty; public $RegistrationNo; public $ExamId; public $Attended; public $AttendanceMk; public $Note; public $MarkError; public $SaveError; public $NotAShift=false; public $NotAShift2=false; public function Mark(){ $this->Attended="F"; } public function getEmptyMarks($ExamId){ $Marks; $query="select * from Mark where ExamId='$ExamId' and empty='T'"; $result=Connection::connect($query); while($row=mysql_fetch_array($result)){ $ma=new Mark(); $maid=$row['Markid']; $ma->Markid=$maid; $ma->Shy=$row['Shy']; $ma->Assignment=$row['Assignment']; $ma->Paper=$row['Paper']; $ma->Empty=$row['Empty']; $ma->RegistrationNo=$row['RegistrationId']; $ma->ExamId=$row['Examid']; $ma->AttendanceMk=$row['Attendance']; $Marks["$maid"]=$ma; } #testing if(Connection::$affectedrows!=0){ return $Marks; } else{ return false; } } public function studentDidExam($RegistrationNo,$Sub_id){ $query="select * from Mark where RegistrationId='$RegistrationNo' and Examid in (select Exam_id from exam where Sub_id='$Sub_id')"; // echo $query; $result=Connection::connect($query); // $this->Shy=Connection::$affectedrows+1; // if(Connection::$affectedrows!=0){ // $this->Note['AttemptNote']="Multiple attempts detected:attempt assigned to $this->Shy on Student $this->RegistrationNo"; // } $Marks; while($row=mysql_fetch_array($result)){ $ma=new Mark(); $maid=$row['Markid']; $ma->Markid=$maid; $ma->Shy=$row['Shy']; $ma->Assignment=$row['Assignment']; $ma->Paper=$row['Paper']; $ma->Empty=$row['Empty']; $ma->RegistrationNo=$row['RegistrationId']; $ma->ExamId=$row['Examid']; $ma->AttendanceMk=$row['Attendance']; $ma->Attended=$row['Attended']; $Marks["$maid"]=$ma; } if(Connection::$affectedrows!=0){ return $Marks; }else{ return false; } } public function studentAttendedExam($RegistrationNo,$Sub_id){ $query="select * from Mark where RegistrationId='$RegistrationNo' and Examid in (select Exam_id from exam where Sub_id='$Sub_id') and Attended='T'"; // echo $query; $result=Connection::connect($query); $this->Shy=Connection::$affectedrows+1; if(Connection::$affectedrows!=0){ $this->Note['AttemptNote']="Multiple attempts detected:attempt assigned to $this->Shy on Student $this->RegistrationNo"; } $Marks; while($row=mysql_fetch_array($result)){ $ma=new Mark(); $maid=$row['Markid']; $ma->Markid=$maid; $ma->Shy=$row['Shy']; $ma->Assignment=$row['Assignment']; $ma->Paper=$row['Paper']; $ma->Empty=$row['Empty']; $ma->RegistrationNo=$row['RegistrationId']; $ma->ExamId=$row['Examid']; $ma->AttendanceMk=$row['Attendance']; $Marks["$maid"]=$ma; } if(Connection::$affectedrows!=0){ return $Marks; }else{ return false; } } public function addMarkEntry($RegistrationNo,$Examid){ $query="insert into Mark (Shy,RegistrationId,Examid) values ('$this->Shy','$RegistrationNo','$Examid')"; $result=Connection::connect($query); } public function setMarkVals(){ if(!(isset($this->MarkError))){ $query="insert into Mark (Shy,RegistrationId,Examid,Attended) values ('$this->Shy','$this->RegistrationNo','$this->ExamId','F')"; $result=Connection::connect($query); }else{ // echo "unable to save"; // echo $this->MarkError; } } public function saveExamMarks(){ $query="update Mark set Paper='$this->Paper',Assignment='$this->Assignment',Attendance='$this->AttendanceMk',Attended='$this->Attended', Empty='F' where RegistrationId='$this->RegistrationNo' and Examid='$this->ExamId'"; echo $qurey; $result=Connection::connect($query); if(Connection::$affectedrows==1){ return true; } else{ return false; } } public function setUpdateShy(){ $newshy=($this->Shy)-1; $query="update Mark set Shy='$newshy' where RegistrationId='$this->RegistrationNo' and Examid='$this->ExamId' and Empty='T'"; Connection::connect($query); } public function registerForExam(Student $student,$subjects){ #$subjects is an array of Exasubject objects; /* * functionality * read Student,read subjects,read Exam_id; * create new mark objects for each exasubject * check if student did the same subject * set the shy of each * save the mark Object * if the student has sat for the same exam without any marks it should be caught */ $st=new Mark(); $stMarks; if(is_array($subjects)){ foreach($subjects as $subject){ $stm=new Mark(); $stm->ExamId=$subject->Exa_id; $stm->RegistrationNo=$student->RegistrationNo; $stm->setShy($subject->Exa_id,$subject); $stm->setMarkVals(); $stmk=$subject->Exa_id; $stMarks["$stmk"]=$stm; } } return $stMarks; } public function setShy($Exam_id,$subject){ $Marks= $this->studentDidExam($this->RegistrationNo, $subject->Sub_id); //print_r($Marks); if(is_array($Marks)){ //echo "hallo its array"; ksort($Marks); $no=count($Marks); $Marks=array_values($Marks); $lsmk=$Marks[($no-1)]; //print_r($lsmk); if(($lsmk->Attended=='T') && (($lsmk->Shy)<3)){ $this->Shy=($lsmk->Shy)+1; }elseif(($lsmk->Attended=='F') && (($lsmk->Shy)<4)){ if($lsmk->Empty=="T"){ // echo $this->ExamId; $this->MarkError="The student appeal duplicate Error"; //echo $this->MarkError; //echo "Error"; }else{ $this->Shy=($lsmk->Shy)+1; $this->Note="Has an ability to appeal";} }else{ $this->MarkError="Unacceptable attempt value $lsmk->Shy attempted"; } }else{ #To manage the the first attept $this->Shy=1; } } } ?>
JavaScript
UTF-8
1,922
2.671875
3
[]
no_license
const template = require('art-template') const fs = require('fs'); const queryString = require('querystring'); const model=require('./05-读取相关的json文件-数据模型层') let controller={ // 加载静态文件 loadstaticfile:function(req,res){ // 处理css抬头 if (req.url.endsWith('.css')) { res.setHeader('Content-Type', 'text/css'); } // 映入相关的静态文件 fs.readFile('.' + req.url, (err, data) => { if (err) console.log(err); res.end(data) }) }, // 处理英雄列表页面的渲染 loadheroindex:function(req,res){ // 读取数据库 model.getdatafile(function(arr){ let html = template(__dirname + req.url, { arrm: arr }) res.end(html) }) }, // 处理请求 // 处理页面发过来的请求 // 添加英雄 addhero:function(req,res){ let data = ''; // post要用接收事件来接收数据,数据会一块一块的发过来 req.on('data', (shuju) => { // 把接收到的一块一块的数据加起来 data += shuju }); req.on('end', () => { // 接收完毕后,吧就收得到的数据转换成对象 data = queryString.parse(data) // fs.readFile('./data/heros.json', (err, odata) => { // if (err) console.log(err); // // let olddata = JSON.parse(odata); // }) model.getdatafile(function(hh){ let olddata=hh model.maxdataid(function(hh){ // 最大的id加一就是新数据的id data.id = hh + 1; olddata.push(data); // 旧数据换成json格式好存储 let jsondata = JSON.stringify(olddata) console.log(jsondata); model.writedata(jsondata) let result = JSON.stringify({ code: 200, msg: '新增成功' }); res.end(result); }) }) }) }, } // 把本页的函数给mvc module.exports=controller;
Markdown
UTF-8
8,010
2.71875
3
[]
no_license
--- title: kernel_mtd date: 2019-06-25 11:43:30 tags: - mtd categories: - drivers --- ## 1. Flash 大致分类 - Nor Flash (intel 开发) - Nand Flash (Toshiba 开发) - OneNand Flash(Samsung 开发) <!--more--> NAND Flash在容量、功耗、使用寿命、写速度快、芯片面积小、单元密度高、擦除速度快、成本低等方面的优势使其成为高数据存储密度的理想解决方案。 NOR Flash的传输效率很高,但写入和擦除速度较低; OneNAND结合了NAND存储密度高、写入速度快和NOR读取速度快的优点,整体性能完全超越常规的NAND和NOR。 __OneNAND采用NAND逻辑结构的存储内核和NOR的控制接口,并直接在系统内整合一定容量SRAM静态随即存储器作为高速缓冲区。__ 当OneNAND执行程序时,代码必须从OneNAND存储核心载入到SRAM,然后在SRAM上执行。由于SRAM的速度优势,数据载入动作几乎可以在瞬间完成,用户感觉不到迟滞现象,加上SRAM被直接封装在OneNAND芯片内部,外界看起来就好像是OneNAND也具备程序的本地执行功能。 Flash | 读 | 写 | 擦除 | 坏块 | XIP(eXecute In Place) | 容量 | 寿命 | 成本 :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: Nor Flash | 100MBps | 0.5MBps | 0.3MBps | - | YES | 常见<= 32M | 10几万 | 较高 Nand Flash | 15MBps | 7MBps | 64MBps |有 | - | 大容量 | 100万 | 低 OneNand Flash | 100MBps | 10MBps | 64MBps | 有 | YES | 较大容量 | 100万 | 较低 ### 1.1. 总线接口 #### 1.1.1. Nand Flash Nand Flash 常见有: - 总线接口Flash - SPI Flash 总线flash需要你的MCU上有外部总线接口,SPI flash就是通过SPI口对flash进行读写。 速度上,总线flash比SPI的快,但是SPI 芯片封装布局具有优势。 如果Nand Flash 使用总线接口,一般pin 如下: Pins | Function :-: | :- I/O 0-7(15) | Data input or output(16 bit buswidth chips are supported in kernel) /CE | Chip Enable /CLE | Command Latch Enable ALE | Address Latch Enable /RE | Read Enable /WE | Write Enable /WP | Write Protect /SE | Spare area Enable ( link to GND) R/B | Ready / Busy Output At the moment there are only a few filesystems which support NAND: - JFFS2 and YAFFS for bare NAND Flash and SmartMediaCards - NTFL for DiskOnChip devices - TRUEFFS from M-Systems for DiskOnChip devices - SmartMedia DOS-FAT as defined by the SSFDC Forum - UBIFS for bare NAND flash #### 1.1.2. Nor Flash 在通信方式上Nor Flash 分为两种类型:CFI Flash和 SPI Flash。 _CFI Flash_ 英文全称是common flash interface,也就是公共闪存接口,是由存储芯片工业界定义的一种获取闪存芯片物理参数和结构参数的操作规程和标准。CFI有许多关于闪存芯片的规定,有利于嵌入式对FLASH的编程。现在的很多NOR FLASH 都支持CFI,但并不是所有的都支持。 CFI接口,相对于串口的SPI来说,也被称为parallel接口,并行接口;另外,CFI接口是JEDEC定义的,所以,有的又成CFI接口为JEDEC接口。所以,可以简单理解为:对于Nor Flash来说,CFI接口=JEDEC接口=Parallel接口 = 并行接口 _SPI Flash_ serial peripheral interface串行外围设备接口,是一种常见的时钟同步串行通信接口。 _两者不同处_ CFI接口的的Nor Flash的针脚较多,芯片较大。之所有会有SPI接口, 可以减少针脚数目,减少芯片封装大小,采用了SPI后的Nor Flash,针脚只有8个。SPI容量都不是很大,读写速度慢,但是价格便宜,操作简单。而parallel接口速度快,容量上市场上已经有1Gmbit的容量,价格昂贵。 ## 2. 延伸扩展 ![](https://gss2.bdstatic.com/-fo3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike92%2C5%2C5%2C92%2C30/sign=47c8a31259ee3d6d36cb8f99227f0647/e1fe9925bc315c60225ddb5a8db1cb13485477be.jpg) ### 2.1. SSD [SATA](https://baike.baidu.com/item/SATA) 接口 (串行口) ![](https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/w%3D268/sign=226f2bbbb13533faf5b6942890d2fdca/d53f8794a4c27d1ee9ac99711bd5ad6edcc438f8.jpg) ### 2.2. SSD [NVME](https://baike.baidu.com/item/NVMe/20293531) 接口 (PCIe 口) ![](https://gss0.bdstatic.com/94o3dSag_xI4khGkpoWK1HF6hhy/baike/c0%3Dbaike150%2C5%2C5%2C150%2C50/sign=61b517595866d0166a14967af642bf62/cefc1e178a82b90112fe57a7798da9773812efd7.jpg) [SSD技术扫盲之:什么是NVMe? NVMe SSD有什么特点?](http://www.chinastor.com/baike/ssd/04103A942017.html) ## 3. Kernel MTD Source code ![](https://raw.githubusercontent.com/JShell07/images/master/kernel_mtd/block%20device%20vs%20mtd%20device.png) Kernel 中MTD 的源码如下图所示: ![](https://raw.githubusercontent.com/JShell07/images/master/kernel_mtd/mtd_source_code_tree.png) MTD 组成的源代码框架如下: ![](https://raw.githubusercontent.com/JShell07/images/master/kernel_mtd/mtd_source_code_structure.png) 项目 | 说明 :-: | :- FTL | Flash Translation Layer, 需要PCMCIA 硬件授权专利 NFTL | Nand flash translation layer, 需要DiskOnChip 硬件授权专利 INFTL | Inverse Nand flash translation layer, 需要DiskOnChip 硬件授权专利 spi-nor | spi nor flash source code chips, maps | CFI Nor Flash nand | nand flash ubi | unsorted block images, 基于raw flash 的卷管理系统 在mtd 目录下还有一些有意思的code, 他们分别是: - mtdconcat.c 将多个MTD 设备组成一个MTD, 功能类似于rapid 磁盘阵列 - cmdlinepart.c 提供解析启动参数中的MTD 信息 - mtdswap.c 交换分区,用于wear leveling 记录erase counter, 但UBI 已经具备此功能 - mtdsuper.c 用于向fs/jffs2, fs/romfs 提供挂载接口 ## 4. 源代码框架 Kernel MTD 在Kernel 中的结构如下: ![](https://raw.githubusercontent.com/JShell07/images/master/kernel_mtd/mtd%20softeware%20structure.png) 在MTD Sub-system 中的结构如下: ![](https://raw.githubusercontent.com/JShell07/images/master/kernel_mtd/mtd_structure.png) mtdchar.c 向flash tools 或者用户层提供IOCTL 操作。 mtdblock.c 向kernel 提供block read/write sector访问。 他们两者的动态加载是通过mtdcore.c 中的add_mtd_device()函数。 例如在mtdblock.c 中: ```c static struct mtd_notifier blktrans_notifier = { .add = blktrans_notify_add, .remove = blktrans_notify_remove, }; int register_mtd_blktrans(struct mtd_blktrans_ops *tr) { ... register_mtd_user(&blktrans_notifier); } ``` 在mtdcore.c 中 ```c int add_mtd_device(struct mtd_info *mtd) { /* register char dev node */ mtd->dev.type = &mtd_devtype; mtd->dev.class = &mtd_class; mtd->dev.devt = MTD_DEVT(i); dev_set_name(&mtd->dev, "mtd%d", i); dev_set_drvdata(&mtd->dev, mtd); if (device_register(&mtd->dev) != 0) goto fail_added; /* call mtd_notifiers, so it will call mtdblock.c blktrans_notify_add() */ list_for_each_entry(not, &mtd_notifiers, list) not->add(mtd); } ``` 大致流程如下图所示: ![](https://raw.githubusercontent.com/JShell07/images/master/kernel_mtd/register%20partition.png) 注册相关数据结构: ```c struct mtd_part { struct mtd_info mtd; struct mtd_info *master; uint64_t offset; struct list_head list; }; struct mtd_partition { const char *name; /* identifier string */ uint64_t size; /* partition size */ uint64_t offset; /* offset within the master MTD space */ uint32_t mask_flags; /* master MTD flags to mask out for this partition */ struct nand_ecclayout *ecclayout; /* out of band layout for this partition (NAND only) */ }; ``` ## 参看资源: [OneNAND](https://blog.csdn.net/programxiao/article/details/6214607) [三星OneNAND技术](https://www.chinaflashmarket.com/Instructor/102570) [Nand Flash,Nor Flash,CFI Flash,SPI Flash 之间的关系](https://www.cnblogs.com/zhangj95/p/5649518.html) [CFI与SPI flash区别](https://blog.csdn.net/pine222/article/details/47090041) [MTD 官网](http://www.linux-mtd.infradead.org/doc/general.html)
Ruby
UTF-8
66
3.265625
3
[]
no_license
# reverse_eachメソッド [1,2,3,4,5].reverse_each{|i| puts i}
JavaScript
UTF-8
322
2.96875
3
[]
no_license
function getInfo(obj){ let pet=""; if(typeof obj.pet == "object") { pet = obj.pet.join(", "); } else if(typeof obj.pet == "string"){ pet = obj.pet; } else { pet = "none"; } return obj.name + "<br>" + obj.email + "<br>" + obj.phone + "<br>" + pet + "<br>"; } module.exports = getInfo;
C
UTF-8
343
3.890625
4
[]
no_license
//simple operations #include<stdio.h> int main() { int a; a=0; float b; b=0.0; a=a+10; b=a*11; a=a%7; a=b/13; return 0; } /*Expected Output :- Valid Expressions : 1 goto 1: 2 a: 0 3 b: 0.0 4 T0: a + 10 5 a: T0 6 T1: a * 11 7 b: T1 8 T2: a % 7 9 a: T2 10 T3: b / 13 11 a: T3 12 return: */
Markdown
UTF-8
1,628
2.96875
3
[]
no_license
## 第一节:机器学习 - TensorFlow ### 1. 安装 #### Step 1: 登录 DataFoundry。如果你还没有账号,请点击注册。 ![](img/login.png) #### Step 2: 登录后的页面如下所示,点击“后端服务”,进行实例申请。 ![](img/backing_service_apply.png) #### Step 3: 创建 TensorFlow 服务的实例,输入服务名称后点击“创建”。 ![](img/create_instance.png) #### Step 4: 在我的后端实例中找到 TensorFlow 实例,点击 Dashboard 图标,进入 jupyter notebook 进行实例编辑。 ![](img/dashboard.png) ![](img/notebook.png) #### Step 5: 进入后,你可以选择运行已有文件,或点击右上方“new”新建自己的文件。 ![image](img/run_jupyter.png) ### 2.示例 - [Get_Started:用平面拟合三维数据](Tutorials/Get_Started.md) 本节从一段用 Python API 撰写的 TensorFlow 示例代码起步,让你对将要学习的内容有初步的印象。 - [MNIST:机器学习入门](Tutorials/MNIST.md) 本节讲述一个经典的手写数字识别 (MNIST) 问题,分别提供了简单实现和基于卷积神经网络的实现。 - [Word2Vec:单词的向量表示](Tutorials/Word2Vec.md) 本节让你了解为什么学会使用向量来表示单词, 是一件很有用的事情,所介绍的 Word2Vec 模型, 是一种高效学习嵌套的方法. - [PDE_Raindrop:运用偏微分方程模拟水滴落入水面的过程](Tutorials/PDE_Raindrop.md) 本节是一个非机器学习计算的例子,我们利用一个原生实现的偏微分方程,对雨滴落在池塘上的过程进行仿真.
C++
UTF-8
31,289
2.640625
3
[]
no_license
// C++11 #include <algorithm> #include <cstdlib> #include <iostream> #include <map> #include <sstream> #include <vector> #include <set> #include <string> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <queue> #include <utility> #include <cstdlib> #include <complex> #include <array> using namespace std; template<class F, class S> string in_v_to_str (const pair<F, S> v); template<class F, class S> string v_to_str (const pair<F, S> v); string in_v_to_str (const char v) { return "'" + string{v} + "'"; } string in_v_to_str (const char *v) { return '"' + v + '"'; } string in_v_to_str (const string v) { return '"' + v + '"'; } template<class T> string in_v_to_str (const T v) { stringstream ss; ss << v; return ss.str(); } template<class T> string v_to_str (const T v) { stringstream ss; ss << v; return ss.str(); } template<class T, size_t N> string v_to_str (const array<T, N> &v) { stringstream ss; if (v.size() > 0) { ss << "["; for (int i = 0; i < v.size() - 1; ++i) { ss << in_v_to_str(v[i]) << ", "; } ss << in_v_to_str(v[v.size() - 1]) << "]"; } else { ss << "[]"; } return ss.str(); } template<class T, size_t N> string v_to_str (const array< array<T, N>, N > &v) { stringstream ss; if (v.size() > 0) { ss << "["; for (int i = 0; i < v.size() - 1; ++i) { ss << v_to_str(v[i]) << ", "; } ss << v_to_str(v[v.size() - 1]) << "]"; } else { ss << "[-]"; } return ss.str(); } template<class T> string v_to_str (const vector<T> &v) { stringstream ss; if (v.size() > 0) { ss << "["; for (int i = 0; i < v.size() - 1; ++i) { ss << in_v_to_str(v[i]) << ", "; } ss << in_v_to_str(v[v.size() - 1]) << "]"; } else { ss << "[]"; } return ss.str(); } template<class T> string v_to_str (const vector< vector<T> > &v) { stringstream ss; if (v.size() > 0) { ss << "["; for (int i = 0; i < v.size() - 1; ++i) { ss << v_to_str(v[i]) << ", "; } ss << v_to_str(v[v.size() - 1]) << "]"; } else { ss << "[-]"; } return ss.str(); } template<class T> string v_to_str (const set<T> &v) { stringstream ss; int len = v.size(); ss << (v.size() > 0 ? "{" : "{}"); for (auto& i : v) { ss << in_v_to_str(i) << (len-- > 1 ? ", " : "}"); } return ss.str(); } template<class K, class V> string v_to_str (const map<K, V> &v) { stringstream ss; int len = v.size(); ss << (v.size() > 0 ? "{" : "{}"); for (auto& i : v) { ss << in_v_to_str(i.first) << " : " << in_v_to_str(i.second) << (len-- > 1 ? ", " : "}"); } return ss.str(); } template<class T> string v_to_str (const unordered_set<T> &v) { stringstream ss; int len = v.size(); ss << (v.size() > 0 ? "{" : "{}"); for (auto& i : v) { ss << in_v_to_str(i) << (len-- > 1 ? ", " : "}"); } return ss.str(); } template<class K, class V> string v_to_str (const unordered_map<K, V> &v) { stringstream ss; int len = v.size(); ss << (v.size() > 0 ? "{" : "{}"); for (auto& i : v) { ss << in_v_to_str(i.first) << " : " << in_v_to_str(i.second) << (len-- > 1 ? ", " : "}"); } return ss.str(); } template<class F, class S> string in_v_to_str (const pair<F, S> v) { stringstream ss; ss << "<" << v_to_str(v.first) << ", " << v_to_str(v.second) << ">"; return ss.str(); } template<class F, class S> string v_to_str (const pair<F, S> v) { stringstream ss; ss << "<" << v_to_str(v.first) << ", " << v_to_str(v.second) << ">"; return ss.str(); } string print () { return ""; } template<typename F, typename... R> string print (const F &f, const R &...r) { stringstream ss; ss << v_to_str(f); if (sizeof...(r) > 0) { ss << " " << print(r...); } return ss.str(); } inline uint32_t xrnd() { static uint32_t y = 2463534242; y = y ^ (y << 13); y = y ^ (y >> 17); return y = y ^ (y << 5); } vector<string> split (string str, string sep = " ", int n = 0) { int prev = 0; vector<string> v; n = n < 1 ? str.size() : n; for (int i = 0; (i = str.find(sep, prev)) > -1 && n; --n) { v.push_back(str.substr(prev, i - prev)); prev = i + sep.size(); } v.push_back(str.substr(prev, str.size())); return v; } vector<string> split (string str, char sep = ' ', int n = 0) { string s = {sep}; return split(str, s, n); } #include <time.h> #include <sys/timeb.h> class StopWatch { public: int starts; int startm; struct timeb timebuffer; StopWatch () { ftime(&this->timebuffer); this->starts = this->timebuffer.time; this->startm = this->timebuffer.millitm; } inline int get_milli_time () { ftime(&this->timebuffer); return (this->timebuffer.time - this->starts) * 1000 + (this->timebuffer.millitm - this->startm); } }; class Player { public: int atk = 0; int def = 0; int agg = 0; int index = 0; Player (string s, int index) { auto vs = split(s, ','); this->atk = stoi(vs[0]); this->def = stoi(vs[1]); this->agg = stoi(vs[2]); // if (this->agg > 10) { this->atk *= 0.95; } // if (this->agg > 10) { this->def *= 0.95; } // if (this->agg > 20) { this->atk *= 0.95; } // if (this->agg > 20) { this->def *= 0.95; } // if (this->agg > 30) { this->atk *= 0.9; } // if (this->agg > 30) { this->def *= 0.9; } // if (this->agg > 40) { this->atk *= 0.9; } // if (this->agg > 40) { this->def *= 0.9; } this->index = index; } }; class Group { public: int flags = 0; int atk = 0; int def = 0; int agg = 0; int eatk = 0; int edef = 0; int eagg = 0; vector<int> indexs; Group (string a, string b) { auto vs = split(a, ','); for (auto &i : vs) { int t = stoi(i); this->flags |= 1 << t; this->indexs.emplace_back(t); } vs = split(b, ','); this->atk = stoi(vs[0]); this->def = stoi(vs[1]); this->agg = stoi(vs[2]); this->eatk = stoi(vs[0]); this->edef = stoi(vs[1]); this->eagg = stoi(vs[2]); // if (this->agg < -5 ) { this->eatk += 2; } // if (this->agg < -5 ) { this->edef += 2; } // if (this->agg < -10) { this->eatk += 2; } // if (this->agg < -10) { this->edef += 2; } // if (this->agg < -15) { this->eatk += 2; } // if (this->agg < -15) { this->edef += 2; } // if (this->agg < -20) { this->eatk += 2; } // if (this->agg < -20) { this->edef += 2; } if (this->agg > 5 ) { this->eatk -= 2; } if (this->agg > 5 ) { this->edef -= 2; } if (this->agg > 10) { this->eatk -= 2; } if (this->agg > 10) { this->edef -= 2; } if (this->agg > 15) { this->eatk -= 2; } if (this->agg > 15) { this->edef -= 2; } if (this->agg > 20) { this->eatk -= 2; } if (this->agg > 20) { this->edef -= 2; } // if (this->agg > 5 ) { this->atk -= 2; } // if (this->agg > 5 ) { this->def -= 2; } // if (this->agg > 10) { this->atk -= 2; } // if (this->agg > 10) { this->def -= 2; } // if (this->agg > 15) { this->atk -= 2; } // if (this->agg > 15) { this->def -= 2; } // if (this->agg > 20) { this->atk -= 2; } // if (this->agg > 20) { this->def -= 2; } } }; class Team { public: vector<Player> players; vector<Group> groups; int calcatk = 0; int calcdef = 0; int calceatk = 0; int calcedef = 0; vector<int> positions; array< vector<int> , 10 > member; int uses = 0; Team () {} void InputPlayers(vector<string> players_vs) { for (int i = 0; i < players_vs.size(); ++i) { this->players.emplace_back(players_vs[i], i); this->positions.emplace_back('-'); } } void InputGroups(vector<string> groups_vs) { for (int i = 0; i < groups_vs.size(); ++i) { auto ss = split(groups_vs[i], ' '); this->groups.emplace_back(ss[0], ss[1]); } } int cnt = 0; string NextMaxPlayer () { this->cnt += 1; int bestscore = 0; int tscore = 0; int index = -1; string p = ""; int tatk = 0; int tdef = 0; for (auto &i : this->players) { if (this->uses & (1 << i.index)) { continue; } if (this->cnt % 2 == 1) { // atk tatk = this->calcatk + i.atk *2; tdef = this->calcdef; this->PreGroupEffect(i.index, tatk, tdef); tscore = tatk + tdef; if (tscore > bestscore) { bestscore = tscore; index = i.index; p = "F "; } } else { // def tatk = this->calcatk; tdef = this->calcdef + i.def *2; this->PreGroupEffect(i.index, tatk, tdef); tscore = tatk + tdef; if (tscore > bestscore) { bestscore = tscore; index = i.index; p = "D "; } } } if (p == "F ") { this->calcatk += this->players[index].atk * 2; this->Use(index, 'F'); } if (p == "M ") { this->calcatk += this->players[index].atk; this->calcdef += this->players[index].def; this->Use(index, 'M'); } if (p == "D ") { this->calcdef += this->players[index].def * 2; this->Use(index, 'D'); } this->GroupEffect(); return p + to_string(index); } void PrintUse () { cerr << "b"; for (int i = 0; i < 30; ++i) { if (this->uses & (1 << i)) { cerr << "1"; } else { cerr << "0"; } } cerr << endl; } void Use (int index, char position) { this->uses |= 1 << index; this->positions[index] = position; } void Remove (int index) { this->uses ^= 1 << index; this->positions[index] = '-'; } void ResetUse () { this->uses = 0; } void GroupEffect () { this->calceatk = 0; this->calcedef = 0; for (auto &i : this->groups) { int t = this->uses & i.flags; if (t == i.flags) { this->calceatk += i.atk; this->calcedef += i.def; } } } void PreGroupEffect (int index, int &atk, int &def) { int preuses = this->uses | (1 << index); for (auto &i : this->groups) { if ((preuses & i.flags) == i.flags) { atk += i.atk; def += i.def; } } } int All_Score () { int atk = 0; int def = 0; for (int i = 0; i < 30; ++i) { if (this->positions[i] == '-') { continue; } if (this->positions[i] == 'F') { atk += this->players[i].atk * 2; } else if (this->positions[i] == 'D') { def += this->players[i].def * 2; } else { atk += this->players[i].atk; def += this->players[i].def; } } for (auto &i : this->groups) { if ((this->uses & i.flags) == i.flags) { for (auto &j : i.indexs) { if (this->positions[j] == 'F') { atk += i.eatk * 2; } else if (this->positions[j] == 'D') { def += i.edef * 2; } else { atk += i.eatk; def += i.edef; } } } } return min(atk, def) + (atk+def)/4;//////////////////// } vector<string> ToRet () { vector<string> ret; for (int i = 0; i < 30; ++i) { if (this->positions[i] == '-') { continue; } ret.emplace_back(print((char)this->positions[i], i)); } return ret; } int createCurrentLineup (array<int, 10> &poss, array<bool, 10> &cords, array<int, 30> &calcAgg) { static const int F = 'F'; static const int D = 'D'; int uses = 0; int atk = 0; int def = 0; vector<int> positions; for (int i = 0; i < 30; ++i) { calcAgg[i] = 0; positions.emplace_back(0); } for (int i = 0; i < 10; ++i) { if (poss[i] >= this->member[i].size()) { continue; } uses |= 1 << this->member[i][poss[i]]; Player p = this->players[this->member[i][poss[i]]]; if (this->member[i][0] == F) { atk += p.atk * 2; } else if (this->member[i][0] == D) { def += p.def * 2; } else { atk += p.atk; def += p.def; } calcAgg[this->member[i][poss[i]]] = p.agg; positions[this->member[i][poss[i]]] = this->member[i][0]; } for (auto &i : this->groups) { if ((uses & i.flags) == i.flags) { for (auto &j : i.indexs) { if (positions[j] == F) { atk += i.atk * 2; } else if (positions[j] == D) { def += i.def * 2; } else { atk += i.atk; def += i.def; } calcAgg[j] += i.agg; } } } return min(atk, def); } void processLineup (array<int, 10> &poss, array<bool, 10> &cords, array<int, 30> &calcAgg, int n) { if (calcAgg[this->member[n][poss[n]]]) { poss[n] += 1; } } int Simulate (int n) { array<int, 10> poss{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; array<bool, 10> cords{false, false, false, false, false, false, false, false, false, false}; array<int, 30> calcAgg; int ret = this->createCurrentLineup(poss, cords, calcAgg); this->processLineup(poss, cords, calcAgg, n); ret += this->createCurrentLineup(poss, cords, calcAgg); return ret; } int ReSimulate () { int ret = 0; int minret = 10000; int maxret = 0; for (int i = 0; i < 10; ++i) { int t = Simulate(i); ret += t; minret = min(minret, t); maxret = max(maxret, t); } for (int i = 0; i < 10; ++i) { int t = Simulate(i); ret += t; minret = min(minret, t); maxret = max(maxret, t); } return ret / 10; } void InitRefrain (vector<int> positions) { int mi = 0; for (int i = 0; i < 30; ++i) { if (positions[i] == '-') { continue; } this->member[mi].emplace_back(positions[i]); this->member[mi].emplace_back(i); mi += 1; } for (int k = 0; k < 3; ++k) { for (int j = 0; j < 10; ++j) { int point = -100; int index = -1; for (int i = 0; i < 30; ++i) { if (positions[i] != '-') { continue; } if (this->member[j][0] == 'F') { if (this->players[i].atk > point) { index = i; point = this->players[i].atk; } } if (this->member[j][0] == 'D') { if (this->players[i].def > point) { index = i; point = this->players[i].def; } } if (this->member[j][0] == 'M') { if (this->players[i].atk+this->players[i].def - abs(this->players[i].atk-this->players[i].def)/2 > point) { index = i; point = this->players[i].atk+this->players[i].def - abs(this->players[i].atk-this->players[i].def)/2; } } } if (index > -1) { this->member[j].emplace_back(index); positions[index] = 'x'; } } } } vector<string> ToRet (vector<int> positions) { vector<string> ret; int mi = 0; for (int i = 0; i < 30; ++i) { if (positions[i] == '-') { continue; } ret.emplace_back(print((char)positions[i], i)); } for (int k = 0; k < 3; ++k) { for (int j = 0; j < 10; ++j) { int point = -1; int index = -1; for (int i = 0; i < 30; ++i) { if (positions[i] != '-') { continue; } if (this->member[j][0] == 'F') { if (this->players[i].atk > point) { index = i; point = this->players[i].atk; } } if (this->member[j][0] == 'D') { if (this->players[i].def > point) { index = i; point = this->players[i].def; } } if (this->member[j][0] == 'M') { if (this->players[i].atk+this->players[i].def - abs(this->players[i].atk-this->players[i].def)/2 > point) { index = i; point = this->players[i].atk+this->players[i].def - abs(this->players[i].atk-this->players[i].def)/2; } } } if (index > -1) { ret[j] += ',' + to_string(index); positions[index] = 'x'; } } } return ret; } vector<string> ToRet2 () { vector<string> ret(10, ""); for (int i = 0; i < 10; ++i) { auto m = this->member[i]; if (m[0] == 'F') { ret[i] += "F "; } else if (m[0] == 'D'){ ret[i] += "D "; } else { ret[i] += "M "; } ret[i] += to_string(m[1]); for (int j = 2; j < m.size(); ++j) { ret[i] += "," + to_string(m[j]); } } return ret; } }; class WorldCupLineup { public: Team team; StopWatch sw; vector<string> selectPositions(vector<string> players, vector<string> groups) { this->team.InputPlayers(players); this->team.InputGroups(groups); for (int j = 0; j < 10; ++j) { this->team.NextMaxPlayer(); //this->team.Use(j, 'F'); } auto vi = this->SA(3000); this->team.InitRefrain(vi); this->SA2(9000); return this->team.ToRet2(); } vector<int> SA (int limit) { vector<int> ret = this->team.positions; double bestscore = this->team.All_Score(); double lastscore = bestscore; int saTimeStart = this->sw.get_milli_time(); int saTimeEnd = limit; int saTimeCurrent = saTimeStart; int64_t R = 1000000000; int loop = 500; while ((saTimeCurrent = this->sw.get_milli_time()) < saTimeEnd) { for (int k = 0; k < 100; ++k) { for (int i = 0; i < loop; ++i) { int a = xrnd() % 30; int b = xrnd() % 30; char tp = this->team.positions[a]; double btscore = 0; char bp = 'F'; if (this->team.positions[a] == '-') { continue; } if (this->team.positions[b] != '-') { continue; } { this->team.Remove(a); bp = "FMD"[xrnd()%3]; this->team.Use(b, bp); btscore = (double)this->team.All_Score(); this->team.Remove(b); this->team.Use(a, tp); } const double T = saTimeEnd-saTimeStart; const double t = saTimeCurrent-saTimeStart; double startTemp = 256.0; double endTemp = 0.0; double temp = startTemp + (endTemp - startTemp) * t / T; double probability = exp((btscore - lastscore) / temp); bool FORCE_NEXT = probability > (double)(xrnd() % R) / R; if (btscore > lastscore || (FORCE_NEXT)) { lastscore = btscore; this->team.Remove(a); this->team.Use(b, bp); if (btscore > bestscore) { bestscore = btscore; ret = this->team.positions; } } else { } } for (int i = 0; i < 30; ++i) { int a = i; char tp = this->team.positions[a]; double btscore = 0; char bp = 'F'; if (this->team.positions[a] == '-') { continue; } { this->team.Remove(a); this->team.Use(a, 'F'); int tscore = this->team.All_Score(); if (tscore > btscore) { btscore = (double)tscore; bp = 'F'; } this->team.Remove(a); this->team.Use(a, tp); } { this->team.Remove(a); this->team.Use(a, 'D'); int tscore = this->team.All_Score(); if (tscore > btscore) { btscore = (double)tscore; bp = 'D'; } this->team.Remove(a); this->team.Use(a, tp); } { this->team.Remove(a); this->team.Use(a, 'M'); int tscore = this->team.All_Score(); if (tscore > (double)btscore) { btscore = tscore; bp = 'M'; } this->team.Remove(a); this->team.Use(a, tp); } const double T = saTimeEnd-saTimeStart; const double t = saTimeCurrent-saTimeStart; double startTemp = 256.0; double endTemp = 0.0; double temp = startTemp + (endTemp - startTemp) * t / T; double probability = exp((btscore - lastscore) / temp); bool FORCE_NEXT = probability > (double)(xrnd() % R) / R; if (btscore > lastscore || (FORCE_NEXT)) { lastscore = btscore; this->team.Remove(a); this->team.Use(a, bp); if (btscore > bestscore) { bestscore = btscore; ret = this->team.positions; } } else { } } } } // this->team.positions = ret;////////////// return ret; } void SA2 (int limit) { auto ret = this->team.member; double bestscore = this->team.ReSimulate(); double lastscore = bestscore; int saTimeStart = sw.get_milli_time(); int saTimeEnd = limit; int saTimeCurrent = saTimeStart; int64_t R = 1000000000; int loop = 10; while ((saTimeCurrent = sw.get_milli_time()) < saTimeEnd) { for (int k = 0; k < 2; ++k) { for (int i = 0; i < loop; ++i) { for (int o = 0; o < 1; ++o) { // { int a = xrnd() % 10; int b = xrnd() % 10; int c = xrnd() % (this->team.member[a].size()-2); int d = xrnd() % (this->team.member[b].size()-2); swap(this->team.member[a][c+2], this->team.member[b][d+2]); int tscore = this->team.ReSimulate(); const double T = saTimeEnd-saTimeStart; const double t = saTimeCurrent-saTimeStart; double startTemp = 256.0; double endTemp = 0.0; double temp = startTemp + (endTemp - startTemp) * t / T; double probability = exp((tscore - lastscore) / temp); bool FORCE_NEXT = probability > (double)(xrnd() % R) / R; if (tscore > lastscore || (FORCE_NEXT)) { lastscore = tscore; if (tscore > bestscore) { bestscore = tscore; ret = this->team.member; } } else { swap(this->team.member[a][c+2], this->team.member[b][d+2]); } } // { // int a = xrnd() % 10; // int c = "FMD"[xrnd() % 3]; // swap(this->team.member[a][0], c); // int tscore = this->team.ReSimulate(); // const double T = saTimeEnd-saTimeStart; // const double t = saTimeCurrent-saTimeStart; // double startTemp = 512.0; // double endTemp = 0.0; // double temp = startTemp + (endTemp - startTemp) * t / T; // double probability = exp((tscore - lastscore) / temp); // bool FORCE_NEXT = probability > (double)(xrnd() % R) / R; // if (tscore > lastscore || (FORCE_NEXT)) { // lastscore = tscore; // if (tscore > bestscore) { // bestscore = tscore; // ret = this->team.member; // } // } else { // swap(this->team.member[a][0], c); // } // } } } } this->team.member = ret; } void SA3 (int limit) { auto ret = this->team.member; double bestscore = this->team.ReSimulate(); double lastscore = bestscore; int saTimeStart = sw.get_milli_time(); int saTimeEnd = limit; int saTimeCurrent = saTimeStart; int64_t R = 1000000000; int loop = 10; while ((saTimeCurrent = sw.get_milli_time()) < saTimeEnd) { for (int k = 0; k < 2; ++k) { for (int i = 0; i < loop; ++i) { { int a = xrnd() % 10; int b = xrnd() % 10; if (this->team.member[a].size() < 4 || a == b) { continue; } this->team.member[b].emplace_back(this->team.member[a][this->team.member[a].size()-1]); this->team.member[a].pop_back(); int tscore = this->team.ReSimulate(); const double T = saTimeEnd-saTimeStart; const double t = saTimeCurrent-saTimeStart; double startTemp = 256.0; double endTemp = 0.0; double temp = startTemp + (endTemp - startTemp) * t / T; double probability = exp((tscore - lastscore) / temp); bool FORCE_NEXT = probability > (double)(xrnd() % R) / R; if (tscore > lastscore || (FORCE_NEXT)) { lastscore = tscore; if (tscore > bestscore) { bestscore = tscore; ret = this->team.member; } } else { this->team.member[a].emplace_back(this->team.member[b][this->team.member[b].size()-1]); this->team.member[b].pop_back(); } } } } } this->team.member = ret; } }; // -------8<------- end of solution submitted to the website -------8<------- template<class T> void getVector(vector<T>& v) { for (int i = 0; i < v.size(); ++i) { // string a = ""; // string b = ""; // cin >> a >> b; // v[i] = a + " " + b; cin >> v[i]; // getline(cin, v[i]); } } template<class T> void getVector2(vector<T>& v) { for (int i = 0; i < v.size(); ++i) { string a = ""; string b = ""; cin >> a >> b; v[i] = a + " " + b; // getline(cin, v[i]); } } int main() { WorldCupLineup sol; int H; cin >> H; vector<string> players(H); getVector(players); cin >> H; vector<string> groups(H); getVector2(groups); vector<string> ret = sol.selectPositions(players, groups); cout << ret.size() << endl; for (int i = 0; i < (int)ret.size(); ++i) cout << ret[i] << endl; cout.flush(); }
Markdown
UTF-8
16,409
3.015625
3
[ "MIT" ]
permissive
--- date: "1" --- # Building an App example - Buy me a Coffee ![](imgs/buy-me-coffee-example.png) We're going to build a very simple application called "Buy me a coffee". A simple button that when pressed, requests a connection to the Plug wallet and a transfer! A [live demo](http://demo.plugwallet.ooo/buy-me-a-coffee?id=xxx&amount=yyy) is available but make sure to replace the url parameters in the address bar with your desired values for testing! If you're clueless, learn more [here](#live-demo). ## Requirements 🤔 The guide assumes you have some basic knowledge of HTML, CSS and Javascript, we'll keep it easy! It's recommended to read the [Getting started](/getting-started/connect-to-plug/) guide before you dive into the examples, as it gives you an overview of how Plug works. Make sure you use a code editor, such as [Visual Studio Code](https://code.visualstudio.com/) or [Sublime text](https://www.sublimetext.com/), for editing the source-code! ## Scaffolding 🏗 Just like a real scaffolding in a building construction site, let's create a quick structure for our project, the skeleton for our application! We're going to write a simple [HTML](https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/HTML_basics) structure for a page, where we'll show the "Buy me a coffee" button. Start by creating a project directory in your operating system, for example, a directory called `Plug-buy-me-coffee` in your [home directory](https://en.wikipedia.org/wiki/Home_directory), or your favourite project directory. In the project directory, create a new file named `index.html`, with the following content and save it! ```html <html> <head> <title>Buy me a coffee</title> <!-- App stylesheet (decoration, styles) --> <!-- App javascript (functionality, logic) --> </head> <body> <!-- App container (button) --> </body> </html> ``` We'll substitute the comments by the actual implementation, ordered by simplicity: - [Application structure](#application-structure) (html) - [Custom styles](#custom-styles) (css) - [Call-to-action](#call-to-action) (javascript) - [Plug implementation](#plug-implementation) (javascript, Plug API) With that said, let's get our hands dirty and start coding! ## Application structure 🚧 Open and edit the file `index.html` replacing the `<!-- App container (button) -->` comment with our desired application structure, as follows: ```html <html> <head> <title>Buy me a coffee</title> <!-- App stylesheet (decoration, styles) --> <!-- App javascript (functionality, logic) --> </head> <body> <div id="app"> <button id="buy-me-coffee">Buy me a coffee</button> </div> </body> </html> ``` Open the `index.html` file in the browser or refresh the page as you go to see the changes! ## Custom styles 👄 Create a new file named `main.css` in the project directory to add custom styles for the app: - Title colour - Button size - etc Open and edit the file `index.html` replacing the `<!-- App stylesheet (decoration, styles) -->` comment with a link to our external stylesheet file we have just created, as follows: ```html <html> <head> <title>Buy me a coffee</title> <link rel="stylesheet" href="main.css"> <!-- App javascript (functionality, logic) --> </head> <body> <div id="app"> <button id="buy-me-coffee">Buy me a coffee</button> </div> </body> </html> ``` Open end edit the stylesheet file `main.css` and add some custom styles. Let's say that we make the button super colourful like Plug, so copy the following content to the `main.css` and save it: ```css #buy-me-coffee { border: none; font-style: normal; font-weight: bold; font-size: 16px; line-height: 24px; background: linear-gradient(94.95deg, #FFE701 -1.41%, #FA51D3 34.12%, #10D9ED 70.19%, #52FF53 101.95%); border-radius: 10px; color: #fff; padding: 6px 32px; cursor: pointer; transition: opacity 0.3s ease-in, transform 0.3s ease-in-out; transform: scale(1); } #buy-me-coffee:hover { opacity: 0.94; transform: scale(1.02); } ``` Once you refresh the page, it should look like example below, a colourful [call-to-action](#call-to-action). We'll implement the action next! ![](imgs/buy-me-coffee-button-style.gif){: style="max-width:480px"} Feel free to edit `main.css` and change the styles to your liking! For example, change the container to center the button verticaly and horizontaly: ```css #app { display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; } ``` ## Call-to-action 🏃🏽‍♀️ We are now going to create our main javascript file where we'll implement the `call-to-action`. Create a file named `app.js` in the project directory. This is where we'll put our implementation code to handle the requests via the [Plug's](/getting-started/connect-to-plug/) application programming interface ([API](https://en.wikipedia.org/wiki/API)), as described in the [Getting started guide](/getting-started/connect-to-plug/). As an initial placeholder, let's add a "mouse-click" event listener to the `call-to-action` that'll show an alert! ```js // Initialises the application listeners and handlers function main() { const button = document.querySelector('#buy-me-coffee'); button.addEventListener("click", onButtonPress); } // Button press handler function onButtonPress() { alert("Buy me a coffee button was pressed!") } // Calls the Main function when the document is ready document.addEventListener("DOMContentLoaded", main); ``` Here's a simple breakdown of what it does: - Awaits for the document to be ready - Calls the `main` function - Adds a listener to the button `#buy-me-coffee` - When `clicked` calls the function `onButtonPress` Link the `app.js` file to the `index.html` for this to work! Open and edit the file `index.html`, replacing the `<!-- App javascript (functionality, logic) -->` with a link to our javascript file `app.js`, as follows: ```html <html> <head> <title>Buy me a coffee</title> <link rel="stylesheet" href="main.css"> <script type="text/javascript" src="app.js"></script> </head> <body> <div id="app"> <button id="buy-me-coffee">Buy me a coffee</button> </div> </body> </html> ``` After you save the changes, refresh the page and press the `Buy me a coffee` button. You'll get an alert with the message `Buy me a coffee button was pressed!`. We can now proceed and implement the Plug processes in the function body `onButtonPress`. ## Plug implementation 👷🏻‍♀️ Open the file `app.js` in your code editor and edit the `onButtonPress` function body, as we want to write the logic to request a transfer of a certain amount via the Plug extension API. We can break it down in the following steps: - [Detect the Plug extension](#detect-the-plug-extension) - [Check balance](#check-balance) - [Request to transfer](#request-to-transfer) - On success or error, display a message ## Detect the Plug extension 🔎 Firstly, we check if the end-user has the Plug extension in the current browser, as documented in the [Getting started guide](/getting-started/connect-to-plug/). Notice that we make the function [asynchronous](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function), as we're dealing with a network request, which is resolved at anytime in the future and as such, a response we need to await. Edit the function body for `onButtonPress` and replace the `alert` placeholder with: ```js async function onButtonPress() { const hasAllowed = await window.ic.plug.requestConnect(); if (hasAllowed) { console.log('Plug wallet is connected'); } else { console.log('Plug wallet connection was refused') } } ``` !!! Important So far, we've been opening the local `index.html` file in the web browser for your easiness! It works because opening html files in a browser, computes what the html file is describing and display the content correctly. But there are [browser security restrictions](https://en.wikipedia.org/wiki/Browser_security), that prevent us to make browser extension requests from local files. For this reason, you'll need to serve the project through a local http server! ## Http Server 🤖 There are plenty of options on how to serve projects locally and you are free to pick whatever suits you best! If you're clueless, the quickest you can get a http server running in your local machine, is to first install [Nodejs]((https://nodejs.org/en/download/)) - a program that executes javascript outside the browser, that let us run scripts such as a `http server`, etc. You can find the instructions for your operating system [here](https://nodejs.org/en/download/). Once [Nodejs](https://nodejs.org/en/download/) is installed and available in your system, install the [Http-server](https://www.npmjs.com/package/http-server) package, as an example. Open your terminal and execute the following: ```sh npm install --global http-server ``` Once the [Http-server](https://www.npmjs.com/package/http-server) package is installed, `cd` to the project directory in your terminal and run the following command (the dot represents the current directory): ```sh http-server . ``` Open the browser that has the Plug extension installed and visit one of the addresses in your http server output: ```sh Starting up http-server, serving . Available on: http://127.0.0.1:8080 http://xxx.xxx.x.xx:8080 ``` Let's do a small test and inspect the data in the `developer console`. Open the `developer console` in the browser to see the application script outputs, (here's an example for [Chrome](https://developer.chrome.com/docs/devtools/open/) and [Firefox](https://developer.mozilla.org/en-US/docs/Tools/Browser_Console)). Press the `Buy me a Coffee` button and the `Plug` notification window should pop-up. ![](../getting-started/imgs/app-connection.jpg){: style="max-width:360px"} Choose one of the options `Allow` or `Decline` and find the correspondent output in the console: `Plug wallet is connected` or `Plug wallet connection was refused`. ## Call-to-action locking 🔒 To complete, ensure that the button is disabled through the Plug wallet request duration, to prevent multiple concurrent requests. Here's a breakdown of our intent: - Modify the `onButtonPress` to take a parameter `el` - Pass the DOM button element as an argument during runtime - Reset the `disabled` button property after 5 seconds We give 5 seconds because we want to provide enough time to the end-user to read the text. ```js async function onButtonPress(el) { el.target.disabled = true; const hasAllowed = await window.ic.plug.requestConnect(); if (hasAllowed) { console.log('Plug wallet is connected'); } else { console.log('Plug wallet connection was refused') } setTimeout(function () { el.target.disabled = false; }, 5000); } ``` Feel free to use your own custom values or implementation! ## Check balance 💸 To keep things easy, let's say that a Coffee is the equivalent of `0.04` ICP or `4000000` (fractional units of ICP tokens, called [e8s](https://sdk.dfinity.org/docs/token-holders/self-custody-quickstart.html)). Add the amount at the top of the `app.js` file! ```js const coffeeAmount = 4000000; ``` You can make the amount more readable by spliting the zero's by groups using an underscore: ```js const coffeeAmount = 4_000_000; ``` Finally, we check if the user has enough balance before proceeding to the last step and request the transfer. We'll also change the button text in each state change to improve the user experience. ![](imgs/buy-me-coffee-button-state-change.gif){: style="max-width:480px"} ```js async function onButtonPress() { el.target.disabled = true; const hasAllowed = await window.ic?.plug?.requestConnect(); if (hasAllowed) { el.target.textContent = "Plug wallet is connected"; const requestBalanceResponse = await window.ic?.plug?.requestBalance(); const balance = requestBalanceResponse[0]?.value; if (balance >= coffeeAmount) { el.target.textContent = "Plug wallet has enough balance"; } else { el.target.textContent = "Plug wallet doesn't have enough balance"; } } else { el.target.textContent = "Plug wallet connection was refused"; } setTimeout(function () { el.target.disabled = false; }, 5000); } ``` !!! Important As described in the [Getting started](/getting-started/connect-to-plug/), the asynchronous method **requestBalance** response data is an array, as such, we pick the first result value that is an object type and get the value of the field name "value" of the object. If you're not familiar with the question mark in `window.ic?.plug?.requestBalance`, don't be worried as that's syntax sugar to help us access nested properties, read more about optional chaining [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). Save the file, refresh the page and press the `Buy me a Coffee` button! You should see the correspondent message to your account balance: `Plug wallet has enough balance` or `Plug wallet doesn't have enough balance`. ## Request to transfer ❓ Continue editing the `app.js` file. In the "has enough balance" block, make the `requestTransfer` call, that requires us to pass an argument to the function, that is an object with required fields `to` and `amount`, as described in our [Getting started](/getting-started/connect-to-plug/). ```js const requestTransferArg = { to: receiverAccountId, amount: coffeeAmount, }; const transfer = await window.ic?.plug?.requestTransfer(requestTransferArg); ``` When the `requestTransfer` is called, the `Plug` pop-up will show the panel: ![](imgs/plug-request-transfer.png){: style="max-width:360px"} As we go, the button text is updated according to the transfer result state. When complete, we reset the Button to have the original text `Buy me a coffee`. ```js async function onButtonPress(el) { el.target.disabled = true; const hasAllowed = await window.ic?.plug?.requestConnect(); if (hasAllowed) { el.target.textContent = "Plug wallet is connected" const balance = await window.ic?.plug?.requestBalance(); if (balance >= coffeeAmount) { el.target.textContent = "Plug wallet has enough balance" const requestTransferArg = { to: 'xxxxx', amount: coffeeAmount, }; const transfer = await window.ic?.plug?.requestTransfer(requestTransferArg); const transferStatus = transfer?.transactions?.transactions[0]?.status; if (transferStatus === 'COMPLETED') { el.target.textContent = `Plug wallet transferred ${coffeeAmount} e8s`; } else if (transferStatus === 'PENDING') { el.target.textContent = "Plug wallet is pending."; } else { el.target.textContent = "Plug wallet failed to transfer"; } } else { el.target.textContent = "Plug wallet doesn't have enough balance"; } } else { el.target.textContent = "Plug wallet connection was refused"; } setTimeout(() => { el.target.disabled = false; el.target.textContent = "Buy me a coffee" }, 5000); } ``` Save the changes, refresh the browser and play with it! If everything's done correctly you should have a working application, that connects to Plug and makes a transfer. Hope you enjoyed the read this far and got to build a simple application with Plug! ## Live demo 🎁 A [live demo](http://demo.plugwallet.ooo/buy-me-a-coffee?id=xxx&amount=yyy) is available but make sure to replace the url parameters in the address bar with your desired values for testing! If you're clueless, here's an example where the `id` and `amount` are replaced: - http://demo.plugwallet.ooo/buy-me-a-coffee?id=xxx&amount=yyy - http://demo.plugwallet.ooo/buy-me-a-coffee?id=893jk-u41jaz-439xx&amount=2000000 The id should be a valid Principal or Address id, the amount in ([e8s](https://sdk.dfinity.org/docs/token-holders/self-custody-quickstart.html)) and you'll have to open or refresh the page after the changes! ## Project source-code ⚙️ The source-code for this guide can be found in our [examples](https://github.com/Psychedelic/plug-docs/tree/main/examples/buy-me-a-coffee).
Java
UTF-8
1,576
2.5
2
[]
no_license
package net.kzn.shoppingbackend.daoImpl; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Repository; import net.kzn.shoppingbackend.dao.CategoryDAO; import net.kzn.shoppingbackend.dto.Category; @Repository("categoryDAO") public class CategoryDAOImpl implements CategoryDAO { private static List<Category> categories = new ArrayList<Category>(); static { // adding first category Category category1 = new Category(); category1.setId(1); category1.setName("Television"); category1.setDescription("Samsung TV(LED)"); category1.setImageURL("D:\\walls\\Himalaya"); category1.setActive(true); categories.add(category1); // adding second category Category category2 = new Category(); category2.setId(2); category2.setName("Laptop"); category2.setDescription("Lenovo Laptop 14Inch."); category2.setImageURL("D:\\walls\\dogy"); category2.setActive(true); categories.add(category2); // adding second category Category category3 = new Category(); category3.setId(2); category3.setName("Mobile"); category3.setDescription("oppo 5Inch."); category3.setImageURL("D:\\walls\\dogy"); category3.setActive(true); categories.add(category3); } @Override public List<Category> list() { // TODO Auto-generated method stub return categories; } @Override public Category get(int id) { // enhanced for loop for (Category category : categories) { if (category.getId() == id) return category; } return null; } }
C++
UTF-8
1,778
3.6875
4
[]
no_license
// This program uses the address of each element in the array. #include <iostream> #include <iomanip> using namespace std; int main() { // The following definition of pint is legal because myValue is an integer. int myValue1; int * pint1 = &myValue1; // The following definition of point is illegal because myFloag is not an int. //float myFloat; //int *pint = &mhFloat; //illegal //Pointers may be defined in the same statement as other variables of the same type. int myValue2, *pint2 = &myValue2; // the following definition defines an array, readings, and a pointer, marker, // which is initialized with the address of the first element in the array: double readings[50], *marker = readings; // The following is illegal because pint is being initialized // with the address ofan object that does not exist yet: //int *pint = &myValue; // Illegal! //int myValue; // In most computers, memory at address 0 is inaccessible to user labs because it is // occupied by operating system data structures. This fact allows programmers to signify that // a pointer variable does not point to a memory location accessible to the program by // initializing the pointer to 0. For example, if ptrToint is a pointer to int, and ptrTofloat // is a pointer to float, we can indicate that neither of them points to a legitimate address by // assigning 0 to both: int *ptrToint1 = 0; float *ptrTofloat1 = 0; // Many header files, including iostream, fstream, and cstdlib, define a constant named // NULL whose value is zero. Thus, assuming one of these header files has been included. // A pointer whose value is the address 0 is often called a null pointer. int *ptrToint2 = NULL; float *ptrTofloat2 = NULL; return 0; }
C#
UTF-8
1,168
3.578125
4
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace Task3 { public class Employee { public string name; public decimal basepay; public Employee(string name, decimal basepay) { this.name = name; this.basepay = basepay; } public virtual decimal CalculatePay() { return basepay; } } public class SalesEmployee : Employee { private decimal salesbonus; public SalesEmployee(string name, decimal basepay, decimal salesbonus) : base(name, basepay) { this.salesbonus = salesbonus; } public override decimal CalculatePay() { return basepay + salesbonus; } } public class PartTimeEmployee : Employee { public int workingDays; public PartTimeEmployee(string name, decimal basepay, int workingDays) : base(name, basepay) { this.workingDays = workingDays; } public override decimal CalculatePay() { return workingDays*(basepay/25); } } }
PHP
UTF-8
3,040
2.78125
3
[]
no_license
<?php namespace Oza75\MakeRepository\Commands; use Exception; use Illuminate\Console\Command; use Illuminate\Contracts\Filesystem\FileNotFoundException; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; class MakeRepositoryCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'make:repository {name : The name of the repository}'; /** * The console command description. * * @var string */ protected $description = 'Create a new repository'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return int * @throws Exception */ public function handle() { $name = Str::studly($this->argument('name')); $this->createBaseDirectory(); $this->createRepositoryDirectory($name); $this->createInterface($name); $this->createClass($name); $this->info("$name repository created"); return 0; } private function createBaseDirectory() { if (!File::exists(app_path('Repositories'))) { File::makeDirectory(app_path('Repositories')); File::put(app_path('Repositories/BaseRepository.php'), $this->content('base.stub')); } } /** * @param string $name * @throws Exception */ private function createRepositoryDirectory(string $name) { if (File::exists(app_path("Repositories/$name"))) { throw new Exception("$name repository already exists"); } File::makeDirectory(app_path("Repositories/$name")); } /** * @param string $path * @return string|null * @throws FileNotFoundException */ private function content(string $path): ?string { return File::get(realpath(__DIR__."/../../stubs/{$path}")); } /** * @param string $name * @throws FileNotFoundException * @throws Exception */ private function createInterface(string $name) { $path = "Repositories/{$name}/{$name}Repository.php"; if (File::exists(app_path($path))) { throw new Exception("$path file already exists"); } $content = str_replace("{{name}}", $name, $this->content('interface.stub')); File::put(app_path($path), $content); } /** * @param string $name * @throws FileNotFoundException * @throws Exception */ private function createClass(string $name) { $path = "Repositories/{$name}/Default{$name}Repository.php"; if (File::exists(app_path($path))) { throw new Exception("$path file already exists"); } $content = str_replace("{{name}}", $name, $this->content('repository.stub')); File::put(app_path($path), $content); } }
JavaScript
UTF-8
3,585
2.59375
3
[ "MIT" ]
permissive
/** * overrides methods in Node.prototype and build NodeList.prototype * @author : yiminghe@gmail.com */ KISSY.add("node/override", function(S, DOM, Node) { var NodeList = Node.List, NLP = NodeList.prototype, NP = Node.prototype; // selector S.mix(NP, { /** * Retrieves a node based on the given CSS selector. */ one: function(selector) { return Node.one(selector, this[0]); }, /** * Retrieves a nodeList based on the given CSS selector. */ all: function(selector) { return NodeList.all(selector, this[0]); } }); // 一个函数被多个节点注册 function tagFn(fn, wrap, target) { fn.__wrap = fn.__wrap || []; fn.__wrap.push({ // 函数 fn:wrap, // 关联节点 target:target }); } S.mix(NP, { fire:null, on:function(type, fn, scope) { var self = this,el = self[0]; function wrap(ev) { var args = S.makeArray(arguments); args.shift(); ev.target = new Node(ev.target); if (ev.relatedTarget) { ev.relatedTarget = new Node(ev.relatedTarget); } args.unshift(ev); return fn.apply(scope || self, args); } Event.add(el, type, wrap, scope); tagFn(fn, wrap, el); return self; }, detach:function(type, fn, scope) { var self = this,el = self[0]; if (S.isFunction(fn)) { var wraps = fn.__wrap || []; for (var i = wraps.length - 1; i >= 0; i--) { var w = wraps[i]; if (w.target == el) { Event.remove(el, type, w.fn, scope); wraps.splice(i, 1); } } } else { Event.remove(this[0], type, fn, scope); } return self; // chain } }); S.each(NP, function(v, k) { NodeList.addMethod(k, v); }); S.each([NP,NLP], function(P, isNodeList) { /** * append(node ,parent) : 参数顺序反过来了 * appendTo(parent,node) : 才是正常 * */ S.each(['append', 'prepend'], function(insertType) { // append 和 prepend P[insertType] = function(html) { S.each(this, function(self) { var domNode; /** * 如果是nodelist 并且新加项是已构建的节点,则需要 clone */ if (isNodeList || S.isString(html)) { domNode = DOM.create(html); } else { var nt = html.nodeType; if (nt == 1 || nt == 3) { domNode = html; } else if (html.getDOMNode) { domNode = html[0]; } } DOM[insertType](domNode, self[0]); }); }; }); }); }, { requires:["dom","./base","./attach"] });
Shell
UTF-8
1,531
3.265625
3
[]
no_license
#!/bin/bash # check if root, when not define alias with sudo if [[ $EUID -ne 0 ]]; then alias docker='sudo '$(which docker) alias docker-compose='sudo '$(which docker-compose) fi alias dk='docker' alias dklc='docker ps -l' # List last Docker container alias dklcid='docker ps -l -q' # List last Docker container ID alias dklcip='docker inspect -f "{{.NetworkSettings.IPAddress}}" $(docker ps -l -q)' # Get IP of last Docker container alias dkps='docker ps' # List running Docker containers alias dkpsa='docker ps -a' # List all Docker containers alias dki='docker images' # List Docker images alias dkrmac='docker rm $(docker ps -a -q)' # Delete all Docker containers alias dkrmui='docker images -q -f dangling=true | xargs -r docker rmi' # Delete all untagged Docker images alias dkelc='docker exec -it $(dklcid) bash --login' # Enter last container (works with Docker 1.3 and above) alias dkrmflast='docker rm -f $(dklcid)' alias dkbash='dkelc' alias dkex='docker exec -it ' # Useful to run any commands into container without leaving host alias dkri='docker run --rm -i ' alias dkrit='docker run --rm -it ' alias dkip='docker image prune -a -f' alias dkvp='docker volume prune -f' alias dksp='docker system prune -a -f' # start a container and show log alias dsl='~/dotfiles/bin/docker-start-and-log-f.sh' # https://docs.docker.com/engine/reference/commandline/ps/ alias dps="docker ps --format 'table {{.Names}}\t{{.Image}}' | sort -n" alias dpsa="docker ps -a --format 'table {{.Names}}\t{{.Image}}' | sort -n"
Rust
UTF-8
9,077
2.6875
3
[ "Apache-2.0" ]
permissive
//! Common structures for secure channels. use byteorder::{ByteOrder, LittleEndian}; use sodalite; use ekiden_common::error::{Error, Result}; use ekiden_common::random; use super::api; // Nonce context is used to prevent message reuse in a different context. pub const NONCE_CONTEXT_LEN: usize = 16; type NonceContext = [u8; NONCE_CONTEXT_LEN]; /// Nonce for use in channel initialization context, contract -> client. pub const NONCE_CONTEXT_INIT: NonceContext = *b"EkidenS-----Init"; /// Nonce for use in channel authentication context, client -> contract. pub const NONCE_CONTEXT_AUTHIN: NonceContext = *b"EkidenS---AuthIn"; /// Nonce for use in channel authentication context, client -> contract. pub const NONCE_CONTEXT_AUTHOUT: NonceContext = *b"EkidenS--AuthOut"; /// Nonce for use in request context. pub const NONCE_CONTEXT_REQUEST: NonceContext = *b"EkidenS--Request"; /// Nonce for use in response context. pub const NONCE_CONTEXT_RESPONSE: NonceContext = *b"EkidenS-Response"; /// Nonce generator. pub trait NonceGenerator { /// Reset nonce generator. fn reset(&mut self); /// Generate a new nonce. fn get_nonce(&mut self, context: &NonceContext) -> Result<sodalite::BoxNonce>; /// Unpack nonce from a cryptographic box. fn unpack_nonce( &mut self, crypto_box: &api::CryptoBox, context: &NonceContext, ) -> Result<sodalite::BoxNonce> { let mut nonce = [0u8; sodalite::BOX_NONCE_LEN]; nonce.copy_from_slice(&crypto_box.get_nonce()); // Ensure that the nonce context is correct. if nonce[..NONCE_CONTEXT_LEN] != context[..NONCE_CONTEXT_LEN] { return Err(Error::new("Invalid nonce")); } Ok(nonce) } } /// Random nonce generator. pub struct RandomNonceGenerator {} impl RandomNonceGenerator { /// Create new random nonce generator. pub fn new() -> Self { RandomNonceGenerator {} } } impl NonceGenerator for RandomNonceGenerator { fn reset(&mut self) { // No reset needed. } fn get_nonce(&mut self, context: &NonceContext) -> Result<sodalite::BoxNonce> { let mut nonce: sodalite::BoxNonce = [0; sodalite::BOX_NONCE_LEN]; random::get_random_bytes(&mut nonce)?; nonce[..NONCE_CONTEXT_LEN].copy_from_slice(context); Ok(nonce) } } impl Default for RandomNonceGenerator { fn default() -> RandomNonceGenerator { RandomNonceGenerator::new() } } /// Monotonic nonce generator. pub struct MonotonicNonceGenerator { /// Next nonce to be sent. next_send_nonce: u64, /// Last nonce that was received. last_received_nonce: Option<u64>, } impl MonotonicNonceGenerator { /// Create new monotonic nonce generator. pub fn new() -> Self { MonotonicNonceGenerator { next_send_nonce: 0, // TODO: Random initialization between 0 and 2**48 - 1? last_received_nonce: None, } } } impl NonceGenerator for MonotonicNonceGenerator { /// Reset nonce generator. fn reset(&mut self) { self.next_send_nonce = 0; self.last_received_nonce = None; } fn get_nonce(&mut self, context: &NonceContext) -> Result<sodalite::BoxNonce> { let mut nonce: Vec<u8> = context.to_vec(); nonce.append(&mut vec![0; 8]); LittleEndian::write_u64(&mut nonce[NONCE_CONTEXT_LEN..], self.next_send_nonce); self.next_send_nonce += 1; assert_eq!(nonce.len(), sodalite::BOX_NONCE_LEN); let mut fixed_nonce: sodalite::BoxNonce = [0; sodalite::BOX_NONCE_LEN]; fixed_nonce.copy_from_slice(&nonce); Ok(fixed_nonce) } fn unpack_nonce( &mut self, crypto_box: &api::CryptoBox, context: &NonceContext, ) -> Result<sodalite::BoxNonce> { let mut nonce = [0u8; sodalite::BOX_NONCE_LEN]; nonce.copy_from_slice(&crypto_box.get_nonce()); // Ensure that the nonce context is correct. if nonce[..NONCE_CONTEXT_LEN] != context[..NONCE_CONTEXT_LEN] { return Err(Error::new("Invalid nonce")); } // Decode counter. let counter_value = LittleEndian::read_u64(&nonce[NONCE_CONTEXT_LEN..]); // Ensure that the nonce has increased. match self.last_received_nonce { Some(last_nonce) => { if counter_value <= last_nonce { return Err(Error::new("Invalid nonce")); } } None => {} } self.last_received_nonce = Some(counter_value); Ok(nonce) } } impl Default for MonotonicNonceGenerator { fn default() -> MonotonicNonceGenerator { MonotonicNonceGenerator::new() } } /// Current state of the secure channel session. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum SessionState { /// Session has been closed and must be reset. /// /// After the session is reset, it will transition into `Init`. Closed, /// Session is being initialized. /// /// From this state, the session will transition into `ClientAuthenticating` or `Established`. Init, /// Client is authenticating (client only). /// /// From this state, the session will transition into `Established`. /// The contract does not use this state. The contract is in the `Established` state while the /// client is in this state. The contract tracks client authentication status in /// `ekiden_rpc_trusted::secure_channel::ClientSession::client_mr_enclave`. ClientAuthenticating, /// Secure channel is established. Established, } impl SessionState { /// Transition secure channel to a new state. pub fn transition_to(&mut self, new_state: SessionState) -> Result<()> { match (*self, new_state) { (SessionState::Closed, SessionState::Init) => {} (SessionState::Init, SessionState::Established) => {} (SessionState::Init, SessionState::ClientAuthenticating) => {} (SessionState::ClientAuthenticating, SessionState::Established) => {} (_, SessionState::Closed) => {} transition => { return Err(Error::new(format!( "Invalid secure channel state transition: {:?}", transition ))) } } // Update state if transition is allowed. *self = new_state; Ok(()) } } impl Default for SessionState { fn default() -> Self { SessionState::Closed } } /// Create cryptographic box (encrypted and authenticated). pub fn create_box<NG: NonceGenerator>( payload: &[u8], nonce_context: &NonceContext, nonce_generator: &mut NG, public_key: &sodalite::BoxPublicKey, private_key: &sodalite::BoxSecretKey, shared_key: &mut Option<sodalite::SecretboxKey>, ) -> Result<api::CryptoBox> { let mut crypto_box = api::CryptoBox::new(); let mut key_with_payload = vec![0u8; payload.len() + 32]; let mut encrypted = vec![0u8; payload.len() + 32]; let nonce = nonce_generator.get_nonce(&nonce_context)?; // First 32 bytes is used to store the shared secret key, so we must make // room for it. The box_ method also requires that it is zero-initialized. key_with_payload[32..].copy_from_slice(payload); if shared_key.is_none() { // Compute shared key so we can speed up subsequent box operations. let mut key = shared_key.get_or_insert([0u8; sodalite::SECRETBOX_KEY_LEN]); sodalite::box_beforenm(&mut key, &public_key, &private_key); } match sodalite::box_afternm( &mut encrypted, &key_with_payload, &nonce, &shared_key.unwrap(), ) { Ok(_) => {} _ => return Err(Error::new("Box operation failed")), }; crypto_box.set_nonce(nonce.to_vec()); crypto_box.set_payload(encrypted); Ok(crypto_box) } /// Open cryptographic box. pub fn open_box<NG: NonceGenerator>( crypto_box: &api::CryptoBox, nonce_context: &NonceContext, nonce_generator: &mut NG, public_key: &sodalite::BoxPublicKey, private_key: &sodalite::BoxSecretKey, shared_key: &mut Option<sodalite::SecretboxKey>, ) -> Result<Vec<u8>> { // Reserve space for payload. let mut payload = vec![0u8; crypto_box.get_payload().len()]; if shared_key.is_none() { // Compute shared key so we can speed up subsequent box operations. let mut key = shared_key.get_or_insert([0u8; sodalite::SECRETBOX_KEY_LEN]); sodalite::box_beforenm(&mut key, &public_key, &private_key); } match sodalite::box_open_afternm( &mut payload, &crypto_box.get_payload(), &nonce_generator.unpack_nonce(&crypto_box, &nonce_context)?, &shared_key.unwrap(), ) { Ok(_) => { // Trim first all-zero 32 bytes that were used to allocate space for the shared // secret key. Ok(payload[32..].to_vec()) } _ => Err(Error::new("Failed to open box")), } }
TypeScript
UTF-8
19,592
2.828125
3
[]
no_license
/** * Loads history and gameplay data of all civs. * * @param selectableOnly {boolean} - Only load civs that can be selected * in the gamesetup. Scenario maps might set non-selectable civs. */ function loadCivFiles(selectableOnly) { let propertyNames = [ "Code", "Culture", "Name", "Emblem", "History", "Music", "Factions", "CivBonuses", "TeamBonuses", "Structures", "StartEntities", "Formations", "AINames", "SkirmishReplacements", "SelectableInGameSetup"]; let civData = {}; for (let filename of Engine.ListDirectoryFiles("simulation/data/civs/", "*.json", false)) { let data = Engine.ReadJSONFile(filename); for (let prop of propertyNames) if (data[prop] === undefined) error(filename + " doesn't contain " + prop); if (!selectableOnly || data.SelectableInGameSetup) civData[data.Code] = data; } return civData; } /** * Gets an array of all classes for this identity template */ function GetIdentityClasses(template) { var classList: string[] = []; if (template.Classes && template.Classes._string) classList = classList.concat(template.Classes._string.split(/\s+/)); if (template.VisibleClasses && template.VisibleClasses._string) classList = classList.concat(template.VisibleClasses._string.split(/\s+/)); if (template.Rank) classList = classList.concat(template.Rank); return classList; } /** * Gets an array with all classes for this identity template * that should be shown in the GUI */ function GetVisibleIdentityClasses(template): string[] { if (template.VisibleClasses && template.VisibleClasses._string) return template.VisibleClasses._string.split(/\s+/); return []; } /** * Check if a given list of classes matches another list of classes. * Useful f.e. for checking identity classes. * * @param classes - List of the classes to check against. * @param match - Either a string in the form * "Class1 Class2+Class3" * where spaces are handled as OR and '+'-signs as AND, * and ! is handled as NOT, thus Class1+!Class2 = Class1 AND NOT Class2. * Or a list in the form * [["Class1"], ["Class2", "Class3"]] * where the outer list is combined as OR, and the inner lists are AND-ed. * Or a hybrid format containing a list of strings, where the list is * combined as OR, and the strings are split by space and '+' and AND-ed. * * @return undefined if there are no classes or no match object * true if the the logical combination in the match object matches the classes * false otherwise. */ function MatchesClassList(classes, match) { if (!match || !classes) return undefined; // Transform the string to an array if (typeof match == "string") match = match.split(/\s+/); for (let sublist of match) { // If the elements are still strings, split them by space or by '+' if (typeof sublist == "string") sublist = sublist.split(/[+\s]+/); if (sublist.every(c => (c[0] == "!" && classes.indexOf(c.substr(1)) == -1) || (c[0] != "!" && classes.indexOf(c) != -1))) return true; } return false; } /** * Gets the value originating at the value_path as-is, with no modifiers applied. * * @param {object} template - A valid template as returned from a template loader. * @param {string} value_path - Route to value within the xml template structure. * @return {number} */ function GetBaseTemplateDataValue(template, value_path) { let current_value = template; for (let property of value_path.split("/")) current_value = current_value[property] || 0; return +current_value; } /** * Gets the value originating at the value_path with the modifiers dictated by the mod_key applied. * * @param {object} template - A valid template as returned from a template loader. * @param {string} value_path - Route to value within the xml template structure. * @param {string} mod_key - Tech modification key, if different from value_path. * @param {number} player - Optional player id. * @param {object} modifiers - Value modifiers from auto-researched techs, unit upgrades, * etc. Optional as only used if no player id provided. * @return {number} Modifier altered value. */ function GetModifiedTemplateDataValue(template, value_path, mod_key, player, modifiers = {}) { let current_value = GetBaseTemplateDataValue(template, value_path); mod_key = mod_key || value_path; if (player) current_value = ApplyValueModificationsToTemplate(mod_key, current_value, player, template); else if (modifiers) current_value = GetTechModifiedProperty(modifiers, GetIdentityClasses(template.Identity), mod_key, current_value); // Using .toFixed() to get around spidermonkey's treatment of numbers (3 * 1.1 = 3.3000000000000003 for instance). return +current_value.toFixed(8); } /** * Get information about a template with or without technology modifications. * * NOTICE: The data returned here should have the same structure as * the object returned by GetEntityState and GetExtendedEntityState! * * @param {object} template - A valid template as returned by the template loader. * @param {number} player - An optional player id to get the technology modifications * of properties. * @param {object} auraTemplates - In the form of { key: { "auraName": "", "auraDescription": "" } }. * @param {object} resources - An instance of the Resources prototype. * @param {object} damageTypes - An instance of the DamageTypes prototype. * @param {object} modifiers - Modifications from auto-researched techs, unit upgrades * etc. Optional as only used if there's no player * id provided. */ function GetTemplateDataHelper(template, player, auraTemplates, resources, damageTypes, modifiers = {}) { // Return data either from template (in tech tree) or sim state (ingame). // @param {string} value_path - Route to the value within the template. // @param {string} mod_key - Modification key, if not the same as the value_path. let getEntityValue = function (value_path, mod_key?) { return GetModifiedTemplateDataValue(template, value_path, mod_key, player, modifiers); }; let ret: any = {}; if (template.Armour) { ret.armour = {}; for (let damageType of damageTypes.GetTypes()) ret.armour[damageType] = getEntityValue("Armour/" + damageType); } if (template.Attack) { ret.attack = {}; for (let type in template.Attack) { let getAttackStat = function (stat) { return getEntityValue("Attack/" + type + "/" + stat); }; if (type == "Capture") ret.attack.Capture = { "value": getAttackStat("Value") }; else { ret.attack[type] = { "minRange": getAttackStat("MinRange"), "maxRange": getAttackStat("MaxRange"), "elevationBonus": getAttackStat("ElevationBonus") }; for (let damageType of damageTypes.GetTypes()) ret.attack[type][damageType] = getAttackStat(damageType); ret.attack[type].elevationAdaptedRange = Math.sqrt(ret.attack[type].maxRange * (2 * ret.attack[type].elevationBonus + ret.attack[type].maxRange)); } ret.attack[type].repeatTime = getAttackStat("RepeatTime"); if (template.Attack[type].Splash) { ret.attack[type].splash = { // true if undefined "friendlyFire": template.Attack[type].Splash.FriendlyFire != "false", "shape": template.Attack[type].Splash.Shape }; for (let damageType of damageTypes.GetTypes()) ret.attack[type].splash[damageType] = getAttackStat("Splash/" + damageType); } } } if (template.DeathDamage) { ret.deathDamage = { "friendlyFire": template.DeathDamage.FriendlyFire != "false" }; for (let damageType of damageTypes.GetTypes()) ret.deathDamage[damageType] = getEntityValue("DeathDamage/" + damageType); } if (template.Auras && auraTemplates) { ret.auras = {}; for (let auraID of template.Auras._string.split(/\s+/)) { let aura = auraTemplates[auraID]; ret.auras[auraID] = { "name": aura.auraName, "description": aura.auraDescription || null, "radius": aura.radius || null }; } } if (template.BuildingAI) ret.buildingAI = { "defaultArrowCount": Math.round(getEntityValue("BuildingAI/DefaultArrowCount")), "garrisonArrowMultiplier": getEntityValue("BuildingAI/GarrisonArrowMultiplier"), "maxArrowCount": Math.round(getEntityValue("BuildingAI/MaxArrowCount")) }; if (template.BuildRestrictions) { // required properties ret.buildRestrictions = { "placementType": template.BuildRestrictions.PlacementType, "territory": template.BuildRestrictions.Territory, "category": template.BuildRestrictions.Category, }; // optional properties if (template.BuildRestrictions.Distance) { ret.buildRestrictions.distance = { "fromClass": template.BuildRestrictions.Distance.FromClass, }; if (template.BuildRestrictions.Distance.MinDistance) ret.buildRestrictions.distance.min = getEntityValue("BuildRestrictions/Distance/MinDistance"); if (template.BuildRestrictions.Distance.MaxDistance) ret.buildRestrictions.distance.max = getEntityValue("BuildRestrictions/Distance/MaxDistance"); } } if (template.TrainingRestrictions) ret.trainingRestrictions = { "category": template.TrainingRestrictions.Category, }; if (template.Cost) { ret.cost = {}; for (let resCode in template.Cost.Resources) ret.cost[resCode] = getEntityValue("Cost/Resources/" + resCode); if (template.Cost.Population) ret.cost.population = getEntityValue("Cost/Population"); if (template.Cost.PopulationBonus) ret.cost.populationBonus = getEntityValue("Cost/PopulationBonus"); if (template.Cost.BuildTime) ret.cost.time = getEntityValue("Cost/BuildTime"); } if (template.Footprint) { ret.footprint = { "height": template.Footprint.Height }; if (template.Footprint.Square) ret.footprint.square = { "width": +template.Footprint.Square["@width"], "depth": +template.Footprint.Square["@depth"] }; else if (template.Footprint.Circle) ret.footprint.circle = { "radius": +template.Footprint.Circle["@radius"] }; else warn("GetTemplateDataHelper(): Unrecognized Footprint type"); } if (template.GarrisonHolder) { ret.garrisonHolder = { "buffHeal": getEntityValue("GarrisonHolder/BuffHeal") }; if (template.GarrisonHolder.Max) ret.garrisonHolder.capacity = getEntityValue("GarrisonHolder/Max"); } if (template.Heal) ret.heal = { "hp": getEntityValue("Heal/HP"), "range": getEntityValue("Heal/Range"), "rate": getEntityValue("Heal/Rate") }; if (template.ResourceGatherer) { ret.resourceGatherRates = {}; let baseSpeed = getEntityValue("ResourceGatherer/BaseSpeed"); for (let type in template.ResourceGatherer.Rates) ret.resourceGatherRates[type] = getEntityValue("ResourceGatherer/Rates/" + type) * baseSpeed; } if (template.ResourceTrickle) { ret.resourceTrickle = { "interval": +template.ResourceTrickle.Interval, "rates": {} }; for (let type in template.ResourceTrickle.Rates) ret.resourceTrickle.rates[type] = getEntityValue("ResourceTrickle/Rates/" + type); } if (template.Loot) { ret.loot = {}; for (let type in template.Loot) ret.loot[type] = getEntityValue("Loot/" + type); } if (template.Obstruction) { ret.obstruction = { "active": ("" + template.Obstruction.Active == "true"), "blockMovement": ("" + template.Obstruction.BlockMovement == "true"), "blockPathfinding": ("" + template.Obstruction.BlockPathfinding == "true"), "blockFoundation": ("" + template.Obstruction.BlockFoundation == "true"), "blockConstruction": ("" + template.Obstruction.BlockConstruction == "true"), "disableBlockMovement": ("" + template.Obstruction.DisableBlockMovement == "true"), "disableBlockPathfinding": ("" + template.Obstruction.DisableBlockPathfinding == "true"), "shape": {} }; if (template.Obstruction.Static) { ret.obstruction.shape.type = "static"; ret.obstruction.shape.width = +template.Obstruction.Static["@width"]; ret.obstruction.shape.depth = +template.Obstruction.Static["@depth"]; } else if (template.Obstruction.Unit) { ret.obstruction.shape.type = "unit"; ret.obstruction.shape.radius = +template.Obstruction.Unit["@radius"]; } else ret.obstruction.shape.type = "cluster"; } if (template.Pack) ret.pack = { "state": template.Pack.State, "time": getEntityValue("Pack/Time"), }; if (template.Health) ret.health = Math.round(getEntityValue("Health/Max")); if (template.Identity) { ret.selectionGroupName = template.Identity.SelectionGroupName; ret.name = { "specific": (template.Identity.SpecificName || template.Identity.GenericName), "generic": template.Identity.GenericName }; ret.icon = template.Identity.Icon; ret.tooltip = template.Identity.Tooltip; ret.requiredTechnology = template.Identity.RequiredTechnology; ret.visibleIdentityClasses = GetVisibleIdentityClasses(template.Identity); ret.nativeCiv = template.Identity.Civ; } if (template.UnitMotion) { ret.speed = { "walk": getEntityValue("UnitMotion/WalkSpeed"), }; if (template.UnitMotion.Run) ret.speed.run = getEntityValue("UnitMotion/Run/Speed"); } if (template.Upgrade) { ret.upgrades = []; for (let upgradeName in template.Upgrade) { let upgrade = template.Upgrade[upgradeName]; let cost: any = {}; if (upgrade.Cost) for (let res in upgrade.Cost) cost[res] = getEntityValue("Upgrade/" + upgradeName + "/Cost/" + res, "Upgrade/Cost/" + res); if (upgrade.Time) cost.time = getEntityValue("Upgrade/" + upgradeName + "/Time", "Upgrade/Time"); ret.upgrades.push({ "entity": upgrade.Entity, "tooltip": upgrade.Tooltip, "cost": cost, "icon": upgrade.Icon || undefined, "requiredTechnology": upgrade.RequiredTechnology || undefined }); } } if (template.ProductionQueue) { ret.techCostMultiplier = {}; for (let res in template.ProductionQueue.TechCostMultiplier) ret.techCostMultiplier[res] = getEntityValue("ProductionQueue/TechCostMultiplier/" + res); } if (template.Trader) ret.trader = { "GainMultiplier": getEntityValue("Trader/GainMultiplier") }; if (template.WallSet) { ret.wallSet = { "templates": { "tower": template.WallSet.Templates.Tower, "gate": template.WallSet.Templates.Gate, "fort": template.WallSet.Templates.Fort || "structures/" + template.Identity.Civ + "_fortress", "long": template.WallSet.Templates.WallLong, "medium": template.WallSet.Templates.WallMedium, "short": template.WallSet.Templates.WallShort }, "maxTowerOverlap": +template.WallSet.MaxTowerOverlap, "minTowerOverlap": +template.WallSet.MinTowerOverlap }; if (template.WallSet.Templates.WallEnd) ret.wallSet.templates.end = template.WallSet.Templates.WallEnd; if (template.WallSet.Templates.WallCurves) ret.wallSet.templates.curves = template.WallSet.Templates.WallCurves.split(" "); } if (template.WallPiece) ret.wallPiece = { "length": +template.WallPiece.Length, "angle": +(template.WallPiece.Orientation || 1) * Math.PI, "indent": +(template.WallPiece.Indent || 0), "bend": +(template.WallPiece.Bend || 0) * Math.PI }; return ret; } /** * Get basic information about a technology template. * @param {object} template - A valid template as obtained by loading the tech JSON file. * @param {string} civ - Civilization for which the tech requirements should be calculated. */ function GetTechnologyBasicDataHelper(template, civ) { return { "name": { "generic": template.genericName }, "icon": template.icon ? "technologies/" + template.icon : undefined, "description": template.description, "reqs": DeriveTechnologyRequirements(template, civ), "modifications": template.modifications, "affects": template.affects, "replaces": template.replaces }; } /** * Get information about a technology template. * @param {object} template - A valid template as obtained by loading the tech JSON file. * @param {string} civ - Civilization for which the specific name and tech requirements should be returned. */ function GetTechnologyDataHelper(template, civ, resources) { let ret: any = GetTechnologyBasicDataHelper(template, civ); if (template.specificName) ret.name.specific = template.specificName[civ] || template.specificName.generic; ret.cost = { "time": template.researchTime ? +template.researchTime : 0 }; for (let type of resources.GetCodes()) ret.cost[type] = +(template.cost && template.cost[type] || 0); ret.tooltip = template.tooltip; ret.requirementsTooltip = template.requirementsTooltip || ""; return ret; } function calculateCarriedResources(carriedResources, tradingGoods) { var resources = {}; if (carriedResources) for (let resource of carriedResources) resources[resource.type] = (resources[resource.type] || 0) + resource.amount; if (tradingGoods && tradingGoods.amount) resources[tradingGoods.type] = (resources[tradingGoods.type] || 0) + (tradingGoods.amount.traderGain || 0) + (tradingGoods.amount.market1Gain || 0) + (tradingGoods.amount.market2Gain || 0); return resources; } /** * Remove filter prefix (mirage, corpse, etc) from template name. * * ie. filter|dir/to/template -> dir/to/template */ function removeFiltersFromTemplateName(templateName) { return templateName.split("|").pop(); }
C++
UTF-8
10,058
2.703125
3
[]
no_license
#include <iostream> #include <fstream> #include <ctime> #include <dirent.h> #include <sys/stat.h> using namespace std; ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // global data string author_name; string home_path = "/etc/newacm/com/iCoding"; string company_name; ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // debug function for debuging use void debug() { cout << "--debug msg--" << endl; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // get current time information string get_current_time() { time_t time_current; struct tm* time_info; time(&time_current); time_info = localtime(&time_current); string str_time_current = asctime(time_info); str_time_current[str_time_current.length() - 1] = 32; return str_time_current; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////// // show help msg if command wrong void iShowHelp() { cout << "+--------------------------------------------------------------------+" << endl; cout << "| |" << endl; cout << "| use \"$ newacm [project name]\" to create usaco project! |" << endl; cout << "| |" << endl; cout << "| Thank you for using this program! |" << endl; cout << "| |" << endl; cout << "| |" << endl; cout << "| \t\t\t\t\tCreated by iCoding@CodeLab |" << endl; cout << "+--------------------------------------------------------------------+" << endl; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // show done msg after project have been created void iShowDoneMsg(string pro) { cout << "+--------------------------------------------------------------------+" << endl; cout << "| |" << endl; cout << "| newacm prject \" "<< pro <<" \" Created successfully!! "; for (int i = 0; i <= (24 - pro.length()); i++) { cout << " "; } cout << "|"<< endl; cout << "| |" << endl; cout << "| Thank you for using this program! |" << endl; cout << "| |" << endl; cout << "| |" << endl; cout << "| \t\t\t\t\tCreated by iCoding@CodeLab |" << endl; cout << "+--------------------------------------------------------------------+" << endl; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // show existing msg if there exist such project already void iShowExistMsg(string pro) { cout << "+--------------------------------------------------------------------+" << endl; cout << "| |" << endl; cout << "| newacm project \" " << pro << " \" have existed already!"; for (int i = 0; i <= (25 - pro.length()); i++) { cout << " "; } cout << "|" << endl; cout << "| |" << endl; cout << "| Thank you for using this program! |" << endl; cout << "| |" << endl; cout << "| |" << endl; cout << "| \t\t\t\t\tCreated by iCoding@CodeLab |" << endl; cout << "+--------------------------------------------------------------------+" << endl; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // check folder exist by pro name /* bool CheckFolderExist(string pro) { WIN32_FIND_DATA wfd; bool rValue = false; HANDLE hFind = FindFirstFile(pro.c_str(), &wfd); if((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { rValue = true; } FindClose(hFind); return rValue; } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // get author's name void get_author_name() { string author_ini_path = home_path + "/Author.ini"; ifstream infile(&author_ini_path[0], ios::in); string str_tmp; while (infile >> str_tmp && str_tmp != "Author") {} infile >> str_tmp; if (str_tmp == "=") { infile >> author_name; } else { author_name = "iCoding"; } //cout << author_ini_path << endl; //cout << author_name << endl; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // get company's name void get_company_name() { string company_name_path = home_path + "/Author.ini"; ifstream infile(&company_name_path[0], ios::in); string str_tmp; while (infile >> str_tmp && str_tmp != "lab") {} infile >> str_tmp; if (str_tmp == "=") { infile >> company_name; } else { company_name = "CodeLab"; } cout << company_name_path << endl; cout << company_name << endl; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // wriete msg to source file void write_source_file_msg(string pro) { string infile_path; string oufile_path; // set path value infile_path = home_path + "/main.cpp"; oufile_path = pro + "/main.cpp"; // // // // ifstream infile (&infile_path[0], ios::in); ofstream oufile (&oufile_path[0], ios::app); // // // char ch; while (infile.get(ch)) { // debug(); // cout << ch; if (ch == '~') { char c, o, d, e; infile.get(c); infile.get(o); infile.get(d); infile.get(e); if (c == 'C' && o == 'O' && d == 'D' && e == 'E') { string instruc; infile >> instruc; if (instruc == "<ProjectName>") { // output project name oufile << pro; } else if (instruc == "<FileName>") { // output file name oufile << "main.cpp"; } else if (instruc == "<AuthorName>") { // output author's name get_author_name(); oufile << author_name ; } else if (instruc == "<DateAndTime>") { // output date and time oufile << get_current_time(); } else if (instruc == "<LabName>") { get_company_name(); oufile << company_name; } else { oufile << instruc; } } else { oufile << "~" << c << o << d << e; } } else { oufile << ch; } } // // close files infile.close(); oufile.close(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // create folder for project void create_folder(string pro) { // string cmd = "mkdir " + pro; // system(&cmd[0]); mkdir(&pro[0], -1); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// // write Makefile void write_makefile(string pro) { string infile_path; string oufile_path; // set path value infile_path = home_path + "/Makefile"; oufile_path = pro + "/Makefile"; // // // // ifstream infile (&infile_path[0], ios::in); ofstream oufile (&oufile_path[0], ios::app); // // // char ch; while (infile.get(ch)) { // debug(); // cout << ch; oufile << ch; } // close file infile.close(); oufile.close(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// void create_in_dat_file(string pro) { string infile_path; infile_path = pro + "/in.dat"; ofstream oufile(&infile_path[0], ios::app); oufile.close(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// int main(int args, char** argv) { /////////////////////////////////////////////////////////////////////////////////////////////////////////// // init for program if (args == 1) { iShowHelp(); return 0; } string pro = argv[1]; /////////////////////////////////////////////////////////////////////////////////////////////////////////// // check project existing /* if (CheckFolderExist(pro) == true) { iShowExistMsg(pro); return 0; } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////// // create folder for project create_folder(pro); /////////////////////////////////////////////////////////////////////////////////////////////////////////// // create main.cpp file for project as the main source file and wirte preFileMsg into it write_source_file_msg(pro); /////////////////////////////////////////////////////////////////////////////////////////////////////////// // create Makefile for project and write preFileMsg into Makefile write_makefile(pro); /////////////////////////////////////////////////////////////////////////////////////////////////////////// // create in.dat for project create_in_dat_file(pro); /////////////////////////////////////////////////////////////////////////////////////////////////////////// // show done msg iShowDoneMsg(pro); /////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////// return 0; } // end // iCoding@CodeLab
Java
UTF-8
1,150
1.859375
2
[]
no_license
package com.karengin.libproject.UI; import com.karengin.libproject.UI.component.MainLayout; import com.karengin.libproject.UI.view.AuthorsView; import com.karengin.libproject.UI.view.BooksView; import com.karengin.libproject.UI.view.ErrorView; import com.karengin.libproject.UI.view.UsersView; import com.vaadin.annotations.Theme; import com.vaadin.server.Page; import com.vaadin.server.VaadinRequest; import com.vaadin.spring.access.SecuredViewAccessControl; import com.vaadin.spring.access.ViewAccessControl; import com.vaadin.spring.annotation.SpringUI; import com.vaadin.spring.navigator.SpringNavigator; import com.vaadin.spring.navigator.SpringViewProvider; import com.vaadin.ui.*; import org.springframework.beans.factory.annotation.Autowired; @SpringUI @Theme("valo") public class BooksUI extends UI { @Autowired private SpringNavigator navigator; @Autowired private MainLayout mainLayout; @Override protected void init(VaadinRequest vaadinRequest) { setContent(mainLayout.getUnderlying()); navigator.init(this, mainLayout.getViewContainer()); navigator.navigateTo(BooksView.NAME); } }
Java
UTF-8
5,196
2.09375
2
[]
no_license
package com.campiador.respdroid.model; import com.google.gson.Gson; /** * Created by behnam on 6/11/17. */ public class RespNode { public String getActivity_name() { return activity_name; } public void setActivity_name(String activity_name) { this.activity_name = activity_name; } private String activity_name; private String app_name; private String package_name; private int app_version_code; private String os_version_release_name; private int node_id; private int experiment_id; private long delay; private String timestamp; private String device; private String operation; private String img_base; private long img_perc; private int img_sizeKB; private int imgWidth; private int imgHeight; private float img_MPs; public RespNode(int node_id, int experiment_id, long delay, String timestamp, String device, String operation, String img_base, long img_perc, int img_sizeKB, int imgWidth, int imgHeight, String app_name, String package_name, int app_version_code, String os_version_release_name, String acivity_name) { this.node_id = node_id; this.experiment_id = experiment_id; this.delay = delay; this.timestamp = timestamp; this.device = device; this.operation = operation; this.img_base = img_base; this.img_perc = img_perc; this.img_sizeKB = img_sizeKB; this.imgWidth = imgWidth; this.imgHeight = imgHeight; this.img_MPs = getImgHeight()* getImgHeight() / (float)1000000; this.app_name = app_name; this.package_name = package_name; this.app_version_code = app_version_code; this.os_version_release_name = os_version_release_name; this.activity_name = acivity_name; } public int getNode_id() { return node_id; } public void setNode_id(int node_id) { this.node_id = node_id; } public String getApp_name() { return app_name; } public void setAppName(String app_name) { this.app_name = app_name; } public String getPackage_name() { return package_name; } public void setPackage_name(String package_name) { this.package_name = package_name; } public void setApp_version_code(int app_version_code) { this.app_version_code = app_version_code; } public void setOs_version_release_name(String os_version_release_name) { this.os_version_release_name = os_version_release_name; } public int getApp_version_code() { return app_version_code; } public String getOs_version_release_name() { return os_version_release_name; } public int getExperiment_id() { return experiment_id; } public void setExperiment_id(int experiment_id) { this.experiment_id = experiment_id; } public long getDelay() { return delay; } public void setDelay(long delay) { this.delay = delay; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public String getDevice() { return device; } public void setDevice(String device) { this.device = device; } public String getOperation() { return operation; } public void setOperation(String operation) { this.operation = operation; } public String getImg_base() { return img_base; } public void setImg_base(String img_base) { this.img_base = img_base; } public long getImg_perc() { return img_perc; } public void setImg_perc(int img_perc) { this.img_perc = img_perc; } public int getImg_sizeKB() { return img_sizeKB; } public void setImg_sizeKB(int img_sizeKB) { this.img_sizeKB = img_sizeKB; } public int getImgWidth() { return imgWidth; } public void setImgWidth(int imgWidth) { this.imgWidth = imgWidth; } public int getImgHeight() { return imgHeight; } public void setImgHeight(int imgHeight) { this.imgHeight = imgHeight; } public String toString() { return "nid: " + node_id + ", xid: " + experiment_id + ", datetime: " + timestamp + ", device: " + device + ", delay: " + delay + ", operation: " + operation + ", imgbase: " + img_base + ", imgperc: " + img_perc + ", sizeKB: " + img_sizeKB + ", Resolution: " + getImageResolution() + ", MPs: " + img_MPs + ", appname:" + app_name + ", package_name:" + package_name + ", app_version_code:" + app_version_code + ", os_version_release_name:" + os_version_release_name + ", activity_name:" + activity_name; } private String getImageResolution() { return getImgWidth() + "x" + getImgHeight(); } public String serialize_to_Json(){ Gson gson = new Gson(); String json = gson.toJson(this); return json; } }
PHP
UTF-8
2,559
2.796875
3
[]
no_license
<?php namespace TimeControlManager\Entities; use TimeControlManager\Exceptions\UnprocessableEntityException; class UserGroup extends BaseEntity { /** * Группы пользователей (типы конфигураций) */ const TABLE_NAME = 'users_groups'; /** * Комментарий к группе * * @var string */ protected $comment; /** * Текстовый код * * @var string */ protected $code; /** * 1 - по умолчанию при добавлении * * @var int */ protected $isDefault; /** * @var array */ protected $map = [ 'UGID' => 'id', 'UGNAME' => 'name', 'GRCOMMENT' => 'comment', 'CODE' => 'code', 'ISDEF' => 'isDefault' ]; protected $_generators = [ 'id' => 'USERS_GROUPS_GEN' ]; /** * @param string $name * @return UserGroup * @throws UnprocessableEntityException */ public function setName(string $name): UserGroup { if (mb_strlen($name) > 100) { throw new UnprocessableEntityException('Name too long'); } $this->name = $name; return $this; } /** * @return string */ public function getComment(): string { return $this->comment; } /** * @param string $comment * @return UserGroup * @throws UnprocessableEntityException */ public function setComment(string $comment): UserGroup { if (mb_strlen($comment) > 1024) { throw new UnprocessableEntityException('Comment too long'); } $this->comment = $comment; return $this; } /** * @return string */ public function getCode(): string { return $this->code; } /** * @param string $code * @return UserGroup * @throws UnprocessableEntityException */ public function setCode(string $code): UserGroup { if (mb_strlen($code) > 8) { throw new UnprocessableEntityException('Code too long'); } $this->code = $code; return $this; } /** * @return bool */ public function getIsDefault(): bool { return $this->isDefault ? true : false; } /** * @param bool $isDefault * @return UserGroup */ public function setIsDefault(bool $isDefault): UserGroup { $this->isDefault = $isDefault; return $this; } }
PHP
UTF-8
2,267
3.1875
3
[]
no_license
<?php namespace landingSILEX\DAO; use Doctrine\DBAL\Connection; use landingSILEX\Custom\Ville; class VilleDAO { /** * Database connection * * @var \Doctrine\DBAL\Connection */ private $db; /** * Constructor * * @param \Doctrine\DBAL\Connection The database connection object */ public function __construct(Connection $db) { $this->db = $db; } /** * Return a list of all pays, sorted by date (most recent first). * * @return array A list of all pays. */ public function findAll() { $sql = "SELECT * FROM ville"; $result = $this->db->fetchAll($sql); // Convert query result to an array of domain objects $ville = array(); foreach ($result as $row) { $villeID = $row['id']; $ville[$villeID] = $this->buildVille($row); } return $ville; } /** * Return a list of the five pays, sorted by date (most recent first). * * @return array A list of five pays. */ public function findFiveCountries() { $sql = "SELECT * FROM ville WHERE `nomPaysNumbeo` = 'Canada' OR `nomPaysNumbeo` = 'Indonesia' OR `nomPaysNumbeo` = 'Morocco' OR `nomPaysNumbeo` = 'Thailand' OR `nomPaysNumbeo` = 'Portugal' OR `nomPaysNumbeo` = 'Spain'"; $result = $this->db->fetchAll($sql); //return $result; // Convert query result to an array of custom objects $fiveCountries = array(); foreach ($result as $row) { $fiveCountriesID = $row['id']; $fiveCountries[$fiveCountriesID] = $this->buildVille($row); } return $fiveCountries; } /** * Creates an pays object based on a DB row. * * @param array $row The DB row containing pays data. * @return \landingSILEX\Custom\Ville */ private function buildVille(array $row) { $ville = new Ville(); $ville->setId($row['id']); $ville->setlongitude($row['longitude']); $ville->setlatitude($row['latitude']); $ville->setidNumbeo($row['idNumbeo']); $ville->setnomNumbeo($row['nomNumbeo']); $ville->setnomPaysNumbeo($row['nomPaysNumbeo']); return $ville; } }
Python
UTF-8
2,995
3.1875
3
[]
no_license
import time from rooms import directory home = 'reading_room' # home = 'chiefs_office' directory[home].check_banana = True class Player(object): def __init__(self, inventory=None): self.alive = True self.location = home self.shape = 'human' self.size = 'medium' self.flying = False self.known_spells = ['human'] self.spell_counter = 0 if inventory == None: self.inventory = [] else: self.inventory = inventory self.shelved_books = [] self.level = 1 def level_up(self): self.level += 1 #increases self.spell_counter so I can give a warning on how to change back: def first_spell(self): self.spell_counter += 1 return ''''You've used your first spell! To change back to human, just type "cast human".''' #for checking inventory from other modules: def invent_test(self, item): return item in self.inventory #for testing location from other modules: def location_test(self, location): return location == self.location def inventory_check(self): if self.inventory == []: check_result = "You're not holding anything!" else: check_result = {'header': "You're holding:", 'text': []} for thing in self.inventory: check_result['text'] += [thing] return check_result def take(self, item): self.inventory.append(item) def drop(self, item): self.inventory.remove(item) def shelve_book(self, book): self.drop(book) self.shelved_books.append(book) def spell_check(self): if self.known_spells == ['human']: spells_inventory = "You don't know any spells." else: spells_inventory = {'header': "You know these spells:", 'text': []} for spell in self.known_spells: if spell != 'human': spells_inventory['text'] += [spell] return spells_inventory def add_spell(self, spell): self.known_spells.append(spell) def move(self, direction): current_location_object = directory[self.location] next_location_object = directory[current_location_object.directions[direction]] if next_location_object.locked: if self.alive == False: self.location = next_location_object.short_name return directory[self.location].describe() else: return next_location_object.locked_description else: self.location = next_location_object.short_name return directory[self.location].describe() def teleport(self): if 'labyrinth' in self.location: self.location = 'labyrinth1' return directory[self.location].describe() else: self.location = home return directory[self.location].describe() player = Player()
Markdown
UTF-8
1,888
2.578125
3
[]
no_license
# sFlow-Monitoring-Tool ## Introduction This tool utilizes the sFlow packet sampling technology to determine the Top Talkers in the network. To decode sFlow data the tool utilizes a Python library called `python-sflow` (https://github.com/auspex-labs/sflow-collector/blob/develop/sflow.py). The errors are calculated using the formulas provided by sFlow at https://sflow.org/packetSamplingBasics/. --- ## Requirements * [sFlow](https://sflow.net/downloads.php) --- ## Run In order to start analizing packets it is necessary to configure sFlow by adding a collector in the config file, under the section "collectors". At this point the only thing left to do to start the tool is executing the following command: python3 main.py The program accepts the following arguments, and if they are not specified the default value is used: * -p sFlow collector port (default=6343) * -a sFlow collector ip (default=127.0.0.1) * -m Max number of talkers to display (default=0, unlimited) * -h Help function It is also possible to interact with the tool by pressing the following keys while it's running: * r Reload the informations * s Switch sorting method * q Exit the tool --- ## Test ### Testing environment * sFlow installed on local machine reporting on loopback * MSTeams conference open * Downloading 1GB file from https://speed.hetzner.de/ (IP 88.198.248.254) ### Testing procedure * Started our tool and [Wireshark](https://www.wireshark.org/) at the same time * Downloaded the 1GB test file * Compared the result from our tool with the Endpoints analyzer in Wireshark ### Results ![tool](images/tool.jpeg) ![wireshark](images/wireshark.png) As we can see the results from Wireshark roughly matches ours. The discrepancies in the data and the fact that our tool recorded less IPs than wireshark are a result of the core functioning model of sFlow.
Python
UTF-8
3,825
2.59375
3
[ "MIT" ]
permissive
import argparse import functools import gc import random import time from redis import Redis from reliableredisqueue import Queue random.seed(73) _NUM_JOBS = 10000 _NUM_ROUNDS = 3 def benchmark(func): @functools.wraps(func) def wrapper(queue, num_jobs, **kwargs): gc.disable() timings = [] try: for _ in range(_NUM_ROUNDS): timings.append(func(queue, num_jobs, **kwargs)) finally: gc.enable() queue.purge() return min(timings) return wrapper @benchmark def benchmark_consumer(queue, num_jobs, unacked_prob=0.0): for index in range(num_jobs): queue.put(index) rand = random.random t0 = time.time() for _ in range(num_jobs): job = queue.get(block=False) if not unacked_prob or rand() > unacked_prob: queue.ack(job) t1 = time.time() queue.purge() return t1 - t0 @benchmark def benchmark_producer(queue, num_jobs): t0 = time.time() for index in range(num_jobs): queue.put(index) t1 = time.time() queue.purge() return t1 - t0 class SimpleQueue: def __init__(self, redis): self.redis = redis self._ready = "rrq:baseline:ready" self._unacked = "rrq:baseline:unacked" def put(self, item): self.redis.lpush(self._ready, item) def get(self, block=False): assert not block, "baseline does not support blocking" return self.redis.rpoplpush(self._ready, self._unacked) def ack(self, item): self.redis.lrem(self._unacked, 1, item) def purge(self): with self.redis.pipeline() as pipe: pipe.delete(self._ready) pipe.delete(self._unacked) pipe.execute() def cli(): parser = argparse.ArgumentParser() parser.add_argument( "--redis", dest="redis_url", metavar="URL", default="redis://localhost:6379", help="URL to Redis") parser.add_argument("--baseline", action="store_true") parser.add_argument( "--retry-time", metavar="FLOAT", type=float, default=60.0, help="number of seconds after which unacked jobs will be retried") parser.add_argument( "--jobs", dest="num_jobs", metavar="INT", type=int, default=_NUM_JOBS, help="number of jobs to enqueue/dequeue") subparsers = parser.add_subparsers() _add_consumer_command(subparsers) _add_producer_command(subparsers) args = parser.parse_args() args.func(args) def _add_consumer_command(subparsers): parser = subparsers.add_parser("consumer") parser.add_argument( "--unacked-prob", metavar="FLOAT", type=float, default=0.0, help="probability of not acking a job") parser.set_defaults(func=_run_consumer_benchmark) def _add_producer_command(subparsers): parser = subparsers.add_parser("producer") parser.set_defaults(func=_run_producer_benchmark) def _run_consumer_benchmark(args): queue = _make_queue(args) _run_benchmark( benchmark_consumer, queue, args.num_jobs, kwargs={"unacked_prob": args.unacked_prob}) def _run_producer_benchmark(args): queue = _make_queue(args) _run_benchmark(benchmark_producer, queue, args.num_jobs) def _make_queue(args): redis = Redis.from_url(args.redis_url) if args.baseline: return SimpleQueue(redis) return Queue(redis, "__bench", retry_time=args.retry_time, serializer=None) def _run_benchmark(func, queue, num_jobs, kwargs=None): elapsed_time = func(queue, num_jobs, **(kwargs or {})) jobs_per_sec = round(num_jobs / elapsed_time, 3) print(f"{jobs_per_sec} jobs/s") if __name__ == "__main__": cli()
JavaScript
UTF-8
2,326
2.640625
3
[]
no_license
/* global describe beforeEach it */ const { expect } = require("chai"); const request = require("supertest"); const db = require("../../db"); const app = require("../../index"); const Order = db.model("order"); // const User = db.model("user"); //let's set up the data we need to pass to the login method describe("Order routes", () => { beforeEach(() => { return db.sync({ force: true }) }) beforeEach(() => { return const userCredentials = { email: 'bob@heyann.com', password: 'plant', isADmin: "TRUE" } }) beforeEach(() => { var authenticatedUser = request.agent(app); return authenticatedUser .post('/login') .send(userCredentials) .end(function(err, response){ expect(response.statusCode).to.equal(200); // expect('Location', '/home'); done(); }) }) describe('GET /api/orders', function(done){ //addresses 1st bullet point: if the user is logged in we should get a 200 status code it('should return a 200 response if the user is logged in', function(done){ authenticatedUser.get('api/orders') .expect(200, done); }); //addresses 2nd bullet point: if the user is not logged in we should get a 302 response code and be directed to the /login page it('should return a 302 response and redirect to /login', function(done){ request(app).get('api/account') .expect('Location', '/login') .expect(302, done); }); }); describe("/api/orders/", () => { const testOrder = { id: 67, orderStatus: "Completed", orderTotal: 234, orderEmail: "me@me.com", orderAddress: "123 streeet st." }; beforeEach(() => { return Order.create(testOrder); }); it("GET /api/orders", () => { return request(app) .get("/api/orders") .expect(200) .then(res => { expect(res.body).to.be.an("array"); expect(res.body[0].id).to.be.equal(67); }); }); it("GET /api/orders/67", () => { return request(app) .get("/api/orders/67") .expect(200) .then(res => { expect(res.body).to.be.an("object"); expect(res.body.userId).to.be.equal(3); }); }); }); }); });
Python
UTF-8
2,086
2.890625
3
[]
no_license
from flask import Flask, render_template, request, send_file, Response from PIL import Image import StringIO import imageio app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def home(): pictures = request.files.getlist('photos') feature = request.form.get('feature') contents = [] if feature == 'filter': for picture in pictures: contents.append(filter(picture)) elif feature == 'collage': contents.append(collage(pictures)) # else: # return movie(pictures) return render_template('pic.html', srcs=contents) @app.route('/a.gif') def f(): gif = open('movie.gif','r') return Response(gif.read(), mimetype='image/gif') def filter(picture): ''' convert colored picture into a pure black and white image mode='1': Black and white (monochrome), one bit per pixel. mode='L': Gray scale, one 8-bit byte per pixel. ''' image_file = Image.open(picture) image_file = image_file.convert(mode='1') output = StringIO.StringIO() image_file.save(output, format='PNG') contents = output.getvalue().encode("base64") output.close() return contents def collage(pictures): ''' Given several images, return one collage ''' ims = [] width = height = 0 thumbnail_heights = [] for picture in pictures: im = Image.open(picture) w, h = im.size thumbnail_heights.append(h) width = max(width, w) height += h ims.append(im) new_im = Image.new('RGB', (width, height)) y = 0 for i, height in enumerate(thumbnail_heights): new_im.paste(ims[i], (0, y)) # (0, y) is the top left coordinate of each image y += height output = StringIO.StringIO() new_im.save(output, format='PNG') contents = output.getvalue().encode("base64") output.close() return contents def movie(pictures): ''' Given several images, possibly different sizes, return one gif ''' with imageio.get_writer('movie.gif', mode='I', duration=0.3, loop=2) as writer: for picture in pictures: image = imageio.imread(picture) writer.append_data(image) gif = open('movie.gif','r') return gif.read() if __name__ == '__main__': app.run(debug=True)
Ruby
UTF-8
191
3.640625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def fizzbuzz(num) output=nil if (((num%3)==0)&&((num%5)==0)) output="FizzBuzz" elsif ((num%3)==0) output="Fizz" elsif ((num%5)==0) output="Buzz" end return output end
TypeScript
UTF-8
675
2.6875
3
[]
no_license
export interface IBill { b_id: number; o_id: number; u_id: number; ammount: number; due_ammount: number; // TODO : Find the correct type. issue_timestamp: Date isdeleted: boolean; // Application audit columns c_date?: Date; u_date?: Date; } export interface ICreateBill { o_id: number; u_id: number; ammount: number; due_ammount: number; issue_timestamp: Date } export interface IUpdateBill { b_id: number; u_id: number; o_id: number; ammount?: number; due_ammount?: number; } export function isBill(bill: IBill | any): bill is IBill { return (bill as IBill).ammount !== undefined; }
TypeScript
UTF-8
1,531
2.84375
3
[]
no_license
import { GeneAdapter } from '../genetic' import Network from './Network' import Buffer from '../helpers/Buffer' export class NetworkBinaryGeneAdapter extends GeneAdapter<Network> { public get(individual: Network): Buffer { let bytes = 0 for (const layer of individual.layers) { for (const { weights } of layer.getNeurons()) { if (weights) { bytes += weights.length * 2 * 4 // weights & biases } } } const gene = Buffer.alloc(bytes) let cursor = 0 for (const layer of individual.layers) { for (const { weights, biases } of layer.getNeurons()) { if (weights) { for (const weight of weights) { gene.writeFloatLE(weight, cursor) cursor += 4 } for (const bias of biases!) { gene.writeFloatLE(bias, cursor) cursor += 4 } } } } return gene } public create(gene: Buffer, [ parent ]: Network[]): Network { const child = parent.clone() const { layers } = child let cursor = 0 for (const layer of layers) { for (const { weights, biases } of layer.getNeurons()) { if (weights) { weights.forEach((_, i) => { weights[i] = gene.readFloatLE(cursor) cursor += 4 }) biases!.forEach((_, i) => { biases![i] = gene.readFloatLE(cursor) cursor += 4 }) } } } return child } } export default NetworkBinaryGeneAdapter
Java
UTF-8
994
2.65625
3
[]
no_license
package com.javaclimb.music.dao; import com.javaclimb.music.domain.Singer; import org.springframework.stereotype.Repository; import java.util.List; @Repository /** * @Repository注解便属于最先引入的一批,它用于将数据访问层 (DAO 层 ) 的类 * 标识为 Spring Bean。具体只需将该注解标注在 DAO类上即可。同时, * 为了让 Spring 能够扫描类路径中的类并识别出 @Repository 注解, * 需要在 XML 配置文件中启用Bean 的自动扫描功能, */ public interface SingerMapper { public int insert (Singer singer); public int update(Singer singer); public int delete (Integer id); /* 根据id主键查询整个对象*/ public Singer selectByPrimaryKey(Integer id); /*查询所有歌手*/ public List<Singer> allSinger (); /*根据歌手名模糊查询列表*/ public List<Singer> singerOfName(String name); /*根据男女查询*/ public List<Singer> singerOfSix(Integer sex); }
C++
ISO-8859-1
496
3.65625
4
[]
no_license
/* Criar uma funo para somar dois nmeros e retornar o resultado da soma. A assinatura da funo : int somar(int a, int b) Criar um main para fazer a chamada a esta funo */ #include <stdio.h> #include <stdlib.h> int somar(int a,int b); int main() { int a,b; printf("Informar numero A: "); scanf("%d",&a); printf("Informar numero B: "); scanf("%d",&b); printf("Resultado da soma: %d \n",somar(a,b)); system("pause>nul"); } int somar(int a, int b) { return (a+b); }
Shell
UTF-8
184
2.515625
3
[]
no_license
#!/bin/bash while true; do humidity=$(wget http://192.168.1.105/humidity -q -O -) #echo $humidity influx -database=loggers -execute "INSERT humidity value=$humidity" sleep 10 done
JavaScript
UTF-8
731
3.328125
3
[]
no_license
var itemNum = 1; function createNewItemLabel(num) { var element = document.createElement("div"); element.innerHTML = "Item #" + num + ":"; return element; } function createNewItem(num) { var element = document.createElement("input"); element.setAttribute("type","text"); element.required = true; element.setAttribute("name", "items[]"); return element; } function addItemGroup() { var elementLabel = createNewItemLabel(itemNum); var elementInput = createNewItem(itemNum); $("#add-item-button").before(elementLabel); $("#add-item-button").before(elementInput); $("#add-item-button").before("<br>"); itemNum++; } addItemGroup(); document.getElementById("add-item-button").setAttribute("onclick", "addItemGroup()");
Shell
UTF-8
2,682
3.765625
4
[ "BSD-2-Clause" ]
permissive
#!/usr/bin/env bash # Useful script that we run @reboot # Author: Daniel Zhelev @ https://zhelev.biz ################################ Begin config EMAIL="root" DELAY="480" POST_BOOT_LOG="/var/log/postboot.log" ERROR_PATTERN="crit|error|warn|fail|unable" IGNORE_PATTERN="PNP0A03" ################################ End config ################################ Begin script vars LINES="============================================================================================================" EXIT=0 # Set secure umask umask 077 ################################ End script vars ################################ report_state() { echo $LINES echo "Current state of system $(hostname -f):" echo $LINES monit status $(hostname -f) | grep -v "Monit" echo echo $LINES echo } check_services() { echo $LINES echo "Current state of all services running on system $(hostname -f):" echo $LINES echo monit report echo SERVICES_DOWN=$(monit report down) if [[ $SERVICES_DOWN -ne 0 ]] then echo echo "Services currently DOWN: $SERVICES_DOWN" echo monit summary -B | egrep -v "Monit|OK" echo let "EXIT++" fi SERVICES_UNMONITORED=$(monit report unmonitored) if [[ $SERVICES_UNMONITORED -ne 0 ]] then echo echo "Services currently UNMONITORED: $SERVICES_UNMONITORED" echo monit summary -B | egrep -v "Monit|OK" echo let "EXIT++" fi echo $LINES echo } check_logs() { echo $LINES echo "Searching common logs for errors:" echo $LINES echo echo "SEARCH PATTERN: $ERROR_PATTERN" echo "IGNORE PATTERN: $IGNORE_PATTERN" echo LOG_FILES_LIST=$(find /var/log \( -name "messages*" -o -name "syslog*" -o -name "boot*" -o -name "dmesg*" \) -type f -mtime -1) if [[ -z $LOG_FILES_LIST ]] then echo "No recent logs found" echo let "EXIT++" return 1 fi echo echo "Searching in:" echo "$LOG_FILES_LIST" echo OUTPUT=$(egrep -i $ERROR_PATTERN $LOG_FILES_LIST | egrep -v $IGNORE_PATTERN) if [[ ! -z $OUTPUT ]] then echo echo "$OUTPUT" echo let "EXIT++" else echo echo "All good, no logs matched our pattern." echo fi echo $LINES echo } check_users_prior_reboot() { echo $LINES echo "Users logged in prior the reboot:" echo $LINES echo REBOOT_DATE=$(last | grep reboot | head -1 | awk '{print $6, $7}') last | grep "$REBOOT_DATE" | grep -A 100 "reboot" echo echo $LINES echo } main() { report_state check_services check_logs check_users_prior_reboot } sleep $DELAY main > $POST_BOOT_LOG if [[ $EXIT -ne 0 ]] then SUBJECT="[ERROR] System $(hostname -f) rebooted and $(basename $0) detected problems" else SUBJECT="[INFO] System $(hostname -f) rebooted, system is operating normally now." fi cat $POST_BOOT_LOG | mail -s "$SUBJECT" $EMAIL exit $EXIT
Java
UTF-8
2,758
2.21875
2
[]
no_license
package com.lyh.guanbei.ui.activity; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.lyh.guanbei.R; import com.lyh.guanbei.base.BaseActivity; import com.lyh.guanbei.bean.User; import com.lyh.guanbei.manager.CustomSharedPreferencesManager; import com.lyh.guanbei.manager.DBManager; import com.lyh.guanbei.mvp.contract.UpdateUserContract; import com.lyh.guanbei.mvp.presenter.UpdateUserPresenter; public class UserNameEditActivity extends BaseActivity implements View.OnClickListener,UpdateUserContract.IUpdateUserView { private TextView mSave; private EditText mName; private User mUser; private UpdateUserPresenter mUpdateUserPresenter; @Override protected int getLayoutId() { return R.layout.activity_user_name_edit; } @Override protected void initUi() { mSave=findViewById(R.id.activity_user_name_save); mName=findViewById(R.id.activity_user_name_name); mName.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mSave.setEnabled(true); } @Override public void afterTextChanged(Editable s) { } }); findViewById(R.id.activity_user_name_back).setOnClickListener(this); findViewById(R.id.activity_user_name_save).setOnClickListener(this); } @Override protected void init() { mUser= CustomSharedPreferencesManager.getInstance().getUser(); mName.setText(mUser.getUser_name()); } @Override public void onUpdateFailed(String msg) { Toast.makeText(this,msg,Toast.LENGTH_SHORT).show(); finish(); } @Override public void onUpdateSuccess(User user) { CustomSharedPreferencesManager.getInstance().saveUser(user); DBManager.getInstance().getDaoSession().getUserDao().update(user); finish(); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.activity_user_name_back: finish(); break; case R.id.activity_user_name_save: mUser.setUser_name(mName.getText().toString()); mUpdateUserPresenter.updateOther(mUser); break; } } @Override public void createPresenters() { mUpdateUserPresenter=new UpdateUserPresenter(); addPresenter(mUpdateUserPresenter); } }
PHP
ISO-8859-1
89,030
2.609375
3
[]
no_license
<? if(!class_exists('bancos')) require 'bancos.php';//CASO EXISTA EU DESVIO A CLASSE ... //Fico indignado com a minha tcnica em orientao a objetos, sem palavras class intermodular { function importar_patopi($id_produto_acabado) { //Aqui eu verifico se o PA j foi importado alguma vez p/ PI ... $sql = "SELECT `id_produto_insumo` FROM `produtos_acabados` WHERE `id_produto_acabado` = '$id_produto_acabado' AND `id_produto_insumo` > '0' AND `ativo` = '1' LIMIT 1 "; $campos = bancos::sql($sql); if(count($campos) == 0) {//Nunca foi importado ... $sql = "SELECT `id_unidade`, `referencia`, `discriminacao`, `observacao` FROM `produtos_acabados` WHERE `id_produto_acabado` = '$id_produto_acabado' LIMIT 1 "; $campos_pa = bancos::sql($sql); $id_unidade = $campos_pa[0]['id_unidade']; $discriminacao = AddSlashes($campos_pa[0]['discriminacao']); $observacao = AddSlashes($campos_pa[0]['observacao']); $data_sys = date('Y-m-d H:i:s'); //Gera um novo PI atravs do PA ... $sql = "INSERT INTO `produtos_insumos` (`id_produto_insumo`, `id_unidade`, `estocagem`, `discriminacao`, `id_grupo`, `data_sys`, `observacao`, `ativo`) VALUES (NULL, '$id_unidade', 'S', '$discriminacao', '9', '$data_sys', '$observacao', 1) "; bancos::sql($sql); $id_produto_insumo = bancos::id_registro(); //Atualizo a Tabela de Produtos Acabados com o 'id_produto_insumo' equivalente "PIPA" ... $sql = "UPDATE `produtos_acabados` SET `id_produto_insumo` = '$id_produto_insumo' WHERE `id_produto_acabado` = '$id_produto_acabado' LIMIT 1 "; bancos::sql($sql); } return $id_produto_insumo; } function incluir_varios_pi_fornecedor($id_fornecedor, $id_produto_insumo) { $sql = "SELECT `id_fornecedor_prod_insumo`, `ativo` FROM `fornecedores_x_prod_insumos` WHERE `id_fornecedor` = '$id_fornecedor' AND `id_produto_insumo` = '$id_produto_insumo' AND `ativo` = '1' LIMIT 1 "; $campos = bancos::sql($sql); $linhas = count($campos); if($linhas == 1) $id_fornecedor_prod_insumo = $campos[0]['id_fornecedor_prod_insumo']; if($linhas == 0) {//Aqui eu atrelo o $id_fornecedor passado ao $id_produto_insumo por parmetro na Lista de Preo com a Data Atual ... $sql = "INSERT INTO `fornecedores_x_prod_insumos` (`id_fornecedor_prod_insumo`, `id_produto_insumo`, `id_fornecedor`, `fator_margem_lucro_pa`, `data_sys`) VALUES (NULL, '$id_produto_insumo', '$id_fornecedor', '".genericas::variavel(22)."', '".date('Y-m-d H:i:s')."') "; bancos::sql($sql); $id_fornecedor_prod_insumo = bancos::id_registro(); return $id_fornecedor_prod_insumo; }else { $ativo = $campos[0]['ativo']; if($ativo == 0) {//J exista como inativo, e voltou a reativar esse item com a Data Atual ... $sql = "UPDATE `fornecedores_x_prod_insumos` SET `data_sys` = '".date('Y-m-d H:i:s')."', `ativo` = '1' WHERE `id_fornecedor_prod_insumo` = '$id_fornecedor_prod_insumo' LIMIT 1 "; bancos::sql($sql); return $id_fornecedor_prod_insumo; }else {//J existe o produto return 0; } } } function excluir_varios_pi_fornecedor($id_fornecedor_prod_insumo) { //Alm de eu desatrelar o Fornecedor do PI, eu tambm j zero os preos deste Fornec na lista de Preo ... $sql = "UPDATE `fornecedores_x_prod_insumos` SET `preco_faturado` = '0.00', `preco_faturado_export` = '0.00', `ativo` = 0 where id_fornecedor_prod_insumo = '$id_fornecedor_prod_insumo' LIMIT 1 "; bancos::sql($sql); } function pa_discriminacao($id_produto_acabado=0, $mostrar=1, $mostrar_status=1, $mostra_status_nao_produzir=1, $id_produto_acabado_discriminacao=0, $pdf=0) { /********************************Busca de Dados do P.A. Principal********************************/ $sql = "SELECT pa.`operacao_custo`, pa.`codigo_fornecedor`, pa.`referencia`, pa.`discriminacao`, pa.`status_custo`, pa.`status_nao_produzir`, pa.`ativo`, u.`sigla` FROM `produtos_acabados` pa INNER JOIN `unidades` u ON u.`id_unidade` = pa.`id_unidade` WHERE pa.`id_produto_acabado` = '$id_produto_acabado' LIMIT 1 "; $campos = bancos::sql($sql); //Dados Referente ao Produto Acabado Principal ... $operacao_custo = $campos[0]['operacao_custo']; $codigo_fornecedor = $campos[0]['codigo_fornecedor']; $referencia = $campos[0]['referencia']; $discriminacao = $campos[0]['discriminacao']; $discriminacao = str_replace('% ', '%', $discriminacao);//Aqui eu retiro o espao q est entre a % e a Sigla de Co $status_custo = $campos[0]['status_custo']; $status_nao_produzir = $campos[0]['status_nao_produzir']; $unidade = $campos[0]['sigla']; $ativo = $campos[0]['ativo']; /******************************Busca de Dados do Custo do P.A. Principal*****************************/ $sql = "SELECT REPLACE(f.`nome`, ' ', '_') AS funcionario_alterou_custo, REPLACE(CONCAT(DATE_FORMAT(SUBSTRING(pac.`data_sys`, 1, 10), '%d/%m/%Y'), ' s', SUBSTRING(pac.`data_sys`, 11, 9)), ' ', '_') AS data_atualizacao FROM `produtos_acabados_custos` pac LEFT JOIN `funcionarios` f ON f.`id_funcionario` = pac.`id_funcionario` WHERE pac.`id_produto_acabado` = '$id_produto_acabado' AND pac.`operacao_custo` = '$operacao_custo' LIMIT 1 "; $campos_custo = bancos::sql($sql); $funcionario_alterou_custo1 = $campos_custo[0]['funcionario_alterou_custo']; $data_atualiazacao1 = $campos_custo[0]['data_atualizacao']; /********************************Busca de Dados do P.A. Discriminao********************************/ $sql = "SELECT pa.`operacao_custo`, pa.`codigo_fornecedor`, pa.`referencia`, pa.`discriminacao`, pa.`status_custo`, pa.`status_nao_produzir`, pa.`ativo`, u.`sigla` FROM `produtos_acabados` pa INNER JOIN `unidades` u ON u.`id_unidade` = pa.`id_unidade` WHERE pa.`id_produto_acabado` = '$id_produto_acabado_discriminacao' LIMIT 1 "; $campos = bancos::sql($sql); //Dados Referente ao Produto Acabado Discriminao ... $operacao_custo2 = $campos[0]['operacao_custo']; $codigo_fornecedor2 = $campos[0]['codigo_fornecedor']; $referencia2 = $campos[0]['referencia']; $discriminacao2 = $campos[0]['discriminacao']; $discriminacao2 = str_replace('% ', '%', $discriminacao2);//Aqui eu retiro o espao q est entre a % e a Sigla de Co $status_custo2 = $campos[0]['status_custo']; $status_nao_produzir2 = $campos[0]['status_nao_produzir']; $unidade2 = $campos[0]['sigla']; /******************************Busca de Dados do Custo do P.A. Principal*****************************/ $sql = "SELECT REPLACE(f.`nome`, ' ', '_') AS funcionario_alterou_custo, REPLACE(CONCAT(DATE_FORMAT(SUBSTRING(pac.`data_sys`, 1, 10), '%d/%m/%Y'), ' s', SUBSTRING(pac.`data_sys`, 11, 9)), ' ', '_') AS data_atualizacao FROM `produtos_acabados_custos` pac LEFT JOIN `funcionarios` f ON f.`id_funcionario` = pac.`id_funcionario` WHERE pac.`id_produto_acabado` = '$id_produto_acabado_discriminacao' AND pac.`operacao_custo` = '$operacao_custo2' LIMIT 1 "; $campos_custo = bancos::sql($sql); $funcionario_alterou_custo2 = $campos_custo[0]['funcionario_alterou_custo']; $data_atualiazacao2 = $campos_custo[0]['data_atualizacao']; /********************************Busca da Qualidade de Ao do P.A. Principal********************************/ //O sistema ir pegar a Qualidade do ao do PA desde de que sua OC seja igual a OC do Custo ... $sql = "SELECT qa.`nome` FROM `produtos_acabados_custos` pac INNER JOIN `produtos_insumos` pi ON pi.`id_produto_insumo` = pac.`id_produto_insumo` INNER JOIN `produtos_insumos_vs_acos` pia ON pia.`id_produto_insumo` = pi.`id_produto_insumo` INNER JOIN `qualidades_acos` qa ON qa.`id_qualidade_aco` = pia.`id_qualidade_aco` WHERE pac.`id_produto_acabado` = '$id_produto_acabado' AND pac.`operacao_custo` = '$operacao_custo' LIMIT 1 "; $campos = bancos::sql($sql); if(count($campos) > 0) { //Qualidade do Ao Referente ao Produto Acabado Principal ... $qualidade_aco = "<font color='blue'>".' ('.$campos[0]['nome'].')'.'</font>'; //Aqui eu verifico com a qualidade do Co $qualidade_cobalto = strtok($campos[0]['nome'], '%'); if($qualidade_cobalto == 5) { $discriminacao = str_replace('%Co', '%co', $discriminacao); $discriminacao = str_replace('%CO', '%co', $discriminacao); $discriminacao = str_replace('%cO', '%co', $discriminacao); }else if($qualidade_cobalto == 8) { $discriminacao = str_replace('%co', '%Co', $discriminacao); $discriminacao = str_replace('%CO', '%Co', $discriminacao); $discriminacao = str_replace('%cO', '%Co', $discriminacao); }else { $discriminacao = str_replace('%Co', '%CO', $discriminacao); $discriminacao = str_replace('%co', '%CO', $discriminacao); $discriminacao = str_replace('%cO', '%CO', $discriminacao); } //Significa que tem q aparecer a qualidade do Ao Principal para o Usurio if($mostrar == 1) $discriminacao.= $qualidade_aco; } //Significa que esse PA j foi excludo do Sistema ... if($ativo == 0) $discriminacao.= ' <font color="red" title="P.A. Excludo"> (EXCL) </font>'; /********************************Busca da Qualidade de Ao do P.A. Discriminao********************************/ $sql = "SELECT qa.`nome` FROM `produtos_acabados_custos` pac INNER JOIN `produtos_insumos` pi ON pi.`id_produto_insumo` = pac.`id_produto_insumo` INNER JOIN `produtos_insumos_vs_acos` pia ON pia.`id_produto_insumo` = pi.`id_produto_insumo` INNER JOIN `qualidades_acos` qa ON qa.`id_qualidade_aco` = pia.`id_qualidade_aco` WHERE pac.`id_produto_acabado` = '$id_produto_acabado_discriminacao' AND pac.`operacao_custo` = '$operacao_custo2' LIMIT 1 "; $campos = bancos::sql($sql); if(count($campos) > 0) { //Qualidade do Ao Referente ao Produto Acabado Discriminao ... $qualidade_aco2 = "<font color='blue'>".' ('.$campos[0]['nome'].')'.'</font>'; //Aqui eu verifico com a qualidade do Co $qualidade_cobalto2 = strtok($campos[0]['nome'], '%'); if($qualidade_cobalto2 == 5) { $discriminacao2 = str_replace('%Co', '%co', $discriminacao2); $discriminacao2 = str_replace('%CO', '%co', $discriminacao2); $discriminacao2 = str_replace('%cO', '%co', $discriminacao2); }else if($qualidade_cobalto == 8) { $discriminacao2 = str_replace('%co', '%Co', $discriminacao2); $discriminacao2 = str_replace('%CO', '%Co', $discriminacao2); $discriminacao2 = str_replace('%cO', '%Co', $discriminacao2); }else { $discriminacao2 = str_replace('%Co', '%CO', $discriminacao2); $discriminacao2 = str_replace('%co', '%CO', $discriminacao2); $discriminacao2 = str_replace('%cO', '%CO', $discriminacao2); } //Significa que tem q aparecer a qualidade do Ao Discrminao para o Usurio if($mostrar == 1) $discriminacao2.= $qualidade_aco2; } //Dados Referente ao Produto Acabado Principal ... $apresentar = $unidade.' * '.$referencia.' * '; if(!empty($codigo_fornecedor)) $apresentar.= $codigo_fornecedor.' * '; //Dados Referente ao Produto Acabado Discriminao ... $apresentar2 = $unidade2.' * '.$referencia2.' * '; if(!empty($codigo_fornecedor2)) $apresentar2.= $codigo_fornecedor2.' * '; /******************************************************************************/ /*************************************HTML*************************************/ /******************************************************************************/ if($pdf == 0) {//Html //Dados Referente ao Produto Acabado Principal ... $apresentar.= $discriminacao; //Dados Referente ao Produto Acabado Discriminao ... $apresentar2.= $discriminacao2; //Aqui verifica se o status do custo est liberado ou bloqueado ... if($mostrar_status == 1) { //Dados Referente ao Produto Acabado Principal ... if($status_custo == 1) {//Est Liberado $title1 = 'Custo_Liberado_em_'.$data_atualiazacao1.'_por_'.$funcionario_alterou_custo1; //A cor Roxa s ser utilizada quando existir Gato por Lebre ... if($id_produto_acabado_discriminacao <> 0) { $color1 = 'purple'; }else { //Se a Referncia do PA = 'ESP', sempre exibiremos na cor Azul ... $color1 = ($referencia == 'ESP') ? '#20B2AA' : 'black'; } }else {//Est Bloqueado $title1 = 'Custo_no_Liberado'; $color1 = 'red'; } //Dados Referente ao Produto Acabado Discriminao ... if($status_custo2 == 1) {//Est Liberado $title2 = 'Custo_Liberado_em_'.$data_atualiazacao2.'_por_'.$funcionario_alterou_custo2; //A cor Roxa s ser utilizada quando existir Gato por Lebre ... if($id_produto_acabado_discriminacao <> 0) { $color2 = 'purple'; }else { //Se a Referncia do PA = 'ESP', sempre exibiremos na cor Verde ... $color2 = ($referencia2 == 'ESP') ? '#20B2AA' : 'black'; } }else {//Est Bloqueado $title2 = 'Custo_no_Liberado'; $color2 = 'red'; } } if($mostra_status_nao_produzir == 1) { //Dados Referente ao Produto Acabado Principal ... if($status_nao_produzir == 1) {//Significa que este PA, est sem Produzir temporariamente if(!empty($title1)) $title1.= '_/_No_Produzido_Temporariamente'; $apresentar.= ' / (P) '; } //Dados Referente ao Produto Acabado Discriminao ... if($status_nao_produzir2 == 1) {//Significa que este PA, est sem Produzir temporariamente if(!empty($title2)) $title2.= '_/_No_Produzido_Temporariamente'; $apresentar2.= ' / (P)'; } } /**********Tratamento p/ apresentar as Discriminaes**********/ if($id_produto_acabado <> 0 && $id_produto_acabado_discriminacao == 0) { return '<font color="'.$color1.'" title="'.$title1.'" style="cursor:help">'.$apresentar.'</font>'; }else if($id_produto_acabado == 0 && $id_produto_acabado_discriminacao <> 0) { return '<font color="'.$color1.'" title="'.$title2.'" style="cursor:help">'.$apresentar2.'</font>'; }else if($id_produto_acabado <> 0 && $id_produto_acabado_discriminacao <> 0) { if(!empty($title1)) $title1.= '_/_(SB):_'.str_replace(' ', '_', $apresentar); return '<font color="'.$color1.'" title="'.$title1.'" style="cursor:help"><b>(SB '.$referencia.') '.$apresentar2.'</b></font>'; } /******************************************************************************/ /*************************************PDF**************************************/ /******************************************************************************/ }else {//No precisar de Tags ... //Dados Referente ao Produto Acabado Principal ... $apresentar.= $discriminacao; //Dados Referente ao Produto Acabado Discriminao ... $apresentar2.= $discriminacao2; if($id_produto_acabado <> 0 && $id_produto_acabado_discriminacao == 0) { return $apresentar; }else if($id_produto_acabado == 0 && $id_produto_acabado_discriminacao <> 0) { return $apresentar2; }else if($id_produto_acabado <> 0 && $id_produto_acabado_discriminacao <> 0) { return $apresentar2; } } } function dados_op($id_op) { $total_entradas_op_para_pa = 0; $exibir_rotulo_pa_baixado_para_pa = 'N'; //Aqui eu busco o Total de Baixa(s) de PA realizada(s) para a OP ... $sql = "SELECT bop.`qtde_baixa`, bmp.`acao` FROM `baixas_ops_vs_pas` bop INNER JOIN `baixas_manipulacoes_pas` bmp ON bmp.`id_baixa_manipulacao_pa` = bop.`id_baixa_manipulacao_pa` WHERE bop.`id_op` = '$id_op' "; $campos_baixa_op_para_pa = bancos::sql($sql); $linhas_baixa_op_para_pa = count($campos_baixa_op_para_pa); for($i = 0; $i < $linhas_baixa_op_para_pa; $i++) { if($campos_baixa_op_para_pa[$i]['acao'] == 'E') {//Ao = 'E' Entrada p/ saber o quanto que ainda resta p/ produzir ... $total_entradas_op_para_pa+= $campos_baixa_op_para_pa[$i]['qtde_baixa']; }else if($campos_baixa_op_para_pa[$i]['acao'] == 'B') {//Somente na ao = 'B' Baixa ... $exibir_rotulo_pa_baixado_para_pa = 'S'; } } /*Aqui eu busco o Total de Baixa(s) de PI da Famlia "AO e METAIS 5" - "BLANKS 22" realizada(s) para a OP, p/ saber o quanto que ainda resta p/ produzir ...*/ $sql = "SELECT SUM(bop.`qtde_baixa`) AS total_baixa_op_para_pi FROM `baixas_ops_vs_pis` bop INNER JOIN `produtos_insumos` pi ON pi.`id_produto_insumo` = bop.`id_produto_insumo` AND pi.`id_grupo` IN (5, 22) WHERE bop.`id_op` = '$id_op' "; $campos_baixa_op_para_pi = bancos::sql($sql); //Aqui eu trago o status - "Situao" da OP ... $sql = "SELECT `qtde_produzir`, DATE_FORMAT(`data_emissao`, '%d/%m/%Y') AS data_emissao, DATE_FORMAT(`prazo_entrega`, '%d/%m/%Y') AS prazo_entrega, `situacao`, `data_ocorrencia`, `status_finalizar` FROM `ops` WHERE `id_op` = '$id_op' LIMIT 1 "; $campos_op = bancos::sql($sql); if($campos_op[0]['status_finalizar'] == 1) { $posicao_op = '<font color="red"><b>(Finalizada)</b></font>'; }else { //Verifico se a OP est importada em alguma O.S ... $sql = "SELECT oi.`qtde_entrada` FROM `oss` INNER JOIN `oss_itens` oi ON oi.`id_os` = oss.`id_os` WHERE oss.`ativo` = '1' AND oi.`id_op` = '$id_op' ORDER BY oi.`id_os_item` DESC LIMIT 1 "; $campos_os = bancos::sql($sql); if(count($campos_os) == 1) {//Sim, realmente a OP est importada em alguma OS ... //Se esse item de OS possui alguma entrada, ento significa que este est fechado "Concludo" ... if($campos_os[0]['qtde_entrada'] > 0) { $posicao_op.= '<font color="darkblue" style="cursor:help" title="Item de OS Concludo"><b> | OS</b></font>'; }else {//Significa que este item de OSS no possui entrada ou seja est "Em Aberto" ... $posicao_op.= '<font color="red" style="cursor:help" title="Item de OS em Aberto"><b> | OS</b></font>'; } } if($exibir_rotulo_pa_baixado_para_pa == 'S') $posicao_op.= '<font color="red" title="PA Baixado" style="cursor:help"><b> | PA</b></font>'; if($campos_baixa_op_para_pi[0]['total_baixa_op_para_pi'] != 0) $posicao_op.= '<font color="red" title="PI Baixado" style="cursor:help"><b> | PI</b></font>'; } $qtde_saldo = $campos_op[0]['qtde_produzir'] - $total_entradas_op_para_pa; if($qtde_saldo < 0) $qtde_saldo = 0; return array('qtde_produzir' => intval($campos_op[0]['qtde_produzir']), 'total_baixa_op_para_pa' => intval($total_entradas_op_para_pa), 'qtde_saldo' => $qtde_saldo, 'data_emissao' => $campos_op[0]['data_emissao'], 'prazo_entrega' => $campos_op[0]['prazo_entrega'], 'situacao' => $campos_op[0]['situacao'], 'data_ocorrencia' => $campos_op[0]['data_ocorrencia'], 'posicao_op' => $posicao_op); } /*Funo que busca os Detalhes e Impostos do PA ... Esse 4 parmetro $id_empresa_nf necessrio por causa das Notas Fiscais que emitimos pela K2 ... Esse 5 parmetro $finalidade, se refere a uma Marcao de cadastro do Cliente, "Artigo Iseno" -> SUSPENSO IPI, CONF.ART.29, PARGRAFO 1, ALNEA A E B, LEI 10637/02 e se a Negociao for do Tipo INDUSTRIALIZAO, zero o IVA pois entende-se que este PA tem uma OF industrializada e no Revenda ... Hoje esse 5 parmetro s utilizado pelo Incluir Itens de Oramento e Itens Nota Fiscal ... Esse 6 parmetro esta relacionado ao Tipo de Nota Fiscal = 'S' => Sada ou 'E' => Entrada ... Esse 7 parmetro s utilizado na parte de Nota Fiscal de Sada ... Esse 8 parmetro s utilizado na parte de Nota Fiscal Outra ...*/ function dados_impostos_pa($id_produto_acabado, $id_uf = 1, $id_cliente = 0, $id_empresa_nf = 0, $finalidade = 'R', $tipo_negociacao = 'S', $id_nf = 0, $id_nf_outra = 0) { if(!class_exists('genericas')) require 'genericas.php';//CASO EXISTA EU DESVIO A CLASSE ... $pis = genericas::variavel(20); $cofins = genericas::variavel(21); //Valores Padres ... $id_pais = 31;//Representa "Brasil" ... $tributar_ipi_rev = 'N'; $pegar_iva = 1;//A princpio a idia pegar o IVA ... //Se existir esse parmetro $id_cliente, ento eu pego alguns dados que sero de extrema importncia no SQL abaixo ... if($id_cliente > 0) { $sql = "SELECT `id_pais`, `artigo_isencao`, `insc_estadual`, `trading`, `tipo_suframa`, `suframa_ativo`, `tributar_ipi_rev`, `optante_simples_nacional`, `isento_st`, `isento_st_em_pinos` FROM `clientes` WHERE `id_cliente` = '$id_cliente' LIMIT 1 "; $campos_cliente = bancos::sql($sql); $id_pais = $campos_cliente[0]['id_pais']; /*Se o Pas for Estrangeiro, no existe UF e sendo assim fao esta assumir 1, porque nossa Empresa est situada no Estado de So Paulo ...*/ if($id_pais != 31) $id_uf = 1; $artigo_isencao = $campos_cliente[0]['artigo_isencao']; $insc_estadual = $campos_cliente[0]['insc_estadual']; $trading = $campos_cliente[0]['trading']; $tipo_suframa = $campos_cliente[0]['tipo_suframa']; $suframa_ativo = $campos_cliente[0]['suframa_ativo']; if($id_empresa_nf > 0) { /*Se a Empresa da Nota Fiscal for 'K2', ento eu sempre assumo que esse campo "$tributar_ipi_rev" do Cliente est marcado, p/ que as OF(s) do PA sempre saiam como Industrial ...*/ $tributar_ipi_rev = ($id_empresa_nf == 3) ? 'S' : $campos_cliente[0]['tributar_ipi_rev']; }else { $tributar_ipi_rev = $campos_cliente[0]['tributar_ipi_rev']; } $optante_simples_nacional = $campos_cliente[0]['optante_simples_nacional']; $isento_st = $campos_cliente[0]['isento_st']; $isento_st_em_pinos = $campos_cliente[0]['isento_st_em_pinos']; /*Esse controle da Inscrio Estadual tem a ver com o 2 do art. 155 da Constituio Federal e no art. 99 do Ato das Disposies Constitucionais Transitrias - ADCT da Constituio Federal, bem como nos arts. 102 e 199 do Cdigo Tributrio Nacional (Lei n 5.172, de 25 de outubro de 1966), resolve celebrar o seguinte ...*/ if(intval($insc_estadual) == 0 || empty($insc_estadual) || $isento_st == 'S') { $pegar_iva = 0;//Essa varivel servir de controle mais abaixo na hora de se pegar o Iva ... /*Se o Cliente tiver marcado no seu Cadastro "Artigo Iseno" -> SUSPENSO IPI, CONF.ART.29, PARGRAFO 1, ALNEA A E B, LEI 10637/02. ou a Nota Fiscal tiver a sua Finalidade como "CONSUMO" ou "INDUSTRIALIZAO", zero o IVA pois entende-se que este PA tem uma OF industrializada e no Revenda ...*/ }else if($artigo_isencao == 1 || $finalidade == 'C' || $finalidade == 'I') { $pegar_iva = 0;//Essa varivel servir de controle mais abaixo na hora de se pegar o Iva ... } if($id_pais == 31) {//Cliente do Brasil ... if(!empty($id_uf_original)) {//Esta varivel tem prioridade sobre o $id_uf passado por parmetro ... if($id_uf_original == 1) {//Estado de So Paulo ... $inicio_cfop = ($tipo_negociacao == 'S') ? 5 : 1; }else {//Fora do Estado de So Paulo ... $inicio_cfop = ($tipo_negociacao == 'S') ? 6 : 2; } }else { if($id_uf == 1) {//Estado de So Paulo ... $inicio_cfop = ($tipo_negociacao == 'S') ? 5 : 1; }else {//Fora do Estado de So Paulo ... $inicio_cfop = ($tipo_negociacao == 'S') ? 6 : 2; } } }else {//Cliente fora do Brasil "Internacional" ... $inicio_cfop = 7; } } /*******************************************************************************************/ /*Adaptao exclusiva somente p/ os Clientes => Bandeirantes / Lemos 115 e Lemos e Gonalves 1034 que so do mesmo dono - 04/02/2016 ...*/ /*******************************************************************************************/ if($id_cliente == 115 || $id_cliente == 1034) { //Aqui eu busco o "id_familia" desse $id_produto_acabado que foi passado por parmetro ... $sql = "SELECT gpa.`id_familia` FROM `produtos_acabados` pa INNER JOIN `gpas_vs_emps_divs` ged ON ged.`id_gpa_vs_emp_div` = pa.`id_gpa_vs_emp_div` INNER JOIN `grupos_pas` gpa ON gpa.`id_grupo_pa` = ged.`id_grupo_pa` WHERE pa.`id_produto_acabado` = '$id_produto_acabado' LIMIT 1 "; $campos_familia = bancos::sql($sql); if($campos_familia[0]['id_familia'] == 30) {//Se a Famlia do PA = 'Rosca Postia' ... $tributar_ipi_rev = 'S';//Adaptao exclusiva s p/ esse caso, pois o cliente exige se creditar de ICMS na compra dessa linha de Produtos ... } } /*******************************************************************************************/ /*No caminho de Exportao, sempre trataremos todos os PA(s) como se fossem Industrial "PA(s) produzidos por ns mesmos" - Produo Nacional, p/ que as OF(s) do PA sempre saiam como Industrial ...*/ /*******************************************************************************************/ if($id_pais != 31) $tributar_ipi_rev = 'S'; /*******************************************************************************************/ /*********************Montagem de Situao Tributria de forma Dinmica*********************/ /*******************************************************************************************/ //Busco os impostos do PA na Unidade Federal passada por parmetro ... $sql = "SELECT cf.`id_classific_fiscal`, cf.`classific_fiscal`, cf.`ipi`, ged.`margem_lucro_exp`, icms.`icms`, icms.`reducao`, icms.`icms_intraestadual`, icms.`fecp`, IF('$pegar_iva' = '0', 0, icms.`iva`) AS iva, pa.`id_gpa_vs_emp_div`, IF('$tributar_ipi_rev' = 'S', 0, pa.`operacao`) AS operacao, pa.`origem_mercadoria` FROM `produtos_acabados` pa INNER JOIN `gpas_vs_emps_divs` ged ON ged.`id_gpa_vs_emp_div` = pa.`id_gpa_vs_emp_div` INNER JOIN `grupos_pas` gpa ON gpa.`id_grupo_pa` = ged.`id_grupo_pa` INNER JOIN `familias` f ON f.`id_familia` = gpa.`id_familia` INNER JOIN `classific_fiscais` cf ON cf.`id_classific_fiscal` = f.`id_classific_fiscal` INNER JOIN `icms` ON icms.`id_classific_fiscal` = cf.`id_classific_fiscal` AND icms.`id_uf` = '$id_uf' WHERE pa.`id_produto_acabado` = '$id_produto_acabado' LIMIT 1 "; $campos_pa_na_uf = bancos::sql($sql); /*************************************************************************************/ /********************************Atribuies Iniciais*********************************/ /*************************************************************************************/ //A princpio essas variveis so os valores que acabaram de serem lidos do BD ... $margem_lucro_exp = $campos_pa_na_uf[0]['margem_lucro_exp']; $id_classific_fiscal= $campos_pa_na_uf[0]['id_classific_fiscal']; $classific_fiscal = $campos_pa_na_uf[0]['classific_fiscal']; $ipi = $campos_pa_na_uf[0]['ipi']; $icms = $campos_pa_na_uf[0]['icms'].'|'; $icms_cadastrado = $campos_pa_na_uf[0]['icms'];//Essa varivel ser utilizada em poucos lugares do sistema ... $reducao = $campos_pa_na_uf[0]['reducao']; $reducao_cadastrado = $campos_pa_na_uf[0]['reducao'];//Essa varivel ser utilizada em poucos lugares do sistema ... $icms_intraestadual = $campos_pa_na_uf[0]['icms_intraestadual']; $fecp = $campos_pa_na_uf[0]['fecp']; //Se este PA pertencer a Classificao Fiscal de PINOS e tiver com essa marcao $isento_st_em_pinos ento, eu no tributo o ST nessa linha ... if($id_classific_fiscal == 3 && $isento_st_em_pinos == 'S') { /*Estou ignorando o Valor de IVA que com certeza foi pego mais acima do SQL dependo da UF e valores que foram cadastrados, acima deste SQL nesse Script eu no pegava o $id_classificao_fiscal, ento a varivel $pegar_iva ficou como sendo 1 e consequentemente retornou sim o IVA do Banco de Dados p/ Pinos porque existe, mais o cliente no quer pagar de jeito nenhum ...*/ $iva = 0; }else { $iva = $campos_pa_na_uf[0]['iva']; } $iva_cadastrado = $campos_pa_na_uf[0]['iva'];//Essa varivel ser utilizada em poucos lugares do sistema ... $operacao = $campos_pa_na_uf[0]['operacao']; $origem_mercadoria = $campos_pa_na_uf[0]['origem_mercadoria']; //Grupo vs Empresa Diviso = '75' representa "Mo de Obra" ou Empresa = "Grupo" ou Pas diferente de Brasil "Exportao" ... if($campos_pa_na_uf[0]['id_gpa_vs_emp_div'] == 75 || $id_empresa_nf == 4 || $id_pais != 31) { $situacao_tributaria = 41;//No Tributada ... $icms = 0; $reducao = 0; $icms_intraestadual = 0; $fecp = 0; $iva = 0; $ipi = 0; $origem_mercadoria = 0;//Como exportamos basicamente p/ o Mercosul obrigamos a Origem ser = 0 Nacional, p/ que os Clientes possam usufluir de todos os benefcios de Reduo de Impostos em seus pases ... /*************Preparei o Sistema p/ uma situao muito absurda*************/ if($tipo_suframa > 0 && $suframa_ativo == 'S') {//Cliente possui Suframa e est ativo ... $fim_cfop = ($tipo_negociacao == 'S') ? 109 : 203; }else if($trading == 1) {//Cliente possui Trading ... $fim_cfop = ($tipo_negociacao == 'S') ? 501 : 503; }else { //Esse o caminho comum ... if($campos_pa_na_uf[0]['operacao'] == 0) { $fim_cfop = ($tipo_negociacao == 'S') ? 101 : 201; }else { $fim_cfop = ($tipo_negociacao == 'S') ? 102 : 202; } } }else { /*Aqui estamos ignorando a lei que obriga a usar o ICMS de SP para Clientes s/ Inscrio Estadual, ou seja estamos abrindo uma brecha na lei ... rsrs */ if($id_uf > 1 || $id_uf_original > 1) {//UF ou UF original diferente do Estado de SP ... //Tratamento com o ICMS ... /********************************************************************************************/ /*Adequao p/ Produtos Importados e UF diferente de So Paulo, que comeou vigorar em 01/01/2013*/ /********************************************************************************************/ /*Essa lei consiste em abaixar o valor de ICMS p/ 4% em cima dos Produtos Importados ... Pas Brasil e fora do Estado de SP, Origem = 1, 2, 3, 6, 7, 8, ST = 00, 10, 20, 70, 90 ou Em cima dos Produtos Importados e ndice de Importao maior do que 40% por isso (origem 5 <=40% e 6 sem similar nacional no entram) e Data de Emisso >= 01/01/2013 ...*/ if($id_pais == 31 && ($origem_mercadoria == 1 || $origem_mercadoria == 2 || $origem_mercadoria == 3 || $origem_mercadoria == 6 || $origem_mercadoria == 7 || $origem_mercadoria == 8) && date('Y-m-d') >= '2013-01-01') { if($icms * (1 - $reducao / 100) > 4) { $icms = 4; $reducao = 0; //Por enquanto o nico caso em que o ICMS cadastrado passa a assumir esse ICMS Instantneo ... $icms_cadastrado = 4; $reducao_cadastrado = 0; } } } /*************************************************************************************/ /*****************************Optante pelo Simples em SC******************************/ /*************************************************************************************/ /*Se o Cliente Optante Simples Nacional e esta no Estado de "SC", devido ao Decreto 3.467/10 3 de 19.08.10, existe uma reduo de 70% no IVA ...*/ if($optante_simples_nacional == 'S' && $id_uf == 7) { $iva*= 0.3; $iva = round($iva, 2); } /*************************************************************************************/ /***************************************SUFRAMA***************************************/ /*************************************************************************************/ $desconto_pis_cofins_icms = 0;//Valor Inicial ... /*1) rea de Livre Comrcio IPI e (ICMS de 7% somente p/ algumas cidades se o Cliente estiver com Suframa Ativo) - Macap e Santana (Amap) - Bonfim e Pacaraima (Roraima) - Guajaramirim (Rondnia) - Tabatinga (Amazonas) - Cruzeiro do Sul, Basilia e Epitaciolandia (Acre) - Boa Vista (Roraima) ... *2) Zona Franca de Manaus IPI, ICMS 7 % e (PIS+COFINS de 3,65% somente p/ algumas cidades) - Manaus - Rio Preto da Eva - Presidente Figueiredo ...*/ if(($tipo_suframa == 1 || $tipo_suframa == 2) && $suframa_ativo == 'S') {//Cliente possui Suframa do Tipo 1 ou 2, "rea de Livre ou Zona Franca de Manaus" e est ativo ... if($campos_pa_na_uf[0]['operacao'] == 0) { $fim_cfop = ($tipo_negociacao == 'S') ? 109 : 203; }else { $fim_cfop = ($tipo_negociacao == 'S') ? 110 : 204; } $desconto_pis_cofins = ($tipo_suframa == 2) ? ($pis + $cofins) : 0; /*Propositalmente fiz a Conta nessa Linha p/ no dar erro concernente ao Desconto pois 5 linhas mais abaixo eu Zero o ICMS e a Reduo ...*/ $desconto_pis_cofins_icms = $desconto_pis_cofins + $icms * (1 - $reducao / 100); $desconto_pis_cofins_icms = round($desconto_pis_cofins_icms, 2); $ipi = 0; $icms = 0; $reducao = 0; $icms_intraestadual = 0; $fecp = 0; $iva = 0; $situacao_tributaria = 40;//Isento, porque um benefcio ... /*************************************************************************************/ /***************************************TRADING***************************************/ /*************************************************************************************/ }else if($trading == 1) {//Cliente possui Trading ... $situacao_tributaria = 41;//Porque segue a mesma idia de Exportao ... if($campos_pa_na_uf[0]['operacao'] == 0) { $fim_cfop = ($tipo_negociacao == 'S') ? 501 : 503; }else { $fim_cfop = ($tipo_negociacao == 'S') ? 502 : 504; } $icms = 0; $reducao = 0; $icms_intraestadual = 0; $fecp = 0; $iva = 0; $ipi = 0; /*************************************************************************************/ /*********************************PROCEDIMENTO NORMAL*********************************/ /*************************************************************************************/ }else { //Se no tem IVA ou a compra como "INDUSTRIALIZAO" ou o Cliente possui a Credencial de Iseno de ST ento ... if($iva == 0 || $finalidade == 'I' || $isento_st == 'S') { //$iva = 0;//Independente do Pas, se for Estrangeiro s estou reafirmando o que j foi feito + acima ... if($id_pais == 31) {//Cliente do Brasil ... if($campos_pa_na_uf[0]['operacao'] == 0 || $tributar_ipi_rev == 'S') { $fim_cfop = ($tipo_negociacao == 'S') ? 101 : 201; }else { $fim_cfop = ($tipo_negociacao == 'S') ? 102 : 202; $ipi = 0;//Sempre em que o PA = 'Revenda', nunca existir IPI ... } $situacao_tributaria = ($campos_pa_na_uf[0]['reducao'] == 0) ? '00' : 20; }else {//Cliente fora do Brasil "Internacional" ... $fim_cfop = ($tipo_negociacao == 'S') ? 101 : 201; } }else {//Iva > '0' ou finalidade = 'R' ou isento_st = 'N' ... /***************Procedimento com Convnio se existir ST***************/ /*Verifico se no Estado do Cliente existe algum Convnio, se sim a varivel "$situacao_tributaria" ir sobrepor o valor que foi atribudo anteriormente ...*/ $sql = "SELECT `convenio` FROM `ufs` WHERE `id_uf` = '$id_uf' LIMIT 1 "; $campos_convenio = bancos::sql($sql); if($campos_convenio[0]['convenio'] != '') {//Existe Convnio ... //Existe convnio, ento significa que o Cliente no ir pagar a GNRE se existir ST e sim ns "Empresa" ... if($campos_pa_na_uf[0]['operacao'] == 0 || $tributar_ipi_rev == 'S') { $fim_cfop = ($tipo_negociacao == 'S') ? 401 : 410; }else { $fim_cfop = ($tipo_negociacao == 'S') ? 403 : 411; $ipi = 0;//Sempre em que o PA = 'Revenda', nunca existir IPI ... } $situacao_tributaria = ($campos_pa_na_uf[0]['reducao'] == 0) ? 10 : 70;//Somos os Substitutos Tributrios ... }else {//No existe Convnio ... if($id_uf == 1) {//Estado de So Paulo ... if($campos_pa_na_uf[0]['operacao'] == 0 || $tributar_ipi_rev == 'S') { $situacao_tributaria = 10;//Somos os Substitutos Tributrios ... $fim_cfop = ($tipo_negociacao == 'S') ? 401 : 410; }else { $icms = 0; $reducao = 0; $icms_intraestadual = 0; $fecp = 0; $iva = 0; $ipi = 0; $situacao_tributaria = 60;//Somos os Substitudos Tributrios ... $fim_cfop = ($tipo_negociacao == 'S') ? 405 : 411; } } } } } //Quando o Cliente no tiver Inscrio Estadual e a sua UF for fora do Estado de SP ... if(empty($insc_estadual) && $id_uf > 1) { if($id_nf > 0) {//Se existir NF ... $sql = "SELECT `status` FROM `nfs` WHERE `id_nf` = '$id_nf' LIMIT 1 "; $campos_nfs = bancos::sql($sql); $fim_cfop = ($campos_nfs[0]['status'] == 6) ? 202 : 108;//NF de Devoluo 102, NF de Sada 108 ... }else { $fim_cfop = 108; } } /*Se estiver marcado no Cadastro do Cliente a Opo de SUSPENSO IPI, CONF.ART.29, PARGRAFO 1, ALNEA A E B, LEI 10637/02 ou Cliente possui Suframa do Tipo 3 "Amaznia Ocidental" e est ativo, ento NO EXISTE IPI ...*/ if($artigo_isencao == 1 || ($tipo_suframa == 3 && $suframa_ativo == 'S')) $ipi = 0; } /**********************************************************************/ /*****************************NF de Sada******************************/ /**********************************************************************/ if($id_nf > 0) { /**********************************************************************/ /**********************Nota Fiscal de Bonificao**********************/ /**********************************************************************/ /*De um modo paleativo para liberar uma Nota Fiscal de Bonificao, fiz essa adaptao aqui no fim dessa funo - 07/12/2015 ...*/ $sql = "SELECT `natureza_operacao` FROM `nfs` WHERE `id_nf` = '$id_nf' LIMIT 1 "; $campos_nfs = bancos::sql($sql); if($campos_nfs[0]['natureza_operacao'] == 'BON') { //Dentro do pas coloco 910, fora do pas no existe esse cdigo ento coloco 949 ... $fim_cfop = ($id_pais == 31) ? 910 : 949; /**********************************************************************/ /***Nota Fiscal de Venda Originada de Encomenda para Entrega Futura****/ /**********************************************************************/ }else if($campos_nfs[0]['natureza_operacao'] == 'VOF') { if($campos_pa_na_uf[0]['operacao'] == 0) { $fim_cfop = 116; }else { $fim_cfop = 117; } /**********************************************************************/ /*****************Nota Fiscal Remessa de Amostra Grtis****************/ /**********************************************************************/ }else if($campos_nfs[0]['natureza_operacao'] == 'RAG') { $fim_cfop = 911; } } /**********************************************************************/ /******************************NF Outras*******************************/ /**********************************************************************/ /*"Notas Fiscais Outras" a nica Situao da qual as Regras p/ CFOP so totalmente diferentes do procedimento normal, mas costumam ser as prprias CFOP(s) selecionadas pelo usurio no Cabealho ...*/ if($id_nf_outra > 0) { //Busca a CFOP da NF Outra e verifico se existe NF Complementar que ir influenciar nesta parte de CFOP(s) ... $sql = "SELECT `id_cfop`, `id_nf_comp`, `id_nf_outra_comp` FROM `nfs_outras` WHERE `id_nf_outra` = '$id_nf_outra' LIMIT 1 "; $campos = bancos::sql($sql); $id_cfop = $campos[0]['id_cfop']; $id_nf_comp = $campos[0]['id_nf_comp']; $id_nf_outra_comp = $campos[0]['id_nf_outra_comp']; if($id_nf_comp > 0) { /*Busco alguns dados da NF de Sada que sero passados por parmetro na funo "dados_impostos_pa" abaixo, 1 s item de NF j me satisfaz, porque hoje em dia a CFOP por item de Nota Fiscal ...*/ $sql = "SELECT c.`id_cliente`, c.`id_uf`, nfs.`id_empresa`, nfs.`status`, nfsi.`id_produto_acabado` FROM `nfs_itens` nfsi INNER JOIN `nfs` ON nfs.`id_nf` = nfsi.`id_nf` INNER JOIN `clientes` c ON c.`id_cliente` = nfs.`id_cliente` WHERE nfs.`id_nf` = '$id_nf_comp' LIMIT 1 "; $campos_nfs_item = bancos::sql($sql); /*Se a Nota Fiscal for uma Devoluo coloco essa Letra E que equivale a Entrada, seno S que equivale a Sada ...*/ $tipo_negociacao = ($campos_nfs_item[0]['status'] == 6) ? 'E' : 'S'; $dados_produto = self::dados_impostos_pa($campos_nfs_item[0]['id_produto_acabado'], $campos_nfs_item[0]['id_uf'], $campos_nfs_item[0]['id_cliente'], $campos_nfs_item[0]['id_empresa'], $campos_nfs_item[0]['finalidade'], $tipo_negociacao, $id_nf_comp); //Busco o id_cfop atravs do N. de CFOP que foi encontrado acima ... $sql = "SELECT `id_cfop` FROM `cfops` WHERE `cfop` = '".substr($dados_produto['cfop'], 0, 1)."' AND `num_cfop` = '".substr($dados_produto['cfop'], 2, 3)."' AND `ativo` = '1' LIMIT 1 "; $campos_cfop = bancos::sql($sql); $id_cfop = $campos_cfop[0]['id_cfop']; }else if($id_nf_outra_comp > 0) { $sql = "SELECT `id_cfop` FROM `nfs_outras` WHERE `id_nf_outra` = '$id_nf_outra_comp' LIMIT 1 "; $campos = bancos::sql($sql); $id_cfop = $campos[0]['id_cfop']; } /*Busco a CFOP equivalente ao id_cfop que foi selecionado no Cabealho da Nota Fiscal ou do que foi encontrado encontrado a pelo caminho desse Script se esta CFOP for pertinente a uma Nota Fiscal Complementar ...*/ $sql = "SELECT `cfop`, `num_cfop` FROM `cfops` WHERE `id_cfop` = '$id_cfop' AND `ativo` = '1' LIMIT 1 "; $campos_cfop = bancos::sql($sql); $inicio_cfop = $campos_cfop[0]['cfop']; $fim_cfop = $campos_cfop[0]['num_cfop']; /*Se a CFOP que estiver no Cabealho dessa NF for 5.116 "Venda originada de encomenda p/ entrega futura", ento nesse caso em especfico eu preciso separar os itens que so Industrial dos itens que so Revenda com outra CFOP = '117' ...*/ if($inicio_cfop == 5 && $fim_cfop == 116 && $campos_pa_na_uf[0]['operacao'] == 1) $fim_cfop = 117; } /**********************************************************************/ $cfop = $inicio_cfop.'.'.$fim_cfop; $cst = $origem_mercadoria.$situacao_tributaria; /*******************************************************************************************/ return array('margem_lucro_exp' => $margem_lucro_exp, 'id_classific_fiscal' => $id_classific_fiscal, 'classific_fiscal' => $classific_fiscal, 'ipi' => $ipi, 'icms' => $icms, 'icms_cadastrado' => $icms_cadastrado, 'reducao' => $reducao, 'reducao_cadastrado' => $reducao_cadastrado, 'icms_intraestadual' => $icms_intraestadual, 'fecp' => $fecp, 'iva' => $iva, 'iva_cadastrado' => $iva_cadastrado, 'operacao' => $operacao, 'situacao_tributaria' => $situacao_tributaria, 'cfop' => $cfop, 'cst' => $cst, 'desconto_pis_cofins_icms' => $desconto_pis_cofins_icms, 'pis' => $pis, 'cofins' => $cofins); } /*Essa Margem de Lucro Estimada utilizada em Vendas no Oramento que tem como objetivo auxilo no clculo da Comisso do Vendedor ...*/ function gravar_campos_para_calcular_margem_lucro_estimada($id_produto_insumo) { if(!class_exists('custos')) require 'custos.php';//CASO EXISTA EU DESVIO A CLASSE ... /***************************************************************************/ /**********************************Compras**********************************/ /***************************************************************************/ //Aqui eu busco o PA do PI que "Matria Prima" - PIPA ... $sql = "SELECT pa.`id_produto_acabado`, pa.`referencia`, pa.`discriminacao`, u.`sigla` FROM `produtos_acabados` pa INNER JOIN `unidades` u ON u.`id_unidade` = pa.`id_unidade` WHERE pa.`id_produto_insumo` = '$id_produto_insumo' LIMIT 1 "; $campos_pa = bancos::sql($sql); if(count($campos_pa) == 1) {//Se esse PI for realmente um PA ento ... $id_fornecedor_default = custos::procurar_fornecedor_default_revenda($campos_pa[0]['id_produto_acabado'], '', 1); $qtde_estoque = estoque_acabado::qtde_estoque($campos_pa[0]['id_produto_acabado']); $ec_pa = $qtde_estoque[8]; $total_qtde_entregue = 0; /*Aqui eu busco todas as NFs de Entrada desse PI que esteja liberado em Estoque at que a Qtde Recebida seja < que o EC do PA ...*/ $sql = "SELECT nfe.`id_nfe`, nfeh.`qtde_entregue` FROM `nfe_historicos` nfeh INNER JOIN `nfe` ON nfe.`id_nfe` = nfeh.`id_nfe` WHERE nfeh.`id_produto_insumo` = '$id_produto_insumo' AND nfeh.`status` = '1' ORDER BY nfe.`data_entrega` DESC "; $campos_nfe = bancos::sql($sql); $linhas_nfe = count($campos_nfe); for($i = 0; $i < $linhas_nfe; $i++) { //Enquanto o Somatrio Total da Qtde Entregue for menor que o EC do PA, vou acumulando nessa varivel $total_qtde_entregue ... if($total_qtde_entregue < $ec_pa) { $total_qtde_entregue+= $campos_nfe[$i]['qtde_entregue']; $vetor_nfe[] = $campos_nfe[$i]['id_nfe']; } } } if(!isset($vetor_nfe)) $vetor_nfe[] = 0;//Trato essa varivel p/ no dar erro na query mais abaixo ... $condicao_nfes = " AND nfe.`id_nfe` IN (".implode(',', $vetor_nfe).") "; $sql = "SELECT `qtde_total_compras_ml_est`, `preco_compra_medio_corr_ml_est`, `qtde_total_pendencias_ml_est`, `preco_pendencias_medio_corr_ml_est`, `data_ultima_atualizacao_ml_est` FROM `produtos_insumos` WHERE `id_produto_insumo` = '$id_produto_insumo' LIMIT 1 "; $campos_pi = bancos::sql($sql); //Trago somente itens que esto na Nota Fiscal de Entrada e que estejam liberados em Estoque ... $sql = "SELECT nfe.`data_emissao`, nfeh.`qtde_entregue`, nfeh.`valor_entregue` FROM `nfe` INNER JOIN `nfe_historicos` nfeh ON nfeh.`id_nfe` = nfe.`id_nfe` AND nfeh.`status` = '1' AND nfeh.`id_produto_insumo` = '$id_produto_insumo' WHERE 1 $condicao_nfes ORDER BY nfe.data_entrega DESC "; $campos = bancos::sql($sql); $linhas = count($campos); if($linhas == 0) {//Se no encontrou nenhuma Compra ... //Guardando campos p/ auxiliar a ML Estimada que utilizada em Vendas ... $sql = "UPDATE `produtos_insumos` SET `qtde_total_compras_ml_est` = '0', `preco_compra_medio_corr_ml_est` = '0' WHERE `id_produto_insumo` = '$id_produto_insumo' LIMIT 1 "; bancos::sql($sql); }else {//Existe pela menos 1 Compra ... $qtde_total = 0; for($i = 0; $i < $linhas; $i++) { //S ir contabilizar a Quantidade quando existir Preo p/ o Item de NF de Entrada ... if($campos[$i]['valor_entregue'] != '0.00') $qtde_total+= $campos[$i]['qtde_entregue']; /*Verifico se existem Compras acima desse perodo capitalizaremos uma Taxa de 0,5% porque a empresa nessa poca no capitava dinheiro nos Bancos ...*/ if($campos[$i]['data_emissao'] < '2009-01-01') { //Aqui anterior a 2009, com meio % apenas ao ms de Taxas ... $taxa_financeira_compras = 0.5; $fator_taxa_financeira = pow(($taxa_financeira_compras / 100 + 1), (1 / 30)); $retorno_data = data::diferenca_data($campos[$i]['data_emissao'], '2008-12-31'); $dias = $retorno_data[0]; $fator_taxa_final_periodo = pow($fator_taxa_financeira, $dias); $preco_corrigido_atual = $campos[$i]['valor_entregue'] * $fator_taxa_final_periodo; /*Aqui j a partir de 01 de janeiro de 2009 com Taxas a partir de 2% ... para esse caso ser cobrado taxa em cima de taxa ...*/ $taxa_financeira_compras = genericas::variavel(4) - 0.5; $fator_taxa_financeira = pow(($taxa_financeira_compras / 100 + 1), (1 / 30)); $retorno_data = data::diferenca_data('2009-01-01', date('Y-m-d')); $dias = $retorno_data[0]; $fator_taxa_final_periodo = pow($fator_taxa_financeira, $dias); $preco_corrigido_atual = $preco_corrigido_atual * $fator_taxa_final_periodo; }else {//Sempre a partir de 1 de Janeiro de 2009 ... /*At o dia 23/07/2013 s 16:38 era desse modo => "genericas::variavel(4) - 0.5" ..., a partir da fixamos 2% porque o Roberto acha que esse o Valor Mximo p/ essa Taxa de Estocagem, como os Juros subiram teramos que fazer uma interpolao o que seria complicado e fizemos isso p/ simplicarmos os clculos e ganharmos tempo ...*/ $taxa_financeira_compras = 2; $fator_taxa_financeira = pow(($taxa_financeira_compras / 100 + 1), (1 / 30)); $retorno_data = data::diferenca_data($campos[$i]['data_emissao'], date('Y-m-d')); $dias = $retorno_data[0]; $fator_taxa_final_periodo = pow($fator_taxa_financeira, $dias); $preco_corrigido_atual = $campos[$i]['valor_entregue'] * $fator_taxa_final_periodo; } $valor_total_corrigido = round($preco_corrigido_atual * $campos[$i]['qtde_entregue'], 2); $valor_total_corrigido_geral+= $valor_total_corrigido; } $preco_medio_corr_atual = ($valor_total_corrigido_geral / $qtde_total); //Guardando campos p/ auxiliar a ML Estimada que utilizada em Vendas ... $sql = "UPDATE `produtos_insumos` SET `qtde_total_compras_ml_est` = '$qtde_total', `preco_compra_medio_corr_ml_est` = '$preco_medio_corr_atual' WHERE `id_produto_insumo` = '$id_produto_insumo' LIMIT 1 "; bancos::sql($sql); } /***************************************************************************/ /*********************************Pendncias********************************/ /***************************************************************************/ //Zero essas variveis abaixo p/ no herdarmos os valores que foram calculadas acima na parte de Compras ... $qtde_total = 0; $valor_total_corrigido_geral = 0; $preco_medio_corr_atual = 0; /*Explicao das duas querys abaixo: 1) Aqui eu busco todos os Itens de Pedido que estejam Totalmente em Aberto ou importados Parcialmente em Nota Fiscal e no liberados em Estoque. Pedidos no Contabilizados aparecem nesse Relatrio com a Marcao C ... 2) Aqui eu busco todos os Itens de Pedido que estejam Totalmente importados em Nota Fiscal e liberados em Estoque ...*/ $sql = "SELECT ip.id_item_pedido FROM `itens_pedidos` ip INNER JOIN `pedidos` p ON p.`id_pedido` = ip.`id_pedido` AND p.`status` = '1' AND ((p.`programado_descontabilizado` = 'S' AND p.`ativo` = '0') OR (p.`programado_descontabilizado` = 'N' AND p.`ativo` = '1')) WHERE ip.`id_produto_insumo` = '$id_produto_insumo' AND ip.`status` < '2' UNION SELECT ip.id_item_pedido FROM `itens_pedidos` ip INNER JOIN `nfe_historicos` nfeh ON nfeh.`id_item_pedido` = ip.`id_item_pedido` AND nfeh.`status` = '0' WHERE ip.`id_produto_insumo` = '$id_produto_insumo' AND ip.`status` = '2' "; $campos = bancos::sql($sql); $linhas = count($campos); if($linhas == 0) {//No existe nenhum item nas situaes cima ... $id_itens_pedidos = 0;//Controle p/ no furar o SQL abaixo ... }else {//Existe pelo menos um item na situao cima ... for($i = 0; $i < $linhas; $i++) $vetor_item_pedido[] = $campos[$i]['id_item_pedido']; $id_itens_pedidos = implode(',', $vetor_item_pedido); } $sql = "SELECT `id_item_pedido`, `preco_unitario`, `qtde` FROM `itens_pedidos` WHERE `id_item_pedido` IN ($id_itens_pedidos) "; $campos = bancos::sql($sql); $linhas = count($campos); if($linhas == 0) {//Se no encontrou nenhuma Pendncia ... //Guardando campos p/ auxiliar a ML Estimada que utilizada em Vendas ... $sql = "UPDATE `produtos_insumos` SET `qtde_total_pendencias_ml_est` = '0', `preco_pendencias_medio_corr_ml_est` = '0', `data_ultima_atualizacao_ml_est` = '".date('Y-m-d')."' WHERE `id_produto_insumo` = '$id_produto_insumo' LIMIT 1 "; bancos::sql($sql); }else {//Existe pela menos 1 Pendncia ... for($i = 0; $i < $linhas; $i++) { //Busca o Total entregue do Item do Pedido em diversas NF(s) ... $sql = "SELECT SUM(`qtde_entregue`) AS total_entregue FROM `nfe_historicos` WHERE `id_item_pedido` = '".$campos[$i]['id_item_pedido']."' "; $campos_entregue = bancos::sql($sql); $total_entregue = $campos_entregue[0]['total_entregue']; //Busca o Total entregue do Item do Pedido em diversas NF(s) que j no foi liberado ... $sql = "SELECT SUM(`qtde_entregue`) AS total_entregue FROM `nfe_historicos` WHERE `id_item_pedido` = '".$campos[$i]['id_item_pedido']."' AND `status` = '0' "; $campos_entregue = bancos::sql($sql); $total_entregue_nao_liberado = $campos_entregue[0]['total_entregue']; $total_restante = $campos[$i]['qtde'] - $total_entregue + $total_entregue_nao_liberado; //S ir contabilizar a Quantidade Restante quando existir Preo p/ o Item de Pedido ... if($campos[$i]['preco_unitario'] != '0.00') $qtde_total+= $total_restante;//Nesse caso a Qtde Total sempre ser em cima do Restante ... $preco_total+= $total_restante * $campos[$i]['preco_unitario']; $compra_producao_total+= $total_restante; } //Nesse caso o Valor Corrigido j o Prprio Preo Total ... $valor_total_corrigido_geral = $preco_total; $preco_medio_corr_atual = ($valor_total_corrigido_geral / $qtde_total); //Guardando campos p/ auxiliar a ML Estimada que utilizada em Vendas ... $sql = "UPDATE `produtos_insumos` SET `qtde_total_pendencias_ml_est` = '$compra_producao_total', `preco_pendencias_medio_corr_ml_est` = '$preco_medio_corr_atual', `data_ultima_atualizacao_ml_est` = '".date('Y-m-d')."' WHERE `id_produto_insumo` = '$id_produto_insumo' LIMIT 1 "; bancos::sql($sql); } } /*Essa funo traz o somatrio de MMV do PA passado por parmetro e de todos os PAs em que ele atrelados 7 Etapa ou que esses PAs esto atrelados a 7 Etapa dele ... Esse parmetro $id_unidade restrigir dados, trazendo somente os pas_atrelados desse PA que entrou no escopo dessa funo, agora da mesma Unidade deste ...*/ function calculo_producao_mmv_estoque_pas_atrelados($id_produto_acabado, $id_unidade) { if(!class_exists('custos')) require 'custos.php';//CASO EXISTA EU DESVIO A CLASSE ... if(!class_exists('estoque_acabado')) require 'estoque_acabado.php';//CASO EXISTA EU DESVIO A CLASSE ... if(!class_exists('genericas')) require 'genericas.php';//CASO EXISTA EU DESVIO A CLASSE ... /*Sempre deleto essa varivel pq se essa funo for chamada p/ ser rodada, por ser uma varivel global acaba acumulando id de outros PAs dos Loops anteriores ...*/ if(isset($id_pa_atrelados)) unset($id_pa_atrelados); //Aqui eu busco a Unidade do PA principal que foi passado por parmetro ... $sql = "SELECT gpa.`id_grupo_pa`, gpa.`id_familia`, pa.`id_unidade`, pa.`referencia` FROM `produtos_acabados` pa INNER JOIN `gpas_vs_emps_divs` ged ON ged.`id_gpa_vs_emp_div` = pa.`id_gpa_vs_emp_div` INNER JOIN `grupos_pas` gpa ON gpa.`id_grupo_pa` = ged.`id_grupo_pa` WHERE pa.`id_produto_acabado` = '$id_produto_acabado' LIMIT 1 "; $campos_unidade_principal = bancos::sql($sql); $id_grupo_pa_principal = $campos_unidade_principal[0]['id_grupo_pa']; $id_familia_principal = $campos_unidade_principal[0]['id_familia']; $id_unidade_principal = $campos_unidade_principal[0]['id_unidade']; $referencia_principal = $campos_unidade_principal[0]['referencia']; /*Essa variavel esta como global por que tenho que pegar o id PA principal depois vejo os atrelados assim ficar ordenado ... Infelizmente tive que manter essa estrutura do Luis que encontrei no arquivo de Visualizar Estoque, pq seno d erro no Custo*/ global $id_pa_atrelados; $id_pa_atrelados[] = $id_produto_acabado; /*Aqui eu verifico se o PA que foi passado por parmetro tem a marcao de visualizao ou seja se ele for componente de um outro, esse no pode ser exibido ...*/ $sql = "SELECT explodir_view_estoque FROM `produtos_acabados` WHERE `id_produto_acabado` = '$id_produto_acabado' LIMIT 1 "; $campos_view_explodir = bancos::sql($sql); if($campos_view_explodir[0]['explodir_view_estoque'] == 'S') {//Esse PA tem ramificao ... $vetor_pas_atrelados = custos::pas_atrelados($id_produto_acabado, $id_unidade);//Aqui eu tambm retorno o prprio PA que foi passado por parmetro ... }else {//Esse PA no tem ramificao ento eu retorno ele prprio apenas ... $vetor_pas_atrelados[] = $id_produto_acabado; } for($i = 0; $i < count($vetor_pas_atrelados); $i++) { //Aqui eu busco a Unidade e o mmv de cada PA ... $sql = "SELECT `id_unidade`, `referencia`, `pecas_por_jogo`, `mmv` FROM `produtos_acabados` WHERE `id_produto_acabado` = '$vetor_pas_atrelados[$i]' AND `ativo` = '1' LIMIT 1 "; $campos_pa = bancos::sql($sql); $retorno = estoque_acabado::qtde_estoque($vetor_pas_atrelados[$i]); $estoque_comprometido = $retorno[8]; $compra = estoque_acabado::compra_producao($vetor_pas_atrelados[$i]); $producao = $retorno[2]; /*Suponho que todos os PA(s) do Loop tambm sejam Machos, seno no teria lgica por isso s analiso a Famlia do PA Principal ...*/ if($id_familia_principal == 9) {//Nesse caso especfico, o procedimento ser um pouquinho diferenciado ... $total_mmv_pas_atrelados+= ($campos_pa[0]['pecas_por_jogo'] * $campos_pa[0]['mmv']); $total_compra_producao_pas_atrelados+= ($campos_pa[0]['pecas_por_jogo'] * ($producao + $compra)); //Aqui eu tambm j calculo o Estoque de Queima de todos os PAs ... $total_ec_pas_atrelados+= ($campos_pa[0]['pecas_por_jogo'] * $estoque_comprometido); }else {//Outras Famlias ... //Se a UN Principal do PA for = a UN do PA que est em evidncia do Looping, acumulo o MMV ... if($id_unidade_principal == $campos_pa[0]['id_unidade']) { $total_mmv_pas_atrelados+= $campos_pa[0]['mmv']; $total_compra_producao_pas_atrelados+= $producao + $compra; //Aqui eu tambm j calculo o Estoque de Queima de todos os PAs ... $total_ec_pas_atrelados+= $estoque_comprometido; } } /*Nunca podemos somar o Estoque Disponvel de PA(s) que sejam Sub-Produtos de um Produto Principal que o que acontece na regra do IF abaixo: Exemplo: MR-053 - o PA Principal "Kit com 3 PA(s) que so o U, D, T" ... MR-053T - o Terceiro Macho do PA Principal ... MR-053D - o Segundo Macho do PA Principal ... MR-053U - o Primeiro Macho do PA Principal ... MR-053A - um Jogo que contm o Primeiro Macho e Terceiro Macho */ if(($campos_pa[0]['referencia'] != $referencia_principal.'U') && ($campos_pa[0]['referencia'] != $referencia_principal.'D') && ($campos_pa[0]['referencia'] != $referencia_principal.'T') && ($campos_pa[0]['referencia'] != $referencia_principal.'A')) { $total_ed_pas_atrelados+= $retorno[3];//Total dos Estoques Disponveis atrelados ... } $total_er_pas_atrelados+= $retorno[0];//Total dos Estoques Reais atrelados ... } /************************************************************************************/ /******************************Controle de Grupos PA(s)******************************/ /************************************************************************************/ //Lima Agulha WS - pode ser vendida avulsa, mas normalmente utilizada p/ montar jogos ... //Lima Agulha Diamantada - pode ser vendida avulsa, mas normalmente utilizada p/ montar jogos ... //Cabo de Lima, no calculo a Queima a funo muy pesada ... //Referncias comeadas por Si-4 podem pq so Bits Sinterizados q temos produzidos bem acima da mdia p/ forar venda ... if($id_grupo_pa_principal == 11 || $id_grupo_pa_principal == 78 || $id_grupo_pa_principal == 81 || strpos($referencia_principal, 'SI-4') !== false) { $retorno = estoque_acabado::qtde_estoque($id_produto_acabado);//Pego o Estoque Comprometido do PA principal ... $total_ec_pas_atrelados = $retorno[8]; } /************************************************************************************/ if($total_mmv_pas_atrelados == 0) $total_mmv_pas_atrelados = 0.01;//Para no dar erro de Diviso por Zero ... //Sendo assim eu fao um arredondamento dessa Qtde de Excesso p/ Baixo ... $estoque_para_x_meses_pas_atrelados = round($total_ec_pas_atrelados / $total_mmv_pas_atrelados, 1); return array('total_mmv_pas_atrelados' => $total_mmv_pas_atrelados, 'total_compra_producao_pas_atrelados' => $total_compra_producao_pas_atrelados, 'total_er_pas_atrelados' => $total_er_pas_atrelados, 'total_ed_pas_atrelados' => $total_ed_pas_atrelados, 'total_ec_pas_atrelados' => $total_ec_pas_atrelados, 'estoque_para_x_meses_pas_atrelados' => $estoque_para_x_meses_pas_atrelados); } /*Essa funo traz o somatrio de Queima "$total_eq_pas_atrelados" do PA passado por parmetro e de todos os PAs em que ele atrelados 7 Etapa ou que esses PAs esto atrelados a 7 Etapa dele ...*/ function calculo_estoque_queima_pas_atrelados($id_produto_acabado) { if(!class_exists('custos')) require 'custos.php';//CASO EXISTA EU DESVIO A CLASSE ... if(!class_exists('estoque_acabado')) require 'estoque_acabado.php';//CASO EXISTA EU DESVIO A CLASSE ... if(!class_exists('genericas')) require 'genericas.php';//CASO EXISTA EU DESVIO A CLASSE ... $dias_validade = (int)genericas::variavel(48);//Essa varivel ser utilizada no SQL + abaixo nos itens de Queima ... $qtde_meses = (int)genericas::variavel(73); $total_eq_pas_atrelados = 0; /*Sempre deleto essa varivel pq se essa funo for chamada p/ ser rodada, por ser uma varivel global acaba acumulando id de outros PAs dos Loops anteriores ...*/ if(isset($id_pa_atrelados)) unset($id_pa_atrelados); //Aqui eu busco a "Unidade do PA principal" e alguns atributos deste que foi passado por parmetro ... $sql = "SELECT ged.`id_gpa_vs_emp_div`, gpa.`id_familia`, pa.`id_unidade` FROM `produtos_acabados` pa INNER JOIN `gpas_vs_emps_divs` ged ON ged.`id_gpa_vs_emp_div` = pa.`id_gpa_vs_emp_div` INNER JOIN `grupos_pas` gpa ON gpa.`id_grupo_pa` = ged.`id_grupo_pa` WHERE pa.`id_produto_acabado` = '$id_produto_acabado' LIMIT 1 "; $campos_unidade_principal = bancos::sql($sql); $id_gpa_vs_emp_div_principal = $campos_unidade_principal[0]['id_gpa_vs_emp_div']; $id_familia_principal = $campos_unidade_principal[0]['id_familia']; $id_unidade_principal = $campos_unidade_principal[0]['id_unidade']; /* partir do dia "24/06/2016" a queima s esta sendo feita em cima dos respectivos "Grupos vs Empresas Divises" -> 22 Machos Manuais WS Jogos, 43 Machos Mquina, 83 Machos Manuais HSS Jogos - Por conta de uma Promoo de Machos Warrior WARRIOR ...*/ $vetor_produtos_em_promocao = array(22, 43, 83); if(in_array($id_gpa_vs_emp_div_principal, $vetor_produtos_em_promocao)) { /*Acumulo nessa varivel "$retorno_pas_atrelados" valores dos PA(s) atrelados a este PA principal desde que sejam da mesma UN ...*/ $retorno_pas_atrelados = intermodular::calculo_producao_mmv_estoque_pas_atrelados($id_produto_acabado, $id_unidade_principal); $total_eq_pas_atrelados = $retorno_pas_atrelados['total_ec_pas_atrelados'] + $retorno_pas_atrelados['total_compra_producao_pas_atrelados'] - $qtde_meses * $retorno_pas_atrelados['total_mmv_pas_atrelados']; } /*Verifico tudo o que tenho atrelado desse PA passado por parmetro, mas desde que seja da mesma Unidade deste ...*/ $vetor_pas_atrelados = custos::pas_atrelados($id_produto_acabado, $id_unidade_principal);//Aqui eu tambm retorno o prprio PA que foi passado por parmetro ... /*Se a varivel "$vetor_pas_atrelados" retornar vazia, ento fao esse controle para no dar erro mais abaixo para esse array ...*/ if(empty($vetor_pas_atrelados)) $vetor_pas_atrelados[] = $id_produto_acabado; /*Embora a funo de Custo "pas_atrelados" tenha trago tambm os PAs que so do Tipo ESP, nesse caso ignoro os mesmos porque no existe queima para este Tipo de Produto ...*/ $sql = "SELECT `id_produto_acabado`, `referencia` FROM `produtos_acabados` WHERE `id_produto_acabado` IN (".implode(',', $vetor_pas_atrelados).") "; $campos_produto_acabado = bancos::sql($sql); $linhas_produto_acabado = count($campos_produto_acabado); for($i = 0; $i < $linhas_produto_acabado; $i++) { if($campos_produto_acabado[$i]['referencia'] == 'ESP') unset($vetor_pas_atrelados[$i]);//Removo o ndice de array que do Tipo ESP ... } $vetor_pas_atrelados = array_values($vetor_pas_atrelados);//Reindexa os ndices do Array ... /*Se no encontrou nenhum PA, ou at tinha encontrado como por exemplo um "ESP", mas esse foi removido pelo trecho de cdigo acima, ento fao esse macete p/ no furar o SQL mais abaixo ...*/ if(count($vetor_pas_atrelados) == 0) $vetor_pas_atrelados[] = 0; /*****************************************************************************************************************************/ /******* Observao: Eu no fiz essa Query com SUM porque tinha horas que no retorna registro porque o resultado no era positivo e devido esse ocorrido retornava NULL em alguns casos o q furava nos clculos, preferi uma estrutura + manual ******/ /*****************************************************************************************************************************/ /*Aqui eu verifico todos os itens de Orcs que possuem esse PA do Loop marcados como Queima de Estoque que estejam em Aberto ou Parcial ...*/ $sql = "SELECT ovi.`id_orcamento_venda_item`, ovi.`qtde` FROM `orcamentos_vendas_itens` ovi INNER JOIN `orcamentos_vendas` ov ON ov.`id_orcamento_venda` = ovi.`id_orcamento_venda` AND ov.`data_emissao` >= DATE_ADD('".date('Y-m-d')."', INTERVAL -$dias_validade DAY) WHERE ovi.`id_produto_acabado` IN (".implode(',', $vetor_pas_atrelados).") AND ovi.`queima_estoque` = 'S' AND ovi.`status` <= '1' "; $campos_orcamentos = bancos::sql($sql); $linhas_orcamentos = count($campos_orcamentos); for($j = 0; $j < $linhas_orcamentos; $j++) { $total_queima_orcado+= $campos_orcamentos[$j]['qtde']; //Aqui eu verifico todos os Pedidos que foram gerados atravs desse Item de Oramento ... $sql = "SELECT `qtde` FROM `pedidos_vendas_itens` WHERE `id_orcamento_venda_item` = '".$campos_orcamentos[$j]['id_orcamento_venda_item']."' "; $campos_pedidos = bancos::sql($sql); $linhas_pedidos = count($campos_pedidos); for($k = 0; $k < $linhas_pedidos; $k++) $total_queima_pedido+= $campos_pedidos[$k]['qtde']; } /*****************************************************************************************************************************/ /*Do total de Queima encontrado pela frmula acima, eu desconto o Total de Queima encontrado nos ORCs do Produto Acabado ...*/ $total_eq_pas_atrelados-= ($total_queima_orcado - $total_queima_pedido); /************************************************************************************/ /******************************Controle de Grupos PA(s)******************************/ /************************************************************************************/ //Se for componente, no existe queima ... if($id_familia_principal == 23 || $id_familia_principal == 24) $total_eq_pas_atrelados = 0; /************************************************************************************/ //Aqui eu verifico se existe Qtde de Peas por Embalagem do PA ... $sql = "SELECT `pecas_por_emb` FROM `pas_vs_pis_embs` WHERE `id_produto_acabado` = '$id_produto_acabado' "; $campos_pecas_por_emb = bancos::sql($sql); //No encontrou registro algum ou at tem registro mas est com valor Zero = 1 ... $pecas_por_emb = (count($campos_pecas_por_emb) == 0 || $campos_pecas_por_emb[0]['pecas_por_emb'] == 0) ? 1 : $campos_pecas_por_emb[0]['pecas_por_emb']; //Sendo assim eu fao um arredondamento dessa Qtde de Excesso p/ Baixo ... $total_eq_pas_atrelados = intval($total_eq_pas_atrelados / $pecas_por_emb) * $pecas_por_emb; if($total_eq_pas_atrelados < 0) $total_eq_pas_atrelados = 0; //Guardo o mesmo valor de "Qtde de Queima p/ Estoque" p/ todos os PA(s) encontrados do Custo de forma a facilitar relatrios ... for($i = 0; $i < count($vetor_pas_atrelados); $i++) { $sql = "UPDATE `produtos_acabados` SET `qtde_queima_estoque` = '$total_eq_pas_atrelados' WHERE `id_produto_acabado` = '$vetor_pas_atrelados[$i]' LIMIT 1 "; bancos::sql($sql); } return array('total_eq_pas_atrelados' => $total_eq_pas_atrelados); } /*Essa funo traz o somatrio de Programado "$total_eq_pas_atrelados" do PA passado por parmetro e de todos os PAs em que ele atrelados 7 Etapa ou que esses PAs esto atrelados a 7 Etapa dele ...*/ function calculo_programado_pas_atrelados($id_produto_acabado) { if(!class_exists('custos')) require 'custos.php';//CASO EXISTA EU DESVIO A CLASSE ... /*Sempre deleto essa varivel pq se essa funo for chamada p/ ser rodada, por ser uma varivel global acaba acumulando id de outros PAs dos Loops anteriores ...*/ if(isset($id_pa_atrelados)) unset($id_pa_atrelados); /*Aqui eu verifico se o PA que foi passado por parmetro tem a marcao de visualizao ou seja se ele for componente de um outro, esse no pode ser exibido ...*/ $sql = "SELECT explodir_view_estoque FROM `produtos_acabados` WHERE `id_produto_acabado` = '$id_produto_acabado' LIMIT 1 "; $campos_view_explodir = bancos::sql($sql); if($campos_view_explodir[0]['explodir_view_estoque'] == 'S') $vetor_pas_atrelados = custos::pas_atrelados($id_produto_acabado);//Aqui eu tambm retorno o prprio PA que foi passado por parmetro ... /*Nessa parte calcula o somatrio de programado do PA passado por parmetro e de todos os PAs em que ele atrelados 7 Etapa ou que esses PAs esto atrelados a 7 Etapa dele ...*/ $id_pas_atrelados = (count($vetor_pas_atrelados) > 0) ? implode(',', $vetor_pas_atrelados) : 0;//Controle p/ no furar o SQL abaixo ... /*SQL que pega a qtde comprometida programada do sistema, para no produzir PA(s) p/ Pedidos acima de um ms ... Exemplo: Hoje dia 17/10/2014, ento o sistema s ir trazer Pedidos que sejam acima de 17/11/2014.*/ $sql = "SELECT (SUM(`qtde_pendente`)) AS total_programado_pas_atrelados FROM `pedidos_vendas_itens` pvi INNER JOIN `pedidos_vendas` pv ON pv.`id_pedido_venda` = pvi.`id_pedido_venda` WHERE pvi.`id_produto_acabado` IN ($id_pas_atrelados) AND pv.`faturar_em` >= DATE_ADD('".date('Y-m-d')."', INTERVAL 1 MONTH) ";//S at prximos 30 dias ... $campos_programado = bancos::sql($sql); $total_programado_pas_atrelados = $campos_programado[0]['total_programado_pas_atrelados']; return array('total_programado_pas_atrelados' => $total_programado_pas_atrelados); } /*Essa funo traz o somatrio de OE(s) "$total_oe_pas_atrelados" do PA passado por parmetro e de todos os PAs em que ele atrelados 7 Etapa ou que esses PAs esto atrelados a 7 Etapa dele ...*/ function calculo_oes_pas_atrelados($id_produto_acabado) { if(!class_exists('custos')) require 'custos.php';//CASO EXISTA EU DESVIO A CLASSE ... /*Sempre deleto essa varivel pq se essa funo for chamada p/ ser rodada, por ser uma varivel global acaba acumulando id de outros PAs dos Loops anteriores ...*/ if(isset($id_pa_atrelados)) unset($id_pa_atrelados); /*Aqui eu verifico se o PA que foi passado por parmetro tem a marcao de visualizao ou seja se ele for componente de um outro, esse no pode ser exibido ...*/ $sql = "SELECT `explodir_view_estoque` FROM `produtos_acabados` WHERE `id_produto_acabado` = '$id_produto_acabado' LIMIT 1 "; $campos_view_explodir = bancos::sql($sql); if($campos_view_explodir[0]['explodir_view_estoque'] == 'S') $vetor_pas_atrelados = custos::pas_atrelados($id_produto_acabado);//Aqui eu tambm retorno o prprio PA que foi passado por parmetro ... for($i = 0; $i < count($vetor_pas_atrelados); $i++) { $vetor_estoque_acabado = estoque_acabado::qtde_estoque($vetor_pas_atrelados[$i]); $total_oe_pas_atrelados+= $vetor_estoque_acabado[11]; } return array('total_oe_pas_atrelados' => $total_oe_pas_atrelados); } //Funo que bloqueia a Emisso de Pedido e de Nota Fiscal, caso esteja incompleto o Cadastro de Cliente function cadastro_cliente_incompleto($id_cliente) { $sql = "SELECT id_pais, id_uf, endereco FROM `clientes` WHERE `id_cliente` = '$id_cliente' LIMIT 1 "; $campos = bancos::sql($sql); $id_pais = $campos[0]['id_pais']; $id_uf = $campos[0]['id_uf']; $endereco = $campos[0]['endereco']; //Se no estiver preenchida a Unidade Federal ento ... if($id_pais == '' || $id_pais == 0) {//Tem que fora o preenchimento do Pas $valor = 1; }else {//Se o pas j estiver preenchido, legal ... if($id_pais == 31) {//Verificao para pases que so do Brasil //Se no estiver preenchida a Un. Federal e o Endereo if($id_uf == 0 || $endereco == '') { $valor = 1; }else { $valor = 0; } }else { $valor = 0; } } return $valor; } function desconto_icms_sgd($forma_venda, $id_cliente, $id_produto_acabado) { //Busco alguns dados do Cliente que sero utilizados mais abaixo ... $sql = "SELECT `id_pais`, `id_uf`, `trading` FROM `clientes` WHERE `id_cliente` = '$id_cliente' LIMIT 1 "; $campos = bancos::sql($sql); //Dados de ICMS e Reducao da Classificao p/ So Paulo ... $dados_produto = self::dados_impostos_pa($id_produto_acabado, 1); $icms_cf_uf_sp = $dados_produto['icms']; $reducao_uf_sp = $dados_produto['reducao']; //Dados de ICMS e Reducao da Classificao p/ a UF do Cliente ... $dados_produto = self::dados_impostos_pa($id_produto_acabado, $campos[0]['id_uf']); $icms_cf_uf_cliente = $dados_produto['icms']; $reducao_uf_cliente = $dados_produto['reducao']; $ICMS_SP = ($icms_cf_uf_sp) * (100 - $reducao_uf_sp) / 100; //SGD ou Cliente Estrangeiro ou Trading ... if($forma_venda == 'S' || $campos[0]['id_pais'] != 31 || $campos[0]['trading'] == 1) { $desconto_icms_sgd = (int)(0.57 * $ICMS_SP);//Conforme cartilha 10/2008 do Wilson ... }else {//Nota Fiscal ... $desconto_icms_sgd = $ICMS_SP - ($icms_cf_uf_cliente) * (100 - $reducao_uf_cliente) / 100; } return $desconto_icms_sgd; } /*Essa funo utilizada em vrios pontos do sistema, mas principalmente na parte Comercial "Vendas" e "Faturamento" ...*/ function prazo_medio($a = 0, $b = 0, $c = 0, $d = 0, $e = 0, $f = 0, $g = 0, $h = 0, $i = 0, $j = 0) { /**********************Prazo Mdio**********************/ if($j > 0) { $prazo_medio = ($a + $b + $c + $d + $e + $f + $g + $h + $i + $j) / 10; }else if($i > 0) { $prazo_medio = ($a + $b + $c + $d + $e + $f + $g + $h + $i) / 9; }else if($h > 0) { $prazo_medio = ($a + $b + $c + $d + $e + $f + $g + $h) / 8; }else if($g > 0) { $prazo_medio = ($a + $b + $c + $d + $e + $f + $g) / 7; }else if($f > 0) { $prazo_medio = ($a + $b + $c + $d + $e + $f) / 6; }else if($e > 0) { $prazo_medio = ($a + $b + $c + $d + $e) / 5; }else if($d > 0) { $prazo_medio = ($a + $b + $c + $d) / 4; }else if($c > 0) { $prazo_medio = ($a + $b + $c) / 3; }else if($b > 0) { $prazo_medio = ($a + $b) / 2; }else { $prazo_medio = $a; } /*******************************************************/ return $prazo_medio; } } ?>
Java
UTF-8
2,312
2.140625
2
[]
no_license
package com.example.sandy.cardviewexample; import android.os.AsyncTask; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ProgressBar; import android.widget.Toast; import com.astuetz.PagerSlidingTabStrip; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; public class CardActivity extends AppCompatActivity { private static final String TAG = "RecyclerViewExample"; private List<FeedItem> feedsList; private RecyclerView mRecyclerView; private MyRecyclerViewAdapter adapter; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_card); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ArrayList<Fragment> fragments = new ArrayList<>(); List<String> tabs = new ArrayList<>(); tabs.add("one"); tabs.add("Two"); Fragment f1 = new CardFragment(); Fragment f2 = new CardFragment(); fragments.add(f1); fragments.add(f2); SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), fragments, tabs); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); // Set the adapter onto the view pager if (viewPager != null) { viewPager.setAdapter(adapter); viewPager.setCurrentItem(viewPager.getAdapter().getCount()); } PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs); // Attach the view pager to the tab strip if (tabsStrip != null && viewPager != null) tabsStrip.setViewPager(viewPager); } }
Java
UTF-8
5,092
2.796875
3
[ "Apache-2.0" ]
permissive
package com.belladati.sdk; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import com.belladati.sdk.exception.InvalidImplementationException; /** * Serves as the entry point to the BellaDati SDK. Use either of the connect * methods to connect to a server, then authenticate to access a user's data. * <p> * It is recommended to use only one {@link BellaDatiConnection} per server to * allow reuse of connection resources. Most client applications will connect * only to a single BellaDati server - BellaDati cloud or an on-premise * installation - meaning only one connection should be used. * <p> * The SDK uses default timeouts of 10 seconds which should work fine for most * servers and internet connections. For environments that require different * settings, timeouts and connection management can be configured using system * properties: * <ul> * <li><strong>bdTimeout</strong>: Sets all timeouts without an individual * setting to the given value.</li> * <li><strong>bdConnectionRequestTimeout</strong>: Timeout for getting a * connection from the local connection manager.</li> * <li><strong>bdConnectTimeout</strong>: Timeout for establishing a connection * to the server.</li> * <li><strong>bdSocketTimeout</strong>: Timeout while waiting for data from the * server.</li> * <li><strong>bdMaxConnections</strong>: Maximum number of simultaneous API * connections. Defaults to 40, which should be plenty for most applications. If * your application sends large amounts of concurrent requests, local caching * may result in better performance than increasing this setting.</li> * </ul> * All timeouts are set in milliseconds. These properties only affect new * connections being created and don't change existing connections. If needed, * set the timeouts before calling any of the {@link #connect()} methods. * * * @author Chris Hennigfeld */ public class BellaDati { /** * Connects to the BellaDati cloud service. * * @return a connection to the BellaDati cloud service */ public static BellaDatiConnection connect() { return connect("https://service.belladati.com/"); } /** * Connects to a BellaDati server hosted at the specified URL. * * @param baseUrl URL of the BellaDati server * @return a connection to the BellaDati server hosted at the specified URL */ public static BellaDatiConnection connect(String baseUrl) { return connect(baseUrl, false); } /** * Connects to a BellaDati server hosted at the specified URL. This * connection accepts servers using self-signed SSL certificates. * <p> * <b>Warning:</b> Avoid using this type of connection whenever possible. * When using a server without a certificate signed by a known certificate * authority, an attacker could impersonate your server and intercept * passwords or sensitive data sent by the SDK. * * @param baseUrl URL of the BellaDati server * @return a connection to the BellaDati server hosted at the specified URL */ public static BellaDatiConnection connectInsecure(String baseUrl) { return connect(baseUrl, true); } private static BellaDatiConnection connect(String baseUrl, boolean trustSelfSigned) { try { return (BellaDatiConnection) getConnectionConstructor().newInstance(baseUrl, trustSelfSigned); } catch (ClassNotFoundException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (NoSuchMethodException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (InvocationTargetException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (IllegalAccessException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (InstantiationException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (IllegalArgumentException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (SecurityException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } catch (ClassCastException e) { throw new InvalidImplementationException("Failed to instantiate connection", e); } } /** * Reflectively loads the implementation's constructor to open a * {@link BellaDatiConnection}. * * @return the constructor of a {@link BellaDatiConnection} implementation * @throws ClassNotFoundException if the implementing class isn't found * @throws NoSuchMethodException if no constructor exists for the expected * arguments * @throws SecurityException if access is denied */ private static Constructor<?> getConnectionConstructor() throws ClassNotFoundException, NoSuchMethodException, SecurityException { Class<?> clazz = Class.forName("com.belladati.sdk.impl.BellaDatiConnectionImpl"); Constructor<?> constructor = clazz.getDeclaredConstructor(String.class, Boolean.TYPE); constructor.setAccessible(true); return constructor; } }
PHP
UTF-8
12,632
2.625
3
[ "Apache-2.0" ]
permissive
<?php /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * Hprose/Socket/Service.php * * * * hprose socket Service library for php 5.3+ * * * * LastModified: Sep 17, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ namespace Hprose\Socket; use stdClass; use Exception; use Throwable; class Service extends \Hprose\Service { public $onAccept = null; public $onClose = null; public $onError = null; public $readBuffer = 8192; public $writeBuffer = 8192; private $readableSockets = array(); private $writeableSockets = array(); private $onReceives = array(); private $onSends = array(); private $deferTasks = array(); private $delayTasks = array(); private $delayId = 0; private $deadlines = array(); public function __construct() { parent::__construct(); $this->timer = new Timer($this); } public function getReadBuffer() { return $this->readBuffer; } public function setReadBuffer($size) { $this->readBuffer = $size; } public function getWriteBuffer() { return $this->writeBuffer; } public function setWriteBuffer($size) { $this->writeBuffer = $size; } public function defer($callback) { $this->deferTasks[] = $callback; } private function runDeferTasks() { $tasks = $this->deferTasks; $this->deferTasks = array(); foreach ($tasks as $task) { call_user_func($task); } } private function nextDelayId($id) { do { if ($id >= 0x7FFFFFFF) { $id = 0; } else { $id++; } } while (isset($this->delayTasks[$id]) && is_callable($this->delayTasks[$id])); return $id; } public function after($delay, $callback) { $id = $this->delayId; $this->deadlines[$id] = ($delay / 1000) + microtime(true); $this->delayTasks[$id] = array($callback, true); $this->delayId = $this->nextDelayId($id); return $id; } public function tick($delay, $callback) { $id = $this->delayId; $this->deadlines[$id] = ($delay / 1000) + microtime(true); $deadlines = &$this->deadlines; $this->delayTasks[$id] = array(function() use ($id, &$deadlines, $delay, $callback) { $deadlines[$id] = ($delay / 1000) + microtime(true); call_user_func($callback); }, false); $this->delayId = $this->nextDelayId($id); return $id; } public function clear($id) { unset($this->delayTasks[$id]); unset($this->deadlines[$id]); } private function runDelayTasks() { foreach ($this->deadlines as $id => $deadline) { if (microtime(true) >= $deadline) { list($task, $once) = $this->delayTasks[$id]; call_user_func($task); if ($once) { unset($this->delayTasks[$id]); unset($this->deadlines[$id]); } } } } protected function nextTick($callback) { $this->defer($callback); } public function createContext($server, $socket) { $context = new stdClass(); $context->server = $server; $context->socket = $socket; $context->userdata = new stdClass(); return $context; } public function addSocket(&$sockets, $socket) { $index = array_search($socket, $sockets, true); if ($index === false) { $sockets[] = $socket; } } public function removeSocket(&$sockets, $socket) { $index = array_search($socket, $sockets, true); if ($index !== false) { unset($sockets[$index]); } } private function getOnSend($server, $socket) { $self = $this; $bytes = ''; $sockets = &$this->writeableSockets; return function($data = '') use ($server, $socket, $self, &$bytes, &$sockets) { $bytes .= $data; $len = strlen($bytes); if ($len === 0) { $self->removeSocket($sockets, $socket); } else { $sent = @fwrite($socket, $bytes, $len); if ($sent === false) { $self->error($server, $socket, 'Unknown write error'); } elseif ($sent < $len) { $bytes = substr($bytes, $sent); $self->addSocket($sockets, $socket); } else { $bytes = ''; $self->removeSocket($sockets, $socket); } } }; } private function getOnReceive($server, $socket) { $self = $this; $bytes = ''; $headerLength = 4; $dataLength = -1; $id = null; $onSend = $this->onSends[(int)$socket]; $send = function($data, $id) use ($onSend) { $dataLength = strlen($data); if ($id === null) { $onSend(pack("N", $dataLength) . $data); } else { $onSend(pack("NN", $dataLength | 0x80000000, $id) . $data); } }; $userFatalErrorHandler = &$this->userFatalErrorHandler; return function() use ($self, $server, $socket, &$bytes, &$headerLength, &$dataLength, &$id, &$userFatalErrorHandler, $send) { $data = @fread($socket, $self->readBuffer); if ($data === false) { $self->error($server, $socket, 'Unknown read error'); return; } elseif ($data === '') { if ($bytes == '') { $self->error($server, $socket, null); } else { $self->error($server, $socket, "$socket closed"); } return; } $bytes .= $data; while (true) { $length = strlen($bytes); if (($dataLength < 0) && ($length >= $headerLength)) { list(, $dataLength) = unpack('N', substr($bytes, 0, 4)); if (($dataLength & 0x80000000) !== 0) { $dataLength &= 0x7FFFFFFF; $headerLength = 8; } } if (($headerLength === 8) && ($id === null) && ($length >= $headerLength)) { list(, $id) = unpack('N', substr($bytes, 4, 4)); } if (($dataLength >= 0) && (($length - $headerLength) >= $dataLength)) { $context = $self->createContext($server, $socket); $data = substr($bytes, $headerLength, $dataLength); $userFatalErrorHandler = function($error) use ($self, $send, $context, $id) { $send($self->endError($error, $context), $id); }; $self->defaultHandle($data, $context)->then(function($data) use ($send, $id) { $send($data, $id); }); $bytes = substr($bytes, $headerLength + $dataLength); $id = null; $headerLength = 4; $dataLength = -1; } else { break; } } }; } private function accept($server) { $socket = @stream_socket_accept($server, 0); if ($socket === false) return; if (@stream_set_blocking($socket, false) === false) { $this->error($server, $socket, 'Unkown error'); return; } @stream_set_read_buffer($socket, $this->readBuffer); @stream_set_write_buffer($socket, $this->writeBuffer); $onAccept = $this->onAccept; if (is_callable($onAccept)) { try { $context = $this->createContext($server, $socket); call_user_func($onAccept, $context); } catch (Exception $e) { $this->error($server, $socket, $e); } catch (Throwable $e) { $this->error($server, $socket, $e); } } $this->readableSockets[] = $socket; $this->onSends[(int)$socket] = $this->getOnSend($server, $socket); $this->onReceives[(int)$socket] = $this->getOnReceive($server, $socket); } private function read($socket) { $onReceive = $this->onReceives[(int)$socket]; $onReceive(); } private function write($socket) { $onSend = $this->onSends[(int)$socket]; $onSend(); } private function close($socket, $context) { $this->removeSocket($this->writeableSockets, $socket); $this->removeSocket($this->readableSockets, $socket); unset($this->onReceives[(int)$socket]); unset($this->onSends[(int)$socket]); @stream_socket_shutdown($socket, STREAM_SHUT_RDWR); $onClose = $this->onClose; if (is_callable($onClose)) { try { call_user_func($onClose, $context); } catch (Exception $e) {} catch (Throwable $e) {} } } public function error($server, $socket, $ex) { $context = $this->createContext($server, $socket); if ($ex !== null) { $onError = $this->onError; if (is_callable($onError)) { if (!($ex instanceof Exception || $ex instanceof Throwable)) { $e = error_get_last(); if ($e === null) { $ex = new Exception($ex); } else { $ex = new ErrorException($e['message'], 0, $e['type'], $e['file'], $e['line']); } } try { call_user_func($onError, $ex, $context); } catch (Exception $e) {} catch (Throwable $e) {} } } $this->close($socket, $context); } private function timeout() { if (empty($this->deferTasks)) { $deadlines = $this->deadlines; if (empty($deadlines)) { return 3600; } return max(0, min($deadlines) - microtime(true)); } return 0; } public function handle($servers) { $readableSockets = &$this->readableSockets; $writeableSockets = &$this->writeableSockets; array_splice($readableSockets, 0, 0, $servers); while (!empty($readableSockets)) { $timeout = $this->timeout(); $sec = floor($timeout); $usec = ($timeout - $sec) * 1000; $read = array_values($readableSockets); $write = array_values($writeableSockets); $except = NULL; $n = @stream_select($read, $write, $except, $sec, $usec); if ($n === false) { foreach ($servers as $server) { $this->error($server, $server, 'Unknown select error'); } break; } if ($n > 0) { foreach ($read as $socket) { if (array_search($socket, $servers, true) !== false) { $this->accept($socket); } else { $this->read($socket); } } foreach ($write as $socket) { $this->write($socket); } } $this->runDeferTasks(); $this->runDelayTasks(); } } }
Java
UTF-8
881
3.296875
3
[]
no_license
import java.util.ArrayList; public class HumanResources { public void issueBadge(Employee[] employees){ for(int i =0; i <employees.length; i++){ System.out.println(employees[i]); } } public void printPaymentInfo(IPayable person){ System.out.println(person.getClass().getSimpleName() + "Should be paid: " + person.calculatePay()); } public void payPerson(IPayable[] payablePeople){ for(int i =0; i<payablePeople.length; i++){ printPaymentInfo(payablePeople[i]); } } public void sortPeopleByIncome(ArrayList<IPayable> payablePeople){ System.out.println("After sorting people by pay..."); for(int i=0; i<payablePeople.size(); i++){ System.out.println(payablePeople.get(i).getClass() + "should be paid: " + payablePeople.get(i).calculatePay()); } } }
Python
UTF-8
3,144
2.859375
3
[]
no_license
import math import numpy as np import matplotlib.pyplot as plt import random dx=0.1 L=15. c=400 N=1000 x0=[] y0=[] with open('case0.txt','r') as f: for line in f: splitline=line.split("\t") x0.append(float(splitline[0])) y0.append(float(splitline[1])-3) flin0=np.poly1d(np.polyfit(x0[4:9],y0[4:9],1)) theta0=np.arctan(flin0[1]) f0=np.poly1d(np.polyfit(x0,y0,3)) TE0=[x0[-1]+L,y0[-1]+L*(np.sin(np.arctan(flin0[1])))] LE0=[TE0[0]-c,TE0[1]] x0range=np.arange(x0[0],TE0[0]+dx,dx) #plt.scatter(x0,y0,c='r') #plt.scatter(TE0[0],TE0[1],s=100,c='r') #plt.scatter(LE0[0],LE0[1],s=100,c='r') #plt.plot(x0range,f0(x0range),linewidth=6,c='r') #plt.plot([TE0[0],LE0[0]],[TE0[1],LE0[1]],linewidth=4,c='r') #plt.legend(['case0']) fulldata=[] with open('alldata.txt','r') as f: for line in f: splitline=line.split("\t") fulldata.append(splitline) selection=[] for i in range(N): selection.append(int(random.uniform(0,len(fulldata)/3))) selection.sort() data=[] for j in selection: data.append(fulldata[j*3]) data.append(fulldata[j*3+1]) data.append(fulldata[j*3+2]) def casedata(i,x=None,y=None,SN=None): x =[] if x is None else x y =[] if y is None else y SN=[] if SN is None else SN k=(i*3) for j in data[k]: SN.append(float(j)) for j in data[k+1]: x.append(float(j)) for j in data[k+2]: y.append(float(j)) return [SN,x,y] def f(i): return np.poly1d(np.polyfit(casedata(i)[1],casedata(i)[2],3)) def flin(i): return np.poly1d(np.polyfit(casedata(i)[1][4:9],casedata(i)[2][4:9],1)) def TE(i): return [casedata(i)[1][-1]+L,casedata(i)[2][-1]+(L*np.arctan(flin(i)[1]))] def alpha(i): return np.arctan(flin(i)[1])-theta0 def LE(i): return [TE(i)[0]-c*np.cos(alpha(i)),TE(i)[1]-c*np.sin(alpha(i))] for i in range(int(len(data)/3)): xrange=np.arange(min(casedata(i)[1]),max(casedata(i)[1])+dx,dx) xlinrange=np.arange((casedata(i)[1][4]),TE(i)[0]+dx,dx) #plt.plot(xrange,f(i)(xrange),'--') #plt.plot(xlinrange,flin(i)(xlinrange)) #print('\n case nr '+str(i)) #print('snapshot nr: ',int(casedata(i)[0][0])) #print('angle of attack: ',round(alpha(i)*(180/np.pi),3),' [deg]') #print('Trailing Edge',TE(i)) #print('Leading Edge',LE(i)) #plt.scatter(casedata(i)[1],casedata(i)[2]) #plt.scatter(TE(i)[0],TE(i)[1],s=100) #plt.scatter(LE(i)[0],LE(i)[1],s=100) #plt.plot([TE(i)[0],LE(i)[0]],[TE(i)[1],LE(i)[1]],'--') plt.grid() #plt.ylim(530,670) #plt.show() time=[] alfa=[] for i in range(int(len(data)/3)): time.append((casedata(i)[0][0])/100) alfa.append(alpha(i)*(180/np.pi)) plt.scatter((casedata(i)[0][0])/100,(alpha(i)*(180/np.pi))) plt.title('Angle of attack') plt.xlabel('time [sec]') plt.ylabel('angle of attack [deg]') A=-4.3 w=2*np.pi/2.05 phi=-0.08 c1=0.3 x=np.arange(min(time),max(time)+dx,dx) def sinusoid(x): return A*np.sin(w*x+phi)+c1 plt.plot(x,sinusoid(x)) plt.grid() plt.show()
Python
UTF-8
527
2.9375
3
[]
no_license
# -*- coding: utf-8 -*- from datetime import datetime from datetime import time from datetime import timedelta def get_time_diff(val_to: time, val_from: time): val_from_del = timedelta(hours=val_from.hour, minutes=val_from.minute) val_to_del = timedelta(hours=val_to.hour, minutes=val_to.minute) if val_from_del > val_to_del: val_to_del = val_to_del + timedelta(hours=24) return (datetime.min + (val_to_del - val_from_del)).time() def time_to_hour(val: time): return val.hour + val.minute / 60
C#
UTF-8
873
3.671875
4
[]
no_license
using System; using System.Linq; namespace GrabAndGo { class Program { static void Main(string[] args) { long[] input = Console.ReadLine().Split().Select(long.Parse).ToArray(); long number = long.Parse(Console.ReadLine()); long index = -1; for (long i = 0; i < input.Length; i++) { if (input[i] == number) { index = i; } } if (index == -1) { Console.WriteLine("No occurrences were found!"); } else { long sum = 0; for (long i = 0; i < index; i++) { sum += input[i]; } Console.WriteLine(sum); } } } }
C++
UTF-8
13,040
3.015625
3
[]
no_license
/* * Wee Siang Wong * willydk@gmail.com * CPSC 566 * Spring 2012 * CWID# 802852186 * * Open courseware from MIT * http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-837-computer-graphics-fall-2003/assignments/ * with some modification * */ #include <stdio.h> #include <string.h> #include "Vectors.h" #include "Scene.h" #include "Camera.h" #include "Orthographic_camera.h" #include "Perspective_camera.h" #include "Light.h" #include "PointLight.h" #include "DirectionalLight.h" #include "Object3d.h" #include "Group.h" #include "Sphere.h" #include "Plane.h" #include "Triangle.h" #include "common.h" //------------------------------------------------------------------------- Scene::Scene() { initialize(); } //------------------------------------------------------------------------- Scene::Scene(const char* filename) { initialize(); // open the file assert(filename != NULL); const char *ext = &filename[strlen(filename)-4]; assert(!strcmp(ext,".txt")); file = fopen(filename,"r"); assert (file != NULL); // parse the scene parseFile(); // close the file fclose(file); file = NULL; } //------------------------------------------------------------------------- Scene::~Scene() { if (group != NULL) delete group; if (camera != NULL) delete camera; } //------------------------------------------------------------------------- void Scene::initialize() { group = NULL; camera = NULL; background_color = Vec3f(0.5,0.5,0.5); lights = NULL; num_lights = 0; ambient_light = Vec3f(1.0,1.0,1.0); current_object_color = Vec3f(1,1,1); file = NULL; } //------------------------------------------------------------------------- void Scene::parseFile() { /* parse the whole file, starting from OrthographicCamera or Perspective Camera to Background to Lights then Group, then the Group parses the Material and the spheres, or other primitives (plane/triangle) */ char token[MAX_PARSER_TOKEN_LENGTH]; while (getToken(token)) { if (!strcmp(token, "OrthographicCamera")) { parseOrthographicCamera(); } else if (!strcmp(token, "PerspectiveCamera")) { parsePerspectiveCamera(); } else if (!strcmp(token, "Background")) { parseBackground(); } else if (!strcmp(token, "Lights")) { parseLights(); } else if (!strcmp(token, "Group")) { group = parseGroup(); } else { printf ("Unknown token in parseFile: '%s'\n", token); exit(0); } } } //------------------------------------------------------------------------- Group* Scene::parseGroup() { char token[MAX_PARSER_TOKEN_LENGTH]; getToken(token); assert (!strcmp(token, "{")); // read in the number of objects getToken(token); assert (!strcmp(token, "numObjects")); int num_objects = readInt(); Group *answer = new Group(num_objects); // read in the objects int count = 0; while (num_objects > count) { getToken(token); // parse the Material for current group if (!strcmp(token, "Material")) { parseMaterial(); } else { // parse Objects in the group, could be sphere/plane/triangle Object3D *object = parseObject(token); assert (object != NULL); answer->addObject(count,object); count++; } } getToken(token); assert (!strcmp(token, "}")); // return the group return answer; } //------------------------------------------------------------------------- Object3D* Scene::parseObject(char token[MAX_PARSER_TOKEN_LENGTH]) { Object3D *answer = NULL; if (!strcmp(token, "Group")) { answer = (Object3D*)parseGroup(); } else if (!strcmp(token, "Sphere")) { answer = (Object3D*)parseSphere(); } else if (!strcmp(token, "Plane")) { answer = (Object3D*)parsePlane(); } else if (!strcmp(token, "Triangle")) { answer = (Object3D*)parseTriangle(); } else if (!strcmp(token, "TriangleMesh")) { answer = (Object3D*)parseTriangleMesh(); } else { printf ("Unknown token in parseObject: '%s'\n", token); exit(0); } return answer; } //------------------------------------------------------------------------- void Scene::parseLights() { char token[MAX_PARSER_TOKEN_LENGTH]; getToken(token); assert (!strcmp(token, "{")); // read in the number of objects getToken(token); assert (!strcmp(token, "numLights")); num_lights = readInt(); lights = new Light*[num_lights]; // read in the objects int count = 0; while (num_lights > count) { getToken(token); if (!strcmp(token, "PointLight")) { getToken(token); assert (!strcmp(token, "{")); getToken(token); assert (!strcmp(token, "position")); Vec3f position = readVec3f(); getToken(token); assert (!strcmp(token, "color")); Vec3f color = readVec3f(); getToken(token); assert (!strcmp(token, "}")); lights[count] = new PointLight(position,color); count++; } else if (!strcmp(token, "DirectionalLight")) { getToken(token); assert (!strcmp(token, "{")); getToken(token); assert (!strcmp(token, "position")); Vec3f position = readVec3f(); getToken(token); assert (!strcmp(token, "direction")); Vec3f direction = readVec3f(); getToken(token); assert (!strcmp(token, "color")); Vec3f color = readVec3f(); getToken(token); assert (!strcmp(token, "angle")); float angle = readFloat(); getToken(token); assert (!strcmp(token, "}")); lights[count] = new DirectionalLight(position,direction,color,angle); count++; } else { printf ("Unknown token in parseLights: '%s'\n", token); exit(0); } } getToken(token); assert (!strcmp(token, "}")); } //------------------------------------------------------------------------- void Scene::parseOrthographicCamera() { char token[MAX_PARSER_TOKEN_LENGTH]; // read in the camera parameters getToken(token); assert (!strcmp(token, "{")); getToken(token); assert (!strcmp(token, "center")); Vec3f center = readVec3f(); getToken(token); assert (!strcmp(token, "direction")); Vec3f direction = readVec3f(); getToken(token); assert (!strcmp(token, "up")); Vec3f up = readVec3f(); getToken(token); assert (!strcmp(token, "width")); float width = readFloat(); getToken(token); assert (!strcmp(token, "height")); float height = readFloat(); getToken(token); assert (!strcmp(token, "pixelsize")); float pixelsize = readFloat(); getToken(token); assert (!strcmp(token, "}")); // set camera to the orthographic camera values that parsed in camera = new OrthographicCamera(center,direction,up,width,height,pixelsize); } //------------------------------------------------------------------------- void Scene::parsePerspectiveCamera() { char token[MAX_PARSER_TOKEN_LENGTH]; // read in the camera parameters getToken(token); assert (!strcmp(token, "{")); getToken(token); assert (!strcmp(token, "center")); Vec3f center = readVec3f(); getToken(token); assert (!strcmp(token, "direction")); Vec3f direction = readVec3f(); getToken(token); assert (!strcmp(token, "up")); Vec3f up = readVec3f(); getToken(token); assert (!strcmp(token, "angle")); float angle_degrees = readFloat(); float angle_radians = DegreesToRadians(angle_degrees); getToken(token); assert (!strcmp(token, "}")); // set camera to the perspective camera values that parsed in camera = new PerspectiveCamera(center,direction,up,angle_radians); } //------------------------------------------------------------------------- void Scene::parseBackground() { char token[MAX_PARSER_TOKEN_LENGTH]; // read in the background color getToken(token); assert (!strcmp(token, "{")); while (1) { getToken(token); if (!strcmp(token, "}")) { break; } else if (!strcmp(token, "color")) { background_color = readVec3f(); } else if (!strcmp(token, "ambientLight")) { ambient_light = readVec3f(); } else { printf ("Unknown token in parseBackground: '%s'\n", token); assert(0); } } } //------------------------------------------------------------------------- void Scene::parseMaterial() { char token[MAX_PARSER_TOKEN_LENGTH]; // read in the material color getToken(token); assert (!strcmp(token, "{")); getToken(token); assert (!strcmp(token, "diffuseColor")); // set the current object color current_object_color = readVec3f(); getToken(token); assert (!strcmp(token, "}")); } //------------------------------------------------------------------------- Sphere* Scene::parseSphere() { char token[MAX_PARSER_TOKEN_LENGTH]; // read in the sphere parameters getToken(token); assert (!strcmp(token, "{")); getToken(token); assert (!strcmp(token, "center")); Vec3f center = readVec3f(); getToken(token); assert (!strcmp(token, "radius")); float radius = readFloat(); getToken(token); assert (!strcmp(token, "}")); // return the values for current sphere return new Sphere(center,radius,current_object_color); } //------------------------------------------------------------------------- Plane* Scene::parsePlane() { char token[MAX_PARSER_TOKEN_LENGTH]; // read in the sphere parameters getToken(token); assert (!strcmp(token, "{")); getToken(token); assert (!strcmp(token, "normal")); Vec3f normal = readVec3f(); getToken(token); assert (!strcmp(token, "offset")); float offset = readFloat(); getToken(token); assert (!strcmp(token, "}")); // return the values for current plane return new Plane(normal,offset,current_object_color); } //------------------------------------------------------------------------- Triangle* Scene::parseTriangle() { char token[MAX_PARSER_TOKEN_LENGTH]; // read in the sphere parameters getToken(token); assert (!strcmp(token, "{")); getToken(token); assert (!strcmp(token, "vertex0")); Vec3f v0 = readVec3f(); getToken(token); assert (!strcmp(token, "vertex1")); Vec3f v1 = readVec3f(); getToken(token); assert (!strcmp(token, "vertex2")); Vec3f v2 = readVec3f(); getToken(token); assert (!strcmp(token, "}")); // return the values for current triangle return new Triangle(v0,v1,v2,current_object_color); } //------------------------------------------------------------------------- Group* Scene::parseTriangleMesh() { char token[MAX_PARSER_TOKEN_LENGTH]; char filename[MAX_PARSER_TOKEN_LENGTH]; // get the filename getToken(token); assert (!strcmp(token, "{")); getToken(filename); getToken(token); assert (!strcmp(token, "}")); const char *ext = &filename[strlen(filename)-4]; assert(!strcmp(ext,".txt")); // read it once, get counts FILE *file = fopen(filename,"r"); assert (file != NULL); int vcount = 0; int fcount = 0; while (1) { int c = fgetc(file); if (c == EOF) { break; } else if (c == 'v') { assert(fcount == 0); float v0,v1,v2; fscanf (file,"%f %f %f",&v0,&v1,&v2); vcount++; } else if (c == 'f') { int f0,f1,f2; fscanf (file,"%d %d %d",&f0,&f1,&f2); fcount++; } } fclose(file); // make arrays Vec3f *verts = new Vec3f[vcount]; Group *answer = new Group(fcount); // read it again, save it file = fopen(filename,"r"); assert (file != NULL); int new_vcount = 0; int new_fcount = 0; while (1) { int c = fgetc(file); if (c == EOF) { break; } else if (c == 'v') { assert(new_fcount == 0); float v0,v1,v2; fscanf (file,"%f %f %f",&v0,&v1,&v2); verts[new_vcount] = Vec3f(v0,v1,v2); new_vcount++; } else if (c == 'f') { assert (vcount == new_vcount); int f0,f1,f2; fscanf (file,"%d %d %d",&f0,&f1,&f2); assert (f0 > 0 && f0 <= vcount); assert (f1 > 0 && f1 <= vcount); assert (f2 > 0 && f2 <= vcount); Triangle *t = new Triangle(verts[f0-1],verts[f1-1],verts[f2-1], current_object_color); answer->addObject(new_fcount,t); new_fcount++; } } delete [] verts; assert (fcount == new_fcount); assert (vcount == new_vcount); fclose(file); return answer; } //------------------------------------------------------------------------- int Scene::getToken(char token[MAX_PARSER_TOKEN_LENGTH]) { // for simplicity, tokens must be separated by whitespace assert (file != NULL); int success = fscanf(file,"%s ",token); if (success == EOF) { token[0] = '\0'; return 0; } return 1; } //------------------------------------------------------------------------- Vec3f Scene::readVec3f() { float x,y,z; int count = fscanf(file,"%f %f %f",&x,&y,&z); if (count != 3) { printf ("Error trying to read 3 floats to make a Vec3f\n"); assert (0); } return Vec3f(x,y,z); } //------------------------------------------------------------------------- float Scene::readFloat() { float answer; int count = fscanf(file,"%f",&answer); if (count != 1) { printf ("Error trying to read 1 float\n"); assert (0); } return answer; } //------------------------------------------------------------------------- int Scene::readInt() { int answer; int count = fscanf(file,"%d",&answer); if (count != 1) { printf ("Error trying to read 1 int\n"); assert (0); } return answer; } //------------------------------------------------------------------------- // end of Scene.cpp
PHP
UTF-8
345
2.75
3
[]
no_license
<?php include_once "api-header.php"; // connect to database $result = $mysqli->query("SELECT * FROM user"); while ($row = $result->fetch_assoc()) { // return with json format echo '<option value="' .$row['email']. '">' .$row['first_name']. '&nbsp;' .$row['last_name']. ' (' .$row['email']. ')</option>'; } mysqli_close($mysqli);
Markdown
UTF-8
2,324
3.671875
4
[]
no_license
--- category: etc date: '2010-08-10' layout: article slug: 'first-class-classes-in-csharp' tags: - c - functional-programming title: '(sort of) First Class Classes in C#' summary: It seems, at first, that C# doesn't have first-class classes. But ... --- I find myself writing some C# code while still thinking in Python. One thing in particular caught me out ... it seems, at first, that C# doesn’t have first class classes. This is annoying, because I’d started writing some device driver classes where each class is a type of device, and instances represent the individual devices themselves. And I wanted to construct a list of these classes, and call a “probe” classmethod on each of them to ask the class to go search out any devices which were available. In Python, this would look something like: ```python device_classes = (FooDevice, BarDevice, BazDevice) for device_class in device_classes: device_class.probe() ``` See? The classes are being treated just like any other variable, because they are, they’re just instances of type `classobj`. But the equivalent doesn’t work in C# — doing this: ```csharp Type[] DeviceClasses = { FooDevice, BarDevice, BazDevice }; ``` ... complains that `‘FooDevice’ is a ‘type’ but is used like a ‘variable’`. At first it seemed that C# didn’t have first class classes, and indeed a few web searches came up empty handed. Thankfully after a bit more exploration it turns out that all that is needed is some syntactic nastiness … namely, `typeof()`, `GetMethod()` and `Invoke()` (Passing `null` to `Invoke()` works for static methods): ```csharp Type[] DeviceClasses = { typeof(FooDevice), typeof(BarDevice), typeof(BazDevice) }; foreach (Type dct in DeviceClasses) { dct.GetMethod("Probe").Invoke(null, new object[] {} ); } ``` Now, quite why a shiny new programming language has to get saddled with such godawful syntax is a bit beyond me, but so it goes. As always, this is [lovingly documented in MSDN](http://msdn.microsoft.com/en-us/library/6hy0h0z1.aspx), in such a way that the answer is clear so long as you already know what you’re looking for. (As a bonus, yes, you can use reflection to find the list of Devices in the first place. It just wasn’t all that relevant to this example)
Java
UTF-8
1,336
2.203125
2
[]
no_license
package com.didichuxing.ctf.controller.user; import com.didichuxing.ctf.model.Flag; import com.didichuxing.ctf.service.FlagService; import java.io.PrintStream; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping({"flag"}) public class FlagController { @Autowired private FlagService flagService; @RequestMapping(value={"/getflag/{email:[0-9a-zA-Z']+}"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) public String getFlag(@PathVariable("email") String email, ModelMap model) { Flag flag = this.flagService.getFlagByEmail(email); return "Encrypted flag : " + flag.getFlag(); } @RequestMapping({"/testflag/{flag}"}) public String submitFlag(@PathVariable("flag") String flag, ModelMap model) { String[] fs = flag.split("[{}]"); Long longFlag = Long.valueOf(fs[1]); int i = this.flagService.exist(flag); if (i > 0) { return "pass!!!"; } return "failed!!!"; } private void init() { System.out.println("test"); } }
C
UTF-8
1,024
4.125
4
[]
no_license
#include <stdio.h> #include <stdlib.h> typedef struct _Calculator { int A, B; int (*add)(const int, const int); int (*substract)(const int, const int); int (*multiple)(const int, const int); int (*divide)(const int, const int); } Calculator; int add(const int A, const int B) { return A + B; } int subtract(const int A, const int B) { return A - B; } int multiple(const int A, const int B) { return A / B; } int divide(const int A, const int B) { return A * B; } Calculator calculator(const int A, const int B) { Calculator* newNode = calloc(1, sizeof(Calculator)); newNode->A = A; newNode->B = B; newNode->add = add; newNode->substract = subtract; newNode->multiple = multiple; newNode->divide = divide; return *newNode; } void main() { int A, B; scanf_s("%d %d", &A, &B); Calculator calc = calculator(A, B); printf("Add : %d\n", calc.add(A, B)); printf("Subtrct : %d\n", calc.substract(A, B)); printf("Mulpitle : %d\n", calc.multiple(A, B)); printf("Divide : %d", calc.divide(A, B)); }
C++
UTF-8
1,745
3.15625
3
[ "MIT" ]
permissive
#include "timer.h" namespace can { Timer::Timer(const TimeoutFunc &timeout_func) : timeout_func_(timeout_func) { } Timer::Timer(const TimeoutFunc &timeout_func, const Interval &interval, bool single_shot) : is_single_shot_(single_shot), interval_(interval), timeout_func_(timeout_func) { } void Timer::Start(bool multi_thread) { if (this->Running() == true) return; running_ = true; if (multi_thread == true) { thread_ = std::thread( &Timer::Temporize_, this); } else { this->Temporize_(); } } void Timer::Stop() { running_ = false; thread_.join(); } bool Timer::Running() const { return running_; } void Timer::SetSingleShot(bool single_shot) { if (this->Running() == true) return; is_single_shot_ = single_shot; } bool Timer::IsSingleShot() const { return is_single_shot_; } void Timer::SetInterval(const Timer::Interval &interval) { if (this->Running() == true) return; interval_ = interval; } const Timer::Interval& Timer::GetInterval() const { return interval_; } void Timer::SetTimeoutFunc(const TimeoutFunc &timeout) { if (this->Running() == true) return; timeout_func_ = timeout; } const Timer::TimeoutFunc& Timer::GetTimeoutFunc() const { return timeout_func_; } void Timer::Temporize_() { if (is_single_shot_ == true) { this->SleepThenTimeout_(); } else { while (this->Running() == true) { this->SleepThenTimeout_(); } } } void Timer::SleepThenTimeout_() { // std::chrono::microseconds m1(250); // std::this_thread::sleep_for(m1); std::this_thread::sleep_for(interval_); if (this->Running() == true) this->GetTimeoutFunc()(); } } //namespace can
Python
UTF-8
2,291
3.0625
3
[ "Apache-2.0" ]
permissive
"""Catalog search strategies.""" import os import gettext from public import public class _BaseStrategy: """Common code for strategies.""" def __init__(self, name): """Create a catalog lookup strategy. :param name: The application's name. :type name: string """ self.name = name self._messages_dir = None def __call__(self, language_code=None): """Find the catalog for the language. :param language_code: The language code to find. If None, then the default gettext language code lookup scheme is used. :type language_code: string :return: A `gettext` catalog. :rtype: `gettext.NullTranslations` or subclass """ # gettext.translation() requires None or a sequence. languages = (None if language_code is None else [language_code]) try: return gettext.translation( self.name, self._messages_dir, languages) except IOError: # Fall back to untranslated source language. return gettext.NullTranslations() @public class PackageStrategy(_BaseStrategy): """A strategy that finds catalogs based on package paths.""" def __init__(self, name, package): """Create a catalog lookup strategy. :param name: The application's name. :type name: string :param package: The package path to the message catalogs. This strategy uses the __file__ of the package path as the directory containing `gettext` messages. :type package_name: module """ super().__init__(name) self._messages_dir = os.path.dirname(package.__file__) @public class SimpleStrategy(_BaseStrategy): """A simpler strategy for getting translations.""" def __init__(self, name): """Create a catalog lookup strategy. :param name: The application's name. :type name: string :param package: The package path to the message catalogs. This strategy uses the __file__ of the package path as the directory containing `gettext` messages. :type package_name: module """ super().__init__(name) self._messages_dir = os.environ.get('LOCPATH')
Java
UTF-8
571
2.5
2
[ "Apache-2.0" ]
permissive
package indi.joynic.joodoo.websupport.support; public class RequestPath { private String val; public RequestPath(final String val) { this.val = val; } public String getVal() { return val; } public static RequestPath valueOf(final String val) { return new RequestPath(val); } @Override public boolean equals(Object obj) { if (!(obj instanceof RequestPath)) { return false; } RequestPath thatPath = (RequestPath) obj; return thatPath.getVal().equals(val); } }
C#
UTF-8
548
2.8125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Petri { public class Network { private readonly IList<Place> _places; private readonly Sequence _sequence = new Sequence(); public Network() { _places = new List<Place>(); } public void Execute() { foreach (Place place in _places) { _sequence.Increment(); place.Execute(_sequence); } } } }
Java
UTF-8
2,569
2.203125
2
[]
no_license
package com.training.reactive.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunction; import static org.springframework.web.reactive.function.server.RequestPredicates.method; import static org.springframework.web.reactive.function.server.RequestPredicates.path; import static org.springframework.web.reactive.function.server.RouterFunctions.nest; import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.ServerResponse.ok; import org.springframework.beans.factory.annotation.Autowired; import com.training.reactive.dao.UserRepoInterface; import com.training.reactive.model.Person; import com.training.reactive.service.UserDetailInterface; import com.training.reactive.service.UserDetailServiceImpl; import reactor.core.publisher.Flux; @RestController @Configuration public class PersonRoutesConfig { @Autowired UserDetailInterface userDetails; @Autowired UserRepoInterface userRepo; @Bean RouterFunction<?> routes(UserRepoInterface personRespository) { return nest(path("/person"), route(RequestPredicates.GET("/{id}"), request -> ok().body(personRespository.findById(request.pathVariable("id")), Person.class)) .andRoute(method(HttpMethod.POST), request -> { personRespository.insert(request.bodyToMono(Person.class)).subscribe(); return ok().build(); }) ); } @RequestMapping(value="/person/getAll",method=RequestMethod.GET,produces= {"application/json"}) public Flux<Person> getAllUsers(){ System.out.println("User--->"); Flux<Person> userList=userDetails.findAllUsers(); userList.collectList(); System.out.println("User--->"+userList.collectList()); return userList; } @RequestMapping(value="/person/add",method=RequestMethod.POST,consumes= {"application/json"},produces= {"application/json"}) public void addUser(Person personObj) { userRepo.save(personObj); Person person= new Person(); } }
Java
UTF-8
1,993
3.25
3
[]
no_license
package HomeWork; import com.collections.Student; public class Data_Structures { public static void main(String[] args) { // TODO Auto-generated method stub int sum=0; int avg; int temp; int top; Student s[]=new student[10]; s[0]=new student(); s[0].name="Sraya"; s[0].marks=95; s[1]=new student(); s[1].name="siva"; s[1].marks=88; s[2]=new student(); s[2].name="raja"; s[2].marks=77; s[3]=new student(); s[3].name="surya"; s[3].marks=96; s[4]=new student(); s[4].name="sidhu"; s[4].marks=82; s[5]=new student(); s[5].name="gowtham"; s[5].marks=90; s[6]=new student(); s[6].name="anusha"; s[6].marks=67; s[7]=new student(); s[7].name="mouni"; s[7].marks=37; s[8]=new student(); s[8].name="vijay"; s[8].marks=28; s[9]=new student(); s[9].name="swetha"; s[9].marks=60; for(int i = 0;i<s.length;i++) { if(s[i].marks>35) { System.out.println("pass"); } else { System.out.println("fail"); } } for(int j=0;j<s.length;j++) { sum=sum+s[j].marks; } System.out.println("total marks of 10 students :"+sum); for(int k=0;k<s.length;k++) { avg=sum/10; } System.out.println("aerage of 10 students is :"+avg); //marks in order for(int i=0;i<s.length;i++) { for(int j=0;j<s.length-i;j++) { if(s.length[j]>s.length[j+1]) { student max = s[j]; s[j]=s[j+1]; s[j+1]=max; } } } for(int i=0;i<s.length;i++) { System.out.println(s[i]); } /* to retrieve top 3 elements * * */ for( int i = 1; i <3; i++) { System.out.println("List of top 3 students: "+s.name()); } } }
Markdown
UTF-8
8,976
3.53125
4
[]
no_license
+-- {: .rightHandSide} +-- {: .toc .clickDown tabindex="0"} ### Context #### Higher category theory +--{: .hide} [[!include higher category theory - contents]] =-- =-- =-- # Contents * table of contents {: toc} ## Idea Given an ordinary [[category]] $C$, a pasting diagram in $C$ is a sequence of composable morphisms in $C$ $$ a_1 \stackrel{f_1}{\to} a_2 \stackrel{f_2}{\to} \cdots \stackrel{f_n}{\to} a_{n+1} \,. $$ We think of these arrows as not yet composed, but _pasted_ together at their objects, such as to form a composable sequence, and then say the _value_ of the sequence is the composite morphism in $C$. Or, we could say that a pasting diagram is a specified decomposition of whatever morphism $f$ it evaluates to, thus breaking down $f$ into morphisms $f_i$ which, in practice, are usually "more basic" than $f$ relative to some type of structure on $C$. For example, if $C$ is a [[monoidal category]], the $f_i$ might be instances of associativity isomorphisms. Pasting decompositions become more elaborate in higher categories. An example of a pasting diagram in a (let's say strict) 2-category is a pasting of two squares $$ \array{ a &\to& b &\to& c \\ \downarrow &\swArrow& \downarrow &\swArrow& \downarrow \\ d &\to& e &\to& f } \,. $$ To evaluate this diagram as a single 2-morphism, we read this diagram explicitly as the vertical composite of the 2-morphism $$ \array{ a &\to& b &\to& c \\ && \downarrow &\swArrow& \downarrow \\ && e &\to& f } $$ with the 2-morphism $$ \array{ a &\to& b && \\ \downarrow &\swArrow& \downarrow && \\ d &\to& e &\to& f } \,. $$ (Notice that the two halves of the boundary of each of these two 2-morphisms are themselves 1-dimensional pasting diagrams.) Similarly, there can be situations where one pastes together other shapes (triangles, pentagons, etc.), and there may be multiple paths on the way to resolving the diagram into a single 2-morphism, but the idea is that all such paths evaluate to the same 2-morphism, at least in a strict 2-category. General theorems which refer to the uniqueness of pastings are called _pasting theorems_. On the other hand, the following diagram is _not_ a pasting diagram: $$ \array{ a &\to& b &\to& c \\ \downarrow &\neArrow& \downarrow &\swArrow& \downarrow \\ d &\to& e &\to& f } \,. $$ Thus, formal definitions of pasting diagram include conditions which impose a consistent "directionality" of the cells so they can be pasted together. In an [[n-category]] a pasting diagram is similarly a collection of [[k-morphism|n-morphisms]] with a prescribed way how they are to fit together at their boundaries. There are a number of ways of formalizing pasting diagrams, depending partly on the constituent shapes one allows, and also on the technical hypotheses that allow proofs of pasting theorems, which include directionality conditions but usually also "loop-freeness" conditions to ensure there exists a unique way to resolve or evaluate the diagram. (N.B.: usually a completely unambiguous evaluation is only possible in a strict $n$-category; in a weak $n$-category, one allows uniqueness up to a "contractible space of choices".) Despite some technical differences among the formalizations, the core idea throughout is that the overall geometric shapes of pasting diagrams should be (contractible) $n$-dimensional polyhedra, broken down into smaller polyhedral cells which come equipped with directionality or orientations, that can be sensibly pasted together as in the above descriptions once the cells have been assigned values in an $n$-category. ## Notions of pasting diagrams Various formalisms for pasting diagrams have been proposed. They include * [[pasting scheme|pasting schemes]] (Johnson) * [[parity complex|parity complexes]] (Street) * [[directed complex|directed complexes]] (Steiner) * [[generalized parity complex|generalized parity complexes]] (Forest) Each of these formalisms involve graded sets $\{C_n\}_{n \geq 0}$ together with maps $\partial^+_n: C_{n+1} \to P(C_n)$, $\partial^-_n: C_{n+1} \to P(C_n)$. This goes under various names; here we call it a **parity structure**. It should be thought of as assigning to each "cell" of dimension $n+1$ a collection of positive boundary cells and negative boundary cells in dimension $n$. The formalisms above are distinguished by the choice of axioms on parity structures, but there is definite kinship among them. Also related are various notions of categories of shapes, including * [[test category]] * [[direct category]] * [[compositions in cubical sets]] ## Examples * [[Toda bracket]] ## Related concepts * [[pasting law]] for [[pullbacks]]/[[homotopy pullbacks]] ## References The notion of pasting in a [[2-category]] was introduced in * [[Jean Benabou]], _Introduction to bicategories_, Reports of the Midwest Category Seminar, Lecture Notes in Mathematics, **47**, 1967. ([doi:10.1007/BFb0074299](https://doi.org/10.1007/BFb0074299)) A reasonably self-contained, formal, and illustrated seven-page introduction to pasting diagrams in the context of weak 2-categories, and their relation to [[string diagrams]] is given in Section A.4 of: * [[Chris Schommer-Pries]], _The Classification of Two-Dimensional Extended Topological Field Theories_, 2011. ([arXiv:1112.1000v2](https://arxiv.org/abs/1112.1000v2)) A survey discussion of pasting in [[2-categories]] is in * [[John Power]], _2-Categories_ ([pdf](http://www.brics.dk/NS/98/7/BRICS-NS-98-7.pdf)) from definition 2.10 on. Details are in * [[John Power]], _A 2-categorical pasting theorem_ , Journal of Algebra, **129**, 1990. &lbrack;<a href="https://doi.org/10.1016/0021-8693(90)90229-H">doi:10.1016/0021-8693(90)90229-H</a>&rbrack; Dominic Verity gave a bicategorical pasting theorem in * [[Dominic Verity]], _Enriched categories, internal categories, and change of base_, PhD thesis, Cambridge University, 1992. Reprinted in TAC ([link](http://www.tac.mta.ca/tac/reprints/articles/20/tr20abs.html)). A definition and discussion of pasting diagrams in [[strict omega-categories]] is in * [[Sjoerd Crans]], _Pasting presentation for Omega-categories_ ([web](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.48.4342)) * [[Sjoerd Crans]], _Pasting schemes for the monoidal biclosed structure on $\omega$-$\mathbf{Cat}$_ ([web](http://home.tiscali.nl/secrans/papers/thten.html), [ps](http://home.tiscali.nl/secrans/papers/thten.ps.gz), [[thten.pdf|pdf:file]]) The notion of pasting scheme used by Crans was introduced by Johnson, * [[Michael Johnson]], _The combinatorics of n-categorical pasting_, Journal of Pure and Applied Algebra, **62**, 1989. &lbrack;<a href="https://doi.org/10.1016/0022-4049(89)90136-9">doi:10.1016/0022-4049(89)90136-9</a>&rbrack; Other notions of pasting presentations have been given by Street and by Steiner, * [[Ross Street]], _Parity complexes_, Cahiers de Topologie et Géométrie Différentielle Catégoriques, **32**, 1991. ([link](http://www.numdam.org/item/?id=CTGDC_1991__32_4_315_0)) * [[Ross Street]], _Parity complexes : corrigenda_, Cahiers de Topologie et Géométrie Différentielle Catégoriques, **35**, 1994. ([link](http://www.numdam.org/item/?id=CTGDC_1994__35_4_359_0)) * [[Richard Steiner]], _The algebra of directed complexes_, Applied Categorical Structures, **1**, 1993. ([doi:0.1007/BF00873990](https://doi.org/10.1007/BF00873990)) These notions were compared, and a new generalized one introduced, in * [[Simon Forest]], _Unifying notions of pasting diagrams_, Higher Structures, **6**, 2022 ([arxiv:1903.00282](https://arxiv.org/abs/1903.00282), [doi:10.21136/HS.2022.01](https://doi.org/10.21136/HS.2022.01)) For an online link to the notion of directed complex, see * [[Sjoerd Crans]] and [[Richard Steiner]], _Presentations of omega-categories by directed complexes_, Journal of the Australian Mathematical Society, **63**, 1997. ([doi:10.1017/S1446788700000318](https://doi.org/10.1017/S1446788700000318)) There is also * [[Michael Makkai]], _Computads and 2 dimensional pasting diagrams_ ([pdf](http://www.math.mcgill.ca/makkai/2dcomputads/2DCOINS1.pdf)) For a cubical approach to multiple compositions and other references see the paper * [[Philip J. Higgins]], _Thin elements and commutative shells in cubical omega-categories_, Theory and Applications of Categories, **14**, 2005. ([link](http://www.tac.mta.ca/tac/volumes/14/4/14-04abs.html)) A formal approach to [[pasting diagrams]] in [[Gray categories]]: * {#DiVittorio2023} [[Nicola Di Vittorio]], _A Gray-categorical pasting theorem_, Theory and Applications of Categories **39** 5 (2023) 150-171 &lbrack;[tac:39-05](http://www.tac.mta.ca/tac/volumes/39/5/39-05abs.html)&rbrack; [[!redirects pasting diagrams]] [[!redirects pasting]]
Java
UTF-8
447
1.648438
2
[ "MIT" ]
permissive
package ca.ualberta.elasticsearch; import ca.ualberta.elasticsearch.index.ElasticIndex; public class test { public static void main(String[] args) { // TODO Auto-generated method stub ElasticSearchManager testelas = new ElasticSearchManager(); //testelas.advancedSearchTitleAndBody("tennis"," Andre"); //testelas.advancedQuery("tennis", "Andre"); // testelas.multiMatchSearch(ElasticIndex.analyzed, "american football"); } }
Java
UTF-8
2,160
1.9375
2
[]
no_license
package com.wetuo.wepic.publish.service; import java.util.List; import java.util.Map; import com.wetuo.wepic.common.hibernate.Pager; import com.wetuo.wepic.publish.beans.PublishCat_Story; import com.wetuo.wepic.publish.dao.PublishCat_StoryDao; public class PublishCat_StorySeviceImpl implements PublishCat_StorySevice { PublishCat_StoryDao publishCatStoryDao; public PublishCat_StoryDao getPublishCatStoryDao() { return publishCatStoryDao; } public void setPublishCatStoryDao(PublishCat_StoryDao publishCatStoryDao) { this.publishCatStoryDao = publishCatStoryDao; } public boolean delete(PublishCat_Story record) { // TODO Auto-generated method stub return publishCatStoryDao.delete(record); } public boolean delete(Integer id) { // TODO Auto-generated method stub return publishCatStoryDao.delete(id); } public List<PublishCat_Story> findAll() { // TODO Auto-generated method stub return publishCatStoryDao.findAll(); } public List<PublishCat_Story> findPart(String strFields, String[] strArrValues) { // TODO Auto-generated method stub return publishCatStoryDao.findPart(strFields, strArrValues); } public Integer insert(PublishCat_Story record) { // TODO Auto-generated method stub return publishCatStoryDao.insert(record); } public Pager list(int pageSize, int pageNo) { // TODO Auto-generated method stub return publishCatStoryDao.list(pageSize, pageNo); } public Pager list(String username, int pageSize, int pageNo) { // TODO Auto-generated method stub return publishCatStoryDao.list(username, pageSize, pageNo); } public Pager list(Map<String, Object> mapSqlParam, int pageSize, int pageNo) { // TODO Auto-generated method stub return publishCatStoryDao.list(mapSqlParam, pageSize, pageNo); } public List list(int publicId) { // TODO Auto-generated method stub return publishCatStoryDao.list(publicId); } public PublishCat_Story select(Integer id) { // TODO Auto-generated method stub return publishCatStoryDao.select(id); } public boolean update(PublishCat_Story record) { // TODO Auto-generated method stub return publishCatStoryDao.update(record); } }
C#
UTF-8
728
2.828125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Data; namespace PrimeTube.Converter { public class StringURIToURIConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string culture) { string uriIn = (string)value; if (uriIn != null) { return new Uri(uriIn, UriKind.RelativeOrAbsolute); } return null; } public object ConvertBack(object value, Type targetType, object parameter, string culture) { throw new NotSupportedException(); } } }
Java
UTF-8
9,407
2.28125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2010 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.ec2.model; /** * <p> * Represents a task to bundle an EC2 Windows instance into a new image. * </p> */ public class BundleTask { /** * Instance associated with this bundle task. */ private String instanceId; /** * Unique identifier for this task. */ private String bundleId; /** * The state of this task. */ private String state; /** * The time this task started. */ private java.util.Date startTime; /** * The time of the most recent update for the task. */ private java.util.Date updateTime; /** * Amazon S3 storage locations. */ private Storage storage; /** * The level of task completion, in percent (e.g., 20%). */ private String progress; /** * If the task fails, a description of the error. */ private BundleTaskError bundleTaskError; /** * Instance associated with this bundle task. * * @return Instance associated with this bundle task. */ public String getInstanceId() { return instanceId; } /** * Instance associated with this bundle task. * * @param instanceId Instance associated with this bundle task. */ public void setInstanceId(String instanceId) { this.instanceId = instanceId; } /** * Instance associated with this bundle task. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param instanceId Instance associated with this bundle task. * * @return A reference to this updated object so that method calls can be chained * together. */ public BundleTask withInstanceId(String instanceId) { this.instanceId = instanceId; return this; } /** * Unique identifier for this task. * * @return Unique identifier for this task. */ public String getBundleId() { return bundleId; } /** * Unique identifier for this task. * * @param bundleId Unique identifier for this task. */ public void setBundleId(String bundleId) { this.bundleId = bundleId; } /** * Unique identifier for this task. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param bundleId Unique identifier for this task. * * @return A reference to this updated object so that method calls can be chained * together. */ public BundleTask withBundleId(String bundleId) { this.bundleId = bundleId; return this; } /** * The state of this task. * * @return The state of this task. */ public String getState() { return state; } /** * The state of this task. * * @param state The state of this task. */ public void setState(String state) { this.state = state; } /** * The state of this task. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param state The state of this task. * * @return A reference to this updated object so that method calls can be chained * together. */ public BundleTask withState(String state) { this.state = state; return this; } /** * The time this task started. * * @return The time this task started. */ public java.util.Date getStartTime() { return startTime; } /** * The time this task started. * * @param startTime The time this task started. */ public void setStartTime(java.util.Date startTime) { this.startTime = startTime; } /** * The time this task started. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param startTime The time this task started. * * @return A reference to this updated object so that method calls can be chained * together. */ public BundleTask withStartTime(java.util.Date startTime) { this.startTime = startTime; return this; } /** * The time of the most recent update for the task. * * @return The time of the most recent update for the task. */ public java.util.Date getUpdateTime() { return updateTime; } /** * The time of the most recent update for the task. * * @param updateTime The time of the most recent update for the task. */ public void setUpdateTime(java.util.Date updateTime) { this.updateTime = updateTime; } /** * The time of the most recent update for the task. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param updateTime The time of the most recent update for the task. * * @return A reference to this updated object so that method calls can be chained * together. */ public BundleTask withUpdateTime(java.util.Date updateTime) { this.updateTime = updateTime; return this; } /** * Amazon S3 storage locations. * * @return Amazon S3 storage locations. */ public Storage getStorage() { return storage; } /** * Amazon S3 storage locations. * * @param storage Amazon S3 storage locations. */ public void setStorage(Storage storage) { this.storage = storage; } /** * Amazon S3 storage locations. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param storage Amazon S3 storage locations. * * @return A reference to this updated object so that method calls can be chained * together. */ public BundleTask withStorage(Storage storage) { this.storage = storage; return this; } /** * The level of task completion, in percent (e.g., 20%). * * @return The level of task completion, in percent (e.g., 20%). */ public String getProgress() { return progress; } /** * The level of task completion, in percent (e.g., 20%). * * @param progress The level of task completion, in percent (e.g., 20%). */ public void setProgress(String progress) { this.progress = progress; } /** * The level of task completion, in percent (e.g., 20%). * <p> * Returns a reference to this object so that method calls can be chained together. * * @param progress The level of task completion, in percent (e.g., 20%). * * @return A reference to this updated object so that method calls can be chained * together. */ public BundleTask withProgress(String progress) { this.progress = progress; return this; } /** * If the task fails, a description of the error. * * @return If the task fails, a description of the error. */ public BundleTaskError getBundleTaskError() { return bundleTaskError; } /** * If the task fails, a description of the error. * * @param bundleTaskError If the task fails, a description of the error. */ public void setBundleTaskError(BundleTaskError bundleTaskError) { this.bundleTaskError = bundleTaskError; } /** * If the task fails, a description of the error. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param bundleTaskError If the task fails, a description of the error. * * @return A reference to this updated object so that method calls can be chained * together. */ public BundleTask withBundleTaskError(BundleTaskError bundleTaskError) { this.bundleTaskError = bundleTaskError; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("InstanceId: " + instanceId + ", "); sb.append("BundleId: " + bundleId + ", "); sb.append("State: " + state + ", "); sb.append("StartTime: " + startTime + ", "); sb.append("UpdateTime: " + updateTime + ", "); sb.append("Storage: " + storage + ", "); sb.append("Progress: " + progress + ", "); sb.append("BundleTaskError: " + bundleTaskError + ", "); sb.append("}"); return sb.toString(); } }
C++
GB18030
845
2.78125
3
[]
no_license
#pragma once #ifndef BASEGROUP_H #define BASEGROUP_H #ifdef DLL_FILE #define EX_IM_PORT _declspec(dllexport) // #else #define EX_IM_PORT _declspec(dllimport) // #endif #include <vector> #include <string> #include <algorithm> using namespace std; class EX_IM_PORT BaseGroup { public: BaseGroup(void):edges_num(0),nodes_num(0){} //캯, virtual ~BaseGroup(void){} //, BaseGroup(const BaseGroup & other); //캯 BaseGroup & operator = (const BaseGroup & other);//ֵ vector<int> & GetNodes();//ⲿȡڵ㼯 virtual void AddNode(int _node) = 0;//ӽڵ virtual void DelNode(int _node) = 0;//ɾڵ public: int edges_num;//Ⱥڱ int nodes_num;//Ⱥڽڵ protected: vector<int> nodes;//ڵ㼯 }; #endif
Python
UTF-8
281
2.75
3
[]
no_license
import os path="./plik.txt" with open(path,"w") as f: f.write("Ciemnosc widze za oknem i wgl") def fun(path): with open(path,"r") as f: text=f.read() ilosc_slow=len(text.split()) print("Ilosc slow:",ilosc_slow) result=os.path.isfile(path) and fun(path)
TypeScript
UTF-8
2,261
2.84375
3
[ "MIT" ]
permissive
import { ref, onUnmounted, Ref } from "../api"; import { PASSIVE_EV, NO_OP, isClient } from "../utils"; export interface BroadcastMessageEvent<T> extends MessageEvent { readonly data: T; } export interface BroadCastChannelReturn<T> { supported: boolean; data: Ref<T | null>; messageEvent: Ref<MessageEvent | null>; errorEvent: Ref<MessageEvent | null>; errored: Ref<boolean>; isClosed: Ref<boolean>; send: (data: T) => void; close: Function; addListener: ( cb: (ev: BroadcastMessageEvent<T>) => void, options?: boolean | AddEventListenerOptions ) => void; } export function useBroadcastChannel<T = any>( name: string, onBeforeClose?: Function ): BroadCastChannelReturn<T> { const supported = isClient && "BroadcastChannel" in self; const data = ref<T | null>(null) as Ref<T | null>; const messageEvent = ref<MessageEvent | null>( null ) as Ref<MessageEvent | null>; const errorEvent = ref<MessageEvent | null>(null) as Ref<MessageEvent | null>; const errored = ref(false); const isClosed = ref(false); let send: (data: T) => void = NO_OP; let close: Function = NO_OP; let addListener: ( cb: (ev: BroadcastMessageEvent<T>) => void, options?: boolean | AddEventListenerOptions ) => void = NO_OP; /* istanbul ignore else */ if (supported) { const bc = new BroadcastChannel(name); bc.addEventListener( "messageerror", e => { errorEvent.value = e; errored.value = true; }, PASSIVE_EV ); bc.addEventListener( "message", ev => { messageEvent.value = ev; data.value = ev.data; }, PASSIVE_EV ); send = d => bc.postMessage(d); close = () => { bc.close(); isClosed.value = true; }; addListener = (cb, o) => { bc.addEventListener("message", cb, o); onUnmounted(() => bc.removeEventListener("message", cb)); }; onUnmounted(() => { onBeforeClose && onBeforeClose(); close(); }); } else { if (__DEV__) { console.warn("[BroadcastChannel] is not supported"); } } return { supported, data, messageEvent, errorEvent, errored, isClosed, send, close, addListener }; }
C
UTF-8
413
3.5
4
[]
no_license
#include "lists.h" /** * get_dnodeint_at_index - returns specified node * @head: pointer to head of the LL * @index: position of the required node * * Return: Specified node is returned */ dlistint_t *get_dnodeint_at_index(dlistint_t *head, unsigned int index) { unsigned int i = 0; while (head != NULL) { if (i == index) { return (head); } head = head->next; i += 1; } return (NULL); }