text
stringlengths
27
775k
# -*- coding: utf-8 -*- from __future__ import unicode_literals import sys __author__ = 'luckydonald' if sys.version < '3': # python 2.7 text_type = unicode binary_type = str native_type = binary_type unicode_type = text_type # because I can't remember to use text_type long_int = long def to_native(x): return to_binary(x) # end def else: # python 3 text_type = str binary_type = bytes native_type = text_type unicode_type = text_type long_int = int def to_native(x): return to_unicode(x) # end def # end if def to_binary(x): if isinstance(x, text_type): return x.encode("utf-8") elif isinstance(x, binary_type): return x else: return to_binary(str(x)) # str() can fail. # do i need bytes() here with py3 (because ascii and stuff?) ? # end if # end def def to_unicode(x): if isinstance(x, binary_type): return x.decode("utf-8") elif isinstance(x, text_type): return x else: return to_unicode(str(x)) # str() can fail. # end if # end def
package com.slemjet.simple; import org.junit.jupiter.api.Test; class CompletableFutureSamplerTest { @Test void runExample() { CompletableFutureSampler completableFutureSampler = new CompletableFutureSampler(); completableFutureSampler.runExample(); } }
import requireAll from 'require-all'; /** * Loads the policies defined on the specified path. When loading, the policy * objects are added to an object. * * @param pathName */ export const loadPolicies = (pathName) => { const policies = {}; const policiesObj = requireAll(pathName); Object.keys(policiesObj).forEach((policy) => { policies[policy] = policiesObj[policy].default ? policiesObj[policy].default : policiesObj[policy]; }); return policies; };
class Manga < ApplicationRecord has_many :manga_genres has_many :chapters has_many :genres, through: :manga_genres validates_presence_of :name, :cover_art, :author validates_uniqueness_of :name end
window.addEventListener("contextmenu",function(event){ event.preventDefault(); let x = event.offsetX + "px"; let y = event.offsetY + "px"; let contextmenu = document.querySelector("#contextmenu"); contextmenu.style.top = y; contextmenu.style.left = x; contextmenu.classList.add("active"); }); window.addEventListener("click",function(event){ let contextmenu = document.querySelector("#contextmenu"); contextmenu.classList.remove("active"); });
module PlayerRefresher def self.refresh_players Player.all.each do |player| player.update_attribute(:potential_p2p, "0") case player.player_acc_type when "Reg" ehp = F2POSRSRanks::Application.config.ehp_reg when "HCIM", "IM" ehp = F2POSRSRanks::Application.config.ehp_iron when "UIM" ehp = F2POSRSRanks::Application.config.ehp_uim end uri = URI.parse("http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player=#{player.player_name}") all_stats = uri.read.split(" ") total_ehp = 0.0 F2POSRSRanks::Application.config.skills.each.with_index do |skill, skill_idx| skill_lvl = all_stats[skill_idx].split(",")[1].to_f skill_xp = all_stats[skill_idx].split(",")[2].to_f if skill != "p2p" and skill != "overall" and skill != "lms" player.update_attribute(:"#{skill}_lvl", skill_lvl) player.update_attribute(:"#{skill}_xp", skill_xp) skill_ehp = 0.0 skill_tiers = ehp["#{skill}_tiers"] skill_xphrs = ehp["#{skill}_xphrs"] last_skill_tier = 0.0 skill_tiers.each.with_index do |skill_tier, tier_idx| skill_tier = skill_tier.to_f skill_xphr = skill_xphrs[tier_idx].to_f if skill_xphr != 0 and skill_tier < skill_xp if (tier_idx + 1) < skill_tiers.length and skill_xp >= skill_tiers[tier_idx + 1] skill_ehp += (skill_tiers[tier_idx+1].to_f - skill_tier)/skill_xphr else skill_ehp += (skill_xp.to_f - skill_tier)/skill_xphr end end end player.update_attribute(:"#{skill}_ehp", skill_ehp.round(2)) total_ehp += skill_ehp.round(2) elsif skill == "p2p" and skill_xp != 0 player.update_attribute(:potential_p2p, player.potential_p2p.to_f + skill_xp.to_f) end end player.update_attribute(:overall_ehp, total_ehp.round(2)) end #redirect_to players_path, notice: 'All players were successfully updated.' end end
# About the `yanom-dev-deb10-slim-buster` Docker Image This Dockerfile will - Build an image based off an official python image - Uses the YANOM source code to build a pyinstaller package - Moves the package into a folder called `yanom`, adds a `data` directory to it and a copy of `config.ini` - Creates a tarball of the yanom folder This docker file is used along with the `yanom-prod-deb10-slim-buster` dockerfile to produce a deployable docker image. There is a script `scripts/build-docker-image.sh` that will automate the process ## Additional files in this folder `.dockerignore` can be used to minimise the amount copied to the image `yanom.spec` is a file that is used by Pyinstaller inside the docker image. Note- a generic `yanom.spec` can not be created on the fly as Pyinstaller can not find `pyfiglets` or Modifications are in the datas line and 3 lines related to hidden imports # Modification 1 Add value to `datas` to find the `pyfiglet` fonts ``` datas=[('/usr/local/lib/python3.9/site-packages/pyfiglet', './pyfiglet')], ``` # Modification 2 Add an entry for hidden import. The module `pandas.plotting._matplotlib` was not located during builds. At the top of the spec file add ``` from PyInstaller.utils.hooks import collect_submodules hidden_imports_pandas=collect_submodules('pandas.plotting._matplotlib') ``` And in the analysis section set `hiddenimports` to ``` hiddenimports=hidden_imports_pandas, ```
import Reflux from 'reflux'; export default Reflux.createActions({ evaluateCell: {asyncResult: true}, startKernel: {asyncResult: true}, stopKernel: {asyncResult: true}, killKernel: {asyncResult: true} })
package main import ( "flag" "fmt" "log" "os" "os/signal" "strings" "syscall" "github.com/Shopify/sarama" "github.com/bsm/sarama-cluster" ) var ( groupID = flag.String("group", "", "REQUIRED: The shared consumer group name") brokerList = flag.String("brokers", os.Getenv("KAFKA_PEERS"), "The comma separated list of brokers in the Kafka cluster") topicList = flag.String("topics", "", "REQUIRED: The comma separated list of topics to consume") offset = flag.String("offset", "newest", "The offset to start with. Can be `oldest`, `newest`") verbose = flag.Bool("verbose", false, "Whether to turn on sarama logging") logger = log.New(os.Stderr, "", log.LstdFlags) ) func main() { flag.Parse() if *groupID == "" { printUsageErrorAndExit("You have to provide a -group name.") } else if *brokerList == "" { printUsageErrorAndExit("You have to provide -brokers as a comma-separated list, or set the KAFKA_PEERS environment variable.") } else if *topicList == "" { printUsageErrorAndExit("You have to provide -topics as a comma-separated list.") } // Init config config := cluster.NewConfig() if *verbose { sarama.Logger = logger } else { config.Consumer.Return.Errors = true config.Group.Return.Notifications = true } switch *offset { case "oldest": config.Consumer.Offsets.Initial = sarama.OffsetOldest case "newest": config.Consumer.Offsets.Initial = sarama.OffsetNewest default: printUsageErrorAndExit("-offset should be `oldest` or `newest`") } // Init consumer, consume errors & messages consumer, err := cluster.NewConsumer(strings.Split(*brokerList, ","), *groupID, strings.Split(*topicList, ","), config) if err != nil { printErrorAndExit(69, "Failed to start consumer: %s", err) } defer consumer.Close() // Create signal channel sigchan := make(chan os.Signal, 1) signal.Notify(sigchan, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM) // Consume all channels, wait for signal to exit for { select { case msg, more := <-consumer.Messages(): if more { fmt.Fprintf(os.Stdout, "%s/%d/%d\t%s\n", msg.Topic, msg.Partition, msg.Offset, msg.Value) consumer.MarkOffset(msg, "") } case ntf, more := <-consumer.Notifications(): if more { logger.Printf("Rebalanced: %+v\n", ntf) } case err, more := <-consumer.Errors(): if more { logger.Printf("Error: %s\n", err.Error()) } case <-sigchan: return } } } func printErrorAndExit(code int, format string, values ...interface{}) { fmt.Fprintf(os.Stderr, "ERROR: "+format+"\n\n", values...) os.Exit(code) } func printUsageErrorAndExit(format string, values ...interface{}) { fmt.Fprintf(os.Stderr, "ERROR: "+format+"\n\n", values...) flag.Usage() os.Exit(64) }
package com.github.arekolek.phone import android.app.Application import timber.log.Timber import net.gotev.uploadservice.UploadService; import net.gotev.uploadservice.Logger; import net.gotev.uploadservice.BuildConfig class App : Application() { override fun onCreate() { super.onCreate() Timber.plant(Timber.DebugTree()) UploadService.NAMESPACE = BuildConfig.APPLICATION_ID; // Set upload service debug log messages level Logger.setLogLevel(Logger.LogLevel.DEBUG); } }
declare module "react-custom-scrollbars" { declare type PositionValues = { top: number, left: number, clientWidth: number, clientHeight: number, scrollWidth: number, scrollHeight: number, scrollLeft: number, scrollTop: number, ... }; declare type Props = { onScroll?: (event: SyntheticUIEvent<*>) => void, onScrollFrame?: (values: PositionValues) => void, onScrollStart?: () => void, onScrollStop?: () => void, onUpdate?: (values: PositionValues) => void, renderView?: React$StatelessFunctionalComponent<any>, renderTrackHorizontal?: React$StatelessFunctionalComponent<any>, renderTrackVertical?: React$StatelessFunctionalComponent<any>, renderThumbHorizontal?: React$StatelessFunctionalComponent<any>, renderThumbVertical?: React$StatelessFunctionalComponent<any>, hideTracksWhenNotNeeded?: boolean, autoHide?: boolean, autoHideTimeout?: number, autoHideDuration?: number, thumbSize?: number, thumbMinSize?: number, universal?: boolean, autoHeight?: boolean, autoHeightMin?: number | string, autoHeightMax?: number | string, ... }; declare export default class Scrollbars extends React$Component<Props> { scrollTop(top: number): void; scrollLeft(left: number): void; scrollToTop(): void; scrollToBottom(): void; scrollToLeft(): void; scrollToRight(): void; getScrollLeft(): number; getScrollTop(): number; getScrollWidth(): number; getScrollHeight(): number; getClientWidth(): number; getClientHeight(): number; getValues(): PositionValues; } }
/** * */ package org.pimslims.bioinf.targets; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.StringTokenizer; import org.pimslims.lab.Util; /** * @author Petr Troshin */ @Deprecated // no longer supported public class SwissProtToPIMS extends TargetImporter { /** * Class designed to upload the SwissProt entries from files to the PIMS Targets database. Class reads * appropriate fields from SwissProt file and puts is to the PIMS database. * * @author Petr Troshin <br> * Created on 28.09.2005 */ /** * <p> * Fields mapping: * * <PRE> * EBI TT vs SwissProt mappings * additionalRemarks = DE -Description. * annotationUrl = link to SwissProt file * database = &quot;SWISSPROT&quot;; * databaseID = AC- Accession number(s) * proteinName = GN- This line contains the name(s) of the gene(s) that encode for the stored protein sequence. * species = OS - Organism species * tagretID = next from 1 * workpackage = 3A see KW field - Keywords. * DR - Database cross-references. * * </PRE> */ /** * Constructor for SwissProtToPIMS * * @param dataOwner */ public SwissProtToPIMS(final String dataOwner) { super(dataOwner); } /** * Path to the directory contains swissProt files */ static final String dirPath = "d:/temp/MAN_Targets/old"; /** * Targets counter */ private static int count; /** * Total number of objects counter */ public static int objCounter; /** * If true - write statistics or log about the progress to out. */ public static final int LogInfo = 0; public static final int LogDebug = 1; public static final int collectStatistic = 2; public static LogWriter log = null; /** * Method performs all the work Load SwissProt file Gets appropriate fields from the annotation Clean this * fields from redundant and unsuitable information * * @see UMTargetsRetrieval * @see UMTargetsRetrieval#getWorkPackage(String) * * public void parse(final File swissProtfile) { BufferedReader br = null; try { // create a buffered * reader to read the sequence file br = new BufferedReader(new FileReader(swissProtfile)); } catch * (final FileNotFoundException ex) { // can't find specified file ex.printStackTrace(); * System.exit(-1); } * * // read the GenBank File final SequenceIterator sequences = SeqIOTools.readSwissprot(br); * * // iterate through the sequences while (sequences.hasNext()) { try { * * final Sequence seq = sequences.nextSequence(); * * final Annotation seqAn = seq.getAnnotation(); * * * // System.out.println("Start parsing Citation: " + // System.currentTimeMillis()); * this.writeCitation(seqAn.getProperty(ReferenceAnnotation.class)); // * System.out.println("Stop parsing Citation: " + // System.currentTimeMillis()); * * // The name of the file is the DB name of the protein. String fname = swissProtfile.getName(); * fname = fname.substring(0, fname.indexOf(".")); * * super.updateUMTarget(fname); * * this.dbNamePrms.put(DbNameAttr.name, "SWISSPROT"); this.dbRefPrms.put(DbRefAttr.code, ((ArrayList) * seqAn.getProperty("swissprot.accessions")).get(0)); // getAccession( // * (String)seqAn.getProperty("AC") // )); * * this.naturalSrcPrms.put(NaturalSourceAttr.ncbiTaxonomyId, SwissProtToPIMS.getTaxId((String) * seqAn.getProperty("OX"))); // * this.naturalSrcPrms.put(NaturalSourceAttr.organismName, * ServletTargetCreator.makeString(seqAn.getProperty("OS"), " ")); // * * * // TODO Change this! final String sp = ServletTargetCreator.makeString(seqAn.getProperty("OS"), * " "); this.naturalSrcPrms.put(NaturalSourceAttr.species, sp.length() > 80 ? sp.substring(0, 79) : * sp); * * this.moleculePrms.put(MoleculeAttr.molType, "protein"); * this.moleculePrms.put(MoleculeAttr.seqString, seq.seqString()); // System.out.println("Mol name: " * + getProtName( // makeString(seqAn.getProperty("GN")) ) ) ; * * this.moleculePrms.put(MoleculeAttr.name, PIMSTargetWriter.getUniqueMolComponentName( * SwissProtToPIMS.getProtName(ServletTargetCreator.makeString(seqAn.getProperty("GN"), " ")), 0, * TargetImporter.molNames)); * * if (seqAn.containsProperty("CC")) { this.moleculePrms .put(MoleculeAttr.details, * ServletTargetCreator.makeString(seqAn.getProperty("CC"), " ")); } * this.moleculePrms.put(MoleculeAttr.keywords, Util.makeCollection(seqAn.getProperty("KW"))); * * this.targetPrms.put(TargetAttr.functionDescription, seqAn.getProperty("DE")); * SwissProtToPIMS.count = SwissProtToPIMS.count++; this.targetPrms.put(TargetAttr.NAME, * SwissProtToPIMS.getUMTargetID(SwissProtToPIMS.count)); this.targetPrms.put(TargetAttr.localName, * SwissProtToPIMS.getSwissProtID((String) seqAn.getProperty("ID"))); * this.targetPrms.put(TargetAttr.whyChosen, "Its one of MPSi selected targets"); * this.targetPrms.put(TargetAttr.functionDescription, * ServletTargetCreator.makeString(seqAn.getProperty("DE"), " ")); // was * targetPrms.put(TargetAttr.proteinName, getProtName( // makeString(seqAn.getProperty("GN")))); // * duplicate call to // GN ! * * System.out .println(UMTargetsRetrieval.getWorkPackage(swissProtfile.getName()).substring(0, 4)); * this.targetGroupPrms.put(TargetGroupAttr.shortName, * (UMTargetsRetrieval.getWorkPackage(swissProtfile.getName()).substring(0, 4)).trim()); * this.targetGroupPrms.put(TargetGroupAttr.completeName, * UMTargetsRetrieval.getWorkPackage(swissProtfile.getName())); * this.targetGroupPrms.put(TargetGroupAttr.groupingType, "TCDB category"); * * // Annotation final FileInfoHolder fHolder = new FileInfoHolder(swissProtfile.getName(), * swissProtfile.getAbsolutePath(), TargetAttr.class.getName()); this.filePrms.add(fHolder); * this.putToDb(); * * } catch (final BioException ex) { // not in SwissProt format this.ex.printStackTrace(); } catch * (final NoSuchElementException ex) { // request for more sequence when there isn't any * this.ex.printStackTrace(); } } } */ /** * Make a Target ID, in general format is: "UM" + 4 digits * * @param targetNumber * @return target ID */ @Deprecated // obsolete public static String getUMTargetID(final int targetNumber) { String id = "UM"; if (targetNumber < 10) { id += "000" + targetNumber; } if (targetNumber >= 10 && targetNumber < 100) { id += "00" + targetNumber; } if (targetNumber >= 100 && targetNumber < 1000) { id += "0" + targetNumber; } if (targetNumber >= 1000 && targetNumber < 10000) { id += targetNumber; } if (targetNumber > 10000) { id = Integer.toString(targetNumber); } return id; } public static String getTaxId(String OX) { OX = OX.trim(); final int indx = OX.toLowerCase().indexOf("ncbi_taxid"); if (indx >= 0) { // TODO check that OX contains only digits return OX.substring(11, OX.length() - 1); } return OX; } /** * Remove any additional DB references. * * @param accession * @return the first DB reference */ public static String getAccession(final String accession) { final int ind = accession.indexOf(";"); if (ind < 0) { return accession; } return accession.substring(0, ind).trim(); } /** * Example data NRTA_ANASP STANDARD; PRT; 440 AA. * * @param ID - full ID string * @return first part of ID - NRTA_ANASP */ public static String getSwissProtID(final String ID) { return ID.trim().substring(0, ID.indexOf(";")); } /** * Remove all additional information from "GN" field * * @param gnline "GN" lines * @return protein name */ public static String getProtName(final String gnline) { final int nidx = gnline.toLowerCase().indexOf("name"); if (nidx < 0) { return gnline; } final int eq = gnline.indexOf("="); final int end = gnline.indexOf(";"); return gnline.substring(eq + 1, end); } /** * Make a Target ID, in general format is: "UM" + 4 digits * * @param targetNumber * @return target ID * * private static String getTargetID(int targetNumber) { String id = "UM"; if(targetNumber < 10) { * id += "000" + targetNumber; } if(targetNumber >= 10 && targetNumber < 100) { id += "00" + * targetNumber; } if(targetNumber >= 100 && targetNumber < 1000) { id += "0" + targetNumber; } * if(targetNumber >= 1000 && targetNumber < 10000) { id += targetNumber; } if(targetNumber > * 10000) { id = Integer.toString(targetNumber); } return id; } */ /** * Data examples: Galinier A., Bleicher F.; * * @param RA - could be ArrayList in case of multiple lines RA or single String String usually contains * the list of authors which must be separated by comma. * @return Collection of HashMaps of person parameters (!) There is only the first author created * temporary see the code for a change */ static void parseRA(final Object RA, final Citation citationParam) { final Collection list = Util.makeCollection(RA); for (final Iterator iter = list.iterator(); iter.hasNext();) { final String elem = (String) iter.next(); final StringTokenizer st = new StringTokenizer(elem, ","); if (st.hasMoreTokens()) { // @TODO note: while - to import all // authors change here! final String author = st.nextToken().trim(); final HashMap person = new HashMap(); final int spaceIndx = SwissProtToPIMS.findSpace(author, author.indexOf("."), false); person.put(PersonAttr.familyName, author.substring(0, spaceIndx)); // System.out.println("AUTHOR: " + author); final ArrayList initials = SwissProtToPIMS.getInitials(author.substring(spaceIndx)); person.put(PersonAttr.middleInitials, initials); citationParam.personsPrms.add(person); } } } /** * Determine the type of Citation and parse the parameters of it * * @param RLine * @param citationParam */ static void parseRL(final String RLine, final Citation citationParam) { // Try do determine Citation type final String rl = RLine.trim(); if (rl.startsWith("Submitted")) { citationParam.setCitationType(Citation.THESIS_CITATION); SwissProtToPIMS.parseSubmittedCitation(rl, citationParam); } else if (rl.startsWith("(In)")) { citationParam.setCitationType(Citation.BOOK_CITATION); /* TODO code this later */ // parseBookCitation(rl, citationParam); } else if (rl.startsWith("Thesis")) { citationParam.setCitationType(Citation.THESIS_CITATION); SwissProtToPIMS.parseThesisCitation(rl, citationParam); } else if (rl.startsWith("Unpublished")) { throw new UnsupportedOperationException( "The 'unpublished' citation type has not been implemented yet. "); } else if (rl.startsWith("(er)")) { throw new UnsupportedOperationException("The 'er' (Electronic publications) " + "citation type has not been implemented yet. "); } else if (rl.startsWith("Patent number")) { throw new UnsupportedOperationException("The 'Parent citation' " + "citation type has not been implemented yet. "); } // Lets think that this is JournalCitation else { citationParam.setCitationType(Citation.JOURNAL_CITATION); if (!SwissProtToPIMS.parseJournalCitation(rl, citationParam)) { System.out.println("Could not make out a data type for the Citation \n" + rl + "\n possible cause - improper formatted citation "); } } } /** * Parse Journal Citation and set it's parameters Data format: J. Bacteriol. 173:2665-2672(1991). * * @param rl - rl line * @param citationParam - TargetImporter.Citation * @return true if citation type was correct and citation was parsed successfully false otherwise */ static boolean parseJournalCitation(final String rl, final Citation citationParam) { final int colonInd = rl.indexOf(":"); if (colonInd != -1 && Character.isDigit(rl.charAt(colonInd - 1)) && colonInd >= 0 && rl.indexOf("-") >= 0) { final int leftIndx = SwissProtToPIMS.findIndex(rl, colonInd, false); final String volume = rl.substring(leftIndx + 1, colonInd); final String rightpart = rl.substring(colonInd); final int dashIndx = rightpart.indexOf("-"); final String fromPage = rightpart.substring(1, dashIndx).trim(); final int lbracketIndx = rightpart.indexOf("("); final String toPage = rightpart.substring(rightpart.indexOf("-") + 1, lbracketIndx).trim(); final String yearString = rightpart.substring(lbracketIndx + 1, rightpart.indexOf(")")); final String jTitle = rl.substring(0, leftIndx).trim(); /* * System.out.println("TITLE : " + jTitle); System.out.println("VOLUM : " + volume); * System.out.println("FROM P: " + fromPage); System.out.println("TO P: " + toPage); * System.out.println("YEAR : " + yearString); */ citationParam.citationPrms.put(JournalCitationAttr.title, jTitle); citationParam.citationPrms.put(JournalCitationAttr.volume, volume); citationParam.citationPrms.put(JournalCitationAttr.firstPage, fromPage); citationParam.citationPrms.put(JournalCitationAttr.lastPage, toPage); final Integer year = SwissProtToPIMS.getInteger(yearString); if (year != null) { citationParam.citationPrms.put(JournalCitationAttr.year, year); } return true; } return false; } /** * Method to parse "Submitted" type of citation treat it as Thesis citation. Data example: Submitted * (OCT-1995) to the EMBL/GenBank/DDBJ databases * * @param rl * @param citationParam * @return */ static void parseSubmittedCitation(final String rl, final Citation citationParam) { String yearString = rl.substring(rl.indexOf("("), rl.indexOf(")")).trim(); final int lyearIndx = SwissProtToPIMS.findIndex(yearString, yearString.length() - 1, false); yearString = yearString.substring(lyearIndx + 1, yearString.length()); // System.out.println("YEAR: " + yearString); citationParam.citationPrms.put(ThesisCitationAttr.details, rl); final Integer year = SwissProtToPIMS.getInteger(yearString); if (year != null) { citationParam.citationPrms.put(ThesisCitationAttr.year, year); } } static Integer getInteger(final String intString) { Integer year = null; try { year = Integer.decode(intString); } catch (final NumberFormatException e) { // Ok could not parse year. Carry on e.printStackTrace(); } return year; } /** * Parse thesis citation to ThesisCitation class. Data example: Thesis (Year), Institution_name, Country. * * @param rl * @param citationParam * @return */ static boolean parseThesisCitation(final String rl, final Citation citationParam) { final StringTokenizer st = new StringTokenizer(rl, ","); if (st.hasMoreTokens()) { final String thName_year = st.nextToken(); final int lbrindx = thName_year.indexOf("("); final int rbrindx = thName_year.indexOf(")"); Integer year = null; String title = ""; if (lbrindx != 0 && rbrindx != 0 && lbrindx > rbrindx) { title = thName_year.substring(0, lbrindx - 1); citationParam.citationPrms.put(ThesisCitationAttr.title, title); final String yearStr = thName_year.substring(lbrindx, rbrindx); year = SwissProtToPIMS.getInteger(yearStr); if (year != null) { citationParam.citationPrms.put(ThesisCitationAttr.year, year); } else { citationParam.citationPrms.put(ThesisCitationAttr.details, yearStr); } } else { return false; } } if (st.hasMoreTokens()) { final String institutionName = st.nextToken(); citationParam.citationPrms.put(ThesisCitationAttr.institution, institutionName); } if (st.hasMoreTokens()) { final String country = st.nextToken(); citationParam.citationPrms.put(ThesisCitationAttr.country, country); } return true; } /** * Find the first not digit in a String starting from "from" position to the right(true) or to the left * (false) * * @param rl * @param from * @param toRight * @return index in a String */ static int findIndex(final String rl, int from, final boolean toRight) { char c; do { if (toRight) { from = from + 1; } else { from = from - 1; } c = rl.charAt(from); // System.out.println("CHAR: " + c); } while (Character.isDigit(c)); return from; } /** * Find the first not digit in a String starting from "from" position to the right(true) or to the left * (false) * * @param rl * @param from * @param toRight * @return index in a String */ static int findSpace(final String rl, int from, final boolean toRight) { char c; do { if (toRight) { from = from + 1; } else { from = from - 1; } c = rl.charAt(from); // System.out.println("CHAR: " + c); } while (Character.isWhitespace(c)); return from; } static ArrayList getInitials(String author) { final ArrayList initials = new ArrayList(); // Last author names may have ";" - it should be deleted final int indx = author.indexOf(";"); if (indx >= 0) { final StringBuffer auth = new StringBuffer(author); auth.deleteCharAt(indx); author = auth.toString(); } final StringTokenizer st = new StringTokenizer(author, "."); // Put initials into collection while (st.hasMoreTokens()) { final String init = st.nextToken().trim(); initials.add(init); // System.out.println("Initials: " + init); } return initials; } /** * Upload Manchester targets with changed state (all new) These targets was selected during the data * analysis. * * private static void getAddedTargets() { // Upload new Man targets File f = new * File("D:/MPSI_web/added_manchester_targets.txt"); try { BufferedReader bf = new BufferedReader(new * FileReader(f)); String line; while((line = bf.readLine()) != null) { String data = * UMTargetsRetrieval.getSwissProtEntry(line.trim()); System.out.println("SEQ: " + data ); * Util.writeToFile(data, "D:/temp/mpsi/added/" + line.trim()); } } catch (FileNotFoundException e) { * e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } */ /** * Method iterate other all files in the directory and construct SwissProtToEBITartes entities. After put * them to the database. For database connection details and etc.. * * @see EBITarget args[] - is not used * * public static void main(final String[] args) { final File[] files = * Util.getAllFiles(SwissProtToPIMS.dirPath); SwissProtToPIMS.log = new * LogWriter(SwissProtToPIMS.collectStatistic); * SwissProtToPIMS.log.printLog("TOTAL number of SWISSPROT files: " + files.length, * SwissProtToPIMS.LogInfo); * * for (int i = 0; i < files.length; i++) { SwissProtToPIMS.log.printLog("", * SwissProtToPIMS.LogInfo); SwissProtToPIMS.log.printExact("Current file: " + files[i], * SwissProtToPIMS.collectStatistic); final Date sd = new Date(System.currentTimeMillis()); * SwissProtToPIMS.log.printExact("Start processing time: " + sd, SwissProtToPIMS.collectStatistic); * SwissProtToPIMS.log.printExact("Objects created so far: " + SwissProtToPIMS.objCounter, * SwissProtToPIMS.collectStatistic); * * SwissProtToPIMS.count = i; new SwissProtToPIMS(files[i]); * * final Date ed = new Date(System.currentTimeMillis()); * SwissProtToPIMS.log.printExact("Full parsing took: " + (ed.getTime() - sd.getTime()) + " ms", * SwissProtToPIMS.collectStatistic); } } */ }
#include "TreeBottomUp.hh" #include <iostream> TreeBottomUp::TreeBottomUp(const Graph& G) : AbstractBottomUp(G) { TWarr = new std::map<VSet, int>*[VSet::maxNumVerts]; } TreeBottomUp::~TreeBottomUp() { delete[] TWarr; } void TreeBottomUp::beginIter() { iter = TWarr[currentLayer-1]->begin(); layerEnd = TWarr[currentLayer-1]->end(); S = iter->first; r = iter->second; } bool TreeBottomUp::iterDone() { return iter == layerEnd; } void TreeBottomUp::iterNext() { //Erase elements as we process them iter = TWarr[currentLayer - 1]->erase(iter); if (iter != layerEnd) { S = iter->first; r = iter->second; } } int TreeBottomUp::TW(int layer, VSet S) { return (*TWarr[layer])[S]; } void TreeBottomUp::updateTW(int layer, VSet S, int tw) { auto searchInfo = (*TWarr[layer]).find(S); if (searchInfo == (*TWarr[layer]).end()) { (*TWarr[layer])[S] = tw; } else { (*TWarr[layer])[S] = std::min(searchInfo->second, tw); } } void TreeBottomUp::beginLayer(int layer) { TWarr[layer] = new std::map<VSet, int>(); } void TreeBottomUp::endLayer(int layer) { std::cout << "TW i size: " << currentLayer << " " << TWarr[currentLayer]->size() << "\n"; delete TWarr[layer]; } int TreeBottomUp::finalResult(int finalLayer, VSet SStart) { auto searchInfo = TWarr[finalLayer]->find(SStart); if (searchInfo == TWarr[finalLayer]->end()) { return globalUpperBound; } return searchInfo->second; } int TreeBottomUp::numStored() { return TWarr[currentLayer]->size() + TWarr[currentLayer-1]->size(); }
package com.anadathur.elastic.easymapping import javax.lang.model.element.Modifier import com.squareup.javapoet.MethodSpec.Builder import com.squareup.javapoet._ class DefaultMappingGen extends TypeGenerator { import scala.collection.JavaConversions._ val generators = List( generateMappingType _, generateDefaultMappingType _, generateMappingTypeProperty _, generateDefaultMappingTypeProperty _ ) override def apply(config: Config): List[TypeSpec] = { generators.map(_.apply(config)).toList } def generateDefaultMappingType(config: Config): TypeSpec = { val params = getParamsOfMappingType(config) val builder = TypeSpec.classBuilder("DefaultMappingType") .addModifiers(Modifier.PUBLIC) .addSuperinterface(config.mappingTypeClass) .addFields(params.values.map {_.fieldBuilder.addModifiers(privFinal: _*).build() }.toList) val constructorParams = params.values.map { _.paramBuilder.build() } val codeBlockBuilder = CodeBlock.builder() for (param <- params.values) { codeBlockBuilder.addStatement(s"this.${param.name} = ${param.name}") } val constructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameters(constructorParams.toList) .addCode(codeBlockBuilder.build()) val methods = getMethodBuilders(params).map { case (name, typeName, bldr) => bldr.addCode(CodeBlock.builder().addStatement(s"return $name").build()) .build() } val hashSet: ClassName = ClassName.get("java.util", "HashSet") val simpleMethod = MethodSpec.methodBuilder("isSimpleType") .returns(TypeName.BOOLEAN) .addModifiers(Modifier.PUBLIC) .addStatement("$T set = new $T<>()", hashSet, hashSet) Array("string", "integer", "long", "float", "double", "boolean", "date").foreach {name => simpleMethod.addStatement("set.add($S)", name) } simpleMethod.addStatement("return set.contains(this.typeName)") builder.addMethod(constructorBuilder.build()) .addMethods(methods.toList) .addMethod(simpleMethod.build()) .build() } def getMethodBuilders(params: Map[String, MetaParam]) = params.values.map { method => (method.name, method.typeName, method.methodBuilder) } def getMethodName(name: String, typeName: TypeName) = (if (typeName.equals(TypeName.BOOLEAN)) "is" else "get") + name.capitalize def generateMappingType(config: Config): TypeSpec = { val fields = List("string", "integer", "long", "float", "double", "boolean", "date", "binary", "object", "nested") .map { name => FieldSpec.builder(classOf[String], name.toUpperCase + "_TYPE") .addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL) .initializer("\"" + name + "\"") .build() } val builders: Iterable[(String, TypeName, Builder)] = getMethodBuilders(getParamsOfMappingType(config)) val builder = TypeSpec.interfaceBuilder("MappingType") .addModifiers(Modifier.PUBLIC) .addMethods(builders.map {_._3.addModifiers(Modifier.ABSTRACT, Modifier.PUBLIC).build()}.toList) .addMethod( MethodSpec.methodBuilder("isSimpleType") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(TypeName.BOOLEAN) .build() ) .addFields(fields) builder.build() } def generateMappingTypeProperty(config: Config): TypeSpec = { val methods = getMethodBuilders(getParamsOfMappingTypeParam(config)).map { case (name, tName, bldr) => bldr.addModifiers(pubAbs: _*).build() } TypeSpec.interfaceBuilder("MappingTypeProperty") .addModifiers(Modifier.PUBLIC) .addMethods(methods.toList) .build() } def generateDefaultMappingTypeProperty(config: Config): TypeSpec = { val param: Map[String, MetaParam] = getParamsOfMappingTypeParam(config) val methods = getMethodBuilders(param).map { case (name, tName, bldr) => bldr.addModifiers(Modifier.PUBLIC) .addStatement("return $N", name) .build() } val block = CodeBlock.builder() param.values.foreach { p => block.addStatement("this.$N = $N", p.name, p.name)} TypeSpec.classBuilder("DefaultMappingTypeProperty") .addModifiers(Modifier.PUBLIC) .addMethod( MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameters(param.values.map(_.paramBuilder.build()).toList) .addCode(block.build()) .build() ) .addFields(param.values.map(_.fieldBuilder.addModifiers(privFinal: _*).build()).toList) .addMethods(methods.toList) .build() } }
const graphql = require("graphql"); const types = require("./types.js"); const logic = require("./logic.js"); module.exports = { getTheme: { type: types.themeType, resolve: () => logic.getTheme(), }, getAllThemes: { type: new graphql.GraphQLList(types.themeType), resolve: (root, { a = {} }, context) => logic.getAllThemes(context), }, getLayout: { type: types.layoutType, resolve: () => logic.getLayout(), }, };
module Lib ( someFunc, doubleIt, doubleRange, rotateList ) where import Data.List import Data.Char import Data.String someFunc :: IO () someFunc = putStrLn "someFunc" doubleIt :: Int -> Int doubleIt x = x * 2 doubleRange :: Int -> [Int] doubleRange x = [x * 2 | x <- [1..10]] rotateList :: Int -> [a] -> [a] rotateList rotations list = zipWith const (drop rotations (cycle list)) list rotateList' :: Int -> [a] -> [a] rotateList' rotations list = take (length list) $ drop rotations (cycle list) modCheck x = filter (test) x where test x = mod x 2 == 0 filterByFirstLetter :: Char -> String -> [String] -> [String] filterByFirstLetter l name acc | name!!0 == l = name:acc | otherwise = acc upperNames :: String -> String upperNames (x:xs) = (toUpper x):xs
# Version 0.0.2 ## change log - 增加了数据下载 - 修正了Risk计算 - 增加了instrument - 增加了position的`market_value`和`value_percent`
# CASPR by Judith Bergadà Pijuan. ## Installation CASPR has been developed and tested under Linux and macOS. To install the tool, please follow the instructions: https://judithbergada.github.io/CASPR/installation/ ## Usage The detailed documentation showing how to use CASPR is available at: https://judithbergada.github.io/CASPR/usage/ Here you can see the input parameters as well as the outputs generated by the tool. ## Tutorial We have prepared a tutorial to help you to understand how to use CASPR: https://judithbergada.github.io/CASPR/tutorial/ In the tutorial, you will find two user cases which will show you everything you need in order to get started with the tool.
import 'package:flutter/services.dart'; import 'package:twitter_clone/views/resources/colors.dart'; class Graphical { static void setSystemUIOverlayStyle() { SystemChrome.setSystemUIOverlayStyle( SystemUiOverlayStyle( systemNavigationBarIconBrightness: Brightness.dark, systemNavigationBarColor: ProjectColors.white, statusBarBrightness: Brightness.light, statusBarColor: ProjectColors.transparent, statusBarIconBrightness: Brightness.dark, ), ); } static Future<void> setPreferredOrientations() { return SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, DeviceOrientation.landscapeRight, DeviceOrientation.landscapeLeft, ]); } }
--- region: MENA country: Libya name: المنظمة الليبية لحقوق العمال ومحاربة الفساد / Libyan Association for Workers' Rights and Fighting Corruption acronym: is_member: no_gndem_member_countries: regional_network: website: https://www.facebook.com/work17 ---
import os import click from keep import cli, utils @click.command('register', short_help='Register user over server.') @cli.pass_context def cli(ctx): """Register user over server.""" dir_path = os.path.join(os.path.expanduser('~'), '.keep', '.credentials') if os.path.exists(dir_path): if click.confirm('[CRITICAL] Reset credentials saved in ~/.keep/.credentials ?', abort=True): os.remove(dir_path) utils.register()
package com.ing.streaming.journal import akka.actor.ActorSystem import akka.testkit.{TestActorRef, TestKit} import com.ing.streaming.data.{Transaction, DataGenerator} import org.joda.time.{DateTime, Interval} import org.scalatest._ import scala.collection.mutable import scala.concurrent.duration._ import com.ing.streaming.data.Event import com.ing.streaming.data.JsonImplicits._ import spray.json._ class QueueTest extends TestKit(ActorSystem("clockQueueSystem")) with WordSpecLike with MustMatchers with BeforeAndAfterAll { /** * Generates data as input for our tests * @param total The total number of transactions to generate * @param interval The timespan of the transaction list */ def generateTransactionList(total: Int, interval: Interval) = { // Generate 5 times as less accounts as transactions val (_, transactions) = DataGenerator.generateData(total / 5, total, interval) assert(transactions.size == total) } override def afterAll { TestKit.shutdownActorSystem(system) } "A Queue actor" should { val senderActorRef = TestActorRef(new SocketSender("", 0)) val queueActorRef = TestActorRef(new Queue(100, senderActorRef)) val time = DateTime.now().getMillis val t = new Transaction(1, time, 1, out = false, 11, 22, 100.40f, "transaction1") /** * Queue works like this: * enqueue -> 3, 2, 1 -> dequeue * 3 was added last, and is last to be dequeued * 1 was added first, and is first to be dequeued */ "exhibit the following basic queue behavior" in { val queue = mutable.Queue.empty[Int] queue.enqueue(1) queue.enqueue(2) val i = queue.dequeue() assert(i == 1) assert(queue.size == 1) queue.enqueue(3) assert(queue.head == queue.front) assert(queue.last == 3) } "Do nothing when fetching from an empty queue" in { // An arbitrary date in the past queueActorRef ! Dequeue(DateTime.now().minusDays(1).getMillis, 0) expectNoMsg(10 millis) // An arbitrary date in the future queueActorRef ! Dequeue(DateTime.now().plusDays(1).getMillis, 0) expectNoMsg(10 millis) } "Enqueue an item to the queue" in { queueActorRef ! Enqueue(new Event(t.toJson.compactPrint)) assert(queueActorRef.underlyingActor.queue.size == 1) expectNoMsg(10 millis) queueActorRef ! Enqueue(new Event(t.toJson.compactPrint)) assert(queueActorRef.underlyingActor.queue.size == 2) expectNoMsg(10 millis) } "Dequeue an item from the queue" in { queueActorRef ! Dequeue(DateTime.now().getMillis, 0) assert(queueActorRef.underlyingActor.queue.size == 0) expectNoMsg(10 millis) queueActorRef ! Dequeue(DateTime.now().getMillis, 0) assert(queueActorRef.underlyingActor.queue.size == 0) expectNoMsg(10 millis) } "Enqueue multiple items to the queue" in { val queue = queueActorRef.underlyingActor.queue for (i <- 1 to 10) { val new_t = new Transaction(t.id, new DateTime(t.time).plusSeconds(i).getMillis, t.trantype, t.out, t.acc1, t.acc2, t.amount, t.descr) queueActorRef ! Enqueue(new Event(new_t.toJson.compactPrint)) } assert(queue.size == 10) val splitTime = new DateTime(t.time).plusSeconds(5).getMillis + 1 queueActorRef ! Dequeue(splitTime, 0) assert(queue.size == 5) assert(queue.front.time < queue.last.time) // Everything that is still in the queue must be after the split time assert(queue.head.time >= splitTime) assert(queue.last.time >= splitTime) } } }
import Test.Tasty import Test.Tasty.QuickCheck as QC import Text.Tarzan.Regex (RE, (<.>)) import qualified Text.Tarzan.Regex as RE import Control.Applicative import Data.Monoid import Data.Either main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Tests" [qcProps] newtype RC = RC (RE Char) instance Show RC where show (RC r) = "/" ++ RE.prettyRe r ++ "/ " ++ show r instance Arbitrary RC where arbitrary = RC <$> sized arbitrary' where arbitrary' n | n <= 0 = frequency [ (4, return RE.eps) , (4, return RE.anychar) , (4, RE.char <$> (arbitrary `suchThat` ((<=0xffff) . fromEnum))) , (1, return RE.empty) , (1, return RE.anything) ] | otherwise = oneof [ arbitrary' 0 , RE.append <$> arbitrary'' <*> arbitrary'' , RE.union <$> arbitrary'' <*> arbitrary'' , RE.kleene <$> arbitrary'' ] where arbitrary'' = arbitrary' (n `div` 2) infix 4 `eq` eq :: RE Char -> RE Char -> Property eq x y = counterexample (RE.prettyRe x ++ " `ne` " ++ RE.prettyRe y) (x `RE.eq` y) parsePrettied :: RC -> Property parsePrettied (RC re) = property $ isRight $ RE.parseRe (RE.prettyRe re) parsePrettyInvoluvitive :: RC -> Property parsePrettyInvoluvitive (RC re) = let (Right re') = RE.parseRe (RE.prettyRe re) in Right re' === RE.parseRe (RE.prettyRe re') parsePrettyEquivalent :: RC -> Property parsePrettyEquivalent (RC re) = let (Right re') = RE.parseRe (RE.prettyRe re) in re' `eq` re appendAssoc :: RC -> RC -> RC -> Property appendAssoc (RC a) (RC b) (RC c) = a <.> (b <.> c) `eq` (a <.> b) <.> c unionAssoc :: RC -> RC -> RC -> Property unionAssoc (RC a) (RC b) (RC c) = a <> (b <> c) `eq` (a <> b) <> c unionComm :: RC -> RC -> Property unionComm (RC a) (RC b) = a <> b `eq` b <> a distrib1 :: RC -> RC -> RC -> Property distrib1 (RC a) (RC b) (RC c) = a <.> (b <> c) `eq` (a <.> b) <> (a <.> c) distrib2 :: RC -> RC -> RC -> Property distrib2 (RC a) (RC b) (RC c) = (b <> c) <.> a `eq` (b <.> a) <> (c <.> a) appendIdentLeft :: RC -> Property appendIdentLeft (RC a) = RE.eps <.> a `eq` a appendIdentRight :: RC -> Property appendIdentRight (RC a) = a <.> RE.eps `eq` a unionIdentLeft :: RC -> Property unionIdentLeft (RC a) = RE.nothing <> a `eq` a unionIdentRight :: RC -> Property unionIdentRight (RC a) = a <> RE.nothing `eq` a nothingAppendLeft :: RC -> Property nothingAppendLeft (RC a) = RE.nothing <.> a `eq` RE.nothing nothingAppendRight :: RC -> Property nothingAppendRight (RC a) = a <.> RE.nothing `eq` RE.nothing unionIdemp :: RC -> Property unionIdemp (RC a) = a <> a `eq` a kleeneProps :: TestTree kleeneProps = testGroup "Kleene algebra laws" [ QC.testProperty "append is associative" appendAssoc , QC.testProperty "union is associtive" unionAssoc , QC.testProperty "union is commutative" unionComm , QC.testProperty "distributivity 1" distrib1 , QC.testProperty "distributivity 2" distrib2 , QC.testProperty "append left identity" appendIdentLeft , QC.testProperty "append right identity" appendIdentRight , QC.testProperty "union left identity" unionIdentLeft , QC.testProperty "union right identity" unionIdentRight , QC.testProperty "nothing left" nothingAppendLeft , QC.testProperty "nothing right" nothingAppendRight , QC.testProperty "union idempotent" unionIdemp ] qcProps :: TestTree qcProps = testGroup "QuickCheck properties" [ QC.testProperty "pretty . parse succeeds" parsePrettied , QC.testProperty "pretty . parse 'involutive" parsePrettyInvoluvitive , QC.testProperty "pretty . parse equivalent to id" parsePrettyEquivalent , kleeneProps ]
<?php namespace Salesfly\Salesfly\Entities; class DetailPurchase extends \Eloquent { protected $table = 'detailPurchases'; protected $fillable = ['producto','descuento', 'montoBruto', 'montoTotal', 'purchases_id', 'detPres_id', 'preProducto', 'preCompra', 'cantidad', 'preProductoDolar', 'preCompraDolar', 'montoBrutoDolar', 'montoTotalDolar' ]; public function detPres() { return $this->belongsTo('\Salesfly\Salesfly\Entities\DetPres'); } public function purchase() { return $this->belongsTo('\Salesfly\Salesfly\Entities\Purchase'); } }
/** * @brief Thread Test * @author Vic Chan * @date 2017-10-23 * */ #include <string> #include <vector> #include "./thread.h" struct message { int id; std::string content; message(int id, std::string content):id(id), content(content) {}; }; void handle(void* msg) { message* msg1 = (message* )msg; printf("id:%d msg:%s\n", msg1->id, msg1->content.c_str()); } using namespace Rina; int main(int argc, char* argv[]) { auto* manager = new ThreadManager; message* msg1 = new message(10, "hello"); message* msg2 = new message(4, "world"); message* msg3 = new message(50, "cpp"); manager->createThread(1, handle, (void* )msg1); manager->createThread(2, handle, (void* )msg2); manager->createThread(3, handle, (void* )msg3); char p = getchar(); return 0; }
# How to check heavy3 file consistency ## Full check sha256 of the full file should be `ffe30d8a63e1731e613b16ff8fd040d2946dba6a09823d7cc09d837570c55199` See full_check.py for az python impl. Takes from 10 to 30 sec. ## Minimal check, file size Not a full check, but tells if the creation process was interrupted (major cause of fails) File size is 1073741824 bytes See size_check.py ## Sampling tests TODO
use worker::*; mod utils; fn log_request(req: &Request) { console_log!( "{} - [{}], located at: {:?}, within: {}", Date::now().to_string(), req.path(), req.cf().coordinates().unwrap_or_default(), req.cf().region().unwrap_or("unknown region".into()) ); } #[event(fetch)] pub async fn main(req: Request, env: Env) -> Result<Response> { log_request(&req); // Optionally, get more helpful error messages written to the console in the case of a panic. utils::set_panic_hook(); // Optionally, use the Router to handle matching endpoints, use ":name" placeholders, or "*name" // catch-alls to match on specific patterns. The Router takes some data with its `new` method // that can be shared throughout all routes. If you don't need any shared data, use `()`. let router = Router::new(()); // Add as many routes as your Worker needs! Each route will get a `Request` for handling HTTP // functionality and a `RouteContext` which you can use to and get route parameters and` // Enviornment bindings like KV Stores, Durable Objects, Secrets, and Variables. router .get("/", |req, _| { let f = req.headers().get("CF-Connecting-IP"); let f = match f { Ok(ip) => ip, Err(error) => panic!("Problem opening the file: {:?}", error), }; Response::ok(f.unwrap_or_default()) }) .run(req, env) .await }
require 'active_support' require_relative 'touth/version' require_relative 'touth/store' require_relative 'touth/authenticator' require_relative 'touth/active_record_support' require_relative 'touth/action_controller_support' require_relative 'touth/middleware' require_relative 'touth/railtie' if defined? Rails # Touth #----------------------------------------------- module Touth class Configuration attr_accessor :access_token_lifetime, :client_secret_key, :password_field, :header_name, :allow_raise def initialize @access_token_lifetime = 60 * (24 * 60 * 60) # 60 days @client_secret_key = '' # use SecureRandom.hex(64) to generate one @password_field = :encrypted_password @header_name = 'X-Access-Token' @allow_raise = false end end class InvalidAccessTokenError < StandardError; end class << self def setup @config ||= Configuration.new yield @config if block_given? end def digest(data) @digest_method ||= OpenSSL::Digest.new 'sha256' OpenSSL::HMAC.digest @digest_method, self.client_secret_key, data end def get_resource_name(name) name.to_s.gsub('::', '_').underscore end def method_missing(method_name, *args, &block) if @config.respond_to? method_name @config.send method_name, *args, &block else super end end def respond_to?(method_name, include_private = false) @config.respond_to? method_name end end end # Setup #----------------------------------------------- Touth.setup # Load #----------------------------------------------- ActiveSupport.on_load(:action_controller) do extend Touth::ActionControllerSupport::ClassMethods include Touth::ActionControllerSupport::InstanceMethods end ActiveSupport.on_load(:active_record) do extend Touth::ActiveRecordSupport::ClassMethods end
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Laravelista\Comments\Comment; /** * App\EntryComment * * @property int $id * @property string|null $commenter_id * @property string|null $commenter_type * @property string|null $guest_name * @property string|null $guest_email * @property string $commentable_type * @property string $commentable_id * @property string $comment * @property bool $approved * @property int|null $child_id * @property \Illuminate\Support\Carbon|null $created_at * @property \Illuminate\Support\Carbon|null $updated_at * @property-read \Illuminate\Database\Eloquent\Collection|\Laravelista\Comments\Comment[] $children * @property-read int|null $children_count * @property-read \Illuminate\Database\Eloquent\Model|\Eloquent $commentable * @property-read \Illuminate\Database\Eloquent\Model|\Eloquent $commenter * @property-read \Illuminate\Database\Eloquent\Collection|\App\Entry[] $entries * @property-read int|null $entries_count * @property-read \Laravelista\Comments\Comment|null $parent * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment newQuery() * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment query() * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereApproved($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereChildId($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereComment($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereCommentableId($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereCommentableType($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereCommenterId($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereCommenterType($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereCreatedAt($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereGuestEmail($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereGuestName($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\EntryComment whereUpdatedAt($value) * @mixin \Eloquent */ class EntryComment extends Comment { protected $table = "comments"; /*** * Return entries for a given comment, one-to-many */ public function entries() { return $this->belongsToMany('App\Entry', 'commentable_id'); } }
<?php namespace App; class OcpwMassEmissionsParameter extends OcpwParameter { }
// // CustomListsPopover.h // Shukofukurou // // Created by 天々座理世 on 2018/07/25. // Copyright © 2018 Atelier Shiori. All rights reserved. // #import <Cocoa/Cocoa.h> @interface CustomListsPopover : NSViewController typedef void (^caction)(NSString *customlistname); @property caction actionblock; @property (strong) IBOutlet NSArrayController *customlistarraycontroller; @property (strong) IBOutlet NSTableView *tableview; - (void)populateandshowCustomLists:(NSArray *)clistarray; @end
<?php namespace Encore\Admin\Widgets\Chart; use Encore\Admin\Admin; use Encore\Admin\Widgets\Widget; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Support\Renderable; class Chart extends Widget implements Renderable { protected $elementId = ''; protected $options = []; protected $data = []; public function __construct($data = []) { $this->data = $data; } public function makeElementId() { return 'chart_'.uniqid(); } public static function color($color = '') { $colors = ['#dd4b39', '#00a65a', '#f39c12', '#00c0ef', '#3c8dbc', '#d2d6de']; return $color ? $color : $colors[array_rand($colors)]; //sprintf('#%06X', mt_rand(0, 0xFFFFFF)); } public function options($options = []) { $this->options = array_merge($this->options, $options); return $this; } /** * @param $data * * @deprecated */ public function data($data) { if ($data instanceof Arrayable) { $data = $data->toArray(); } $this->data = $data; } public function render() { $this->elementId = $this->makeElementId(); Admin::script($this->script()); return view('admin::widgets.chart', ['id' => $this->elementId])->render(); } }
import * as Yup from 'yup'; import DeliveryProblem from '../models/DeliveryProblem'; import Order from '../models/Order'; import Deliveryman from '../models/Deliveryman'; import Recipient from '../models/Recipient'; import Mail from '../../lib/Mail'; class DeliveryProblemController { async index(req, res) { const deliveryProblem = await DeliveryProblem.findAll({ attributes: ['id', 'description', 'delivery_id'], order: [['created_at', 'DESC']], }); return res.json(deliveryProblem); } async show(req, res) { const deliveryProblem = await DeliveryProblem.findAll({ where: { delivery_id: req.params.id, }, }); return res.json(deliveryProblem); } async store(req, res) { const schema = Yup.object().shape({ description: Yup.string() .trim() .required(), }); if (!(await schema.isValid(req.body))) { return res.status(400).json({ error: 'Validation fails' }); } const order = await Order.findByPk(req.params.id); if (!order) { return res.status(400).json({ error: 'Order not exists' }); } const { id, description, delivery_id } = await DeliveryProblem.create({ description: req.body.description, delivery_id: req.params.id, }); return res.json({ id, description, delivery_id }); } async delete(req, res) { const deliveryProblem = await DeliveryProblem.findByPk(req.params.id); if (!deliveryProblem) { return res.status(400).json({ error: 'Problem not exists' }); } const order = await Order.findOne({ where: { id: deliveryProblem.delivery_id, }, attributes: ['id', 'product', 'canceled_at'], include: [ { model: Deliveryman, attributes: ['id', 'name', 'email'], as: 'deliveryman', }, { model: Recipient, attributes: [ 'id', 'name', 'street', 'number', 'complement', 'state', 'city', 'zip_code', ], as: 'recipient', }, ], }); order.canceled_at = new Date(); await order.save(); /** * Send mail for deliveryman */ await Mail.sendMail({ to: `${order.deliveryman.name} <${order.deliveryman.email}>`, subject: 'Encomenda disponível para a retirada', template: 'deliveryCanceled', context: { description: deliveryProblem.description, deliveryman: order.deliveryman.name, product: order.product, name: order.recipient.name, street: order.recipient.street, number: order.recipient.number, complement: order.recipient.complement, state: order.recipient.state, city: order.recipient.city, zip_code: order.recipient.zip_code, }, }); return res.json(order); } } export default new DeliveryProblemController();
--- category: event title: LambdaConf logo: /resources/img/lambdaconf.png location: Boulder, CO, USA description: "(Truly) Advanced Scala & Other Functional Programming" start: 25 May 2017 end: 27 May 2017 link-out: http://lambdaconf.us ---
<?php use WP_CLI\Tests\TestCase; class WP_CLI_Test extends TestCase { public function testGetPHPBinary() { $this->assertSame( WP_CLI\Utils\get_php_binary(), WP_CLI::get_php_binary() ); } public function testErrorToString() { $this->expectException( 'InvalidArgumentException' ); $this->expectExceptionMessage( "Unsupported argument type passed to WP_CLI::error_to_string(): 'boolean'" ); WP_CLI::error_to_string( true ); } }
package com.xpf.attributeview; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.View; /** * Created by xpf on 2016/9/23 10:41 * 作用:自定义属性类 */ public class MyAttributeView extends View { private Bitmap bitmap; private int ageInt; private String nameStr; private static final String TAG = MyAttributeView.class.getSimpleName(); public MyAttributeView(Context context) { this(context, null); } public MyAttributeView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MyAttributeView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { //得到属性有三种方式 //1.使用命名空间取属性 String name = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "name"); String age = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "age"); String bg = attrs.getAttributeValue("http://schemas.android.com/apk/res-auto", "bg"); Log.e(TAG, "name==" + name + ",age==" + age + ",bg==" + bg); //2.使用循环 for (int i = 0; i < attrs.getAttributeCount(); i++) { Log.e(TAG, attrs.getAttributeName(i) + "," + attrs.getAttributeValue(i)); } //3.使用系统工具 TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyAttributeView); for (int i = 0; i < array.getIndexCount(); i++) { int index = array.getIndex(i);//id switch (index) { case R.styleable.MyAttributeView_name: nameStr = array.getString(index); break; case R.styleable.MyAttributeView_age: ageInt = array.getInt(index, 0); break; case R.styleable.MyAttributeView_bg: Drawable drawable = array.getDrawable(index); BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; bitmap = bitmapDrawable.getBitmap(); break; } } // 3.回收 array.recycle(); } @SuppressLint("DrawAllocation") @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setTextSize(30); paint.setColor(Color.WHITE); canvas.drawBitmap(bitmap, 0, 0, paint); canvas.drawText(nameStr + ":" + ageInt, 20, 40, paint); } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Mono.Debugger.Soft { // Represents a temporary type of a lambda expression. // In order to determine the type of a lambda based on // its context, type evaluation for it must be delayed. public class DelayedLambdaType : Mirror { class ParsedType { public string nameSpace; public string typeName; public string [] argTypeNames; } string expression; Tuple<string, Value>[] locals; string uniqueName; public DelayedLambdaType (VirtualMachine vm, Tuple<string, Value>[] locals, string expression) : base (vm, 0) { this.expression = expression; this.locals = locals; this.uniqueName = "Lambda" + Guid.NewGuid ().ToString ("N"); } public string Expression { get { return expression; } } public Tuple<string, Value>[] Locals { get { if (locals == null) return new Tuple<string, Value> [0]; return locals; } } public string Name { get { return uniqueName; } } public Value[] GetLocalValues () { var vals = new Value [Locals.Length]; for (int i = 0; i < vals.Length; i++) vals [i] = Locals [i].Item2; return vals; } public bool IsAcceptableType (TypeMirror t) { return IsAcceptable (ParseFullName (t)); } private bool IsAcceptable (ParsedType t) { return t != null; } public string GetLiteralType (TypeMirror typ) { ParsedType t = ParseFullName (typ); if (t == null || !IsAcceptable (t)) return null; var ns = t.nameSpace != null ? t.nameSpace + "." : ""; var args = t.argTypeNames != null ? "<" + String.Join (",", t.argTypeNames) + ">" : ""; return ns + t.typeName + args; } private static ParsedType ParseFullName (TypeMirror t) { try { return OnParseFullName (t); } catch (Exception) { return null; } } private static ParsedType OnParseFullName (TypeMirror typ) { // Parse fullName of type to ParsedType that is defined above. Examples for the parsing // are following. // 1) System.Action`1[[System.Int32, mscorlib, Version=xxx, Culture=xxx, // PublicKeyToken=xxx]] // => { nameSpace: "System", typeName: "Action", argTypeNames: ["System.Int32"] } // 2) System.Func`2[[System.Int32, mscorlib, Version=xxx, Culture=xxx, // PublicKeyToken=xxx],[System.Single, mscorlib, Version=xxx, Culture=xxx, // PublicKeyToken=xxx]] // => { nameSpace: "System", typeName: "Func", // argTypeNames: ["System.Int32", "System.Single"] } if (typ == null) return null; string fullName = typ.FullName.Replace ('+', '.'); string nmespace = typ.Namespace == "" ? null : typ.Namespace; string typeName = ""; string [] argTypeNames = null; string rest = fullName; if (nmespace != null) { var omit = nmespace + "."; if (!rest.StartsWith (omit, StringComparison.Ordinal)) { throw new ArgumentException ("should starts with namespace"); } rest = rest.Substring (omit.Length, rest.Length - omit.Length); } string pattern = @"(.*?)`\d+(.*)"; Match m = Regex.Match (rest, pattern); if (m.Success) { typeName = m.Groups [1].Value; rest = m.Groups [2].Value; int len = rest.Length; if (rest [0] != '[' || rest [len - 1] != ']') throw new ArgumentException ("Failed to skip braces"); rest = rest.Substring (1, len - 2); argTypeNames = ReadArgTypeNames (rest); } else { if (!rest.EndsWith (typ.Name, StringComparison.Ordinal)) throw new ArgumentException ("invalid"); typeName = rest; } ParsedType t = new ParsedType (); t.nameSpace = nmespace; t.typeName = typeName; t.argTypeNames = argTypeNames; return t; } private static string [] ReadArgTypeNames (string s) { List<string> args = new List<string> (); int nest = 0; int start = 0; for (int i = 0; i < s.Length; i++) { char c = s [i]; if (c == '[') { if (nest == 0) start = i; nest++; } else if (c == ']') { if (nest == 1) args.Add (s.Substring (start, i - start + 1)); nest--; } } string [] result = new string [args.Count]; int n = 0; foreach (string arg in args) { string pattern = @"\[(.*?)[,\]]"; Match m = Regex.Match (arg, pattern); if (!m.Success) throw new ArgumentException ("Failed to parse arg's names"); result [n] = m.Groups [1].Value; n++; } return result; } } }
package model // 视图渲染内容对象 type View struct { Title string // 页面标题 Keywords string // 页面关键字 Description string // 页面描述 Error string // 错误信息 MainTpl string // 自定义MainTpl展示模板文件 Redirect string // 引导页面跳转 ContentType string // 内容模型 BreadCrumb []ViewBreadCrumb // 面包屑 Data interface{} // 页面参数v } // 视图面包屑结构 type ViewBreadCrumb struct { Name string // 显示名称 Url string // 链接地址,当为空时表示被选中 }
package transport import ( "testing" "github.com/stretchr/testify/assert" ) func TestCodec(t *testing.T) { audio := Codec{ MimeType: "audio/opus", ClockRate: 48000, Channels: 2, SDPFmtpLine: "", } video := Codec{ MimeType: "video/vp8", ClockRate: 90000, Channels: 0, SDPFmtpLine: "", } assert.Equal(t, TrackKindAudio, audio.TrackKind()) assert.Equal(t, TrackKindVideo, video.TrackKind()) }
using System; using DG.Tweening; using UnityEngine; public class Avatar : IAttackable, IHealth, IMovable { public string name => _data.name; public bool IsOnCombat; public bool IsDead => _currentHp <= 0; public int CurrentHp => _currentHp; public int MaxHp => _data.hp; public string Type => _data.type.value; public string instanceId => _instanceId; public Sprite sprite => _data.sprite; public Vector2 position => _transform == null ? Vector3.zero : _transform.position; public Vector3 currentDir; private int _currentHp; private string _instanceId; private Transform _transform; private CharacterData _data; private CharacterSpriteWorker _spriteWorker; public Avatar(string instanceId, Transform transform, CharacterData data) { _instanceId = instanceId; _currentHp = data.hp; _data = new CharacterData(data); _transform = transform; _spriteWorker = new CharacterSpriteWorker(transform); } public void TransferAvatar(string instanceId, Transform transform) { _instanceId = instanceId; _transform = transform; _spriteWorker = new CharacterSpriteWorker(transform); } public int Attack(string otherType) { var damage = _data.type.value == otherType ? _data.attack * 2 : _data.attack; return Mathf.CeilToInt(damage * -1); } public void Modify(int modifyValue) { if (modifyValue < 0) { modifyValue += _data.defence; if (modifyValue >= 0) modifyValue = -1; } _currentHp = (_currentHp + modifyValue) < 0 ? 0 : _currentHp + modifyValue; } public void InstantDeath() { _currentHp = 0; } public void SetPos(Vector3 vector) { if (_transform == null) return; _spriteWorker.HandleSprite(currentDir.x); _transform.position = vector; } public void Move(float speedMultiplier, Vector3 vector) { if (_transform == null) return; if (IsOnCombat) return; currentDir = vector; _spriteWorker.HandleSprite(currentDir.x); _transform.Translate(vector * speedMultiplier * Time.deltaTime); } public PlayerStatData GetStat() { var stat = new PlayerStatData(); stat.sprite = sprite; stat.attackDmg = _data.attack.ToString(); stat.def = _data.defence.ToString(); stat.name = _data.name; return stat; } }
use pest::Error; use pest::iterators::{Pair, Pairs}; use parser::Rule; pub fn as_amb<'a, F, T>( pairs: Pairs<'a, Rule>, a_rule: Rule, b_rule: Rule, func: F, ) -> Result<T, Error<'a, Rule>> where F: Fn(Pairs<'a, Rule>, Option<Pairs<'a, Rule>>) -> Result<T, Error<'a, Rule>>, { as_ht(pairs, a_rule, |a, mut pairs| { if let Some(b) = pairs.next() { if let Some(token) = pairs.next() { Err(Error::ParsingError { positives: vec![], negatives: vec![token.as_rule()], pos: token.into_span().start_pos(), }) } else if b.as_rule() == b_rule { func(a, Some(b.into_inner())) } else { Err(Error::ParsingError { positives: vec![b_rule], negatives: vec![], pos: b.into_span().start_pos(), }) } } else { func(a, None) } }) } fn as_ht<'a, F, T>( mut pairs: Pairs<'a, Rule>, head_rule: Rule, func: F, ) -> Result<T, Error<'a, Rule>> where F: Fn(Pairs<'a, Rule>, Pairs<'a, Rule>) -> Result<T, Error<'a, Rule>>, { if let Some(head) = pairs.next() { if head.as_rule() == head_rule { func(head.into_inner(), pairs) } else { Err(Error::ParsingError { positives: vec![head_rule], negatives: vec![], pos: head.into_span().start_pos(), }) } } else { panic!("Could not find expected {}", head_rule) } } pub fn as_one_any<'a, F, T>( mut pairs: Pairs<'a, Rule>, rule: Rule, func: F, ) -> Result<T, Error<'a, Rule>> where F: Fn(Pair<'a, Rule>) -> Result<T, Error<'a, Rule>>, { if let Some(token) = pairs.next() { if let Some(token) = pairs.next() { Err(Error::ParsingError { positives: vec![], negatives: vec![token.as_rule()], pos: token.into_span().start_pos(), }) } else { func(token) } } else { panic!("Could not find expected {}", rule) } } pub fn as_one<'a, F, T>( pairs: Pairs<'a, Rule>, rule: Rule, func: F, ) -> Result<T, Error<'a, Rule>> where F: Fn(Pairs<'a, Rule>) -> Result<T, Error<'a, Rule>>, { as_one_any(pairs, rule, |token| { if token.as_rule() == rule { func(token.into_inner()) } else { Err(Error::ParsingError { positives: vec![rule], negatives: vec![], pos: token.into_span().start_pos(), }) } }) }
--- '@backstage/create-app': patch --- Adjust template to the latest changes in the `api-docs` plugin. ## Template Changes While updating to the latest `api-docs` plugin, the following changes are necessary for the `create-app` template in your `app/src/components/catalog/EntityPage.tsx`. This adds: - A custom entity page for API entities - Changes the API tab to include the new `ConsumedApisCard` and `ProvidedApisCard` that link to the API entity. ```diff import { + ApiDefinitionCard, - Router as ApiDocsRouter, + ConsumedApisCard, + ProvidedApisCard, + ConsumedApisCard, + ConsumingComponentsCard, + ProvidedApisCard, + ProvidingComponentsCard } from '@backstage/plugin-api-docs'; ... +const ComponentApisContent = ({ entity }: { entity: Entity }) => ( + <Grid container spacing={3} alignItems="stretch"> + <Grid item md={6}> + <ProvidedApisCard entity={entity} /> + </Grid> + <Grid item md={6}> + <ConsumedApisCard entity={entity} /> + </Grid> + </Grid> +); const ServiceEntityPage = ({ entity }: { entity: Entity }) => ( <EntityPageLayout> <EntityPageLayout.Content path="/" title="Overview" element={<OverviewContent entity={entity} />} /> <EntityPageLayout.Content path="/ci-cd/*" title="CI/CD" element={<CICDSwitcher entity={entity} />} /> <EntityPageLayout.Content path="/api/*" title="API" - element={<ApiDocsRouter entity={entity} />} + element={<ComponentApisContent entity={entity} />} /> ... -export const EntityPage = () => { - const { entity } = useEntity(); - switch (entity?.spec?.type) { - case 'service': - return <ServiceEntityPage entity={entity} />; - case 'website': - return <WebsiteEntityPage entity={entity} />; - default: - return <DefaultEntityPage entity={entity} />; - } -}; +export const ComponentEntityPage = ({ entity }: { entity: Entity }) => { + switch (entity?.spec?.type) { + case 'service': + return <ServiceEntityPage entity={entity} />; + case 'website': + return <WebsiteEntityPage entity={entity} />; + default: + return <DefaultEntityPage entity={entity} />; + } +}; + +const ApiOverviewContent = ({ entity }: { entity: Entity }) => ( + <Grid container spacing={3}> + <Grid item md={6}> + <AboutCard entity={entity} /> + </Grid> + <Grid container item md={12}> + <Grid item md={6}> + <ProvidingComponentsCard entity={entity} /> + </Grid> + <Grid item md={6}> + <ConsumingComponentsCard entity={entity} /> + </Grid> + </Grid> + </Grid> +); + +const ApiDefinitionContent = ({ entity }: { entity: ApiEntity }) => ( + <Grid container spacing={3}> + <Grid item xs={12}> + <ApiDefinitionCard apiEntity={entity} /> + </Grid> + </Grid> +); + +const ApiEntityPage = ({ entity }: { entity: Entity }) => ( + <EntityPageLayout> + <EntityPageLayout.Content + path="/*" + title="Overview" + element={<ApiOverviewContent entity={entity} />} + /> + <EntityPageLayout.Content + path="/definition/*" + title="Definition" + element={<ApiDefinitionContent entity={entity as ApiEntity} />} + /> + </EntityPageLayout> +); + +export const EntityPage = () => { + const { entity } = useEntity(); + + switch (entity?.kind?.toLowerCase()) { + case 'component': + return <ComponentEntityPage entity={entity} />; + case 'api': + return <ApiEntityPage entity={entity} />; + default: + return <DefaultEntityPage entity={entity} />; + } +}; ```
[4, 5].each do |element| p element end {"example" => 0}.each do |key, value| p key p value end
using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Controls; using System.Windows.Threading; namespace SpellChecker { ///<summary> /// Finds the spelling errors in comments for a specific buffer. ///</summary> /// <remarks><para>The lifespan of this object is tied to the lifespan of the taggers on the view. On creation of the first tagger, the SpellChecker starts doing /// work to find errors in the file. On the disposal of the last tagger, it shuts down.</para> /// </remarks> public class SpellChecker { private readonly SpellCheckerProvider _provider; private readonly ITextBuffer _buffer; private readonly Dispatcher _uiThreadDispatcher; private readonly TextBox _box = new TextBox(); // Used to do spell checking. private IClassifier _classifier; private ITextSnapshot _currentSnapshot; private NormalizedSnapshotSpanCollection _dirtySpans; private bool _isUpdating = false; private bool _isDisposed = false; private readonly List<SpellCheckerTagger> _activeTaggers = new List<SpellCheckerTagger>(); internal readonly string FilePath; internal readonly SpellingErrorsFactory Factory; internal SpellChecker(SpellCheckerProvider provider, ITextView textView, ITextBuffer buffer) { _provider = provider; _buffer = buffer; _currentSnapshot = buffer.CurrentSnapshot; // Get the name of the underlying document buffer ITextDocument document; if (provider.TextDocumentFactoryService.TryGetTextDocument(textView.TextDataModel.DocumentBuffer, out document)) { this.FilePath = document.FilePath; // TODO we should listen for the file changing its name (ITextDocument.FileActionOccurred) } // turn on spell checking for the box we're using to do spell checking. _box.SpellCheck.IsEnabled = true; // We're assuming we're created on the UI thread so capture the dispatcher so we can do all of our updates on the UI thread. _uiThreadDispatcher = Dispatcher.CurrentDispatcher; this.Factory = new SpellingErrorsFactory(this, new SpellingErrorsSnapshot(this.FilePath, 0)); } internal void AddTagger(SpellCheckerTagger tagger) { _activeTaggers.Add(tagger); if (_activeTaggers.Count == 1) { // First tagger created ... start doing stuff. _classifier = _provider.ClassifierAggregatorService.GetClassifier(_buffer); _buffer.ChangedLowPriority += this.OnBufferChange; _dirtySpans = new NormalizedSnapshotSpanCollection(new SnapshotSpan(_currentSnapshot, 0, _currentSnapshot.Length)); _provider.AddSpellChecker(this); this.KickUpdate(); } } internal void RemoveTagger(SpellCheckerTagger tagger) { _activeTaggers.Remove(tagger); if (_activeTaggers.Count == 0) { // Last tagger was disposed of. This is means there are no longer any open views on the buffer so we can safely shut down // spell checking for that buffer. _buffer.ChangedLowPriority -= this.OnBufferChange; _provider.RemoveSpellChecker(this); _isDisposed = true; _buffer.Properties.RemoveProperty(typeof(SpellChecker)); IDisposable classifierDispose = _classifier as IDisposable; if (classifierDispose != null) classifierDispose.Dispose(); _classifier = null; } } private void OnBufferChange(object sender, TextContentChangedEventArgs e) { _currentSnapshot = e.After; // Translate all of the old dirty spans to the new snapshot. NormalizedSnapshotSpanCollection newDirtySpans = _dirtySpans.CloneAndTrackTo(e.After, SpanTrackingMode.EdgeInclusive); // Dirty all the spans that changed. foreach (var change in e.Changes) { newDirtySpans = NormalizedSnapshotSpanCollection.Union(newDirtySpans, new NormalizedSnapshotSpanCollection(e.After, change.NewSpan)); } // Translate all the spelling errors to the new snapshot (and remove anything that is a dirty region since we will need to check that again). var oldSpenningErrors = this.Factory.CurrentSnapshot; var newSpellingErrors = new SpellingErrorsSnapshot(this.FilePath, oldSpenningErrors.VersionNumber + 1); // Copy all of the old errors to the new errors unless the error was affected by the text change foreach (var error in oldSpenningErrors.Errors) { Debug.Assert(error.NextIndex == -1); var newError = SpellingError.CloneAndTranslateTo(error, e.After); if (newError != null) { Debug.Assert(newError.Span.Length == error.Span.Length); error.NextIndex = newSpellingErrors.Errors.Count; newSpellingErrors.Errors.Add(newError); } } this.UpdateSpellingErrors(newSpellingErrors); _dirtySpans = newDirtySpans; // Start processing the dirty spans (which no-ops if we're already doing it). if (_dirtySpans.Count != 0) { this.KickUpdate(); } } private void KickUpdate() { // We're assuming we will only be called from the UI thread so there should be no issues with race conditions. if (!_isUpdating) { _isUpdating = true; _uiThreadDispatcher.BeginInvoke(new Action(() => this.DoUpdate()), DispatcherPriority.Background); } } private void DoUpdate() { // It would be good to do all of this work on a background thread but we can't: // _classifier.GetClassificationSpans() should only be called on the UI thread because some classifiers assume they are called from the UI thread. // Raising the TagsChanged event from the taggers needs to happen on the UI thread (because some consumers might assume it is being raised on the UI thread). // // Updating the snapshot for the factory and calling the sink can happen on any thread but those operations are so fast that there is no point. if ((!_isDisposed) && (_dirtySpans.Count > 0)) { var line = _dirtySpans[0].Start.GetContainingLine(); if (line.Length > 0) { var oldSpellingErrors = this.Factory.CurrentSnapshot; var newSpellingErrors = new SpellingErrorsSnapshot(this.FilePath, oldSpellingErrors.VersionNumber + 1); // Go through the existing errors. If they are on the line we are currently parsing then // copy them to oldLineErrors, otherwise they go to the new errors. var oldLineErrors = new List<SpellingError>(); foreach (var error in oldSpellingErrors.Errors) { Debug.Assert(error.NextIndex == -1); if (line.Extent.Contains(error.Span)) { error.NextIndex = -1; oldLineErrors.Add(error); // Do not clone old error here ... we'll do that later there is no change. } else { error.NextIndex = newSpellingErrors.Errors.Count; newSpellingErrors.Errors.Add(SpellingError.Clone(error)); // We must clone the old error here. } } int expectedErrorCount = newSpellingErrors.Errors.Count + oldLineErrors.Count; bool anyNewErrors = false; var classifications = _classifier.GetClassificationSpans(line.Extent); foreach (var classification in classifications) { if (classification.ClassificationType.IsOfType(PredefinedClassificationTypeNames.Comment) || classification.ClassificationType.IsOfType("xml doc comment - text")) { string text = classification.Span.GetText(); _box.Text = text; int index = 0; while (index < text.Length) { int errorStart = _box.GetNextSpellingErrorCharacterIndex(index, System.Windows.Documents.LogicalDirection.Forward); if (errorStart < 0) { break; } int errorLength = _box.GetSpellingErrorLength(errorStart); if (errorLength > 1) // Ignore any single character misspelling. { var newSpan = new SnapshotSpan(classification.Span.Start + errorStart, errorLength); if (SpellChecker.IsPossibleSpellingError(newSpan)) { var oldError = oldLineErrors.Find((e) => e.Span == newSpan); if (oldError != null) { // There was a spelling error at the same span as the old one so we should be able to just reuse it. oldError.NextIndex = newSpellingErrors.Errors.Count; newSpellingErrors.Errors.Add(SpellingError.Clone(oldError)); // Don't clone the old error yet } else { // Let WPF decide whether or not there are any suggested spellings. var wpfSpellngError = _box.GetSpellingError(errorStart); newSpellingErrors.Errors.Add(new SpellingError(newSpan, new List<string>(wpfSpellngError.Suggestions))); anyNewErrors = true; } } index = errorStart + errorLength; } else { // How can you have a spelling error with a length of 0? Handle it gracefully in any case. index = errorStart + 1; } } } } // This does a deep comparison so we will only do the update if the a different set of errors was discovered compared to what we had previously. // If there were any new errors or if we didn't see all the expected errors then there is a change and we need to update the spelling errors. if (anyNewErrors || (newSpellingErrors.Errors.Count != expectedErrorCount)) { this.UpdateSpellingErrors(newSpellingErrors); } else { // There were no changes so we don't need to update our snapshot. // We have, however, dirtied the old errors by setting their NextIndex property on the assumption that we would be updating the errors. // Revert all those changes. foreach (var error in oldSpellingErrors.Errors) { error.NextIndex = -1; } } } // NormalizedSnapshotSpanCollection.Difference doesn't quite do what we need here. If I have {[5,5), [10,20)} and subtract {[5, 15)} and do a ...Difference, I // end up with {[5,5), [15,20)} (the zero length span at the beginning isn't getting removed). A zero-length span at the end wouldn't be removed but, in this case, // that is the desired behavior (the zero length span at the end could be a change at the beginning of the next line, which we'd want to keep). var newDirtySpans = new List<Span>(_dirtySpans.Count + 1); var extent = line.ExtentIncludingLineBreak; for (int i = 0; (i < _dirtySpans.Count); ++i) { Span s = _dirtySpans[i]; if ((s.End < extent.Start) || (s.Start >= extent.End)) // Intentionally asymmetric { newDirtySpans.Add(s); } else { if (s.Start < extent.Start) { newDirtySpans.Add(Span.FromBounds(s.Start, extent.Start)); } if ((s.End >= extent.End) && (extent.End < line.Snapshot.Length)) { newDirtySpans.Add(Span.FromBounds(extent.End, s.End)); //This could add a zero length span (which is by design since we want to ensure we spell check the next line). } } } _dirtySpans = new NormalizedSnapshotSpanCollection(line.Snapshot, newDirtySpans); if (_dirtySpans.Count == 0) { // We've cleaned up all the dirty spans. _isUpdating = false; } else { // Still more work to do. _uiThreadDispatcher.BeginInvoke(new Action(() => this.DoUpdate()), DispatcherPriority.Background); } } } // Reject spelling errors for words that are probably code constructs embedded in a comment. // Reject if: // Any upper case characters after the 1st character. // Any _ in the span. // Any . in the span. // Any digits in the span. private static bool IsPossibleSpellingError(SnapshotSpan span) { for (int i = 0; (i < span.Length); ++i) { char c = (span.Start + i).GetChar(); if ((c == '_') || (c == '.') || char.IsDigit(c) || ((i > 0) && char.IsUpper(c))) { return false; } } return true; } private void UpdateSpellingErrors(SpellingErrorsSnapshot spellingErrors) { // Tell our factory to snap to a new snapshot. this.Factory.UpdateErrors(spellingErrors); // Tell the provider to mark all the sinks dirty (so, as a side-effect, they will start an update pass that will get the new snapshot // from the factory). _provider.UpdateAllSinks(); foreach (var tagger in _activeTaggers) { tagger.UpdateErrors(_currentSnapshot, spellingErrors); } this.LastSpellingErrors = spellingErrors; } internal SpellingErrorsSnapshot LastSpellingErrors { get; private set; } } }
package org.motechproject.umurinzi.dto; import lombok.Getter; import lombok.Setter; import org.motechproject.umurinzi.domain.enums.EmailSchedulePeriod; public class EmailReportConfigDto { @Getter @Setter private Boolean enableEmailReportJob = false; @Getter @Setter private String emailReportStartDate; @Getter @Setter private EmailSchedulePeriod emailSchedulePeriod; @Getter @Setter private String emailRecipients; @Getter @Setter private String emailSubject; @Getter @Setter private String emailBody; }
package de.katzenpapst.amunra.helper; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.AxisAlignedBB; public class NbtHelper { public static NBTTagCompound getAsNBT(AxisAlignedBB aabb) { NBTTagCompound result = new NBTTagCompound(); writeToNBT(result, aabb); return result; } public static void writeToNBT(NBTTagCompound nbt, AxisAlignedBB aabb) { nbt.setDouble("minX", aabb.minX); nbt.setDouble("minY", aabb.minY); nbt.setDouble("minZ", aabb.minZ); nbt.setDouble("maxX", aabb.maxX); nbt.setDouble("maxY", aabb.maxY); nbt.setDouble("maxZ", aabb.maxZ); } public static AxisAlignedBB readAABB(NBTTagCompound nbt) { return AxisAlignedBB.getBoundingBox( nbt.getDouble("minX"), nbt.getDouble("minY"), nbt.getDouble("minZ"), nbt.getDouble("maxX"), nbt.getDouble("maxY"), nbt.getDouble("maxZ") ); } public static ItemStack[] readInventory(NBTTagCompound nbt, int inventorySize) { final NBTTagList itemTag = nbt.getTagList("Items", 10); ItemStack[] result = new ItemStack[inventorySize]; for (int i = 0; i < itemTag.tagCount(); ++i) { final NBTTagCompound stackNbt = itemTag.getCompoundTagAt(i); final int slotNr = stackNbt.getByte("Slot") & 255; if (slotNr < inventorySize) { result[slotNr] = ItemStack.loadItemStackFromNBT(stackNbt); } } return result; } public static void writeInventory(NBTTagCompound nbt, ItemStack[] inventory) { final NBTTagList list = new NBTTagList(); int length = inventory.length; for (int i = 0; i < length; ++i) { if (inventory[i] != null) { final NBTTagCompound stackNbt = new NBTTagCompound(); stackNbt.setByte("Slot", (byte) i); inventory[i].writeToNBT(stackNbt); list.appendTag(stackNbt); } } nbt.setTag("Items", list); } }
package com.lwt.qmqiu_sps1.bean import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Document @Document(collection = "gift_log") data class GiftLog( @Id var _id:String?=null, //0 购买 1赠送 2兑换 var type:Int? = 0, //总花费 var cash:Int? = 0, var giftCount:String ="0*0*0*0", var giftPrice:String ="18*38*68*88", //主动方 var name:String?="", //从哪来 var from:String?="", //到哪去 var to:String?="", //交易时间 var happenTime:Long = System.currentTimeMillis() )
namespace Me20.Common.Interfaces { public interface IHaveInternalName { string InternalName { get; } } }
using Shouldly; using Stryker.DataCollector; using System; using System.Diagnostics; using System.Threading; using System.Xml; using Xunit; namespace Stryker.Core.UnitTest.TestRunners { public class CoverageCaptureTests { private static bool WaitFor(object lck, Func<bool> predicate, int timeout) { var stopwatch = new Stopwatch(); stopwatch.Start(); while (stopwatch.ElapsedMilliseconds < timeout) { lock (lck) { if (predicate()) { return true; } Monitor.Wait(lck, (int)Math.Max(0, timeout - stopwatch.ElapsedMilliseconds)); } } return predicate(); } [Fact] public void CanParseConfiguration() { var referenceConf="<Parameters><Environment name=\"ActiveMutant\" value=\"1\"/></Parameters>"; var node = new XmlDocument(); node.LoadXml(referenceConf); node.ChildNodes.Count.ShouldBe(1); var coolChild = node.GetElementsByTagName("Parameters"); coolChild[0].Name.ShouldBe("Parameters"); var envVars = node.GetElementsByTagName("Environment"); envVars.Count.ShouldBe(1); } } }
# Integers # Literals generate a value of the "default" integer type (Int64 on my workstation) 1 1234 # Types of Literals typeof(1) # Internal variable, `Sys.WORD_SIZE`, indicates word architecture of target system Sys.WORD_SIZE # Synonyms for signed and unsigned default integers Int UInt # Values that **do not** fit in 32-bits but **can** be represented in 64-bits **always** create a 64-bit integer typeof(3_000_000_000) # Similar promotion occurs from 64-bits to 128-bits on my workstation typeof(3_000_000_000_000) typeof(3_000_000_000_000_000) typeof(3_000_000_000_000_000_000) typeof(3_000_000_000_000_000_000_000) # Unsigned integers are input and output using the `0x` prefix and hexadecimal digits '0-9a-f'. The size of the # value is determined by the number of hexadecimal digits used. x = 0xff typeof(x) x = 0xffff typeof(x) x = 0xfffffff typeof(x) x = 0xffffffff typeof(x) x = 0xffffffffff typeof(x) x = 0x1 typeof(x) x = 0x123 typeof(x) x = 0x1234567 typeof(x) x = 0x123456789abcdef typeof(x) x = 0x11112222333344445555666677778888 typeof(x) # Binary and octal literals are also supported x = 0b10 typeof(x) x = 0o010 typeof(x) # 16 leading zeros x = 0x0000000000000000111122223333444 typeof(x) # 18 leading zeros x = 0x000000000000000000111122223333444 typeof(x) # If one preceeds a binary, octal or hexadecimal literal, the value is the two's complement of the literal without # the sign x = -0x2 typeof(x) x = -0x0002 typeof(x) # Use `typemin` and `typemax` to obtain the minimum and maximum representable values of the primitive numeric # types such as integers. (typemin(Int32), typemax(Int32)) for T in [Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128] println("$(lpad(T, 7)): [$(typemin(T)), $(typemax(T))]") end # Overflow # In Julia, exceeding the maximum representable value of a given type results in wrap around behavior. x = typemax(Int64) x + 1 x + 1 == typemin(Int64) x = typemin(Int64) x - 1 x - 1 == typemax(Int64) # Beware. In applications where overflow is possible, explicit checking for wrap around behavior produced by # overflow (and underflow) is essential; otherwise the `BigInt` type in _Arbitrary Precision Arithmetic_ is # recommended instead. # An example of overflow behavior and how to potentially resolve it is as follows: 10^19 # Does not produce expected value because of overflow big(10)^19 # Use `BigInt` instead # Division Errors # Integer division, the `div` function, has two exceptional cases: # - Dividing by zero # - Dividing the lowest negative number (`typemin`) by -1 # Both of these cases produce a `DivideError` div(1, 0) div(typemin(Int64), -1) # The remainder and modulus functions, `rem` and `mod`, respectively, throw a `DivideError` when their second # argument is zero. rem(1, 0) mod(1, 0) # Floating-point numbers # Literal floating-point numbers are represented using the "standard" formats using e-notation when necessary: 1.0 typeof(1.0) 1. typeof(1.) 0.5 typeof(0.5) .5 typeof(.5) -1.23 typeof(-1.23) 1e10 typeof(1e10) 2.5e-4 typeof(2.5e-4) # The previous values are all of type `Float64`. Literal `Float32` values can be entered by writing an `f` in place # of the `e` x = 0.5f0 typeof(x) x = 2.5f-4 typeof(x) # One **cannot** simply use the `f` suffix x = 0.5f # One can easily convert values to `Float32` values x = Float32(-1.5) typeof(x) # Hexadecimal floating-point literals are also valid, but only as `Float64` values, with `p` preceding the base-2 # exponent. One must understand how `Float64` values are stored using the IEEE standard. See # [the Wikipedia article](https://en.wikipedia.org/wiki/Floating-point_arithmetic) 0x1p0 0x1.8p3 x = 0x.4p-1 typeof(x) # Julia also supports half-precision floating-point numbers (`Float16`); however, they are implemented in software # and use `Float32` for calculations sizeof(Float16(4.)) 2 * Float16(4.) # Floating-point zero # Floating-point numbers have **two** zeros: positive zero and negative zero. They are equal to each other, but # actually have different binary representations. The different representations can be seen using the `bitstring` # function. 0.0 == -0.0 bitstring(0.0) bitstring(-0.0) # Special floating-point values Inf16 ## `Float16` infinity Inf32 ## `Float32` infinity Inf ## `Float64` infinity -Inf16 ## `Float16` negative infinity -Inf32 ## `Float32` negative infinity -Inf ## `Float64` negative infinity NaN16 ## `Float16` not a number NaN32 ## `Float32` not a number NaN ## `Float64` not a number # Comparing these values may not be obvious. See the section, "Numeric Comparisons." # These special floating-point values, per the _IEEE-754 standard_, are the result of certain arithmetic # operations. 1 / Inf 1 / 0 -5 / 0 0.000001 / 0 0 / 0 500 + Inf 500 - Inf Inf + Inf Inf - Inf Inf * Inf Inf / Inf 0 * Inf # The `typemin` and `typemax` functions also apply to floating-point types. (typemin(Float16), typemax(Float16)) (typemin(Float32), typemax(Float32)) (typemin(Float64), typemax(Float64)) # Machine epsilon # Most real numbers **cannot** be represented with floating-point numbers. For many purposes, it is important to # know the distance between two adjacent floating-point numbers. This distance is often known as the # "machine epsilon." # Julia provides `eps`, which gives the distance between 1.0 and the next larger representable floating-point # value. eps(Float32) # Same as 2.0^-23 as a `Float32` value Float32(2.0)^-23 eps(Float64) # Same as 2.0^-52 as a `Float64` value Float64(2.0^-52) eps() # Same as `eps(Float64)` # The `eps` function also accepts a floating point value. In this situation, the result of `eps()` is the distance # between the argument to `eps()` and the next (higher) representable floating-point number. eps(1.0) eps(1000.) eps(1e-27) eps(0.0) # Note that the distance between two adjacent floating-point values is **not** uniform throughout the # floating-point range; instead, floating-point numbers are densest close to 0.0 and grow exponentially sparser as # one moves away from zero. # Julia also provides `nextfloat` and `prevfloat` functions that return the next largest or smallest x = 1.25f0 nextfloat(x) prevfloat(x) bitstring(x) bitstring(nextfloat(x)) bitstring(prevfloat(x)) x = 1.25 nextfloat(x) prevfloat(x) bitstring(x) bitstring(nextfloat(x)) bitstring(prevfloat(x)) # Arbitrary Precision Arithmetic # Julia wraps the _GNU Multiple Precision Arithmetic Library (GMP)_ and the _GNU MPFR Library_, respectively. The # `BigInt` and `BigFloat` types are available in Julia for arbitrary precision integer and floating point numbers, # respectively. # Use constructors to create these types from either primitive numerical types. Additionally, one can use the # _string literal_ `@big_str` or `parse` to construct instances from `AbstractString` values. Values of type # `BigInt` can be constructed from integer literals when the exceed the bounds of `Int128`. # Note that **no** unsigned arbitrary-precision integer types exist in _Base_; instead, `BigInt` is sufficient in # most cases. Additionally, binary, octal and hexadecimal integer literals can be used (in addition to decimal # literals). # Once created, arbitrary-precision integers and floating-point values participate in arithmetic with all other # numeric types because of Julia's _type promotion and conversion mechansims_. BigInt(typemax(Int64)) + 1 big"1234567890123456789012345678901234567890" + 1 parse(BigInt, "123456789012345678901234567890") + 1 string(big"2"^200, base=16) typeof(0x1000_0000_0000_0000_0000_0000_0000_0000) typeof(0x1000_0000_0000_0000_0000_0000_0000_0000_0) 0x1000_0000_0000_0000_0000_0000_0000_0000_0 - 1 == typemax(UInt128) 0x0000_0000_0000_0000_0000_0000_0000_0000_0 typeof(ans) big"1.23456789012345678901" parse(BigFloat, "1.23456789012345678901") BigFloat(2.0^66) / 3 factorial(BigInt(40)) # However, type promotion between the primitive types above and `BigInt` / `BigFloat` is **not** automatic and must # be explicity stated. x = typemin(Int64) x = x - 1 typeof(x) y = BigInt(typemin(Int64)) y = y - 1 typeof(y) # The default precision (in number of bits of the significand) and rounding mode of `BigFloat` operations can be # changed globally by calling `setprecision` and `setrounding`, and all further calculations will take these # changes into account. Alternatively, the precision or the rounding can be changed only within the execution of a # particular block of code using the same functions with a `do` block. setrounding(BigFloat, RoundUp) do BigFloat(1) + parse(BigFloat, "0.1") end setrounding(BigFloat, RoundDown) do BigFloat(1) + parse(BigFloat, "0.1") end setprecision(40) do BigFloat(1) + parse(BigFloat, "0.1") end # Numeric Literal Coefficents # To make common numeric forulae and expressions clearer, Julia allows variables to be immediately preceded by a # numeric literal, implying multiplication. This makes writing polynomial expressions much clearer. x = 3 2x^2 - 3x + 1 1.5x^2 - .5x + 1 # It also makes writing exponential functions more elegant 2^2x # The precedence of numeric literal coefficents is slightly lower than that of unary operators such as negation. # So, -2x is parsed as (-2) * x and √2x is parsed as (√2) * x. However, numeric literal coefficients parse # similarly to unary operators when combined with exponentiation. For example, 2^3x is parsed as 2 * (3x), and # 2x^3 is parsed as 2 * (x ^ 3). # Numeric literals also work as coefficients to parenthesized expressions. 2(x - 1)^2 - 3(x - 1) + 1 # **Note** # # The precedence of numeric literal coefficients used for implicit multiplication is higher than other binary # operators such as multiplication (*) and division(/, \, and //). This means, for example, that 1 / 2im equals # -0.5im and 6 // 2(2 + 1) equals 1 // 1. # Additionally, parenthesized expressions can be used as coefficients to variables, implying multiplication of the # expression by the variable: (x - 1)x # Neither juxtaposition of two parenthesized, nor placing a variable before a parenthesized expression, however, # can be used to imply multiplication. (x + 1)(x + 1) x(x + 1) # Instead, both expressions are interpreted as function application; that is, any expression that is **not** a # numeric literal, when immediately followed by a parenthetical, is interpreted as a function application to the # values in parentheses. # The above syntatic enhancements significantly reduce the visual noise incurred when writing common mathematical # formulae. Finally, note that **no** whitespace may come between a numeric literal coefficient and the identifier # or parenthisized expression which it multiplies.
import React from "react"; import { Icons, MakeIcon, Icon } from "./icons"; import { Chatbot } from "../../components"; import Ebet from "../../images/ebet.png"; import "./home.scss"; import { Spin } from "antd"; import { IChatbotPresentationalProps, ChatbotPresentational, } from "components/Chatbot/chatbotPresentational"; const Home: React.FC = () => { return ( <div className="Home"> <img src={Ebet} id="ebet" alt="Elephant Logo" /> <h1>Jameel Kelley</h1> <div id="icons"> {Icons.map((icon: Icon, i: number) => MakeIcon(icon.href, icon.icon, i) )} </div> <br /> <hr style={{ width: "80%" }} /> <br /> <Chatbot dataFileName={"chatbot_jamkelley.com"} loadingElement={<Spin />} render={(props: IChatbotPresentationalProps) => ( <ChatbotPresentational {...props} /> )} /> </div> ); }; export default Home;
use strict; use CXGN::Page; my $page=CXGN::Page->new("chromosome6.html","html2pl converter"); $page->header("Mapping information for chromosome 6"); print<<END_HEREDOC; <center> <h1>Chromosome 6</h1> <img alt="" src="/documents/maps/lpimp_ibl/IMAGES/lycopimp6.png" usemap="#synteny_map_chr6" /> <map name="synteny_map_chr6" id="synteny_map_chr6"> <area alt="" coords="370,62,492,72" href= "/search/markers/markerinfo.pl?marker_id=516" /> <area alt="" coords="370,165,484,176" href= "/search/markers/markerinfo.pl?marker_id=106" /> <area alt="" coords="370,289,473,299" href= "/search/markers/markerinfo.pl?marker_id=509" /> <area alt="" coords="370,478,473,489" href= "/search/markers/markerinfo.pl?marker_id=53" /> <area alt="" coords="370,592,491,603" href= "/search/markers/markerinfo.pl?marker_id=76" /> <area alt="" coords="370,754,483,765" href= "/search/markers/markerinfo.pl?marker_id=216" /> <area alt="" coords="370,812,468,822" href= "/search/markers/markerinfo.pl?marker_id=3187" /> <area alt="" coords="370,869,472,879" href= "/search/markers/markerinfo.pl?marker_id=3113" /> <area alt="" coords="370,906,484,917" href= "/search/markers/markerinfo.pl?marker_id=130" /> </map> </center> END_HEREDOC $page->footer();
{ DocuGes - Gestion Documental Autor: Fco. Javier Perez Vidal <developer at f-javier dot es> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA } unit aboutbox; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, Buttons, ComCtrls; type { TfAboutBox } TfAboutBox = class(TForm) btnSalir: TBitBtn; Imagen: TImage; Label1: TLabel; LVersion: TLabel; LNombre: TLabel; Label3: TLabel; Licencia: TMemo; pc: TPageControl; tsAbout: TTabSheet; tsLicencia: TTabSheet; procedure btnSalirClick(Sender: TObject); procedure FormClose(Sender: TObject; var CloseAction: TCloseAction); procedure FormCreate(Sender: TObject); private { private declarations } public { public declarations } end; var fAboutBox: TfAboutBox; implementation { TfAboutBox } uses recursostexto; procedure TfAboutBox.FormCreate(Sender: TObject); begin LVersion.Caption := 'DocuGes - Ver. 1.0 (Rev. 20)'; pc.ActivePage:=tsAbout; Imagen.Picture.LoadFromFile(DirectorioAplicacion+'about.png'); Licencia.Lines.LoadFromFile(UTF8ToAnsi(DirectorioAplicacion+'license.txt')); end; procedure TfAboutBox.btnSalirClick(Sender: TObject); begin Self.Close; end; procedure TfAboutBox.FormClose(Sender: TObject; var CloseAction: TCloseAction); begin CloseAction:=caFree; end; initialization {$I aboutbox.lrs} end.
using System; using System.Diagnostics; using DediLib; using Xunit; using Xunit.Abstractions; namespace Test.DediLib { public class TestInjectionContext { private readonly ITestOutputHelper _output; public TestInjectionContext(ITestOutputHelper output) { _output = output; } [Fact] public void Get_InterfaceNotRegistered_ThrowsInvalidOperationException() { using (var context = new InjectionContext()) { Assert.Throws<InvalidOperationException>(() => context.Get<ITestInterface>()); } } [Fact] public void TryGet_InterfaceNotRegistered_Null() { using (var context = new InjectionContext()) { Assert.Null(context.TryGet<ITestInterface>()); } } [Fact] public void Get_InterfaceRegistered_InstanceOfRegisteredInterface() { using (var context = new InjectionContext()) { context.Register<ITestInterface>(c => new TestClass()); Assert.IsAssignableFrom<TestClass>(context.Get<ITestInterface>()); } } [Fact] public void IsRegistered_InterfaceNotRegistered_False() { using (var context = new InjectionContext()) { Assert.False(context.IsRegistered<ITestInterface>()); Assert.False(context.IsRegistered(typeof(ITestInterface))); } } [Fact] public void IsRegistered_InterfaceRegistered_True() { using (var context = new InjectionContext()) { context.Register<ITestInterface>(c => new TestClass()); Assert.True(context.IsRegistered<ITestInterface>()); Assert.True(context.IsRegistered(typeof(ITestInterface))); } } [Fact] public void IsRegistered_SingletonRegistered_True() { using (var context = new InjectionContext()) { context.Singleton<ITestInterface>(c => new TestClass()); Assert.True(context.IsRegistered<ITestInterface>()); Assert.True(context.IsRegistered(typeof(ITestInterface))); } } [Fact] public void TryGet_InterfaceRegistered_InstanceOfRegisteredInterface() { using (var context = new InjectionContext()) { context.Register<ITestInterface>(c => new TestClass()); Assert.IsAssignableFrom<TestClass>(context.TryGet<ITestInterface>()); } } [Fact] public void Get_ClassWithNonPublicConstructor_ThrowsInvalidOperationException() { using (var context = new InjectionContext()) { Assert.Throws<InvalidOperationException>(() => context.Get<TestClassWithNonPublicConstructor>()); } } [Fact] public void TryGet_ClassWithNonPublicConstructor_Null() { using (var context = new InjectionContext()) { Assert.Null(context.TryGet<TestClassWithNonPublicConstructor>()); } } [Fact] public void Get_ClassWithInterfaceConstructor_InstanceForInterfaceIsCreated() { using (var context = new InjectionContext()) { context.Register<ITestInterface>(c => new TestClass()); var instance = context.Get<TestClassWithInterfaceConstructor>(); Assert.IsAssignableFrom<TestClass>(instance.TestInterface); } } [Fact] public void TryGet_ClassWithInterfaceConstructor_InstanceForInterfaceIsCreated() { using (var context = new InjectionContext()) { context.Register<ITestInterface>(c => new TestClass()); var instance = context.TryGet<TestClassWithInterfaceConstructor>(); Assert.IsAssignableFrom<TestClass>(instance.TestInterface); } } [Fact] public void Get_ClassWithIInjectionContextConstructor_InjectionContextIsPassedIntoConstructor() { using (var context = new InjectionContext()) { var instance = context.Get<TestClassWithIInjectionContext>(); Assert.Same(context, instance.InjectionContext); } } [Fact] public void TryGet_ClassWithIInjectionContextConstructor_InjectionContextIsPassedIntoConstructor() { using (var context = new InjectionContext()) { var instance = context.TryGet<TestClassWithIInjectionContext>(); Assert.Same(context, instance.InjectionContext); } } [Fact] public void Register_GenericTypeNotAnInterface_InvalidOperationException() { using (var context = new InjectionContext()) { Assert.Throws<InvalidOperationException>(() => context.Register(c => new TestClass())); } } [Fact] public void Register_GetTwice_DifferentInstances() { using (var context = new InjectionContext()) { context.Register<ITestInterface>(c => new TestClass()); var instance1 = context.Get<ITestInterface>(); var instance2 = context.Get<ITestInterface>(); Assert.IsAssignableFrom<TestClass>(instance1); Assert.IsAssignableFrom<TestClass>(instance2); Assert.NotSame(instance2, instance1); } } [Fact] public void RegisterGeneric_GetTwice_DifferentInstances() { using (var context = new InjectionContext()) { context.Register<ITestInterface, TestClass>(); var instance1 = context.Get<ITestInterface>(); var instance2 = context.Get<ITestInterface>(); Assert.IsAssignableFrom<TestClass>(instance1); Assert.IsAssignableFrom<TestClass>(instance2); Assert.NotSame(instance2, instance1); } } [Fact] public void Register_OverrideRegistration_LastRegisterWins() { using (var context = new InjectionContext()) { context.Register<ITestInterface>(c => new TestClass()); context.Register<ITestInterface>(c => new OtherTestClass()); Assert.IsAssignableFrom<OtherTestClass>(context.Get<ITestInterface>()); } } [Fact] public void RegisterGeneric_OverrideRegistration_LastRegisterWins() { using (var context = new InjectionContext()) { context.Register<ITestInterface, TestClass>(); context.Register<ITestInterface, OtherTestClass>(); Assert.IsAssignableFrom<OtherTestClass>(context.Get<ITestInterface>()); } } [Fact] public void Singleton_GenericTypeNotAnInterface_InvalidOperationException() { using (var context = new InjectionContext()) { Assert.Throws<InvalidOperationException>(() => context.Singleton(c => new TestClass())); } } [Fact] public void Singleton_GetTwice_SameInstance() { using (var context = new InjectionContext()) { context.Singleton<ITestInterface>(c => new TestClass()); var instance1 = context.Get<ITestInterface>(); var instance2 = context.Get<ITestInterface>(); Assert.Same(instance2, instance1); } } [Fact] public void SingletonGeneric_GetTwice_SameInstance() { using (var context = new InjectionContext()) { context.Singleton<ITestInterface, TestClass>(); var instance1 = context.Get<ITestInterface>(); var instance2 = context.Get<ITestInterface>(); Assert.Same(instance2, instance1); } } [Fact] public void Singleton_OverrideRegistration_LastRegisterWins() { using (var context = new InjectionContext()) { context.Singleton<ITestInterface>(c => new TestClass()); context.Singleton<ITestInterface>(c => new OtherTestClass()); Assert.IsAssignableFrom<OtherTestClass>(context.Get<ITestInterface>()); } } [Fact] public void SingletonGeneric_OverrideRegistration_LastRegisterWins() { using (var context = new InjectionContext()) { context.Singleton<ITestInterface, TestClass>(); context.Singleton<ITestInterface, OtherTestClass>(); Assert.IsAssignableFrom<OtherTestClass>(context.Get<ITestInterface>()); } } [Fact] public void CreateScope_inherits_registered_components_from_parent_scope() { using (var context = new InjectionContext()) { context.Register<ITestInterface>(c => new TestClass()); using (var subContext = context.CreateScope()) { Assert.IsAssignableFrom<TestClass>(subContext.Get<ITestInterface>()); } } } [Fact] public void CreateScope_child_scope_overrides_existing_parent_registration() { using (var context = new InjectionContext()) { context.Register<ITestInterface>(c => new TestClass()); using (var subContext = context.CreateScope()) { subContext.Register<ITestInterface>(c => new OtherTestClass()); Assert.IsAssignableFrom<OtherTestClass>(subContext.Get<ITestInterface>()); } } } [Fact] public void CreateScope_parent_scope_changes_do_not_affect_child_scopes() { using (var context = new InjectionContext()) { context.Register<ITestInterface>(c => new TestClass()); using (var subContext = context.CreateScope()) { context.Register<ITestInterface>(c => new OtherTestClass()); Assert.IsAssignableFrom<OtherTestClass>(context.Get<ITestInterface>()); Assert.IsAssignableFrom<TestClass>(subContext.Get<ITestInterface>()); } } } [Trait("Category", "Benchmark")] [Fact] public void Benchmark_RegisterGet_TestClass() { using (var context = new InjectionContext()) { context.Register<ITestInterface, TestClass>(); const int count = 10000000; var sw = Stopwatch.StartNew(); for (var i = 0; i < count; i++) { context.Get<ITestInterface>(); } sw.Stop(); var opsPerSec = count / sw.Elapsed.TotalMilliseconds * 1000; _output.WriteLine($"{sw.Elapsed} ({opsPerSec:N0} ops/sec)"); } } [Trait("Category", "Benchmark")] [Fact] public void Benchmark_SingletonGet_TestClass() { using (var context = new InjectionContext()) { context.Singleton<ITestInterface>(c => new TestClass()); const int count = 10000000; var sw = Stopwatch.StartNew(); for (var i = 0; i < count; i++) { context.Get<ITestInterface>(); } sw.Stop(); var opsPerSec = count / sw.Elapsed.TotalMilliseconds * 1000; _output.WriteLine($"{sw.Elapsed} ({opsPerSec:N0} ops/sec)"); } } private class TestClass : ITestInterface { } private class OtherTestClass : ITestInterface { } // ReSharper disable once ClassNeverInstantiated.Local private class TestClassWithNonPublicConstructor { private TestClassWithNonPublicConstructor() { } } public class TestClassWithIInjectionContext { public IInjectionContext InjectionContext { get; } public TestClassWithIInjectionContext(IInjectionContext injectionContext) { InjectionContext = injectionContext; } } public class TestClassWithInterfaceConstructor { public ITestInterface TestInterface { get; } public TestClassWithInterfaceConstructor(ITestInterface testInterface) { TestInterface = testInterface; } } public interface ITestInterface { } public interface ISingleInterface { } public class SingleClass : ISingleInterface { } public interface IMultipleInterface { } public class MultipleClass1 : IMultipleInterface { } public class MultipleClass2 : IMultipleInterface { } } }
create dabatabase dashboard; create user 'dashboard'@'localhost' identified by 'dashboard'; GRANT ALL PRIVILEGES ON * . * TO 'dashboard'@'localhost'; use dashboard; /* Modulos de Puppet */ create table modulos ( id_modulo int not null auto_increment, nombre char(25) not null unique, primary key (id_modulo) ); insert into modulos (nombre) values ('$nombre_modulo'); /* Clases de los modulos */ create table clases ( id_modulo int not null, id_clase int not null auto_increment, nombre char(25) not null unique, primary key (id_clase), foreign key (id_modulo) refences modulos (id_modulo) ); /* Nodos servidos por puppet */ create table nodos ( id_nodo int not null auto_increment, ip_addr varchar(15), mac_addr varchar(17) unique, hostname varchar(32), primary key (id_nodo) ); 192.168.123.124 91:75:1a:ec:9a:c7 /* Querys utiles */ delete from tabla; alter table tabla auto_increment=1;
function Get-CommandDefinitionHtml { # this tells powershell to allow advanced features, # like the [validatenotnullorempty()] attribute below. [CmdletBinding()] param( [ValidateNotNullOrEmpty()] [string]$name ) $command = get-command $name # Look mom! I'm a cmdlet! $PSCmdlet.WriteVerbose("Dumping HTML for " + $command) @" <html> <head> <title>$($command.name)</title> </head> <body> <table border="1"> $( $command.parametersets | % { @" <tr> <td>$($_.name)</td> <td> <table border="1"> <tr> <th colspan="8">Parameters</th> $( $count = 0 $_.parameters | % { if (0 -eq ($count % 8)) { @' </tr> <tr> '@ } @" <td>$($_.name)</td> "@ $count++ } ) </tr> </table> </td> </tr> "@ } ) </table> </body> </html> "@ } Get-CommandDefinitionHtml get-item > out.html # show in browser invoke-item out.html
# added for Dartium # export DART_SDK=/usr/local/opt/dart/libexec # export DARTIUM=/usr/local/opt/dart/Chromium.app
inherited frmCadProdutos: TfrmCadProdutos Caption = 'Cadastro de Produtos' ClientHeight = 407 PixelsPerInch = 96 TextHeight = 13 inherited PageControl1: TPageControl Height = 388 inherited TabSheet1: TTabSheet inherited DBText1: TDBText DataField = 'PRO_CODIGO' end object Label2: TLabel [2] Left = 16 Top = 56 Width = 48 Height = 13 Caption = 'Descri'#231#227'o' FocusControl = dbeDescricao Transparent = True end object Label3: TLabel [3] Left = 16 Top = 96 Width = 52 Height = 13 Caption = 'Refer'#234'ncia' FocusControl = dbeReferencia Transparent = True end object Label4: TLabel [4] Left = 160 Top = 96 Width = 54 Height = 13 Caption = 'Fornecedor' FocusControl = cmbFornecedor Transparent = True end object Label5: TLabel [5] Left = 16 Top = 137 Width = 40 Height = 13 Caption = 'Unidade' FocusControl = cmbUND Transparent = True end object Label6: TLabel [6] Left = 86 Top = 137 Width = 78 Height = 13 Caption = 'Valor de Compra' FocusControl = dbeVLCOMP Transparent = True end object Label7: TLabel [7] Left = 240 Top = 137 Width = 73 Height = 13 Caption = 'Valor de Venda' FocusControl = dbeVLVEND Transparent = True end object Label8: TLabel [8] Left = 16 Top = 180 Width = 58 Height = 13 Caption = 'Observa'#231#227'o' FocusControl = DBMemo1 Transparent = True end object Label9: TLabel [9] Left = 395 Top = 137 Width = 68 Height = 13 Caption = 'Data Cadastro' FocusControl = dbeVLVEND Transparent = True end inherited pnlBotoes: TPanel Top = 319 TabOrder = 1 end object dbeDescricao: TDBEdit Left = 16 Top = 72 Width = 500 Height = 21 CharCase = ecUpperCase DataField = 'PRO_DESCRICAO' DataSource = dsCadastro TabOrder = 2 end object dbeReferencia: TDBEdit Left = 16 Top = 112 Width = 137 Height = 21 DataField = 'PRO_REFERENCIA' DataSource = dsCadastro TabOrder = 3 OnExit = dbeReferenciaExit end object cmbFornecedor: TDBLookupComboBox Left = 160 Top = 112 Width = 355 Height = 21 DataField = 'PRO_NMFORN' DataSource = dsCadastro TabOrder = 4 end object cmbUND: TDBLookupComboBox Left = 16 Top = 153 Width = 65 Height = 21 DataField = 'PRO_NMUNID' DataSource = dsCadastro TabOrder = 5 end object dbeVLCOMP: TDBEdit Left = 86 Top = 153 Width = 150 Height = 21 DataField = 'PRO_VLCOMPRA' DataSource = dsCadastro TabOrder = 6 end object dbeVLVEND: TDBEdit Left = 240 Top = 153 Width = 150 Height = 21 DataField = 'PRO_VLVENDA' DataSource = dsCadastro TabOrder = 7 end object DBDateEdit1: TDBDateEdit Left = 395 Top = 153 Width = 121 Height = 21 TabStop = False DataField = 'PRO_DTCADASTRO' DataSource = dsCadastro ReadOnly = True NumGlyphs = 2 TabOrder = 8 end object DBMemo1: TDBMemo Left = 16 Top = 196 Width = 500 Height = 94 DataField = 'PRO_OBSERVACAO' DataSource = dsCadastro ScrollBars = ssVertical TabOrder = 9 end object DBRadioGroup1: TDBRadioGroup Left = 331 Top = 16 Width = 185 Height = 41 Caption = '[ Tipo de Produto ]' Columns = 2 DataField = 'PRO_FLPROD' DataSource = dsCadastro Items.Strings = ( 'Produto' 'Servi'#231'o') TabOrder = 0 Values.Strings = ( 'P' 'S') end object Panel1: TPanel Left = 565 Top = 0 Width = 34 Height = 319 Align = alRight TabOrder = 10 object sbUlti: TSpeedButton Left = 5 Top = 83 Width = 25 Height = 35 Hint = 'Pr'#243'ximo registro' Enabled = False Flat = True Glyph.Data = { 76060000424D7606000000000000360400002800000018000000180000000100 0800000000004002000000000000000000000001000000000000FFFFFF00FFE6 E600FEE5E500FCE3E300FBE1E100F9DFE000F7DDDE00F7DDDD00F5DBDB00F4DB DB00F2D9D900E6D9D900F0D6D700EED4D400EBD2D200E9D0D000E9CFD000E7CD CD00E5CBCB00E3C9C900E0C7C700DEC4C400DCC2C200CCC0C000D9C0BF00D7BE BD00D4BBBB00D3B9B900D0B7B700CFB5B500CEB4B400CCB3B300C9B0B000C7AE AE00C5ACAC00C3AAAA00C1A8A800C1A7A700BFA5A500BDA3A300BCA3A300BAA0 A100BAA1A000B89E9E00B59C9C00B39A9A00AF969600AD949400A88F8F00A68D 8D00A18888009F8686009B8382009A818100998080006633330000000000C0C0 C000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000393939393939 3939393939393939393939393939393939393939393939393939393939393939 3939393939393939393939393939393939393939393939393939393939393939 3939393939393939393939393939393939393939393939393939393939393939 3939393939393939393939393939393939393939393939393939393939003939 3939393939393939393939393939393939393939000037393939393939393939 39393939393939393939390000370D3839393939393939393939393939393939 39390000370D260D383939393939393939393939393939393900003706260D2E 1138393939393939393939393939393900003706260D2C112E15383939393939 3939393939393900003705210D2B112E15311938393939393939393939390000 3706210D261038143019331D383939393939393939000037012106260D383938 18331D331D38393939393939000037012106260D3839393938193321331D3839 393939393937011D05250C3839393939393821331D170B383939393939393801 25063839393939393939381D170B383939393939393939380638393939393939 393939380B383939393939393939393938393939393939393939393938393939 3939393939393939393939393939393939393939393939393939393939393939 3939393939393939393939393939393939393939393939393939393939393939 3939393939393939393939393939393939393939393939393939393939393939 3939393939393939393939393939393939393939393939393939} ParentShowHint = False ShowHint = True OnClick = sbProximoClick end object sbProx: TSpeedButton Left = 5 Top = 122 Width = 25 Height = 35 Hint = #218'ltimo registro' Enabled = False Flat = True Glyph.Data = { 96010000424D9601000000000000760000002800000018000000180000000100 0400000000002001000000000000000000001000000000000000FFFFFF006130 30006E3D3D00916161009E6E6E00C2919100CF9E9E00C0C0C000000000000000 0000000000000000000000000000000000000000000000000000777777777777 7777777777777777777777777777777777777777777777777777777777777777 7777777777777777777777777777777077777777777777777777770027777777 7777777777777002327777777777777777770023432777777777777777700234 3432777777777777770023434343277777777777700234343434327777777777 0025656565656547777777700256565656565654777777772121212121212121 2777777777777777777777777777777000000000000000007777777034343434 3434343617777770456565656565656527777770365656565656565617777770 4565656565656565277777771212121212121212177777777777777777777777 7777777777777777777777777777777777777777777777777777} ParentShowHint = False ShowHint = True OnClick = sbUltimoClick end object sbAnte: TSpeedButton Left = 5 Top = 44 Width = 25 Height = 35 Hint = 'Registro anterior' Enabled = False Flat = True Glyph.Data = { 76060000424D7606000000000000360400002800000018000000180000000100 0800000000004002000000000000000000000001000000000000FFFFFF00FEE5 E400FDE3E300FBE1E100F9DFE000F7DEDD00F4DBDB00F2D9D900E6D9D900F0D7 D700EED4D400EBD2D200E9CFCF00E7CECD00E5CBCB00E3C9C900E0C6C700DEC4 C500DBC2C200D9C0C000CDC0C000CCC0C000D7BDBD00D5BBBB00D3B9B900D1B7 B700CFB6B500CFB5B500CDB4B400CCB3B300C7AEAE00C6ACAC00C1A8A800BFA6 A600BAA0A100B89E9E00B39A9A00B1989800AD949400AA919100A68D8D00A38A 8A009F8686009D8484009C8283009A818100998080006633330000000000C0C0 C000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000313131313131 3131313131313131313131313131313131313131313131313131313131313131 3131313131313131313131313131313131313131313131313131313131313131 3131313131313131313131313131313131313131313131313131313131313131 3131313131313131313131313131313131313131313131003131313131313131 313131003131313131313131313100002F31313131313131313100002F313131 313131313100002F01303131313131313100002F1A3031313131313100002F01 1E0530313131313100002F1A2A1A303131313131312F011E05210A3031313100 002F1E2A1A1408303131313131313004210A230D303100002F1E2A1A14083031 313131313131313005210D241130002F1A2A1A16083031313131313131313131 300A240D26162F1A2A1A140830313131313131313131313131300D2611281A2A 1A1408303131313131313131313131313131301128162A1A1408303131313131 313131313131313131313130162A1A1408303131313131313131313131313131 3131313130191408303131313131313131313131313131313131313131300830 3131313131313131313131313131313131313131313130313131313131313131 3131313131313131313131313131313131313131313131313131313131313131 3131313131313131313131313131313131313131313131313131313131313131 3131313131313131313131313131313131313131313131313131313131313131 3131313131313131313131313131313131313131313131313131} ParentShowHint = False ShowHint = True OnClick = sbAnteriorClick end object spPrim: TSpeedButton Left = 5 Top = 6 Width = 25 Height = 35 Hint = 'Primeiro registro' Enabled = False Flat = True Glyph.Data = { 96010000424D9601000000000000760000002800000018000000180000000100 0400000000002001000000000000000000001000000000000000FFFFFF006130 30006E3D3D00916161009E6E6E00C2919100CF9E9E00C0C0C000000000000000 0000000000000000000000000000000000000000000000000000777777777777 7777777777777777777777777777777777777777777777777777777777777770 0000000000000000777777703434343434343436177777704565656565656565 2777777036565656565656561777777045656565656565652777777712121212 1212121217777777777777777777777777777777777777777777777777777770 0000000000000000777777771212121212121212177777777143434343434341 7777777777143434343656177777777777714343436561777777777777771434 3656177777777777777771436561777777777777777777165617777777777777 7777777161777777777777777777777717777777777777777777777777777777 7777777777777777777777777777777777777777777777777777} ParentShowHint = False ShowHint = True OnClick = sbPrimeiroClick end end end inherited TabSheet2: TTabSheet inherited pnlProcurar: TPanel inherited btnConsultar: TBitBtn OnClick = btnConsultarClick end end inherited Panel3: TPanel Height = 287 end inherited grdConsultar: TDBGrid Height = 287 OnDblClick = btnConsultarClick Columns = < item Expanded = False FieldName = 'PRO_CODIGO' Title.Caption = 'C'#243'digo' Title.Font.Charset = ANSI_CHARSET Title.Font.Color = clWindowText Title.Font.Height = -11 Title.Font.Name = 'Verdana' Title.Font.Style = [fsBold] Width = 92 Visible = True end item Expanded = False FieldName = 'PRO_DESCRICAO' Title.Caption = 'Descri'#231#227'o' Title.Font.Charset = ANSI_CHARSET Title.Font.Color = clWindowText Title.Font.Height = -11 Title.Font.Name = 'Verdana' Title.Font.Style = [fsBold] Width = 303 Visible = True end item Expanded = False FieldName = 'PRO_VLVENDA' Title.Alignment = taRightJustify Title.Caption = 'Valor Venda' Title.Font.Charset = ANSI_CHARSET Title.Font.Color = clWindowText Title.Font.Height = -11 Title.Font.Name = 'Verdana' Title.Font.Style = [fsBold] Width = 96 Visible = True end> end end end inherited StatusBar1: TStatusBar Top = 388 end inherited dsConsultar: TDataSource Left = 252 Top = 266 end inherited dspConsultar: TDataSetProvider Left = 332 Top = 266 end inherited cdsConsultar: TClientDataSet Left = 364 Top = 266 object cdsConsultarPRO_CODIGO: TStringField FieldName = 'PRO_CODIGO' Required = True FixedChar = True Size = 13 end object cdsConsultarPRO_REFERENCIA: TStringField FieldName = 'PRO_REFERENCIA' Size = 14 end object cdsConsultarPRO_DESCRICAO: TStringField FieldName = 'PRO_DESCRICAO' Required = True Size = 60 end object cdsConsultarPRO_VLVENDA: TFMTBCDField FieldName = 'PRO_VLVENDA' DisplayFormat = '###,##0.#0' EditFormat = '###,##0.#0' Precision = 18 Size = 2 end end inherited dsCadastro: TDataSource DataSet = dmDados.cdsProduto Left = 212 Top = 264 end inherited datasetConsultar: TSQLDataSet CommandText = 'select PRO_CODIGO, PRO_REFERENCIA, PRO_DESCRICAO, PRO_VLVENDA fr' + 'om PRODUTOS' Left = 292 Top = 264 end object dstNavegacao: TSQLDataSet CommandText = 'Select PRO_CODIGO, PRO_DESCRICAO from PRODUTOS order by PRO_DESC' + 'RICAO' MaxBlobSize = -1 Params = <> SQLConnection = dmDados.sqlConexao Left = 388 Top = 200 end object dspNavegacao: TDataSetProvider DataSet = dstNavegacao Options = [poAllowCommandText] Left = 428 Top = 200 end object cdsNavegavacao: TClientDataSet Aggregates = <> Params = <> ProviderName = 'dspNavegacao' Left = 468 Top = 200 object cdsNavegavacaoPRO_CODIGO: TStringField FieldName = 'PRO_CODIGO' Required = True FixedChar = True Size = 13 end object cdsNavegavacaoPRO_DESCRICAO: TStringField FieldName = 'PRO_DESCRICAO' Required = True Size = 60 end end object dsNavegacao: TDataSource DataSet = cdsNavegavacao OnDataChange = dsNavegacaoDataChange Left = 500 Top = 200 end end
#!/bin/bash # This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. # A virtual env names benchmark has been created # and has all the qiskit-app-benchmarks requirements-dev.txt # dependencies installed # lock file with this file name and containing the pid LOCKFILE=/tmp/`basename $0`.lock if [ -f $LOCKFILE ]; then if ps -p `cat $LOCKFILE` > /dev/null 2>&1; then echo "Script $0 is still running." exit 0 fi fi echo 'Start script ...' echo $$ > $LOCKFILE # Removes the file if: # EXIT - normal termination # SIGHUP - termination of the controlling process # SIGKILL - immediate program termination # SIGINT - program interrupt INTR character # SIGQUIT - program interrupt QUIT characte # SIGTERM - program termination by kill trap 'rm -f "$LOCKFILE" >/dev/null 2>&1' EXIT HUP KILL INT QUIT TERM # find if asv is installed ASV_CMD="asv" if command -v $ASV_CMD > /dev/null 2>&1; then echo "asv command is available in known paths." else ASV_CMD="/usr/local/bin/asv" if command -v $ASV_CMD > /dev/null 2>&1; then echo "asv command is available at $ASV_CMD" else echo "asv command not found in any known path." exit 1 fi fi echo "echo $3" > /tmp/.git-askpass chmod +x /tmp/.git-askpass export GIT_ASKPASS=/tmp/.git-askpass source /opt/benchmark/bin/activate set -e echo 'qiskit-app-benchmarks was already cloned in opt and is checkout to main branch' echo 'qiskit-app-benchmarks has a gh-pages branch with the html contents in it' rm -rf /tmp/qiskit-app-benchmarks git clone https://$2@github.com/$1/qiskit-app-benchmarks.git /tmp/qiskit-app-benchmarks git pull make clean_sphinx make html SPHINXOPTS=-W echo 'Copy main docs' pushd /tmp/qiskit-app-benchmarks git config user.name "Qiskit Application Benchmarks Autodeploy" git config user.email "qiskit@qiskit.org" git checkout gh-pages GLOBIGNORE=.git:finance:machine_learning:nature:optimization rm -rf * .* unset GLOBIGNORE popd declare -a targets=("finance" "nature" "optimization" "machine_learning") # copy base html to benchmarks gh-pages branch rm -rf /tmp/qiskit-app-benchmarks-html mkdir /tmp/qiskit-app-benchmarks-html cp -r docs/_build/html/. /tmp/qiskit-app-benchmarks-html for target in "${targets[@]}" do rm -rf /tmp/qiskit-app-benchmarks-html/$target done cp -r /tmp/qiskit-app-benchmarks-html/. /tmp/qiskit-app-benchmarks pushd /tmp/qiskit-app-benchmarks git add . # push only if there are changes if git diff-index --quiet HEAD --; then echo 'Nothing to commit for the base doc template.' else git commit -m "[Benchmarks] Base documentation update" fi popd echo 'Run Benchmarks for domains' for target in "${targets[@]}" do pushd $target if [ -n "$(find benchmarks/* -not -name '__*' | head -1)" ]; then date asv_result=0 if [ -z "$ASV_QUICK" ]; then echo "Run Benchmarks for domain $target" $ASV_CMD run --show-stderr --launch-method spawn --record-samples NEW && asv_result=$? || asv_result=$? else echo "Run Quick Benchmarks for domain $target" $ASV_CMD run --quick --show-stderr && asv_result=$? || asv_result=$? fi date echo "asv command returned $asv_result for domain $target" if [ $asv_result == 0 ]; then echo "Publish Benchmark for domain $target" $ASV_CMD publish rm -rf /tmp/qiskit-app-benchmarks/$target/* cp -r .asv/html/. /tmp/qiskit-app-benchmarks/$target fi else rm -rf /tmp/qiskit-app-benchmarks/$target/* cp -r ../docs/_build/html/$target/. /tmp/qiskit-app-benchmarks/$target echo "No Benchmark files found for domain $target, run skipped." fi popd pushd /tmp/qiskit-app-benchmarks git add . # push only if there are changes if git diff-index --quiet HEAD --; then echo "Nothing to push for $target." else echo "Push benchmark for $target." git commit -m "[Benchmarks $target] Automated documentation update" git push origin gh-pages fi popd done echo 'Final Cleanup' unset GIT_ASKPASS rm /tmp/.git-askpass rm -rf /tmp/qiskit-app-benchmarks rm -rf /tmp/qiskit-app-benchmarks-html echo 'End of script.'
// @ts-check const { getConfig } = require('@airbnb/config-babel'); const { getSettings } = require('@airbnb/nimbus-common'); const { context, tool } = process.beemo; const { graphql, library, next, node, react, env } = getSettings(); module.exports = getConfig({ env, esm: !!(context.args.esm || process.env.ESM), graphql, library, next, node, react, typescript: tool.isPluginEnabled('driver', 'typescript'), });
Rails.application.routes.draw do mount Korgi::Engine => "/korgi" namespace :admin do resources :posts end resources :posts end
ALTER EXTERNAL DATA SOURCE hadoop_eds SET LOCATION = 'hdfs://10.10.10.10:8020', RESOURCE_MANAGER_LOCATION = '10.10.10.10:8032' ; ALTER EXTERNAL DATA SOURCE hadoop_eds SET CREDENTIAL = new_hadoop_user ; ALTER EXTERNAL DATA SOURCE MyAzureInvoices WITH ( TYPE = BLOB_STORAGE, LOCATION = 'https://newinvoices.blob.core.windows.net', CREDENTIAL = UploadInvoices );
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE CPP #-} module Test.Hspec.Wai.Internal ( WaiExpectation , WaiSession(..) , runWaiSession , runWithState , withApplication , getApp , getState , formatHeader ) where import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Monad.Trans.Reader import Network.Wai (Application) import Network.Wai.Test hiding (request) import Test.Hspec.Core.Spec import Test.Hspec.Wai.Util (formatHeader) #if MIN_VERSION_base(4,9,0) import Control.Monad.Fail #endif -- | An expectation in the `WaiSession` monad. Failing expectations are -- communicated through exceptions (similar to `Test.Hspec.Expectations.Expectation` and -- `Test.HUnit.Base.Assertion`). type WaiExpectation st = WaiSession st () -- | A <http://www.yesodweb.com/book/web-application-interface WAI> test -- session that carries the `Application` under test and some client state. newtype WaiSession st a = WaiSession {unWaiSession :: ReaderT st Session a} deriving (Functor, Applicative, Monad, MonadIO #if MIN_VERSION_base(4,9,0) , MonadFail #endif ) runWaiSession :: WaiSession () a -> Application -> IO a runWaiSession action app = runWithState action ((), app) runWithState :: WaiSession st a -> (st, Application) -> IO a runWithState action (st, app) = runSession (flip runReaderT st $ unWaiSession action) app withApplication :: Application -> WaiSession () a -> IO a withApplication = flip runWaiSession instance Example (WaiExpectation st) where type Arg (WaiExpectation st) = (st, Application) evaluateExample e p action = evaluateExample (action $ runWithState e) p ($ ()) getApp :: WaiSession st Application getApp = WaiSession (lift ask) getState :: WaiSession st st getState = WaiSession ask
package org.patternfly.sample internal interface FormSample { fun form() { } }
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use Gufy\PdfToHtml\Config; use setasign\Fpdi\Fpdi; use setasign\Fpdi\PdfReader; use App\Http\Controllers\Controller; use Validator; use App\Form; use App\Notifications; class DonorController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } public function view(Request $request) { $page = $this->getPage($request); return view($page['template'], $page); } public function create(Request $request){ $validator = Validator::make($request->all(), [ 'first_name' => ['required', 'string', 'max:255'], 'last_name' => ['required', 'string', 'max:255'], 'address' => ['required', 'string', 'max:255'], 'city' => ['required', 'string', 'max:255'], 'state' => ['required', 'string', 'max:2'], 'zip' => ['required', 'integer'], 'user' => ['required', 'integer'], ]); if ($validator->fails()) { return redirect('admin/donors') ->withErrors($validator) ->withInput(); } else{ $user = new \App\Donor(); $user->user_id = $request->input('user'); $user->donor_id = $request->input('donor_id'); $user->first_name = $request->input('first_name'); $user->last_name = $request->input('last_name'); $user->address= $request->input('address'); $user->address2= $request->input('address2'); $user->city= $request->input('city'); $user->state= $request->input('state'); $user->zipcode= $request->input('zip'); $user->phone_home= $request->input('home_phone'); $user->phone_cell= $request->input('cell_phone'); $user->save(); return redirect('admin/donors')->with('success','Donor created successfully!'); } } public function update(Request $request){ $validator = Validator::make($request->all(), [ 'id' => ['required'], 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255'], 'password' => ['sometimes', 'confirmed'], ]); if ($validator->fails()) { return redirect('admin/users') ->withErrors($validator) ->withInput(); } else{ $user = \App\User::where('id', $request->input('id'))->first(); $user->name = $request->input('name'); $user->email = $request->input('email'); $user->password = bcrypt($request->input('password')); $user->active = $request->input('status') == "on" ? 1:0; $user->update(); $roles = []; foreach($request->input('role') as $key => $value){ $roles[] = $key; } $user->permissions()->sync($roles); return redirect('admin/users')->with('success','User updated successfully!'); } } }
export const LoginServiceFactory = () => ({ events: {subscribe: f => f}, complete: true });
cp tests/stu2 tests/7.out ./addstu tests/7.out 5056789 "Tom Jones" 3778 80.5
#! /bin/bash # reference: https://blogs.msdn.microsoft.com/commandline/2017/12/08/cross-post-wsl-interoperability-with-docker/ export GO_VERSION=1.9.4 echo "Installing go $GO_VERSION" wget https://dl.google.com/go/go${GO_VERSION}.linux-amd64.tar.gz sudo tar -C /usr/local -xzf go${GO_VERSION}.linux-amd64.tar.gz export PATH=$PATH:/usr/local/go/bin echo "Installing the relay program" go get -d github.com/jstarks/npiperelay GOOS=windows go build -o /mnt/c/Users/${USER}/go/bin/npiperelay.exe github.com/jstarks/npiperelay sudo ln -s /mnt/c/Users/${USER}/go/bin/npiperelay.exe /usr/local/bin/npiperelay.exe echo "Installing Docker CE and socat" curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository \ "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt-get update && sudo apt-get install socat docker-ce echo "Installing Docker Compose" export COMPOSE_VERSION=1.20.1 sudo curl -L \ https://github.com/docker/compose/releases/download/$COMPOSE_VERSION/docker-compose-`uname -s`-`uname -m` \ -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose echo "Creating local relay daemon script" cp docker-relay ~/docker-relay chmod +x ~/docker-relay echo "Adding $USER to the docker group" sudo adduser $USER docker echo "Removing 'docker-compose' aliases in '$HOME/.bashrc'" sed -i -s '/alias docker-compose/d' $HOME/.bashrc echo "Close this session and open another to activate 'docker' group membership."
/* * MCA implementation for AMD CPUs * Copyright (c) 2007-2012 Advanced Micro Devices, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; If not, see <http://www.gnu.org/licenses/>. */ #ifndef X86_MCA_H #define X86_MCA_H #include <public/arch-x86/xen-mca.h> /* The MCA/MCE MSRs should not be used anywhere else. * They are cpu family/model specific and are only for use * in terms of machine check handling. * So we define them here rather in <asm/msr.h>. */ /* Bitfield of the MSR_IA32_MCG_CAP register */ #define MCG_CAP_COUNT 0x00000000000000ffULL #define MCG_CTL_P (1ULL<<8) #define MCG_EXT_P (1ULL<<9) /* Intel specific */ #define MCG_CMCI_P (1ULL<<10) /* Intel specific */ #define MCG_TES_P (1ULL<<11) /* Intel specific */ #define MCG_EXT_CNT 16 /* Intel specific */ #define MCG_SER_P (1ULL<<24) /* Intel specific */ /* Other bits are reserved */ /* Bitfield of the MSR_IA32_MCG_STATUS register */ #define MCG_STATUS_RIPV 0x0000000000000001ULL #define MCG_STATUS_EIPV 0x0000000000000002ULL #define MCG_STATUS_MCIP 0x0000000000000004ULL /* Bits 3-63 are reserved */ /* Bitfield of MSR_K8_MCi_STATUS registers */ /* MCA error code */ #define MCi_STATUS_MCA 0x000000000000ffffULL /* model-specific error code */ #define MCi_STATUS_MSEC 0x00000000ffff0000ULL /* Other information */ #define MCi_STATUS_OTHER 0x01ffffff00000000ULL /* Action Required flag */ #define MCi_STATUS_AR 0x0080000000000000ULL /* Intel specific */ /* Signaling flag */ #define MCi_STATUS_S 0x0100000000000000ULL /* Intel specific */ /* processor context corrupt */ #define MCi_STATUS_PCC 0x0200000000000000ULL /* MSR_K8_MCi_ADDR register valid */ #define MCi_STATUS_ADDRV 0x0400000000000000ULL /* MSR_K8_MCi_MISC register valid */ #define MCi_STATUS_MISCV 0x0800000000000000ULL /* error condition enabled */ #define MCi_STATUS_EN 0x1000000000000000ULL /* uncorrected error */ #define MCi_STATUS_UC 0x2000000000000000ULL /* status register overflow */ #define MCi_STATUS_OVER 0x4000000000000000ULL /* valid */ #define MCi_STATUS_VAL 0x8000000000000000ULL /* Bitfield of MSi_STATUS_OTHER field */ /* reserved bits */ #define MCi_STATUS_OTHER_RESERVED1 0x00001fff00000000ULL /* uncorrectable ECC error */ #define MCi_STATUS_OTEHR_UC_ECC 0x0000200000000000ULL /* correctable ECC error */ #define MCi_STATUS_OTHER_C_ECC 0x0000400000000000ULL /* ECC syndrome of an ECC error */ #define MCi_STATUS_OTHER_ECC_SYNDROME 0x007f800000000000ULL /* reserved bits */ #define MCi_STATUS_OTHER_RESERVED2 0x0180000000000000ULL /* Bitfield of MSR_K8_HWCR register */ #define K8_HWCR_MCi_STATUS_WREN (1ULL << 18) /*Intel Specific bitfield*/ #define MCi_MISC_ADDRMOD_MASK (0x7UL << 6) #define MCi_MISC_PHYSMOD (0x2UL << 6) #include <asm/domain.h> struct mca_banks { int num; unsigned long *bank_map; }; static inline void mcabanks_clear(int bit, struct mca_banks *banks) { if (!banks || !banks->bank_map || bit >= banks->num) return ; clear_bit(bit, banks->bank_map); } static inline void mcabanks_set(int bit, struct mca_banks* banks) { if (!banks || !banks->bank_map || bit >= banks->num) return; set_bit(bit, banks->bank_map); } static inline int mcabanks_test(int bit, struct mca_banks* banks) { if (!banks || !banks->bank_map || bit >= banks->num) return 0; return test_bit(bit, banks->bank_map); } struct mca_banks *mcabanks_alloc(void); void mcabanks_free(struct mca_banks *banks); extern struct mca_banks *mca_allbanks; /* Keep bank so that we can get status even if mib is NULL */ struct mca_binfo { int bank; struct mcinfo_global *mig; struct mcinfo_bank *mib; struct mc_info *mi; struct cpu_user_regs *regs; }; enum mce_result { MCER_NOERROR, MCER_RECOVERED, /* Not recovered, but can continue */ MCER_CONTINUE, MCER_RESET, }; struct mca_error_handler { /* Assume corresponding recovery action could be uniquely * identified by mca_code. Otherwise, we might need to have * a seperate function to decode the corresponding actions * for the particular mca error later. */ int (*owned_error)(uint64_t status); void (*recovery_handler)(struct mca_binfo *binfo, enum mce_result *result, const struct cpu_user_regs *regs); }; /* Global variables */ extern bool_t mce_disabled; #endif /* X86_MCA_H */
package me.kalmanbncz.nd.ar.entity; import com.badlogic.gdx.math.Vector3; public class GroundMovement extends Movement { public GroundMovement(int entityId) { super(entityId); } @Override void accelerate(float timeStep) { Vector3 diff = tmp; diff.set(destination).sub(position); // no vertical velocity, no matter the height of the destination diff.y = 0f; acceleration.set(diff).nor().scl(accelRate).scl(timeStep); //Log.log("ground accelerate: " + Tools.fmt(acceleration)); velocity.add(acceleration); } }
/*++ Copyright (c) 1997 Microsoft Corporation Module Name: stack.c Abstract: Dumps the AML Context Structure in Human-Readable-Form (HRF) Author: Stephane Plante (splante) 26-Oct-1997 Environment: User Mode. Revision History: --*/ #include "pch.h" VOID stackArgument( IN ULONG_PTR ObjectAddress ) { BOOL result; OBJDATA object; PUCHAR buffer = NULL; ULONG returnLength; // // Read the object // result = ReadMemory( ObjectAddress, &object, sizeof(OBJDATA), &returnLength ); if (!result || returnLength != sizeof(OBJDATA)) { dprintf("_BAD_"); return; } if (object.pbDataBuff != 0) { buffer = LocalAlloc( LPTR, object.dwDataLen+1 ); if (buffer == NULL) { dprintf("_MEM_"); return; } result = ReadMemory( (ULONG_PTR) object.pbDataBuff, buffer, object.dwDataLen, &returnLength ); if (!result || returnLength != object.dwDataLen) { dprintf("_BUF_"); return; } } switch (object.dwDataType) { case OBJTYPE_INTDATA: dprintf("0x%x", object.uipDataValue); break; case OBJTYPE_STRDATA: buffer[object.dwDataLen] = '\0'; dprintf("%s",buffer); break; case OBJTYPE_BUFFDATA: dprintf( "<buffer> %08lx-%08lx", object.pbDataBuff, object.pbDataBuff+object.dwDataLen ); break; case OBJTYPE_PKGDATA: dprintf("<package> %08lx", ObjectAddress ); break; case OBJTYPE_FIELDUNIT: dprintf("<fieldunit> %08lx", ObjectAddress ); break; case OBJTYPE_DEVICE: dprintf("<device> %08lx", ObjectAddress ); break; case OBJTYPE_EVENT: dprintf("<event> %08lx", ObjectAddress ); break; case OBJTYPE_METHOD: dprintf("<method> %08lx", ObjectAddress ); break; case OBJTYPE_MUTEX: dprintf("<mutex> %08lx", ObjectAddress ); break; case OBJTYPE_OPREGION: dprintf("<opregion> %08lx", ObjectAddress ); break; case OBJTYPE_POWERRES: dprintf("<powerres> %08lx", ObjectAddress ); break; case OBJTYPE_PROCESSOR: dprintf("<processor> %08lx", ObjectAddress ); break; case OBJTYPE_THERMALZONE: dprintf("<thermalzone> %08lx", ObjectAddress ); break; case OBJTYPE_BUFFFIELD: dprintf("<bufffield> %08lx", ObjectAddress ); break; case OBJTYPE_DDBHANDLE: dprintf("<ddbhandle> %08lx", ObjectAddress ); break; case OBJTYPE_DEBUG: dprintf("<debug> %08lx", ObjectAddress ); break; case OBJTYPE_DATAALIAS: dprintf("<dataalias> %08lx", ObjectAddress ); break; case OBJTYPE_BANKFIELD: dprintf("<bankfield> %08lx", ObjectAddress ); break; case OBJTYPE_FIELD: dprintf("<field> %08lx", ObjectAddress ); break; case OBJTYPE_INDEXFIELD: dprintf("<indexfield> %08lx", ObjectAddress ); break; default: dprintf("<unknown> %08lx", ObjectAddress ); break; } } VOID stackCall( IN ULONG_PTR CallAddress ) /*++ Format Displayed: ResultAddress MethodName( Arg0, ..., ArgN ) --*/ { ULONG_PTR address; BOOL result; CALL call; INT i; NSOBJ object; PUCHAR objectPath; ULONG returnLength; result = ReadMemory( CallAddress, &call, sizeof(CALL), &returnLength ); if (result != TRUE || returnLength != sizeof(CALL) || call.FrameHdr.dwSig != SIG_CALL) { dprintf( "stackCall: --- Coult not read call frame %08lx\n", CallAddress ); return; } if (call.pnsMethod == NULL) { dprintf( "%08lx --- No method\n", CallAddress ); return; } // // Display result address // dprintf("CALL %08lx ", CallAddress ); // // Display the function name // objectPath = stackGetObjectPath( (ULONG_PTR) call.pnsMethod ); dprintf("%s(", objectPath); // // Display all parsed arguments; // for (i = 0; i < call.iArg; i++) { // // What is the address of the argument // address = (ULONG_PTR) &call.pdataArgs[i]; // // Display that argument // stackArgument( address ); if (i < (call.icArgs - 1)) { dprintf(","); } } // // Let the user know how many unprocessed arguments there are // for (; i < call.icArgs; i++) { dprintf("_???_"); if (i < (call.icArgs-1)) { dprintf(","); } } dprintf(")\n"); } PUCHAR stackGetAmlTermPath( IN ULONG_PTR AmlTermAddress ) { AMLTERM amlTerm; BOOL result; static UCHAR termPath[2049]; ULONG i; ULONG resultLength; result = ReadMemory( AmlTermAddress, &amlTerm, sizeof(AMLTERM), &resultLength ); if (!result || resultLength != sizeof(AMLTERM)) { return NULL; } if (amlTerm.pszTermName == NULL) { return NULL; } result = ReadMemory( (ULONG_PTR) amlTerm.pszTermName, &termPath, 2048, &resultLength ); if (!result || resultLength == 0) { return NULL; } termPath[resultLength] = '\0'; return termPath; } PUCHAR stackGetObjectPath( IN ULONG_PTR ObjectAddress ) { BOOL result; NSOBJ object; static UCHAR namePath[2049]; ULONG i; ULONG resultLength; // // Read the object // result = ReadMemory( ObjectAddress, &object, sizeof(NSOBJ), &resultLength ); if (!result || resultLength != sizeof(NSOBJ)) { return NULL; } if (object.pnsParent == NULL) { strcpy( namePath, "\\"); } else { NSOBJ parent; stackGetObjectPath( (ULONG_PTR) object.pnsParent ); result = ReadMemory( (ULONG_PTR) object.pnsParent, &parent, sizeof(NSOBJ), &resultLength ); if (!result || resultLength != sizeof(NSOBJ)) { return NULL; } if (parent.pnsParent != NULL) { strcat(namePath, "."); } strncat( namePath, (PUCHAR) &(object.dwNameSeg), sizeof(NAMESEG) ); for (i = strlen(namePath); i > 0; --i) { if (namePath[i-1] == '_') { namePath[i-1] = '\0'; } else { break; } } } return namePath; } VOID stackTerm( IN ULONG_PTR TermAddress ) /*++ Format Displayed: term TermAddress TermName( Arg0, ..., ArgN ) --*/ { ULONG_PTR address; BOOL result; INT i; NSOBJ object; PUCHAR objectPath; TERM term; ULONG returnLength; result = ReadMemory( TermAddress, &term, sizeof(TERM), &returnLength ); if (result != TRUE || returnLength != sizeof(TERM) || term.FrameHdr.dwSig != SIG_TERM) { dprintf( "stackTerm: --- Coult not read call frame %08lx\n", TermAddress ); return; } if (term.pamlterm == NULL) { dprintf( "%08lx --- No term\n", TermAddress ); return; } // // Display result address // dprintf("TERM %08lx ", TermAddress ); // // Display the function name // objectPath = stackGetAmlTermPath( (ULONG_PTR) term.pamlterm ); dprintf("%s(", objectPath); // // Display all parsed arguments; // for (i = 0; i < term.iArg; i++) { // // What is the address of the argument // address = (ULONG_PTR) &term.pdataArgs[i]; // // Display that argument // stackArgument( address ); if (i < (term.icArgs - 1)) { dprintf(","); } } // // Let the user know how many unprocessed arguments there are // for (; i < term.icArgs; i++) { dprintf("_???_"); if (i < (term.icArgs-1)) { dprintf(","); } } dprintf(")\n"); } VOID stackTrace( IN ULONG_PTR ContextAddress, IN ULONG Verbose ) /*++ Routine Description: This routine dumps a context as a stack Arguments: ContextAddress - Where the stack is located Verbose - How much information to display Return Value: None --*/ { BOOL callSeen = FALSE; BOOL result; CTXT context; FRAMEHDR frame; PUCHAR frameAddress; ULONG returnLength; // // Read the context from the target // result = ReadMemory( ContextAddress, &context, sizeof(CTXT), &returnLength ); if (result != TRUE || returnLength != sizeof(CTXT)) { dprintf( "stackTrace: --- Could not read Context %08lx\n", ContextAddress ); return; } if (context.dwSig != SIG_CTXT) { dprintf( "stackTrace: --- Not a Context (%08lx)\n", context.dwSig ); return; } // // Begin to walk the frames // frameAddress = context.LocalHeap.pbHeapEnd; while (frameAddress < context.pbCtxtEnd) { result = ReadMemory( (ULONG_PTR) frameAddress, &frame, sizeof(FRAMEHDR), &returnLength ); if (result != TRUE || returnLength != sizeof(FRAMEHDR)) { dprintf( "stackTrace: --- could not read frame %08lx\n", frameAddress ); return; } // // Do we care about the frame? // switch(frame.dwSig) { case SIG_CALL: callSeen = TRUE; stackCall( (ULONG_PTR) frameAddress ); break; case SIG_TERM: if (!callSeen || (callSeen && Verbose)) { stackTerm( (ULONG_PTR) frameAddress ); } } // switch // // Next // frameAddress += frame.dwLen; } }
import 'package:sqlparser/sqlparser.dart'; import 'package:test/test.dart'; extension ExpectErrors on AnalysisContext { void expectError(String lexeme, {AnalysisErrorType? type}) { expect( errors, [analysisErrorWith(lexeme: lexeme, type: type)], ); } void expectNoError() { expect(errors, isEmpty); } } Matcher analysisErrorWith({String? lexeme, AnalysisErrorType? type}) { var matcher = isA<AnalysisError>(); if (lexeme != null) { matcher = matcher.having((e) => e.span?.text, 'span.text', lexeme); } if (type != null) { matcher = matcher.having((e) => e.type, 'type', type); } return matcher; }
import 'package:postgresql/postgresql.dart' show Row; import '../../entity/application.dart'; import '../../entity/application_environment.dart'; import '../../entity/application_revision.dart'; import '../../entity/aws_cloudfront.dart'; import '../../entity/aws_s3.dart'; import '../../entity/session.dart'; import '../../entity/user.dart'; import '../../entity/uuid.dart'; Application deserializeToApplication(Row row) => new Application(id: row.id, name: row.name, ownerId: row.owner_id); ApplicationEnvironment deserializeToApplicationEnvironment(Row row) => new ApplicationEnvironment( id: row.id, name: row.name, bucketId: new Uuid.fromString(row.bucket_id), destinationId: new Uuid.fromString(row.destination_id), ); ApplicationRevision deserializeToApplicationRevision(Row row) => new ApplicationRevision(id: row.id, createdAt: row.created_at); AwsCloudfront deserializeToAwsCloudfront(Row row) => new AwsCloudfront( id: new Uuid.fromString(row.id), distributionId: row.payload['distributionId'], arn: row.payload['arn'], domainName: row.payload['domainName'], ); AwsS3 deserializeToAwsS3(Row row) => new AwsS3( id: new Uuid.fromString(row.id), bucketName: row.payload['bucketName'], ); Session deserializeToSession(Row row) => row == null ? null : new Session.fromToken(row.token); User deserializeToUser(Row row) => new User( id: row.id, username: row.username, email: row.email, name: row.name, profileImageUrl: row.profile_image_url, );
// +build ffmpeg30 package avfilter func (l *Link) Status() int { return int(l.CAVFilterLink.status) } func (l *Link) FrameCount() int64 { return int64(l.CAVFilterLink.frame_count) }
CREATE VIEW `v_user_music_count` AS select `m_user`.`id` AS `userBean.id`, count(`m_article`.`id`) AS `cnt` from ((`m_article` left join `r_music` ON ((`m_article`.`id` = `r_music`.`id`))) left join `m_user` ON ((`m_article`.`user_id` = `m_user`.`id`))) where ((`m_article`.`del_flg` = '0') and (`m_article`.`publish_flg` = '1') and (`r_music`.`del_flg` = '0') and (`m_user`.`id` is not null)) group by `m_user`.`id`
use crate::puzzle_input; pub fn run() { let input = puzzle_input::read_all_lines("./input/2020-d01-input1.txt"); let expenses: Vec<i64> = input .iter() .map(|x| x.trim().parse::<i64>().unwrap()) .collect(); println!("** Part 1 Final: {:?}", check_two_expenses(&expenses)); println!("** Part 2 Final: {:?}", check_three_expenses(&expenses)); } fn check_two_expenses(expenses: &[i64]) -> i64 { for (i, &x) in expenses.iter().enumerate() { let next = i + 1; let slice = &expenses[next..]; for y in slice.iter() { if x + y == 2020 { return x * y; } } } 0 } fn check_three_expenses(expenses: &[i64]) -> i64 { for (i, &x) in expenses.iter().enumerate() { let m = i + 1; let s1 = &expenses[m..]; for (j, &y) in s1.iter().enumerate() { let n = j + 1; let s2 = &expenses[n..]; for z in s2.iter() { if x + y + z == 2020 { return x * y * z; } } } } 0 } #[cfg(test)] mod tests { use super::*; #[test] fn test_check_expenses() { let input = vec![1721, 979, 366, 299, 675, 1456]; assert_eq!(check_two_expenses(&input), 514579); assert_eq!(check_three_expenses(&input), 241861950); } }
Epure::Application.routes.draw do resources :schedules resources :schedules do resources :entries, :except => [:show] do collection do get :search_course_names get :search_lecturers end end get "color_schemes", :to => "color_schemes#index" post "color_schemes/reset", :to => "color_schemes#reset" post "color_schemes/bw", :to => "color_schemes#bw" end get "/home", :to => "schedules#index" get "/srednia", :to => "application#avg" post "/srednia", :to => "application#avg" get "/akz/katalog", :to => "application#akz_catalogue" get "/akz", :to => "application#akz" get "/:slug", :to => "schedules#show", :as => :schedule_slug root :to => "schedules#index" end
import { Injectable } from "@nestjs/common"; import fetch, { RequestInit, Response } from "node-fetch"; @Injectable() export class HttpService { public fetch(uri: string, init?: RequestInit): Promise<Response> { return fetch(uri, init); } }
--- date: 2000-01-01T00:00:00+00:00 title: Rails author: bradrydzewski weight: 12 draft: true toc: false --- # Rails Example Help Wanted.
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.0. You may not use this file * except in compliance with the Zeebe Community License 1.0. */ package io.zeebe.logstreams.state; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.groups.Tuple.tuple; import io.zeebe.db.impl.DefaultColumnFamily; import io.zeebe.db.impl.rocksdb.ZeebeRocksDbFactory; import io.zeebe.logstreams.util.RocksDBWrapper; import io.zeebe.logstreams.util.TestSnapshotStorage; import io.zeebe.test.util.AutoCloseableRule; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.zip.CRC32; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public final class ReplicateSnapshotControllerTest { private static final int VALUE = 0xCAFE; private static final String KEY = "test"; @Rule public final TemporaryFolder tempFolderRule = new TemporaryFolder(); @Rule public final AutoCloseableRule autoCloseableRule = new AutoCloseableRule(); private StateSnapshotController replicatorSnapshotController; private StateSnapshotController receiverSnapshotController; private Replicator replicator; private SnapshotStorage receiverStorage; @Before public void setup() throws IOException { final var senderRoot = tempFolderRule.newFolder("sender").toPath(); final var storage = new TestSnapshotStorage(senderRoot); final var receiverRoot = tempFolderRule.newFolder("receiver").toPath(); receiverStorage = new TestSnapshotStorage(receiverRoot); replicator = new Replicator(); replicatorSnapshotController = new StateSnapshotController( ZeebeRocksDbFactory.newFactory(DefaultColumnFamily.class), storage, replicator); receiverSnapshotController = new StateSnapshotController( ZeebeRocksDbFactory.newFactory(DefaultColumnFamily.class), receiverStorage, replicator); autoCloseableRule.manage(replicatorSnapshotController); autoCloseableRule.manage(receiverSnapshotController); autoCloseableRule.manage(storage); autoCloseableRule.manage(receiverStorage); final RocksDBWrapper wrapper = new RocksDBWrapper(); wrapper.wrap(replicatorSnapshotController.openDb()); wrapper.putInt(KEY, VALUE); } @Test public void shouldReplicateSnapshotChunks() { // given replicatorSnapshotController.takeSnapshot(1); // when replicatorSnapshotController.replicateLatestSnapshot(Runnable::run); // then final List<SnapshotChunk> replicatedChunks = replicator.replicatedChunks; final int totalCount = replicatedChunks.size(); assertThat(totalCount).isGreaterThan(0); final SnapshotChunk firstChunk = replicatedChunks.get(0); final int chunkTotalCount = firstChunk.getTotalCount(); assertThat(totalCount).isEqualTo(chunkTotalCount); assertThat(replicatedChunks) .extracting(SnapshotChunk::getSnapshotId, SnapshotChunk::getTotalCount) .containsOnly(tuple("1", totalCount)); } @Test public void shouldContainChecksumPerChunk() { // given replicatorSnapshotController.takeSnapshot(1); // when replicatorSnapshotController.replicateLatestSnapshot(Runnable::run); // then final List<SnapshotChunk> replicatedChunks = replicator.replicatedChunks; assertThat(replicatedChunks.size()).isGreaterThan(0); replicatedChunks.forEach( chunk -> { final CRC32 crc32 = new CRC32(); crc32.update(chunk.getContent()); assertThat(chunk.getChecksum()).isEqualTo(crc32.getValue()); }); } @Test public void shouldNotReplicateWithoutSnapshot() { // given // when replicatorSnapshotController.replicateLatestSnapshot(Runnable::run); // then final List<SnapshotChunk> replicatedChunks = replicator.replicatedChunks; final int totalCount = replicatedChunks.size(); assertThat(totalCount).isEqualTo(0); } @Test public void shouldReceiveSnapshotChunks() throws Exception { // given receiverSnapshotController.consumeReplicatedSnapshots(); replicatorSnapshotController.takeSnapshot(1); // when replicatorSnapshotController.replicateLatestSnapshot(Runnable::run); // then final RocksDBWrapper wrapper = new RocksDBWrapper(); final long recoveredSnapshot = receiverSnapshotController.recover(); assertThat(recoveredSnapshot).isEqualTo(1); wrapper.wrap(receiverSnapshotController.openDb()); final int valueFromSnapshot = wrapper.getInt(KEY); assertThat(valueFromSnapshot).isEqualTo(VALUE); } @Test public void shouldNotFailOnReplicatingAndReceivingTwice() throws Exception { // given receiverSnapshotController.consumeReplicatedSnapshots(); replicatorSnapshotController.takeSnapshot(1); replicatorSnapshotController.replicateLatestSnapshot(Runnable::run); // when replicatorSnapshotController.replicateLatestSnapshot(Runnable::run); // then final RocksDBWrapper wrapper = new RocksDBWrapper(); final long recoveredSnapshot = receiverSnapshotController.recover(); assertThat(recoveredSnapshot).isEqualTo(1); wrapper.wrap(receiverSnapshotController.openDb()); final int valueFromSnapshot = wrapper.getInt(KEY); assertThat(valueFromSnapshot).isEqualTo(VALUE); } protected static final class Replicator implements SnapshotReplication { final List<SnapshotChunk> replicatedChunks = new ArrayList<>(); private Consumer<SnapshotChunk> chunkConsumer; @Override public void replicate(final SnapshotChunk snapshot) { replicatedChunks.add(snapshot); if (chunkConsumer != null) { chunkConsumer.accept(snapshot); } } @Override public void consume(final Consumer<SnapshotChunk> consumer) { chunkConsumer = consumer; } @Override public void close() {} } }
import StyleDictionary from "style-dictionary"; import MeiucaEngineCore from "meiuca-engine-core"; import * as cssFormatBlock from "./component-format-block/css"; import * as scssFormatBlock from "./component-format-block/scss"; import * as rnFormatBlock from "./react-native-format-block"; import transformer from "./react-native-transformer"; export default function createRegisters( dictionary: StyleDictionary, core: MeiucaEngineCore ) { dictionary.registerTransform({ name: "size/object", type: "value", matcher: (prop) => prop.attributes.category === "size", transformer, }); dictionary.registerTransformGroup({ name: "native", transforms: ["name/cti/camel", "size/object", "color/css"], }); dictionary.registerTransformGroup({ name: "default", transforms: ["name/cti/kebab"], }); dictionary.registerFormat({ ...cssFormatBlock, formatter: cssFormatBlock.formatter.bind(core), }); dictionary.registerFormat({ ...scssFormatBlock, formatter: scssFormatBlock.formatter.bind(core), }); dictionary.registerFormat({ ...rnFormatBlock, }); dictionary.registerFilter({ name: "isNotComponent", matcher: function (prop) { return ( prop.attributes.category !== (core.config.globals.ds || "component") ); }, }); }
# $1 : alias CN of certificate # $2 : key-store name # $3 : password cd src/main/resources/keystore/ || exit #openssl pkcs12 -in ${1}.p12 -nokeys -out ${2} keytool -exportcert -alias ${1} -keypass keypass \ -keystore ${2}.p12 -storepass ${3} -file ${1}.crt -rfc keytool -printcert -file ${1}.crt echo "Done"
# ploc ploc is a python program to count lines in a Python file. It aims to demonstrate the following language features: * Variables * Text * Functions * Branching * Looping * Arrays * File I/O * Error Handling * Classes * Debugging (comment out any useful debug print statements) * Testing
<?php declare(strict_types=1); namespace Thinktomorrow\Chief\Managers; interface Manager { public function managedModelClass(): string; public function route(string $action, $model = null, ...$parameters): string; public function can(string $action, $model = null): bool; }
mutable struct SVMSurrogate{X,Y,M,L,U} <: AbstractSurrogate x::X y::Y model::M lb::L ub::U end function SVMSurrogate(x,y,lb::Number,ub::Number) xn = reshape(x,length(x),1) model = LIBSVM.fit!(SVC(),xn,y) SVMSurrogate(xn,y,model,lb,ub) end function (svmsurr::SVMSurrogate)(val::Number) return LIBSVM.predict(svmsurr.model,[val]) end """ SVMSurrogate(x,y,lb,ub) Builds SVM surrogate. """ function SVMSurrogate(x,y,lb,ub) X = Array{Float64,2}(undef,length(x),length(x[1])) for j = 1:length(x) X[j,:] = vec(collect(x[j])) end model = LIBSVM.fit!(SVC(),X,y) SVMSurrogate(x,y,model,lb,ub) end function (svmsurr::SVMSurrogate)(val) n = length(val) return LIBSVM.predict(svmsurr.model,reshape(collect(val),1,n))[1] end function add_point!(svmsurr::SVMSurrogate,x_new,y_new) if length(svmsurr.lb) == 1 #1D svmsurr.x = vcat(svmsurr.x,x_new) svmsurr.y = vcat(svmsurr.y,y_new) svmsurr.model = LIBSVM.fit!(SVC(),reshape(svmsurr.x,length(svmsurr.x),1),svmsurr.y) else n_previous = length(svmsurr.x) a = vcat(svmsurr.x,x_new) n_after = length(a) dim_new = n_after - n_previous n = length(svmsurr.x) d = length(svmsurr.x[1]) tot_dim = n + dim_new X = Array{Float64,2}(undef,tot_dim,d) for j = 1:n X[j,:] = vec(collect(svmsurr.x[j])) end if dim_new == 1 X[n+1,:] = vec(collect(x_new)) else i = 1 for j = n+1:tot_dim X[j,:] = vec(collect(x_new[i])) i = i + 1 end end svmsurr.x = vcat(svmsurr.x,x_new) svmsurr.y = vcat(svmsurr.y,y_new) svmsurr.model = LIBSVM.fit!(SVC(),X,svmsurr.y) end nothing end
package gocron import ( "sort" "sync" "time" ) // Scheduler struct, the only data member is the list of jobs. // - implements the sort.Interface{} for sorting jobs, by the time nextRun type Scheduler struct { jobs []*Job // Array store jobs mu sync.RWMutex running bool stopChan chan struct{} } // NewScheduler creates a new Scheduler func NewScheduler() *Scheduler { return &Scheduler{ jobs: make([]*Job, 0), running: false, stopChan: make(chan struct{}), } } func (s *Scheduler) Start() { <-s.StartAsync() } func (s *Scheduler) StartAsync() chan struct{} { if s.running { return s.stopChan } s.running = true ticker := time.NewTicker(time.Second) go func() { for { select { case <-ticker.C: s.runPending() case <-s.stopChan: ticker.Stop() s.running = false return } } }() return s.stopChan } func (s *Scheduler) Stop() { if s.running { s.stopScheduler() } } func (s *Scheduler) stopScheduler() { s.stopChan <- struct{}{} } // Jobs returns the list of Jobs from the Scheduler func (s *Scheduler) Jobs() []*Job { s.mu.RLock() jobs := s.jobs s.mu.RUnlock() return jobs } func (s *Scheduler) Len() int { return len(s.jobs) } func (s *Scheduler) Swap(i, j int) { s.jobs[i], s.jobs[j] = s.jobs[j], s.jobs[i] } func (s *Scheduler) Less(i, j int) bool { return s.jobs[j].nextRun.Unix() >= s.jobs[i].nextRun.Unix() } // Get the current runnable jobs, which shouldRun is True func (s *Scheduler) runnableJobs() []*Job { var jobs []*Job sort.Sort(s) for _, job := range s.jobs { if s.shouldRun(job) { jobs = append(jobs, job) } else { break } } return jobs } // NextRun datetime when the next job should run. func (s *Scheduler) NextRun() (*Job, time.Time) { s.mu.RLock() defer s.mu.RUnlock() if len(s.jobs) == 0 { return nil, time.Now() } sort.Sort(s) return s.jobs[0], s.jobs[0].nextRun } // Every schedule a new periodic job with interval func (s *Scheduler) Every(interval time.Duration) *Job { job := NewJob(interval) s.mu.Lock() defer s.mu.Unlock() s.jobs = append(s.jobs, job) return job } // runPending runs all the jobs that are scheduled to run. func (s *Scheduler) runPending() { s.mu.RLock() defer s.mu.RUnlock() var onceJobs []*Job jobs := s.runnableJobs() for _, j := range jobs { go j.run() j.lastRun = time.Now() j.scheduleNextRun() if j.once { onceJobs = append(onceJobs, j) } } for _, j := range onceJobs { s.RemoveByRef(j) } } // RunAll run all jobs regardless if they are scheduled to run or not func (s *Scheduler) RunAll() { s.RunAllwithDelay(0) } // RunAllwithDelay runs all jobs with delay seconds func (s *Scheduler) RunAllwithDelay(d time.Duration) { s.mu.RLock() defer s.mu.RUnlock() for _, job := range s.jobs { go job.run() if 0 != d { time.Sleep(d) } } } // Remove specific job j by function func (s *Scheduler) Remove(j interface{}) { s.removeByCondition(func(someJob *Job) bool { return someJob.jobFunc == getFunctionName(j) }) } // RemoveByRef removes specific job j by reference func (s *Scheduler) RemoveByRef(j *Job) { s.removeByCondition(func(someJob *Job) bool { return someJob == j }) } func (s *Scheduler) RemoveByTag(tag string) { s.removeByCondition(func(j *Job) bool { for idx, _ := range j.tags { if j.tags[idx] == tag { return true } } return false }) } func (s *Scheduler) removeByCondition(shouldRemove func(*Job) bool) { retainedJobs := make([]*Job, 0) for _, job := range s.jobs { if !shouldRemove(job) { retainedJobs = append(retainedJobs, job) } } s.jobs = retainedJobs } // Scheduled checks if specific job j was already added func (s *Scheduler) Scheduled(j interface{}) bool { s.mu.RLock() defer s.mu.RUnlock() for _, job := range s.jobs { if job.jobFunc == getFunctionName(j) { return true } } return false } // Clear delete all scheduled jobs func (s *Scheduler) Clear() { s.mu.Lock() defer s.mu.Unlock() s.jobs = make([]*Job, 0) } func (s *Scheduler) shouldRun(j *Job) bool { return time.Now().After(j.nextRun) }
#!/bin/bash TMP_FILE=tmp.smali OLD_IFS=$IFS for f in `grep -rn "IccCard;->" $1 | grep "invoke-virtual" | cut -d: -f1 | uniq | sort` do echo "replace file:$f" cat /dev/null > $TMP_FILE IFS=$'\n' for l in `cat $f` do echo $l | grep "IccCard;->" | grep "invoke-virtual" -q if [ $? -eq 0 ] then l=`echo $l | sed "s/invoke-virtual/invoke-interface/"` fi echo $l >> $TMP_FILE done cp $TMP_FILE $f done if [ -f $TMP_FILE ] then rm $TMP_FILE fi IFS=$OLD_IFS for f in `grep -rn "IccCard;->registerForNetworkLocked(" $1 | cut -d: -f1 | uniq | sort` do echo "replace file:$f" sed "s/IccCard;->registerForNetworkLocked(/IccCard;->registerForPersoLocked(/g" $f > $TMP_FILE cp $TMP_FILE $f rm $TMP_FILE done for f in `grep -rn "IccCardApplication\$AppType;" $1 | cut -d: -f1 | uniq | sort` do echo "replace file:$f" sed "s/IccCardApplication\$AppType;/IccCardApplicationStatus\$AppType;/g" $f > $TMP_FILE cp $TMP_FILE $f rm $TMP_FILE done
#!/bin/sh set -e wheel_gid=1 tty_gid=2 phys_gid=3 audio_gid=4 window_uid=13 window_gid=13 die() { echo "die: $*" exit 1 } if [ "$(id -u)" != 0 ]; then die "this script needs to run as root" fi [ -z "$SERENITY_ROOT" ] && die "SERENITY_ROOT is not set" [ -d "$SERENITY_ROOT/Base" ] || die "$SERENITY_ROOT/Base doesn't exist" umask 0022 printf "creating initial filesystem structure... " for dir in bin etc proc mnt tmp boot mod; do mkdir -p mnt/$dir done chmod 700 mnt/boot chmod 700 mnt/mod chmod 1777 mnt/tmp echo "done" printf "setting up device nodes... " mkdir -p mnt/dev mkdir -p mnt/dev/pts mknod mnt/dev/fb0 b 29 0 chmod 660 mnt/dev/fb0 chown 0:$phys_gid mnt/dev/fb0 mknod mnt/dev/tty0 c 4 0 mknod mnt/dev/tty1 c 4 1 mknod mnt/dev/tty2 c 4 2 mknod mnt/dev/tty3 c 4 3 mknod mnt/dev/ttyS0 c 4 64 mknod mnt/dev/ttyS1 c 4 65 mknod mnt/dev/ttyS2 c 4 66 mknod mnt/dev/ttyS3 c 4 67 for tty in 0 1 2 3 S0 S1 S2 S3; do chmod 620 mnt/dev/tty$tty chown 0:$tty_gid mnt/dev/tty$tty done mknod mnt/dev/random c 1 8 mknod mnt/dev/null c 1 3 mknod mnt/dev/zero c 1 5 mknod mnt/dev/full c 1 7 # random, is failing (randomly) on fuse-ext2 on macos :) chmod 666 mnt/dev/random || true chmod 666 mnt/dev/null chmod 666 mnt/dev/zero chmod 666 mnt/dev/full mknod mnt/dev/keyboard c 85 1 chmod 440 mnt/dev/keyboard chown 0:$phys_gid mnt/dev/keyboard mknod mnt/dev/mouse c 10 1 chmod 440 mnt/dev/mouse chown 0:$phys_gid mnt/dev/mouse mknod mnt/dev/audio c 42 42 chmod 220 mnt/dev/audio chown 0:$audio_gid mnt/dev/audio mknod mnt/dev/ptmx c 5 2 chmod 666 mnt/dev/ptmx mknod mnt/dev/hda b 3 0 mknod mnt/dev/hdb b 3 1 mknod mnt/dev/hdc b 4 0 mknod mnt/dev/hdd b 4 1 for hd in a b c d; do chmod 600 mnt/dev/hd$hd done ln -s /proc/self/fd/0 mnt/dev/stdin ln -s /proc/self/fd/1 mnt/dev/stdout ln -s /proc/self/fd/2 mnt/dev/stderr echo "done" printf "installing base system... " cp -R "$SERENITY_ROOT"/Base/* mnt/ cp -R Root/* mnt/ chmod 400 mnt/res/kernel.map chmod 660 mnt/etc/WindowServer/WindowServer.ini chown $window_uid:$window_gid mnt/etc/WindowServer/WindowServer.ini echo "/bin/sh" > mnt/etc/shells chown 0:$wheel_gid mnt/bin/su chown 0:$phys_gid mnt/bin/shutdown chown 0:$phys_gid mnt/bin/reboot chown 0:0 mnt/boot/Kernel chown 0:0 mnt/res/kernel.map chmod 0400 mnt/res/kernel.map chmod 0400 mnt/boot/Kernel chmod 4750 mnt/bin/su chmod 4755 mnt/bin/ping chmod 4750 mnt/bin/reboot chmod 4750 mnt/bin/shutdown echo "done" printf "installing users... " mkdir -p mnt/root mkdir -p mnt/home/anon mkdir -p mnt/home/anon/Desktop mkdir -p mnt/home/anon/Downloads mkdir -p mnt/home/nona cp "$SERENITY_ROOT"/ReadMe.md mnt/home/anon/ cp -r "$SERENITY_ROOT"/Libraries/LibJS/Tests mnt/home/anon/js-tests chmod 700 mnt/root chmod 700 mnt/home/anon chmod 700 mnt/home/nona chown -R 0:0 mnt/root chown -R 100:100 mnt/home/anon chown -R 200:200 mnt/home/nona echo "done" printf "installing shortcuts... " ln -s FileManager mnt/bin/fm ln -s HelloWorld mnt/bin/hw ln -s IRCClient mnt/bin/irc ln -s Minesweeper mnt/bin/ms ln -s Shell mnt/bin/sh ln -s Snake mnt/bin/sn ln -s Taskbar mnt/bin/tb ln -s VisualBuilder mnt/bin/vb ln -s WidgetGallery mnt/bin/wg ln -s TextEditor mnt/bin/te ln -s HexEditor mnt/bin/he ln -s PaintBrush mnt/bin/pb ln -s QuickShow mnt/bin/qs ln -s Piano mnt/bin/pi ln -s SystemDialog mnt/bin/sd ln -s Calculator mnt/bin/calc ln -s Calendar mnt/bin/calendar ln -s Inspector mnt/bin/ins ln -s SoundPlayer mnt/bin/sp ln -s Help mnt/bin/help ln -s Browser mnt/bin/br ln -s HackStudio mnt/bin/hs ln -s SystemMonitor mnt/bin/sm ln -s ProfileViewer mnt/bin/pv ln -s WebServer mnt/bin/ws ln -s Solitaire mnt/bin/sl echo "done" # Run local sync script, if it exists if [ -f sync-local.sh ]; then sh sync-local.sh fi
#!/bin/bash if [ -z "$USERNAME" ] ; then USERNAME=squid fi if [ -z "$PASSWORD" ] ; then PASSWORD=squid fi if [ -z "$HTTP_PORT" ] ; then HTTP_PORT=3128 fi if [ ! -f $squid_conf_file ] ; then echo "Missing squid3 configuration file" exit 1 fi # Copy artifact configuration file if [ ! -f /etc/squid3/squid.conf.default ] ; then sudo cp /etc/squid3/squid.conf /etc/squid3/squid.conf.default sudo mv $squid_conf_file /etc/squid3/squid.conf fi # Override port if [ "$(grep http_port /etc/squid3/squid.conf 2>/dev/null)" ] ; then sudo sed -i "s/http_port [0-9]*/http_port $HTTP_PORT/" /etc/squid3/squid.conf else echo "" | sudo tee -a /etc/squid3/squid.conf echo "http_port $HTTP_PORT" | sudo tee -a /etc/squid3/squid.conf fi # Add user sudo htpasswd -b -c /etc/squid3/passwords $USERNAME $PASSWORD
require 'spec_helper' describe AthenaHealth::Allergy do let(:order_type_attributes) do { 'ordertypeid': '123456', 'name': 'Some name' } end subject { AthenaHealth::OrderType.new(order_type_attributes) } it_behaves_like 'a model' it 'have proper attributes' do expect(subject).to have_attributes( ordertypeid: 123456, name: 'Some name' ) end end
/* vi:set ts=4 sw=4 expandtab: * * Copyright 2016, Chris Leishman (http://github.com/cleishm) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CYPHER_PARSER_ERRORS_H #define CYPHER_PARSER_ERRORS_H #include "cypher-parser.h" struct cypher_parse_error { struct cypher_input_position position; char *msg; char *context; size_t context_offset; }; void cp_errors_vcleanup(cypher_parse_error_t *errors, unsigned int n); typedef struct cp_error_tracking cp_error_tracking_t; struct cp_error_tracking { const struct cypher_parser_colorization *colorization; struct cypher_input_position last_position; char last_char; const char **labels; unsigned int labels_capacity; unsigned int nlabels; cypher_parse_error_t *errors; unsigned int errors_capacity; unsigned int nerrors; size_t last_error_offset; }; void cp_et_init(cp_error_tracking_t *et, const struct cypher_parser_colorization *colorization); int cp_et_note_potential_error(cp_error_tracking_t *et, struct cypher_input_position position, char c, const char *label); int cp_et_reify_potentials(cp_error_tracking_t *et); static inline void cp_et_clear_potentials(cp_error_tracking_t *et) { et->nlabels = 0; } static inline unsigned int cp_et_nerrors(const cp_error_tracking_t *et) { return et->nerrors; } static inline cypher_parse_error_t *cp_et_errors(cp_error_tracking_t *et) { return et->errors; } static inline void cp_et_clear_errors(cp_error_tracking_t *et) { et->nerrors = 0; } void cp_et_cleanup(cp_error_tracking_t *et); #endif/*CYPHER_PARSER_ERRORS_H*/
# Kubernetes Basic Commands List ```bash kubectl config get-contexts kubectl config use-context <context> kubectl get po kubectl logs -f <container> kubectl exec -it <container> sh ```
import 'package:cirilla/mixins/mixins.dart'; import 'package:cirilla/widgets/cirilla_cache_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_swiper/flutter_swiper.dart'; class SliderBlock extends StatelessWidget with Utility { final Map<String, dynamic> block; const SliderBlock({Key key, this.block}) : super(key: key); List<String> convertData(List data) { List<String> result = []; for (var i = 0; i < data.length; i++) { dynamic item = data.elementAt(i); String image = item is Map ? get(item, ['image', 'url'], '') : ''; if (image.isNotEmpty) { result.add(image); } } return result; } @override Widget build(BuildContext context) { Map attrs = get(block, ['attrs'], {}) is Map ? get(block, ['attrs'], {}) : {}; List slides = get(attrs, ['slides'], []); List<String> data = convertData(slides); if (data.isEmpty) { return Container(); } return LayoutBuilder( builder: (_, BoxConstraints constraints) { double width = constraints.maxWidth; double height = (width * 185) / 337; double heightItem = height + 56; return SizedBox( width: width, height: heightItem, child: Swiper( itemBuilder: (BuildContext context, int index) { return Container( alignment: Alignment.topCenter, child: CirillaCacheImage( data.elementAt(index), width: width, height: height, ), ); }, itemCount: data.length, itemWidth: width, itemHeight: heightItem, pagination: SwiperCustomPagination(builder: (_, SwiperPluginConfig config) { int activeVisit = config?.activeIndex ?? 0; return Align( alignment: AlignmentDirectional.bottomStart, child: SizedBox( height: 48, child: ListView.separated( padding: EdgeInsets.zero, scrollDirection: Axis.horizontal, itemBuilder: (_, index) { Color colorFilter = activeVisit == index ? Colors.black.withOpacity(0.5) : Colors.transparent; return ColorFiltered( colorFilter: ColorFilter.mode(colorFilter, BlendMode.srcOver), child: CirillaCacheImage( data.elementAt(index), width: 72, height: 48, ), ); }, separatorBuilder: (_, index) { return SizedBox(width: 8); }, itemCount: data.length, ), ), ); }), ), ); }, ); } }
'use strict'; const timeago = require('timeago.js'); const timeagoInstance = timeago(); $(document).ready(function() { var action = ''; var index = 0; var team_type = ''; function load_team(type) { team_type = type; $('#message').html(''); clear_table(); $('#team_list_segment').addClass('loading'); $.get('/api/private/office/team/' + type, function(data, status) { if (status == 'success') { $('#team_list_segment').removeClass('loading'); if (data.length == 0) { $('#message').html( '<h3 class=\'ui center aligned header\'>Sorry, nothing found.</h3>' ); } else { for (let x in data) { add_row(data[x]); } } } else { pqy_notify.warn('Err fetching results, please try again'); } }); } function add_row(data) { var table = document.getElementById('team_list'); var row = table.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); var cell4 = row.insertCell(3); var cell5 = row.insertCell(4); var cell6 = row.insertCell(5); cell1.innerHTML = '@' + data.account; cell2.innerHTML = data.email; cell3.innerHTML = timeagoInstance.format(data.created); cell4.innerHTML = data.status; cell5.innerHTML = data.label; if (team_type == 'inactive') { cell6.innerHTML = ''; } else { cell6.innerHTML = '<botton class=\'circular ui icon mini remove button\'> <i class=\'icon user times\'></i> </button>'; } } function add_team() { $('#message').html(''); var new_team_account = $('#new_team_account').val(); var new_team_email = $('#new_team_email').val(); var new_team_role = $('#new_team_role').val(); var new_team_label = $('#new_team_label').val(); var new_team_about = $('#new_team_about').val(); if (new_team_account == '') $('#new_team_account_field').addClass('error'); else if (new_team_email == '') $('#new_team_email_field').addClass('error'); else if (new_team_role == '') $('#new_team_role_field').addClass('error'); else if (new_team_label == '') $('#new_team_label_field').addClass('error'); else if (new_team_about == '') $('#new_team_about_field').addClass('error'); else { $('#new_team_account_field').removeClass('error'); $('#new_team_email_field').removeClass('error'); $('#new_team_role_field').removeClass('error'); $('#new_team_label_field').removeClass('error'); $('#new_team_about_field').removeClass('error'); $('#new_team_form').addClass('loading'); $('.form_inputs').addClass('disabled'); $('.form .ui.dropdown').addClass('disabled'); $.post( '/api/private/office/team/add', { account: new_team_account, email: new_team_email, role: new_team_role, label: new_team_label, about: new_team_about, }, function(response, status) { $('#new_team_form').removeClass('loading'); if (status === 'success') { $('#new_team_form').addClass('success'); //add list team member in real-time let data = {}; data.account = new_team_account; data.email = new_team_email; data.created = new Date(); data.label = new_team_label; data.status = 'core'; add_row(data); } else { $('#new_team_form').addClass('error'); } } ).fail(function(data, textStatus, xhr) { if (data.status == 405) pqy_notify.warn('Sorry, account not found'); }); } } function remove_team() { $('#remove_btn').addClass('disabled'); var table = document.getElementById('team_list'); var delete_team_account = table.rows[ index ].cells[0].innerHTML.substring(1); $.post( '/api/private/office/team/remove', { account: delete_team_account, }, function(data, status) { if (status === 'success') { window.close_remove_modal(); document.getElementById('team_list').deleteRow(index); } else { pqy_notify.warn( 'Sorry, there was an error. Pease try again.' ); $('.ui.basic.modal') .modal({ onHide: function() { $('#remove_btn').removeClass('disabled'); }, }) .modal('hide'); } } ); } load_team('admin'); function clear_table() { var tableHeaderRowCount = 1; var table = document.getElementById('team_list'); var rowCount = table.rows.length; for (var i = tableHeaderRowCount; i < rowCount; i++) { table.deleteRow(tableHeaderRowCount); } } //set up click event listeners $('#team_admins').click(function() { load_team('admin'); }); $('#team_mods').click(function() { load_team('moderator'); }); $('#team_curies').click(function() { load_team('curator'); }); $('#team_core').click(function() { load_team('core'); }); $('#team_inactive').click(function() { load_team('inactive'); }); // $('#add_team').click(function() { add_team(); }); $('#remove_team').click(function() { remove_team(); }); });
import { Observable } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { Inject, Injectable, } from '@angular/core'; import { Media } from '../../../../api/src/types/media/media'; @Injectable({ providedIn: 'root' }) export class SailPicturesService { constructor(@Inject(HttpClient) private http: HttpClient) { } public getPictures(sail_id: string): Observable<Media[]> { return this.http.get<Media[]>(this.API_URL(sail_id)); } public addNewPictures(sail_id: string, pictures: Media[]): Observable<Media[]> { return this.http.put<Media[]>(this.API_URL(sail_id), pictures); } public deletePicture(sail_id: string, pictureId: string): Observable<Media[]> { return this.http.delete<Media[]>(`${this.API_URL(sail_id)}/${pictureId}`); } private readonly API_URL = (sail_id: string) => `/api/sail/${sail_id}/pictures`; }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace Microsoft.AspNetCore.SignalR { /// <summary> /// Metadata that describes the <see cref="Hub"/> information associated with a specific endpoint. /// </summary> public class HubMetadata { public HubMetadata(Type hubType) { HubType = hubType; } /// <summary> /// The type of <see cref="Hub"/>. /// </summary> public Type HubType { get; } } }
import 'package:doing/components/camera.dart'; import 'package:doing/constants/colors.dart'; import 'package:doing/services/shared_preferences.service.dart'; import 'package:doing/widgets/inputs/text_input.dart'; import 'package:flutter/material.dart'; import 'package:doing/constants/shared_preferences.dart'; class ProfilePage extends StatefulWidget { const ProfilePage({Key? key}) : super(key: key); @override _ProfilePageState createState() => _ProfilePageState(); } class _ProfilePageState extends State<ProfilePage> { final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); TextEditingController firstNameController = TextEditingController(text: ""); TextEditingController lastNameController = TextEditingController(text: ""); TextEditingController ageController = TextEditingController(text: ""); TextEditingController jobController = TextEditingController(text: ""); @override void initState() { super.initState(); loadData(); } void loadData() async { firstNameController.text = await SharedPreferencesService().getString(AppSharedPreferences.firstname) ?? ''; lastNameController.text = await SharedPreferencesService().getString(AppSharedPreferences.lastname) ?? ''; ageController.text = await SharedPreferencesService().getString(AppSharedPreferences.age) ?? ''; jobController.text = await SharedPreferencesService().getString(AppSharedPreferences.job) ?? ''; } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, backgroundColor: AppColors.success, appBar: AppBar( title: const Text("Profile"), centerTitle: true, ), body: Container( constraints: const BoxConstraints.expand(), decoration: BoxDecoration(color: Theme.of(context).scaffoldBackgroundColor), child: SingleChildScrollView( padding: const EdgeInsets.fromLTRB(16.0, 64.0, 16.0, 32.0), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ const SizedBox(width: double.infinity), const TakePictureScreen(), const SizedBox(height: 32), AppInput( controller: firstNameController, placeholder: 'Firstname *', textCapitalization: TextCapitalization.words, errorMessage: "Please enter your firstname", ), const SizedBox(height: 16.0), AppInput( controller: lastNameController, placeholder: 'Lastname *', textCapitalization: TextCapitalization.words, errorMessage: "Please enter your lastname", ), const SizedBox(height: 16.0), AppInput( controller: jobController, placeholder: 'Job *', textCapitalization: TextCapitalization.sentences, errorMessage: "Please enter your job", ), const SizedBox(height: 16.0), AppInput( controller: ageController, placeholder: 'Age *', textCapitalization: TextCapitalization.none, errorMessage: "Please enter your age", ), ], )))), bottomNavigationBar: SafeArea( bottom: true, child: MaterialButton( splashColor: Colors.transparent, highlightColor: Colors.transparent, highlightElevation: 0.0, elevation: 0.0, color: AppColors.success, child: const Text('Save', style: TextStyle(fontSize: 16.0, color: Colors.white)), onPressed: () { if (_formKey.currentState!.validate()) { SharedPreferencesService().setString(AppSharedPreferences.firstname, firstNameController.text); SharedPreferencesService().setString(AppSharedPreferences.lastname, lastNameController.text); SharedPreferencesService().setString(AppSharedPreferences.job, jobController.text); SharedPreferencesService().setString(AppSharedPreferences.age, ageController.text); Navigator.pop(context); } }, ), ), ); } }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho.codelab import android.graphics.Canvas import android.graphics.Color import android.graphics.ColorFilter import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.drawable.Drawable class ClockDrawable : Drawable() { companion object { const val ONE_MINUTE = 60L * 1000 const val ONE_HOUR = 60 * ONE_MINUTE const val TWELVE_HOURS = 12 * ONE_HOUR } private val paintThin = buildPaint(6) private val paintMedium = buildPaint(9) private val paintWide = buildPaint(12) private var longHandAngle = 0 private var shortHandAngle = 0 var radius = 0 private fun buildPaint(strokeWidthPx: Int): Paint { return Paint().apply { color = Color.BLACK isAntiAlias = true style = Paint.Style.STROKE strokeWidth = strokeWidthPx.toFloat() } } private fun drawHand( canvas: Canvas, degrees: Float, length: Int, paint: Paint, centerX: Float, centerY: Float ) { // Save and then rotate canvas canvas.run { val savedCount = save() rotate(degrees, centerX, centerY) // Draw a hand drawLine(centerX, centerY, centerX, centerY - length, paint) // Restore canvas restoreToCount(savedCount) } } fun setTime(timeMillis: Long) { val inHourProgress = timeMillis.toFloat() % ONE_HOUR / ONE_HOUR longHandAngle = (360 * inHourProgress).toInt() val inTwelveHoursProgress = timeMillis.toFloat() / TWELVE_HOURS shortHandAngle = (360 * inTwelveHoursProgress).toInt() } override fun draw(canvas: Canvas) { val bounds = bounds canvas.run { val saveCount = save() translate(bounds.left.toFloat(), bounds.top.toFloat()) drawCircle(radius.toFloat(), radius.toFloat(), radius.toFloat(), paintWide) drawHand( this, longHandAngle.toFloat(), radius * 2 / 3, paintThin, radius.toFloat(), radius.toFloat()) drawHand( this, shortHandAngle.toFloat(), radius / 3, paintMedium, radius.toFloat(), radius.toFloat()) restoreToCount(saveCount) } } override fun setAlpha(alpha: Int) {} override fun setColorFilter(colorFilter: ColorFilter?) {} override fun getOpacity(): Int { return PixelFormat.OPAQUE } }
using UnityEngine; using UnityEngine.SceneManagement; public class SilentCreditsMusic : MonoBehaviour { [SerializeField] private AudioSource endPianoMusic1; [SerializeField] private AudioSource endPianoMusic2; public void SilentMusic() { endPianoMusic1.volume -= 0.25f; endPianoMusic2.volume -= 0.25f; } }
package com.netcracker.tripnwalk.entry; import com.netcracker.tripnwalk.entry.components.BillingLike; import javax.persistence.*; @Entity @Table(name = "like_route") public class Like { public Like() { } public Like(BillingLike key) { this.key = key; } public Like(Long idUser, Long idRoute) { this.key = new BillingLike(idUser, idRoute); } @EmbeddedId private BillingLike key; public BillingLike getKey() { return key; } public void setKey(BillingLike key) { this.key = key; } }