repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
WheatonCS/Lexos
lexos/managers/utility.py
<reponame>WheatonCS/Lexos import os import re import pickle import numpy as np from flask import request from os import makedirs from typing import Dict, List from os.path import join as path_join import lexos.helpers.constants as constants import lexos.helpers.general_functions as general_functions import lexos.managers.session_manager as session_manager import lexos.processors.visualize.multicloud_topic as multicloud_topic from lexos.managers.file_manager import FileManager from lexos.managers.session_manager import session_folder def generate_json_for_d3(file_manager: FileManager, merged_set): """ Generates the data formatted nicely for the d3 visualization library. Args: merged_set: Boolean saying whether to merge all files into one data set or, if false, create a list of datasets. Returns: An object, formatted in the JSON that d3 needs, either a list or a dictionary. """ active_files = [] for l_file in list(file_manager.files.values()): if l_file.active: active_files.append(l_file) if merged_set: # Create one JSON Object across all the chunks minimum_length = int(request.form['minlength']) \ if 'minlength' in request.form else 0 master_word_counts = {} for l_file in active_files: word_counts = l_file.get_word_counts() for key in word_counts: if len(key) <= minimum_length: continue if key in master_word_counts: master_word_counts[key] += word_counts[key] else: master_word_counts[key] = word_counts[key] if 'maxwords' in request.form: # Make sure there is a number in the input form check_for_value = request.form['maxwords'] if check_for_value == "": max_num_words = 100 else: max_num_words = int(request.form['maxwords']) sorted_word_counts = sorted( master_word_counts, key=master_word_counts.__getitem__) j = len(sorted_word_counts) - max_num_words for i in range(len(sorted_word_counts) - 1, -1, -1): if i < j: del master_word_counts[sorted_word_counts[i]] return_obj = general_functions.generate_d3_object( master_word_counts, object_label="tokens", word_label="name", count_label="size") else: # Create a JSON object for each chunk return_obj = [] for l_file in active_files: return_obj.append( l_file.generate_d3_json_object( word_label="text", count_label="size")) # NOTE: Objects in JSON are dictionaries in Python, but Lists are Arrays # are Objects as well. return return_obj def generate_mc_json_obj(file_manager: FileManager): """ Generates a JSON object for multicloud when working with a mallet .txt file Args: malletPath: path to the saved mallet .txt file Returns: An object, formatted in the JSON that d3 needs, either a list or a dictionary. """ content_path = os.path.join( session_manager.session_folder(), constants.FILE_CONTENTS_FOLDER, constants.MALLET_INPUT_FILE_NAME) output_path = os.path.join( session_manager.session_folder(), constants.RESULTS_FOLDER, constants.MALLET_OUTPUT_FILE_NAME) try: makedirs( path_join(session_manager.session_folder(), constants.RESULTS_FOLDER)) # attempt to make the result dir except FileExistsError: pass # result dir already exists if request.form['analysistype'] == 'userfiles': json_obj = generate_json_for_d3(file_manager, merged_set=False) else: # request.form['analysistype'] == 'topicfile' topic_string = str(request.files['optuploadname']) topic_string = re.search(r"'(.*?)'", topic_string) topic_string = topic_string.group(1) if topic_string != '': request.files['optuploadname'].save(content_path) with open(content_path, 'r', encoding='utf-8') as f: content = f.read() # reads content from the upload file # Coerce to non UTF-8 files to UTF-8 encoding = general_functions.get_encoding(content) if encoding != 'utf-8': content = content.decode(encoding).encode('utf-8') if content.startswith('#doc source pos typeindex type topic'): # begin converting a Mallet file into the file d3 can understand tuples = [] # Read the output_state file with open(content_path, encoding='utf-8') as f: # Skip the first three lines for _ in range(3): next(f) # Create a list of type:topic combinations for line in f: # Make sure the number of columns is correct line = re.sub(r'\s+', ' ', line) try: doc, source, pos, type_index, doc_type, topic = \ line.rstrip().split(' ') type_topic_combination = doc_type + ':' + topic tuples.append(type_topic_combination) except BaseException: raise Exception( "Your source data cannot be parsed into a regular " "number of columns. Please ensure that there are " "no spaces in your file names or file paths. It; " "may be easiest to open the outpt_state file in a " "spreadsheet using a space as; the delimiter and " "text as the field type. Data should only be " "present in columns; A to F. Please fix any " "misaligned data and run this script again.") # Count the number of times each type-topic combo appears from collections import defaultdict topic_count = defaultdict(int) for x in tuples: topic_count[x] += 1 # Populate a topic_counts dict with type: topic:count words = [] topic_counts = {} for k, v in topic_count.items(): doc_type, topic = k.split(':') count = int(v) tc = topic + ":" + str(count) if doc_type in words: topic_counts[doc_type] = topic_counts[doc_type] + " " + tc else: topic_counts[doc_type] = tc words.append(doc_type) # Add a word ID out = "" i = 0 for k, v in topic_counts.items(): out += str(i) + " " + k + " " + v + "\n" i += 1 # Write the output file with open(output_path, 'w', encoding='utf-8') as f: f.write(out) # Python will convert \n to os.linesep # end converting a Mallet file into the file d3 can understand else: with open(output_path, 'w', encoding='utf-8') as f: # if this is the json form, # just write that in the output folder f.write(content) json_obj = multicloud_topic.topic_json_maker(output_path) return json_obj def save_file_manager(file_manager: FileManager): """ Saves the file manager to the hard drive. Args: file_manager: File manager object to be saved. Returns: None """ file_manager_path = os.path.join( session_folder(), constants.FILEMANAGER_FILENAME) pickle.dump(file_manager, open(file_manager_path, 'wb')) def load_file_manager() -> FileManager: """ Loads the file manager for the specific session from the hard drive. Args: None Returns: The file manager object for the session. """ file_manager_path = os.path.join( session_folder(), constants.FILEMANAGER_FILENAME) file_manager = pickle.load(open(file_manager_path, 'rb')) return file_manager def xml_handling_options(data: dict = {}): file_manager = load_file_manager() from lexos.managers import session_manager from xml.etree import ElementTree tags = [] for file in file_manager.get_active_files(): try: root = ElementTree.fromstring(file.load_contents()) iterate = root.getiterator() # Remove processing instructions -- # not necessary to get a list of tags # for pi in root.xpath("//processing-instruction()"): # etree.strip_tags(pi.getparent(), pi.tag) # Get the list of the tags for element in iterate: tag = re.sub('{.+}', '', element.tag) tags.append(tag) except ElementTree.ParseError: import bs4 from bs4 import BeautifulSoup soup = BeautifulSoup(file.load_contents(), 'xml') for e in soup: if isinstance(e, bs4.element.ProcessingInstruction): e.extract() [tags.append(tag.name) for tag in soup.find_all()] # Get a sorted list of unique tags tags = list(set(tags)) for tag in tags: if tag not in session_manager.session['xmlhandlingoptions']: session_manager.session['xmlhandlingoptions'][tag] = { "action": 'Remove Tag', "attribute": ''} # If they have saved, data is passed. # This block updates any previous entries in the dict that have been saved if data: for key in list(data.keys()): if key in tags: data_values = data[key].split(',') session_manager.session['xmlhandlingoptions'][key] = { "action": data_values[0], "attribute": data["attributeValue" + key]} session_manager.session.modified = True for key in list(session_manager.session['xmlhandlingoptions'].keys()): # makes sure that all current tags are in the active docs if key not in tags: del session_manager.session['xmlhandlingoptions'][key] session_manager.session.modified = True def simple_vectorizer(content: str, token_type: str, token_size: int): """ Creates a DTM from tokenization settings stored in the session. Args: A string generated from the document(s) to be vectorized Returns: A DTM array and a vocab term list array produced by CountVectorizer(). """ from sklearn.feature_extraction.text import CountVectorizer vectorizer = CountVectorizer( input=u'content', analyzer=token_type, ngram_range=( token_size, token_size), token_pattern=r"(?u)\b\w+\b") dtm = vectorizer.fit_transform(content) # a sparse matrix vocab = vectorizer.get_feature_names() # a list dtm = dtm.toarray() # convert to a regular array vocab = np.array(vocab) return dtm, vocab def get_active_document_label_map() -> Dict: """ Get a map of the ids and labels of the active documents. :return: A map of the ids and labels of the active documents. """ return {file.id: file.label for file in load_file_manager().get_active_files()} def get_active_document_labels() -> List: """ Get the labels of the active documents. :return: The labels of the active documents. """ return [file.label for file in load_file_manager().get_active_files()]
meteoorkip/GROOVE
groove/src/groove/match/rete/QuantifierCountChecker.java
<reponame>meteoorkip/GROOVE<gh_stars>1-10 /* GROOVE: GRaphs for Object Oriented VErification * Copyright 2003--2011 University of Twente * * 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. * * $Id: QuantifierCountChecker.java 5816 2016-11-01 07:03:51Z rensink $ */ package groove.match.rete; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import groove.algebra.Algebra; import groove.algebra.JavaIntAlgebra; import groove.grammar.Condition; import groove.grammar.Condition.Op; import groove.grammar.host.HostNode; import groove.grammar.host.ValueNode; import groove.grammar.rule.RuleElement; import groove.grammar.rule.RuleNode; import groove.grammar.rule.RuleToHostMap; import groove.grammar.rule.VariableNode; import groove.graph.NodeComparator; import groove.match.TreeMatch; import groove.match.rete.ReteSimpleMatch.ReteCountMatch; import groove.util.Visitor; import groove.util.Visitor.Collector; import groove.util.collect.TreeHashSet; /** * Asks an associated condition-checker related to a universal * quantifier for its total number of actual matches (taking its submatches * into account) and passing down a match binding the count attribute node * of the quantifier to that value. * * @author <NAME> * @version $Revision $ */ public class QuantifierCountChecker extends ReteNetworkNode implements ReteStateSubscriber { private Condition condition; private RuleElement[] pattern; /** * The match containing the single node-binding between the * count node and the actual count value calculated at each round. */ private Set<ReteCountMatch> matches = new TreeHashSet<>(); private ReteCountMatch dummyMatch; /** * The condition checker for the universal quantifier to be * counted. */ private ConditionChecker universalQuantifierChecker; /** * Inidicates if the latest valid count matches have been * sent down to the successors. */ private boolean updatesSent = false; /** * The full matcher used to ask the matches for counting * purposes. */ private ReteSearchStrategy conditionMatcher = null; /** * @param network The RETE network this checker n-node would belong to. */ public QuantifierCountChecker(ReteNetwork network, Condition condition) { super(network); assert condition.getOp() == Op.FORALL && (condition.getCountNode() != null); this.condition = condition; makePattern(); getPatternLookupTable(); //Just to fill out the pattern index this.getOwner() .getState() .subscribe(this, true); } private void makePattern() { ArrayList<RuleNode> rootNodes = new ArrayList<>(); rootNodes.addAll(this.condition.getRoot() .nodeSet()); Collections.sort(rootNodes, NodeComparator.instance()); this.pattern = new RuleElement[rootNodes.size() + 1]; int i = 0; for (RuleNode n : rootNodes) { this.pattern[i++] = n; } this.pattern[i] = this.condition.getCountNode(); } @Override public int demandOneMatch() { return 0; } @Override public boolean demandUpdate() { return false; } @Override public boolean equals(ReteNetworkNode node) { return (node instanceof QuantifierCountChecker) && (((QuantifierCountChecker) node).condition.equals(this.condition)); } @Override public boolean equals(Object obj) { return (obj instanceof ReteNetworkNode) && this.equals((ReteNetworkNode) obj); } @Override public int hashCode() { return this.condition.hashCode(); } @Override public RuleElement[] getPattern() { return this.pattern; } @Override /** * This method should not to be called by any one. */ public void receive(ReteNetworkNode source, int repeatIndex, AbstractReteMatch match) { throw new UnsupportedOperationException(); } @Override public int size() { return 1; } /** * The condition checker n-node associated with * the universal quantifier condition which this * n-node is supposed to count the matches of. */ public ConditionChecker getUniversalQuantifierChecker() { return this.universalQuantifierChecker; } /** * Set the associated condition checker for the universal quantifier */ public void setUniversalQuantifierChecker(ConditionChecker cc) { assert cc.getCondition() .equals(this.condition); this.universalQuantifierChecker = cc; } /** * Utility method for easy retrieval of the count node * of the associated condition. */ public VariableNode getCountNode() { return this.universalQuantifierChecker.getCondition() .getCountNode(); } /** * This method is called by the associated condition-checker * n-node to notify this checker n-node that the pre-calculated * count is no longer valid (due to some changes to the conflict * set of this condition checker or of its sub-condition-checkers) */ public boolean invalidateCount() { boolean result = !this.matches.isEmpty(); if (result) { for (ReteSimpleMatch match : this.matches) { match.dominoDelete(null); } this.matches.clear(); } if (this.dummyMatch != null) { this.dummyMatch.dominoDelete(null); this.dummyMatch = null; } this.updatesSent = false; return result; } @Override public void clear() { this.matches.clear(); this.dummyMatch = null; this.updatesSent = false; this.conditionMatcher = null; } @Override public List<? extends Object> initialize() { return null; } @Override public void updateBegin() { //There's nothing to do //we just have to wait for all the updates to happen //before we can start calculating the counts } @Override public void updateEnd() { if (!this.updatesSent) { calculateMatches(); if (!this.matches.isEmpty()) { for (ReteSimpleMatch match : this.matches) { passDownMatchToSuccessors(match); } } if (this.dummyMatch != null) { passDownMatchToSuccessors(this.dummyMatch); } this.updatesSent = true; } } private void calculateMatches() { this.matches.clear(); Set<RuleToHostMap> activeAnchors = this.universalQuantifierChecker.getActiveConflictsetAnchors(false); if (this.conditionMatcher == null) { this.conditionMatcher = this.getOwner() .getOwnerEngine() .createMatcher(this.universalQuantifierChecker.getCondition(), null); } if (activeAnchors != null) { for (RuleToHostMap anchor : activeAnchors) { ReteCountMatch m = getCountMatch(anchor); if (m != null) { this.matches.add(m); } } } else { ReteCountMatch m = getCountMatch(null); if (m != null) { this.matches.add(m); } } if (this.condition.getCountNode() .getConstant() == null) { Algebra<Integer> intAlgebra = JavaIntAlgebra.instance; ValueNode countNode = this.getOwner() .getOwnerEngine() .getNetwork() .getHostFactory() .createNode(intAlgebra, intAlgebra.toValueFromJava(0)); this.dummyMatch = new ReteCountMatch(this, countNode); } else { this.dummyMatch = null; } } private ReteCountMatch getCountMatch(RuleToHostMap anchor) { ReteCountMatch countMatch = null; List<TreeMatch> matchList = new ArrayList<>(); Collector<TreeMatch,?> collector = Visitor.newCollector(matchList); this.conditionMatcher.traverse(this.getOwner() .getOwnerEngine() .getNetwork() .getState() .getHostGraph(), anchor, collector); Algebra<Integer> intAlgebra = JavaIntAlgebra.instance; ValueNode vn = this.getOwner() .getOwnerEngine() .getNetwork() .getHostFactory() .createNode(intAlgebra, intAlgebra.toValueFromJava(matchList.size())); if (this.getCountNode() .hasConstant()) { if (this.getCountNode() .getConstant() .equals(vn.getTerm())) { countMatch = new ReteCountMatch(this, getAnchorNodes(anchor), vn); } } else { countMatch = new ReteCountMatch(this, getAnchorNodes(anchor), vn); } if (countMatch != null) { this.matches.add(countMatch); } return countMatch; } private HostNode[] getAnchorNodes(RuleToHostMap map) { HostNode[] result = new HostNode[this.pattern.length - 1]; if (map != null) { for (int i = 0; i < this.pattern.length - 1; i++) { HostNode hn = map.getNode((RuleNode) this.pattern[i]); assert hn != null; result[i] = hn; } } return result; } /** * Determines if this quantifier count checker produces different count * values for different given higher level anchors. * * If the return * value of this method is <code>true</code> then it means this checker * n-node will only produce one count match. */ public boolean isAnchored() { return !this.condition.getRoot() .isEmpty(); } /** * Returns <code>true</code> if the count node that this checker * is associated with is a constant, in which case a dummy match * is not produced. Returns <code>false</code> otherwise. */ public boolean isConstant() { return this.getCountNode() .getConstant() != null; } }
ingeniousthings/sigfox-rest-client
src/main/java/ingeniousthings/sigfox/model/Group.java
<gh_stars>0 package ingeniousthings.sigfox.model; import java.util.Arrays; public class Group { public final String id; public final String name; public final String nameCI; public final String description; public final String[] path; public final boolean billable; public final String bssId; public Group(String id, String name, String nameCI, String description, String[] path, boolean billable, String bssId) { this.id = id; this.name = name; this.nameCI = nameCI; this.description = description; this.path = path; this.billable = billable; this.bssId = bssId; } @Override public String toString() { return "Group{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", nameCI='" + nameCI + '\'' + ", description='" + description + '\'' + ", path=" + Arrays.toString(path) + ", billable=" + billable + ", bssId='" + bssId + '\'' + '}'; } }
n3llino/jclouds
core/src/test/java/org/jclouds/utils/TestUtils.java
<filename>core/src/test/java/org/jclouds/utils/TestUtils.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.jclouds.utils; import java.io.InputStream; import java.io.IOException; import java.util.Random; import com.google.common.io.ByteSource; /** * Utility class for test */ public class TestUtils { public static boolean isMacOSX() { String osName = System.getProperty("os.name"); return osName.contains("OS X"); } public static boolean isJava6() { return System.getProperty("java.version", "").contains("1.6."); } public static ByteSource randomByteSource() { return randomByteSource(0); } public static ByteSource randomByteSource(long seed) { return new RandomByteSource(seed); } private static class RandomByteSource extends ByteSource { private final long seed; RandomByteSource(long seed) { this.seed = seed; } @Override public InputStream openStream() { return new RandomInputStream(seed); } } private static class RandomInputStream extends InputStream { private final Random random; RandomInputStream(long seed) { this.random = new Random(seed); } @Override public synchronized int read() { return (byte) random.nextInt(); } @Override public synchronized int read(byte[] b) throws IOException { random.nextBytes(b); return b.length; } @Override public synchronized int read(byte[] b, int off, int len) throws IOException { // need extra array to cope with offset byte[] srcBytes = new byte[len]; random.nextBytes(srcBytes); System.arraycopy(srcBytes, 0, b, off, len); return len; } } }
piloer/cloudflared
cmd/cloudflared/app_resolver_service.go
package main import ( "github.com/rs/zerolog" "github.com/cloudflare/cloudflared/config" "github.com/cloudflare/cloudflared/tunneldns" ) const ( // ResolverServiceType is used to identify what kind of overwatch service this is ResolverServiceType = "resolver" LogFieldResolverAddress = "resolverAddress" LogFieldResolverPort = "resolverPort" LogFieldResolverMaxUpstreamConns = "resolverMaxUpstreamConns" ) // ResolverService is used to wrap the tunneldns package's DNS over HTTP // into a service model for the overwatch package. // it also holds a reference to the config object that represents its state type ResolverService struct { resolver config.DNSResolver shutdown chan struct{} log *zerolog.Logger } // NewResolverService creates a new resolver service func NewResolverService(r config.DNSResolver, log *zerolog.Logger) *ResolverService { return &ResolverService{resolver: r, shutdown: make(chan struct{}), log: log, } } // Name is used to figure out this service is related to the others (normally the addr it binds to) // this is just "resolver" since there can only be one DNS resolver running func (s *ResolverService) Name() string { return ResolverServiceType } // Type is used to identify what kind of overwatch service this is func (s *ResolverService) Type() string { return ResolverServiceType } // Hash is used to figure out if this forwarder is the unchanged or not from the config file updates func (s *ResolverService) Hash() string { return s.resolver.Hash() } // Shutdown stops the tunneldns listener func (s *ResolverService) Shutdown() { s.shutdown <- struct{}{} } // Run is the run loop that is started by the overwatch service func (s *ResolverService) Run() error { // create a listener l, err := tunneldns.CreateListener(s.resolver.AddressOrDefault(), s.resolver.PortOrDefault(), s.resolver.UpstreamsOrDefault(), s.resolver.BootstrapsOrDefault(), s.resolver.MaxUpstreamConnectionsOrDefault(), s.log) if err != nil { return err } // start the listener. readySignal := make(chan struct{}) err = l.Start(readySignal) if err != nil { _ = l.Stop() return err } <-readySignal resolverLog := s.log.With(). Str(LogFieldResolverAddress, s.resolver.AddressOrDefault()). Uint16(LogFieldResolverPort, s.resolver.PortOrDefault()). Int(LogFieldResolverMaxUpstreamConns, s.resolver.MaxUpstreamConnectionsOrDefault()). Logger() resolverLog.Info().Msg("Starting resolver") // wait for shutdown signal <-s.shutdown resolverLog.Info().Msg("Shutting down resolver") return l.Stop() }
Kingwentao/DesignPatternOfBeauty
src/BasicPrincple/ocp/NotificationEmergencyLevel.java
<filename>src/BasicPrincple/ocp/NotificationEmergencyLevel.java package BasicPrincple.ocp; /** * author: WentaoKing * created on: 2019/12/9 * description:表示通知的紧急程度,包括 SEVERE(严重)、URGENCY(紧急)、 * NORMAL(普通)、TRIVIAL(无关紧要),不同的紧急程度对应不同的发送渠道 */ public class NotificationEmergencyLevel { public static final int URGENCY = 0; public static final int SEVERE = 1; }
ticifer/Tbed
src/main/java/cn/hellohao/utils/SetFiles.java
package cn.hellohao.utils; import org.springframework.web.multipart.MultipartFile; import java.io.File; public class SetFiles { // 转换文件方法 public static File changeFile(MultipartFile multipartFile) throws Exception { // 获取文件名 String fileName = multipartFile.getOriginalFilename(); // 获取文件后缀 String prefix = fileName.substring(fileName.lastIndexOf(".")); // todo 修改临时文件文件名 File file = File.createTempFile(fileName, prefix); multipartFile.transferTo(file); return file; } }
duneswake/ervell
src/v2/components/UI/Inputs/components/Select/index.js
import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' import mixin from 'v2/components/UI/Inputs/mixin' const SelectWrapper = styled.div` position: relative; &:after { display: inline-block; content ''; width: 0; height: 0; position: absolute; top: 50%; right: 1em; transform: translate(0.25em, -50%); border-top: 0.5em solid ${x => x.theme.colors.gray.semiBold}; border-right: 0.25em solid transparent; border-left: 0.25em solid transparent; pointer-events: none; } ` const SelectTag = styled.select` ${mixin} padding-right: 1.5em; ` const Select = ({ children, ...rest }) => ( <SelectWrapper> <SelectTag {...rest}>{children}</SelectTag> </SelectWrapper> ) Select.propTypes = { children: PropTypes.node.isRequired, } export default Select
Alpha470/cainiaoshop
cainiaoshop-product/src/main/java/com/alpha/cainiaoshop/product/service/SkuInfoService.java
<filename>cainiaoshop-product/src/main/java/com/alpha/cainiaoshop/product/service/SkuInfoService.java<gh_stars>1-10 package com.alpha.cainiaoshop.product.service; import com.baomidou.mybatisplus.extension.service.IService; import com.alpha.common.utils.PageUtils; import com.alpha.cainiaoshop.product.entity.SkuInfoEntity; import java.util.Map; /** * sku信息 * * @author guojun * @email <EMAIL> * @date 2020-05-25 20:50:29 */ public interface SkuInfoService extends IService<SkuInfoEntity> { PageUtils queryPage(Map<String, Object> params); void saveSkuInfo(SkuInfoEntity skuInfoEntity); PageUtils queryPageByCondition(Map<String, Object> params); }
shmily1012/linux-zns
Linux_Kernel/linux-master/drivers/misc/habanalabs/command_submission.c
<reponame>shmily1012/linux-zns // SPDX-License-Identifier: GPL-2.0 /* * Copyright 2016-2019 HabanaLabs, Ltd. * All Rights Reserved. */ #include <uapi/misc/habanalabs.h> #include "habanalabs.h" #include <linux/uaccess.h> #include <linux/slab.h> #define HL_CS_FLAGS_SIG_WAIT (HL_CS_FLAGS_SIGNAL | HL_CS_FLAGS_WAIT) static void job_wq_completion(struct work_struct *work); static long _hl_cs_wait_ioctl(struct hl_device *hdev, struct hl_ctx *ctx, u64 timeout_us, u64 seq); static void cs_do_release(struct kref *ref); static void hl_sob_reset(struct kref *ref) { struct hl_hw_sob *hw_sob = container_of(ref, struct hl_hw_sob, kref); struct hl_device *hdev = hw_sob->hdev; hdev->asic_funcs->reset_sob(hdev, hw_sob); } void hl_sob_reset_error(struct kref *ref) { struct hl_hw_sob *hw_sob = container_of(ref, struct hl_hw_sob, kref); struct hl_device *hdev = hw_sob->hdev; dev_crit(hdev->dev, "SOB release shouldn't be called here, q_idx: %d, sob_id: %d\n", hw_sob->q_idx, hw_sob->sob_id); } static const char *hl_fence_get_driver_name(struct dma_fence *fence) { return "HabanaLabs"; } static const char *hl_fence_get_timeline_name(struct dma_fence *fence) { struct hl_cs_compl *hl_cs_compl = container_of(fence, struct hl_cs_compl, base_fence); return dev_name(hl_cs_compl->hdev->dev); } static bool hl_fence_enable_signaling(struct dma_fence *fence) { return true; } static void hl_fence_release(struct dma_fence *fence) { struct hl_cs_compl *hl_cs_cmpl = container_of(fence, struct hl_cs_compl, base_fence); struct hl_device *hdev = hl_cs_cmpl->hdev; /* EBUSY means the CS was never submitted and hence we don't have * an attached hw_sob object that we should handle here */ if (fence->error == -EBUSY) goto free; if ((hl_cs_cmpl->type == CS_TYPE_SIGNAL) || (hl_cs_cmpl->type == CS_TYPE_WAIT)) { dev_dbg(hdev->dev, "CS 0x%llx type %d finished, sob_id: %d, sob_val: 0x%x\n", hl_cs_cmpl->cs_seq, hl_cs_cmpl->type, hl_cs_cmpl->hw_sob->sob_id, hl_cs_cmpl->sob_val); /* * A signal CS can get completion while the corresponding wait * for signal CS is on its way to the PQ. The wait for signal CS * will get stuck if the signal CS incremented the SOB to its * max value and there are no pending (submitted) waits on this * SOB. * We do the following to void this situation: * 1. The wait for signal CS must get a ref for the signal CS as * soon as possible in cs_ioctl_signal_wait() and put it * before being submitted to the PQ but after it incremented * the SOB refcnt in init_signal_wait_cs(). * 2. Signal/Wait for signal CS will decrement the SOB refcnt * here. * These two measures guarantee that the wait for signal CS will * reset the SOB upon completion rather than the signal CS and * hence the above scenario is avoided. */ kref_put(&hl_cs_cmpl->hw_sob->kref, hl_sob_reset); } free: kfree_rcu(hl_cs_cmpl, base_fence.rcu); } static const struct dma_fence_ops hl_fence_ops = { .get_driver_name = hl_fence_get_driver_name, .get_timeline_name = hl_fence_get_timeline_name, .enable_signaling = hl_fence_enable_signaling, .release = hl_fence_release }; static void cs_get(struct hl_cs *cs) { kref_get(&cs->refcount); } static int cs_get_unless_zero(struct hl_cs *cs) { return kref_get_unless_zero(&cs->refcount); } static void cs_put(struct hl_cs *cs) { kref_put(&cs->refcount, cs_do_release); } static bool is_cb_patched(struct hl_device *hdev, struct hl_cs_job *job) { /* * Patched CB is created for external queues jobs, and for H/W queues * jobs if the user CB was allocated by driver and MMU is disabled. */ return (job->queue_type == QUEUE_TYPE_EXT || (job->queue_type == QUEUE_TYPE_HW && job->is_kernel_allocated_cb && !hdev->mmu_enable)); } /* * cs_parser - parse the user command submission * * @hpriv : pointer to the private data of the fd * @job : pointer to the job that holds the command submission info * * The function parses the command submission of the user. It calls the * ASIC specific parser, which returns a list of memory blocks to send * to the device as different command buffers * */ static int cs_parser(struct hl_fpriv *hpriv, struct hl_cs_job *job) { struct hl_device *hdev = hpriv->hdev; struct hl_cs_parser parser; int rc; parser.ctx_id = job->cs->ctx->asid; parser.cs_sequence = job->cs->sequence; parser.job_id = job->id; parser.hw_queue_id = job->hw_queue_id; parser.job_userptr_list = &job->userptr_list; parser.patched_cb = NULL; parser.user_cb = job->user_cb; parser.user_cb_size = job->user_cb_size; parser.queue_type = job->queue_type; parser.is_kernel_allocated_cb = job->is_kernel_allocated_cb; job->patched_cb = NULL; rc = hdev->asic_funcs->cs_parser(hdev, &parser); if (is_cb_patched(hdev, job)) { if (!rc) { job->patched_cb = parser.patched_cb; job->job_cb_size = parser.patched_cb_size; job->contains_dma_pkt = parser.contains_dma_pkt; spin_lock(&job->patched_cb->lock); job->patched_cb->cs_cnt++; spin_unlock(&job->patched_cb->lock); } /* * Whether the parsing worked or not, we don't need the * original CB anymore because it was already parsed and * won't be accessed again for this CS */ spin_lock(&job->user_cb->lock); job->user_cb->cs_cnt--; spin_unlock(&job->user_cb->lock); hl_cb_put(job->user_cb); job->user_cb = NULL; } else if (!rc) { job->job_cb_size = job->user_cb_size; } return rc; } static void free_job(struct hl_device *hdev, struct hl_cs_job *job) { struct hl_cs *cs = job->cs; if (is_cb_patched(hdev, job)) { hl_userptr_delete_list(hdev, &job->userptr_list); /* * We might arrive here from rollback and patched CB wasn't * created, so we need to check it's not NULL */ if (job->patched_cb) { spin_lock(&job->patched_cb->lock); job->patched_cb->cs_cnt--; spin_unlock(&job->patched_cb->lock); hl_cb_put(job->patched_cb); } } /* For H/W queue jobs, if a user CB was allocated by driver and MMU is * enabled, the user CB isn't released in cs_parser() and thus should be * released here. */ if (job->queue_type == QUEUE_TYPE_HW && job->is_kernel_allocated_cb && hdev->mmu_enable) { spin_lock(&job->user_cb->lock); job->user_cb->cs_cnt--; spin_unlock(&job->user_cb->lock); hl_cb_put(job->user_cb); } /* * This is the only place where there can be multiple threads * modifying the list at the same time */ spin_lock(&cs->job_lock); list_del(&job->cs_node); spin_unlock(&cs->job_lock); hl_debugfs_remove_job(hdev, job); if (job->queue_type == QUEUE_TYPE_EXT || job->queue_type == QUEUE_TYPE_HW) cs_put(cs); kfree(job); } static void cs_do_release(struct kref *ref) { struct hl_cs *cs = container_of(ref, struct hl_cs, refcount); struct hl_device *hdev = cs->ctx->hdev; struct hl_cs_job *job, *tmp; cs->completed = true; /* * Although if we reached here it means that all external jobs have * finished, because each one of them took refcnt to CS, we still * need to go over the internal jobs and free them. Otherwise, we * will have leaked memory and what's worse, the CS object (and * potentially the CTX object) could be released, while the JOB * still holds a pointer to them (but no reference). */ list_for_each_entry_safe(job, tmp, &cs->job_list, cs_node) free_job(hdev, job); /* We also need to update CI for internal queues */ if (cs->submitted) { hdev->asic_funcs->hw_queues_lock(hdev); hdev->cs_active_cnt--; if (!hdev->cs_active_cnt) { struct hl_device_idle_busy_ts *ts; ts = &hdev->idle_busy_ts_arr[hdev->idle_busy_ts_idx++]; ts->busy_to_idle_ts = ktime_get(); if (hdev->idle_busy_ts_idx == HL_IDLE_BUSY_TS_ARR_SIZE) hdev->idle_busy_ts_idx = 0; } else if (hdev->cs_active_cnt < 0) { dev_crit(hdev->dev, "CS active cnt %d is negative\n", hdev->cs_active_cnt); } hdev->asic_funcs->hw_queues_unlock(hdev); hl_int_hw_queue_update_ci(cs); spin_lock(&hdev->hw_queues_mirror_lock); /* remove CS from hw_queues mirror list */ list_del_init(&cs->mirror_node); spin_unlock(&hdev->hw_queues_mirror_lock); /* * Don't cancel TDR in case this CS was timedout because we * might be running from the TDR context */ if ((!cs->timedout) && (hdev->timeout_jiffies != MAX_SCHEDULE_TIMEOUT)) { struct hl_cs *next; if (cs->tdr_active) cancel_delayed_work_sync(&cs->work_tdr); spin_lock(&hdev->hw_queues_mirror_lock); /* queue TDR for next CS */ next = list_first_entry_or_null( &hdev->hw_queues_mirror_list, struct hl_cs, mirror_node); if ((next) && (!next->tdr_active)) { next->tdr_active = true; schedule_delayed_work(&next->work_tdr, hdev->timeout_jiffies); } spin_unlock(&hdev->hw_queues_mirror_lock); } } else if (cs->type == CS_TYPE_WAIT) { /* * In case the wait for signal CS was submitted, the put occurs * in init_signal_wait_cs() right before hanging on the PQ. */ dma_fence_put(cs->signal_fence); } /* * Must be called before hl_ctx_put because inside we use ctx to get * the device */ hl_debugfs_remove_cs(cs); hl_ctx_put(cs->ctx); /* We need to mark an error for not submitted because in that case * the dma fence release flow is different. Mainly, we don't need * to handle hw_sob for signal/wait */ if (cs->timedout) dma_fence_set_error(cs->fence, -ETIMEDOUT); else if (cs->aborted) dma_fence_set_error(cs->fence, -EIO); else if (!cs->submitted) dma_fence_set_error(cs->fence, -EBUSY); dma_fence_signal(cs->fence); dma_fence_put(cs->fence); kfree(cs); } static void cs_timedout(struct work_struct *work) { struct hl_device *hdev; int ctx_asid, rc; struct hl_cs *cs = container_of(work, struct hl_cs, work_tdr.work); rc = cs_get_unless_zero(cs); if (!rc) return; if ((!cs->submitted) || (cs->completed)) { cs_put(cs); return; } /* Mark the CS is timed out so we won't try to cancel its TDR */ cs->timedout = true; hdev = cs->ctx->hdev; ctx_asid = cs->ctx->asid; /* TODO: add information about last signaled seq and last emitted seq */ dev_err(hdev->dev, "User %d command submission %llu got stuck!\n", ctx_asid, cs->sequence); cs_put(cs); if (hdev->reset_on_lockup) hl_device_reset(hdev, false, false); } static int allocate_cs(struct hl_device *hdev, struct hl_ctx *ctx, enum hl_cs_type cs_type, struct hl_cs **cs_new) { struct hl_cs_compl *cs_cmpl; struct dma_fence *other = NULL; struct hl_cs *cs; int rc; cs = kzalloc(sizeof(*cs), GFP_ATOMIC); if (!cs) return -ENOMEM; cs->ctx = ctx; cs->submitted = false; cs->completed = false; cs->type = cs_type; INIT_LIST_HEAD(&cs->job_list); INIT_DELAYED_WORK(&cs->work_tdr, cs_timedout); kref_init(&cs->refcount); spin_lock_init(&cs->job_lock); cs_cmpl = kmalloc(sizeof(*cs_cmpl), GFP_ATOMIC); if (!cs_cmpl) { rc = -ENOMEM; goto free_cs; } cs_cmpl->hdev = hdev; cs_cmpl->type = cs->type; spin_lock_init(&cs_cmpl->lock); cs->fence = &cs_cmpl->base_fence; spin_lock(&ctx->cs_lock); cs_cmpl->cs_seq = ctx->cs_sequence; other = ctx->cs_pending[cs_cmpl->cs_seq & (HL_MAX_PENDING_CS - 1)]; if ((other) && (!dma_fence_is_signaled(other))) { spin_unlock(&ctx->cs_lock); dev_dbg(hdev->dev, "Rejecting CS because of too many in-flights CS\n"); rc = -EAGAIN; goto free_fence; } dma_fence_init(&cs_cmpl->base_fence, &hl_fence_ops, &cs_cmpl->lock, ctx->asid, ctx->cs_sequence); cs->sequence = cs_cmpl->cs_seq; ctx->cs_pending[cs_cmpl->cs_seq & (HL_MAX_PENDING_CS - 1)] = &cs_cmpl->base_fence; ctx->cs_sequence++; dma_fence_get(&cs_cmpl->base_fence); dma_fence_put(other); spin_unlock(&ctx->cs_lock); *cs_new = cs; return 0; free_fence: kfree(cs_cmpl); free_cs: kfree(cs); return rc; } static void cs_rollback(struct hl_device *hdev, struct hl_cs *cs) { struct hl_cs_job *job, *tmp; list_for_each_entry_safe(job, tmp, &cs->job_list, cs_node) free_job(hdev, job); } void hl_cs_rollback_all(struct hl_device *hdev) { struct hl_cs *cs, *tmp; /* flush all completions */ flush_workqueue(hdev->cq_wq); /* Make sure we don't have leftovers in the H/W queues mirror list */ list_for_each_entry_safe(cs, tmp, &hdev->hw_queues_mirror_list, mirror_node) { cs_get(cs); cs->aborted = true; dev_warn_ratelimited(hdev->dev, "Killing CS %d.%llu\n", cs->ctx->asid, cs->sequence); cs_rollback(hdev, cs); cs_put(cs); } } static void job_wq_completion(struct work_struct *work) { struct hl_cs_job *job = container_of(work, struct hl_cs_job, finish_work); struct hl_cs *cs = job->cs; struct hl_device *hdev = cs->ctx->hdev; /* job is no longer needed */ free_job(hdev, job); } static int validate_queue_index(struct hl_device *hdev, struct hl_cs_chunk *chunk, enum hl_queue_type *queue_type, bool *is_kernel_allocated_cb) { struct asic_fixed_properties *asic = &hdev->asic_prop; struct hw_queue_properties *hw_queue_prop; hw_queue_prop = &asic->hw_queues_props[chunk->queue_index]; if ((chunk->queue_index >= HL_MAX_QUEUES) || (hw_queue_prop->type == QUEUE_TYPE_NA)) { dev_err(hdev->dev, "Queue index %d is invalid\n", chunk->queue_index); return -EINVAL; } if (hw_queue_prop->driver_only) { dev_err(hdev->dev, "Queue index %d is restricted for the kernel driver\n", chunk->queue_index); return -EINVAL; } *queue_type = hw_queue_prop->type; *is_kernel_allocated_cb = !!hw_queue_prop->requires_kernel_cb; return 0; } static struct hl_cb *get_cb_from_cs_chunk(struct hl_device *hdev, struct hl_cb_mgr *cb_mgr, struct hl_cs_chunk *chunk) { struct hl_cb *cb; u32 cb_handle; cb_handle = (u32) (chunk->cb_handle >> PAGE_SHIFT); cb = hl_cb_get(hdev, cb_mgr, cb_handle); if (!cb) { dev_err(hdev->dev, "CB handle 0x%x invalid\n", cb_handle); return NULL; } if ((chunk->cb_size < 8) || (chunk->cb_size > cb->size)) { dev_err(hdev->dev, "CB size %u invalid\n", chunk->cb_size); goto release_cb; } spin_lock(&cb->lock); cb->cs_cnt++; spin_unlock(&cb->lock); return cb; release_cb: hl_cb_put(cb); return NULL; } struct hl_cs_job *hl_cs_allocate_job(struct hl_device *hdev, enum hl_queue_type queue_type, bool is_kernel_allocated_cb) { struct hl_cs_job *job; job = kzalloc(sizeof(*job), GFP_ATOMIC); if (!job) return NULL; job->queue_type = queue_type; job->is_kernel_allocated_cb = is_kernel_allocated_cb; if (is_cb_patched(hdev, job)) INIT_LIST_HEAD(&job->userptr_list); if (job->queue_type == QUEUE_TYPE_EXT) INIT_WORK(&job->finish_work, job_wq_completion); return job; } static int cs_ioctl_default(struct hl_fpriv *hpriv, void __user *chunks, u32 num_chunks, u64 *cs_seq) { struct hl_device *hdev = hpriv->hdev; struct hl_cs_chunk *cs_chunk_array; struct hl_cs_job *job; struct hl_cs *cs; struct hl_cb *cb; bool int_queues_only = true; u32 size_to_copy; int rc, i; *cs_seq = ULLONG_MAX; if (num_chunks > HL_MAX_JOBS_PER_CS) { dev_err(hdev->dev, "Number of chunks can NOT be larger than %d\n", HL_MAX_JOBS_PER_CS); rc = -EINVAL; goto out; } cs_chunk_array = kmalloc_array(num_chunks, sizeof(*cs_chunk_array), GFP_ATOMIC); if (!cs_chunk_array) { rc = -ENOMEM; goto out; } size_to_copy = num_chunks * sizeof(struct hl_cs_chunk); if (copy_from_user(cs_chunk_array, chunks, size_to_copy)) { dev_err(hdev->dev, "Failed to copy cs chunk array from user\n"); rc = -EFAULT; goto free_cs_chunk_array; } /* increment refcnt for context */ hl_ctx_get(hdev, hpriv->ctx); rc = allocate_cs(hdev, hpriv->ctx, CS_TYPE_DEFAULT, &cs); if (rc) { hl_ctx_put(hpriv->ctx); goto free_cs_chunk_array; } *cs_seq = cs->sequence; hl_debugfs_add_cs(cs); /* Validate ALL the CS chunks before submitting the CS */ for (i = 0 ; i < num_chunks ; i++) { struct hl_cs_chunk *chunk = &cs_chunk_array[i]; enum hl_queue_type queue_type; bool is_kernel_allocated_cb; rc = validate_queue_index(hdev, chunk, &queue_type, &is_kernel_allocated_cb); if (rc) goto free_cs_object; if (is_kernel_allocated_cb) { cb = get_cb_from_cs_chunk(hdev, &hpriv->cb_mgr, chunk); if (!cb) { rc = -EINVAL; goto free_cs_object; } } else { cb = (struct hl_cb *) (uintptr_t) chunk->cb_handle; } if (queue_type == QUEUE_TYPE_EXT || queue_type == QUEUE_TYPE_HW) int_queues_only = false; job = hl_cs_allocate_job(hdev, queue_type, is_kernel_allocated_cb); if (!job) { dev_err(hdev->dev, "Failed to allocate a new job\n"); rc = -ENOMEM; if (is_kernel_allocated_cb) goto release_cb; else goto free_cs_object; } job->id = i + 1; job->cs = cs; job->user_cb = cb; job->user_cb_size = chunk->cb_size; job->hw_queue_id = chunk->queue_index; cs->jobs_in_queue_cnt[job->hw_queue_id]++; list_add_tail(&job->cs_node, &cs->job_list); /* * Increment CS reference. When CS reference is 0, CS is * done and can be signaled to user and free all its resources * Only increment for JOB on external or H/W queues, because * only for those JOBs we get completion */ if (job->queue_type == QUEUE_TYPE_EXT || job->queue_type == QUEUE_TYPE_HW) cs_get(cs); hl_debugfs_add_job(hdev, job); rc = cs_parser(hpriv, job); if (rc) { dev_err(hdev->dev, "Failed to parse JOB %d.%llu.%d, err %d, rejecting the CS\n", cs->ctx->asid, cs->sequence, job->id, rc); goto free_cs_object; } } if (int_queues_only) { dev_err(hdev->dev, "Reject CS %d.%llu because only internal queues jobs are present\n", cs->ctx->asid, cs->sequence); rc = -EINVAL; goto free_cs_object; } rc = hl_hw_queue_schedule_cs(cs); if (rc) { if (rc != -EAGAIN) dev_err(hdev->dev, "Failed to submit CS %d.%llu to H/W queues, error %d\n", cs->ctx->asid, cs->sequence, rc); goto free_cs_object; } rc = HL_CS_STATUS_SUCCESS; goto put_cs; release_cb: spin_lock(&cb->lock); cb->cs_cnt--; spin_unlock(&cb->lock); hl_cb_put(cb); free_cs_object: cs_rollback(hdev, cs); *cs_seq = ULLONG_MAX; /* The path below is both for good and erroneous exits */ put_cs: /* We finished with the CS in this function, so put the ref */ cs_put(cs); free_cs_chunk_array: kfree(cs_chunk_array); out: return rc; } static int cs_ioctl_signal_wait(struct hl_fpriv *hpriv, enum hl_cs_type cs_type, void __user *chunks, u32 num_chunks, u64 *cs_seq) { struct hl_device *hdev = hpriv->hdev; struct hl_ctx *ctx = hpriv->ctx; struct hl_cs_chunk *cs_chunk_array, *chunk; struct hw_queue_properties *hw_queue_prop; struct dma_fence *sig_fence = NULL; struct hl_cs_job *job; struct hl_cs *cs; struct hl_cb *cb; u64 *signal_seq_arr = NULL, signal_seq; u32 size_to_copy, q_idx, signal_seq_arr_len, cb_size; int rc; *cs_seq = ULLONG_MAX; if (num_chunks > HL_MAX_JOBS_PER_CS) { dev_err(hdev->dev, "Number of chunks can NOT be larger than %d\n", HL_MAX_JOBS_PER_CS); rc = -EINVAL; goto out; } cs_chunk_array = kmalloc_array(num_chunks, sizeof(*cs_chunk_array), GFP_ATOMIC); if (!cs_chunk_array) { rc = -ENOMEM; goto out; } size_to_copy = num_chunks * sizeof(struct hl_cs_chunk); if (copy_from_user(cs_chunk_array, chunks, size_to_copy)) { dev_err(hdev->dev, "Failed to copy cs chunk array from user\n"); rc = -EFAULT; goto free_cs_chunk_array; } /* currently it is guaranteed to have only one chunk */ chunk = &cs_chunk_array[0]; q_idx = chunk->queue_index; hw_queue_prop = &hdev->asic_prop.hw_queues_props[q_idx]; if ((q_idx >= HL_MAX_QUEUES) || (hw_queue_prop->type != QUEUE_TYPE_EXT)) { dev_err(hdev->dev, "Queue index %d is invalid\n", q_idx); rc = -EINVAL; goto free_cs_chunk_array; } if (cs_type == CS_TYPE_WAIT) { struct hl_cs_compl *sig_waitcs_cmpl; signal_seq_arr_len = chunk->num_signal_seq_arr; /* currently only one signal seq is supported */ if (signal_seq_arr_len != 1) { dev_err(hdev->dev, "Wait for signal CS supports only one signal CS seq\n"); rc = -EINVAL; goto free_cs_chunk_array; } signal_seq_arr = kmalloc_array(signal_seq_arr_len, sizeof(*signal_seq_arr), GFP_ATOMIC); if (!signal_seq_arr) { rc = -ENOMEM; goto free_cs_chunk_array; } size_to_copy = chunk->num_signal_seq_arr * sizeof(*signal_seq_arr); if (copy_from_user(signal_seq_arr, u64_to_user_ptr(chunk->signal_seq_arr), size_to_copy)) { dev_err(hdev->dev, "Failed to copy signal seq array from user\n"); rc = -EFAULT; goto free_signal_seq_array; } /* currently it is guaranteed to have only one signal seq */ signal_seq = signal_seq_arr[0]; sig_fence = hl_ctx_get_fence(ctx, signal_seq); if (IS_ERR(sig_fence)) { dev_err(hdev->dev, "Failed to get signal CS with seq 0x%llx\n", signal_seq); rc = PTR_ERR(sig_fence); goto free_signal_seq_array; } if (!sig_fence) { /* signal CS already finished */ rc = 0; goto free_signal_seq_array; } sig_waitcs_cmpl = container_of(sig_fence, struct hl_cs_compl, base_fence); if (sig_waitcs_cmpl->type != CS_TYPE_SIGNAL) { dev_err(hdev->dev, "CS seq 0x%llx is not of a signal CS\n", signal_seq); dma_fence_put(sig_fence); rc = -EINVAL; goto free_signal_seq_array; } if (dma_fence_is_signaled(sig_fence)) { /* signal CS already finished */ dma_fence_put(sig_fence); rc = 0; goto free_signal_seq_array; } } /* increment refcnt for context */ hl_ctx_get(hdev, ctx); rc = allocate_cs(hdev, ctx, cs_type, &cs); if (rc) { if (cs_type == CS_TYPE_WAIT) dma_fence_put(sig_fence); hl_ctx_put(ctx); goto free_signal_seq_array; } /* * Save the signal CS fence for later initialization right before * hanging the wait CS on the queue. */ if (cs->type == CS_TYPE_WAIT) cs->signal_fence = sig_fence; hl_debugfs_add_cs(cs); *cs_seq = cs->sequence; job = hl_cs_allocate_job(hdev, QUEUE_TYPE_EXT, true); if (!job) { dev_err(hdev->dev, "Failed to allocate a new job\n"); rc = -ENOMEM; goto put_cs; } cb = hl_cb_kernel_create(hdev, PAGE_SIZE); if (!cb) { kfree(job); rc = -EFAULT; goto put_cs; } if (cs->type == CS_TYPE_WAIT) cb_size = hdev->asic_funcs->get_wait_cb_size(hdev); else cb_size = hdev->asic_funcs->get_signal_cb_size(hdev); job->id = 0; job->cs = cs; job->user_cb = cb; job->user_cb->cs_cnt++; job->user_cb_size = cb_size; job->hw_queue_id = q_idx; /* * No need in parsing, user CB is the patched CB. * We call hl_cb_destroy() out of two reasons - we don't need the CB in * the CB idr anymore and to decrement its refcount as it was * incremented inside hl_cb_kernel_create(). */ job->patched_cb = job->user_cb; job->job_cb_size = job->user_cb_size; hl_cb_destroy(hdev, &hdev->kernel_cb_mgr, cb->id << PAGE_SHIFT); cs->jobs_in_queue_cnt[job->hw_queue_id]++; list_add_tail(&job->cs_node, &cs->job_list); /* increment refcount as for external queues we get completion */ cs_get(cs); hl_debugfs_add_job(hdev, job); rc = hl_hw_queue_schedule_cs(cs); if (rc) { if (rc != -EAGAIN) dev_err(hdev->dev, "Failed to submit CS %d.%llu to H/W queues, error %d\n", ctx->asid, cs->sequence, rc); goto free_cs_object; } rc = HL_CS_STATUS_SUCCESS; goto put_cs; free_cs_object: cs_rollback(hdev, cs); *cs_seq = ULLONG_MAX; /* The path below is both for good and erroneous exits */ put_cs: /* We finished with the CS in this function, so put the ref */ cs_put(cs); free_signal_seq_array: if (cs_type == CS_TYPE_WAIT) kfree(signal_seq_arr); free_cs_chunk_array: kfree(cs_chunk_array); out: return rc; } int hl_cs_ioctl(struct hl_fpriv *hpriv, void *data) { struct hl_device *hdev = hpriv->hdev; union hl_cs_args *args = data; struct hl_ctx *ctx = hpriv->ctx; void __user *chunks_execute, *chunks_restore; enum hl_cs_type cs_type; u32 num_chunks_execute, num_chunks_restore, sig_wait_flags; u64 cs_seq = ULONG_MAX; int rc, do_ctx_switch; bool need_soft_reset = false; if (hl_device_disabled_or_in_reset(hdev)) { dev_warn_ratelimited(hdev->dev, "Device is %s. Can't submit new CS\n", atomic_read(&hdev->in_reset) ? "in_reset" : "disabled"); rc = -EBUSY; goto out; } sig_wait_flags = args->in.cs_flags & HL_CS_FLAGS_SIG_WAIT; if (unlikely(sig_wait_flags == HL_CS_FLAGS_SIG_WAIT)) { dev_err(hdev->dev, "Signal and wait CS flags are mutually exclusive, context %d\n", ctx->asid); rc = -EINVAL; goto out; } if (unlikely((sig_wait_flags & HL_CS_FLAGS_SIG_WAIT) && (!hdev->supports_sync_stream))) { dev_err(hdev->dev, "Sync stream CS is not supported\n"); rc = -EINVAL; goto out; } if (args->in.cs_flags & HL_CS_FLAGS_SIGNAL) cs_type = CS_TYPE_SIGNAL; else if (args->in.cs_flags & HL_CS_FLAGS_WAIT) cs_type = CS_TYPE_WAIT; else cs_type = CS_TYPE_DEFAULT; chunks_execute = (void __user *) (uintptr_t) args->in.chunks_execute; num_chunks_execute = args->in.num_chunks_execute; if (cs_type == CS_TYPE_DEFAULT) { if (!num_chunks_execute) { dev_err(hdev->dev, "Got execute CS with 0 chunks, context %d\n", ctx->asid); rc = -EINVAL; goto out; } } else if (num_chunks_execute != 1) { dev_err(hdev->dev, "Sync stream CS mandates one chunk only, context %d\n", ctx->asid); rc = -EINVAL; goto out; } do_ctx_switch = atomic_cmpxchg(&ctx->thread_ctx_switch_token, 1, 0); if (do_ctx_switch || (args->in.cs_flags & HL_CS_FLAGS_FORCE_RESTORE)) { long ret; chunks_restore = (void __user *) (uintptr_t) args->in.chunks_restore; num_chunks_restore = args->in.num_chunks_restore; mutex_lock(&hpriv->restore_phase_mutex); if (do_ctx_switch) { rc = hdev->asic_funcs->context_switch(hdev, ctx->asid); if (rc) { dev_err_ratelimited(hdev->dev, "Failed to switch to context %d, rejecting CS! %d\n", ctx->asid, rc); /* * If we timedout, or if the device is not IDLE * while we want to do context-switch (-EBUSY), * we need to soft-reset because QMAN is * probably stuck. However, we can't call to * reset here directly because of deadlock, so * need to do it at the very end of this * function */ if ((rc == -ETIMEDOUT) || (rc == -EBUSY)) need_soft_reset = true; mutex_unlock(&hpriv->restore_phase_mutex); goto out; } } hdev->asic_funcs->restore_phase_topology(hdev); if (!num_chunks_restore) { dev_dbg(hdev->dev, "Need to run restore phase but restore CS is empty\n"); rc = 0; } else { rc = cs_ioctl_default(hpriv, chunks_restore, num_chunks_restore, &cs_seq); } mutex_unlock(&hpriv->restore_phase_mutex); if (rc) { dev_err(hdev->dev, "Failed to submit restore CS for context %d (%d)\n", ctx->asid, rc); goto out; } /* Need to wait for restore completion before execution phase */ if (num_chunks_restore) { ret = _hl_cs_wait_ioctl(hdev, ctx, jiffies_to_usecs(hdev->timeout_jiffies), cs_seq); if (ret <= 0) { dev_err(hdev->dev, "Restore CS for context %d failed to complete %ld\n", ctx->asid, ret); rc = -ENOEXEC; goto out; } } ctx->thread_ctx_switch_wait_token = 1; } else if (!ctx->thread_ctx_switch_wait_token) { u32 tmp; rc = hl_poll_timeout_memory(hdev, &ctx->thread_ctx_switch_wait_token, tmp, (tmp == 1), 100, jiffies_to_usecs(hdev->timeout_jiffies), false); if (rc == -ETIMEDOUT) { dev_err(hdev->dev, "context switch phase timeout (%d)\n", tmp); goto out; } } if (cs_type == CS_TYPE_DEFAULT) rc = cs_ioctl_default(hpriv, chunks_execute, num_chunks_execute, &cs_seq); else rc = cs_ioctl_signal_wait(hpriv, cs_type, chunks_execute, num_chunks_execute, &cs_seq); out: if (rc != -EAGAIN) { memset(args, 0, sizeof(*args)); args->out.status = rc; args->out.seq = cs_seq; } if (((rc == -ETIMEDOUT) || (rc == -EBUSY)) && (need_soft_reset)) hl_device_reset(hdev, false, false); return rc; } static long _hl_cs_wait_ioctl(struct hl_device *hdev, struct hl_ctx *ctx, u64 timeout_us, u64 seq) { struct dma_fence *fence; unsigned long timeout; long rc; if (timeout_us == MAX_SCHEDULE_TIMEOUT) timeout = timeout_us; else timeout = usecs_to_jiffies(timeout_us); hl_ctx_get(hdev, ctx); fence = hl_ctx_get_fence(ctx, seq); if (IS_ERR(fence)) { rc = PTR_ERR(fence); if (rc == -EINVAL) dev_notice_ratelimited(hdev->dev, "Can't wait on seq %llu because current CS is at seq %llu\n", seq, ctx->cs_sequence); } else if (fence) { rc = dma_fence_wait_timeout(fence, true, timeout); if (fence->error == -ETIMEDOUT) rc = -ETIMEDOUT; else if (fence->error == -EIO) rc = -EIO; dma_fence_put(fence); } else { dev_dbg(hdev->dev, "Can't wait on seq %llu because current CS is at seq %llu (Fence is gone)\n", seq, ctx->cs_sequence); rc = 1; } hl_ctx_put(ctx); return rc; } int hl_cs_wait_ioctl(struct hl_fpriv *hpriv, void *data) { struct hl_device *hdev = hpriv->hdev; union hl_wait_cs_args *args = data; u64 seq = args->in.seq; long rc; rc = _hl_cs_wait_ioctl(hdev, hpriv->ctx, args->in.timeout_us, seq); memset(args, 0, sizeof(*args)); if (rc < 0) { dev_err_ratelimited(hdev->dev, "Error %ld on waiting for CS handle %llu\n", rc, seq); if (rc == -ERESTARTSYS) { args->out.status = HL_WAIT_CS_STATUS_INTERRUPTED; rc = -EINTR; } else if (rc == -ETIMEDOUT) { args->out.status = HL_WAIT_CS_STATUS_TIMEDOUT; } else if (rc == -EIO) { args->out.status = HL_WAIT_CS_STATUS_ABORTED; } return rc; } if (rc == 0) args->out.status = HL_WAIT_CS_STATUS_BUSY; else args->out.status = HL_WAIT_CS_STATUS_COMPLETED; return 0; }
Talon1024/Raze
source/common/engine/namedef.h
<filename>source/common/engine/namedef.h // 'None' must always be the first name. xx(None) xx(Null) xx(_) xx(Super) xx(Object) xx(Actor) xx(Class) xx(Thinker) xx(Untranslated) xx(Doom) xx(Heretic) xx(Hexen) xx(Strife) xx(Raven) // blood spawning xx(Blood) xx(BloodSplatter) xx(AxeBlood) xx(Spray) // Invulnerability types xx(Ghost) xx(Reflective) // Invisibility types xx(Additive) xx(Cumulative) xx(Fuzzy) xx(Opaque) xx(Stencil) xx(AddStencil) // Render styles xx(Normal) xx(SoulTrans) xx(OptFuzzy) xx(Add) xx(Shaded) xx(AddShaded) xx(TranslucentStencil) xx(Shadow) xx(Subtract) xx(Subtractive) xx(FillColor) xx(ColorBlend) xx(ColorAdd) xx(Multiply) // Healingradius types xx(Mana) xx(Armor) // Per-actor sound channels xx(Auto) xx(Weapon) xx(Voice) xx(Item) xx(Body) xx(SoundSlot5) xx(SoundSlot6) xx(SoundSlot7) // Hexen sound sequence names xx(Platform) xx(PlatformMetal) xx(Silence) xx(Lava) xx(Water) xx(Ice) xx(Earth) xx(PlatformMetal2) xx(DoorNormal) xx(DoorHeavy) xx(DoorMetal) xx(DoorCreak) xx(DoorMetal2) xx(Wind) xx(PointPusher) xx(PointPuller) xx(UpperStackLookOnly) xx(LowerStackLookOnly) xx(StackPoint) xx(SkyCamCompat) xx(BasicArmorBonus) xx(BasicArmorPickup) xx(SaveAmount) xx(SavePercent) xx(MaxAbsorb) xx(MaxFullAbsorb) xx(MaxAmount) xx(ActualSaveAmount) xx(ArmorType) xx(HexenArmor) xx(Slots) xx(SlotsIncrement) xx(InterHubAmount) xx(Icon) xx(AltHUDIcon) xx(PickupFlash) xx(BulletPuff) xx(StrifePuff) xx(MaulerPuff) // Special bosses A_BossDeath knows about xx(Fatso) xx(Arachnotron) xx(BaronOfHell) xx(Cyberdemon) xx(SpiderMastermind) xx(Ironlich) xx(Minotaur) xx(Sorcerer2) // Bots check this xx(Megasphere) xx(MegasphereHealth) // Standard player classes xx(DoomPlayer) xx(HereticPlayer) xx(StrifePlayer) xx(FighterPlayer) xx(ClericPlayer) xx(MagePlayer) xx(ChexPlayer) xx(ChickenPlayer) xx(PigPlayer) // Flechette names for the different Hexen player classes xx(ArtiPoisonBag1) xx(ArtiPoisonBag2) xx(ArtiPoisonBag3) // Strife quests xx(QuestItem) xx(Sigil) xx(GiveSigilPiece) xx(SetWeapon) xx(SetSprite) // Armor xx(BasicArmor) // Doom ammo types xx(Clip) xx(PuzzleItem) xx(PuzzleItemNumber) xx(HealthPickup) xx(autousemode) xx(Ammo) xx(WeaponGiver) xx(DehackedPickup) xx(PowerTargeter) xx(PowerInvulnerable) xx(PowerStrength) xx(PowerInvisibility) xx(PowerIronFeet) xx(PowerLightAmp) xx(PowerWeaponLevel2) xx(PowerFlight) xx(PowerSpeed) xx(PowerTorch) xx(PowerHighJump) xx(PowerReflection) xx(PowerDrain) xx(Reflection) xx(CustomInventory) xx(Inventory) xx(StateProvider) xx(CallTryPickup) xx(QuestItem25) xx(QuestItem28) xx(PowerDoubleFiringSpeed) xx(PowerInfiniteAmmo) xx(PowerBuddha) xx(TeleportDest) xx(TeleportDest2) // Standard animator names. xx(Spawn) xx(See) xx(Pain) xx(Melee) xx(Missile) xx(Crash) xx(Death) xx(Raise) xx(Wound) xx(Heal) xx(Crush) xx(Yes) xx(No) xx(Greetings) xx(Idle) xx(GenericFreezeDeath) xx(GenericCrush) // Bounce state names xx(Bounce) xx(Wall) xx(Floor) xx(Ceiling) xx(Creature) // Compatible death names for the decorate parser. xx(XDeath) xx(Burn) //xx(Ice) // already defined above xx(Disintegrate) xx(Smash) // Weapon animator names. xx(Select) xx(Deselect) xx(DeadLowered) xx(Ready) xx(Fire) xx(Hold) xx(AltFire) xx(AltHold) xx(Flash) xx(AltFlash) xx(Reload) xx(Zoom) xx(User1) xx(User2) xx(User3) xx(User4) // State names used by ASwitchableDecoration xx(Active) xx(Inactive) // State names used by ACustomInventory xx(Pickup) xx(Use) xx(Drop) xx(Fist) //xx(Berserk) xx(Chainsaw) xx(Pistol) xx(Shotgun) xx(SSG) xx(Chaingun) xx(Rocket) xx(Plasma) xx(BFG) //xx(Railgun) xx(Dagger) // Damage types //xx(Fire) already defined above //xx(Ice) //xx(Disintegrate) xx(Drowning) xx(Slime) //xx(Crush) xx(Telefrag) xx(Falling) xx(Suicide) xx(Exit) xx(Railgun) xx(Poison) xx(Electric) xx(BFGSplash) xx(DrainLife) // A weapon like the Sigil that drains your life away. xx(Massacre) // For death by a cheater! //(Melee) already defined above, so don't define it again xx(InstantDeath) // Strife "instant death" xx(PoisonCloud) // makes monsters howl. xx(Hitscan) // for normal guns and the like xx(Quake) // Special death name for getting killed excessively. Could be used as // a damage type if you wanted to force an extreme death. xx(Extreme) xx(MDK) xx(Cast) // 'damage type' for the cast call // Special names for thingdef_exp.cpp xx(Random) xx(FRandom) xx(Random2) xx(RandomPick) xx(FRandomPick) xx(SetRandomSeed) xx(BuiltinRandomSeed) xx(BuiltinNew) xx(GetClass) xx(GetParentClass) xx(GetClassName) xx(GetDefaultByType) xx(Exp) xx(Log10) xx(Ceil) xx(ACos) xx(ASin) xx(ATan) xx(Cos) xx(Sin) xx(Tan) xx(CosH) xx(SinH) xx(TanH) xx(Round) xx(ATan2) xx(VectorAngle) xx(New) xx(Alpha) xx(Angle) xx(Args) xx(CeilingZ) xx(FloorZ) xx(Health) xx(Pitch) xx(SpecialName) xx(Special) xx(TID) xx(TIDtoHate) xx(WaterLevel) xx(X) xx(Y) xx(Z) xx(XY) xx(MomX) xx(MomY) xx(MomZ) xx(Threshold) xx(DefThreshold) xx(Abs) xx(TeleportSpecial) xx(Teleport) xx(ACS_NamedExecuteWithResult) xx(CallACS) xx(Sqrt) xx(CheckClass) xx(IsPointerEqual) xx(Pick) xx(Mass) xx(VelX) xx(VelY) xx(VelZ) xx(Accuracy) xx(Stamina) xx(Radius) xx(ReactionTime) xx(MeleeRange) xx(Speed) xx(FastSpeed) xx(HowlSound) xx(Clamp) xx(VisibleStartAngle) xx(VisibleStartPitch) xx(VisibleEndAngle) xx(VisibleEndPitch) xx(Format) xx(PickupMsg) xx(Respawnable) xx(ExplosionDamage) xx(ExplosionRadius) xx(DontHurtShooter) // Various actor names which are used internally xx(MapSpot) xx(PatrolPoint) xx(PatrolSpecial) xx(Communicator) xx(PowerScanner) // Textmap properties //xx(X) //xx(Y) xx(ZFloor) xx(ZCeiling) xx(Height) //xx(Tid) //xx(Angle) xx(Type) //xx(Special) xx(Arg0) xx(Arg1) xx(Arg2) xx(Arg3) xx(Arg4) xx(Arg0Str) xx(Arg1Str) xx(Id) xx(MoreIds) xx(V1) xx(V2) xx(Sidefront) xx(Sideback) xx(Offsetx) xx(Offsety) xx(Texturetop) xx(Texturebottom) xx(Texturemiddle) xx(Sector) xx(Heightfloor) xx(Heightceiling) xx(Lightlevel) xx(Texturefloor) xx(Textureceiling) xx(Nodecals) xx(Skill1) xx(Skill2) xx(Skill3) xx(Skill4) xx(Skill5) xx(Skill6) xx(Skill7) xx(Skill8) xx(Skill9) xx(Skill10) xx(Skill11) xx(Skill12) xx(Skill13) xx(Skill14) xx(Skill15) xx(Skill16) xx(Medium) xx(Hard) xx(Ambush) xx(Dormant) xx(Class0) xx(Class1) xx(Class2) xx(Class3) xx(Class4) xx(Class5) xx(Class6) xx(Class7) xx(Class8) xx(Class9) xx(Class10) xx(Class11) xx(Class12) xx(Class13) xx(Class14) xx(Class15) xx(Class16) xx(Single) xx(Coop) xx(Dm) xx(Translucent) xx(Invisible) xx(Friend) xx(Strifeally) xx(Standing) xx(Countsecret) xx(NoCount) xx(Score) xx(Roll) xx(Scale) xx(ScaleX) xx(ScaleY) xx(FriendlySeeBlocks) xx(Floatbobphase) xx(Floatbobstrength) xx(Target) xx(Master) xx(Tracer) xx(Blocking) xx(Blockmonsters) xx(Twosided) xx(Dontpegtop) xx(Dontpegbottom) xx(Secret) xx(Blocksound) xx(Dontdraw) xx(Mapped) xx(Monsteractivate) xx(Blockplayers) xx(Blockeverything) xx(Zoneboundary) xx(Jumpover) xx(Blockfloaters) xx(Clipmidtex) xx(Wrapmidtex) xx(Midtex3d) xx(Checkswitchrange) xx(Firstsideonly) xx(Transparent) xx(Passuse) xx(Repeatspecial) xx(Conversation) xx(Locknumber) xx(Midtex3dimpassible) xx(Revealed) xx(AutomapStyle) xx(DrawFullHeight) xx(Playercross) xx(Playeruse) xx(Playeruseback) xx(Monstercross) xx(Impact) xx(Playerpush) xx(Missilecross) xx(Anycross) xx(Monsteruse) xx(Monsterpush) xx(ZDoom) xx(ZDoomTranslated) xx(Vavoom) xx(GZDoom) xx(Xpanningfloor) xx(Ypanningfloor) xx(Xpanningceiling) xx(Ypanningceiling) xx(Xscalefloor) xx(Yscalefloor) xx(Xscaleceiling) xx(Yscaleceiling) xx(Rotationfloor) xx(Rotationceiling) xx(Lightfloor) xx(Lightceiling) xx(Lightfloorabsolute) xx(Lightceilingabsolute) xx(Gravity) xx(Lightcolor) xx(Fadecolor) xx(Color_Floor) xx(Color_Ceiling) xx(Color_Walltop) xx(Color_Wallbottom) xx(Color_Sprites) xx(ColorAdd_Floor) xx(ColorAdd_Ceiling) xx(ColorAdd_Sprites) xx(ColorAdd_Walls) xx(NoSkyWalls) xx(Desaturation) xx(SoundSequence) xx(Silent) xx(Nofallingdamage) xx(Dropactors) xx(NoRespawn) xx(Alphafloor) xx(Alphaceiling) xx(Renderstylefloor) xx(Renderstyleceiling) xx(Waterzone) xx(portal_ceil_blocksound) xx(portal_ceil_disabled) xx(portal_ceil_nopass) xx(portal_ceil_norender) xx(portal_ceil_overlaytype) xx(portal_ceil_useglobaltex) xx(portal_floor_blocksound) xx(portal_floor_disabled) xx(portal_floor_nopass) xx(portal_floor_norender) xx(portal_floor_overlaytype) xx(portal_floor_useglobaltex) xx(scroll_ceil_x) xx(scroll_ceil_y) xx(scroll_ceil_type) xx(scroll_floor_x) xx(scroll_floor_y) xx(scroll_floor_type) xx(offsetx_top) xx(offsety_top) xx(offsetx_mid) xx(offsety_mid) xx(offsetx_bottom) xx(offsety_bottom) xx(scalex_top) xx(scaley_top) xx(scalex_mid) xx(scaley_mid) xx(scalex_bottom) xx(scaley_bottom) xx(light) xx(lightabsolute) xx(lightfog) xx(nofakecontrast) xx(smoothlighting) xx(blockprojectiles) xx(blockuse) xx(hidden) xx(blocksight) xx(blockhitscan) xx(nogradient_top) xx(flipgradient_top) xx(clampgradient_top) xx(useowncolors_top) xx(uppercolor_top) xx(lowercolor_top) xx(nogradient_mid) xx(flipgradient_mid) xx(clampgradient_mid) xx(useowncolors_mid) xx(uppercolor_mid) xx(lowercolor_mid) xx(nogradient_bottom) xx(flipgradient_bottom) xx(clampgradient_bottom) xx(useowncolors_bottom) xx(uppercolor_bottom) xx(lowercolor_bottom) xx(useowncoloradd_top) xx(coloradd_top) xx(useowncoloradd_mid) xx(coloradd_mid) xx(useowncoloradd_bottom) xx(coloradd_bottom) xx(colorization_top) xx(colorization_mid) xx(colorization_bottom) xx(colorization_floor) xx(colorization_ceiling) xx(Renderstyle) xx(ceilingplane_a) xx(ceilingplane_b) xx(ceilingplane_c) xx(ceilingplane_d) xx(floorplane_a) xx(floorplane_b) xx(floorplane_c) xx(floorplane_d) xx(damageamount) xx(damagetype) xx(damageinterval) xx(leakiness) xx(damageterraineffect) xx(damagehazard) xx(floorterrain) xx(ceilingterrain) xx(floor_reflect) xx(ceiling_reflect) xx(floorglowcolor) xx(floorglowheight) xx(ceilingglowcolor) xx(ceilingglowheight) xx(fogdensity) xx(Static) xx(Staticconst) xx(DeathmatchStatusScreen) xx(CoopStatusScreen) xx(RavenStatusScreen) xx(StatusbarWidget) xx(StatusbarHead) xx(StatusbarCondition) xx(Next) xx(Prev) xx(Children) xx(Owner) xx(FlameThrower) xx(HealthFloor) xx(HealthCeiling) xx(Health3D) xx(DamageSpecial) xx(DeathSpecial) xx(HealthFloorGroup) xx(HealthCeilingGroup) xx(Health3DGroup) xx(HealthGroup) // USDF keywords xx(Amount) xx(Text) xx(Displaycost) xx(Yesmessage) xx(Nomessage) xx(Log) xx(Giveitem) xx(Nextpage) xx(Closedialog) xx(Cost) xx(Page) xx(Count) xx(Name) xx(Panel) xx(Dialog) xx(Ifitem) xx(Choice) xx(Link) xx(Goodbye) xx(Require) xx(Exclude) xx(Userstring) xx(Sky) xx(Pagename) // Special menus xx(Mainmenu) xx(MainmenuTextOnly) xx(Episodemenu) xx(Playerclassmenu) xx(HexenDefaultPlayerclassmenu) xx(Skillmenu) xx(Startgame) xx(StartgameConfirm) xx(StartgameConfirmed) xx(Loadgamemenu) xx(Savegamemenu) xx(Readthismenu) xx(Optionsmenu) xx(Quitmenu) xx(Savemenu) xx(Playermenu) xx(EndGameMenu) xx(IngameMenu) xx(HelpMenu) xx(SoundMenu) xx(ConfirmPlayerReset) xx(HuntMenu) xx(WeaponMenu) xx(TargetMenu) xx(UsermapMenu) xx(EngineCredits) xx(EngineCredits2) xx(CreditsMenu) xx(MultiMenu) xx(CustomGameMenu) xx(CustomSubMenu1) xx(CustomSubMenu2) xx(CustomSubMenu3) xx(CustomSubMenu4) xx(CustomSubMenu5) xx(CustomSubMenu6) xx(CustomSubMenu7) xx(Playerbox) xx(Team) xx(Color) xx(Red) xx(Green) xx(Blue) xx(Skin) xx(Gender) xx(Autoaim) xx(Switch) xx(Playerdisplay) xx(Controlmessage) xx(Crosshairs) xx(Colorpickermenu) xx(Mididevices) xx(Aldevices) xx(Alresamplers) xx(CustomizeControls) xx(MessageOptions) xx(AutomapOptions) xx(ScoreboardOptions) xx(MapColorMenu) xx(GameplayOptions) xx(CompatibilityOptions) xx(MouseOptions) xx(JoystickOptions) xx(SoundOptions) xx(AdvSoundOptions) xx(ModReplayerOptions) xx(VideoOptions) xx(JoystickConfigMenu) xx(VMEnterText) xx(VMTestText) xx(VideoModeMenu) xx(res_0) xx(res_1) xx(res_2) xx(res_3) xx(res_4) xx(res_5) xx(res_6) xx(res_7) xx(res_8) xx(res_9) xx(AlwaysRun) // end sequences xx(Inter_Chess) xx(Inter_Strife) xx(Inter_Strife_Good) xx(Inter_Strife_Sad) xx(Inter_Strife_Bad) xx(Inter_Strife_Lose) xx(Inter_Strife_MAP03) xx(Inter_Strife_MAP10) xx(Multiplayer) // more stuff xx(ColorSet) xx(NeverSwitchOnPickup) xx(MoveBob) xx(StillBob) xx(ClassicFlight) xx(WBobSpeed) xx(WBobFire) xx(PlayerClass) xx(MonsterClass) xx(MorphedMonster) xx(Wi_NoAutostartMap) xx(Duration) xx(MorphStyle) xx(MorphFlash) xx(UnMorphFlash) xx(Powerup) xx(EffectTics) xx(PowerupGiver) xx(BlendColor) xx(Strength) xx(Mode) xx(PowerupType) xx(PlayerPawn) xx(Key) // Decorate compatibility functions xx(BuiltinTypeCheck) xx(BuiltinRandom) xx(BuiltinRandom2) xx(BuiltinFRandom) xx(BuiltinCallLineSpecial) xx(BuiltinNameToClass) xx(BuiltinFindMultiNameState) xx(BuiltinFindSingleNameState) xx(BuiltinHandleRuntimeState) xx(BuiltinGetDefault) xx(BuiltinClassCast) xx(BuiltinFormat) xx(Damage) xx(Noattack) // basic type names xx(Default) xx(sByte) xx(Byte) xx(Short) xx(uShort) xx(Int) xx(uInt) xx(Bool) xx(uint8) xx(int8) xx(uint16) xx(int16) xx(Float) xx(Float32) xx(Float64) xx(Double) xx(String) xx(Vector) xx(Map) xx(Array) xx(Include) xx(Sound) xx(State) xx(Fixed) xx(Vector2) xx(Vector3) xx(let) xx(Min) xx(Max) xx(Min_Normal) xx(Min_Denormal) xx(Epsilon) xx(NaN) xx(Infinity) xx(Dig) xx(Min_Exp) xx(Max_Exp) xx(Mant_Dig) xx(Min_10_Exp) xx(Max_10_Exp) // implicit function parameters xx(self) xx(invoker) xx(stateinfo) xx(__decorate_internal_int__) xx(__decorate_internal_bool__) xx(__decorate_internal_float__) xx(ResolveState) xx(DamageFunction) xx(Length) xx(Unit) xx(Size) xx(Push) xx(Insert) xx(Copy) xx(Move) xx(Voidptr) xx(StateLabel) xx(SpriteID) xx(TextureID) xx(Overlay) xx(IsValid) xx(IsNull) xx(Exists) xx(SetInvalid) xx(SetNull) xx(A_Punch) xx(A_FirePistol) xx(A_FireShotgun) xx(A_FireShotgun2) xx(A_FireCGun) xx(A_FireMissile) xx(A_Saw) xx(A_FirePlasma) xx(A_FireBFG) xx(A_FireOldBFG) xx(A_FireRailgun) // color channels xx(a) xx(r) xx(g) xx(b) // Special translation names xx(RainPillar1) xx(RainPillar2) xx(RainPillar3) xx(RainPillar4) xx(RainPillar5) xx(RainPillar6) xx(RainPillar7) xx(RainPillar8) xx(Player1) xx(Player2) xx(Player3) xx(Player4) xx(Player5) xx(Player6) xx(Player7) xx(Player8) xx(PlayerChunk) xx(RestrictedToPlayerClass) xx(ForbiddenToPlayerClass) xx(Prototype) xx(Void) xx(Label) xx(Pointer) xx(Enum) xx(StaticArray) xx(DynArray) xx(Struct) xx(ReflectType) xx(MessageBoxMenu) xx(Both) xx(Physical) xx(Visual) xx(OptionMenuItemSubmenu) xx(OptionMenuItemCommand) xx(OptionMenuItemControlBase) xx(OptionMenuItemOptionBase) xx(OptionMenuSliderBase) xx(OptionMenuFieldBase) xx(OptionMenuItemColorPicker) xx(OptionMenuItemStaticText) xx(OptionMenuItemStaticTextSwitchable) // blacklisted former CVARs xx(snd_waterlp) xx(snd_output) xx(snd_output_format) xx(snd_speakermode) xx(snd_resampler) // ScriptUtil entry points xx(ScriptUtil) xx(SetMarineWeapon) xx(SetMarineSprite) xx(GiveInventory) xx(TakeInventory) xx(ClearInventory) // Weapon member fields that need direct access xx(Ammo1) xx(Ammo2) xx(AmmoType1) xx(AmmoType2) xx(AmmoGive1) xx(AmmoGive2) xx(AmmoUse1) xx(SisterWeapon) xx(BobStyle) xx(Kickback) xx(MinSelAmmo1) xx(bDehAmmo) xx(FOVScale) xx(LookScale) xx(YAdjust) xx(Crosshair) xx(WeaponFlags) xx(DropTime) xx(PickupSound) // PlayerPawn member fields xx(ColorRangeStart) xx(ColorRangeEnd) xx(InvFirst) xx(ForwardMove1) xx(ForwardMove2) xx(SideMove1) xx(SideMove2) xx(Face) xx(Slot) xx(SoundClass) xx(ViewBob) xx(DamageFade) xx(MaxHealth) xx(crouchsprite) xx(UseRange) xx(AttackZOffset) xx(SpawnMask) xx(ScoreIcon) xx(ViewHeight) xx(FallingScreamMinSpeed) xx(FallingScreamMaxSpeed) xx(GruntSpeed) xx(JumpZ) xx(MugShotMaxHealth) xx(BonusHealth) xx(PlayerFlags) xx(InvSel) xx(FullHeight) xx(BlueCard) xx(YellowCard) xx(RedCard) xx(BlueSkull) xx(YellowSkull) xx(RedSkull) xx(DynamicLight) xx(SpotInnerAngle) xx(SpotOuterAngle) xx(lightflags) xx(lighttype) xx(InternalDynamicLight) xx(_a_chase_default) xx(MapMarker) xx(Spawn2) xx(LevelLocals) xx(Level) xx(PlayerTeam) xx(PlayerColors) xx(PlayerSkin) xx(NewPlayerMenu) xx(AltHud)
WallaceLiu/distributed-realtime-capfaiss
core/coordinate/MyScheduler.py
<filename>core/coordinate/MyScheduler.py # -*- coding:utf-8 -*- import logging class MyScheduler(object): def __init__(self): pass def init_scheduler(self): logging.info('########## start scheduler ############') def stop_scheduler(self): logging.info('########## stop scheduler ############')
Chaosvex/HAC2
src/hac/OpticBezier.h
<reponame>Chaosvex/HAC2<gh_stars>10-100 #pragma once namespace Optic { class OpticBezier { double x1, y1, x2, y2; double getTForX(double aX); double getSlope(double aT, double aA1, double aA2); double A(double aA1, double aA2); double B(double aA1, double aA2); double C(double aA1); double calculate(double aT, double aA1, double aA2); public: OpticBezier(double x1, double y1, double x2, double y2); double get(double t); }; }
tinyzimmer/k3p
pkg/types/cluster.go
<filename>pkg/types/cluster.go<gh_stars>10-100 package types // NodeConnectOptions are options for configuring a connection to a remote node. type NodeConnectOptions struct { // The user to attempt to SSH into the remote node as. SSHUser string // A password to use for SSH authentication. SSHPassword string // The path to the key to use for SSH authentication. SSHKeyFile string // The port to use for the SSH connection SSHPort int // The address of the new node. Address string } // AddNodeOptions represents options passed to the AddNode operation. type AddNodeOptions struct { // Options for remote connections *NodeConnectOptions // The role to assign the new node. NodeRole K3sRole } // RemoveNodeOptions are options passed to a RemoveNode operation (not implemented). type RemoveNodeOptions struct { // Options for remote connections *NodeConnectOptions // Attempt to remote into the system and uninstall k3s Uninstall bool // The name of the node to remove Name string // The IP address of the node to remove IPAddress string } // ClusterManager is an interface for managing the nodes in a k3s cluster. type ClusterManager interface { // AddNode should add a new node to the k3s cluster. AddNode(Node, *AddNodeOptions) error // RemoveNode should drain and remove the given node from the k3s cluster. // If NodeConnectOptions are not nil and Uninstall is true, then k3s and // all of its assets should be completely removed from the system. (not implemented) RemoveNode(*RemoveNodeOptions) error }
AleksandrSidorov/react-fb-chat
app/components/ContactInfoLink/index.js
/** * * ContactInfoHomepage * */ import React, { PropTypes } from 'react'; import Wrapper from './Wrapper' import Header from './Header' import Link from './Link' function ContactInfoLink(props) { return ( <Wrapper> <Header>Profile Link</Header> <Link href={props.link} target="_blank">{props.link}</Link> </Wrapper> ); } ContactInfoLink.propTypes = { link: PropTypes.string }; export default ContactInfoLink;
swedenconnect/tsl-trust
sigval-webapp/src/main/java/se/tillvaxtverket/ttsigvalws/ttwssigvalidation/sigVerify/XmlSigVerifier.java
/* * Copyright 2017 Swedish E-identification Board (E-legitimationsnämnden) * * 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, see <http://www.gnu.org/licenses/>. */ package se.tillvaxtverket.ttsigvalws.ttwssigvalidation.sigVerify; import com.aaasec.lib.crypto.xml.SigVerifyResult; import com.aaasec.lib.crypto.xml.XMLSign; import com.aaasec.lib.crypto.xml.XmlBeansUtil; import com.aaasec.lib.crypto.xml.XmlUtils; import iaik.x509.X509Certificate; import iaik.x509.extensions.qualified.QCStatements; import iaik.x509.extensions.qualified.structures.QCStatement; import iaik.x509.extensions.qualified.structures.etsi.QcEuCompliance; import iaik.x509.extensions.qualified.structures.etsi.QcEuSSCD; import java.security.KeyStore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.util.encoders.Base64; import org.w3.x2000.x09.xmldsig.SignatureDocument; import org.w3.x2000.x09.xmldsig.SignatureType; import org.w3.x2000.x09.xmldsig.SignedInfoType; import org.w3c.dom.Document; import org.w3c.dom.Node; import se.tillvaxtverket.tsltrust.common.iaik.KsCertFactory; import se.tillvaxtverket.tsltrust.common.utils.general.Algorithms; import se.tillvaxtverket.ttsigvalws.ttwssigvalidation.models.SigValidationBaseModel; import se.tillvaxtverket.ttsigvalws.ttwssigvalidation.models.SigValidationModel; import se.tillvaxtverket.ttsigvalws.ttwssigvalidation.sigVerify.context.SignatureValidationContext; import se.tillvaxtverket.ttsigvalws.ttwssigvalidation.sigVerify.context.TimeStampContext; import se.tillvaxtverket.ttsigvalws.ttwssigvalidation.statusCheck.CRLChecker; /** * Verifier of XML signed documents */ public class XmlSigVerifier extends SigVerifier { public XmlSigVerifier(SigValidationModel sigModel) { this.model = sigModel; } @Override protected void getSignatureContext() { SigValidationBaseModel basemodel = model.getBaseModel(); CRLChecker crlCache = basemodel.getCrlCache(); KeyStore keyStore = basemodel.getTrustStore().getKeyStore(model.getPolicyName()); boolean checkOcspAndCrl = model.isCheckOcspAndCrl(); boolean prefOcsp = model.isPrefSpeed(); crlCache.clearLog(); List<SignatureValidationContext> svcList = new ArrayList<SignatureValidationContext>(); CertChainVerifier certChainVerifier = new CertChainVerifier(model); if (!certChainVerifier.isInitialized()) { errClose(); return; } certChainVerifier.setCheckAllRev(checkOcspAndCrl); certChainVerifier.setPreferSpeed(prefOcsp); byte[] signedData = model.getSigDocument().getDocBytes(); Document signedDoc = null; try { signedDoc = XmlUtils.getDocument(signedData); } catch (Exception ex) { Logger.getLogger(XmlSigVerifier.class.getName()).log(Level.SEVERE, null, ex); } if (signedDoc == null) { errClose(); model.setSignVerificationComplete(false); } SigVerifyResult sigResults = XMLSign.verifySignature(signedDoc); List<SigVerifyResult.IndivdualSignatureResult> resultList = sigResults.resultList; int sigIndex = 0; for (SigVerifyResult.IndivdualSignatureResult result : resultList) { SignatureValidationContext svc = new SignatureValidationContext(); svc.setSignatureName(getSigName(sigIndex++)); svc.setCoversDoc(true); svc.setRevision(-1); svc.setRevisions(-1); String sigAlgName = getSigAlgXmlName(result.thisSignatureNode); String sigAlgOid = getSigAlgOid(sigAlgName); if (sigAlgOid == null) { svc.setSigValidationError(new String[]{"Unknown algorithm"}); } svc.setSignaturePkAlgOID(null); svc.setSignatureAlgOID(new ASN1ObjectIdentifier(sigAlgOid)); svc.setSignatureHashAlgOID(getHash(sigAlgName)); svc.setTimestamped(false); TimeStampContext tsCont = null; svc.setTstContext(tsCont); try { svc.setProvidedChain(getCertList(result)); // svc.setProvidedChain(KsCertFactory.getIaikCertList(verifySignature.keyInfo.getCertificates())); svc.setSignCert(KsCertFactory.getIaikCert(result.thisCert)); // modified code boolean signatureValid = result.thisValid; svc.setSigValid(signatureValid); svc.setDigestValid(signatureValid); //if (svc.isSigValid()) { svc.setSignCertValidation(certChainVerifier.verifyChain(svc.getProvidedChain())); // Require that chain validation succeeds. svc.setSigChainVerified(svc.getSignCertValidation().isSigChainVerified()); } catch (Exception ex) { svc.setDigestValid(false); } //QC compliance test qcComplianceTest(svc); //Store result and move on to next signature svcList.add(svc); } model.setSignVerificationComplete(true); model.setSignatureContexts(svcList); setChanged(); if (running) { notifyObservers(COMPLETE); } else { notifyObservers(RETURN_FROM_ABORT); } } private ASN1ObjectIdentifier getHash(String sigAlgName) { try { HashMap<String, String> algoHashMap = Algorithms.xmlHashOids; String hashOid = algoHashMap.get(sigAlgName); return new ASN1ObjectIdentifier(hashOid); } catch (Exception ex) { return null; } } private void qcComplianceTest(SignatureValidationContext svc) { svc.setQualifiedCertificate(false); svc.setSscd(false); try { X509Certificate cert = svc.getSignCertValidation().getChain().get(0); QCStatements qcsExtension = (QCStatements) cert.getExtension(QCStatements.oid); QCStatement[] statements = qcsExtension.getQCStatements(); for (QCStatement qcs : statements) { if (qcs.getStatementID().equals(QcEuCompliance.statementID)) { svc.setQualifiedCertificate(true); } if (qcs.getStatementID().equals(QcEuSSCD.statementID)) { svc.setSscd(true); } } } catch (Exception ex) { } } private String getSigName(int sigIndex) { return textBundle.getString("signature") + " " + String.valueOf(sigIndex + 1); } private String getSigAlgOid(String algorithm) { try { return Algorithms.xmlAlgIds.get(algorithm); } catch (Exception ex) { return null; } } private String getSigAlgXmlName(Node sigNode) { String sigAlgOid; try { SignatureType sig = SignatureDocument.Factory.parse(sigNode).getSignature(); SignedInfoType signedInfo = sig.getSignedInfo(); String algorithm = signedInfo.getSignatureMethod().getAlgorithm(); return algorithm; } catch (Exception ex) { return null; } } private List<X509Certificate> getCertList(SigVerifyResult.IndivdualSignatureResult result) { List<X509Certificate> certList = new ArrayList<X509Certificate>(); List<byte[]> certByteList = result.getCertList(); for (byte[] certBytes : certByteList) { X509Certificate iaikCert = KsCertFactory.getIaikCert(certBytes); if (iaikCert != null) { certList.add(iaikCert); } } return certList; } }
wangwangok/leetcode
nc3_detectCycle.cpp
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: /// 返回相遇点,如果不形成环路,那么返回nullptr ListNode* isCycle(ListNode *head) { ListNode *lead = head, *tail =head; ListNode *result = nullptr; while (lead && tail) { if (lead->next) { lead = lead->next->next; tail = tail->next; } else { lead = nullptr; } if (lead == tail) { result = lead; break; } } return result; } ListNode *detectCycle(ListNode *head) { if (head == nullptr) return nullptr; ListNode *equal_ptr = isCycle(head); if (equal_ptr == nullptr) { return equal_ptr; } /* |-----x------|----------m ○ → ○ → ○ → ○ → ○ → ○ → ○ → ○ → ○ → ○ | | ↑ ↓ | | ○ ○ | | ↑ ↓ | | ○ ← ○ ← ● ← ○ ← ○ | n -----|------ ●:表示相遇点 周长为c,快指针在环内跑了p圈,慢指针在环内跑了q圈。快指针的速度是慢指针速度的2倍,那么相同时间,快指针行进的距离是慢指针的两倍:则有如下公式: x+m+p*c = 2(x+m+q*c); x+m+p*c = 2x+2m+2*q*c; x = c*(p-2q-1)+n 也就是说起点距离环入口点的距离为c*(p-2q-1)+n。此时在点处放置一个指针ptr1,在相遇点放置一个指针ptr2,它们两个都是一次移动一个结点: 当ptr1移动c*(p-2q-1)长度时,那么距离环入口为n;同样的对于ptr2来说,移动c*(p-2q-1)距离,也依然在相遇点不变,距离环入口点长度也是n。 因此我们知道当ptr1==ptr2时,即是环入口点。 */ ListNode *ptr1 = head, *ptr2 = equal_ptr; ListNode *result = nullptr; while (ptr1 && ptr2) { if (ptr1 == ptr2) { result = ptr1; break; } ptr1 = ptr1->next; ptr2 = ptr2->next; } return result; } }; int main(int argc, const char *argv[]) { Solution s; ListNode *node1 = new ListNode(1); ListNode *node2 = new ListNode(2); node2->next=node1; ListNode *node3 = new ListNode(3); node3->next=node2; ListNode *node4 = new ListNode(4); node4->next=node3; ListNode *node5 = new ListNode(5); ListNode *node6 = new ListNode(6); node5->next=node4; node6->next=node5; // node1->next=node4; ListNode *result = s.detectCycle(node4); cout<<result->val<<endl; return 0; }
hmcts/wa-monitor-unconfigured-tasks-service
src/main/java/uk/gov/hmcts/reform/wataskmonitor/domain/camunda/CamundaTask.java
<filename>src/main/java/uk/gov/hmcts/reform/wataskmonitor/domain/camunda/CamundaTask.java<gh_stars>0 package uk.gov.hmcts.reform.wataskmonitor.domain.camunda; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.ToString; import org.springframework.format.annotation.DateTimeFormat; import java.time.ZonedDateTime; import static uk.gov.hmcts.reform.wataskmonitor.domain.camunda.CamundaTime.CAMUNDA_DATA_TIME_FORMAT; @ToString @EqualsAndHashCode @Getter @JsonIgnoreProperties(ignoreUnknown = true) public class CamundaTask { private final String id; private final String name; private final String processInstanceId; private final String assignee; @DateTimeFormat(iso = DateTimeFormat.ISO.TIME) @JsonFormat(pattern = CAMUNDA_DATA_TIME_FORMAT) private final ZonedDateTime created; @DateTimeFormat(iso = DateTimeFormat.ISO.TIME) @JsonFormat(pattern = CAMUNDA_DATA_TIME_FORMAT) private final ZonedDateTime due; private final String description; private final String owner; private final String formKey; public CamundaTask(String id, String name, String processInstanceId) { this(id, name, processInstanceId, null, null, null, null, null, null); } public CamundaTask(@JsonProperty("id") String id, @JsonProperty("name") String name, @JsonProperty("processInstanceId") String processInstanceId, @JsonProperty("assignee") String assignee, @JsonProperty("created") ZonedDateTime created, @JsonProperty("due") ZonedDateTime due, @JsonProperty("description") String description, @JsonProperty("owner") String owner, @JsonProperty("formKey") String formKey ) { this.id = id; this.name = name; this.assignee = assignee; this.created = created; this.due = due; this.description = description; this.owner = owner; this.formKey = formKey; this.processInstanceId = processInstanceId; } public String getId() { return id; } public String getName() { return name; } public String getAssignee() { return assignee; } public ZonedDateTime getCreated() { return created; } public ZonedDateTime getDue() { return due; } public String getDescription() { return description; } public String getOwner() { return owner; } public String getFormKey() { return formKey; } public String getProcessInstanceId() { return processInstanceId; } }
nlebas/tiles-autotag
tiles-autotag-core/src/main/java/org/apache/tiles/autotag/generate/BasicTemplateGenerator.java
/* * $Id$ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.tiles.autotag.generate; import java.util.List; import java.util.Map; import org.apache.tiles.autotag.core.OutputLocator; import org.apache.tiles.autotag.model.TemplateClass; import org.apache.tiles.autotag.model.TemplateSuite; /** * The basic template generator. Use {@link TemplateGeneratorBuilder} to * create instances of this class. * * @version $Rev$ $Date$ */ class BasicTemplateGenerator implements TemplateGenerator { /** * The template suite generators. */ private List<TSGeneratorDirectoryPair> templateSuiteGenerators; /** * The template class generators. */ private List<TCGeneratorDirectoryPair> templateClassGenerators; /** * Indicates that this generator generates resources. */ private boolean generatingResources = false; /** * Indicates that this generator generates classes. */ private boolean generatingClasses = false; /** * Constructor. * * @param templateSuiteGenerators The template suite generators. * @param templateClassGenerators The template class generators. * @param generatingClasses Indicates that this generator generates classes. * @param generatingResources Indicates that this generator generates resources. */ BasicTemplateGenerator( List<TSGeneratorDirectoryPair> templateSuiteGenerators, List<TCGeneratorDirectoryPair> templateClassGenerators, boolean generatingClasses, boolean generatingResources) { this.templateSuiteGenerators = templateSuiteGenerators; this.templateClassGenerators = templateClassGenerators; this.generatingClasses = generatingClasses; this.generatingResources = generatingResources; } @Override public void generate(String packageName, TemplateSuite suite, Map<String, String> parameters, String runtimeClass, String requestClass) { for (TSGeneratorDirectoryPair pair : templateSuiteGenerators) { pair.getGenerator().generate(pair.getOutputLocator(), packageName, suite, parameters); } for (TemplateClass templateClass : suite.getTemplateClasses()) { for (TCGeneratorDirectoryPair pair : templateClassGenerators) { pair.getGenerator().generate(pair.getOutputLocator(), packageName, suite, templateClass, parameters, runtimeClass, requestClass); } } } /** * A pair of a template suite generator and a directory. * * @version $Rev$ $Date$ */ static class TSGeneratorDirectoryPair { /** * The directory where files are generated. */ private OutputLocator outputLocator; /** * The generator. */ private TemplateSuiteGenerator generator; /** * Constructor. * * @param directory The directory where files are generated. * @param generator The generator. */ public TSGeneratorDirectoryPair(OutputLocator outputLocator, TemplateSuiteGenerator generator) { this.outputLocator = outputLocator; this.generator = generator; } /** * Returns the directory where files are generated. * * @return The directory where files are generated. */ public OutputLocator getOutputLocator() { return outputLocator; } /** * Returns the generator. * * @return The generator. */ public TemplateSuiteGenerator getGenerator() { return generator; } } /** * A pair of a template class generator and a directory. * * @version $Rev$ $Date$ */ static class TCGeneratorDirectoryPair { /** * The directory where files are generated. */ private OutputLocator outputLocator; /** * The generator. */ private TemplateClassGenerator generator; /** * Constructor. * * @param directory The directory where files are generated. * @param generator The generator. */ public TCGeneratorDirectoryPair(OutputLocator outputLocator, TemplateClassGenerator generator) { this.outputLocator = outputLocator; this.generator = generator; } /** * Returns the directory where files are generated. * * @return The directory where files are generated. */ public OutputLocator getOutputLocator() { return outputLocator; } /** * Returns the generator. * * @return The generator. */ public TemplateClassGenerator getGenerator() { return generator; } } @Override public boolean isGeneratingResources() { return generatingResources; } @Override public boolean isGeneratingClasses() { return generatingClasses; } }
tadvi/uva
UVa 12166 - Equilibrium Mobile/sample/12166 - Equilibrium Mobile.cpp
<gh_stars>1-10 #include <stdio.h> #include <string.h> #include <vector> #include <map> using namespace std; char exp[1048576]; map<long long, int> R; void dfs(int l, int r, int dep) { if (exp[l] == '[') { int p = 0; for (int i = l + 1; i <= r - 1; i++) { if (exp[i] == '[') p++; if (exp[i] == ']') p--; if (p == 0 && exp[i] == ',') { dfs(l+1, i-1, dep+1); dfs(i+1, r-1, dep+1); } } } else { int w; exp[r+1] = '\0'; sscanf(exp+l, "%d", &w); R[(long long)w<<dep]++; } } int main() { int testcase; scanf("%d", &testcase); while (testcase--) { scanf("%s", exp); R.clear(); dfs(0, strlen(exp) - 1, 0); int sum = 0, mx = 0; for (map<long long, int>::iterator it = R.begin(); it != R.end(); it++) sum += it->second, mx = max(mx, it->second); printf("%d\n", sum - mx); } return 0; } /* 3 [[3,7],6] 40 [[2,3],[4,5]] */
liuhaozzu/linux
kernels/linux-2.4.0/include/asm-arm/proc-fns.h
/* * linux/include/asm-arm/proc-fns.h * * Copyright (C) 1997-1999 <NAME> * Copyright (C) 2000 Deep Blue Solutions Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #ifndef __ASM_PROCFNS_H #define __ASM_PROCFNS_H #ifdef __KERNEL__ #include <linux/config.h> /* * Work out if we need multiple CPU support */ #undef MULTI_CPU #undef CPU_NAME #ifdef CONFIG_CPU_26 # define CPU_INCLUDE_NAME "asm/cpu-multi26.h" # define MULTI_CPU #endif #ifdef CONFIG_CPU_32 # define CPU_INCLUDE_NAME "asm/cpu-multi32.h" # ifdef CONFIG_CPU_ARM6 # ifdef CPU_NAME # undef MULTI_CPU # define MULTI_CPU # else # define CPU_NAME arm6 # endif # endif # ifdef CONFIG_CPU_ARM7 # ifdef CPU_NAME # undef MULTI_CPU # define MULTI_CPU # else # define CPU_NAME arm7 # endif # endif # ifdef CONFIG_CPU_ARM720 # ifdef CPU_NAME # undef MULTI_CPU # define MULTI_CPU # else # define CPU_NAME arm720 # endif # endif # ifdef CONFIG_CPU_ARM920 # ifdef CPU_NAME # undef MULTI_CPU # define MULTI_CPU # else # define CPU_NAME arm920 # endif # endif # ifdef CONFIG_CPU_SA110 # ifdef CPU_NAME # undef MULTI_CPU # define MULTI_CPU # else # define CPU_NAME sa110 # endif # endif # ifdef CONFIG_CPU_SA1100 # ifdef CPU_NAME # undef MULTI_CPU # define MULTI_CPU # else # define CPU_NAME sa1100 # endif # endif #endif #ifndef MULTI_CPU #undef CPU_INCLUDE_NAME #define CPU_INCLUDE_NAME "asm/cpu-single.h" #endif #include CPU_INCLUDE_NAME #endif /* __KERNEL__ */ #if 0 * The following is to fool mkdep into generating the correct * dependencies. Without this, it cant figure out that this * file does indeed depend on the cpu-*.h files. #include <asm/cpu-single.h> #include <asm/cpu-multi26.h> #include <asm/cpu-multi32.h> * #endif #endif /* __ASM_PROCFNS_H */
TigerBSD/FreeBSD-Custom-ThinkPad
FreeBSD/libexec/rtld-elf/powerpc64/reloc.c
/* $NetBSD: ppc_reloc.c,v 1.10 2001/09/10 06:09:41 mycroft Exp $ */ /*- * Copyright (C) 1998 <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * $FreeBSD$ */ #include <sys/param.h> #include <sys/mman.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <machine/cpu.h> #include <machine/md_var.h> #include "debug.h" #include "rtld.h" #if !defined(_CALL_ELF) || _CALL_ELF == 1 struct funcdesc { Elf_Addr addr; Elf_Addr toc; Elf_Addr env; }; #endif /* * Process the R_PPC_COPY relocations */ int do_copy_relocations(Obj_Entry *dstobj) { const Elf_Rela *relalim; const Elf_Rela *rela; /* * COPY relocs are invalid outside of the main program */ assert(dstobj->mainprog); relalim = (const Elf_Rela *) ((caddr_t) dstobj->rela + dstobj->relasize); for (rela = dstobj->rela; rela < relalim; rela++) { void *dstaddr; const Elf_Sym *dstsym; const char *name; size_t size; const void *srcaddr; const Elf_Sym *srcsym = NULL; const Obj_Entry *srcobj, *defobj; SymLook req; int res; if (ELF_R_TYPE(rela->r_info) != R_PPC_COPY) { continue; } dstaddr = (void *) (dstobj->relocbase + rela->r_offset); dstsym = dstobj->symtab + ELF_R_SYM(rela->r_info); name = dstobj->strtab + dstsym->st_name; size = dstsym->st_size; symlook_init(&req, name); req.ventry = fetch_ventry(dstobj, ELF_R_SYM(rela->r_info)); req.flags = SYMLOOK_EARLY; for (srcobj = globallist_next(dstobj); srcobj != NULL; srcobj = globallist_next(srcobj)) { res = symlook_obj(&req, srcobj); if (res == 0) { srcsym = req.sym_out; defobj = req.defobj_out; break; } } if (srcobj == NULL) { _rtld_error("Undefined symbol \"%s\" " " referenced from COPY" " relocation in %s", name, dstobj->path); return (-1); } srcaddr = (const void *) (defobj->relocbase+srcsym->st_value); memcpy(dstaddr, srcaddr, size); dbg("copy_reloc: src=%p,dst=%p,size=%zd\n",srcaddr,dstaddr,size); } return (0); } /* * Perform early relocation of the run-time linker image */ void reloc_non_plt_self(Elf_Dyn *dynp, Elf_Addr relocbase) { const Elf_Rela *rela = NULL, *relalim; Elf_Addr relasz = 0; Elf_Addr *where; /* * Extract the rela/relasz values from the dynamic section */ for (; dynp->d_tag != DT_NULL; dynp++) { switch (dynp->d_tag) { case DT_RELA: rela = (const Elf_Rela *)(relocbase+dynp->d_un.d_ptr); break; case DT_RELASZ: relasz = dynp->d_un.d_val; break; } } /* * Relocate these values */ relalim = (const Elf_Rela *)((caddr_t)rela + relasz); for (; rela < relalim; rela++) { where = (Elf_Addr *)(relocbase + rela->r_offset); *where = (Elf_Addr)(relocbase + rela->r_addend); } } /* * Relocate a non-PLT object with addend. */ static int reloc_nonplt_object(Obj_Entry *obj_rtld, Obj_Entry *obj, const Elf_Rela *rela, SymCache *cache, int flags, RtldLockState *lockstate) { Elf_Addr *where = (Elf_Addr *)(obj->relocbase + rela->r_offset); const Elf_Sym *def; const Obj_Entry *defobj; Elf_Addr tmp; switch (ELF_R_TYPE(rela->r_info)) { case R_PPC_NONE: break; case R_PPC64_UADDR64: /* doubleword64 S + A */ case R_PPC64_ADDR64: case R_PPC_GLOB_DAT: def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj, flags, cache, lockstate); if (def == NULL) { return (-1); } tmp = (Elf_Addr)(defobj->relocbase + def->st_value + rela->r_addend); /* Don't issue write if unnecessary; avoid COW page fault */ if (*where != tmp) { *where = tmp; } break; case R_PPC_RELATIVE: /* doubleword64 B + A */ tmp = (Elf_Addr)(obj->relocbase + rela->r_addend); /* As above, don't issue write unnecessarily */ if (*where != tmp) { *where = tmp; } break; case R_PPC_COPY: /* * These are deferred until all other relocations * have been done. All we do here is make sure * that the COPY relocation is not in a shared * library. They are allowed only in executable * files. */ if (!obj->mainprog) { _rtld_error("%s: Unexpected R_COPY " " relocation in shared library", obj->path); return (-1); } break; case R_PPC_JMP_SLOT: /* * These will be handled by the plt/jmpslot routines */ break; case R_PPC64_DTPMOD64: def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj, flags, cache, lockstate); if (def == NULL) return (-1); *where = (Elf_Addr) defobj->tlsindex; break; case R_PPC64_TPREL64: def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj, flags, cache, lockstate); if (def == NULL) return (-1); /* * We lazily allocate offsets for static TLS as we * see the first relocation that references the * TLS block. This allows us to support (small * amounts of) static TLS in dynamically loaded * modules. If we run out of space, we generate an * error. */ if (!defobj->tls_done) { if (!allocate_tls_offset((Obj_Entry*) defobj)) { _rtld_error("%s: No space available for static " "Thread Local Storage", obj->path); return (-1); } } *(Elf_Addr **)where = *where * sizeof(Elf_Addr) + (Elf_Addr *)(def->st_value + rela->r_addend + defobj->tlsoffset - TLS_TP_OFFSET); break; case R_PPC64_DTPREL64: def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj, flags, cache, lockstate); if (def == NULL) return (-1); *where += (Elf_Addr)(def->st_value + rela->r_addend - TLS_DTV_OFFSET); break; default: _rtld_error("%s: Unsupported relocation type %ld" " in non-PLT relocations\n", obj->path, ELF_R_TYPE(rela->r_info)); return (-1); } return (0); } /* * Process non-PLT relocations */ int reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld, int flags, RtldLockState *lockstate) { const Elf_Rela *relalim; const Elf_Rela *rela; SymCache *cache; int bytes = obj->dynsymcount * sizeof(SymCache); int r = -1; if ((flags & SYMLOOK_IFUNC) != 0) /* XXX not implemented */ return (0); /* * The dynamic loader may be called from a thread, we have * limited amounts of stack available so we cannot use alloca(). */ if (obj != obj_rtld) { cache = mmap(NULL, bytes, PROT_READ|PROT_WRITE, MAP_ANON, -1, 0); if (cache == MAP_FAILED) cache = NULL; } else cache = NULL; /* * From the SVR4 PPC ABI: * "The PowerPC family uses only the Elf32_Rela relocation * entries with explicit addends." */ relalim = (const Elf_Rela *)((caddr_t)obj->rela + obj->relasize); for (rela = obj->rela; rela < relalim; rela++) { if (reloc_nonplt_object(obj_rtld, obj, rela, cache, flags, lockstate) < 0) goto done; } r = 0; done: if (cache) munmap(cache, bytes); /* Synchronize icache for text seg in case we made any changes */ __syncicache(obj->mapbase, obj->textsize); return (r); } /* * Initialise a PLT slot to the resolving trampoline */ static int reloc_plt_object(Obj_Entry *obj, const Elf_Rela *rela) { Elf_Addr *where = (Elf_Addr *)(obj->relocbase + rela->r_offset); long reloff; reloff = rela - obj->pltrela; dbg(" reloc_plt_object: where=%p,reloff=%lx,glink=%#lx", (void *)where, reloff, obj->glink); #if !defined(_CALL_ELF) || _CALL_ELF == 1 /* Glink code is 3 instructions after the first 32k, 2 before */ *where = (Elf_Addr)obj->glink + 32 + 8*((reloff < 0x8000) ? reloff : 0x8000) + 12*((reloff < 0x8000) ? 0 : (reloff - 0x8000)); #else *where = (Elf_Addr)obj->glink + 4*reloff + 32; #endif return (0); } /* * Process the PLT relocations. */ int reloc_plt(Obj_Entry *obj) { const Elf_Rela *relalim; const Elf_Rela *rela; if (obj->pltrelasize != 0) { relalim = (const Elf_Rela *)((char *)obj->pltrela + obj->pltrelasize); for (rela = obj->pltrela; rela < relalim; rela++) { assert(ELF_R_TYPE(rela->r_info) == R_PPC_JMP_SLOT); if (reloc_plt_object(obj, rela) < 0) { return (-1); } } } return (0); } /* * LD_BIND_NOW was set - force relocation for all jump slots */ int reloc_jmpslots(Obj_Entry *obj, int flags, RtldLockState *lockstate) { const Obj_Entry *defobj; const Elf_Rela *relalim; const Elf_Rela *rela; const Elf_Sym *def; Elf_Addr *where; Elf_Addr target; relalim = (const Elf_Rela *)((char *)obj->pltrela + obj->pltrelasize); for (rela = obj->pltrela; rela < relalim; rela++) { assert(ELF_R_TYPE(rela->r_info) == R_PPC_JMP_SLOT); where = (Elf_Addr *)(obj->relocbase + rela->r_offset); def = find_symdef(ELF_R_SYM(rela->r_info), obj, &defobj, SYMLOOK_IN_PLT | flags, NULL, lockstate); if (def == NULL) { dbg("reloc_jmpslots: sym not found"); return (-1); } target = (Elf_Addr)(defobj->relocbase + def->st_value); if (def == &sym_zero) { /* Zero undefined weak symbols */ #if !defined(_CALL_ELF) || _CALL_ELF == 1 bzero(where, sizeof(struct funcdesc)); #else *where = 0; #endif } else { reloc_jmpslot(where, target, defobj, obj, (const Elf_Rel *) rela); } } obj->jmpslots_done = true; return (0); } /* * Update the value of a PLT jump slot. */ Elf_Addr reloc_jmpslot(Elf_Addr *wherep, Elf_Addr target, const Obj_Entry *defobj, const Obj_Entry *obj, const Elf_Rel *rel) { /* * At the PLT entry pointed at by `wherep', construct * a direct transfer to the now fully resolved function * address. */ #if !defined(_CALL_ELF) || _CALL_ELF == 1 dbg(" reloc_jmpslot: where=%p, target=%p (%#lx + %#lx)", (void *)wherep, (void *)target, *(Elf_Addr *)target, (Elf_Addr)defobj->relocbase); /* * For the trampoline, the second two elements of the function * descriptor are unused, so we are fine replacing those at any time * with the real ones with no thread safety implications. However, we * need to make sure the main entry point pointer ([0]) is seen to be * modified *after* the second two elements. This can't be done in * general, since there are no barriers in the reading code, but put in * some isyncs to at least make it a little better. */ memcpy(wherep, (void *)target, sizeof(struct funcdesc)); wherep[2] = ((Elf_Addr *)target)[2]; wherep[1] = ((Elf_Addr *)target)[1]; __asm __volatile ("isync" : : : "memory"); wherep[0] = ((Elf_Addr *)target)[0]; __asm __volatile ("isync" : : : "memory"); if (((struct funcdesc *)(wherep))->addr < (Elf_Addr)defobj->relocbase) { /* * It is possible (LD_BIND_NOW) that the function * descriptor we are copying has not yet been relocated. * If this happens, fix it. Don't worry about threading in * this case since LD_BIND_NOW makes it irrelevant. */ ((struct funcdesc *)(wherep))->addr += (Elf_Addr)defobj->relocbase; ((struct funcdesc *)(wherep))->toc += (Elf_Addr)defobj->relocbase; } #else dbg(" reloc_jmpslot: where=%p, target=%p", (void *)wherep, (void *)target); *wherep = target; #endif return (target); } int reloc_iresolve(Obj_Entry *obj, struct Struct_RtldLockState *lockstate) { /* XXX not implemented */ return (0); } int reloc_gnu_ifunc(Obj_Entry *obj, int flags, struct Struct_RtldLockState *lockstate) { /* XXX not implemented */ return (0); } void init_pltgot(Obj_Entry *obj) { Elf_Addr *pltcall; pltcall = obj->pltgot; if (pltcall == NULL) { return; } #if defined(_CALL_ELF) && _CALL_ELF == 2 pltcall[0] = (Elf_Addr)&_rtld_bind_start; pltcall[1] = (Elf_Addr)obj; #else memcpy(pltcall, _rtld_bind_start, sizeof(struct funcdesc)); pltcall[2] = (Elf_Addr)obj; #endif } void allocate_initial_tls(Obj_Entry *list) { Elf_Addr **tp; /* * Fix the size of the static TLS block by using the maximum * offset allocated so far and adding a bit for dynamic modules to * use. */ tls_static_space = tls_last_offset + tls_last_size + RTLD_STATIC_TLS_EXTRA; tp = (Elf_Addr **) ((char *)allocate_tls(list, NULL, TLS_TCB_SIZE, 16) + TLS_TP_OFFSET + TLS_TCB_SIZE); __asm __volatile("mr 13,%0" :: "r"(tp)); } void* __tls_get_addr(tls_index* ti) { Elf_Addr **tp; char *p; __asm __volatile("mr %0,13" : "=r"(tp)); p = tls_get_addr_common((Elf_Addr**)((Elf_Addr)tp - TLS_TP_OFFSET - TLS_TCB_SIZE), ti->ti_module, ti->ti_offset); return (p + TLS_DTV_OFFSET); }
Andruxin52rus/openvino
ngraph/test/backend/concat.in.cpp
//***************************************************************************** // Copyright 2017-2021 Intel Corporation // // 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. //***************************************************************************** #include "gtest/gtest.h" #include "ngraph/ngraph.hpp" #include "ngraph/runtime/tensor.hpp" #include "runtime/backend.hpp" #include "util/all_close.hpp" #include "util/all_close_f.hpp" #include "util/ndarray.hpp" #include "util/test_control.hpp" #include "util/test_tools.hpp" NGRAPH_SUPPRESS_DEPRECATED_START using namespace std; using namespace ngraph; static string s_manifest = "${MANIFEST}"; NGRAPH_TEST(${BACKEND_NAME}, concat_negative_axis) { auto pshape_a = PartialShape::dynamic(); auto A = make_shared<op::Parameter>(element::f32, pshape_a); auto pshape_b = PartialShape::dynamic(); auto B = make_shared<op::Parameter>(element::f32, pshape_b); auto pshape_c = PartialShape::dynamic(); auto C = make_shared<op::Parameter>(element::f32, pshape_c); auto pshape_r = PartialShape::dynamic(); auto f = make_shared<Function>(make_shared<op::Concat>(NodeVector{A, B, C}, -1), ParameterVector{A, B, C}); auto backend = runtime::Backend::create("${BACKEND_NAME}", true); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, Shape{2, 2}); copy_data(a, vector<float>{2, 4, 8, 16}); auto b = backend->create_tensor(element::f32, Shape{2, 3}); copy_data(b, vector<float>{1, 2, 4, 8, 16, 32}); auto c = backend->create_tensor(element::f32, Shape{2, 3}); copy_data(c, vector<float>{2, 3, 5, 7, 11, 13}); auto result = backend->create_dynamic_tensor(element::f32, PartialShape::dynamic()); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c}); ASSERT_EQ(result->get_shape(), (Shape{2, 8})); EXPECT_TRUE( test::all_close_f((vector<float>{2, 4, 1, 2, 4, 2, 3, 5, 8, 16, 8, 16, 32, 7, 11, 13}), read_vector<float>(result))); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_colwise) { Shape shape_a{2, 2}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_b{2, 3}; auto B = make_shared<op::Parameter>(element::f32, shape_b); Shape shape_c{2, 3}; auto C = make_shared<op::Parameter>(element::f32, shape_c); Shape shape_r{2, 8}; auto f = make_shared<Function>(make_shared<op::Concat>(NodeVector{A, B, C}, 1), ParameterVector{A, B, C}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape_a); copy_data(a, vector<float>{2, 4, 8, 16}); auto b = backend->create_tensor(element::f32, shape_b); copy_data(b, vector<float>{1, 2, 4, 8, 16, 32}); auto c = backend->create_tensor(element::f32, shape_c); copy_data(c, vector<float>{2, 3, 5, 7, 11, 13}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c}); EXPECT_TRUE( test::all_close_f((vector<float>{2, 4, 1, 2, 4, 2, 3, 5, 8, 16, 8, 16, 32, 7, 11, 13}), read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_rowwise) { Shape shape_a{2, 2}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_b{3, 2}; auto B = make_shared<op::Parameter>(element::f32, shape_b); Shape shape_c{3, 2}; auto C = make_shared<op::Parameter>(element::f32, shape_c); Shape shape_r{8, 2}; auto f = make_shared<Function>(make_shared<op::Concat>(NodeVector{A, B, C}, 0), ParameterVector{A, B, C}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape_a); copy_data(a, vector<float>{2, 4, 8, 16}); auto b = backend->create_tensor(element::f32, shape_b); copy_data(b, vector<float>{1, 2, 4, 8, 16, 32}); auto c = backend->create_tensor(element::f32, shape_c); copy_data(c, vector<float>{2, 3, 5, 7, 11, 13}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c}); EXPECT_TRUE( test::all_close_f((vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 2, 3, 5, 7, 11, 13}), read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_int64) { Shape shape_a{2, 2}; auto A = make_shared<op::Parameter>(element::i64, shape_a); Shape shape_b{3, 2}; auto B = make_shared<op::Parameter>(element::i64, shape_b); Shape shape_c{3, 2}; auto C = make_shared<op::Parameter>(element::i64, shape_c); Shape shape_r{8, 2}; auto f = make_shared<Function>(make_shared<op::Concat>(NodeVector{A, B, C}, 0), ParameterVector{A, B, C}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::i64, shape_a); copy_data(a, vector<int64_t>{2, 4, 8, 16}); auto b = backend->create_tensor(element::i64, shape_b); copy_data(b, vector<int64_t>{1, 2, 4, 8, 16, 32}); auto c = backend->create_tensor(element::i64, shape_c); copy_data(c, vector<int64_t>{2, 3, 5, 7, 11, 13}); auto result = backend->create_tensor(element::i64, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c}); EXPECT_EQ((vector<int64_t>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 2, 3, 5, 7, 11, 13}), read_vector<int64_t>(result)); } // Params to drive concat_vector_large testing variations class concat_vector_params : public ::testing::TestWithParam<int> { protected: concat_vector_params() { num_inputs = GetParam(); } uint32_t num_inputs; }; NGRAPH_TEST_P(${BACKEND_NAME}, concat_vector_params, concat_vector_large) { Shape shape_a{1}; NodeVector inputs; ParameterVector inputs_param; for (uint32_t i = 0; i < num_inputs; i++) { auto A = make_shared<op::Parameter>(element::f32, shape_a); inputs_param.push_back(A); inputs.push_back(A); } Shape shape_r{num_inputs}; auto f = make_shared<Function>(make_shared<op::Concat>(inputs, 0), inputs_param); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output std::vector<std::shared_ptr<runtime::Tensor>> inputs_value; std::vector<float> ref_result; for (uint32_t i = 0; i < num_inputs; i++) { auto a = backend->create_tensor(element::f32, shape_a); copy_data(a, vector<float>{static_cast<float>(i)}); ref_result.push_back(static_cast<float>(i)); inputs_value.push_back(a); } auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, inputs_value); EXPECT_TRUE( test::all_close_f(ref_result, read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } // concat_vector_large case generation // Add thhosw tests to cover paramter space overflow: // cuda kernel parameter space have limit, if there is large number of parameters, // there will be overflow for parameter space. NGRAPH_INSTANTIATE_TEST_CASE_P(${BACKEND_NAME}, input_sizes, concat_vector_params, testing::Values(100, 128, 999)); NGRAPH_TEST(${BACKEND_NAME}, concat_vector) { Shape shape_a{4}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_b{6}; auto B = make_shared<op::Parameter>(element::f32, shape_b); Shape shape_c{2}; auto C = make_shared<op::Parameter>(element::f32, shape_c); Shape shape_r{12}; auto f = make_shared<Function>(make_shared<op::Concat>(NodeVector{A, B, C}, 0), ParameterVector{A, B, C}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape_a); copy_data(a, vector<float>{2, 4, 8, 16}); auto b = backend->create_tensor(element::f32, shape_b); copy_data(b, vector<float>{1, 2, 4, 8, 16, 32}); auto c = backend->create_tensor(element::f32, shape_c); copy_data(c, vector<float>{18, 19}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c}); EXPECT_TRUE(test::all_close_f((vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 18, 19}), read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_4d_tensor) { Shape shape{1, 1, 1, 1}; auto A = make_shared<op::Parameter>(element::f32, shape); auto B = make_shared<op::Parameter>(element::f32, shape); auto C = make_shared<op::Parameter>(element::f32, shape); Shape shape_r{3, 1, 1, 1}; auto f = make_shared<Function>(make_shared<op::Concat>(NodeVector{A, B, C}, 0), ParameterVector{A, B, C}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape); copy_data(a, vector<float>{1}); auto b = backend->create_tensor(element::f32, shape); copy_data(b, vector<float>{2}); auto c = backend->create_tensor(element::f32, shape); copy_data(c, vector<float>{3}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c}); EXPECT_TRUE(test::all_close_f( (vector<float>{1, 2, 3}), read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_2d_tensor) { Shape shape{1, 1}; auto A = make_shared<op::Parameter>(element::f32, shape); auto B = make_shared<op::Parameter>(element::f32, shape); auto C = make_shared<op::Parameter>(element::f32, shape); Shape shape_r{3, 1}; auto f = make_shared<Function>(make_shared<op::Concat>(NodeVector{A, B, C}, 0), ParameterVector{A, B, C}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape); copy_data(a, vector<float>{1}); auto b = backend->create_tensor(element::f32, shape); copy_data(b, vector<float>{2}); auto c = backend->create_tensor(element::f32, shape); copy_data(c, vector<float>{3}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c}); EXPECT_TRUE(test::all_close_f( (vector<float>{1, 2, 3}), read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_in_place_2d_tensor) { Shape shape{1, 1}; auto A = make_shared<op::Parameter>(element::f32, shape); auto B = make_shared<op::Parameter>(element::f32, shape); auto add1 = make_shared<op::v1::Add>(A, B); auto C = make_shared<op::Parameter>(element::f32, shape); auto D = make_shared<op::Parameter>(element::f32, shape); auto add2 = make_shared<op::v1::Add>(C, D); auto subtract = make_shared<op::v1::Subtract>(C, A); Shape shape_r{3, 1}; auto f = make_shared<Function>(make_shared<op::Concat>(NodeVector{add1, add2, subtract}, 0), ParameterVector{A, B, C, D}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape); copy_data(a, vector<float>{1}); auto b = backend->create_tensor(element::f32, shape); copy_data(b, vector<float>{2}); auto c = backend->create_tensor(element::f32, shape); copy_data(c, vector<float>{3}); auto d = backend->create_tensor(element::f32, shape); copy_data(d, vector<float>{4}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c, d}); EXPECT_TRUE(test::all_close_f( (vector<float>{3, 7, 2}), read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_in_place_propagate_2d_tensor) { Shape shape{1, 1}; auto A = make_shared<op::Parameter>(element::f32, shape); auto B = make_shared<op::Parameter>(element::f32, shape); auto add1 = make_shared<op::v1::Add>(A, B); auto C = make_shared<op::Parameter>(element::f32, shape); auto D = make_shared<op::Parameter>(element::f32, shape); auto add2 = make_shared<op::v1::Add>(C, D); auto concat1 = make_shared<op::Concat>(NodeVector{add1, add2}, 0); auto subtract = make_shared<op::v1::Subtract>(C, A); Shape shape_r{3, 1}; auto f = make_shared<Function>(make_shared<op::Concat>(NodeVector{concat1, subtract}, 0), ParameterVector{A, B, C, D}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape); copy_data(a, vector<float>{1}); auto b = backend->create_tensor(element::f32, shape); copy_data(b, vector<float>{2}); auto c = backend->create_tensor(element::f32, shape); copy_data(c, vector<float>{3}); auto d = backend->create_tensor(element::f32, shape); copy_data(d, vector<float>{4}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c, d}); EXPECT_TRUE(test::all_close_f( (vector<float>{3, 7, 2}), read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_in_place_tree_1) { Shape shape{1, 2, 2}; Shape shape_r{1, 4, 2}; auto A = make_shared<op::Parameter>(element::f32, shape); auto B = make_shared<op::Parameter>(element::f32, shape); auto add1 = make_shared<op::v1::Add>(A, B); auto add2 = make_shared<op::v1::Add>(A, B); auto concat = make_shared<op::Concat>(NodeVector{add1, add2}, 1); auto f = make_shared<Function>(make_shared<op::v1::Add>(concat, concat), ParameterVector{A, B}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape); copy_data(a, vector<float>{1, 1, 1, 1}); auto b = backend->create_tensor(element::f32, shape); copy_data(b, vector<float>{1, 1, 1, 1}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b}); vector<float> expected; expected.resize(8, 4); EXPECT_TRUE(test::all_close_f(expected, read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_in_place_tree_2) { Shape shape{1, 2, 2}; Shape shape_r{1, 8, 2}; auto A = make_shared<op::Parameter>(element::f32, shape); auto B = make_shared<op::Parameter>(element::f32, shape); auto add1 = make_shared<op::v1::Add>(A, B); auto add2 = make_shared<op::v1::Add>(A, B); auto concat1 = make_shared<op::Concat>(NodeVector{add1, add2}, 1); auto concat2 = make_shared<op::Concat>(NodeVector{add1, add2}, 1); auto concat12 = make_shared<op::Concat>(NodeVector{concat1, concat2}, 1); auto f = make_shared<Function>(make_shared<op::v1::Add>(concat12, concat12), ParameterVector{A, B}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape); copy_data(a, vector<float>{1, 1, 1, 1}); auto b = backend->create_tensor(element::f32, shape); copy_data(b, vector<float>{1, 1, 1, 1}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b}); vector<float> expected; expected.resize(16, 4); EXPECT_TRUE(test::all_close_f(expected, read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_in_place_tree_3) { Shape shape{1, 2, 2}; Shape shape_r{1, 16, 2}; auto A = make_shared<op::Parameter>(element::f32, shape); auto B = make_shared<op::Parameter>(element::f32, shape); auto concat1 = make_shared<op::Concat>(NodeVector{A, B}, 1); auto concat2 = make_shared<op::Concat>(NodeVector{A, B}, 1); auto concat3 = make_shared<op::Concat>(NodeVector{A, B}, 1); auto concat4 = make_shared<op::Concat>(NodeVector{A, B}, 1); auto concat12 = make_shared<op::Concat>(NodeVector{concat1, concat2}, 1); auto concat34 = make_shared<op::Concat>(NodeVector{concat3, concat4}, 1); auto concat14 = make_shared<op::Concat>(NodeVector{concat12, concat34}, 1); auto f = make_shared<Function>(make_shared<op::v1::Add>(concat14, concat14), ParameterVector{A, B}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape); copy_data(a, vector<float>{1, 1, 1, 1}); auto b = backend->create_tensor(element::f32, shape); copy_data(b, vector<float>{1, 1, 1, 1}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b}); vector<float> expected; expected.resize(32, 2); EXPECT_TRUE(test::all_close_f(expected, read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_in_place_add_concat) { Shape shape{2, 2}; Shape shape_r{4, 2}; auto A = make_shared<op::Parameter>(element::f32, shape); auto B = make_shared<op::Parameter>(element::f32, shape); auto add1 = make_shared<op::v1::Add>(A, B); auto add2 = make_shared<op::v1::Add>(add1, add1); auto concat = make_shared<op::Concat>(NodeVector{add1, add2}, 0); auto add3 = make_shared<op::v1::Add>(concat, concat); auto f = make_shared<Function>(add3, ParameterVector{A, B}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); auto a = backend->create_tensor(element::f32, shape); copy_data(a, vector<float>{1, 1, 1, 1}); auto b = backend->create_tensor(element::f32, shape); copy_data(b, vector<float>{1, 1, 1, 1}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b}); vector<float> expected = {4, 4, 4, 4, 8, 8, 8, 8}; EXPECT_TRUE(test::all_close_f(expected, read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_in_place_add_concat_2) { Shape shape{1, 2, 2}; Shape shape_r{1, 6, 2}; auto A = make_shared<op::Parameter>(element::f32, shape); auto B = make_shared<op::Parameter>(element::f32, shape); auto add1 = make_shared<op::v1::Add>(A, B); auto add2 = make_shared<op::v1::Add>(A, B); auto add3 = make_shared<op::v1::Add>(A, B); auto add4 = make_shared<op::v1::Add>(A, B); auto add5 = make_shared<op::v1::Add>(A, B); auto concat1 = make_shared<op::Concat>(NodeVector{add1, add2, add3}, 1); auto concat2 = make_shared<op::Concat>(NodeVector{add4, add2, add5}, 1); auto add6 = make_shared<op::v1::Add>(concat1, concat2); auto f = make_shared<Function>(add6, ParameterVector{A, B}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); auto a = backend->create_tensor(element::f32, shape); copy_data(a, vector<float>{1, 1, 1, 1}); auto b = backend->create_tensor(element::f32, shape); copy_data(b, vector<float>{1, 1, 1, 1}); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b}); vector<float> expected = {4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4}; EXPECT_TRUE(test::all_close_f(expected, read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } // from numpy import * // a=linspace(1,2*3*4*3*2,2*3*4*3*2) // b=linspace(1000+1,1000+2*3*3*3*2,2*3*3*3*2) // c=linspace(2000+1,2000+2*3*2*3*2,2*3*2*3*2) // a.shape=(2,3,4,3,2) // b.shape=(2,3,3,3,2) // c.shape=(2,3,2,3,2) // z=concatenate((a,b,c),axis=2) // z.shape=(2*3*(4+3+2)*3*2) // set_printoptions(suppress=True) // print(z) // // [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. // 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. // 21. 22. 23. 24. 1001. 1002. 1003. 1004. 1005. 1006. // 1007. 1008. 1009. 1010. 1011. 1012. 1013. 1014. 1015. 1016. // 1017. 1018. 2001. 2002. 2003. 2004. 2005. 2006. 2007. 2008. // 2009. 2010. 2011. 2012. 25. 26. 27. 28. 29. 30. // 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. // 41. 42. 43. 44. 45. 46. 47. 48. 1019. 1020. // 1021. 1022. 1023. 1024. 1025. 1026. 1027. 1028. 1029. 1030. // 1031. 1032. 1033. 1034. 1035. 1036. 2013. 2014. 2015. 2016. // 2017. 2018. 2019. 2020. 2021. 2022. 2023. 2024. 49. 50. // 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. // 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. // 71. 72. 1037. 1038. 1039. 1040. 1041. 1042. 1043. 1044. // 1045. 1046. 1047. 1048. 1049. 1050. 1051. 1052. 1053. 1054. // 2025. 2026. 2027. 2028. 2029. 2030. 2031. 2032. 2033. 2034. // 2035. 2036. 73. 74. 75. 76. 77. 78. 79. 80. // 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. // 91. 92. 93. 94. 95. 96. 1055. 1056. 1057. 1058. // 1059. 1060. 1061. 1062. 1063. 1064. 1065. 1066. 1067. 1068. // 1069. 1070. 1071. 1072. 2037. 2038. 2039. 2040. 2041. 2042. // 2043. 2044. 2045. 2046. 2047. 2048. 97. 98. 99. 100. // 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. // 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. // 1073. 1074. 1075. 1076. 1077. 1078. 1079. 1080. 1081. 1082. // 1083. 1084. 1085. 1086. 1087. 1088. 1089. 1090. 2049. 2050. // 2051. 2052. 2053. 2054. 2055. 2056. 2057. 2058. 2059. 2060. // 121. 122. 123. 124. 125. 126. 127. 128. 129. 130. // 131. 132. 133. 134. 135. 136. 137. 138. 139. 140. // 141. 142. 143. 144. 1091. 1092. 1093. 1094. 1095. 1096. // 1097. 1098. 1099. 1100. 1101. 1102. 1103. 1104. 1105. 1106. // 1107. 1108. 2061. 2062. 2063. 2064. 2065. 2066. 2067. 2068. // 2069. 2070. 2071. 2072.] NGRAPH_TEST(${BACKEND_NAME}, concat_5d) { vector<float> a_data(2 * 3 * 4 * 3 * 2); for (int i = 0; i < 2 * 3 * 4 * 3 * 2; i++) { a_data[i] = float(i + 1); } vector<float> b_data(2 * 3 * 3 * 3 * 2); for (int i = 0; i < 2 * 3 * 3 * 3 * 2; i++) { b_data[i] = 1000 + float(i + 1); } vector<float> c_data(2 * 3 * 2 * 3 * 2); for (int i = 0; i < 2 * 3 * 2 * 3 * 2; i++) { c_data[i] = 2000 + float(i + 1); } Shape shape_a{2, 3, 4, 3, 2}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_b{2, 3, 3, 3, 2}; auto B = make_shared<op::Parameter>(element::f32, shape_b); Shape shape_c{2, 3, 2, 3, 2}; auto C = make_shared<op::Parameter>(element::f32, shape_c); Shape shape_r{2, 3, 9, 3, 2}; auto r = make_shared<op::Concat>(NodeVector{A, B, C}, 2); auto f = make_shared<Function>(r, ParameterVector{A, B, C}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output auto a = backend->create_tensor(element::f32, shape_a); copy_data(a, a_data); auto b = backend->create_tensor(element::f32, shape_b); copy_data(b, b_data); auto c = backend->create_tensor(element::f32, shape_c); copy_data(c, c_data); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c}); EXPECT_TRUE(test::all_close_f( (vector<float>{ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 1001., 1002., 1003., 1004., 1005., 1006., 1007., 1008., 1009., 1010., 1011., 1012., 1013., 1014., 1015., 1016., 1017., 1018., 2001., 2002., 2003., 2004., 2005., 2006., 2007., 2008., 2009., 2010., 2011., 2012., 25., 26., 27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39., 40., 41., 42., 43., 44., 45., 46., 47., 48., 1019., 1020., 1021., 1022., 1023., 1024., 1025., 1026., 1027., 1028., 1029., 1030., 1031., 1032., 1033., 1034., 1035., 1036., 2013., 2014., 2015., 2016., 2017., 2018., 2019., 2020., 2021., 2022., 2023., 2024., 49., 50., 51., 52., 53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65., 66., 67., 68., 69., 70., 71., 72., 1037., 1038., 1039., 1040., 1041., 1042., 1043., 1044., 1045., 1046., 1047., 1048., 1049., 1050., 1051., 1052., 1053., 1054., 2025., 2026., 2027., 2028., 2029., 2030., 2031., 2032., 2033., 2034., 2035., 2036., 73., 74., 75., 76., 77., 78., 79., 80., 81., 82., 83., 84., 85., 86., 87., 88., 89., 90., 91., 92., 93., 94., 95., 96., 1055., 1056., 1057., 1058., 1059., 1060., 1061., 1062., 1063., 1064., 1065., 1066., 1067., 1068., 1069., 1070., 1071., 1072., 2037., 2038., 2039., 2040., 2041., 2042., 2043., 2044., 2045., 2046., 2047., 2048., 97., 98., 99., 100., 101., 102., 103., 104., 105., 106., 107., 108., 109., 110., 111., 112., 113., 114., 115., 116., 117., 118., 119., 120., 1073., 1074., 1075., 1076., 1077., 1078., 1079., 1080., 1081., 1082., 1083., 1084., 1085., 1086., 1087., 1088., 1089., 1090., 2049., 2050., 2051., 2052., 2053., 2054., 2055., 2056., 2057., 2058., 2059., 2060., 121., 122., 123., 124., 125., 126., 127., 128., 129., 130., 131., 132., 133., 134., 135., 136., 137., 138., 139., 140., 141., 142., 143., 144., 1091., 1092., 1093., 1094., 1095., 1096., 1097., 1098., 1099., 1100., 1101., 1102., 1103., 1104., 1105., 1106., 1107., 1108., 2061., 2062., 2063., 2064., 2065., 2066., 2067., 2068., 2069., 2070., 2071., 2072.}), read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_zero_length_1d_last) { Shape shape_a{4}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_b{0}; auto B = make_shared<op::Parameter>(element::f32, shape_b); Shape shape_r{4}; auto r = make_shared<op::Concat>(NodeVector{A, B}, 0); auto f = make_shared<Function>(r, ParameterVector{A, B}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output vector<float> a_data{1, 2, 3, 4}; vector<float> b_data(0); auto a = backend->create_tensor(element::f32, shape_a); copy_data(a, a_data); auto b = backend->create_tensor(element::f32, shape_b); copy_data(b, b_data); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b}); EXPECT_TRUE(test::all_close_f( (vector<float>{1, 2, 3, 4}), read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_zero_length_1d_middle) { Shape shape_a{4}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_b{0}; auto B = make_shared<op::Parameter>(element::f32, shape_b); Shape shape_c{4}; auto C = make_shared<op::Parameter>(element::f32, shape_c); Shape shape_r{8}; auto r = make_shared<op::Concat>(NodeVector{A, B, C}, 0); auto f = make_shared<Function>(r, ParameterVector{A, B, C}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output vector<float> a_data{1, 2, 3, 4}; vector<float> b_data(0); vector<float> c_data{5, 6, 7, 8}; auto a = backend->create_tensor(element::f32, shape_a); copy_data(a, a_data); auto b = backend->create_tensor(element::f32, shape_b); copy_data(b, b_data); auto c = backend->create_tensor(element::f32, shape_c); copy_data(c, c_data); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c}); EXPECT_TRUE(test::all_close_f((vector<float>{1, 2, 3, 4, 5, 6, 7, 8}), read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_zero_zero) { Shape shape{0}; auto constant_1 = op::Constant::create(element::f32, shape, {1}); auto concat_1 = make_shared<op::Concat>(NodeVector{constant_1, constant_1}, 0); auto f = make_shared<Function>(concat_1, ParameterVector{}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); auto result = backend->create_tensor(element::f32, shape); auto handle = backend->compile(f); handle->call_with_validate({result}, {}); EXPECT_TRUE( test::all_close_f(vector<float>{}, read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); } NGRAPH_TEST(${BACKEND_NAME}, concat_zero_length_4d_middle) { Shape shape_a{2, 2, 1, 1}; auto A = make_shared<op::Parameter>(element::f32, shape_a); Shape shape_b{2, 2, 0, 1}; auto B = make_shared<op::Parameter>(element::f32, shape_b); Shape shape_c{2, 2, 1, 1}; auto C = make_shared<op::Parameter>(element::f32, shape_c); Shape shape_r{2, 2, 2, 1}; auto r = make_shared<op::Concat>(NodeVector{A, B, C}, 2); auto f = make_shared<Function>(r, ParameterVector{A, B, C}); auto backend = runtime::Backend::create("${BACKEND_NAME}"); // Create some tensors for input/output vector<float> a_data{1, 2, 3, 4}; vector<float> b_data(0); vector<float> c_data{5, 6, 7, 8}; auto a = backend->create_tensor(element::f32, shape_a); copy_data(a, a_data); auto b = backend->create_tensor(element::f32, shape_b); copy_data(b, b_data); auto c = backend->create_tensor(element::f32, shape_c); copy_data(c, c_data); auto result = backend->create_tensor(element::f32, shape_r); auto handle = backend->compile(f); handle->call_with_validate({result}, {a, b, c}); EXPECT_TRUE(test::all_close_f((vector<float>{1, 5, 2, 6, 3, 7, 4, 8}), read_vector<float>(result), MIN_FLOAT_TOLERANCE_BITS)); }
lp-rep/stackprof-1
sourceCode/application/ui/geoCRSSelect/dialog_geoCRSSelect_tableview.h
#ifndef DIALOG_GEOCRSSELECT_TABLEVIEW_H #define DIALOG_GEOCRSSELECT_TABLEVIEW_H #include <QDialog> #include <QItemSelection> #include "../../logic/georef/geo_EPSGCodeData_struct.h" namespace Ui { class Dialog_geoCRSSelect_tableView; } class geoCRSSelect_inheritQATableModel; class Dialog_geoCRSSelect_tableView : public QDialog { Q_OBJECT public: explicit Dialog_geoCRSSelect_tableView(QWidget *parent = nullptr); ~Dialog_geoCRSSelect_tableView(); void setModelsPtr_geoCRSSelect_tableView(geoCRSSelect_inheritQATableModel *geoCRSSelect_inheritQATableModel_ptr); void initConnectionModelViewSignalsSlots(); virtual void closeEvent(QCloseEvent *event); //@LP about close window button typically virtual void reject(); //@LP about escape key typically virtual void accept(); void showEvent(QShowEvent *event); //void clear_and_send_signal_keywordListCleared_toModel(); void resetToDefault(); public slots: void slot_lineEdit_keywordsToSearch_textEdited(const QString &text); void slot_pushButton_search_clicked(); void slot_pushButton_clear_clicked(); void slot_searchFromKeywords_resultCount(int resultCount/*, bool bMaxToSearchReached*/); void slot_pushButtonKeyword_clicked(); void slot_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void slot_EPSGDataAboutSelection(const QString& strEPSGCode, const QString& strName); signals: void signal_searchFromKeywords(QStringList strListKeywords); void signal_keywordListCleared(); void signal_selectionChangedInTableView(int index); //for outside: void signal_EPSGCodeSelectedFromList(QString strSelectedEPSGCode); private: void setEnableStateOfSearchAndClearPushButton(); void setEnableState_pushButtonOK(bool bState); void setEnableState_widgetAboutOneCodeSelected(bool bState); void clearAboutOneCodeSelected(); void clearTableViewRowSelection(); //void tableview_unselectAll(); private: enum e_UIGeoCRSSelectKeywordID { e_UIGCRSSKID_WGS84_UTM, e_UIGCRSSKID_UTM, e_UIGCRSSKID_WGS84, e_UIGCRSSKID_NAD27, e_UIGCRSSKID_NAD83, e_UIGCRSSKID_ETRS89, e_UIGCRSSKID_zone, }; private: Ui::Dialog_geoCRSSelect_tableView *ui; QStringList _strList_keywordsToSearch; geoCRSSelect_inheritQATableModel *_geoCRSSelect_inheritQATableModel_ptr; QHash<e_UIGeoCRSSelectKeywordID, QString> _qhash_UIGCRSSKID_string; QVector<QPushButton*> _qvect_QPushButtonPtr_keywordPreset; bool _bEnableState_pushButtonOK; int _selectedCodeTableViewRow; bool _bOneCodeSelected; struct S_SelectedEPSGCode_data { QString strEPSGCode; S_dataForAKnownEPSGCode_fromProjDB _sDataForAKnownEPSGCode_fromProjDB; } _sSelectedEPSGCode_data; }; #endif // DIALOG_GEOCRSSELECT_TABLEVIEW_H
typetree/hasor
hasor-dataql/dataql-fx/src/main/java/net/hasor/dataql/fx/basic/CompareUdfSource.java
/* * Copyright 2008-2009 the original author or authors. * * 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 net.hasor.dataql.fx.basic; import net.hasor.dataql.UdfSourceAssembly; import javax.inject.Singleton; /** * 比较函数。函数库引入 <code>import 'net.hasor.dataql.fx.basic.CompareUdfSource' as compare;</code> * @author 赵永春 (<EMAIL>) * @version : 2020-03-31 */ @Singleton public class CompareUdfSource implements UdfSourceAssembly { /** 比较两个字符串 */ public static int compareString(String str1, String str2) { str1 = str1 == null ? "" : str1; str2 = str2 == null ? "" : str2; return str1.compareTo(str2); } /** 比较两个字符串 */ public static int compareStringIgnoreCase(String str1, String str2) { str1 = str1 == null ? "" : str1; str2 = str2 == null ? "" : str2; return str1.compareToIgnoreCase(str2); } // /** 比较两个数字 */ // public static int compareNumber(Number num1, Number num2) { // num1 = num1 == null ? 0 : num1; // num2 = num2 == null ? 0 : num2; // return num1 > num2; // } }
lambertlb/ElectronicBattleMat
src/main/java/per/serverApp/ServerApp.java
<filename>src/main/java/per/serverApp/ServerApp.java<gh_stars>0 /* * Copyright (C) 2019 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package per.serverApp; import java.io.File; import java.net.InetAddress; import java.net.UnknownHostException; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.webapp.WebAppContext; /** * Application so client can run Jetty server locally to DM a session. * * @author LLambert * */ public final class ServerApp { /** * Constructor. */ private ServerApp() { } /** * Main entry point. * * @param args arguments * @throws Exception if error. */ public static void main(final String[] args) throws Exception { buildWelcome(); File tempDir = new File("./ElectronicBattleMatTemp"); Server server = new Server(8088); WebAppContext webAppContext = new WebAppContext(); webAppContext.setContextPath("/"); if (!tempDir.exists()) { webAppContext.setWar("./ElectronicBattleMat.war"); webAppContext.setTempDirectory(new File("./ElectronicBattleMatTemp")); } else { // use existing directory so war does not overwrite any dungeon changes we made. webAppContext.setDescriptor("./ElectronicBattleMatTemp/webapp/WEB-INF/web.xml"); webAppContext.setResourceBase("./ElectronicBattleMatTemp/webapp"); webAppContext.setTempDirectory(new File("./ElectronicBattleMatTemp2")); } webAppContext.setParentLoaderPriority(true); webAppContext.setServer(server); webAppContext.setClassLoader(ClassLoader.getSystemClassLoader()); server.setHandler(webAppContext); server.start(); } /** * Show pre-amble to user. */ private static void buildWelcome() { String ipAddress = getIpAddress(); if (ipAddress == null) { System.out.println("No ip address found."); System.out.println("Must have network card to run this program."); return; } System.out.println("Enter the following URL to access dungeons"); System.out.println("http://" + ipAddress + ":8088"); System.out.println(""); System.out.println(""); } /** * Get ip address of machine. * * @return address of machine. */ private static String getIpAddress() { InetAddress ip; try { ip = InetAddress.getLocalHost(); } catch (UnknownHostException e) { return (null); } return (ip.getHostAddress()); } }
hxhxhx88/futuquant
futuquant/testcase/person/eva/pressure_test/opend_pressure/sub_aType.py
#-*-coding:utf-8-*- import futuquant from evatest.pressure_test.opend_pressure.quotation_handler import * from evatest.utils.logUtil import Logs from evatest.datas.collect_stock import * import time class SubAType(object): ''' 压测:同时订阅500只股票的一种实时数据 ''' subTypes = [SubType.QUOTE, SubType.ORDER_BOOK, SubType.TICKER, SubType.RT_DATA, SubType.BROKER, SubType.K_1M,SubType.K_5M,SubType.K_15M, SubType.K_30M, SubType.K_60M, SubType.K_DAY, SubType.K_WEEK, SubType.K_MON] # def __init__(self): timestamp = (int)(time.time()) self.dir = 'SubAType_' + str(timestamp) self.logger = Logs().getNewLogger('sub', self.dir) def sub(self, codes,subType,port): #行情上下文实例 quote_ctx = futuquant.OpenQuoteContext(host='127.0.0.1', port= port) quote_ctx.start() # 判断监听类型 subType_index = SubAType.subTypes.index(subType) print('subType_index = %s'%subType_index) handler = None if subType_index is SubAType.subTypes.index(SubType.QUOTE): handler = StockQuoteTest() elif subType_index is SubAType.subTypes.index(SubType.ORDER_BOOK): handler = OrderBookTest() elif subType_index is SubAType.subTypes.index(SubType.TICKER): handler = TickerTest() elif subType_index is SubAType.subTypes.index(SubType.RT_DATA): handler = RTDataTest() elif subType_index is SubAType.subTypes.index(SubType.BROKER): handler = BrokerTest() else: handler = CurKlineTest() # 设置监听 handler.set_loggerDir(self.dir) quote_ctx.set_handler(handler) # 触发订阅 ret_code_sub, ret_data_sub = quote_ctx.subscribe(codes, subType) print(quote_ctx.query_subscription()) #记录订阅结果 self.logger.info('subType = '+subType+' ret_code_sub = ' + str(ret_code_sub) + ' ret_data_sub = ' + str(ret_data_sub)) return ret_code_sub if __name__ == '__main__': port = 11111 codes = get_codes_cvs()[:250] # sat = SubAType() # sat.sub(codes, SubType.K_WEEK, port) for subType in SubAType.subTypes: port += 1 sat.sub(codes, subType, port)
gallowstree/ArduinoMazeNavV2
src/BarProject/EventLogger.h
<gh_stars>0 #ifndef MYARDUINOPROJECT_EVENTLOGGER_H #define MYARDUINOPROJECT_EVENTLOGGER_H #include "Tile.h" #include "TCPClient.h" #include <Arduino.h> class EventLogger { public: static void discoveredTile(Tile * tile); static void updateLocation(int facing, int row, int col); static void genericLog(float angle); static String host; static int port; private: static TCPClient client; }; #endif
dianed-square/connect-nodejs-sdk
test/model/LoyaltyProgramAccrualRule.spec.js
/** * Square Connect API * Client library for accessing the Square Connect APIs * * OpenAPI spec version: 2.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * * Swagger Codegen version: 2.3.0-SNAPSHOT * */ const SquareConnect = require('../../src/index'); describe('LoyaltyProgramAccrualRule', function() { beforeEach(function() { this.api = new SquareConnect.LoyaltyProgramAccrualRule(); }); it('should create an instance of LoyaltyProgramAccrualRule', function() { // uncomment below and update the code to test LoyaltyProgramAccrualRule //var instane = new SquareConnect.LoyaltyProgramAccrualRule(); //expect(instance).to.be.a(SquareConnect.LoyaltyProgramAccrualRule); }); it('should have the property accrualType (base name: "accrual_type")', function() { // uncomment below and update the code to test the property accrualType //var instane = new SquareConnect.LoyaltyProgramAccrualRule(); //expect(instance).to.be(); }); it('should have the property points (base name: "points")', function() { // uncomment below and update the code to test the property points //var instane = new SquareConnect.LoyaltyProgramAccrualRule(); //expect(instance).to.be(); }); it('should have the property visitMinimumAmountMoney (base name: "visit_minimum_amount_money")', function() { // uncomment below and update the code to test the property visitMinimumAmountMoney //var instane = new SquareConnect.LoyaltyProgramAccrualRule(); //expect(instance).to.be(); }); it('should have the property spendAmountMoney (base name: "spend_amount_money")', function() { // uncomment below and update the code to test the property spendAmountMoney //var instane = new SquareConnect.LoyaltyProgramAccrualRule(); //expect(instance).to.be(); }); it('should have the property catalogObjectId (base name: "catalog_object_id")', function() { // uncomment below and update the code to test the property catalogObjectId //var instane = new SquareConnect.LoyaltyProgramAccrualRule(); //expect(instance).to.be(); }); });
impedimentToProgress/UCI-BlueChip
snapgear_linux/user/ntp/ntpd/refclock_shm.c
/* * refclock_shm - clock driver for utc via shared memory * - under construction - * To add new modes: Extend or union the shmTime-struct. Do not * extend/shrink size, because otherwise existing implementations * will specify wrong size of shared memory-segment * PB 18.3.97 */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #if defined(REFCLOCK) && defined(CLOCK_SHM) #include "ntpd.h" #undef fileno #include "ntp_io.h" #undef fileno #include "ntp_refclock.h" #undef fileno #include "ntp_unixtime.h" #undef fileno #include "ntp_stdlib.h" #undef fileno #include <ctype.h> #undef fileno #ifndef SYS_WINNT # include <sys/ipc.h> # include <sys/shm.h> # include <assert.h> # include <unistd.h> # include <stdio.h> #endif /* * This driver supports a reference clock attached thru shared memory */ /* * SHM interface definitions */ #define PRECISION (-1) /* precision assumed (0.5 s) */ #define REFID "SHM" /* reference ID */ #define DESCRIPTION "SHM/Shared memory interface" #define NSAMPLES 3 /* stages of median filter */ /* * Function prototypes */ static int shm_start (int, struct peer *); static void shm_shutdown (int, struct peer *); static void shm_poll (int unit, struct peer *); /* * Transfer vector */ struct refclock refclock_shm = { shm_start, /* start up driver */ shm_shutdown, /* shut down driver */ shm_poll, /* transmit poll message */ noentry, /* not used */ noentry, /* initialize driver (not used) */ noentry, /* not used */ NOFLAGS /* not used */ }; struct shmTime { int mode; /* 0 - if valid set * use values, * clear valid * 1 - if valid set * if count before and after read of values is equal, * use values * clear valid */ int count; time_t clockTimeStampSec; int clockTimeStampUSec; time_t receiveTimeStampSec; int receiveTimeStampUSec; int leap; int precision; int nsamples; int valid; int dummy[10]; }; struct shmTime *getShmTime (int unit) { #ifndef SYS_WINNT int shmid=0; assert (unit<10); /* MAXUNIT is 4, so should never happen */ shmid=shmget (0x4e545030+unit, sizeof (struct shmTime), IPC_CREAT|(unit<2?0700:0777)); if (shmid==-1) { /*error */ msyslog(LOG_ERR,"SHM shmget (unit %d): %s",unit,strerror(errno)); return 0; } else { /* no error */ struct shmTime *p=(struct shmTime *)shmat (shmid, 0, 0); if ((int)(long)p==-1) { /* error */ msyslog(LOG_ERR,"SHM shmat (unit %d): %s",unit,strerror(errno)); return 0; } return p; } #else char buf[10]; LPSECURITY_ATTRIBUTES psec=0; HANDLE shmid=0; SECURITY_DESCRIPTOR sd; SECURITY_ATTRIBUTES sa; sprintf (buf,"NTP%d",unit); if (unit>=2) { /* world access */ if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) { msyslog(LOG_ERR,"SHM InitializeSecurityDescriptor (unit %d): %m",unit); return 0; } if (!SetSecurityDescriptorDacl(&sd,1,0,0)) { msyslog(LOG_ERR,"SHM SetSecurityDescriptorDacl (unit %d): %m",unit); return 0; } sa.nLength=sizeof (SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor=&sd; sa.bInheritHandle=0; psec=&sa; } shmid=CreateFileMapping ((HANDLE)0xffffffff, psec, PAGE_READWRITE, 0, sizeof (struct shmTime),buf); if (!shmid) { /*error*/ char buf[1000]; FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError (), 0, buf, sizeof (buf), 0); msyslog(LOG_ERR,"SHM CreateFileMapping (unit %d): %s",unit,buf); return 0; } else { struct shmTime *p=(struct shmTime *) MapViewOfFile (shmid, FILE_MAP_WRITE, 0, 0, sizeof (struct shmTime)); if (p==0) { /*error*/ char buf[1000]; FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError (), 0, buf, sizeof (buf), 0); msyslog(LOG_ERR,"SHM MapViewOfFile (unit %d): %s",unit,buf); return 0; } return p; } #endif return 0; } /* * shm_start - attach to shared memory */ static int shm_start( int unit, struct peer *peer ) { struct refclockproc *pp; pp = peer->procptr; pp->io.clock_recv = noentry; pp->io.srcclock = (caddr_t)peer; pp->io.datalen = 0; pp->io.fd = -1; pp->unitptr = (caddr_t)getShmTime(unit); /* * Initialize miscellaneous peer variables */ memcpy((char *)&pp->refid, REFID, 4); if (pp->unitptr!=0) { ((struct shmTime*)pp->unitptr)->precision=PRECISION; peer->precision = ((struct shmTime*)pp->unitptr)->precision; ((struct shmTime*)pp->unitptr)->valid=0; ((struct shmTime*)pp->unitptr)->nsamples=NSAMPLES; pp->clockdesc = DESCRIPTION; return (1); } else { return 0; } } /* * shm_shutdown - shut down the clock */ static void shm_shutdown( int unit, struct peer *peer ) { register struct shmTime *up; struct refclockproc *pp; pp = peer->procptr; up = (struct shmTime *)pp->unitptr; #ifndef SYS_WINNT shmdt (up); #else UnmapViewOfFile (up); #endif } /* * shm_poll - called by the transmit procedure */ static void shm_poll( int unit, struct peer *peer ) { register struct shmTime *up; struct refclockproc *pp; /* * This is the main routine. It snatches the time from the shm * board and tacks on a local timestamp. */ pp = peer->procptr; up = (struct shmTime*)pp->unitptr; if (up==0) { /* try to map again - this may succeed if meanwhile some- body has ipcrm'ed the old (unaccessible) shared mem segment */ pp->unitptr = (caddr_t)getShmTime(unit); up = (struct shmTime*)pp->unitptr; } if (up==0) { refclock_report(peer, CEVNT_FAULT); return; } if (up->valid) { struct timeval tvr; struct timeval tvt; struct tm *t; int ok=1; switch (up->mode) { case 0: { tvr.tv_sec=up->receiveTimeStampSec; tvr.tv_usec=up->receiveTimeStampUSec; tvt.tv_sec=up->clockTimeStampSec; tvt.tv_usec=up->clockTimeStampUSec; } break; case 1: { int cnt=up->count; tvr.tv_sec=up->receiveTimeStampSec; tvr.tv_usec=up->receiveTimeStampUSec; tvt.tv_sec=up->clockTimeStampSec; tvt.tv_usec=up->clockTimeStampUSec; ok=(cnt==up->count); } break; default: msyslog (LOG_ERR, "SHM: bad mode found in shared memory: %d",up->mode); } up->valid=0; if (ok) { TVTOTS(&tvr,&pp->lastrec); pp->lastrec.l_ui += JAN_1970; /* pp->lasttime = current_time; */ pp->polls++; t=gmtime (&tvt.tv_sec); pp->day=t->tm_yday+1; pp->hour=t->tm_hour; pp->minute=t->tm_min; pp->second=t->tm_sec; pp->msec=0; pp->usec=tvt.tv_usec; peer->precision=up->precision; pp->leap=up->leap; } else { refclock_report(peer, CEVNT_FAULT); msyslog (LOG_NOTICE, "SHM: access clash in shared memory"); return; } } else { refclock_report(peer, CEVNT_TIMEOUT); msyslog (LOG_NOTICE, "SHM: no new value found in shared memory"); return; } if (!refclock_process(pp)) { refclock_report(peer, CEVNT_BADTIME); return; } refclock_receive(peer); } #else int refclock_shm_bs; #endif /* REFCLOCK */
monciego/TypeScript
tests/baselines/reference/requireOfESWithPropertyAccess.js
<reponame>monciego/TypeScript //// [tests/cases/conformance/salsa/requireOfESWithPropertyAccess.ts] //// //// [main.js] const x = require('./ch').x x x.grey x.x.grey //// [ch.js] const x = { grey: {} } export { x } //// [ch.js] "use strict"; exports.__esModule = true; exports.x = void 0; var x = { grey: {} }; exports.x = x; //// [main.js] "use strict"; var x = require('./ch').x; x; x.grey; x.x.grey; //// [ch.d.ts] export namespace x { const grey: {}; } //// [main.d.ts] export {};
fossabot/jymfony
src/Component/DependencyInjection/src/Compiler/ResolveInjectDecoratorPass.js
<reponame>fossabot/jymfony import { Inject, Parameter } from '@jymfony/decorators' optional; const AbstractRecursivePass = Jymfony.Component.DependencyInjection.Compiler.AbstractRecursivePass; const Definition = Jymfony.Component.DependencyInjection.Definition; const DIParameter = Jymfony.Component.DependencyInjection.Parameter; const Reference = Jymfony.Component.DependencyInjection.Reference; /** * @memberOf Jymfony.Component.DependencyInjection.Compiler */ export default class ResolveInjectDecoratorPass extends AbstractRecursivePass { process(container) { if (undefined === Inject || undefined === Parameter) { // @jymfony/decorators is not installed. return; } super.process(container); } /** * @inheritdoc */ _processValue(value, isRoot = false) { if (! (value instanceof Definition)) { return super._processValue(value, isRoot); } const class_ = value.getClass(); if (! ReflectionClass.exists(class_)) { return value; } const reflClass = new ReflectionClass(class_); for (const field of reflClass.fields) { const reflField = reflClass.getField(field); for (const [ , annotation ] of reflField.metadata) { if (annotation instanceof Inject) { value.addProperty(field, new Reference(annotation.serviceId, annotation.invalidBehavior)); } else if (annotation instanceof Parameter) { value.addProperty(field, new DIParameter(annotation.parameterName)); } } } for (const property of reflClass.properties) { if (! reflClass.hasWritableProperty(property)) { continue; } const reflProperty = reflClass.getWritableProperty(property); for (const [ , annotation ] of reflProperty.metadata) { if (annotation instanceof Inject) { value.addProperty(property, new Reference(annotation.serviceId, annotation.invalidBehavior)); } else if (annotation instanceof Parameter) { value.addProperty(property, new DIParameter(annotation.parameterName)); } } } return value; } }
jiujieti/elvish
pkg/edit/state_api.go
package edit import ( "src.elv.sh/pkg/cli" "src.elv.sh/pkg/eval" "src.elv.sh/pkg/eval/vals" "src.elv.sh/pkg/eval/vars" ) //elvdoc:fn insert-at-dot // // ```elvish // edit:insert-at-dot $text // ``` // // Inserts the given text at the dot, moving the dot after the newly // inserted text. func insertAtDot(app cli.App, text string) { app.CodeArea().MutateState(func(s *cli.CodeAreaState) { s.Buffer.InsertAtDot(text) }) } //elvdoc:fn replace-input // // ```elvish // edit:replace-input $text // ``` // // Equivalent to assigning `$text` to `$edit:current-command`. func replaceInput(app cli.App, text string) { cli.SetCodeBuffer(app, cli.CodeBuffer{Content: text, Dot: len(text)}) } //elvdoc:var -dot // // Contains the current position of the cursor, as a byte position within // `$edit:current-command`. //elvdoc:var current-command // // Contains the content of the current input. Setting the variable will // cause the cursor to move to the very end, as if `edit-dot = (count // $edit:current-command)` has been invoked. // // This API is subject to change. func initStateAPI(app cli.App, nb eval.NsBuilder) { nb.AddGoFns("<edit>", map[string]interface{}{ "insert-at-dot": func(s string) { insertAtDot(app, s) }, "replace-input": func(s string) { replaceInput(app, s) }, }) setDot := func(v interface{}) error { var dot int err := vals.ScanToGo(v, &dot) if err != nil { return err } app.CodeArea().MutateState(func(s *cli.CodeAreaState) { s.Buffer.Dot = dot }) return nil } getDot := func() interface{} { return vals.FromGo(app.CodeArea().CopyState().Buffer.Dot) } nb.Add("-dot", vars.FromSetGet(setDot, getDot)) setCurrentCommand := func(v interface{}) error { var content string err := vals.ScanToGo(v, &content) if err != nil { return err } replaceInput(app, content) return nil } getCurrentCommand := func() interface{} { return vals.FromGo(cli.GetCodeBuffer(app).Content) } nb.Add("current-command", vars.FromSetGet(setCurrentCommand, getCurrentCommand)) }
Deepak5310/packages_apps_Settings
src/com/android/settings/development/storage/SharedDataPreferenceController.java
/* * Copyright (C) 2020 The Android Open Source Project * * 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.android.settings.development.storage; import android.app.blob.BlobStoreManager; import android.content.Context; import android.os.UserHandle; import android.util.Log; import androidx.preference.Preference; import com.android.settings.R; import com.android.settings.core.PreferenceControllerMixin; import com.android.settingslib.development.DeveloperOptionsPreferenceController; import java.io.IOException; public class SharedDataPreferenceController extends DeveloperOptionsPreferenceController implements PreferenceControllerMixin { private static final String TAG = "SharedDataPrefCtrl"; private static final String SHARED_DATA = "shared_data"; private BlobStoreManager mBlobStoreManager; public SharedDataPreferenceController(Context context) { super(context); mBlobStoreManager = (BlobStoreManager) context.getSystemService(BlobStoreManager.class); } @Override public String getPreferenceKey() { return SHARED_DATA; } @Override public void updateState(Preference preference) { try { final boolean showPref = mBlobStoreManager != null && !mBlobStoreManager.queryBlobsForUser(UserHandle.CURRENT).isEmpty(); preference.setEnabled(showPref); preference.setSummary(showPref ? R.string.shared_data_summary : R.string.shared_data_no_blobs_text); } catch (IOException e) { Log.e(TAG, "Unable to fetch blobs for current user: " + e.getMessage()); preference.setEnabled(false); preference.setSummary(R.string.shared_data_no_blobs_text); } } }
Angold-4/OSDI
Minix3/servers/vfs/device.c
/* When a needed block is not in the cache, it must be fetched from the disk. * Special character files also require I/O. The routines for these are here. * * The entry points in this file are: * dev_open: FS opens a device * dev_close: FS closes a device * dev_io: FS does a read or write on a device * dev_status: FS processes callback request alert * gen_opcl: generic call to a task to perform an open/close * gen_io: generic call to a task to perform an I/O operation * no_dev: open/close processing for devices that don't exist * no_dev_io: i/o processing for devices that don't exist * tty_opcl: perform tty-specific processing for open/close * ctty_opcl: perform controlling-tty-specific processing for open/close * ctty_io: perform controlling-tty-specific processing for I/O * do_ioctl: perform the IOCTL system call * do_setsid: perform the SETSID system call (FS side) */ #include "fs.h" #include <fcntl.h> #include <assert.h> #include <minix/callnr.h> #include <minix/com.h> #include <minix/endpoint.h> #include <minix/ioctl.h> #include <minix/u64.h> #include "file.h" #include "fproc.h" #include <minix/vfsif.h> #include "vnode.h" #include "vmnt.h" #include "param.h" #define ELEMENTS(a) (sizeof(a)/sizeof((a)[0])) FORWARD _PROTOTYPE( int safe_io_conversion, (endpoint_t, cp_grant_id_t *, int *, cp_grant_id_t *, int, endpoint_t *, void **, int *, vir_bytes, u32_t *)); FORWARD _PROTOTYPE( void safe_io_cleanup, (cp_grant_id_t, cp_grant_id_t *, int)); FORWARD _PROTOTYPE( void restart_reopen, (int maj) ); extern int dmap_size; PRIVATE int dummyproc; /*===========================================================================* * dev_open * *===========================================================================*/ PUBLIC int dev_open(dev, proc, flags) dev_t dev; /* device to open */ int proc; /* process to open for */ int flags; /* mode bits and flags */ { int major, r; struct dmap *dp; /* Determine the major device number call the device class specific * open/close routine. (This is the only routine that must check the * device number for being in range. All others can trust this check.) */ major = (dev >> MAJOR) & BYTE; if (major >= NR_DEVICES) major = 0; dp = &dmap[major]; if (dp->dmap_driver == NONE) return ENXIO; r = (*dp->dmap_opcl)(DEV_OPEN, dev, proc, flags); return(r); } /*===========================================================================* * dev_reopen * *===========================================================================*/ PUBLIC int dev_reopen(dev, filp_no, flags) dev_t dev; /* device to open */ int filp_no; /* filp to reopen for */ int flags; /* mode bits and flags */ { int major, r; struct dmap *dp; /* Determine the major device number call the device class specific * open/close routine. (This is the only routine that must check the * device number for being in range. All others can trust this check.) */ major = (dev >> MAJOR) & BYTE; if (major >= NR_DEVICES) major = 0; dp = &dmap[major]; if (dp->dmap_driver == NONE) return ENXIO; r = (*dp->dmap_opcl)(DEV_REOPEN, dev, filp_no, flags); if (r == OK) panic(__FILE__,"OK on reopen from", dp->dmap_driver); if (r == SUSPEND) r= OK; return(r); } /*===========================================================================* * dev_close * *===========================================================================*/ PUBLIC int dev_close(dev, filp_no) dev_t dev; /* device to close */ int filp_no; { int r; /* See if driver is roughly valid. */ if (dmap[(dev >> MAJOR)].dmap_driver == NONE) { return ENXIO; } r= (*dmap[(dev >> MAJOR) & BYTE].dmap_opcl)(DEV_CLOSE, dev, filp_no, 0); return r; } /*===========================================================================* * suspended_ep * *===========================================================================*/ endpoint_t suspended_ep(endpoint_t driver, cp_grant_id_t g) { /* A process is suspended on a driver for which FS issued * a grant. Find out which process it was. */ struct fproc *rfp; for (rfp = &fproc[0]; rfp < &fproc[NR_PROCS]; rfp++) { if(rfp->fp_pid == PID_FREE) continue; if(rfp->fp_blocked_on == FP_BLOCKED_ON_OTHER && rfp->fp_task == driver && rfp->fp_grant == g) { return rfp->fp_endpoint; } } return NONE; } /*===========================================================================* * dev_status * *===========================================================================*/ PUBLIC void dev_status(message *m) { message st; int d, get_more = 1; endpoint_t endpt; for(d = 0; d < NR_DEVICES; d++) if (dmap[d].dmap_driver != NONE && dmap[d].dmap_driver == m->m_source) break; if (d >= NR_DEVICES) return; if (dmap[d].dmap_async_driver) { printf( "dev_status: not doing dev_status for async driver %d\n", m->m_source); return; } do { int r; st.m_type = DEV_STATUS; if ((r=sendrec(m->m_source, &st)) != OK) { printf("DEV_STATUS failed to %d: %d\n", m->m_source, r); if (r == EDEADSRCDST) return; if (r == EDSTDIED) return; if (r == ESRCDIED) return; panic(__FILE__,"couldn't sendrec for DEV_STATUS", r); } switch(st.m_type) { case DEV_REVIVE: endpt = st.REP_ENDPT; if(endpt == FS_PROC_NR) { endpt = suspended_ep(m->m_source, st.REP_IO_GRANT); if(endpt == NONE) { printf("FS: proc with " "grant %d from %d not found (revive)\n", st.REP_IO_GRANT, st.m_source); continue; } } revive(endpt, st.REP_STATUS); break; case DEV_IO_READY: select_notified(d, st.DEV_MINOR, st.DEV_SEL_OPS); break; default: printf("FS: unrecognized reply %d to " "DEV_STATUS\n", st.m_type); /* Fall through. */ case DEV_NO_STATUS: get_more = 0; break; } } while(get_more); return; } /*===========================================================================* * safe_io_conversion * *===========================================================================*/ PRIVATE int safe_io_conversion(driver, gid, op, gids, gids_size, io_ept, buf, vec_grants, bytes, pos_lo) endpoint_t driver; cp_grant_id_t *gid; int *op; cp_grant_id_t *gids; int gids_size; endpoint_t *io_ept; void **buf; int *vec_grants; vir_bytes bytes; u32_t *pos_lo; { int access = 0, size; int j; iovec_t *v; static iovec_t new_iovec[NR_IOREQS]; /* Number of grants allocated in vector I/O. */ *vec_grants = 0; /* Driver can handle it - change request to a safe one. */ *gid = GRANT_INVALID; switch(*op) { case VFS_DEV_READ: case VFS_DEV_WRITE: /* Change to safe op. */ *op = *op == VFS_DEV_READ ? DEV_READ_S : DEV_WRITE_S; if((*gid=cpf_grant_magic(driver, *io_ept, (vir_bytes) *buf, bytes, *op == DEV_READ_S ? CPF_WRITE : CPF_READ)) < 0) { panic(__FILE__, "cpf_grant_magic of buffer failed\n", NO_NUM); } break; case VFS_DEV_GATHER: case VFS_DEV_SCATTER: /* Change to safe op. */ *op = *op == VFS_DEV_GATHER ? DEV_GATHER_S : DEV_SCATTER_S; /* Grant access to my new i/o vector. */ if((*gid = cpf_grant_direct(driver, (vir_bytes) new_iovec, bytes * sizeof(iovec_t), CPF_READ | CPF_WRITE)) < 0) { panic(__FILE__, "cpf_grant_direct of vector failed", NO_NUM); } v = (iovec_t *) *buf; /* Grant access to i/o buffers. */ for(j = 0; j < bytes; j++) { if(j >= NR_IOREQS) panic(__FILE__, "vec too big", bytes); new_iovec[j].iov_addr = gids[j] = cpf_grant_direct(driver, (vir_bytes) v[j].iov_addr, v[j].iov_size, *op == DEV_GATHER_S ? CPF_WRITE : CPF_READ); if(!GRANT_VALID(gids[j])) { panic(__FILE__, "grant to iovec buf failed", NO_NUM); } new_iovec[j].iov_size = v[j].iov_size; (*vec_grants)++; } /* Set user's vector to the new one. */ *buf = new_iovec; break; case VFS_DEV_IOCTL: *pos_lo = *io_ept; /* Old endpoint in POSITION field. */ *op = DEV_IOCTL_S; if(_MINIX_IOCTL_IOR(m_in.REQUEST)) access |= CPF_WRITE; if(_MINIX_IOCTL_IOW(m_in.REQUEST)) access |= CPF_READ; if(_MINIX_IOCTL_BIG(m_in.REQUEST)) size = _MINIX_IOCTL_SIZE_BIG(m_in.REQUEST); else size = _MINIX_IOCTL_SIZE(m_in.REQUEST); /* Do this even if no I/O happens with the ioctl, in * order to disambiguate requests with DEV_IOCTL_S. */ if((*gid=cpf_grant_magic(driver, *io_ept, (vir_bytes) *buf, size, access)) < 0) { panic(__FILE__, "cpf_grant_magic failed (ioctl)\n", NO_NUM); } break; case VFS_DEV_SELECT: *op = DEV_SELECT; break; default: panic(__FILE__,"safe_io_conversion: unknown operation", *op); } /* If we have converted to a safe operation, I/O * endpoint becomes FS if it wasn't already. */ if(GRANT_VALID(*gid)) { *io_ept = FS_PROC_NR; return 1; } /* Not converted to a safe operation (because there is no * copying involved in this operation). */ return 0; } /*===========================================================================* * safe_io_cleanup * *===========================================================================*/ PRIVATE void safe_io_cleanup(gid, gids, gids_size) cp_grant_id_t gid; cp_grant_id_t *gids; int gids_size; { /* Free resources (specifically, grants) allocated by safe_io_conversion(). */ int j; cpf_revoke(gid); for(j = 0; j < gids_size; j++) cpf_revoke(gids[j]); return; } /*===========================================================================* * dev_io * *===========================================================================*/ PUBLIC int dev_io(op, dev, proc_e, buf, pos, bytes, flags, suspend_reopen) int op; /* DEV_READ, DEV_WRITE, DEV_IOCTL, etc. */ dev_t dev; /* major-minor device number */ int proc_e; /* in whose address space is buf? */ void *buf; /* virtual address of the buffer */ u64_t pos; /* byte position */ int bytes; /* how many bytes to transfer */ int flags; /* special flags, like O_NONBLOCK */ int suspend_reopen; /* Just suspend the process */ { /* Read or write from a device. The parameter 'dev' tells which one. */ struct dmap *dp; u32_t pos_lo, pos_high; message dev_mess; cp_grant_id_t gid = GRANT_INVALID; static cp_grant_id_t gids[NR_IOREQS]; int vec_grants = 0, orig_op, safe; void *buf_used; endpoint_t ioproc; pos_lo= ex64lo(pos); pos_high= ex64hi(pos); /* Determine task dmap. */ dp = &dmap[(dev >> MAJOR) & BYTE]; orig_op = op; /* See if driver is roughly valid. */ if (dp->dmap_driver == NONE) { printf("FS: dev_io: no driver for dev %x\n", dev); return ENXIO; } if (suspend_reopen) { /* Suspend user. */ fp->fp_grant = GRANT_INVALID; fp->fp_ioproc = NONE; wait_for(dp->dmap_driver); fp->fp_flags |= SUSP_REOPEN; return(SUSPEND); } if(isokendpt(dp->dmap_driver, &dummyproc) != OK) { printf("FS: dev_io: old driver for dev %x (%d)\n", dev, dp->dmap_driver); return ENXIO; } /* By default, these are right. */ dev_mess.IO_ENDPT = proc_e; dev_mess.ADDRESS = buf; /* Convert DEV_* to DEV_*_S variants. */ buf_used = buf; safe = safe_io_conversion(dp->dmap_driver, &gid, &op, gids, NR_IOREQS, (endpoint_t*) &dev_mess.IO_ENDPT, &buf_used, &vec_grants, bytes, &pos_lo); if(buf != buf_used) panic(__FILE__,"dev_io: safe_io_conversion changed buffer", NO_NUM); /* If the safe conversion was done, set the ADDRESS to * the grant id. */ if(safe) dev_mess.IO_GRANT = (char *) gid; /* Set up the rest of the message passed to task. */ dev_mess.m_type = op; dev_mess.DEVICE = (dev >> MINOR) & BYTE; dev_mess.POSITION = pos_lo; dev_mess.COUNT = bytes; dev_mess.HIGHPOS = pos_high; /* This will be used if the i/o is suspended. */ ioproc = dev_mess.IO_ENDPT; /* Call the task. */ (*dp->dmap_io)(dp->dmap_driver, &dev_mess); if(dp->dmap_driver == NONE) { /* Driver has vanished. */ printf("Driver gone?\n"); if(safe) safe_io_cleanup(gid, gids, vec_grants); return EIO; } /* Task has completed. See if call completed. */ if (dev_mess.REP_STATUS == SUSPEND) { if(vec_grants > 0) { panic(__FILE__,"SUSPEND on vectored i/o", NO_NUM); } /* fp is uninitialized at init time. */ if(!fp) panic(__FILE__,"SUSPEND on NULL fp", NO_NUM); if ((flags & O_NONBLOCK) && !dp->dmap_async_driver) { /* Not supposed to block. */ dev_mess.m_type = CANCEL; dev_mess.IO_ENDPT = ioproc; dev_mess.IO_GRANT = (char *) gid; /* This R_BIT/W_BIT check taken from suspend()/unpause() * logic. Mode is expected in the COUNT field. */ dev_mess.COUNT = 0; if(call_nr == READ) dev_mess.COUNT = R_BIT; else if(call_nr == WRITE) dev_mess.COUNT = W_BIT; dev_mess.DEVICE = (dev >> MINOR) & BYTE; (*dp->dmap_io)(dp->dmap_driver, &dev_mess); if (dev_mess.REP_STATUS == EINTR) dev_mess.REP_STATUS = EAGAIN; } else { /* select() will do suspending itself. */ if(op != DEV_SELECT) { /* Suspend user. */ wait_for(dp->dmap_driver); } assert(!GRANT_VALID(fp->fp_grant)); fp->fp_grant = gid; /* revoke this when unsuspended. */ fp->fp_ioproc = ioproc; if (flags & O_NONBLOCK) { /* Not supposed to block, send cancel message */ dev_mess.m_type = CANCEL; dev_mess.IO_ENDPT = ioproc; dev_mess.IO_GRANT = (char *) gid; /* This R_BIT/W_BIT check taken from suspend()/unpause() * logic. Mode is expected in the COUNT field. */ dev_mess.COUNT = 0; if(call_nr == READ) dev_mess.COUNT = R_BIT; else if(call_nr == WRITE) dev_mess.COUNT = W_BIT; dev_mess.DEVICE = (dev >> MINOR) & BYTE; (*dp->dmap_io)(dp->dmap_driver, &dev_mess); /* Should do something about EINTR -> EAGAIN mapping */ } return(SUSPEND); } } /* No suspend, or cancelled suspend, so I/O is over and can be cleaned up. */ if(safe) safe_io_cleanup(gid, gids, vec_grants); return(dev_mess.REP_STATUS); } /*===========================================================================* * gen_opcl * *===========================================================================*/ PUBLIC int gen_opcl(op, dev, proc_e, flags) int op; /* operation, DEV_OPEN or DEV_CLOSE */ dev_t dev; /* device to open or close */ int proc_e; /* process to open/close for */ int flags; /* mode bits and flags */ { /* Called from the dmap struct in table.c on opens & closes of special files.*/ int r; struct dmap *dp; message dev_mess; /* Determine task dmap. */ dp = &dmap[(dev >> MAJOR) & BYTE]; dev_mess.m_type = op; dev_mess.DEVICE = (dev >> MINOR) & BYTE; dev_mess.IO_ENDPT = proc_e; dev_mess.COUNT = flags; if (dp->dmap_driver == NONE) { printf("FS: gen_opcl: no driver for dev %x\n", dev); return ENXIO; } /* Call the task. */ r= (*dp->dmap_io)(dp->dmap_driver, &dev_mess); if (r != OK) return r; return(dev_mess.REP_STATUS); } /*===========================================================================* * tty_opcl * *===========================================================================*/ PUBLIC int tty_opcl(op, dev, proc_e, flags) int op; /* operation, DEV_OPEN or DEV_CLOSE */ dev_t dev; /* device to open or close */ int proc_e; /* process to open/close for */ int flags; /* mode bits and flags */ { /* This procedure is called from the dmap struct on tty open/close. */ int r; register struct fproc *rfp; /* Add O_NOCTTY to the flags if this process is not a session leader, or * if it already has a controlling tty, or if it is someone elses * controlling tty. */ if (!fp->fp_sesldr || fp->fp_tty != 0) { flags |= O_NOCTTY; } else { for (rfp = &fproc[0]; rfp < &fproc[NR_PROCS]; rfp++) { if(rfp->fp_pid == PID_FREE) continue; if (rfp->fp_tty == dev) flags |= O_NOCTTY; } } r = gen_opcl(op, dev, proc_e, flags); /* Did this call make the tty the controlling tty? */ if (r == 1) { fp->fp_tty = dev; r = OK; } return(r); } /*===========================================================================* * ctty_opcl * *===========================================================================*/ PUBLIC int ctty_opcl(op, dev, proc_e, flags) int op; /* operation, DEV_OPEN or DEV_CLOSE */ dev_t dev; /* device to open or close */ int proc_e; /* process to open/close for */ int flags; /* mode bits and flags */ { /* This procedure is called from the dmap struct in table.c on opening/closing * /dev/tty, the magic device that translates to the controlling tty. */ return(fp->fp_tty == 0 ? ENXIO : OK); } /*===========================================================================* * pm_setsid * *===========================================================================*/ PUBLIC void pm_setsid(proc_e) int proc_e; { /* Perform the FS side of the SETSID call, i.e. get rid of the controlling * terminal of a process, and make the process a session leader. */ register struct fproc *rfp; int slot; /* Make the process a session leader with no controlling tty. */ okendpt(proc_e, &slot); rfp = &fproc[slot]; rfp->fp_sesldr = TRUE; rfp->fp_tty = 0; } /*===========================================================================* * do_ioctl * *===========================================================================*/ PUBLIC int do_ioctl() { /* Perform the ioctl(ls_fd, request, argx) system call (uses m2 fmt). */ int suspend_reopen; struct filp *f; register struct vnode *vp; dev_t dev; if ( (f = get_filp(m_in.ls_fd)) == NIL_FILP) return(err_code); vp = f->filp_vno; /* get vnode pointer */ if ( (vp->v_mode & I_TYPE) != I_CHAR_SPECIAL && (vp->v_mode & I_TYPE) != I_BLOCK_SPECIAL) return(ENOTTY); suspend_reopen= (f->filp_state != FS_NORMAL); dev = (dev_t) vp->v_sdev; return (dev_io(VFS_DEV_IOCTL, dev, who_e, m_in.ADDRESS, cvu64(0), m_in.REQUEST, f->filp_flags, suspend_reopen)); } /*===========================================================================* * gen_io * *===========================================================================*/ PUBLIC int gen_io(task_nr, mess_ptr) int task_nr; /* which task to call */ message *mess_ptr; /* pointer to message for task */ { /* All file system I/O ultimately comes down to I/O on major/minor device * pairs. These lead to calls on the following routines via the dmap table. */ int r, proc_e; if(task_nr == SYSTEM) { printf("VFS: sending %d to SYSTEM\n", mess_ptr->m_type); } proc_e = mess_ptr->IO_ENDPT; r = sendrec(task_nr, mess_ptr); if (r != OK) { if (r == EDEADSRCDST || r == EDSTDIED || r == ESRCDIED) { printf("fs: dead driver %d\n", task_nr); dmap_unmap_by_endpt(task_nr); return r; } if (r == ELOCKED) { printf("fs: ELOCKED talking to %d\n", task_nr); return r; } panic(__FILE__,"call_task: can't send/receive", r); } /* Did the process we did the sendrec() for get a result? */ if (mess_ptr->REP_ENDPT != proc_e) { printf( "fs: strange device reply from %d, type = %d, proc = %d (not %d) (2) ignored\n", mess_ptr->m_source, mess_ptr->m_type, proc_e, mess_ptr->REP_ENDPT); return EIO; } return OK; } /*===========================================================================* * asyn_io * *===========================================================================*/ PUBLIC int asyn_io(task_nr, mess_ptr) int task_nr; /* which task to call */ message *mess_ptr; /* pointer to message for task */ { /* All file system I/O ultimately comes down to I/O on major/minor device * pairs. These lead to calls on the following routines via the dmap table. */ int r, proc_e; proc_e = mess_ptr->IO_ENDPT; r= asynsend(task_nr, mess_ptr); if (r != OK) panic(__FILE__, "asyn_io: asynsend failed", r); /* Fake a SUSPEND */ mess_ptr->REP_STATUS= SUSPEND; return OK; } /*===========================================================================* * ctty_io * *===========================================================================*/ PUBLIC int ctty_io(task_nr, mess_ptr) int task_nr; /* not used - for compatibility with dmap_t */ message *mess_ptr; /* pointer to message for task */ { /* This routine is only called for one device, namely /dev/tty. Its job * is to change the message to use the controlling terminal, instead of the * major/minor pair for /dev/tty itself. */ struct dmap *dp; if (fp->fp_tty == 0) { /* No controlling tty present anymore, return an I/O error. */ mess_ptr->REP_STATUS = EIO; } else { /* Substitute the controlling terminal device. */ dp = &dmap[(fp->fp_tty >> MAJOR) & BYTE]; mess_ptr->DEVICE = (fp->fp_tty >> MINOR) & BYTE; if (dp->dmap_driver == NONE) { printf("FS: ctty_io: no driver for dev\n"); return EIO; } if(isokendpt(dp->dmap_driver, &dummyproc) != OK) { printf("FS: ctty_io: old driver %d\n", dp->dmap_driver); return EIO; } (*dp->dmap_io)(dp->dmap_driver, mess_ptr); } return OK; } /*===========================================================================* * no_dev * *===========================================================================*/ PUBLIC int no_dev(op, dev, proc, flags) int op; /* operation, DEV_OPEN or DEV_CLOSE */ dev_t dev; /* device to open or close */ int proc; /* process to open/close for */ int flags; /* mode bits and flags */ { /* Called when opening a nonexistent device. */ return(ENODEV); } /*===========================================================================* * no_dev_io * *===========================================================================*/ PUBLIC int no_dev_io(int proc, message *m) { /* Called when doing i/o on a nonexistent device. */ printf("VFS: I/O on unmapped device number\n"); return EIO; } /*===========================================================================* * clone_opcl * *===========================================================================*/ PUBLIC int clone_opcl(op, dev, proc_e, flags) int op; /* operation, DEV_OPEN or DEV_CLOSE */ dev_t dev; /* device to open or close */ int proc_e; /* process to open/close for */ int flags; /* mode bits and flags */ { /* Some devices need special processing upon open. Such a device is "cloned", * i.e. on a succesful open it is replaced by a new device with a new unique * minor device number. This new device number identifies a new object (such * as a new network connection) that has been allocated within a task. */ struct dmap *dp; int r, minor; message dev_mess; /* Determine task dmap. */ dp = &dmap[(dev >> MAJOR) & BYTE]; minor = (dev >> MINOR) & BYTE; dev_mess.m_type = op; dev_mess.DEVICE = minor; dev_mess.IO_ENDPT = proc_e; dev_mess.COUNT = flags; if (dp->dmap_driver == NONE) { printf("vfs:clone_opcl: no driver for dev %x\n", dev); return ENXIO; } if(isokendpt(dp->dmap_driver, &dummyproc) != OK) { printf("vfs:clone_opcl: bad driver endpoint for dev %x (%d)\n", dev, dp->dmap_driver); return ENXIO; } /* Call the task. */ r= (*dp->dmap_io)(dp->dmap_driver, &dev_mess); if (r != OK) return r; if (op == DEV_OPEN && dev_mess.REP_STATUS >= 0) { if (dev_mess.REP_STATUS != minor) { struct vnode *vp; struct vmnt *vmp; struct node_details res; /* A new minor device number has been returned. * Request the root FS to create a temporary device file to * hold it. */ /* Device number of the new device. */ dev = (dev & ~(BYTE << MINOR)) | (dev_mess.REP_STATUS << MINOR); /* Issue request */ r = req_newnode(ROOT_FS_E, fp->fp_effuid, fp->fp_effgid, ALL_MODES | I_CHAR_SPECIAL, dev, &res); if (r != OK) { (void) clone_opcl(DEV_CLOSE, dev, proc_e, 0); return r; } /* Drop old node and use the new values */ vp = fp->fp_filp[m_in.fd]->filp_vno; put_vnode(vp); if ((vp = get_free_vnode(__FILE__, __LINE__)) == NIL_VNODE) { printf( "vfs:clone_opcl: failed to get a free vnode..\n"); vp = fp->fp_filp[m_in.fd]->filp_vno; } vp->v_fs_e = res.fs_e; if ((vmp = find_vmnt(vp->v_fs_e)) == NIL_VMNT) printf("vfs:clone_opcl: no vmnt found\n"); vp->v_vmnt = vmp; vp->v_dev = vmp->m_dev; vp->v_fs_e = res.fs_e; vp->v_inode_nr = res.inode_nr; vp->v_mode = res.fmode; vp->v_sdev = dev; vp->v_fs_count = 1; vp->v_ref_count = 1; fp->fp_filp[m_in.fd]->filp_vno = vp; } dev_mess.REP_STATUS = OK; } return(dev_mess.REP_STATUS); } /*===========================================================================* * dev_up * *===========================================================================*/ PUBLIC void dev_up(int maj) { /* A new device driver has been mapped in. This function * checks if any filesystems are mounted on it, and if so, * dev_open()s them so the filesystem can be reused. */ int r, new_driver_e, needs_reopen, fd_nr; struct filp *fp; struct vmnt *vmp; struct fproc *rfp; struct vnode *vp; message m; /* Open a device once for every filp that's opened on it, * and once for every filesystem mounted from it. */ new_driver_e = dmap[maj].dmap_driver; for (vmp = &vmnt[0]; vmp < &vmnt[NR_MNTS]; ++vmp) { int minor; if (vmp->m_dev == NO_DEV) continue; if ( ((vmp->m_dev >> MAJOR) & BYTE) != maj) continue; minor = ((vmp->m_dev >> MINOR) & BYTE); if ((r = dev_open(vmp->m_dev, FS_PROC_NR, vmp->m_flags ? R_BIT : (R_BIT|W_BIT))) != OK) { printf("VFS: mounted dev %d/%d re-open failed: %d.\n", maj, minor, r); } /* Send new driver endpoint */ if (OK != req_newdriver(vmp->m_fs_e, vmp->m_dev, new_driver_e)) printf( "VFSdev_up: error sending new driver endpoint. FS_e: %d req_nr: %d\n", vmp->m_fs_e, REQ_NEW_DRIVER); } /* Look for processes that are suspened in an OPEN call. Set SUSP_REOPEN * to indicate that this process was suspended before the call to dev_up. */ for (rfp = &fproc[0]; rfp < &fproc[NR_PROCS]; rfp++) { if(rfp->fp_pid == PID_FREE) continue; if(rfp->fp_blocked_on != FP_BLOCKED_ON_DOPEN) continue; printf("dev_up: found process in FP_BLOCKED_ON_DOPEN, fd %d\n", rfp->fp_fd >> 8); fd_nr= (rfp->fp_fd >> 8); fp= rfp->fp_filp[fd_nr]; vp= fp->filp_vno; if (!vp) panic(__FILE__, "restart_reopen: no vp", NO_NUM); if ((vp->v_mode & I_TYPE) != I_CHAR_SPECIAL) continue; if (((vp->v_sdev >> MAJOR) & BYTE) != maj) continue; rfp->fp_flags |= SUSP_REOPEN; } needs_reopen= FALSE; for (fp = filp; fp < &filp[NR_FILPS]; fp++) { struct vnode *vp; int minor; if(fp->filp_count < 1 || !(vp = fp->filp_vno)) continue; if(((vp->v_sdev >> MAJOR) & BYTE) != maj) continue; if(!(vp->v_mode & (I_BLOCK_SPECIAL|I_CHAR_SPECIAL))) continue; fp->filp_state= FS_NEEDS_REOPEN; needs_reopen= TRUE; } if (needs_reopen) restart_reopen(maj); } /*===========================================================================* * restart_reopen * *===========================================================================*/ PRIVATE void restart_reopen(maj) int maj; { int n, r, minor, fd_nr; endpoint_t driver_e; struct vnode *vp; struct filp *fp; struct fproc *rfp; for (fp = filp; fp < &filp[NR_FILPS]; fp++) { if (fp->filp_count < 1 || !(vp = fp->filp_vno)) continue; if (fp->filp_state != FS_NEEDS_REOPEN) continue; if (((vp->v_sdev >> MAJOR) & BYTE) != maj) continue; if ((vp->v_mode & I_TYPE) != I_CHAR_SPECIAL) continue; if (!(fp->filp_flags & O_REOPEN)) { /* File descriptor is to be closed when driver restarts. */ /* The function inval_filp will set the fp_filp[]s of * processes holding that fp to NULL, but _not_ clear * fp_filp_inuse, so that fd can't be recycled until * it's close()d. */ n = inval_filp(fp); if (n != fp->filp_count) { printf("VFS: warning: invalidate/count " "discrepancy (%d, %d)\n", n, fp->filp_count); } fp->filp_count = 0; continue; } minor = ((vp->v_sdev >> MINOR) & BYTE); r = dev_reopen(vp->v_sdev, fp-filp, vp->v_mode & (R_BIT|W_BIT)); if (r == OK) return; /* This function will set the fp_filp[]s of processes * holding that fp to NULL, but _not_ clear * fp_filp_inuse, so that fd can't be recycled until * it's close()d. */ n = inval_filp(fp); if (n != fp->filp_count) { printf("VFS: warning: invalidate/count " "discrepancy (%d, %d)\n", n, fp->filp_count); } fp->filp_count = 0; printf("VFS: file on dev %d/%d re-open failed: %d; " "invalidated %d fd's.\n", maj, minor, r, n); } /* Nothing more to re-open. Restart suspended processes */ driver_e= dmap[maj].dmap_driver; for (rfp = &fproc[0]; rfp < &fproc[NR_PROCS]; rfp++) { if(rfp->fp_pid == PID_FREE) continue; if(rfp->fp_blocked_on == FP_BLOCKED_ON_OTHER && rfp->fp_task == driver_e && (rfp->fp_flags & SUSP_REOPEN)) { rfp->fp_flags &= ~SUSP_REOPEN; rfp->fp_blocked_on = FP_BLOCKED_ON_NONE; reply(rfp->fp_endpoint, ERESTART); } } /* Look for processes that are suspened in an OPEN call */ for (rfp = &fproc[0]; rfp < &fproc[NR_PROCS]; rfp++) { if (rfp->fp_pid == PID_FREE) continue; if (rfp->fp_blocked_on == FP_BLOCKED_ON_DOPEN || !(rfp->fp_flags & SUSP_REOPEN)) continue; printf("restart_reopen: found process in FP_BLOCKED_ON_DOPEN, fd %d\n", rfp->fp_fd >> 8); fd_nr= (rfp->fp_fd >> 8); fp= rfp->fp_filp[fd_nr]; if (!fp) { /* Open failed, and automatic reopen was not requested */ rfp->fp_blocked_on = FP_BLOCKED_ON_NONE; FD_CLR(fd_nr, &rfp->fp_filp_inuse); reply(rfp->fp_endpoint, EIO); continue; } vp= fp->filp_vno; if (!vp) panic(__FILE__, "restart_reopen: no vp", NO_NUM); if ((vp->v_mode & I_TYPE) != I_CHAR_SPECIAL) continue; if (((vp->v_sdev >> MAJOR) & BYTE) != maj) continue; rfp->fp_blocked_on = FP_BLOCKED_ON_NONE; reply(rfp->fp_endpoint, fd_nr); } } /*===========================================================================* * reopen_reply * *===========================================================================*/ PUBLIC void reopen_reply() { endpoint_t driver_e; int filp_no, status, maj; struct filp *fp; struct vnode *vp; struct dmap *dp; driver_e= m_in.m_source; filp_no= m_in.REP_ENDPT; status= m_in.REP_STATUS; if (filp_no < 0 || filp_no >= NR_FILPS) { printf("reopen_reply: bad filp number %d from driver %d\n", filp_no, driver_e); return; } fp= &filp[filp_no]; if (fp->filp_count < 1) { printf( "reopen_reply: filp number %d not inuse (from driver %d)\n", filp_no, driver_e); return; } vp= fp->filp_vno; if (!vp) { printf( "reopen_reply: no vnode for filp number %d (from driver %d)\n", filp_no, driver_e); return; } if (fp->filp_state != FS_NEEDS_REOPEN) { printf( "reopen_reply: bad state %d for filp number %d (from driver %d)\n", fp->filp_state, filp_no, driver_e); return; } if ((vp->v_mode & I_TYPE) != I_CHAR_SPECIAL) { printf( "reopen_reply: bad mode 0%o for filp number %d (from driver %d)\n", vp->v_mode, filp_no, driver_e); return; } maj= ((vp->v_sdev >> MAJOR) & BYTE); dp = &dmap[maj]; if (dp->dmap_driver != driver_e) { printf("reopen_reply: bad major %d for filp number %d " "(from driver %d, current driver is %d)\n", maj, filp_no, driver_e, dp->dmap_driver); return; } if (status == OK) { fp->filp_state= FS_NORMAL; } else { printf("reopen_reply: should handle error status\n"); return; } restart_reopen(maj); } #if 0 #define ASYN_NR 100 PRIVATE asynmsg_t msgtable[ASYN_NR]; PRIVATE int first_slot= 0, next_slot= 0; PUBLIC int asynsend(dst, mp) endpoint_t dst; message *mp; { int r, src_ind, dst_ind; unsigned flags; /* Update first_slot */ for (; first_slot < next_slot; first_slot++) { flags= msgtable[first_slot].flags; if ((flags & (AMF_VALID|AMF_DONE)) == (AMF_VALID|AMF_DONE)) { if (msgtable[first_slot].result != OK) { printf( "asynsend: found completed entry %d with error %d\n", first_slot, msgtable[first_slot].result); } continue; } if (flags != AMF_EMPTY) break; } if (first_slot >= next_slot) { /* Reset first_slot and next_slot */ next_slot= first_slot= 0; } if (next_slot >= ASYN_NR) { /* Tell the kernel to stop processing */ r= senda(NULL, 0); if (r != OK) panic(__FILE__, "asynsend: senda failed", r); dst_ind= 0; for (src_ind= first_slot; src_ind<next_slot; src_ind++) { flags= msgtable[src_ind].flags; if ((flags & (AMF_VALID|AMF_DONE)) == (AMF_VALID|AMF_DONE)) { if (msgtable[src_ind].result != OK) { printf( "asynsend: found completed entry %d with error %d\n", src_ind, msgtable[src_ind].result); } continue; } if (flags == AMF_EMPTY) continue; #if 0 printf("asynsend: copying entry %d to %d\n", src_ind, dst_ind); #endif if (src_ind != dst_ind) msgtable[dst_ind]= msgtable[src_ind]; dst_ind++; } first_slot= 0; next_slot= dst_ind; if (next_slot >= ASYN_NR) panic(__FILE__, "asynsend: msgtable full", NO_NUM); } msgtable[next_slot].dst= dst; msgtable[next_slot].msg= *mp; msgtable[next_slot].flags= AMF_VALID; /* Has to be last. The kernel * scans this table while we * are sleeping. */ next_slot++; /* Tell the kernel to rescan the table */ return senda(msgtable+first_slot, next_slot-first_slot); } #endif
jonasnic/codingame
puzzles/python3/vox-codei1/vox_codei1.py
import copy from typing import List, Optional EMPTY = '.' TARGET = '@' WALL = '#' EXPLOSION_TIME = 3 BOMB_RANGE = 3 class Node: def __init__(self, x: int, y: int, symbol: str): self.x = x self.y = y self.symbol = symbol self.to_destroy = False self.time_to_detonation = EXPLOSION_TIME self.invalid = False def is_valid_target(self) -> bool: return self.symbol == TARGET and not self.to_destroy def is_valid_future_bomb_placement(self) -> bool: return not self.invalid and (self.symbol == EMPTY or (self.symbol == TARGET and self.to_destroy)) def update(self): if self.symbol == TARGET and self.to_destroy: self.time_to_detonation -= 1 if self.time_to_detonation == 0: self.symbol = EMPTY class Grid: def __init__(self, width: int, height: int): self.width = width self.height = height self.nodes: List[List[Node]] = [] def mark_as_to_destroy(self, x: int, y: int): self.nodes[y][x].to_destroy = True def is_valid_target(self, x: int, y: int) -> bool: return self.nodes[y][x].is_valid_target() def is_valid_future_bomb_placement(self, x: int, y: int) -> bool: return self.nodes[y][x].is_valid_future_bomb_placement() def is_cleared(self) -> bool: for y in range(self.height): for x in range(self.width): if self.nodes[y][x].symbol == TARGET: return False return True def update(self): for y in range(self.height): for x in range(self.width): self.nodes[y][x].update() def pick_bomb_placement(self) -> Optional[Node]: """Greedy solution: pick the bomb placement with the maximum score.""" max_score = 0 max_node: Optional[Node] = None for y in range(self.height): for x in range(self.width): if self.is_valid_future_bomb_placement(x, y): score = self.place_bomb_score(x, y) if score > max_score: max_score = score max_node = self.nodes[y][x] return max_node def place_bomb(self, x: int, y: int): """ Update the state of the grid according to the coordinates of the bomb. Precondition: The node at (x, y) should be a valid target. """ # BOTTOM for i in range(y + 1, y + BOMB_RANGE + 1): if i >= self.height: break if self.is_valid_target(x, i): self.mark_as_to_destroy(x, i) elif self.nodes[i][x].symbol == WALL: break # TOP for j in range(y - 1, y - (BOMB_RANGE + 1), -1): if j < 0: break if self.is_valid_target(x, j): self.mark_as_to_destroy(x, j) elif self.nodes[j][x].symbol == WALL: break # RIGHT for k in range(x + 1, x + BOMB_RANGE + 1): if k >= self.width: break if self.is_valid_target(k, y): self.mark_as_to_destroy(k, y) elif self.nodes[y][k].symbol == WALL: break # LEFT for m in range(x - 1, x - (BOMB_RANGE + 1), -1): if m < 0: break if self.is_valid_target(m, y): self.mark_as_to_destroy(m, y) elif self.nodes[y][m].symbol == WALL: break def place_bomb_score(self, x: int, y: int) -> int: """ Returns the score for placing a bomb at the (x, y) position. score = number of targets destroyed Precondition: The node at (x, y) should be a valid target. """ score = 0 # BOTTOM for i in range(y + 1, y + BOMB_RANGE + 1): if i >= self.height: break if self.is_valid_target(x, i): score += 1 elif self.nodes[i][x].symbol == WALL: break # TOP for j in range(y - 1, y - (BOMB_RANGE + 1), -1): if j < 0: break if self.is_valid_target(x, j): score += 1 elif self.nodes[j][x].symbol == WALL: break # RIGHT for k in range(x + 1, x + BOMB_RANGE + 1): if k >= self.width: break if self.is_valid_target(k, y): score += 1 elif self.nodes[y][k].symbol == WALL: break # LEFT for m in range(x - 1, x - (BOMB_RANGE + 1), -1): if m < 0: break if self.is_valid_target(m, y): score += 1 elif self.nodes[y][m].symbol == WALL: break return score class VoxCodei: def __init__(self): self.grid: Optional[Grid] = None self.nb_rounds_left = 0 # number of rounds left before the end of the game self.nb_bombs_left = 0 self.round = 1 def read_init_input(self): width, height = map(int, input().split()) self.grid = Grid(width, height) for y in range(height): map_row = input() row: List[Node] = [] self.grid.nodes.append(row) for x, symbol in enumerate(map_row): self.grid.nodes[y].append(Node(x, y, symbol)) def game_loop(self): while True: self.nb_rounds_left, self.nb_bombs_left = map(int, input().split()) self.play_turn() self.round += 1 def play_turn(self): node: Optional[Node] = self.grid.pick_bomb_placement() # simulate everything for the selected node, if it doesn't work out, backtrack if node is not None: if not self.simulate_turn(node.x, node.y): node.invalid = True node = self.grid.pick_bomb_placement() # validate bomb placement for next turn if node is None or node.symbol != EMPTY: print("WAIT") # wait until it gets destroyed else: self.grid.place_bomb(node.x, node.y) print(f"{node.x} {node.y}") self.grid.update() def simulate_turn(self, x: int, y: int) -> bool: bombs = self.nb_bombs_left rounds = self.nb_rounds_left grid_copy: Optional[Grid] = copy.deepcopy(self.grid) if not grid_copy: return False current: Optional[Node] = grid_copy.nodes[y][x] while bombs != 0 and rounds != 0 and not grid_copy.is_cleared(): if current is not None and current.symbol == EMPTY: grid_copy.place_bomb(current.x, current.y) bombs -= 1 grid_copy.update() rounds -= 1 current = grid_copy.pick_bomb_placement() while rounds != 0 and not grid_copy.is_cleared(): grid_copy.update() rounds -= 1 return grid_copy.is_cleared() if __name__ == "__main__": vox_codei = VoxCodei() vox_codei.read_init_input() vox_codei.game_loop()
attila-sim/attila-sim
src/trace/D3DDriver/D3DControllers/CSemanticMapping_9.cpp
<filename>src/trace/D3DDriver/D3DControllers/CSemanticMapping_9.cpp #include "Common.h" #include "CSemanticMapping_9.h" void CSemanticMapping9::on_add_node_child(StateDataNode* parent, StateDataNode* child) {} void CSemanticMapping9::on_remove_node_child(StateDataNode* parent, StateDataNode* child) {} void CSemanticMapping9::on_write_node_data(StateDataNode* node, size_t size, UINT offset) {} void CSemanticMapping9::on_added_controller(StateDataNode* node) { if(node->get_id().name == NAME_DEVICE_9) { // watch assignation tables AssignationsRegistry::get_table(NAME_ELEMENT_STREAM)->add_observer(this); AssignationsRegistry::get_table(NAME_VS_INPUT)->add_observer(this); } } void CSemanticMapping9::on_removed_controller(StateDataNode* node) { if(node->get_id().name == NAME_DEVICE_9) { // unwatch assignation tables AssignationsRegistry::get_table(NAME_VS_INPUT)->remove_observer(this); AssignationsRegistry::get_table(NAME_ELEMENT_STREAM)->remove_observer(this); } } void CSemanticMapping9::on_assigned(ResourceAssignationTable* table, UsageId usage, ResourceId resource) { if(table->get_name() == NAME_ELEMENT_STREAM) { assigned_streams.insert(usage); // Check if there's an input register with this usage set< UsageId >:: iterator it_r; it_r = assigned_registers.find(usage); if(it_r != assigned_registers.end()) { // Get input register ResourceId r = AssignationsRegistry::get_table(NAME_VS_INPUT)->get_assigned_to(*it_r); u32bit gpu_register = r.index; // Get input stream u32bit gpu_stream = resource.index; // Bind register to stream GPURegData data; data.uintVal = gpu_stream; GPUDriver::getGPUDriver()->writeGPURegister(GPU_VERTEX_ATTRIBUTE_MAP, gpu_register, data); D3D_DEBUG( cout << "CSEMANTICMAPPING9: Mapping vs input register "; ) D3D_DEBUG( cout << gpu_register << " to stream " << gpu_stream << endl; ) D3D_DEBUG( cout << "CSEMANTICMAPPING9: Usage is "; ) D3D_DEBUG( cout << usage.name << "[" << usage.index << "]" << endl; ) } } else if(table->get_name() == NAME_VS_INPUT) { assigned_registers.insert(usage); // Check if there's an stream with this usage set< UsageId >:: iterator it_r; it_r = assigned_streams.find(usage); if(it_r != assigned_streams.end()) { // Get input stream ResourceId r = AssignationsRegistry::get_table(NAME_STREAMS)->get_assigned_to(*it_r); u32bit gpu_stream = r.index; // Get input register u32bit gpu_register = resource.index; // Bind register to stream GPURegData data; data.uintVal = gpu_stream; GPUDriver::getGPUDriver()->writeGPURegister(GPU_VERTEX_ATTRIBUTE_MAP, gpu_register, data); D3D_DEBUG( cout << "CSEMANTICMAPPING9: Mapping vs input register "; ) D3D_DEBUG( cout << gpu_register << " to stream " << gpu_stream << endl; ) D3D_DEBUG( cout << "CSEMANTICMAPPING9: Usage is "; ) D3D_DEBUG( cout << usage.name << "[" << usage.index << "]" << endl; ) } else { // Get input register u32bit gpu_register = resource.index; // Unbind register GPURegData data; data.uintVal = ST_INACTIVE_ATTRIBUTE; GPUDriver::getGPUDriver()->writeGPURegister(GPU_VERTEX_ATTRIBUTE_MAP, gpu_register, data); D3D_DEBUG( cout << "CSEMANTICMAPPING9: Unmapped vs input register "; ) D3D_DEBUG( cout << gpu_register << endl; ) D3D_DEBUG( cout << "CSEMANTICMAPPING9: Usage is "; ) D3D_DEBUG( cout << usage.name << "[" << usage.index << "]" << endl; ) } } } void CSemanticMapping9::on_unassigned(ResourceAssignationTable* table, UsageId usage, ResourceId resource) { if(table->get_name() == NAME_ELEMENT_STREAM) { assigned_streams.erase(usage); // Check if there's an input register with this usage set< UsageId >:: iterator it_r; it_r = assigned_registers.find(usage); if(it_r != assigned_registers.end()) { // Get input register ResourceId r = AssignationsRegistry::get_table(NAME_VS_INPUT)->get_assigned_to(*it_r); u32bit gpu_register = r.index; // Unbind register GPURegData data; data.uintVal = ST_INACTIVE_ATTRIBUTE; GPUDriver::getGPUDriver()->writeGPURegister(GPU_VERTEX_ATTRIBUTE_MAP, gpu_register, data); D3D_DEBUG( cout << "CSEMANTICMAPPING9: Unmapped vs input register "; ) D3D_DEBUG( cout << gpu_register << endl; ) D3D_DEBUG( cout << "CSEMANTICMAPPING9: Usage is "; ) D3D_DEBUG( cout << usage.name << "[" << usage.index << "]" << endl; ) } } else if(table->get_name() == NAME_VS_INPUT) { assigned_registers.erase(usage); // Check if there's an stream with this usage set< UsageId >:: iterator it_r; it_r = assigned_streams.find(usage); if(it_r != assigned_streams.end()) { // Get input register u32bit gpu_register = resource.index; // Unbind register GPURegData data; data.uintVal = ST_INACTIVE_ATTRIBUTE; GPUDriver::getGPUDriver()->writeGPURegister(GPU_VERTEX_ATTRIBUTE_MAP, gpu_register, data); D3D_DEBUG( cout << "CSEMANTICMAPPING9: Unmapped vs input register "; ) D3D_DEBUG( cout << gpu_register << endl; ) D3D_DEBUG( cout << "CSEMANTICMAPPING9: Usage is "; ) D3D_DEBUG( cout << usage.name << "[" << usage.index << "]" << endl; ) } } }
akindele214/181hub_2
chat/forms.py
from django.contrib.auth.models import User from django import forms from .models import Chat class ReportForm(forms.ModelForm): content = forms.CharField(label="", required=True, widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Report Goes Here', 'rows': '4', 'cols': '30'})) class Meta: model= Chat fields = ['content']
npocmaka/Windows-Server-2003
com/netfx/src/framework/mit/setup/mshelpdetection/isvsrunning.cpp
<reponame>npocmaka/Windows-Server-2003 //------------------------------------------------------------------------------ // <copyright file="isvsrunning.cpp" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /**************************************************************************\ * * Copyright (c) 1998-2002, Microsoft Corp. All Rights Reserved. * * Module Name: * * isvsrunning.cpp * * Abstract: * * Revision History: * \**************************************************************************/ #define UNICODE 1 #include <windows.h> #include <winuser.h> #include <tchar.h> #include "psapi.h" #include "msi.h" #include "msiquery.h" #define STANDARD_BUFFER 512 BOOL IsDevEnv( DWORD processID ) { HMODULE hMod; HANDLE hProcess = NULL; DWORD cbNeeded; BOOL bFound = false; TCHAR szModName[MAX_PATH + 1]; hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID ); if (!hProcess) { goto Exit; } EnumProcessModules(hProcess, &hMod, sizeof(HMODULE), &cbNeeded); if ( GetModuleBaseName( hProcess, hMod, szModName,MAX_PATH)) { if (!wcscmp(CharLower(szModName), L"devenv.exe") || !wcscmp(CharLower(szModName), L"dexplore.exe")) { bFound = true; } } Exit: if (hProcess) { CloseHandle( hProcess ); } return bFound; } BOOL IsDevEnvRunning( ) { DWORD *aProcesses; DWORD cbPreviousNeeded = 0; DWORD cbNeeded= 0; DWORD cbSize = 0; DWORD cProcesses; BOOL bFound = false; unsigned int i; do { cbSize += 1024; aProcesses = (DWORD *) malloc(cbSize); if (!aProcesses) { goto Exit; } EnumProcesses(aProcesses, cbSize, &cbNeeded); if (cbSize == cbNeeded) { free(aProcesses); aProcesses = NULL; } } while (!aProcesses); cProcesses = cbNeeded / sizeof(DWORD); for ( i = 0; i < cProcesses; i++ ) { if (IsDevEnv(aProcesses[i])) { bFound = true; goto Exit; } } Exit: if (aProcesses) { free(aProcesses); } return bFound; } extern "C" __declspec(dllexport) UINT __stdcall IsVSRunning(MSIHANDLE hInstaller) { BOOL bFound; WCHAR VSIsRunningErrMsg[STANDARD_BUFFER]; WCHAR InstallationWarningCaption[STANDARD_BUFFER]; int nRetCode; DWORD dwSize = STANDARD_BUFFER; MsiGetProperty(hInstaller, L"VisualStudioIsRunningErrMsg", VSIsRunningErrMsg, &dwSize); dwSize = STANDARD_BUFFER; MsiGetProperty(hInstaller, L"InstallationWarningCaption", InstallationWarningCaption, &dwSize); while (IsDevEnvRunning()) { nRetCode = MessageBox(0, VSIsRunningErrMsg, InstallationWarningCaption, MB_ABORTRETRYIGNORE); if (nRetCode == IDABORT) { return ERROR_INSTALL_USEREXIT; } else { if (nRetCode == IDIGNORE) { return ERROR_SUCCESS; } } } return ERROR_SUCCESS; }
IshitaTakeshi/DVO
examples/rgbd_desk.py
import csv import sys from pathlib import Path sys.path.append(str(Path(__file__).resolve().parent.parent)) from skimage.color import rgb2gray import numpy as np from tqdm import tqdm from tadataka import VisualOdometry, CameraParameters from tadataka.rigid import exp_se3, log_se3 from tadataka.projection import warp from tadataka.mapping import MapBuilder from tadataka.quaternion import quaternion_to_rotation from tadataka.datasets.tum_rgbd import TUMDataset, PoseSequence from visualization.plot import plot # dataset format is explained at # https://vision.in.tum.de/data/datasets/rgbd-dataset/file_formats# # intrinsic_camera_calibration_of_the_kinect dataset_root = Path("datasets", "rgbd_dataset_freiburg1_desk") # dataset_root = Path("datasets", "rgbd_dataset_freiburg2_pioneer_360") # dataset_root = Path("datasets", "rgbd_dataset_freiburg3_structure_texture_near") def error(image_true, image_pred, mask): return np.power(image_true[mask]-image_pred[mask], 2).mean() def visualize_error_function(camera_parameters, I0, D0, I1, xi_pred): def generate_error_curve(i, start, stop, n): xi = np.copy(xi_pred) vs = xi[i] + np.linspace(start, stop, n) errors = [] for v in vs: xi[i] = v DG = exp_se3(xi) estimated, mask = warp(camera_parameters, I1, D0, DG) errors.append(error(I0, estimated, mask)) errors = np.array(errors) return vs, errors from matplotlib import pyplot as plt fig = plt.figure() for xi_index, ax_index in enumerate([1, 3, 5, 2, 4, 6]): ax = fig.add_subplot(3, 2, ax_index) vs, errors = generate_error_curve(xi_index, start=-0.10, stop=0.10, n=101) ax.set_title("Axis {}".format(xi_index+1)) ax.axvline(vs[np.argmin(errors)], label="ground truth") ax.axvline(xi_pred[xi_index], color="red", label="prediction") ax.legend() ax.plot(vs, errors) plt.show() def main(): np.set_printoptions(suppress=True, precision=8, linewidth=1e8) camera_parameters = CameraParameters( focal_length=[525.0, 525.0], offset=[319.5, 239.5] ) dataset = TUMDataset(dataset_root) G = np.eye(4) frame0 = dataset.load_color(0) sequence_pred = PoseSequence() sequence_pred.add(frame0.timestamp_depth, G) for i in tqdm(range(1, dataset.size)): frame1 = dataset.load_color(i) # TODO not necessary to convert the color of the same image twice # we need to create a better interface vo = VisualOdometry(camera_parameters, rgb2gray(frame0.image), frame0.depth_map, rgb2gray(frame1.image)) DG = vo.estimate_motion(n_coarse_to_fine=6) G = np.dot(G, np.linalg.inv(DG)) sequence_pred.add(frame1.timestamp_depth, G) frame0 = frame1 sequence_pred.save("poses.txt") # TODO implement the following # pointcloud = map_builder.export() # export_pointcloud(pointcloud) main()
pyvelkov/ALVR
alvr/client/android/app/src/main/cpp/gl_render_utils/texture.h
<gh_stars>1000+ #pragma once #include <GLES3/gl3.h> #include <GLES2/gl2ext.h> #include <vector> #include <string> namespace gl_render_utils { class Texture { public: Texture(bool oes, uint32_t width = 0, uint32_t height = 0, GLenum format = GL_RGBA, std::vector<uint8_t> content = {}); Texture(GLuint externalHandle, bool oes, uint32_t width = 0, uint32_t height = 0, GLenum format = GL_RGBA, std::vector<uint8_t> content = {}); uint32_t GetWidth() const { return mWidth; } uint32_t GetHeight() const { return mHeight; } GLuint GetGLTexture() const { return mGLTexture; } GLenum GetTarget() const { return mTarget; } bool IsOES() const { return mOES; } ~Texture(); private: void initialize(bool external, GLuint externalHandle, bool oes, uint32_t width, uint32_t height, GLenum format, std::vector<uint8_t> &content); bool mOES; uint32_t mWidth, mHeight; GLuint mGLTexture; GLenum mTarget; bool mExternal; }; }
aliostad/deep-learning-lang-detection
data/train/js/a0456e0c240886309253bc3c318ce4771514c68cindex.js
<gh_stars>10-100 'use strict'; var fs = require('fs'); module.exports = angular.module('app.patterns', [ 'ui.router', require('../../../_shared/angular/resources/spaces/spaces').name ]) .config( function($stateProvider) { $stateProvider .state('app.pattern', { url: '/patterns', views: { '@': { controller: 'PatternController', template: fs.readFileSync(__dirname + '/templates/_patterns.html') } } }) .state('app.pattern.styleguide', { url: '/styleguide', controller: 'PatternController', controllerAs: 'styleguide', template: fs.readFileSync(__dirname + '/templates/styleguide.html') }) .state('app.pattern.accordion', { url: '/accordion', controller: 'DemoAccordionController', controllerAs: 'accordionDemo', template: fs.readFileSync(__dirname + '/templates/accordion-demo.html') }) .state('app.pattern.alert', { url: '/alerts', controller: 'DemoAlertController', controllerAs: 'alertDemo', template: fs.readFileSync(__dirname + '/templates/alert-demo.html') }) .state('app.pattern.buttons', { url: '/buttons', controller: 'DemoButtonsController', controllerAs: 'buttonDemo', template: fs.readFileSync(__dirname + '/templates/buttons-demo.html') }) .state('app.pattern.carousel', { url: '/carousel', controller: 'DemoCarouselController', controllerAs: 'carouselDemo', template: fs.readFileSync(__dirname + '/templates/carousel-demo.html') }) .state('app.pattern.collapse', { url: '/collapse', controller: 'DemoCollapseController', controllerAs: 'collapseDemo', template: fs.readFileSync(__dirname + '/templates/collapse-demo.html') }) .state('app.pattern.datepicker', { url: '/datepicker', controller: 'DemoDatepickerController', controllerAs: 'datepickerDemo', template: fs.readFileSync(__dirname + '/templates/datepicker-demo.html') }) .state('app.pattern.dropdown', { url: '/dropdown', controller: 'DemoDropdownController', controllerAs: 'dropdownDemo', template: fs.readFileSync(__dirname + '/templates/dropdown-demo.html') }) .state('app.pattern.input', { url: '/input', controller: 'DemoInputController', controllerAs: 'inputDemo', template: fs.readFileSync(__dirname + '/templates/input-demo.html') }) .state('app.pattern.modal', { url: '/modal', controller: 'DemoModalController', controllerAs: 'modalDemo', template: fs.readFileSync(__dirname + '/templates/modal-demo.html') }) .state('app.pattern.pagination', { url: '/pagination', controller: 'DemoPaginationController', controllerAs: 'paginationDemo', template: fs.readFileSync(__dirname + '/templates/pagination-demo.html') }) .state('app.pattern.popover', { url: '/popover', controller: 'DemoPopoverController', controllerAs: 'popoverDemo', template: fs.readFileSync(__dirname + '/templates/popover-demo.html') }) .state('app.pattern.progressbar', { url: '/progressbar', controller: 'DemoProgressbarController', controllerAs: 'progressbarDemo', template: fs.readFileSync(__dirname + '/templates/progressbar-demo.html') }) .state('app.pattern.rating', { url: '/rating', controller: 'DemoRatingController', controllerAs: 'ratingDemo', template: fs.readFileSync(__dirname + '/templates/rating-demo.html') }) .state('app.pattern.tabs', { url: '/tabs', controller: 'DemoTabsController', controllerAs: 'tabsDemo', template: fs.readFileSync(__dirname + '/templates/tabs-demo.html') }) .state('app.pattern.timepicker', { url: '/timepicker', controller: 'DemoTimepickerController', controllerAs: 'timepickerDemo', template: fs.readFileSync(__dirname + '/templates/timepicker-demo.html') }) .state('app.pattern.tooltip', { url: '/tooltip', controller: 'DemoTooltipController', controllerAs: 'tooltipDemo', template: fs.readFileSync(__dirname + '/templates/tooltip-demo.html') }) .state('app.pattern.typeahead', { url: '/typeahead', controller: 'DemoTypeaheadController', controllerAs: 'typeaheadDemo', template: fs.readFileSync(__dirname + '/templates/typeahead-demo.html') }); } ) .controller('PatternController', require('./controllers/_pattern_controller')) .controller('DemoAccordionController', require('./controllers/accordion_controller')) .controller('DemoAlertController', require('./controllers/alert_controller')) .controller('DemoButtonsController', require('./controllers/buttons_controller')) .controller('DemoCarouselController', require('./controllers/carousel_controller')) .controller('DemoCollapseController', require('./controllers/collapse_controller')) .controller('DemoDatepickerController', require('./controllers/datepicker_controller')) .controller('DemoDropdownController', require('./controllers/dropdown_controller')) .controller('DemoInputController', require('./controllers/input_controller')) .controller('DemoModalController', require('./controllers/modal_controller')) .controller('ModalInstanceController', require('./controllers/modal_instance_controller')) .controller('DemoPaginationController', require('./controllers/pagination_controller')) .controller('DemoPopoverController', require('./controllers/popover_controller')) .controller('DemoProgressbarController', require('./controllers/progressbar_controller')) .controller('DemoRatingController', require('./controllers/rating_controller')) .controller('DemoTabsController', require('./controllers/tabs_controller')) .controller('DemoTimepickerController', require('./controllers/timepicker_controller')) .controller('DemoTooltipController', require('./controllers/tooltip_controller')) .controller('DemoTypeaheadController', require('./controllers/typeahead_controller')) // .controller('DemoUISelectController', require('./controllers/ui_select_controller')) ;
juanfelipe82193/opensap
sapui5-sdk-1.74.0/test-resources/sap/ca/ui/qunit/model/type/NumberTest.js
window.addEventListener("load", function () { var oHtml = new sap.ui.core.HTML({ content: '<div id="contentHolder"></div><h1 id="qunit-header">Fiori Wave 2: Test Page for Number</h1><h2 id="qunit-banner"></h2><h2 id="qunit-userAgent"></h2><ol id="qunit-tests"></ol>', afterRendering: function () { oLabel.placeAt("contentHolder"); } }); var page = new sap.m.Page("TestPage", { title: "Number Test", showNavButton: true, enableScrolling: true, content: oHtml }); var oLabel = new sap.m.Label({text: "Test"}); var app = new sap.m.App("TestApp", { initialPage: "TestPage" }); app.addPage(page).placeAt("content"); /////////////// //Testing Part: Number type /////////////// // require module to be tested jQuery.sap.require("sap.ca.ui.model.type.Number"); function getSapCaUiNumber() { return new sap.ca.ui.model.type.Number(); } // -------------------------------------------------------------------------------- module("NumberType"); test("formatValue to string", function () { equal(getSapCaUiNumber().formatValue("340", "string"), "340", 'formatValue("340", "string") == "340"'); }); test("formatValue to int", function () { equal(getSapCaUiNumber().formatValue(340, "int"), 340, 'formatValue("340", "int") == "340"'); }); test("formatValue to float", function () { equal(getSapCaUiNumber().formatValue(40, "float"), 40, 'formatValue("40", "float") == "40"'); }); test("parseValue from string", function () { equal(getSapCaUiNumber().parseValue("340", "string"), "340", 'parseValue("340") == "340"'); }); test("validateValue Good", function () { equal(getSapCaUiNumber().validateValue(340), undefined, 'validateValue(340) == undefined'); }); });
ConsumerDataStandardsAustralia/java-artifacts
data-holder/src/main/java/au/org/consumerdatastandards/holder/model/energy/EnergyPlanControlledLoad.java
package au.org.consumerdatastandards.holder.model.energy; import com.fasterxml.jackson.annotation.JsonIgnore; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.hibernate.annotations.GenericGenerator; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Required if pricing model is SINGLE_RATE_CONT_LOAD or TIME_OF_USE_CONT_LOAD or FLEXIBLE_CONT_LOAD */ @ApiModel(description = "Required if pricing model is SINGLE_RATE_CONT_LOAD or TIME_OF_USE_CONT_LOAD or FLEXIBLE_CONT_LOAD") @Entity public class EnergyPlanControlledLoad { @Id @GeneratedValue(generator = "system-uuid") @GenericGenerator(name = "system-uuid", strategy = "uuid2") @JsonIgnore private String id; private String displayName; private String description; private String dailyCharge; private String period; @Valid @OneToMany(cascade = CascadeType.ALL) private List<EnergyPlanControlledLoadRates> rates = new ArrayList<>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public EnergyPlanControlledLoad displayName(String displayName) { this.displayName = displayName; return this; } /** * A display name for the controlled load tier * * @return displayName */ @ApiModelProperty(required = true, value = "A display name for the controlled load tier") @NotNull public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public EnergyPlanControlledLoad description(String description) { this.description = description; return this; } /** * A description of the controlled load tier * * @return description */ @ApiModelProperty(value = "A description of the controlled load tier") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public EnergyPlanControlledLoad dailyCharge(String dailyCharge) { this.dailyCharge = dailyCharge; return this; } /** * The daily supply charge (exclusive of GST) for this controlled load tier * * @return dailyCharge */ @ApiModelProperty(required = true, value = "The daily supply charge (exclusive of GST) for this controlled load tier") @NotNull public String getDailyCharge() { return dailyCharge; } public void setDailyCharge(String dailyCharge) { this.dailyCharge = dailyCharge; } public EnergyPlanControlledLoad period(String period) { this.period = period; return this; } /** * The period for which the controlled load rate applies. Formatted according to [ISO 8601 Durations](https://en.wikipedia.org/wiki/ISO_8601#Durations) (excludes recurrence syntax) * * @return period */ @ApiModelProperty(required = true, value = "The period for which the controlled load rate applies. Formatted according to [ISO 8601 Durations](https://en.wikipedia.org/wiki/ISO_8601#Durations) (excludes recurrence syntax)") @NotNull public String getPeriod() { return period; } public void setPeriod(String period) { this.period = period; } public EnergyPlanControlledLoad rates(List<EnergyPlanControlledLoadRates> rates) { this.rates = rates; return this; } public EnergyPlanControlledLoad addRatesItem(EnergyPlanControlledLoadRates ratesItem) { this.rates.add(ratesItem); return this; } /** * Array of controlled load rates in order of usage volume * * @return rates */ @ApiModelProperty(required = true, value = "Array of controlled load rates in order of usage volume") @NotNull @Valid public List<EnergyPlanControlledLoadRates> getRates() { return rates; } public void setRates(List<EnergyPlanControlledLoadRates> rates) { this.rates = rates; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EnergyPlanControlledLoad energyPlanControlledLoad = (EnergyPlanControlledLoad) o; return Objects.equals(this.displayName, energyPlanControlledLoad.displayName) && Objects.equals(this.description, energyPlanControlledLoad.description) && Objects.equals(this.dailyCharge, energyPlanControlledLoad.dailyCharge) && Objects.equals(this.period, energyPlanControlledLoad.period) && Objects.equals(this.rates, energyPlanControlledLoad.rates); } @Override public int hashCode() { return Objects.hash(displayName, description, dailyCharge, period, rates); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class EnergyPlanControlledLoad {\n"); sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); sb.append(" description: ").append(toIndentedString(description)).append("\n"); sb.append(" dailyCharge: ").append(toIndentedString(dailyCharge)).append("\n"); sb.append(" period: ").append(toIndentedString(period)).append("\n"); sb.append(" rates: ").append(toIndentedString(rates)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
downiec/COG
cog/installation/config.py
<filename>cog/installation/config.py ''' CoG configuration script. This class creates or updates the CoG settings file $COG_CONFIG_DIR/cog_settings.cfg, but it does NOT override existing settings. Settings imported from /esg/config/esgf.properties, unless already found in cog_settings.cfg: esgf.host=esg-datanode.jpl.nasa.gov: - SITE_NAME = ESG-DATANODE.JPL.NASA.GOV - SITE_DOMAIN = esg-datanode.jpl.nasa.gov:8000 - DEFAULT_SEARCH_URL = http://esg-datanode.jpl.nasa.gov/esg-search/search/ db.user=... - DATABASE_USER=... db.host=localhost - DATABASE_HOST=localhost db.port=5432 - DATABASE_PORT=5432 mail.admin.address=<EMAIL> - EMAIL_SENDER=<EMAIL> (also used as default email of site administrator) The postgres database password is read from the file /esg/config/.esg_pg_pass - DATABASE_PASSWORD ''' import ConfigParser import StringIO import collections import logging import os import time from django.utils.crypto import get_random_string from constants import (SECTION_DEFAULT, COG_SECTION_DEFAULT, SECTION_ESGF, SECTION_EMAIL, ESGF_PROPERTIES_FILE, ESGF_PASSWORD_FILE, IDP_WHITELIST, KNOWN_PROVIDERS, PEER_NODES, DEFAULT_PROJECT_SHORT_NAME) # location of site specific settings configuration file COG_CONFIG_DIR = os.getenv('COG_CONFIG_DIR', '/usr/local/cog/cog_config') CONFIGFILEPATH = os.path.join(COG_CONFIG_DIR, 'cog_settings.cfg') class CogConfig(object): def __init__(self, esgfFlag): self.esgf = esgfFlag def config(self): '''Driver method.''' self._readCogConfig() self._readEsgfConfig() self._setupConfig() self._writeCogConfig() def _readCogConfig(self): '''Method that reads an existing COG configuration file, or create a new one if not existing.''' # initialize COG configuration file self.cogConfig = ConfigParser.ConfigParser(allow_no_value=True, dict_type=collections.OrderedDict) # must set following line explicitly to preserve the case of configuration keys self.cogConfig.optionxform = str # create configuration directory if not existing already if not os.path.exists(COG_CONFIG_DIR): os.makedirs( COG_CONFIG_DIR ) logging.debug("Created configuration directory: %s" % COG_CONFIG_DIR ) # read existing configuration file try: filenames = self.cogConfig.read( CONFIGFILEPATH ) logging.info("filenames: %s", filenames ) if len(filenames)>0: logging.info("Using existing configuration file: %s" % CONFIGFILEPATH ) else: logging.info("Configuration file: %s not found, will create new one" % CONFIGFILEPATH ) except Exception as e: print e logging.error("Error reading configuration file: %s" % CONFIGFILEPATH) logging.error(e) def _readEsgfConfig(self): '''Method that reads local parameters from ESGF configuration file esgf.properties.''' # read ESGF configuration file ($esg_config_dir/esgf.properties), if available self.esgfConfig = ConfigParser.ConfigParser() try: self.esgfConfig.read(ESGF_PROPERTIES_FILE) except IOError: # file not found logging.warn("ESGF properties file: %s not found" % ESGF_PROPERTIES_FILE) else: #Functionality for ESGF 3.0 where esgf.properties already has a section header called installer.properties if SECTION_DEFAULT in self.esgfConfig.sections(): logging.info("Existing section header found.") logging.info("Read ESGF configuration parameters from file: %s" % ESGF_PROPERTIES_FILE) else: with open(ESGF_PROPERTIES_FILE, 'r') as f: # transform Java properties file into python configuration file: must prepend a section config_string = '[%s]\n' % SECTION_DEFAULT + f.read() config_file = StringIO.StringIO(config_string) self.esgfConfig.readfp(config_file) logging.info("Read ESGF configuration parameters from file: %s" % ESGF_PROPERTIES_FILE) # $esg_config_dir/.esg_pg_pass try: with open(ESGF_PASSWORD_FILE, 'r') as f: password = f.read().strip() # if found, value in .esg_pg_pass will override value from esgf.properties self.esgfConfig.set(SECTION_DEFAULT, "db.password", password) logging.info("Read ESGF database password from file: %s" % ESGF_PASSWORD_FILE) except IOError: # file not found logging.warn("ESGF database password file: %s could not found or could not be read" % ESGF_PASSWORD_FILE) def _safeSet(self, key, value, section=COG_SECTION_DEFAULT, override=False): '''Method to set a configuration option, without overriding an existing value (unless explicitly requested).''' if not self.cogConfig.has_section(section): logging.debug("Section %s not found", section) if section != COG_SECTION_DEFAULT: logging.debug("attempting to add section %s", section) self.cogConfig.add_section(section) # "The DEFAULT section is not acknowledged." if override or not self.cogConfig.has_option(section, key): self.cogConfig.set(section, key, value) def _safeGet(self, key, default=None, section=SECTION_DEFAULT): '''Method to retrieve a value by key, or use a default.''' try: return self.esgfConfig.get(section, key) except: return default def _setupConfig(self): '''Method that assigns the CoG settings.''' # [DEFAULT] hostName = self._safeGet("esgf.host", default='localhost') self._safeSet('SITE_NAME', hostName.upper()) self._safeSet('SITE_DOMAIN', hostName) self._safeSet('TIME_ZONE', 'America/Denver') self._safeSet('SECRET_KEY', get_random_string(length=128)) self._safeSet('COG_MAILING_LIST','<EMAIL>') if self.esgf: # ESGF: use postgres by default self._safeSet('DJANGO_DATABASE','postgres') else: # no ESGF: use sqllite3 by default self._safeSet('DJANGO_DATABASE','sqllite3') # if DJANGO_DATABASE=sqllite3 self._safeSet('DATABASE_PATH','%s/django.data' % COG_CONFIG_DIR) # if DJANGO_DATABASE=postgres self._safeSet('DATABASE_NAME', 'cogdb') self._safeSet('DATABASE_USER', self._safeGet("db.user")) self._safeSet('DATABASE_PASSWORD', self._safeGet("db.password")) self._safeSet('DATABASE_HOST', self._safeGet("db.host", default='localhost')) self._safeSet('DATABASE_PORT', self._safeGet("db.port", default='5432')) self._safeSet('MEDIA_ROOT','%s/site_media' % COG_CONFIG_DIR) # default project to where '/' requests are redirected self._safeSet('HOME_PROJECT', DEFAULT_PROJECT_SHORT_NAME) # default search service URL, before any project customization self._safeSet('DEFAULT_SEARCH_URL','http://%s/esg-search/search/' % hostName) # interval between updates of user's projects, during user session self._safeSet('MY_PROJECTS_REFRESH_SECONDS', 3600) # optional number of days after which password expire self._safeSet('PWD_EXPIRATION_DAYS','0') # optional top-level URL to redirect user registration (no trailing '/') idpPeer = self._safeGet("esgf.idp.peer", default=None) if hostName != idpPeer and idpPeer is not None: self._safeSet('IDP_REDIRECT', 'https://%s' % idpPeer) # redirect to specified "esgf.idp.peer" else: self._safeSet('IDP_REDIRECT','') # no redirect by default # DEBUG setting: must be False for production servers to avoid broadcasting detailed system paths self._safeSet('DEBUG', 'False') # ALLOWED_HOSTS = [] must be included if DEBUG=False self._safeSet('ALLOWED_HOSTS', hostName) # IDP_WHITELIST = /esg/config/esgf_idp.xml, /esg/config/esgf_idp_static.xml self._safeSet('IDP_WHITELIST', IDP_WHITELIST) # KNOWN_PROVIDERS = /esg/config/esgf_known_providers.xml self._safeSet('KNOWN_PROVIDERS', KNOWN_PROVIDERS) # PEER_NODES = /esg/config/esgf_cogs.xml self._safeSet('PEER_NODES', PEER_NODES) # option to send SESSION and CSRF cookies via SSL only - requires full SSL-encrypted site self._safeSet('PRODUCTION_SERVER', True) # ESGF software stack version esgfVersion = self._safeGet("version", default=None) if esgfVersion: self._safeSet('ESGF_VERSION', esgfVersion, override=True) # option to disable CAPTCHA for creating account in automatic testing self._safeSet('USE_CAPTCHA', True) #[ESGF] if self.esgf: self._safeSet('ESGF_HOSTNAME', hostName, section=SECTION_ESGF) self._safeSet('ESGF_DBURL', "postgresql://%s:%s@%s/esgcet" % (self._safeGet("db.user"), self._safeGet("db.password"), self._safeGet("db.host")), section=SECTION_ESGF) #[EMAIL] self._safeSet('EMAIL_SERVER', self._safeGet("mail.smtp.host"), section=SECTION_EMAIL) self._safeSet('EMAIL_PORT', '', section=SECTION_EMAIL) self._safeSet('EMAIL_SENDER', self._safeGet("mail.admin.address", default='CoG@%s' % hostName), section=SECTION_EMAIL) self._safeSet('EMAIL_USERNAME', '', section=SECTION_EMAIL) self._safeSet('EMAIL_PASSWORD', '', section=SECTION_EMAIL) self._safeSet('EMAIL_SECURITY', 'STARTTLS', section=SECTION_EMAIL) def _writeCogConfig(self): '''Method to write out the new CoG configuration.''' # backup existing file if os.path.exists( CONFIGFILEPATH ): os.rename(CONFIGFILEPATH, CONFIGFILEPATH + "-backup-%s" % time.strftime('%Y-%m-%d_%H:%M:%S')) cfgfile = open(CONFIGFILEPATH,'w') self.cogConfig.write(cfgfile) cfgfile.close() logging.info("Written CoG configuration file: %s" % CONFIGFILEPATH) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) cogConfig = CogConfig(False) # esgfFlag cogConfig.config()
zhangdulin/common-utils
src/dom/addEventListener.js
<reponame>zhangdulin/common-utils /* * @Author: zhangyu * @Email: <EMAIL> * @Date: 2021-06-22 09:05:29 * @LastEditors: zhangyu * @LastEditTime: 2021-06-25 14:09:39 * @Description: */ function isDOM(dom) { return (typeof HTMLElement === 'function') ? (dom instanceof HTMLElement) : (dom && (typeof dom === 'object') && (dom.nodeType === 1) && (typeof dom.nodeName === 'string')); } function pasteEvent(event) { //谷歌浏览器的的粘贴文件在这个对象下面 if (event.clipboardData || event.originalEvent) { var clipboardData = (event.clipboardData || event.originalEvent.clipboardData); var items = clipboardData.items //获取文件的属性就在这里获取,打印该对象可以看到相关属性,结果的操作就在items里面,所以需要循环items let fileObj = null for (let i = 0; i < items.length; i++) { // (items[i].type.indexOf("image") //getAsFile() 此方法只是该浏览器下才会有的方法 fileObj = items[i].getAsFile(); } return fileObj // 第一种 // 在上面的代码if处接着写 // if(fileObj !== null) { // var fileUrl=URL.createObjectURL(blob); // document.getElementById("imgNode").src=fileUrl; // } // URL是一个公用的对象 // 第二种方法是用base64的方法可以实现, 需要借助FileReader对象 // var reader = new FileReader(); // reader.onload = function (event) { // //event.target.result 即为图片的Base64编码字符串 // var base64_str = event.target.result; // document.getElementById("imgNode").src=base64_str; // } // reader.readAsDataURL(blob); } else { return 'errpr-nonsupport' } } /** * @description: 获取黏贴内容 复制文本内容 * @param {*} clipboardObj.getClipboardData 获取黏贴内容传参dom; clipboardObj.copyToClipBoard 复制传参字符串 * @return {*} Boolean */ export const clipboardObj = { dom: '', value: '', getClipboardData(dom) { const domPaste = (dom && isDOM(dom)) || document.body domPaste && dom.addEventListener('paste', pasteEvent) }, copyToClipBoard(value) { if (document.execCommand) { var x = document.createElement("INPUT"); console.log(x) x.setAttribute("type", "text") x.value = value document.body.appendChild(x) x.select(); document.execCommand("Copy"); x.style.display = 'none'; document.body.removeChild(x) return true; } if (window.clipboardData) { window.clipboardData.setData("Text", value); return true; } return false; } } /** * @description: 焦点相关功能函数 * @param {*} focus:获取焦点 传入dom;insertAfterText:插入文本 传参dom 文本;getCursortPosition:获取光标位置 传参dom; setCaretPosition: 设置光标位置 传参dom 位置 * @return {*} */ export const cursortPosition = { textDom: '', value: '', focus(textDom) { if (window.getSelection) { // ie11 10 9 ff safari textDom.focus() // 解决ff不获取焦点无法定位问题 const range = window.getSelection() // 创建range range.selectAllChildren(textDom) // range 选择textDom下所有子内容 range.collapseToEnd() // 光标移至最后 } else if (document.selection) { // ie10 9 8 7 6 5 const range = document.selection.createRange() // 创建选择对象 // var range = document.body.createTextRange(); range.moveToElementText(textDom) // range定位到textDom range.collapse(false) // 光标移至最后 range.select() } else { textDom.focus() } }, // 插入文本 insertAfterText(textDom, value) { var selectRange; // 文本长度 var length = textDom.value && String(textDom.value+value).length || String(value).length if (document.selection) { // IE Support textDom.focus(); selectRange = document.selection.createRange(); selectRange.text = value; textDom.focus(); this.setCaretPosition(textDom, length) return selectRange.text; } else if (textDom.selectionStart || textDom.selectionStart == '0') { // Firefox support const startPos = textDom.selectionStart; const endPos = textDom.selectionEnd; const scrollTop = textDom.scrollTop; textDom.value = textDom.value.substring(0, startPos) + value + textDom.value.substring(endPos, textDom.value.length); textDom.focus(); textDom.selectionStart = startPos + value.length; textDom.selectionEnd = startPos + value.length; textDom.scrollTop = scrollTop; this.setCaretPosition(textDom, length) return textDom.value; } else { textDom.value += value; textDom.focus(); this.setCaretPosition(textDom, length) return textDom.value; } }, // 获取光标位置 getCursortPosition(textDom) { var cursorPos = 0; if (document.selection) { // IE Support textDom.focus(); const selectRange = document.selection.createRange(); selectRange.moveStart('character', -textDom.value.length); cursorPos = selectRange.text.length; } else if (textDom.selectionStart || textDom.selectionStart == '0') { // Firefox support cursorPos = textDom.selectionStart; } return cursorPos; }, // 设置光标位置 setCaretPosition(textDom, pos) { if (textDom.setSelectionRange) { // IE Support textDom.focus(); textDom.setSelectionRange(pos, pos); } else if (textDom.createTextRange) { // Firefox support const range = textDom.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } } }
devgateway/ocportal
web/src/main/java/org/devgateway/ocds/web/flags/release/ReleaseFlagI085Processor.java
<filename>web/src/main/java/org/devgateway/ocds/web/flags/release/ReleaseFlagI085Processor.java package org.devgateway.ocds.web.flags.release; import org.devgateway.ocds.persistence.mongo.Detail; import org.devgateway.ocds.persistence.mongo.FlaggedRelease; import org.devgateway.ocds.persistence.mongo.flags.AbstractFlaggedReleaseFlagProcessor; import org.devgateway.ocds.persistence.mongo.flags.Flag; import org.devgateway.ocds.persistence.mongo.flags.FlagType; import org.devgateway.ocds.persistence.mongo.flags.preconditions.FlaggedReleasePredicates; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author mpostelnicu * <p> * i085 Bids are an exact percentage apart */ @Component public class ReleaseFlagI085Processor extends AbstractFlaggedReleaseFlagProcessor { private MathContext mc = new MathContext(4, RoundingMode.HALF_UP); public BigDecimal getPercent(BigDecimal left, BigDecimal right) { if (left.equals(right) || right.equals(BigDecimal.ZERO)) { return null; } BigDecimal divide = left.divide(right, mc); return divide; } @PostConstruct @Override protected void setPredicates() { preconditionsPredicates = Collections.synchronizedList(Arrays.asList( FlaggedReleasePredicates.ACTIVE_AWARD, FlaggedReleasePredicates.OPEN_PROCUREMENT_METHOD, FlaggedReleasePredicates.MULTIPLE_BIDS )); } @Override protected void setFlag(Flag flag, FlaggedRelease flaggable) { flaggable.getFlags().setI085(flag); } @Override protected Set<FlagType> flagTypes() { return new HashSet<>(Collections.singletonList(FlagType.COLLUSION)); } @Override protected Boolean calculateFlag(FlaggedRelease flaggable, StringBuffer rationale) { List<BigDecimal> bids = new ArrayList<>(); for (Detail bid : flaggable.getBids().getDetails()) { if (bid.getValue() != null) { bids.add(bid.getValue().getAmount()); } } for (int x = 0; x < bids.size(); x++) { for (int y = 0; y < bids.size(); y++) { BigDecimal percent = getPercent(bids.get(x), bids.get(y)); //percent has to be non null, with scale of 2 or less, and less than twice the other number if (percent != null && percent.scale() <= 2 && percent.compareTo(BigDecimal.valueOf(2)) < 0) { rationale.append("Bids ") .append(bids.get(x)) .append(" and ") .append(bids.get(y)) .append(" are an exact % apart: ") .append(percent); return true; } } } return false; } }
guoshucan/mpaas
ghost.framework.web.mvc.context/src/main/java/ghost/framework/web/mvc/context/bind/package-info.java
/** * package: ghost.framework.web.mvc.context.bind * * @Author: 郭树灿{gsc-e590} * @link: 手机:13715848993, QQ 27048384 * @Description:mvc内容绑定包 * @Date: 2020/5/27:23:31 */ package ghost.framework.web.mvc.context.bind;
fahamk/writersblock
node_modules/@firebase/firestore/dist/cjs/src/local/local_serializer.js
<filename>node_modules/@firebase/firestore/dist/cjs/src/local/local_serializer.js "use strict"; /** * Copyright 2017 Google Inc. * * 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. */ Object.defineProperty(exports, "__esModule", { value: true }); var snapshot_version_1 = require("../core/snapshot_version"); var timestamp_1 = require("../core/timestamp"); var document_1 = require("../model/document"); var document_key_1 = require("../model/document_key"); var mutation_batch_1 = require("../model/mutation_batch"); var assert_1 = require("../util/assert"); var indexeddb_schema_1 = require("./indexeddb_schema"); var query_data_1 = require("./query_data"); /** Serializer for values stored in the LocalStore. */ var LocalSerializer = /** @class */ (function () { function LocalSerializer(remoteSerializer) { this.remoteSerializer = remoteSerializer; } /** Decodes a remote document from storage locally to a Document. */ LocalSerializer.prototype.fromDbRemoteDocument = function (remoteDoc) { if (remoteDoc.document) { return this.remoteSerializer.fromDocument(remoteDoc.document); } else if (remoteDoc.noDocument) { var key = document_key_1.DocumentKey.fromSegments(remoteDoc.noDocument.path); var readTime = remoteDoc.noDocument.readTime; var timestamp = new timestamp_1.Timestamp(readTime.seconds, readTime.nanos); return new document_1.NoDocument(key, snapshot_version_1.SnapshotVersion.fromTimestamp(timestamp)); } else { return assert_1.fail('Unexpected DbRemoteDocument'); } }; /** Encodes a document for storage locally. */ LocalSerializer.prototype.toDbRemoteDocument = function (maybeDoc) { if (maybeDoc instanceof document_1.Document) { var doc = this.remoteSerializer.toDocument(maybeDoc); return new indexeddb_schema_1.DbRemoteDocument(null, doc); } else { var path = maybeDoc.key.path.toArray(); var timestamp = maybeDoc.version.toTimestamp(); var readTime = new indexeddb_schema_1.DbTimestamp(timestamp.seconds, timestamp.nanos); return new indexeddb_schema_1.DbRemoteDocument(new indexeddb_schema_1.DbNoDocument(path, readTime), null); } }; /** Encodes a batch of mutations into a DbMutationBatch for local storage. */ LocalSerializer.prototype.toDbMutationBatch = function (userId, batch) { var _this = this; var serializedMutations = batch.mutations.map(function (m) { return _this.remoteSerializer.toMutation(m); }); return new indexeddb_schema_1.DbMutationBatch(userId, batch.batchId, batch.localWriteTime.toEpochMilliseconds(), serializedMutations); }; /** Decodes a DbMutationBatch into a MutationBatch */ LocalSerializer.prototype.fromDbMutationBatch = function (dbBatch) { var _this = this; var mutations = dbBatch.mutations.map(function (m) { return _this.remoteSerializer.fromMutation(m); }); var timestamp = timestamp_1.Timestamp.fromEpochMilliseconds(dbBatch.localWriteTimeMs); return new mutation_batch_1.MutationBatch(dbBatch.batchId, timestamp, mutations); }; /** Decodes a DbTarget into QueryData */ LocalSerializer.prototype.fromDbTarget = function (dbTarget) { var readTime = new timestamp_1.Timestamp(dbTarget.readTime.seconds, dbTarget.readTime.nanos); var version = snapshot_version_1.SnapshotVersion.fromTimestamp(readTime); var query; if (isDocumentQuery(dbTarget.query)) { query = this.remoteSerializer.fromDocumentsTarget(dbTarget.query); } else { query = this.remoteSerializer.fromQueryTarget(dbTarget.query); } return new query_data_1.QueryData(query, dbTarget.targetId, query_data_1.QueryPurpose.Listen, version, dbTarget.resumeToken); }; /** Encodes QueryData into a DbTarget for storage locally. */ LocalSerializer.prototype.toDbTarget = function (queryData) { assert_1.assert(query_data_1.QueryPurpose.Listen === queryData.purpose, 'Only queries with purpose ' + query_data_1.QueryPurpose.Listen + ' may be stored, got ' + queryData.purpose); var timestamp = queryData.snapshotVersion.toTimestamp(); var dbTimestamp = new indexeddb_schema_1.DbTimestamp(timestamp.seconds, timestamp.nanos); var queryProto; if (queryData.query.isDocumentQuery()) { queryProto = this.remoteSerializer.toDocumentsTarget(queryData.query); } else { queryProto = this.remoteSerializer.toQueryTarget(queryData.query); } assert_1.assert(typeof queryData.resumeToken === 'string', 'Persisting non-string resume token not supported.'); var resumeToken = queryData.resumeToken; // lastListenSequenceNumber is always 0 until we do real GC. return new indexeddb_schema_1.DbTarget(queryData.targetId, queryData.query.canonicalId(), dbTimestamp, resumeToken, 0, queryProto); }; return LocalSerializer; }()); exports.LocalSerializer = LocalSerializer; /** * A helper function for figuring out what kind of query has been stored. */ function isDocumentQuery(dbQuery) { return dbQuery.documents !== undefined; } //# sourceMappingURL=local_serializer.js.map
zsilbi/cphalcon
ext/phalcon/firewall/adapter/adapterinterface.zep.c
#ifdef HAVE_CONFIG_H #include "../../../ext_config.h" #endif #include <php.h> #include "../../../php_ext.h" #include "../../../ext.h" #include <Zend/zend_exceptions.h> #include "kernel/main.h" /** * This file is part of the Phalcon Framework. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE.txt * file that was distributed with this source code. */ /** * Interface for Phalcon\Mvc\Dispatcher\Firewall adapters */ ZEPHIR_INIT_CLASS(Phalcon_Firewall_Adapter_AdapterInterface) { ZEPHIR_REGISTER_INTERFACE(Phalcon\\Firewall\\Adapter, AdapterInterface, phalcon, firewall_adapter_adapterinterface, phalcon_firewall_adapter_adapterinterface_method_entry); return SUCCESS; } /** * Returns the default ACL access level */ ZEPHIR_DOC_METHOD(Phalcon_Firewall_Adapter_AdapterInterface, getDefaultAccess); /** * Gets role callback to fetch role name */ ZEPHIR_DOC_METHOD(Phalcon_Firewall_Adapter_AdapterInterface, getRoleCallback); /** * Gets always resolving role option */ ZEPHIR_DOC_METHOD(Phalcon_Firewall_Adapter_AdapterInterface, isAlwaysResolvingRole); /** * Sets always resolving role option */ ZEPHIR_DOC_METHOD(Phalcon_Firewall_Adapter_AdapterInterface, setAlwaysResolvingRole); /** * Sets cache backend */ ZEPHIR_DOC_METHOD(Phalcon_Firewall_Adapter_AdapterInterface, setCache); /** * Sets the default access level (Phalcon\Acl::ALLOW or Phalcon\Acl::DENY) */ ZEPHIR_DOC_METHOD(Phalcon_Firewall_Adapter_AdapterInterface, setDefaultAccess); /** * Sets role callback to fetch role name */ ZEPHIR_DOC_METHOD(Phalcon_Firewall_Adapter_AdapterInterface, setRoleCallback);
SheelaQueen/Gravebot
src/translate.js
<reponame>SheelaQueen/Gravebot import glob from 'glob'; import path from 'path'; import R from 'ramda'; import logger from './logger'; // Load in translations const translations_path = path.join(__dirname, '../i18n'); const translations = R.fromPairs(R.map(file_path => { return [path.basename(file_path).replace(/.json/g, ''), require(file_path)]; }, glob.sync(`${translations_path}/*(!(_source.json))`))); // Load up variables that don't require translations // TODO: Temporary workaround to fix tests failing. let static_texts = {}; if (!process.env.TEST) { static_texts = R.map(js_path => { const help_data = require(js_path).help; if (help_data) return R.map(R.prop('static_texts'), R.values(help_data)); }, require('./commands').command_files); static_texts = R.mergeAll(R.reject(R.isNil, R.flatten(static_texts))); } export default function translate(key, lang = 'en') { let translation = translations[lang][key] || translations.en[key] || ''; if (!translations[lang][key]) logger.warn(`${key} in language ${lang} does not exist`); const static_text = translation.match(/[^#{]+(?=\})/g); if (static_text) { R.forEach(key => { if (static_texts[key]) translation = translation.replace(new RegExp(`#{${key}}`, 'g'), static_texts[key]); }, static_text); } return translation; } export const langs = R.keys(translations);
jamolnng/WebServer
WebServerCommon/status_line.cpp
/* Copyright 2018 <NAME> */ #include "status_line.h" using webserver::http::response::StatusLine; StatusLine::StatusLine() noexcept : Line({"HTTP-Version", "Status-Code", "Reason-Phrase"}) {}
UlrichBerntien/Codewars-Katas
7_kyu/Two_to_One.py
# Merges the characters of two strings. # Returned strings is sorted of unique characters. def longest(a1 :str, a2 :str) -> str: accu = set(a1) accu.update(a2) return "".join(sorted(accu))
ceekay1991/AliPayForDebug
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/CTGrowingTextViewSizeDelegate-Protocol.h
<reponame>ceekay1991/AliPayForDebug<filename>AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/CTGrowingTextViewSizeDelegate-Protocol.h<gh_stars>1-10 // // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import "NSObject-Protocol.h" @class CTGrowingTextView; @protocol CTGrowingTextViewSizeDelegate <NSObject> - (void)growingTextView:(CTGrowingTextView *)arg1 didChangeHeight:(float)arg2; - (void)growingTextView:(CTGrowingTextView *)arg1 willChangeHeight:(float)arg2; @end
BjornMelgaard/ran
app/containers/Layout/App.js
import PropTypes from 'prop-types' import { ThemeProvider, injectGlobal } from 'styled-components' import getTheme from '~/themes' import installOfflinePlugin from '~/lib/installOfflinePlugin' import { App as StyledApp } from '~/components/Theme' const App = ({ children, theme }) => { installOfflinePlugin() return ( <ThemeProvider theme={getTheme(theme)}> <StyledApp> {children} </StyledApp> </ThemeProvider> ) } App.defaultProps = { theme: 'main' } App.propTypes = { children: PropTypes.array.isRequired, theme: PropTypes.string } injectGlobal` * { font-family: Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, serif; } body { margin: 0; padding: 20px 40px; } ` export default App
lastweek/source-freebsd
src/usr.bin/netstat/mroute.c
/*- * SPDX-License-Identifier: BSD-4-Clause * * Copyright (c) 1989 <NAME> * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * <NAME> of Stanford University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)mroute.c 8.2 (Berkeley) 4/28/95 */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); /* * Print multicast routing structures and statistics. * * MROUTING 1.0 */ #include <sys/param.h> #include <sys/queue.h> #include <sys/socket.h> #include <sys/socketvar.h> #include <sys/sysctl.h> #include <sys/protosw.h> #include <sys/mbuf.h> #include <sys/time.h> #include <net/if.h> #include <netinet/in.h> #include <netinet/igmp.h> #include <net/route.h> #define _KERNEL 1 #include <netinet/ip_mroute.h> #undef _KERNEL #include <err.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <libxo/xo.h> #include "netstat.h" #include "nl_defs.h" static void print_bw_meter(struct bw_meter *, int *); static void print_mfc(struct mfc *, int, int *); static void print_bw_meter(struct bw_meter *bw_meter, int *banner_printed) { char s1[256], s2[256], s3[256]; struct timeval now, end, delta; gettimeofday(&now, NULL); if (! *banner_printed) { xo_open_list("bandwidth-meter"); xo_emit(" {T:Bandwidth Meters}\n"); xo_emit(" {T:/%-30s}", "Measured(Start|Packets|Bytes)"); xo_emit(" {T:/%s}", "Type"); xo_emit(" {T:/%-30s}", "Thresh(Interval|Packets|Bytes)"); xo_emit(" {T:Remain}"); xo_emit("\n"); *banner_printed = 1; } xo_open_instance("bandwidth-meter"); /* The measured values */ if (bw_meter->bm_flags & BW_METER_UNIT_PACKETS) { snprintf(s1, sizeof(s1), "%ju", (uintmax_t)bw_meter->bm_measured.b_packets); xo_emit("{e:measured-packets/%ju}", (uintmax_t)bw_meter->bm_measured.b_packets); } else strcpy(s1, "?"); if (bw_meter->bm_flags & BW_METER_UNIT_BYTES) { snprintf(s2, sizeof(s2), "%ju", (uintmax_t)bw_meter->bm_measured.b_bytes); xo_emit("{e:measured-bytes/%ju}", (uintmax_t)bw_meter->bm_measured.b_bytes); } else strcpy(s2, "?"); xo_emit(" {[:-30}{:start-time/%lu.%06lu}|{q:measured-packets/%s}" "|{q:measured-bytes%s}{]:}", (u_long)bw_meter->bm_start_time.tv_sec, (u_long)bw_meter->bm_start_time.tv_usec, s1, s2); /* The type of entry */ xo_emit(" {t:type/%-3s}", (bw_meter->bm_flags & BW_METER_GEQ) ? ">=" : (bw_meter->bm_flags & BW_METER_LEQ) ? "<=" : "?"); /* The threshold values */ if (bw_meter->bm_flags & BW_METER_UNIT_PACKETS) { snprintf(s1, sizeof(s1), "%ju", (uintmax_t)bw_meter->bm_threshold.b_packets); xo_emit("{e:threshold-packets/%ju}", (uintmax_t)bw_meter->bm_threshold.b_packets); } else strcpy(s1, "?"); if (bw_meter->bm_flags & BW_METER_UNIT_BYTES) { snprintf(s2, sizeof(s2), "%ju", (uintmax_t)bw_meter->bm_threshold.b_bytes); xo_emit("{e:threshold-bytes/%ju}", (uintmax_t)bw_meter->bm_threshold.b_bytes); } else strcpy(s2, "?"); xo_emit(" {[:-30}{:threshold-time/%lu.%06lu}|{q:threshold-packets/%s}" "|{q:threshold-bytes%s}{]:}", (u_long)bw_meter->bm_threshold.b_time.tv_sec, (u_long)bw_meter->bm_threshold.b_time.tv_usec, s1, s2); /* Remaining time */ timeradd(&bw_meter->bm_start_time, &bw_meter->bm_threshold.b_time, &end); if (timercmp(&now, &end, <=)) { timersub(&end, &now, &delta); snprintf(s3, sizeof(s3), "%lu.%06lu", (u_long)delta.tv_sec, (u_long)delta.tv_usec); } else { /* Negative time */ timersub(&now, &end, &delta); snprintf(s3, sizeof(s3), "-%lu.06%lu", (u_long)delta.tv_sec, (u_long)delta.tv_usec); } xo_emit(" {:remaining-time/%s}", s3); xo_open_instance("bandwidth-meter"); xo_emit("\n"); } static void print_mfc(struct mfc *m, int maxvif, int *banner_printed) { struct sockaddr_in sin; struct sockaddr *sa = (struct sockaddr *)&sin; struct bw_meter bw_meter, *bwm; int bw_banner_printed; int error; vifi_t vifi; bw_banner_printed = 0; memset(&sin, 0, sizeof(sin)); sin.sin_len = sizeof(sin); sin.sin_family = AF_INET; if (! *banner_printed) { xo_open_list("multicast-forwarding-entry"); xo_emit("\n{T:IPv4 Multicast Forwarding Table}\n" " {T:Origin} {T:Group} " " {T:Packets In-Vif} {T:Out-Vifs:Ttls}\n"); *banner_printed = 1; } memcpy(&sin.sin_addr, &m->mfc_origin, sizeof(sin.sin_addr)); xo_emit(" {:origin-address/%-15.15s}", routename(sa, numeric_addr)); memcpy(&sin.sin_addr, &m->mfc_mcastgrp, sizeof(sin.sin_addr)); xo_emit(" {:group-address/%-15.15s}", routename(sa, numeric_addr)); xo_emit(" {:sent-packets/%9lu}", m->mfc_pkt_cnt); xo_emit(" {:parent/%3d} ", m->mfc_parent); xo_open_list("vif-ttl"); for (vifi = 0; vifi <= maxvif; vifi++) { if (m->mfc_ttls[vifi] > 0) { xo_open_instance("vif-ttl"); xo_emit(" {k:vif/%u}:{:ttl/%u}", vifi, m->mfc_ttls[vifi]); xo_close_instance("vif-ttl"); } } xo_close_list("vif-ttl"); xo_emit("\n"); /* * XXX We break the rules and try to use KVM to read the * bandwidth meters, they are not retrievable via sysctl yet. */ bwm = m->mfc_bw_meter; while (bwm != NULL) { error = kread((u_long)bwm, (char *)&bw_meter, sizeof(bw_meter)); if (error) break; print_bw_meter(&bw_meter, &bw_banner_printed); bwm = bw_meter.bm_mfc_next; } if (banner_printed) xo_close_list("bandwidth-meter"); } void mroutepr() { struct sockaddr_in sin; struct sockaddr *sa = (struct sockaddr *)&sin; struct vif viftable[MAXVIFS]; struct vif *v; struct mfc *m; u_long pmfchashtbl, pmfctablesize, pviftbl; int banner_printed; int saved_numeric_addr; size_t len; vifi_t vifi, maxvif; saved_numeric_addr = numeric_addr; numeric_addr = 1; memset(&sin, 0, sizeof(sin)); sin.sin_len = sizeof(sin); sin.sin_family = AF_INET; /* * TODO: * The VIF table will move to hanging off the struct if_info for * each IPv4 configured interface. Currently it is statically * allocated, and retrieved either using KVM or an opaque SYSCTL. * * This can't happen until the API documented in multicast(4) * is itself refactored. The historical reason why VIFs use * a separate ifindex space is entirely due to the legacy * capability of the MROUTING code to create IPIP tunnels on * the fly to support DVMRP. When gif(4) became available, this * functionality was deprecated, as PIM does not use it. */ maxvif = 0; pmfchashtbl = pmfctablesize = pviftbl = 0; len = sizeof(viftable); if (live) { if (sysctlbyname("net.inet.ip.viftable", viftable, &len, NULL, 0) < 0) { xo_warn("sysctl: net.inet.ip.viftable"); return; } } else { pmfchashtbl = nl[N_MFCHASHTBL].n_value; pmfctablesize = nl[N_MFCTABLESIZE].n_value; pviftbl = nl[N_VIFTABLE].n_value; if (pmfchashtbl == 0 || pmfctablesize == 0 || pviftbl == 0) { xo_warnx("No IPv4 MROUTING kernel support."); return; } kread(pviftbl, (char *)viftable, sizeof(viftable)); } banner_printed = 0; for (vifi = 0, v = viftable; vifi < MAXVIFS; ++vifi, ++v) { if (v->v_lcl_addr.s_addr == 0) continue; maxvif = vifi; if (!banner_printed) { xo_emit("\n{T:IPv4 Virtual Interface Table\n" " Vif Thresh Local-Address " "Remote-Address Pkts-In Pkts-Out}\n"); banner_printed = 1; xo_open_list("vif"); } xo_open_instance("vif"); memcpy(&sin.sin_addr, &v->v_lcl_addr, sizeof(sin.sin_addr)); xo_emit(" {:vif/%2u} {:threshold/%6u} {:route/%-15.15s}", /* opposite math of add_vif() */ vifi, v->v_threshold, routename(sa, numeric_addr)); memcpy(&sin.sin_addr, &v->v_rmt_addr, sizeof(sin.sin_addr)); xo_emit(" {:source/%-15.15s}", (v->v_flags & VIFF_TUNNEL) ? routename(sa, numeric_addr) : ""); xo_emit(" {:received-packets/%9lu} {:sent-packets/%9lu}\n", v->v_pkt_in, v->v_pkt_out); xo_close_instance("vif"); } if (banner_printed) xo_close_list("vif"); else xo_emit("\n{T:IPv4 Virtual Interface Table is empty}\n"); banner_printed = 0; /* * TODO: * The MFC table will move into the AF_INET radix trie in future. * In 8.x, it becomes a dynamically allocated structure referenced * by a hashed LIST, allowing more than 256 entries w/o kernel tuning. * * If retrieved via opaque SYSCTL, the kernel will coalesce it into * a static table for us. * If retrieved via KVM, the hash list pointers must be followed. */ if (live) { struct mfc *mfctable; len = 0; if (sysctlbyname("net.inet.ip.mfctable", NULL, &len, NULL, 0) < 0) { xo_warn("sysctl: net.inet.ip.mfctable"); return; } mfctable = malloc(len); if (mfctable == NULL) { xo_warnx("malloc %lu bytes", (u_long)len); return; } if (sysctlbyname("net.inet.ip.mfctable", mfctable, &len, NULL, 0) < 0) { free(mfctable); xo_warn("sysctl: net.inet.ip.mfctable"); return; } m = mfctable; while (len >= sizeof(*m)) { print_mfc(m++, maxvif, &banner_printed); len -= sizeof(*m); } if (banner_printed) xo_close_list("multicast-forwarding-entry"); if (len != 0) xo_warnx("print_mfc: %lu trailing bytes", (u_long)len); free(mfctable); } else { LIST_HEAD(, mfc) *mfchashtbl; u_long i, mfctablesize; struct mfc mfc; int error; error = kread(pmfctablesize, (char *)&mfctablesize, sizeof(u_long)); if (error) { xo_warn("kread: mfctablesize"); return; } len = sizeof(*mfchashtbl) * mfctablesize; mfchashtbl = malloc(len); if (mfchashtbl == NULL) { xo_warnx("malloc %lu bytes", (u_long)len); return; } kread(pmfchashtbl, (char *)&mfchashtbl, len); for (i = 0; i < mfctablesize; i++) { LIST_FOREACH(m, &mfchashtbl[i], mfc_hash) { kread((u_long)m, (char *)&mfc, sizeof(mfc)); print_mfc(m, maxvif, &banner_printed); } } if (banner_printed) xo_close_list("multicast-forwarding-entry"); free(mfchashtbl); } if (!banner_printed) xo_emit("\n{T:IPv4 Multicast Forwarding Table is empty}\n"); xo_emit("\n"); numeric_addr = saved_numeric_addr; } void mrt_stats() { struct mrtstat mrtstat; u_long mstaddr; mstaddr = nl[N_MRTSTAT].n_value; if (fetch_stats("net.inet.ip.mrtstat", mstaddr, &mrtstat, sizeof(mrtstat), kread_counters) != 0) { if ((live && errno == ENOENT) || (!live && mstaddr == 0)) fprintf(stderr, "No IPv4 MROUTING kernel support.\n"); return; } xo_emit("{T:IPv4 multicast forwarding}:\n"); #define p(f, m) if (mrtstat.f || sflag <= 1) \ xo_emit(m, (uintmax_t)mrtstat.f, plural(mrtstat.f)) #define p2(f, m) if (mrtstat.f || sflag <= 1) \ xo_emit(m, (uintmax_t)mrtstat.f, plurales(mrtstat.f)) xo_open_container("multicast-statistics"); p(mrts_mfc_lookups, "\t{:cache-lookups/%ju} " "{N:/multicast forwarding cache lookup%s}\n"); p2(mrts_mfc_misses, "\t{:cache-misses/%ju} " "{N:/multicast forwarding cache miss%s}\n"); p(mrts_upcalls, "\t{:upcalls-total/%ju} " "{N:/upcall%s to multicast routing daemon}\n"); p(mrts_upq_ovflw, "\t{:upcall-overflows/%ju} " "{N:/upcall queue overflow%s}\n"); p(mrts_upq_sockfull, "\t{:upcalls-dropped-full-buffer/%ju} " "{N:/upcall%s dropped due to full socket buffer}\n"); p(mrts_cache_cleanups, "\t{:cache-cleanups/%ju} " "{N:/cache cleanup%s}\n"); p(mrts_no_route, "\t{:dropped-no-origin/%ju} " "{N:/datagram%s with no route for origin}\n"); p(mrts_bad_tunnel, "\t{:dropped-bad-tunnel/%ju} " "{N:/datagram%s arrived with bad tunneling}\n"); p(mrts_cant_tunnel, "\t{:dropped-could-not-tunnel/%ju} " "{N:/datagram%s could not be tunneled}\n"); p(mrts_wrong_if, "\t{:dropped-wrong-incoming-interface/%ju} " "{N:/datagram%s arrived on wrong interface}\n"); p(mrts_drop_sel, "\t{:dropped-selectively/%ju} " "{N:/datagram%s selectively dropped}\n"); p(mrts_q_overflow, "\t{:dropped-queue-overflow/%ju} " "{N:/datagram%s dropped due to queue overflow}\n"); p(mrts_pkt2large, "\t{:dropped-too-large/%ju} " "{N:/datagram%s dropped for being too large}\n"); #undef p2 #undef p }
aonguyen123/frontend_KiemDien
src/views/ClassDetail/components/CardClassMember/components/TableToolBar.js/TableToolBar.js
<gh_stars>0 import React, { useState } from 'react'; import clsx from 'clsx'; import { withStyles } from '@material-ui/core/styles'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import IconButton from '@material-ui/core/IconButton'; import Tooltip from '@material-ui/core/Tooltip'; import DeleteIcon from '@material-ui/icons/Delete'; import EditIcon from '@material-ui/icons/Edit'; import { ConfirmDialog } from 'components'; import EditMemberDialog from './../EditMemberDialog/EditMemberDialog'; import styles from './styles'; const TableToolBar = props => { const { selectedMember, selectedMssv, classes, member, idClass, errors, editClassMemberById, clearErrors, deleteClassMemberById } = props; const [open, setOpen] = useState(false); const [openConfirm, setOpenConfirm] = useState(false); const handleClickEdit = () => { setOpen(true); }; const handleOpenConfirm = () => { setOpenConfirm(true); }; const handleCloseDialog = params => { setOpen(params); }; const closeConfirm = params => { setOpenConfirm(params); }; const handleClickDelete = () => { deleteClassMemberById(idClass, selectedMember, selectedMssv); }; return ( <React.Fragment> <ConfirmDialog open={openConfirm} closeDialog={closeConfirm} deleteConfirm={handleClickDelete} title="Delete class member" /> <EditMemberDialog open={open} handleCloseDialog={handleCloseDialog} member={member} idClass={idClass} errors={errors} editClassMemberById={editClassMemberById} clearErrors={clearErrors} /> <Toolbar className={clsx(classes.root, { [classes.highlight]: selectedMember.length > 0 })} > {selectedMember.length > 0 && ( <Typography className={classes.title} color="inherit" variant="subtitle1" > {selectedMember.length} selected </Typography> )} {selectedMember.length === 1 && ( <Tooltip title="Edit"> <IconButton aria-label="edit" onClick={handleClickEdit}> <EditIcon color="primary" /> </IconButton> </Tooltip> )} {selectedMember.length > 0 && ( <Tooltip title="Delete"> <IconButton aria-label="delete" onClick={handleOpenConfirm} > <DeleteIcon color="secondary" /> </IconButton> </Tooltip> )} </Toolbar> </React.Fragment> ); }; export default withStyles(styles)(TableToolBar);
wuhlcom/tio-showcase
im/server/src/main/java/org/tio/examples/im/service/BadWordService.java
package org.tio.examples.im.service; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tio.examples.im.server.ImServerStarter; import cn.hutool.core.io.FileUtil; import cn.hutool.dfa.WordTree; /** * @author tanyaowu * 2017年5月29日 下午2:50:41 */ public class BadWordService { public static interface BadWordHandler { /** * * @param initText * @param badWord * @return * @author tanyaowu */ String replace(String initText, String badWord); } public static class BaiduBadWordHandler implements BadWordHandler { public static BaiduBadWordHandler instance = new BaiduBadWordHandler(); private BaiduBadWordHandler() { } /** * @param initText * @param badWord * @return * @author tanyaowu */ @Override public String replace(String initText, String badWord) { try { //<span style='color:#ee3344;padding:4px;border:1px solid #ee3344;border-radius:5px;margin:4px 4px;'><a href='http://www.gov.cn' target='_blank'>此处为敏感词</a></span> String baidu = "https://www.baidu.com/s?word=" + URLEncoder.encode(badWord, "utf-8");//<a href='http://www.gov.cn' target='_blank'>此处为敏感词</a> String repStr = "<a style='padding:4px;border-bottom:1px solid #ee3344;border-radius:0px;margin:0px 4px;' href='" + baidu + "' target='_blank'>此处为敏感词</a>"; return StringUtils.replaceAll(initText, badWord, repStr); } catch (UnsupportedEncodingException e) { log.error(e.toString(), e); return initText; } } } private static Logger log = LoggerFactory.getLogger(BadWordService.class); public static final WordTree wordTree = new WordTree(); public static void init() { String rootDirStr = FileUtil.getAbsolutePath("classpath:config/dict/"); File rootDir = new File(rootDirStr); File[] files = rootDir.listFiles(); int count = 0; if (files != null) { for (File file : files) { List<String> lines = FileUtil.readLines(file, "utf-8"); for (String line : lines) { wordTree.addWord(line); count++; //log.error(line); } } } log.error("一共{}个敏感词", count); } /** * @param args * @author tanyaowu */ public static void main(String[] args) { init(); replaceWithDefaultReplace("习近平dddd|sss"); } public static String replaceBadWord(String initText, BadWordHandler badWordHandler, Object logstr) { List<String> list = wordTree.matchAll(initText); if (list != null && list.size() > 0) { String ret = initText; for (String word : list) { ret = badWordHandler.replace(ret, word);//StringUtils.replaceAll(ret, word, replaceText); } if (logstr != null) { log.error("{}, 找到敏感词,原文:【{}】,替换后的:【{}】", logstr, initText, ret); } else { log.error("找到敏感词,原文:【{}】,替换后的:【{}】", initText, ret); } return ret; } return null; } public static String replaceBadWord(String initText, String replaceText) { return replaceBadWord(initText, replaceText, null); } /** * 如果没匹配到就返回null,否则返回替换后的string * @param initText * @param replaceText * @param logstr * @return * @author tanyaowu */ public static String replaceBadWord(String initText, String replaceText, Object logstr) { List<String> list = wordTree.matchAll(initText); if (list != null && list.size() > 0) { String ret = initText; for (String word : list) { ret = StringUtils.replaceAll(ret, word, replaceText); } if (logstr != null) { log.error("{}, 找到敏感词,原文:【{}】,替换后的:【{}】", logstr, initText, ret); } else { log.error("找到敏感词,原文:【{}】,替换后的:【{}】", initText, ret); } return ret; } return null; } public static String replaceWithDefaultReplace(String initText) { return replaceBadWord(initText, ImServerStarter.conf.getString("dft.badword.replaceText")); } public static String replaceWithDefaultReplace(String initText, String logstr) { return replaceBadWord(initText, ImServerStarter.conf.getString("dft.badword.replaceText"), logstr); } /** * * @author tanyaowu */ public BadWordService() { } }
gocom/startpage
tests/unit/model/Config/ConfigValue.spec.js
<filename>tests/unit/model/Config/ConfigValue.spec.js import Model from '../../../../src/model/Config/ConfigValue'; test('Defaults', () => { const config = new Model(); expect(config.id).toMatch(''); expect(config.value).toBeNull(); }); test('Pass data', () => { const config = new Model({ id: 'id', value: 'value', }); expect(config.id).toMatch('id'); expect(config.value).toMatch('value'); });
FateRevoked/mage
Mage.Sets/src/mage/cards/d/Disperse.java
package mage.cards.d; import java.util.UUID; import mage.abilities.effects.common.ReturnToHandTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.target.common.TargetNonlandPermanent; /** * * @author nantuko */ public final class Disperse extends CardImpl { public Disperse (UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{1}{U}"); // Return target nonland permanent to its owner's hand. this.getSpellAbility().addTarget(new TargetNonlandPermanent()); this.getSpellAbility().addEffect(new ReturnToHandTargetEffect()); } public Disperse (final Disperse card) { super(card); } @Override public Disperse copy() { return new Disperse(this); } }
Dee-Why/lite-bo
examples/optimize_problem_with_constraint.py
<filename>examples/optimize_problem_with_constraint.py # License: MIT import numpy as np import matplotlib.pyplot as plt from openbox import Optimizer, sp def mishra(config: sp.Configuration): config_dict = config.get_dictionary() X = np.array([config_dict['x%d' % i] for i in range(2)]) x, y = X[0], X[1] t1 = np.sin(y) * np.exp((1 - np.cos(x))**2) t2 = np.cos(x) * np.exp((1 - np.sin(y))**2) t3 = (x - y)**2 result = dict() result['objs'] = [t1 + t2 + t3, ] result['constraints'] = [np.sum((X + 5)**2) - 25, ] return result if __name__ == "__main__": params = { 'float': { 'x0': (-10, 0, -5), 'x1': (-6.5, 0, -3.25) } } space = sp.Space() space.add_variables([ sp.Real(name, *para) for name, para in params['float'].items() ]) opt = Optimizer( mishra, space, num_constraints=1, num_objs=1, surrogate_type='gp', acq_optimizer_type='random_scipy', max_runs=50, time_limit_per_trial=10, task_id='soc', ) history = opt.run() print(history) history.plot_convergence(true_minimum=-106.7645367) plt.show()
npocmaka/Windows-Server-2003
base/tools/instaler/handler.c
<reponame>npocmaka/Windows-Server-2003<filename>base/tools/instaler/handler.c /*++ Copyright (c) 1992 Microsoft Corporation Module Name: handler.c Abstract: This module contains the individual API handler routines for the INSTALER program Author: <NAME> (stevewo) 10-Aug-1994 Revision History: --*/ #include "instaler.h" #include <ntstatus.dbg> BOOLEAN HandleBreakpoint( PPROCESS_INFO Process, PTHREAD_INFO Thread, PBREAKPOINT_INFO Breakpoint ) { BOOLEAN Result; API_SAVED_PARAMETERS SavedParameters; UCHAR ApiIndex; PBREAKPOINT_INFO ReturnBreakpoint; Result = FALSE; ApiIndex = Breakpoint->ApiIndex; if (ApiInfo[ ApiIndex ].ModuleIndex < Thread->ModuleIndexCurrentlyIn) { return TRUE; } DbgEvent( DBGEVENT, ( "Processing Breakpoint at %ws!%s\n", Breakpoint->ModuleName, Breakpoint->ProcedureName ) ); if (!Breakpoint->SavedParametersValid) { memset( &SavedParameters, 0, sizeof( SavedParameters ) ); Result = TRUE; if (ExtractProcedureParameters( Process, Thread, (PVOID)&SavedParameters.ReturnAddress, ApiInfo[ ApiIndex ].SizeOfParameters, (PULONG)&SavedParameters.InputParameters ) ) { if (ApiInfo[ ApiIndex ].EntryPointHandler == NULL || (ApiInfo[ ApiIndex ].EntryPointHandler)( Process, Thread, &SavedParameters ) ) { if (SavedParameters.ReturnAddress == NULL) { Result = FALSE; } else if (CreateBreakpoint( SavedParameters.ReturnAddress, Process, Thread, // thread specific ApiIndex, &SavedParameters, &ReturnBreakpoint ) ) { ReturnBreakpoint->ModuleName = L"Return from"; ReturnBreakpoint->ProcedureName = Breakpoint->ProcedureName; Thread->ModuleIndexCurrentlyIn = ApiInfo[ ApiIndex ].ModuleIndex; SuspendAllButThisThread( Process, Thread ); } } } #if DBG TrimTemporaryBuffer(); #endif } else { if (UndoReturnAddressBreakpoint( Process, Thread ) && ExtractProcedureReturnValue( Process, Thread, &Breakpoint->SavedParameters.ReturnValue, ApiInfo[ ApiIndex ].SizeOfReturnValue ) ) { Breakpoint->SavedParameters.ReturnValueValid = TRUE; if (ApiInfo[ ApiIndex ].EntryPointHandler != NULL) { (ApiInfo[ ApiIndex ].EntryPointHandler)( Process, Thread, &Breakpoint->SavedParameters ); } } Thread->ModuleIndexCurrentlyIn = 0; FreeSavedCallState( &Breakpoint->SavedParameters.SavedCallState ); DestroyBreakpoint( Breakpoint->Address, Process, Thread ); ResumeAllButThisThread( Process, Thread ); #if DBG TrimTemporaryBuffer(); #endif Result = FALSE; } return Result; } BOOLEAN CreateSavedCallState( PPROCESS_INFO Process, PAPI_SAVED_CALL_STATE SavedCallState, API_ACTION Action, ULONG Type, PWSTR FullName, ... ) { va_list arglist; va_start( arglist, FullName ); SavedCallState->Action = Action; SavedCallState->Type = Type; SavedCallState->FullName = FullName; switch (Action) { case OpenPath: SavedCallState->PathOpen.InheritHandle = va_arg( arglist, BOOLEAN ); SavedCallState->PathOpen.WriteAccessRequested = va_arg( arglist, BOOLEAN ); SavedCallState->PathOpen.ResultHandleAddress = va_arg( arglist, PHANDLE ); break; case RenamePath: SavedCallState->PathRename.NewName = va_arg( arglist, PWSTR ); SavedCallState->PathRename.ReplaceIfExists = va_arg( arglist, BOOLEAN ); break; case DeletePath: case QueryPath: case SetValue: case DeleteValue: break; case WriteIniValue: SavedCallState->SetIniValue.SectionName = va_arg( arglist, PWSTR ); SavedCallState->SetIniValue.VariableName = va_arg( arglist, PWSTR ); SavedCallState->SetIniValue.VariableValue = va_arg( arglist, PWSTR ); break; case WriteIniSection: SavedCallState->SetIniSection.SectionName = va_arg( arglist, PWSTR ); SavedCallState->SetIniSection.SectionValue = va_arg( arglist, PWSTR ); break; default: return FALSE; } va_end( arglist ); return TRUE; } VOID FreeSavedCallState( PAPI_SAVED_CALL_STATE CallState ) { switch (CallState->Action) { case WriteIniValue: FreeMem( &CallState->SetIniValue.VariableValue ); break; case WriteIniSection: FreeMem( &CallState->SetIniSection.SectionValue ); break; } return; } BOOLEAN CaptureObjectAttributes( PPROCESS_INFO Process, POBJECT_ATTRIBUTES ObjectAttributesAddress, POBJECT_ATTRIBUTES ObjectAttributes, PUNICODE_STRING ObjectName ) { if (ObjectAttributesAddress != NULL && ReadMemory( Process, ObjectAttributesAddress, ObjectAttributes, sizeof( *ObjectAttributes ), "object attributes" ) && ObjectAttributes->ObjectName != NULL && ReadMemory( Process, ObjectAttributes->ObjectName, ObjectName, sizeof( *ObjectName ), "object name string" ) ) { return TRUE; } else { return FALSE; } } BOOLEAN CaptureFullName( PPROCESS_INFO Process, ULONG Type, HANDLE RootDirectory, PWSTR Name, ULONG Length, PWSTR *ReturnedFullName ) { POPENHANDLE_INFO HandleInfo; UNICODE_STRING FullName; ULONG LengthOfName; PWSTR s; BOOLEAN Result; *ReturnedFullName = NULL; if (RootDirectory != NULL) { HandleInfo = FindOpenHandle( Process, RootDirectory, Type ); if (HandleInfo == NULL) { // // If handle not found then we dont care about this open // as it is relative to a device that is not local. // return FALSE; } } else { HandleInfo = NULL; } LengthOfName = Length + sizeof( UNICODE_NULL ); if (HandleInfo != NULL) { LengthOfName += HandleInfo->LengthOfName + sizeof( OBJ_NAME_PATH_SEPARATOR ); } FullName.Buffer = AllocMem( LengthOfName ); if (FullName.Buffer == NULL) { return FALSE; } s = FullName.Buffer; if (HandleInfo != NULL) { RtlMoveMemory( s, HandleInfo->Name, HandleInfo->LengthOfName ); s = &FullName.Buffer[ HandleInfo->LengthOfName / sizeof( WCHAR ) ]; if (s[-1] != OBJ_NAME_PATH_SEPARATOR) { *s++ = OBJ_NAME_PATH_SEPARATOR; } } if (!ReadMemory( Process, Name, s, Length, "object name buffer" ) ) { FreeMem( &FullName.Buffer ); return FALSE; } s = &s[ Length / sizeof( WCHAR ) ]; *s = UNICODE_NULL; FullName.Length = (PCHAR)s - (PCHAR)FullName.Buffer; FullName.MaximumLength = (USHORT)(FullName.Length + sizeof( UNICODE_NULL )); if (HandleInfo == NULL && Type == HANDLE_TYPE_FILE) { Result = IsDriveLetterPath( &FullName ); } else { Result = TRUE; } *ReturnedFullName = AddName( &FullName ); FreeMem( &FullName.Buffer ); return Result; } BOOLEAN CaptureOpenState( PPROCESS_INFO Process, PAPI_SAVED_PARAMETERS Parameters, POBJECT_ATTRIBUTES ObjectAttributesAddress, BOOLEAN WriteAccess, PHANDLE ResultHandleAddress, ULONG Type ) { OBJECT_ATTRIBUTES ObjectAttributes; UNICODE_STRING ObjectName; PWSTR FullName; BOOLEAN Result; Result = FALSE; if (CaptureObjectAttributes( Process, ObjectAttributesAddress, &ObjectAttributes, &ObjectName ) && CaptureFullName( Process, Type, ObjectAttributes.RootDirectory, ObjectName.Buffer, ObjectName.Length, &FullName ) && CreateSavedCallState( Process, &Parameters->SavedCallState, OpenPath, Type, FullName, (BOOLEAN)((ObjectAttributes.Attributes & OBJ_INHERIT) != 0), WriteAccess, ResultHandleAddress ) ) { if (Type == HANDLE_TYPE_FILE) { Result = CreateFileReference( FullName, Parameters->SavedCallState.PathOpen.WriteAccessRequested, (PFILE_REFERENCE *)&Parameters->SavedCallState.Reference ); } else { Result = CreateKeyReference( FullName, Parameters->SavedCallState.PathOpen.WriteAccessRequested, (PKEY_REFERENCE *)&Parameters->SavedCallState.Reference ); } } return Result; } BOOLEAN CompleteOpenState( PPROCESS_INFO Process, PAPI_SAVED_PARAMETERS Parameters ) { PAPI_SAVED_CALL_STATE p = &Parameters->SavedCallState; HANDLE Handle; BOOLEAN CallSuccessful; PFILE_REFERENCE FileReference; PKEY_REFERENCE KeyReference; if (NT_SUCCESS( Parameters->ReturnValue.ReturnedLong ) && ReadMemory( Process, p->PathOpen.ResultHandleAddress, &Handle, sizeof( Handle ), "result handle" ) && AddOpenHandle( Process, Handle, p->Type, p->FullName, p->PathOpen.InheritHandle ) ) { CallSuccessful = TRUE; } else { CallSuccessful = FALSE; } IncrementOpenCount( p->FullName, CallSuccessful ); if (p->Type == HANDLE_TYPE_FILE) { FileReference = (PFILE_REFERENCE)p->Reference; CompleteFileReference( FileReference, CallSuccessful, FALSE, NULL ); } else if (p->Type == HANDLE_TYPE_KEY) { KeyReference = (PKEY_REFERENCE)p->Reference; CompleteKeyReference( (PKEY_REFERENCE)p->Reference, CallSuccessful, FALSE ); } return TRUE; } #if TRACE_ENABLED ENUM_TYPE_NAMES FileAccessNames[] = { FILE_READ_DATA, "FILE_READ_DATA", FILE_READ_DATA, "FILE_READ_DATA", FILE_WRITE_DATA, "FILE_WRITE_DATA", FILE_APPEND_DATA, "FILE_APPEND_DATA", FILE_READ_EA, "FILE_READ_EA", FILE_WRITE_EA, "FILE_WRITE_EA", FILE_EXECUTE, "FILE_EXECUTE", FILE_DELETE_CHILD, "FILE_DELETE_CHILD", FILE_READ_ATTRIBUTES, "FILE_READ_ATTRIBUTES", FILE_WRITE_ATTRIBUTES, "FILE_WRITE_ATTRIBUTES", DELETE, "DELETE", READ_CONTROL, "READ_CONTROL", WRITE_DAC, "WRITE_DAC", WRITE_OWNER, "WRITE_OWNER", SYNCHRONIZE, "SYNCHRONIZE", GENERIC_READ, "GENERIC_READ", GENERIC_WRITE, "GENERIC_WRITE", GENERIC_EXECUTE, "GENERIC_EXECUTE", GENERIC_ALL, "GENERIC_ALL", 0xFFFFFFFF, "%x" }; ENUM_TYPE_NAMES FileShareNames[] = { FILE_SHARE_READ, "FILE_SHARE_READ", FILE_SHARE_WRITE, "FILE_SHARE_WRITE", FILE_SHARE_DELETE, "FILE_SHARE_DELETE", 0xFFFFFFFF, "FILE_SHARE_NONE" }; ENUM_TYPE_NAMES FileCreateDispositionNames[] = { FILE_SUPERSEDE, "FILE_SUPERSEDE", FILE_OPEN, "FILE_OPEN", FILE_CREATE, "FILE_CREATE", FILE_OPEN_IF, "FILE_OPEN_IF", FILE_OVERWRITE, "FILE_OVERWRITE", FILE_OVERWRITE_IF, "FILE_OVERWRITE_IF", 0xFFFFFFFF, "%x" }; ENUM_TYPE_NAMES FileCreateOptionNames[] = { FILE_DIRECTORY_FILE, "FILE_DIRECTORY_FILE", FILE_WRITE_THROUGH, "FILE_WRITE_THROUGH", FILE_SEQUENTIAL_ONLY, "FILE_SEQUENTIAL_ONLY", FILE_NO_INTERMEDIATE_BUFFERING, "FILE_NO_INTERMEDIATE_BUFFERING", FILE_SYNCHRONOUS_IO_ALERT, "FILE_SYNCHRONOUS_IO_ALERT", FILE_SYNCHRONOUS_IO_NONALERT, "FILE_SYNCHRONOUS_IO_NONALERT", FILE_NON_DIRECTORY_FILE, "FILE_NON_DIRECTORY_FILE", FILE_CREATE_TREE_CONNECTION, "FILE_CREATE_TREE_CONNECTION", FILE_COMPLETE_IF_OPLOCKED, "FILE_COMPLETE_IF_OPLOCKED", FILE_NO_EA_KNOWLEDGE, "FILE_NO_EA_KNOWLEDGE", FILE_RANDOM_ACCESS, "FILE_RANDOM_ACCESS", FILE_DELETE_ON_CLOSE, "FILE_DELETE_ON_CLOSE", FILE_OPEN_BY_FILE_ID, "FILE_OPEN_BY_FILE_ID", FILE_OPEN_FOR_BACKUP_INTENT, "FILE_OPEN_FOR_BACKUP_INTENT", FILE_NO_COMPRESSION, "FILE_NO_COMPRESSION", 0xFFFFFFFF, "%x" }; ENUM_TYPE_NAMES FileIoStatusInfoNames[] = { FILE_SUPERSEDED, "FILE_SUPERSEDED", FILE_OPENED, "FILE_OPENED", FILE_CREATED, "FILE_CREATED", FILE_OVERWRITTEN, "FILE_OVERWRITTEN", FILE_EXISTS, "FILE_EXISTS", FILE_DOES_NOT_EXIST, "FILE_DOES_NOT_EXIST", 0xFFFFFFFF, "%x" }; ENUM_TYPE_NAMES SetFileInfoClassNames[] = { FileDirectoryInformation, "FileDirectoryInformation", FileFullDirectoryInformation, "FileFullDirectoryInformation", FileBothDirectoryInformation, "FileBothDirectoryInformation", FileBasicInformation, "FileBasicInformation", FileStandardInformation, "FileStandardInformation", FileInternalInformation, "FileInternalInformation", FileEaInformation, "FileEaInformation", FileAccessInformation, "FileAccessInformation", FileNameInformation, "FileNameInformation", FileRenameInformation, "FileRenameInformation", FileLinkInformation, "FileLinkInformation", FileNamesInformation, "FileNamesInformation", FileDispositionInformation, "FileDispositionInformation", FilePositionInformation, "FilePositionInformation", FileFullEaInformation, "FileFullEaInformation", FileModeInformation, "FileModeInformation", FileAlignmentInformation, "FileAlignmentInformation", FileAllInformation, "FileAllInformation", FileAllocationInformation, "FileAllocationInformation", FileEndOfFileInformation, "FileEndOfFileInformation", FileAlternateNameInformation, "FileAlternateNameInformation", FileStreamInformation, "FileStreamInformation", FilePipeInformation, "FilePipeInformation", FilePipeLocalInformation, "FilePipeLocalInformation", FilePipeRemoteInformation, "FilePipeRemoteInformation", FileMailslotQueryInformation, "FileMailslotQueryInformation", FileMailslotSetInformation, "FileMailslotSetInformation", FileCompressionInformation, "FileCompressionInformation", FileCompletionInformation, "FileCompletionInformation", FileMoveClusterInformation, "FileMoveClusterInformation", 0xFFFFFFFF, "%x" }; ENUM_TYPE_NAMES KeyCreateOptionNames[] = { REG_OPTION_VOLATILE, "REG_OPTION_VOLATILE", REG_OPTION_CREATE_LINK, "REG_OPTION_CREATE_LINK", REG_OPTION_BACKUP_RESTORE, "REG_OPTION_BACKUP_RESTORE", 0xFFFFFFFF, "%x" }; ENUM_TYPE_NAMES KeyDispositionNames[] = { REG_CREATED_NEW_KEY, "REG_CREATED_NEW_KEY", REG_OPENED_EXISTING_KEY, "REG_OPENED_EXISTING_KEY", 0xFFFFFFFF, "%x" }; #endif // TRACE_ENABLED BOOLEAN IsFileWriteAccessRequested( ACCESS_MASK DesiredAccess, ULONG CreateDisposition ) { if (DesiredAccess & (GENERIC_WRITE | GENERIC_ALL | DELETE | FILE_WRITE_DATA | FILE_APPEND_DATA ) ) { return TRUE; } if (CreateDisposition != FILE_OPEN && CreateDisposition != FILE_OPEN_IF) { return TRUE; } return FALSE; } BOOLEAN NtCreateFileHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PCREATEFILE_PARAMETERS p = &Parameters->InputParameters.CreateFile; BOOLEAN Result; if (!Parameters->ReturnValueValid) { Result = CaptureOpenState( Process, Parameters, p->ObjectAttributes, IsFileWriteAccessRequested( p->DesiredAccess, p->CreateDisposition ), p->FileHandle, HANDLE_TYPE_FILE ); if (Result // && Parameters->SavedCallState.PathOpen.WriteAccessRequested ) { DbgEvent( CREATEEVENT, ( "NtCreateFile called:\n" " Name: %ws\n" " Access: %s\n" " Share: %s\n" " Create: %s\n" " Options:%s\n", Parameters->SavedCallState.FullName, FormatEnumType( 0, FileAccessNames, p->DesiredAccess, TRUE ), FormatEnumType( 1, FileShareNames, p->ShareAccess, TRUE ), FormatEnumType( 2, FileCreateDispositionNames, p->CreateDisposition, FALSE ), FormatEnumType( 3, FileCreateOptionNames, p->CreateOptions, TRUE ) ) ); } } else { Result = CompleteOpenState( Process, Parameters ); if (Result // && Parameters->SavedCallState.PathOpen.WriteAccessRequested ) { IO_STATUS_BLOCK IoStatusBlock; ReadMemory( Process, p->IoStatusBlock, &IoStatusBlock, sizeof( IoStatusBlock ), "IoStatusBlock" ); DbgEvent( CREATEEVENT, ( "*** Returned %s [%s %s]\n", FormatEnumType( 0, (PENUM_TYPE_NAMES)ntstatusSymbolicNames, Parameters->ReturnValue.ReturnedLong, FALSE ), FormatEnumType( 1, (PENUM_TYPE_NAMES)ntstatusSymbolicNames, IoStatusBlock.Status, FALSE ), FormatEnumType( 2, FileIoStatusInfoNames, IoStatusBlock.Information, FALSE ) ) ); } } return Result; } BOOLEAN NtOpenFileHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { POPENFILE_PARAMETERS p = &Parameters->InputParameters.OpenFile; BOOLEAN Result; if (!Parameters->ReturnValueValid) { Result = CaptureOpenState( Process, Parameters, p->ObjectAttributes, IsFileWriteAccessRequested( p->DesiredAccess, FILE_OPEN ), p->FileHandle, HANDLE_TYPE_FILE ); if (Result // && Parameters->SavedCallState.PathOpen.WriteAccessRequested ) { DbgEvent( CREATEEVENT, ( "NtOpenFile called:\n" " Name: %ws\n" " Access: %s\n" " Share: %s\n" " Options:%s\n", Parameters->SavedCallState.FullName, FormatEnumType( 0, FileAccessNames, p->DesiredAccess, TRUE ), FormatEnumType( 1, FileShareNames, p->ShareAccess, TRUE ), FormatEnumType( 2, FileCreateOptionNames, p->OpenOptions, TRUE ) ) ); } } else { Result = CompleteOpenState( Process, Parameters ); if (Result // && Parameters->SavedCallState.PathOpen.WriteAccessRequested ) { IO_STATUS_BLOCK IoStatusBlock; ReadMemory( Process, p->IoStatusBlock, &IoStatusBlock, sizeof( IoStatusBlock ), "IoStatusBlock" ); DbgEvent( CREATEEVENT, ( "*** Returned %s [%s %s]\n", FormatEnumType( 0, (PENUM_TYPE_NAMES)ntstatusSymbolicNames, Parameters->ReturnValue.ReturnedLong, FALSE ), FormatEnumType( 1, (PENUM_TYPE_NAMES)ntstatusSymbolicNames, IoStatusBlock.Status, FALSE ), FormatEnumType( 2, FileIoStatusInfoNames, IoStatusBlock.Information, FALSE ) ) ); } } return Result; } BOOLEAN NtDeleteFileHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PDELETEFILE_PARAMETERS p = &Parameters->InputParameters.DeleteFile; OBJECT_ATTRIBUTES ObjectAttributes; UNICODE_STRING ObjectName; PWSTR FullName; BOOLEAN Result, CallSuccessful; PFILE_REFERENCE FileReference; if (!Parameters->ReturnValueValid) { if (CaptureObjectAttributes( Process, p->ObjectAttributes, &ObjectAttributes, &ObjectName ) && CaptureFullName( Process, HANDLE_TYPE_FILE, ObjectAttributes.RootDirectory, ObjectName.Buffer, ObjectName.Length, &FullName ) && CreateSavedCallState( Process, &Parameters->SavedCallState, DeletePath, HANDLE_TYPE_FILE, FullName ) ) { Result = CreateFileReference( FullName, TRUE, (PFILE_REFERENCE *)&Parameters->SavedCallState.Reference ); } else { Result = FALSE; } return Result; } else { if (NT_SUCCESS( Parameters->ReturnValue.ReturnedLong )) { CallSuccessful = TRUE; } else { CallSuccessful = FALSE; } FileReference = (PFILE_REFERENCE)Parameters->SavedCallState.Reference; CompleteFileReference( FileReference, CallSuccessful, TRUE, NULL ); return TRUE; } } #undef DeleteFile BOOLEAN NtSetInformationFileHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PSETINFORMATIONFILE_PARAMETERS p = &Parameters->InputParameters.SetInformationFile; POPENHANDLE_INFO HandleInfo; FILE_RENAME_INFORMATION RenameInformation; FILE_DISPOSITION_INFORMATION DispositionInformation; PWSTR NewName, OldName; PFILE_REFERENCE OldFileReference; PFILE_REFERENCE NewFileReference; BOOLEAN Result, CallSuccessful; HandleInfo = FindOpenHandle( Process, p->FileHandle, HANDLE_TYPE_FILE ); if (HandleInfo == NULL) { Result = FALSE; } else if (p->FileInformationClass == FileRenameInformation) { // // Renaming an open file. // if (!Parameters->ReturnValueValid) { if (ReadMemory( Process, p->FileInformation, &RenameInformation, FIELD_OFFSET( FILE_RENAME_INFORMATION, FileName ), "rename information" ) && CaptureFullName( Process, HANDLE_TYPE_FILE, RenameInformation.RootDirectory, &((PFILE_RENAME_INFORMATION)(p->FileInformation))->FileName[ 0 ], RenameInformation.FileNameLength, &NewName ) && CreateSavedCallState( Process, &Parameters->SavedCallState, RenamePath, HANDLE_TYPE_FILE, HandleInfo->Name, NewName, RenameInformation.ReplaceIfExists ) ) { Result = CreateFileReference( NewName, RenameInformation.ReplaceIfExists, (PFILE_REFERENCE *)&Parameters->SavedCallState.Reference ); } else { Result = FALSE; } } else { OldName = NULL; if (NT_SUCCESS( Parameters->ReturnValue.ReturnedLong )) { CallSuccessful = TRUE; OldFileReference = FindFileReference( HandleInfo->Name ); if (OldFileReference) { OldName = OldFileReference->Name; } } else { CallSuccessful = FALSE; OldFileReference = NULL; } NewFileReference = (PFILE_REFERENCE)Parameters->SavedCallState.Reference; NewName = NewFileReference->Name; CompleteFileReference( NewFileReference, CallSuccessful, (BOOLEAN)(!NewFileReference->Created), OldFileReference ); Result = TRUE; } } else if (p->FileInformationClass == FileDispositionInformation) { // // Marking an open file for delete. // if (!Parameters->ReturnValueValid) { if (ReadMemory( Process, p->FileInformation, &DispositionInformation, sizeof( DispositionInformation ), "disposition information" ) && DispositionInformation.DeleteFile && CreateSavedCallState( Process, &Parameters->SavedCallState, DeletePath, HANDLE_TYPE_FILE, HandleInfo->Name ) ) { Result = TRUE; } else { Result = FALSE; } } else { if (NT_SUCCESS( Parameters->ReturnValue.ReturnedLong )) { if (OldFileReference = FindFileReference( HandleInfo->Name )) { if (OldFileReference->Created) { LogEvent( INSTALER_EVENT_DELETE_TEMP_FILE, 2, OldFileReference->DirectoryFile ? L"directory" : L"file", OldFileReference->Name ); DestroyFileReference( OldFileReference ); } else { OldFileReference->Deleted = TRUE; LogEvent( INSTALER_EVENT_DELETE_FILE, 2, OldFileReference->DirectoryFile ? L"directory" : L"file", OldFileReference->Name ); } } } Result = TRUE; } } else { Result = FALSE; } return Result; } BOOLEAN CaptureUnicodeString( PPROCESS_INFO Process, PUNICODE_STRING UnicodeStringAddress, PWSTR *ReturnedString ) { UNICODE_STRING UnicodeString; PWSTR s; s = NULL; if (ReadMemory( Process, UnicodeStringAddress, &UnicodeString, sizeof( UnicodeString ), "unicode string" ) && ((s = AllocMem( UnicodeString.Length + sizeof( UNICODE_NULL ) )) != NULL) && ReadMemory( Process, UnicodeString.Buffer, s, UnicodeString.Length, "unicode string buffer" ) ) { *ReturnedString = s; return TRUE; } FreeMem( &s ); return FALSE; } BOOLEAN NtQueryAttributesFileHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PQUERYATTRIBUTESFILE_PARAMETERS p = &Parameters->InputParameters.QueryAttributesFile; OBJECT_ATTRIBUTES ObjectAttributes; UNICODE_STRING ObjectName; PWSTR FullName; NTSTATUS Status; BOOLEAN Result; CHAR Buffer[ MAX_PATH ]; if (!Parameters->ReturnValueValid) { FullName = NULL; Result = FALSE; if (CaptureObjectAttributes( Process, p->ObjectAttributes, &ObjectAttributes, &ObjectName ) && CaptureFullName( Process, HANDLE_TYPE_FILE, ObjectAttributes.RootDirectory, ObjectName.Buffer, ObjectName.Length, &FullName ) && CreateSavedCallState( Process, &Parameters->SavedCallState, QueryPath, HANDLE_TYPE_FILE, FullName ) ) { Result = CreateFileReference( FullName, FALSE, (PFILE_REFERENCE *)&Parameters->SavedCallState.Reference ); } else { Result = FALSE; } return Result; } else { FILE_BASIC_INFORMATION FileInformation; ReadMemory( Process, p->FileInformation, &FileInformation, sizeof( FileInformation ), "FileInformation" ); return TRUE; } } BOOLEAN NtQueryDirectoryFileHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PQUERYDIRECTORYFILE_PARAMETERS p = &Parameters->InputParameters.QueryDirectoryFile; POPENHANDLE_INFO HandleInfo; PWSTR FileName; NTSTATUS Status; BOOLEAN Result; PULONG pNextEntryOffset; ULONG NextEntryOffset; ULONG EntriesReturned; if (!Parameters->ReturnValueValid) { FileName = NULL; Result = FALSE; if ((HandleInfo = FindOpenHandle( Process, p->FileHandle, HANDLE_TYPE_FILE ) ) != NULL && p->FileName != NULL && CaptureUnicodeString( Process, p->FileName, &FileName ) ) { if (HandleInfo->RootDirectory && !wcscmp( FileName, L"*" ) || !wcscmp( FileName, L"*.*" ) ) { if (AskUserOnce) { AskUserOnce = FALSE; if (AskUser( MB_OKCANCEL, INSTALER_ASKUSER_ROOTSCAN, 1, HandleInfo->Name ) == IDCANCEL ) { FailAllScansOfRootDirectories = TRUE; } } Parameters->AbortCall = FailAllScansOfRootDirectories; } if (FileName) { HandleInfo->QueryName = FileName; } } return TRUE; } else { if (Parameters->AbortCall) { // // If we get here, then user wanted to fail this call. // Status = STATUS_NO_MORE_FILES; SetProcedureReturnValue( Process, Thread, &Status, sizeof( Status ) ); return TRUE; } else { if ((HandleInfo = FindOpenHandle( Process, p->FileHandle, HANDLE_TYPE_FILE ) ) != NULL ) { // // If successful, count entries returned // if (NT_SUCCESS( Parameters->ReturnValue.ReturnedLong )) { // // Return buffer is a set of records, the first DWORD of each contains // the offset to the next one or zero to indicate the end. Count them. // pNextEntryOffset = (PULONG)p->FileInformation; EntriesReturned = 1; while (ReadMemory( Process, pNextEntryOffset, &NextEntryOffset, sizeof( NextEntryOffset ), "DirectoryInformation" ) && NextEntryOffset != 0 ) { pNextEntryOffset = (PULONG)((PCHAR)pNextEntryOffset + NextEntryOffset); EntriesReturned += 1; } LogEvent( INSTALER_EVENT_SCAN_DIRECTORY, 3, HandleInfo->Name, HandleInfo->QueryName ? HandleInfo->QueryName : L"*", EntriesReturned ); } else { FreeMem( &HandleInfo->QueryName ); } } } return TRUE; } } BOOLEAN IsKeyWriteAccessRequested( ACCESS_MASK DesiredAccess ) { if (DesiredAccess & (GENERIC_WRITE | GENERIC_ALL | DELETE | KEY_SET_VALUE | KEY_CREATE_SUB_KEY | KEY_CREATE_LINK ) ) { return TRUE; } return FALSE; } BOOLEAN NtCreateKeyHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PCREATEKEY_PARAMETERS p = &Parameters->InputParameters.CreateKey; BOOLEAN Result; if (!Parameters->ReturnValueValid) { Result = CaptureOpenState( Process, Parameters, p->ObjectAttributes, IsKeyWriteAccessRequested( p->DesiredAccess ), p->KeyHandle, HANDLE_TYPE_KEY ); } else { Result = CompleteOpenState( Process, Parameters ); } return Result; } BOOLEAN NtOpenKeyHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { POPENKEY_PARAMETERS p = &Parameters->InputParameters.OpenKey; BOOLEAN Result; if (!Parameters->ReturnValueValid) { Result = CaptureOpenState( Process, Parameters, p->ObjectAttributes, IsKeyWriteAccessRequested( p->DesiredAccess ), p->KeyHandle, HANDLE_TYPE_KEY ); } else { Result = CompleteOpenState( Process, Parameters ); } return Result; } BOOLEAN NtDeleteKeyHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PDELETEKEY_PARAMETERS p = &Parameters->InputParameters.DeleteKey; POPENHANDLE_INFO HandleInfo; PKEY_REFERENCE OldKeyReference; BOOLEAN Result; // // Marking an open key for delete. // HandleInfo = FindOpenHandle( Process, p->KeyHandle, HANDLE_TYPE_KEY ); if (HandleInfo == NULL) { Result = FALSE; } else if (!Parameters->ReturnValueValid) { if (CreateSavedCallState( Process, &Parameters->SavedCallState, DeletePath, HANDLE_TYPE_KEY, HandleInfo->Name ) ) { Result = TRUE; } else { Result = FALSE; } } else { if (NT_SUCCESS( Parameters->ReturnValue.ReturnedLong )) { if (OldKeyReference = FindKeyReference( HandleInfo->Name )) { if (OldKeyReference->Created) { LogEvent( INSTALER_EVENT_DELETE_TEMP_KEY, 1, OldKeyReference->Name ); DestroyKeyReference( OldKeyReference ); } else { MarkKeyDeleted( OldKeyReference ); LogEvent( INSTALER_EVENT_DELETE_KEY, 1, OldKeyReference->Name ); } } } Result = TRUE; } return Result; } BOOLEAN CaptureValueName( PPROCESS_INFO Process, PUNICODE_STRING Name, PWSTR *ReturnedValueName ) { UNICODE_STRING ValueName; PWSTR s; *ReturnedValueName = NULL; if (Name == NULL || !ReadMemory( Process, Name, &ValueName, sizeof( ValueName ), "value name string" ) ) { return FALSE; } s = AllocMem( ValueName.Length + sizeof( UNICODE_NULL ) ); if (s == NULL) { return FALSE; } if (!ReadMemory( Process, ValueName.Buffer, s, ValueName.Length, "value name buffer" ) ) { FreeMem( &s ); return FALSE; } s[ ValueName.Length / sizeof( WCHAR ) ] = UNICODE_NULL; ValueName.Buffer = s; ValueName.MaximumLength = (USHORT)(ValueName.Length + sizeof( UNICODE_NULL )); *ReturnedValueName = AddName( &ValueName ); FreeMem( &ValueName.Buffer ); return TRUE; } BOOLEAN NtSetValueKeyHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PSETVALUEKEY_PARAMETERS p = &Parameters->InputParameters.SetValueKey; POPENHANDLE_INFO HandleInfo; PWSTR ValueName; PKEY_REFERENCE KeyReference; PVALUE_REFERENCE ValueReference; BOOLEAN Result; // // Setting a value // HandleInfo = FindOpenHandle( Process, p->KeyHandle, HANDLE_TYPE_KEY ); if (HandleInfo == NULL) { Result = FALSE; } else if (!Parameters->ReturnValueValid) { if (CaptureValueName( Process, p->ValueName, &ValueName ) && CreateSavedCallState( Process, &Parameters->SavedCallState, SetValue, HANDLE_TYPE_KEY, ValueName ) ) { Result = TRUE; } else { Result = FALSE; } } else { if (NT_SUCCESS( Parameters->ReturnValue.ReturnedLong ) && (KeyReference = FindKeyReference( HandleInfo->Name )) ) { CreateValueReference( Process, KeyReference, Parameters->SavedCallState.FullName, p->TitleIndex, p->Type, p->Data, p->DataLength, &ValueReference ); if (ValueReference != NULL) { LogEvent( INSTALER_EVENT_SET_KEY_VALUE, 2, ValueReference->Name, KeyReference->Name ); } } Result = TRUE; } return Result; } BOOLEAN NtDeleteValueKeyHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PDELETEVALUEKEY_PARAMETERS p = &Parameters->InputParameters.DeleteValueKey; POPENHANDLE_INFO HandleInfo; PWSTR ValueName; PKEY_REFERENCE KeyReference; PVALUE_REFERENCE ValueReference; BOOLEAN Result; // // Marking a value for delete. // HandleInfo = FindOpenHandle( Process, p->KeyHandle, HANDLE_TYPE_KEY ); if (HandleInfo == NULL) { Result = FALSE; } else if (!Parameters->ReturnValueValid) { if (CaptureValueName( Process, p->ValueName, &ValueName ) && CreateSavedCallState( Process, &Parameters->SavedCallState, DeleteValue, HANDLE_TYPE_KEY, ValueName ) ) { Result = TRUE; } else { Result = FALSE; } } else { if (NT_SUCCESS( Parameters->ReturnValue.ReturnedLong ) && (KeyReference = FindKeyReference( HandleInfo->Name )) && (ValueReference = FindValueReference( KeyReference, Parameters->SavedCallState.FullName )) ) { if (ValueReference->Created) { LogEvent( INSTALER_EVENT_DELETE_KEY_TEMP_VALUE, 2, ValueReference->Name, KeyReference->Name ); DestroyValueReference( ValueReference ); } else { ValueReference->Deleted = TRUE; LogEvent( INSTALER_EVENT_DELETE_KEY_VALUE, 2, ValueReference->Name, KeyReference->Name ); } } Result = TRUE; } return Result; } BOOLEAN NtCloseHandleHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PCLOSEHANDLE_PARAMETERS p = &Parameters->InputParameters.CloseHandle; POPENHANDLE_INFO HandleInfo; PFILE_REFERENCE FileReference; HandleInfo = FindOpenHandle( Process, p->Handle, (ULONG)-1 ); if (!Parameters->ReturnValueValid) { if (HandleInfo != NULL) { return TRUE; } else { return FALSE; } } else { if (NT_SUCCESS( Parameters->ReturnValue.ReturnedLong )) { if (HandleInfo != NULL && HandleInfo->Type == HANDLE_TYPE_FILE && (FileReference = FindFileReference( HandleInfo->Name )) != NULL && FileReference->WriteAccess && !FileReference->Created && !FileReference->DirectoryFile && IsNewFileSameAsBackup( FileReference ) ) { DestroyFileReference( FileReference ); FileReference = NULL; } DeleteOpenHandle( Process, p->Handle, (ULONG)-1 ); } return TRUE; } } UCHAR AnsiStringBuffer[ MAX_PATH+1 ]; WCHAR UnicodeStringBuffer[ MAX_PATH+1 ]; BOOLEAN CaptureAnsiAsUnicode( PPROCESS_INFO Process, LPCSTR Address, BOOLEAN DoubleNullTermination, PWSTR *ReturnedName, PWSTR *ReturnedData ) { NTSTATUS Status; ULONG BytesRead; ANSI_STRING AnsiString; UNICODE_STRING UnicodeString; if (Address == NULL) { if (ReturnedName != NULL) { *ReturnedName = NULL; } else { *ReturnedData = NULL; } return TRUE; } BytesRead = FillTemporaryBuffer( Process, (PVOID)Address, FALSE, DoubleNullTermination ); if (BytesRead != 0 && BytesRead < 0x7FFF) { AnsiString.Buffer = TemporaryBuffer; AnsiString.Length = (USHORT)BytesRead; AnsiString.MaximumLength = (USHORT)BytesRead; Status = RtlAnsiStringToUnicodeString( &UnicodeString, &AnsiString, TRUE ); if (NT_SUCCESS( Status )) { if (ReturnedName != NULL) { *ReturnedName = AddName( &UnicodeString ); RtlFreeUnicodeString( &UnicodeString ); return TRUE; } else { *ReturnedData = UnicodeString.Buffer; return TRUE; } } } return FALSE; } BOOLEAN CaptureUnicode( PPROCESS_INFO Process, LPCWSTR Address, BOOLEAN DoubleNullTermination, PWSTR *ReturnedName, PWSTR *ReturnedData ) { ULONG BytesRead; UNICODE_STRING UnicodeString; if (Address == NULL) { if (ReturnedName != NULL) { *ReturnedName = NULL; } else { *ReturnedData = NULL; } return TRUE; } BytesRead = FillTemporaryBuffer( Process, (PVOID)Address, TRUE, DoubleNullTermination ); if (BytesRead != 0 && (BytesRead & 1) == 0 && BytesRead <= 0xFFFC) { if (ReturnedName != NULL) { RtlInitUnicodeString( &UnicodeString, TemporaryBuffer ); *ReturnedName = AddName( &UnicodeString ); return TRUE; } else { *ReturnedData = AllocMem( BytesRead + sizeof( UNICODE_NULL ) ); if (*ReturnedData != NULL) { memmove( *ReturnedData, TemporaryBuffer, BytesRead ); return TRUE; } } } return FALSE; } BOOLEAN GetVersionHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { DWORD dwVersion; if (!Parameters->ReturnValueValid) { if (AskUserOnce) { AskUserOnce = FALSE; if (AskUser( MB_OKCANCEL, INSTALER_ASKUSER_GETVERSION, 0 ) == IDCANCEL ) { DefaultGetVersionToWin95 = TRUE; } else { DefaultGetVersionToWin95 = FALSE; } } LogEvent( INSTALER_EVENT_GETVERSION, 1, DefaultGetVersionToWin95 ? L"Windows 95" : L"Windows NT" ); Parameters->AbortCall = DefaultGetVersionToWin95; return Parameters->AbortCall; } else { dwVersion = 0xC0000004; // What Windows 95 returns SetProcedureReturnValue( Process, Thread, &dwVersion, sizeof( dwVersion ) ); return TRUE; } } BOOLEAN GetVersionExWHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PGETVERSIONEXW_PARAMETERS p = &Parameters->InputParameters.GetVersionExW; OSVERSIONINFOW VersionInformation; if (!Parameters->ReturnValueValid) { if (AskUserOnce) { AskUserOnce = FALSE; if (AskUser( MB_OKCANCEL, INSTALER_ASKUSER_GETVERSION, 0 ) == IDCANCEL ) { DefaultGetVersionToWin95 = TRUE; } else { DefaultGetVersionToWin95 = FALSE; } } Parameters->AbortCall = DefaultGetVersionToWin95; return Parameters->AbortCall; } else { memset( &VersionInformation, 0, sizeof( VersionInformation ) ); VersionInformation.dwMajorVersion = 4; VersionInformation.dwBuildNumber = 0x3B6; // What Windows 95 returns VersionInformation.dwPlatformId = VER_PLATFORM_WIN32_WINDOWS; WriteMemory( Process, p->lpVersionInformation, &VersionInformation, sizeof( VersionInformation ), "GetVersionExW" ); return TRUE; } } BOOLEAN SetCurrentDirectoryAHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PSETCURRENTDIRECTORYA_PARAMETERS p = &Parameters->InputParameters.SetCurrentDirectoryA; PWSTR PathName; WCHAR PathBuffer[ MAX_PATH ]; if (!Parameters->ReturnValueValid) { if (CaptureAnsiAsUnicode( Process, p->lpPathName, FALSE, NULL, &PathName ) && PathName != NULL) { Parameters->CurrentDirectory = AllocMem( (wcslen( PathName ) + 1) * sizeof( WCHAR ) ); if (Parameters->CurrentDirectory != NULL) { wcscpy( Parameters->CurrentDirectory, PathName ); return TRUE; } } return FALSE; } else { if (Parameters->ReturnValue.ReturnedBool != 0) { if (SetCurrentDirectory( Parameters->CurrentDirectory ) && GetCurrentDirectory( MAX_PATH, PathBuffer ) ) { LogEvent( INSTALER_EVENT_SET_DIRECTORY, 1, PathBuffer ); } } FreeMem( &Parameters->CurrentDirectory ); return TRUE; } } BOOLEAN SetCurrentDirectoryWHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PSETCURRENTDIRECTORYW_PARAMETERS p = &Parameters->InputParameters.SetCurrentDirectoryW; PWSTR PathName; WCHAR PathBuffer[ MAX_PATH ]; if (!Parameters->ReturnValueValid) { if (CaptureUnicode( Process, p->lpPathName, FALSE, NULL, &PathName ) && PathName != NULL) { Parameters->CurrentDirectory = AllocMem( (wcslen( PathName ) + 1) * sizeof( WCHAR ) ); if (Parameters->CurrentDirectory != NULL) { wcscpy( Parameters->CurrentDirectory, PathName ); return TRUE; } } return FALSE; } else { if (Parameters->ReturnValue.ReturnedBool != 0) { if (SetCurrentDirectory( Parameters->CurrentDirectory ) && GetCurrentDirectory( MAX_PATH, PathBuffer ) ) { LogEvent( INSTALER_EVENT_SET_DIRECTORY, 1, PathBuffer ); } } FreeMem( &Parameters->CurrentDirectory ); return TRUE; } } BOOLEAN GetIniFilePath( PWSTR IniFileName, PWSTR *ReturnedIniFilePath ) { NTSTATUS Status; UNICODE_STRING FileName, UnicodeString; PWSTR FilePart; DWORD n; if (IniFileName == NULL) { RtlInitUnicodeString( &FileName, L"win.ini" ); } else { RtlInitUnicodeString( &FileName, IniFileName ); } if ((FileName.Length > sizeof( WCHAR ) && FileName.Buffer[ 1 ] == L':' ) || (FileName.Length != 0 && wcscspn( FileName.Buffer, L"\\/" ) != (FileName.Length / sizeof( WCHAR )) ) ) { UnicodeString.MaximumLength = (USHORT)(MAX_PATH * sizeof( WCHAR )); UnicodeString.Buffer = AllocMem( UnicodeString.MaximumLength ); if (UnicodeString.Buffer == NULL) { Status = STATUS_NO_MEMORY; } else { UnicodeString.Length = 0; n = GetFullPathNameW( FileName.Buffer, UnicodeString.MaximumLength / sizeof( WCHAR ), UnicodeString.Buffer, &FilePart ); if (n > UnicodeString.MaximumLength) { Status = STATUS_BUFFER_TOO_SMALL; } else { UnicodeString.Length = (USHORT)(n * sizeof( WCHAR )); Status = STATUS_SUCCESS; } } } else { UnicodeString.Length = 0; UnicodeString.MaximumLength = (USHORT)(WindowsDirectory.Length + sizeof( WCHAR ) + FileName.Length + sizeof( UNICODE_NULL ) ); UnicodeString.Buffer = AllocMem( UnicodeString.MaximumLength ); if (UnicodeString.Buffer == NULL) { Status = STATUS_NO_MEMORY; } else { RtlCopyUnicodeString( &UnicodeString, &WindowsDirectory ); Status = RtlAppendUnicodeToString( &UnicodeString, L"\\" ); if (NT_SUCCESS( Status )) { Status = RtlAppendUnicodeStringToString( &UnicodeString, &FileName ); } } } if (IniFileName != NULL) { FreeMem( &IniFileName ); } if (NT_SUCCESS( Status )) { *ReturnedIniFilePath = AddName( &UnicodeString ); FreeMem( &UnicodeString.Buffer ); return TRUE; } else { FreeMem( &UnicodeString.Buffer ); return FALSE; } } BOOLEAN WritePrivateProfileStringEntry( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters, PWSTR IniFilePath, PWSTR SectionName, PWSTR VariableName, PWSTR VariableValue ) { if (CreateSavedCallState( Process, &Parameters->SavedCallState, WriteIniValue, HANDLE_TYPE_NONE, IniFilePath, SectionName, VariableName, VariableValue ) && CreateIniFileReference( IniFilePath, (PINI_FILE_REFERENCE *)&Parameters->SavedCallState.Reference ) ) { return TRUE; } else { FreeMem( &VariableValue ); return FALSE; } } BOOLEAN WritePrivateProfileStringExit( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PAPI_SAVED_CALL_STATE CallState; PINI_FILE_REFERENCE IniFileReference; PINI_SECTION_REFERENCE IniSectionReference; PINI_VARIABLE_REFERENCE IniVariableReference; if (Parameters->ReturnValue.ReturnedLong != 0) { CallState = &Parameters->SavedCallState; if (CallState->FullName == NULL && CallState->SetIniValue.SectionName == NULL && CallState->SetIniValue.VariableName == NULL ) { // // Ignore calls to flush INI cache // return FALSE; } IniFileReference = FindIniFileReference( CallState->FullName ); if (IniFileReference == NULL) { return TRUE; } IniSectionReference = FindIniSectionReference( IniFileReference, CallState->SetIniValue.SectionName, (BOOLEAN)(CallState->SetIniValue.VariableName != NULL) ); if (IniSectionReference == NULL) { return TRUE; } if (CallState->SetIniValue.VariableName == NULL) { IniSectionReference->Deleted = TRUE; LogEvent( INSTALER_EVENT_INI_DELETE_SECTION, 2, CallState->FullName, CallState->SetIniValue.SectionName ); } else { IniVariableReference = FindIniVariableReference( IniSectionReference, CallState->SetIniValue.VariableName, (BOOLEAN)(CallState->SetIniValue.VariableValue != NULL) ); if (IniVariableReference != NULL) { if (CallState->SetIniValue.VariableValue != NULL) { FreeMem( &IniVariableReference->Value ); IniVariableReference->Value = CallState->SetIniValue.VariableValue; CallState->SetIniValue.VariableValue = NULL; if (!IniVariableReference->Created) { if (!wcscmp( IniVariableReference->Value, IniVariableReference->OriginalValue ) ) { FreeMem( &IniVariableReference->Value ); } else { IniVariableReference->Modified = TRUE; LogEvent( INSTALER_EVENT_INI_CHANGE, 5, CallState->FullName, CallState->SetIniValue.SectionName, CallState->SetIniValue.VariableName, IniVariableReference->Value, IniVariableReference->OriginalValue ); } } else { LogEvent( INSTALER_EVENT_INI_CREATE, 4, CallState->FullName, CallState->SetIniValue.SectionName, CallState->SetIniValue.VariableName, IniVariableReference->Value ); } } else if (!IniVariableReference->Created) { IniVariableReference->Deleted = TRUE; LogEvent( INSTALER_EVENT_INI_DELETE, 4, CallState->FullName, CallState->SetIniValue.SectionName, CallState->SetIniValue.VariableName, IniVariableReference->OriginalValue ); } else { DestroyIniVariableReference( IniVariableReference ); } } } } return TRUE; } BOOLEAN WritePrivateProfileStringAHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PWRITEPRIVATEPROFILESTRINGA_PARAMETERS p = &Parameters->InputParameters.WritePrivateProfileStringA; PWSTR SectionName, VariableName, FileName, VariableValue; PWSTR IniFilePath; if (!Parameters->ReturnValueValid) { FileName = NULL; VariableValue = NULL; if (CaptureAnsiAsUnicode( Process, p->lpFileName, FALSE, NULL, &FileName ) && GetIniFilePath( FileName, &IniFilePath ) && CaptureAnsiAsUnicode( Process, p->lpAppName, FALSE, &SectionName, NULL ) && CaptureAnsiAsUnicode( Process, p->lpKeyName, FALSE, &VariableName, NULL ) && CaptureAnsiAsUnicode( Process, p->lpString, FALSE, NULL, &VariableValue ) ) { if (FileName != NULL || SectionName != NULL) { return WritePrivateProfileStringEntry( Process, Thread, Parameters, IniFilePath, SectionName, VariableName, VariableValue ); } } return TRUE; } else { return WritePrivateProfileStringExit( Process, Thread, Parameters ); } } BOOLEAN WritePrivateProfileStringWHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PWRITEPRIVATEPROFILESTRINGW_PARAMETERS p = &Parameters->InputParameters.WritePrivateProfileStringW; PWSTR SectionName, VariableName, FileName, VariableValue; PWSTR IniFilePath; if (!Parameters->ReturnValueValid) { FileName = NULL; IniFilePath = NULL; SectionName = NULL; VariableName = NULL; VariableValue = NULL; if (CaptureUnicode( Process, p->lpFileName, FALSE, NULL, &FileName ) && GetIniFilePath( FileName, &IniFilePath ) && CaptureUnicode( Process, p->lpAppName, FALSE, &SectionName, NULL ) && CaptureUnicode( Process, p->lpKeyName, FALSE, &VariableName, NULL ) && CaptureUnicode( Process, p->lpString, FALSE, NULL, &VariableValue ) ) { if (FileName != NULL || SectionName != NULL) { return WritePrivateProfileStringEntry( Process, Thread, Parameters, IniFilePath, SectionName, VariableName, VariableValue ); } } return TRUE; } return WritePrivateProfileStringExit( Process, Thread, Parameters ); } BOOLEAN WritePrivateProfileSectionEntry( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters, PWSTR IniFilePath, PWSTR SectionName, PWSTR SectionValue ) { if (CreateSavedCallState( Process, &Parameters->SavedCallState, WriteIniSection, HANDLE_TYPE_NONE, IniFilePath, SectionName, SectionValue ) && CreateIniFileReference( IniFilePath, (PINI_FILE_REFERENCE *)&Parameters->SavedCallState.Reference ) ) { return TRUE; } FreeMem( &SectionValue ); return FALSE; } BOOLEAN WritePrivateProfileSectionExit( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PAPI_SAVED_CALL_STATE CallState; PINI_FILE_REFERENCE IniFileReference; PINI_SECTION_REFERENCE IniSectionReference; PINI_VARIABLE_REFERENCE IniVariableReference; PWSTR VariableName, VariableValue; UNICODE_STRING UnicodeString; if (Parameters->ReturnValue.ReturnedLong != 0) { CallState = &Parameters->SavedCallState; IniFileReference = FindIniFileReference( CallState->FullName ); if (IniFileReference == NULL) { return TRUE; } IniSectionReference = FindIniSectionReference( IniFileReference, CallState->SetIniSection.SectionName, (BOOLEAN)(CallState->SetIniSection.SectionValue != NULL) ); if (IniSectionReference == NULL) { return TRUE; } if (CallState->SetIniSection.SectionValue == NULL) { IniSectionReference->Deleted = TRUE; } else { VariableName = CallState->SetIniSection.SectionValue; while (*VariableName) { VariableValue = VariableName; while (*VariableValue != UNICODE_NULL && *VariableValue != L'=') { VariableValue += 1; } if (*VariableValue != L'=') { break; } *VariableValue++ = UNICODE_NULL; RtlInitUnicodeString( &UnicodeString, VariableName ); IniVariableReference = FindIniVariableReference( IniSectionReference, AddName( &UnicodeString ), (BOOLEAN)(*VariableValue != UNICODE_NULL) ); if (IniVariableReference != NULL) { if (*VariableValue != UNICODE_NULL) { FreeMem( &IniVariableReference->Value ); IniVariableReference->Value = AllocMem( (wcslen( VariableValue ) + 1) * sizeof( WCHAR ) ); wcscpy( IniVariableReference->Value, VariableValue ); if (!IniVariableReference->Created) { if (!wcscmp( IniVariableReference->Value, IniVariableReference->OriginalValue ) ) { FreeMem( &IniVariableReference->Value ); } else { IniVariableReference->Modified = TRUE; } } } else if (!IniVariableReference->Created) { IniVariableReference->Deleted = TRUE; } else { DestroyIniVariableReference( IniVariableReference ); } } VariableName = VariableValue; while (*VariableName++ != UNICODE_NULL) {} } } } return TRUE; } BOOLEAN WritePrivateProfileSectionAHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PWRITEPRIVATEPROFILESECTIONA_PARAMETERS p = &Parameters->InputParameters.WritePrivateProfileSectionA; PWSTR SectionName, FileName, SectionValue; PWSTR IniFilePath; if (!Parameters->ReturnValueValid) { FileName = NULL; SectionValue = NULL; if (CaptureAnsiAsUnicode( Process, p->lpFileName, FALSE, NULL, &FileName ) && GetIniFilePath( FileName, &IniFilePath ) && CaptureAnsiAsUnicode( Process, p->lpAppName, FALSE, &SectionName, NULL ) && CaptureAnsiAsUnicode( Process, p->lpString, TRUE, NULL, &SectionValue ) ) { return WritePrivateProfileSectionEntry( Process, Thread, Parameters, IniFilePath, SectionName, SectionValue ); } return FALSE; } else { return WritePrivateProfileSectionExit( Process, Thread, Parameters ); } } BOOLEAN WritePrivateProfileSectionWHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PWRITEPRIVATEPROFILESECTIONW_PARAMETERS p = &Parameters->InputParameters.WritePrivateProfileSectionW; PWSTR SectionName, FileName, SectionValue; PWSTR IniFilePath; if (!Parameters->ReturnValueValid) { FileName = NULL; SectionValue = NULL; if (CaptureUnicode( Process, p->lpFileName, FALSE, NULL, &FileName ) && GetIniFilePath( FileName, &IniFilePath ) && CaptureUnicode( Process, p->lpAppName, FALSE, &SectionName, NULL ) && CaptureUnicode( Process, p->lpString, TRUE, NULL, &SectionValue ) ) { return WritePrivateProfileSectionEntry( Process, Thread, Parameters, IniFilePath, SectionName, SectionValue ); } return FALSE; } else { return WritePrivateProfileSectionExit( Process, Thread, Parameters ); } } BOOLEAN RegConnectRegistryWHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PREGCONNECTREGISTRYW_PARAMETERS p = &Parameters->InputParameters.RegConnectRegistryW; PWSTR MachineName; LONG ErrorCode; HKEY hKey; if (!Parameters->ReturnValueValid) { MachineName = NULL; if (!CaptureUnicode( Process, p->lpMachineName, FALSE, NULL, &MachineName )) { MachineName = L"Unknown"; } if (AskUser( MB_OKCANCEL, INSTALER_ASKUSER_REGCONNECT, 1, MachineName ) == IDCANCEL ) { FreeMem( &MachineName ); Parameters->AbortCall = TRUE; return TRUE; } else { FreeMem( &MachineName ); return FALSE; } } else if (Parameters->ReturnValue.ReturnedLong == 0) { ErrorCode = ERROR_ACCESS_DENIED; if (SetProcedureReturnValue( Process, Thread, &ErrorCode, sizeof( ErrorCode ) ) ) { if (ReadMemory( Process, p->phkResult, &hKey, sizeof( hKey ), "phkResult" ) ) { RegCloseKey( hKey ); hKey = NULL; WriteMemory( Process, p->phkResult, &hKey, sizeof( hKey ), "phkResult" ); } } } return TRUE; } BOOLEAN ExitWindowsExHandler( PPROCESS_INFO Process, PTHREAD_INFO Thread, PAPI_SAVED_PARAMETERS Parameters ) { PEXITWINDOWSEX_PARAMETERS p = &Parameters->InputParameters.ExitWindowsEx; PWSTR MachineName; LONG ErrorCode; HKEY hKey; if (!Parameters->ReturnValueValid) { // // About to shutdown, save .IML file // return TRUE; } else if (!Parameters->ReturnValue.ReturnedBool) { // // Shutdown attempt failed, keep going // } return TRUE; }
masahase0117/delegate
maker/getrusage.c
<reponame>masahase0117/delegate #ifndef _MSC_VER #include "ystring.h" int strfRusage(PVStr(usg),PCStr(fmt),int who,PCStr(sru)){ setVStrEnd(usg,0); return 0; } #endif
adamsaparudin/portfolio-hacktiv8
11. Something Cool/server/controllers/question.js
<reponame>adamsaparudin/portfolio-hacktiv8 let Question = require('../models/question') let User = require('../models/user') module.exports = { create: (req, res, next) => { let doc = new Question(req.body) doc.save().then( (data) => { User.findByIdAndUpdate(data.poster, {$push: {"listQuestion": data._id}}, function(err, user) { if(err) console.log(err); else console.log(user); }) res.send(data) }).catch( (err) =>{ res.send(err) }) }, readOne: (req, res, next) => { Question.findOne({_id: req.params.id}).populate([ { path: 'poster', model: 'User', select: 'username' }, { path: 'listAnswer', model: 'Answer', populate: [ { path: 'listComment', model: 'Comment', select: 'comment, poster', populate: { path: 'poster', model: 'User', select: 'username', } }, { path: 'poster', populate: 'User', select: 'username' } ] } ]).exec((err, docs) => { if(err) res.send(err) res.json(docs) }) }, upvote: (req, res, next) => { Question.findById(req.params.id, (err, doc) => { let score = doc.score if(req.params.id == undefined || req.params.id == null) { let index = doc.listGiveScore.findIndex( x => x.user == req.params.user); if(index == -1) { doc.update({ score: doc.score + 1, $push: {"listGiveScore": {user: req.params.user, tipe: 'upvote'}}, }, {new: true, upsert: true}, (err, data) => { if(err) res.send(err) else res.send({score : doc.score + 1}) }) } else if (doc.listGiveScore[index].tipe == "downvote" && index != -1) { let key = 'listGiveScore.' + index + '.tipe' let obj = {} obj[key] = 'upvote' doc.update({ score: doc.score + 2, $set: obj, }, {new: true, upsert: true}, (err, data) => { if(err) res.send(err) else res.send({score : doc.score + 2}) }) } else { res.send("you already upvote that shit") } } else res.send("Stupid nigga") }) }, downvote: (req, res, next) => { Question.findById(req.params.id, (err, doc) => { let score = doc.score if(req.params.id == undefined || req.params.id == null) { let index = doc.listGiveScore.findIndex( x => x.user == req.params.user); if(index == -1) { doc.update({ score: doc.score - 1, $push: {"listGiveScore": {user: req.params.user, tipe: 'downvote'}}, }, {'new': true, upsert: true}, (err, data) => { if(err) res.send(err) else res.send({score : doc.score - 1}) }) } else if (doc.listGiveScore[index].tipe == "upvote" && index != -1) { let key = 'listGiveScore.' + index + '.tipe' let obj = {} obj[key] = 'downvote' doc.update({ score: doc.score - 2, $set: obj, }, {'new': true, upsert: true}, (err, data) => { if(err) res.send(err) else res.send({score : doc.score - 2}) }) } else { res.send("you already downvote that shit") } } else { res.send("Supid nigga") } }) }, undoVote: (req, res, next) => { Question.findById(req.params.id, (err, doc) => { let newScore = doc.score - 1 doc.update({score: newScore, $pull: {listGiveScore : req.params.user}}, (err, data) => { if(err) res.send(err) else res.send(data) }) }) }, read: (req, res, next) => { Question.find({}).populate({ path: 'poster', model: 'User' }).exec((err, docs) => { if(err) res.send(err) else res.json(docs) }) }, update: (req, res, next) => { Question.findById(req.params.id, (err, doc) => { if (err) res.send(err) else { doc.update(req.body, (error, data) => { if(error) res.send(error) else res.send(data) }) } }) }, deleteQuestion: (req, res, next) => { Question.remove({_id : req.params.id}, (err, doc) => { if (err) res.send(err) else res.send(doc) }) } }
aoelen/orkg-frontend
src/components/Home/TrendingProblems.js
<reponame>aoelen/orkg-frontend<filename>src/components/Home/TrendingProblems.js import { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import styled from 'styled-components'; import { FontAwesomeIcon as Icon } from '@fortawesome/react-fontawesome'; import { faFire, faSpinner } from '@fortawesome/free-solid-svg-icons'; import { getTopResearchProblems } from 'services/backend/problems'; import Tippy from '@tippyjs/react'; import ROUTES from 'constants/routes'; import { reverseWithSlug } from 'utils'; const List = styled.div` padding: 0 40px; // have a large horizontal padding to ensure the items are not out of the box on transform & > div { display: block; div { transition: transform 0.3s ease-in-out; } &:hover > div { transform: scale(1.2); } a { text-decoration: none; } } .item-0 { font-size: 145%; min-height: 40px; a { color: ${props => props.theme.secondaryDarker}!important; } } .item-1, .item-2 { font-size: 145%; min-height: 40px; a { color: ${props => props.theme.secondary}!important; } } .item-3, .item-4 { font-size: 100%; min-height: 30px; a { color: ${props => props.theme.secondary}!important; opacity: 0.8; } } `; const TrendingProblems = props => { const [problems, setProblems] = useState([]); const [isLoading, setIsLoading] = useState(true); useEffect(() => { const getProblems = () => { getTopResearchProblems() .then(problemsList => { setProblems(problemsList); setIsLoading(false); }) .catch(error => { setIsLoading(false); }); }; getProblems(); }, []); return ( <div> <div className="box rounded-3 mt-4"> <h2 className="h5 p-3 mb-0"> <Tippy content="A list of research problems addressed by papers recently added to ORKG."> <span> <Icon icon={faFire} className="text-primary me-2" /> Trending research problems </span> </Tippy> </h2> <hr className="mx-3 mt-0" /> {isLoading ? ( <div className="text-center py-5"> <Icon icon={faSpinner} spin /> Loading </div> ) : ( <div className="px-4 text-center pb-5"> <List> {problems.map((problem, index) => ( <div key={`${index}-problem`}> <div className={`item-${index}`}> <Link to={reverseWithSlug(ROUTES.RESEARCH_PROBLEM, { researchProblemId: problem.id, slug: problem.label })}> {problem.label} </Link> </div> {index !== problems.length - 1 && <hr className="mx-3 mb-1 mt-0" />} </div> ))} </List> </div> )} </div> </div> ); }; export default TrendingProblems;
maciejg-git/vue-bootstrap-icons
dist-mdi/mdi/gesture-two-tap.js
import { h } from 'vue' export default { name: "GestureTwoTap", vendor: "Mdi", type: "", tags: ["gesture","two","tap"], render() { return h( "svg", {"xmlns":"http://www.w3.org/2000/svg","width":"24","height":"24","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"mdi-gesture-two-tap","innerHTML":"<path d='M19,15.14V21.5C18.97,22.32 18.32,22.97 17.5,23H11C10.62,23 10.26,22.85 10,22.57L5.1,18.37L5.84,17.6C6.03,17.39 6.3,17.28 6.58,17.28H6.8L10,19V9A1,1 0 0,1 11,8A1,1 0 0,1 12,9V7A1,1 0 0,1 13,6A1,1 0 0,1 14,7V12L18.15,13.84C18.66,14.07 19,14.58 19,15.14M15,10.45V9.24L15,9.23C15.23,9.03 15.42,8.79 15.57,8.54C15.84,8.09 16,7.56 16,7A3,3 0 0,0 13,4C12.21,4 11.5,4.31 10.95,4.81L10.81,4.95C10.68,5.09 10.56,5.24 10.46,5.4C10.36,5.56 10.27,5.74 10.2,5.92C10.17,6 10.15,6.06 10.13,6.13C8.9,6.5 8,7.65 8,9C8,9.7 8.24,10.34 8.64,10.85C8.74,11 8.87,11.11 9,11.23V11.24L9,12.46V12.46C7.8,11.77 7,10.5 7,9C7,7.38 7.97,6 9.35,5.35C10,3.97 11.38,3 13,3A4,4 0 0,1 17,7C17,8.5 16.2,9.77 15,10.46V10.45Z' />"}, ) } }
Remydeme/PROROK
deep-q-learning/SoftPolicyGradient/Sac/Networks/ValueNetwork.py
<filename>deep-q-learning/SoftPolicyGradient/Sac/Networks/ValueNetwork.py import tensorflow as tf import tensorflow.keras.layers as layers import tensorflow.keras.losses as kl import numpy as np from datetime import datetime class ValueNetworks(): hidden_1 = 128 hidden_2 = 64 def __init__(self, input_size, lr=1e-3): self.__lr = lr self.__input_size = input_size self.__initializer = tf.keras.initializers.he_uniform(seed=7) self.__output_init = tf.keras.initializers.RandomUniform(minval=-3e-3, maxval=3e-3, seed=None) self.__valueNet, self.__valueOptimizer = self._build_network() self.__targetNet,self.__targetNetOptimizer = self._build_network() def _build_network(self): model = tf.keras.Sequential() model.add(layers.Dense(self.hidden_1, input_dim=self.__input_size, activation='elu', kernel_initializer=self.__initializer)) model.add(layers.Dense(self.hidden_2, activation='elu', kernel_initializer=self.__initializer)) model.add(layers.Dense(1, activation='linear', kernel_initializer=self.__output_init)) model.build() optimizer = tf.keras.optimizers.Adam(learning_rate=self.__lr) model.compile(optimizer=optimizer, loss='mse') return model, optimizer def computeValue(self, observation): """ compute the value using observation as input :param observation: :return value: """ value = self.__valueNet(observation) return value def computeTargetValue(self, observation): """ compute the taget value using observation as input :param observation: :return value: """ value = self.__targetNet(observation) return value def updateTarget(self, tau=0.2): """ Copy the weights of the value network into the target network :return: """ pars_behavior = self.__valueNet.get_weights() # these have form [W1, b1, W2, b2, ..], Wi = pars_target = self.__targetNet.get_weights() # bi = biases in layer i ctr = 0 for par_behavior, par_target in zip(pars_behavior, pars_target): par_target = par_target * (1 - tau) + tau * par_behavior pars_target[ctr] = par_target ctr += 1 self.__targetNet.set_weights(pars_target) def train(self, observations, value): """ mse = tf.keras.losses.mean_squared_error(target, value) with tf.GradientTape() as tape: gradient = tape.gradient(mse, self.__valueNet.trainable_variables) self.__valueOptimizer.apply_gradients(zip(gradient, self.__valueNet.trainable_variables)) return mse """ self.__valueNet.fit(observations, value) def save(self): model_filename = "SACValueModel" + datetime.now().strftime("%Y%m%d-%H%M%S") target_model_filename = "SACTragetValueModel" + datetime.now().strftime("%Y%m%d-%H%M%S") self.__valueNet.save(model_filename) self.__targetNet.save(target_model_filename)
MeepSplize/Uniquis-Framework
src/cpp/Framework/Managers/Graphics Manager/Toolkit/DirectX 12/HeapDescription.cpp
<reponame>MeepSplize/Uniquis-Framework #include "pch.h" #include "Framework\\Managers\\Graphics Manager\\Toolkit\\DirectX 12\\HeapDescription.h" template<Uniquis::DirectX12::HeapType Type> Uniquis::DirectX12::HeapDescription<Type>::HeapDescription(const unsigned __int64 alignment, const unsigned __int64 byteSize, const HeapFlags& flags) : InternalDescription() { this->InternalDescription.SizeInBytes = byteSize; this->InternalDescription.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; this->InternalDescription.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; this->InternalDescription.Properties.CreationNodeMask = 0; this->InternalDescription.Properties.VisibleNodeMask = 0; this->InternalDescription.Alignment = alignment; this->InternalDescription.Flags = D3D12_HEAP_FLAGS(flags); } template<Uniquis::DirectX12::HeapType Type> Uniquis::DirectX12::HeapDescription<Type>::HeapDescription(const unsigned __int8 cInputDescriptions, const InternalResourceDescription* pInternalResourceDescriptions, const HeapFlags& flags, const Device& pDevice) : InternalDescription() { ResourceAllocationInformation AllocationInformation; AllocationInformation = pDevice->GetResourceAllocationInfo(0, cInputDescriptions, pInternalResourceDescriptions); this->InternalDescription.SizeInBytes = AllocationInformation.SizeInBytes; this->InternalDescription.Properties.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN; this->InternalDescription.Properties.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN; this->InternalDescription.Properties.CreationNodeMask = 0; this->InternalDescription.Properties.VisibleNodeMask = 0; this->InternalDescription.Alignment = AllocationInformation.Alignment; this->InternalDescription.Flags = D3D12_HEAP_FLAGS(flags); } template<Uniquis::DirectX12::HeapType Type> Uniquis::DirectX12::HeapDescription<Type>::~HeapDescription() { } template<Uniquis::DirectX12::HeapType Type> const InternalHeapDescription* Uniquis::DirectX12::HeapDescription<Type>::operator*() const noexcept { return &(this->InternalDescription); } template class Uniquis::DirectX12::HeapDescription<Uniquis::DirectX12::HeapType::Default>; template class Uniquis::DirectX12::HeapDescription<Uniquis::DirectX12::HeapType::Upload>;
Wzzzx/chromium-crosswalk
ui/file_manager/file_manager/foreground/js/ui/file_table.js
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * Namespace for utility functions. */ var filelist = {}; /** * Custom column model for advanced auto-resizing. * * @param {!Array<cr.ui.table.TableColumn>} tableColumns Table columns. * @extends {cr.ui.table.TableColumnModel} * @constructor */ function FileTableColumnModel(tableColumns) { cr.ui.table.TableColumnModel.call(this, tableColumns); } /** * Inherits from cr.ui.TableColumnModel. */ FileTableColumnModel.prototype.__proto__ = cr.ui.table.TableColumnModel.prototype; /** * Minimum width of column. * @const {number} * @private */ FileTableColumnModel.MIN_WIDTH_ = 10; /** * Sets column width so that the column dividers move to the specified position. * This function also check the width of each column and keep the width larger * than MIN_WIDTH_. * * @private * @param {Array<number>} newPos Positions of each column dividers. */ FileTableColumnModel.prototype.applyColumnPositions_ = function(newPos) { // Check the minimum width and adjust the positions. for (var i = 0; i < newPos.length - 2; i++) { if (!this.columns_[i].visible) { newPos[i + 1] = newPos[i]; } else if (newPos[i + 1] - newPos[i] < FileTableColumnModel.MIN_WIDTH_) { newPos[i + 1] = newPos[i] + FileTableColumnModel.MIN_WIDTH_; } } for (var i = newPos.length - 1; i >= 2; i--) { if (!this.columns_[i - 1].visible) { newPos[i - 1] = newPos[i]; } else if (newPos[i] - newPos[i - 1] < FileTableColumnModel.MIN_WIDTH_) { newPos[i - 1] = newPos[i] - FileTableColumnModel.MIN_WIDTH_; } } // Set the new width of columns for (var i = 0; i < this.columns_.length; i++) { this.columns_[i].width = newPos[i + 1] - newPos[i]; } }; /** * Normalizes widths to make their sum 100% if possible. Uses the proportional * approach with some additional constraints. * * @param {number} contentWidth Target width. * @override */ FileTableColumnModel.prototype.normalizeWidths = function(contentWidth) { var totalWidth = 0; // Some columns have fixed width. for (var i = 0; i < this.columns_.length; i++) { totalWidth += this.columns_[i].width; } var positions = [0]; var sum = 0; for (var i = 0; i < this.columns_.length; i++) { var column = this.columns_[i]; sum += column.width; // Faster alternative to Math.floor for non-negative numbers. positions[i + 1] = ~~(contentWidth * sum / totalWidth); } this.applyColumnPositions_(positions); }; /** * Handles to the start of column resizing by splitters. */ FileTableColumnModel.prototype.handleSplitterDragStart = function() { this.initializeColumnPos(); }; /** * Handles to the end of column resizing by splitters. */ FileTableColumnModel.prototype.handleSplitterDragEnd = function() { this.destroyColumnPos(); }; /** * Initialize a column snapshot which is used in setWidthAndKeepTotal(). */ FileTableColumnModel.prototype.initializeColumnPos = function() { this.snapshot_ = new FileTableColumnModel.ColumnSnapshot(this.columns_); }; /** * Destroy the column snapshot which is used in setWidthAndKeepTotal(). */ FileTableColumnModel.prototype.destroyColumnPos = function() { this.snapshot_ = null; }; /** * Sets the width of column while keeping the total width of table. * Before and after calling this method, you must initialize and destroy * columnPos with initializeColumnPos() and destroyColumnPos(). * @param {number} columnIndex Index of column that is resized. * @param {number} columnWidth New width of the column. */ FileTableColumnModel.prototype.setWidthAndKeepTotal = function( columnIndex, columnWidth) { columnWidth = Math.max(columnWidth, FileTableColumnModel.MIN_WIDTH_); this.snapshot_.setWidth(columnIndex, columnWidth); this.applyColumnPositions_(this.snapshot_.newPos); // Notify about resizing cr.dispatchSimpleEvent(this, 'resize'); }; /** * Obtains a column by the specified horizontal position. * @param {number} x Horizontal position. * @return {Object} The object that contains column index, column width, and * hitPosition where the horizontal position is hit in the column. */ FileTableColumnModel.prototype.getHitColumn = function(x) { for (var i = 0; x >= this.columns_[i].width; i++) { x -= this.columns_[i].width; } if (i >= this.columns_.length) return null; return {index: i, hitPosition: x, width: this.columns_[i].width}; }; /** @override */ FileTableColumnModel.prototype.setVisible = function(index, visible) { if (index < 0 || index > this.columns_.size -1) return; var column = this.columns_[index]; if (column.visible === visible) return; // Re-layout the table. This overrides the default column layout code in the // parent class. var snapshot = new FileTableColumnModel.ColumnSnapshot(this.columns_); column.visible = visible; // Keep the current column width, but adjust the other columns to accomodate // the new column. snapshot.setWidth(index, column.width); this.applyColumnPositions_(snapshot.newPos); }; /** * Export a set of column widths for use by #restoreColumnWidths. Use these two * methods instead of manually saving and setting column widths, because doing * the latter will not correctly save/restore column widths for hidden columns. * @see #restoreColumnWidths * @return {!Object} config */ FileTableColumnModel.prototype.exportColumnConfig = function() { // Make a snapshot, and use that to compute a column layout where all the // columns are visible. var snapshot = new FileTableColumnModel.ColumnSnapshot(this.columns_); for (var i = 0; i < this.columns_.length; i++) { if (!this.columns_[i].visible) { snapshot.setWidth(i, this.columns_[i].absoluteWidth); } } // Export the column widths. var config = {}; for (var i = 0; i < this.columns_.length; i++) { config[this.columns_[i].id] = { width: snapshot.newPos[i + 1] - snapshot.newPos[i] }; } return config; }; /** * Restores a set of column widths previously created by calling * #exportColumnConfig. * @see #exportColumnConfig * @param {!Object} config */ FileTableColumnModel.prototype.restoreColumnConfig = function(config) { // Convert old-style raw column widths into new-style config objects. if (Array.isArray(config)) { var tmpConfig = {}; tmpConfig[this.columns_[0].id] = config[0]; tmpConfig[this.columns_[1].id] = config[1]; tmpConfig[this.columns_[3].id] = config[2]; tmpConfig[this.columns_[4].id] = config[3]; config = tmpConfig; } // Columns must all be made visible before restoring their widths. Save the // current visibility so it can be restored after. var visibility = []; for (var i = 0; i < this.columns_.length; i++) { visibility[i] = this.columns_[i].visible; this.columns_[i].visible = true; } // Do not use external setters (e.g. #setVisible, #setWidth) here because they // trigger layout thrash, and also try to dynamically resize columns, which // interferes with restoring the old column layout. for (var columnId in config) { var column = this.columns_[this.indexOf(columnId)]; if (column) { // Set column width. Ignore invalid widths. var width = ~~config[columnId].width; if (width > 0) column.width = width; } } // Restore column visibility. Use setVisible here, to trigger table relayout. for (var i = 0; i < this.columns_.length; i++) { this.setVisible(i, visibility[i]); } }; /** * A helper class for performing resizing of columns. * @param {!Array<!cr.ui.table.TableColumn>} columns * @constructor */ FileTableColumnModel.ColumnSnapshot = function(columns) { /** @private {!Array<number>} */ this.columnPos_ = [0]; for (var i = 0; i < columns.length; i++) { this.columnPos_[i + 1] = columns[i].width + this.columnPos_[i]; } /** * Starts off as a copy of the current column positions, but gets modified. * @private {!Array<number>} */ this.newPos = this.columnPos_.slice(0); }; /** * Set the width of the given column. The snapshot will keep the total width of * the table constant. * @param {number} index * @param {number} width */ FileTableColumnModel.ColumnSnapshot.prototype.setWidth = function( index, width) { // Skip to resize 'selection' column if (index < 0 || index >= this.columnPos_.length - 1 || !this.columnPos_) { return; } // Round up if the column is shrinking, and down if the column is expanding. // This prevents off-by-one drift. var currentWidth = this.columnPos_[index + 1] - this.columnPos_[index]; var round = width < currentWidth ? Math.ceil : Math.floor; // Calculate new positions of column splitters. var newPosStart = this.columnPos_[index] + width; var posEnd = this.columnPos_[this.columnPos_.length - 1]; for (var i = 0; i < index + 1; i++) { this.newPos[i] = this.columnPos_[i]; } for (var i = index + 1; i < this.columnPos_.length - 1; i++) { var posStart = this.columnPos_[index + 1]; this.newPos[i] = (posEnd - newPosStart) * (this.columnPos_[i] - posStart) / (posEnd - posStart) + newPosStart; this.newPos[i] = round(this.newPos[i]); } this.newPos[index] = this.columnPos_[index]; this.newPos[this.columnPos_.length - 1] = posEnd; }; /** * Custom splitter that resizes column with retaining the sum of all the column * width. */ var FileTableSplitter = cr.ui.define('div'); /** * Inherits from cr.ui.TableSplitter. */ FileTableSplitter.prototype.__proto__ = cr.ui.TableSplitter.prototype; /** * Handles the drag start event. */ FileTableSplitter.prototype.handleSplitterDragStart = function() { cr.ui.TableSplitter.prototype.handleSplitterDragStart.call(this); this.table_.columnModel.handleSplitterDragStart(); }; /** * Handles the drag move event. * @param {number} deltaX Horizontal mouse move offset. */ FileTableSplitter.prototype.handleSplitterDragMove = function(deltaX) { this.table_.columnModel.setWidthAndKeepTotal(this.columnIndex, this.columnWidth_ + deltaX, true); }; /** * Handles the drag end event. */ FileTableSplitter.prototype.handleSplitterDragEnd = function() { cr.ui.TableSplitter.prototype.handleSplitterDragEnd.call(this); this.table_.columnModel.handleSplitterDragEnd(); }; /** * File list Table View. * @constructor * @extends {cr.ui.Table} */ function FileTable() { throw new Error('Designed to decorate elements'); } /** * Inherits from cr.ui.Table. */ FileTable.prototype.__proto__ = cr.ui.Table.prototype; /** * Decorates the element. * @param {!Element} self Table to decorate. * @param {!MetadataModel} metadataModel To retrieve * metadata. * @param {VolumeManagerWrapper} volumeManager To retrieve volume info. * @param {!importer.HistoryLoader} historyLoader * @param {boolean} fullPage True if it's full page File Manager, * False if a file open/save dialog. */ FileTable.decorate = function( self, metadataModel, volumeManager, historyLoader, fullPage) { cr.ui.Table.decorate(self); FileTableList.decorate(self.list); self.__proto__ = FileTable.prototype; self.metadataModel_ = metadataModel; self.volumeManager_ = volumeManager; self.historyLoader_ = historyLoader; /** @private {ListThumbnailLoader} */ self.listThumbnailLoader_ = null; /** @private {number} */ self.beginIndex_ = 0; /** @private {number} */ self.endIndex_ = 0; /** @private {function(!Event)} */ self.onThumbnailLoadedBound_ = self.onThumbnailLoaded_.bind(self); /** * Reflects the visibility of import status in the UI. Assumption: import * status is only enabled in import-eligible locations. See * ImportController#onDirectoryChanged. For this reason, the code in this * class checks if import status is visible, and if so, assumes that all the * files are in an import-eligible location. * TODO(kenobi): Clean this up once import status is queryable from metadata. * * @private {boolean} */ self.importStatusVisible_ = true; var nameColumn = new cr.ui.table.TableColumn( 'name', str('NAME_COLUMN_LABEL'), fullPage ? 386 : 324); nameColumn.renderFunction = self.renderName_.bind(self); var sizeColumn = new cr.ui.table.TableColumn( 'size', str('SIZE_COLUMN_LABEL'), 110, true); sizeColumn.renderFunction = self.renderSize_.bind(self); sizeColumn.defaultOrder = 'desc'; var statusColumn = new cr.ui.table.TableColumn( 'status', str('STATUS_COLUMN_LABEL'), 60, true); statusColumn.renderFunction = self.renderStatus_.bind(self); statusColumn.visible = self.importStatusVisible_; var typeColumn = new cr.ui.table.TableColumn( 'type', str('TYPE_COLUMN_LABEL'), fullPage ? 110 : 110); typeColumn.renderFunction = self.renderType_.bind(self); var modTimeColumn = new cr.ui.table.TableColumn( 'modificationTime', str('DATE_COLUMN_LABEL'), fullPage ? 150 : 210); modTimeColumn.renderFunction = self.renderDate_.bind(self); modTimeColumn.defaultOrder = 'desc'; var columns = [ nameColumn, sizeColumn, statusColumn, typeColumn, modTimeColumn ]; var columnModel = new FileTableColumnModel(columns); self.columnModel = columnModel; self.formatter_ = new FileMetadataFormatter(); self.setRenderFunction(self.renderTableRow_.bind(self, self.getRenderFunction())); self.scrollBar_ = new ScrollBar(); self.scrollBar_.initialize(self, self.list); // Keep focus on the file list when clicking on the header. self.header.addEventListener('mousedown', function(e) { self.list.focus(); e.preventDefault(); }); self.relayoutRateLimiter_ = new AsyncUtil.RateLimiter(self.relayoutImmediately_.bind(self)); // Override header#redraw to use FileTableSplitter. /** @this {cr.ui.table.TableHeader} */ self.header.redraw = function() { this.__proto__.redraw.call(this); // Extend table splitters var splitters = this.querySelectorAll('.table-header-splitter'); for (var i = 0; i < splitters.length; i++) { if (splitters[i] instanceof FileTableSplitter) continue; FileTableSplitter.decorate(splitters[i]); } }; // Save the last selection. This is used by shouldStartDragSelection. self.list.addEventListener('mousedown', function(e) { this.lastSelection_ = this.selectionModel.selectedIndexes; }.bind(self), true); self.list.shouldStartDragSelection = self.shouldStartDragSelection_.bind(self); /** * Obtains the index list of elements that are hit by the point or the * rectangle. * * @param {number} x X coordinate value. * @param {number} y Y coordinate value. * @param {number=} opt_width Width of the coordinate. * @param {number=} opt_height Height of the coordinate. * @return {Array<number>} Index list of hit elements. * @this {cr.ui.List} */ self.list.getHitElements = function(x, y, opt_width, opt_height) { var currentSelection = []; var bottom = y + (opt_height || 0); for (var i = 0; i < this.selectionModel_.length; i++) { var itemMetrics = this.getHeightsForIndex_(i); if (itemMetrics.top < bottom && itemMetrics.top + itemMetrics.height >= y) currentSelection.push(i); } return currentSelection; }; }; /** * Updates high priority range of list thumbnail loader based on current * viewport. * * @param {number} beginIndex Begin index. * @param {number} endIndex End index. */ FileTable.prototype.updateHighPriorityRange = function(beginIndex, endIndex) { // Keep these values to set range when a new list thumbnail loader is set. this.beginIndex_ = beginIndex; this.endIndex_ = endIndex; if (this.listThumbnailLoader_ !== null) this.listThumbnailLoader_.setHighPriorityRange(beginIndex, endIndex); }; /** * Sets list thumbnail loader. * @param {ListThumbnailLoader} listThumbnailLoader A list thumbnail loader. */ FileTable.prototype.setListThumbnailLoader = function(listThumbnailLoader) { if (this.listThumbnailLoader_) { this.listThumbnailLoader_.removeEventListener( 'thumbnailLoaded', this.onThumbnailLoadedBound_); } this.listThumbnailLoader_ = listThumbnailLoader; if (this.listThumbnailLoader_) { this.listThumbnailLoader_.addEventListener( 'thumbnailLoaded', this.onThumbnailLoadedBound_); this.listThumbnailLoader_.setHighPriorityRange( this.beginIndex_, this.endIndex_); } }; /** * Handles thumbnail loaded event. * @param {!Event} event An event. * @private */ FileTable.prototype.onThumbnailLoaded_ = function(event) { var listItem = this.getListItemByIndex(event.index); if (listItem) { var box = listItem.querySelector('.detail-thumbnail'); if (box) { if (event.dataUrl) { this.setThumbnailImage_( assertInstanceof(box, HTMLDivElement), event.dataUrl, true /* with animation */); } else { this.clearThumbnailImage_( assertInstanceof(box, HTMLDivElement)); } } } }; /** * Adjust column width to fit its content. * @param {number} index Index of the column to adjust width. * @override */ FileTable.prototype.fitColumn = function(index) { var render = this.columnModel.getRenderFunction(index); var MAXIMUM_ROWS_TO_MEASURE = 1000; // Create a temporaty list item, put all cells into it and measure its // width. Then remove the item. It fits "list > *" CSS rules. var container = this.ownerDocument.createElement('li'); container.style.display = 'inline-block'; container.style.textAlign = 'start'; // The container will have width of the longest cell. container.style.webkitBoxOrient = 'vertical'; // Select at most MAXIMUM_ROWS_TO_MEASURE items around visible area. var items = this.list.getItemsInViewPort(this.list.scrollTop, this.list.clientHeight); var firstIndex = Math.floor(Math.max(0, (items.last + items.first - MAXIMUM_ROWS_TO_MEASURE) / 2)); var lastIndex = Math.min(this.dataModel.length, firstIndex + MAXIMUM_ROWS_TO_MEASURE); for (var i = firstIndex; i < lastIndex; i++) { var item = this.dataModel.item(i); var div = this.ownerDocument.createElement('div'); div.className = 'table-row-cell'; div.appendChild(render(item, this.columnModel.getId(index), this)); container.appendChild(div); } this.list.appendChild(container); var width = parseFloat(window.getComputedStyle(container).width); this.list.removeChild(container); this.columnModel.initializeColumnPos(); this.columnModel.setWidthAndKeepTotal(index, Math.ceil(width)); this.columnModel.destroyColumnPos(); }; /** * Sets the visibility of the cloud import status column. * @param {boolean} visible */ FileTable.prototype.setImportStatusVisible = function(visible) { if (this.importStatusVisible_ != visible) { this.importStatusVisible_ = visible; this.columnModel.setVisible(this.columnModel.indexOf('status'), visible); this.relayout(); } }; /** * Sets date and time format. * @param {boolean} use12hourClock True if 12 hours clock, False if 24 hours. */ FileTable.prototype.setDateTimeFormat = function(use12hourClock) { this.formatter_.setDateTimeFormat(use12hourClock); }; /** * Obtains if the drag selection should be start or not by referring the mouse * event. * @param {MouseEvent} event Drag start event. * @return {boolean} True if the mouse is hit to the background of the list. * @private */ FileTable.prototype.shouldStartDragSelection_ = function(event) { // If the shift key is pressed, it should starts drag selection. if (event.shiftKey) return true; // If the position values are negative, it points the out of list. // It should start the drag selection. var pos = DragSelector.getScrolledPosition(this.list, event); if (!pos) return false; if (pos.x < 0 || pos.y < 0) return true; // If the item index is out of range, it should start the drag selection. var itemHeight = this.list.measureItem().height; // Faster alternative to Math.floor for non-negative numbers. var itemIndex = ~~(pos.y / itemHeight); if (itemIndex >= this.list.dataModel.length) return true; // If the pointed item is already selected, it should not start the drag // selection. if (this.lastSelection_ && this.lastSelection_.indexOf(itemIndex) !== -1) return false; // If the horizontal value is not hit to column, it should start the drag // selection. var hitColumn = this.columnModel.getHitColumn(pos.x); if (!hitColumn) return true; // Check if the point is on the column contents or not. switch (this.columnModel.columns_[hitColumn.index].id) { case 'name': var item = this.list.getListItemByIndex(itemIndex); if (!item) return false; var spanElement = item.querySelector('.filename-label span'); var spanRect = spanElement.getBoundingClientRect(); // The this.list.cachedBounds_ object is set by // DragSelector.getScrolledPosition. if (!this.list.cachedBounds) return true; var textRight = spanRect.left - this.list.cachedBounds.left + spanRect.width; return textRight <= hitColumn.hitPosition; default: return true; } }; /** * Render the Name column of the detail table. * * Invoked by cr.ui.Table when a file needs to be rendered. * * @param {!Entry} entry The Entry object to render. * @param {string} columnId The id of the column to be rendered. * @param {cr.ui.Table} table The table doing the rendering. * @return {!HTMLDivElement} Created element. * @private */ FileTable.prototype.renderName_ = function(entry, columnId, table) { var label = /** @type {!HTMLDivElement} */ (this.ownerDocument.createElement('div')); var mimeType = this.metadataModel_.getCache([entry], ['contentMimeType'])[0].contentMimeType; var icon = filelist.renderFileTypeIcon(this.ownerDocument, entry, mimeType); if (FileType.isImage(entry, mimeType) || FileType.isVideo(entry, mimeType) || FileType.isAudio(entry, mimeType) || FileType.isRaw(entry, mimeType)) { icon.appendChild(this.renderThumbnail_(entry)); } icon.appendChild(this.renderCheckmark_()); label.appendChild(icon); label.entry = entry; label.className = 'detail-name'; label.appendChild(filelist.renderFileNameLabel(this.ownerDocument, entry)); return label; }; /** * Render the Size column of the detail table. * * @param {Entry} entry The Entry object to render. * @param {string} columnId The id of the column to be rendered. * @param {cr.ui.Table} table The table doing the rendering. * @return {!HTMLDivElement} Created element. * @private */ FileTable.prototype.renderSize_ = function(entry, columnId, table) { var div = /** @type {!HTMLDivElement} */ (this.ownerDocument.createElement('div')); div.className = 'size'; this.updateSize_(div, entry); return div; }; /** * Sets up or updates the size cell. * * @param {HTMLDivElement} div The table cell. * @param {Entry} entry The corresponding entry. * @private */ FileTable.prototype.updateSize_ = function(div, entry) { var metadata = this.metadataModel_.getCache( [entry], ['size', 'hosted'])[0]; var size = metadata.size; var hosted = metadata.hosted; div.textContent = this.formatter_.formatSize(size, hosted); }; /** * Render the Status column of the detail table. * * @param {Entry} entry The Entry object to render. * @param {string} columnId The id of the column to be rendered. * @param {cr.ui.Table} table The table doing the rendering. * @return {!HTMLDivElement} Created element. * @private */ FileTable.prototype.renderStatus_ = function(entry, columnId, table) { var div = /** @type {!HTMLDivElement} */ ( this.ownerDocument.createElement('div')); div.className = 'status status-icon'; if (entry) { this.updateStatus_(div, entry); } return div; }; /** * Returns the status of the entry w.r.t. the given import destination. * @param {Entry} entry * @param {!importer.Destination} destination * @return {!Promise<string>} The import status - will be 'imported', 'copied', * or 'unknown'. */ FileTable.prototype.getImportStatus_ = function(entry, destination) { // If import status is not visible, early out because there's no point // retrieving it. if (!this.importStatusVisible_ || !importer.isEligibleType(entry)) { // Our import history doesn't deal with directories. // TODO(kenobi): May need to revisit this if the above assumption changes. return Promise.resolve('unknown'); } // For the compiler. var fileEntry = /** @type {!FileEntry} */ (entry); return this.historyLoader_.getHistory() .then( /** @param {!importer.ImportHistory} history */ function(history) { return Promise.all([ history.wasImported(fileEntry, destination), history.wasCopied(fileEntry, destination) ]); }) .then( /** @param {!Array<boolean>} status */ function(status) { if (status[0]) { return 'imported'; } else if (status[1]) { return 'copied'; } else { return 'unknown'; } }); }; /** * Render the status icon of the detail table. * * @param {HTMLDivElement} div * @param {Entry} entry The Entry object to render. * @private */ FileTable.prototype.updateStatus_ = function(div, entry) { this.getImportStatus_(entry, importer.Destination.GOOGLE_DRIVE).then( /** @param {string} status */ function(status) { div.setAttribute('file-status-icon', status); }); }; /** * Render the Type column of the detail table. * * @param {Entry} entry The Entry object to render. * @param {string} columnId The id of the column to be rendered. * @param {cr.ui.Table} table The table doing the rendering. * @return {!HTMLDivElement} Created element. * @private */ FileTable.prototype.renderType_ = function(entry, columnId, table) { var div = /** @type {!HTMLDivElement} */ (this.ownerDocument.createElement('div')); div.className = 'type'; var mimeType = this.metadataModel_.getCache([entry], ['contentMimeType'])[0].contentMimeType; div.textContent = FileListModel.getFileTypeString( FileType.getType(entry, mimeType)); return div; }; /** * Render the Date column of the detail table. * * @param {Entry} entry The Entry object to render. * @param {string} columnId The id of the column to be rendered. * @param {cr.ui.Table} table The table doing the rendering. * @return {HTMLDivElement} Created element. * @private */ FileTable.prototype.renderDate_ = function(entry, columnId, table) { var div = /** @type {!HTMLDivElement} */ (this.ownerDocument.createElement('div')); div.className = 'date'; this.updateDate_(div, entry); return div; }; /** * Sets up or updates the date cell. * * @param {HTMLDivElement} div The table cell. * @param {Entry} entry Entry of file to update. * @private */ FileTable.prototype.updateDate_ = function(div, entry) { var modTime = this.metadataModel_.getCache( [entry], ['modificationTime'])[0].modificationTime; div.textContent = this.formatter_.formatModDate(modTime); }; /** * Updates the file metadata in the table item. * * @param {Element} item Table item. * @param {Entry} entry File entry. */ FileTable.prototype.updateFileMetadata = function(item, entry) { this.updateDate_( /** @type {!HTMLDivElement} */ (item.querySelector('.date')), entry); this.updateSize_( /** @type {!HTMLDivElement} */ (item.querySelector('.size')), entry); this.updateStatus_( /** @type {!HTMLDivElement} */ (item.querySelector('.status')), entry); }; /** * Updates list items 'in place' on metadata change. * @param {string} type Type of metadata change. * @param {Array<Entry>} entries Entries to update. */ FileTable.prototype.updateListItemsMetadata = function(type, entries) { var urls = util.entriesToURLs(entries); var forEachCell = function(selector, callback) { var cells = this.querySelectorAll(selector); for (var i = 0; i < cells.length; i++) { var cell = cells[i]; var listItem = this.list_.getListItemAncestor(cell); var entry = this.dataModel.item(listItem.listIndex); if (entry && urls.indexOf(entry.toURL()) !== -1) callback.call(this, cell, entry, listItem); } }.bind(this); if (type === 'filesystem') { forEachCell('.table-row-cell > .date', function(item, entry, unused) { this.updateDate_(item, entry); }); forEachCell('.table-row-cell > .size', function(item, entry, unused) { this.updateSize_(item, entry); }); } else if (type === 'external') { // The cell name does not matter as the entire list item is needed. forEachCell('.table-row-cell > .date', function(item, entry, listItem) { filelist.updateListItemExternalProps( listItem, this.metadataModel_.getCache( [entry], ['availableOffline', 'customIconUrl', 'shared'])[0]); }); } else if (type === 'import-history') { forEachCell('.table-row-cell > .status', function(item, entry, unused) { this.updateStatus_(item, entry); }); } }; /** * Renders table row. * @param {function(Entry, cr.ui.Table)} baseRenderFunction Base renderer. * @param {Entry} entry Corresponding entry. * @return {HTMLLIElement} Created element. * @private */ FileTable.prototype.renderTableRow_ = function(baseRenderFunction, entry) { var item = baseRenderFunction(entry, this); filelist.decorateListItem(item, entry, this.metadataModel_); return item; }; /** * Renders the file thumbnail in the detail table. * @param {Entry} entry The Entry object to render. * @return {!HTMLDivElement} Created element. * @private */ FileTable.prototype.renderThumbnail_ = function(entry) { var box = /** @type {!HTMLDivElement} */ (this.ownerDocument.createElement('div')); box.className = 'detail-thumbnail'; // Set thumbnail if it's already in cache. var thumbnailData = this.listThumbnailLoader_ ? this.listThumbnailLoader_.getThumbnailFromCache(entry) : null; if (thumbnailData && thumbnailData.dataUrl) { this.setThumbnailImage_( box, this.listThumbnailLoader_.getThumbnailFromCache(entry).dataUrl, false /* without animation */); } return box; }; /** * Sets thumbnail image to the box. * @param {!HTMLDivElement} box Detail thumbnail div element. * @param {string} dataUrl Data url of thumbnail. * @param {boolean} shouldAnimate Whether the thumbnail is shown with animation * or not. * @private */ FileTable.prototype.setThumbnailImage_ = function(box, dataUrl, shouldAnimate) { var oldThumbnails = box.querySelectorAll('.thumbnail'); var thumbnail = box.ownerDocument.createElement('div'); thumbnail.classList.add('thumbnail'); thumbnail.style.backgroundImage = 'url(' + dataUrl + ')'; thumbnail.addEventListener('webkitAnimationEnd', function() { // Remove animation css once animation is completed in order not to animate // again when an item is attached to the dom again. thumbnail.classList.remove('animate'); for (var i = 0; i < oldThumbnails.length; i++) { if (box.contains(oldThumbnails[i])) box.removeChild(oldThumbnails[i]); } }); if (shouldAnimate) thumbnail.classList.add('animate'); box.appendChild(thumbnail); }; /** * Clears thumbnail image from the box. * @param {!HTMLDivElement} box Detail thumbnail div element. * @private */ FileTable.prototype.clearThumbnailImage_ = function(box) { var oldThumbnails = box.querySelectorAll('.thumbnail'); for (var i = 0; i < oldThumbnails.length; i++) { box.removeChild(oldThumbnails[i]); } }; /** * Renders the selection checkmark in the detail table. * @return {!HTMLDivElement} Created element. * @private */ FileTable.prototype.renderCheckmark_ = function() { var checkmark = /** @type {!HTMLDivElement} */ (this.ownerDocument.createElement('div')); checkmark.className = 'detail-checkmark'; return checkmark; }; /** * Redraws the UI. Skips multiple consecutive calls. */ FileTable.prototype.relayout = function() { this.relayoutRateLimiter_.run(); }; /** * Redraws the UI immediately. * @private */ FileTable.prototype.relayoutImmediately_ = function() { if (this.clientWidth > 0) this.normalizeColumns(); this.redraw(); cr.dispatchSimpleEvent(this.list, 'relayout'); }; /** * Common item decoration for table's and grid's items. * @param {cr.ui.ListItem} li List item. * @param {Entry} entry The entry. * @param {!MetadataModel} metadataModel Cache to * retrieve metadada. */ filelist.decorateListItem = function(li, entry, metadataModel) { li.classList.add(entry.isDirectory ? 'directory' : 'file'); // The metadata may not yet be ready. In that case, the list item will be // updated when the metadata is ready via updateListItemsMetadata. For files // not on an external backend, externalProps is not available. var externalProps = metadataModel.getCache( [entry], ['hosted', 'availableOffline', 'customIconUrl', 'shared'])[0]; filelist.updateListItemExternalProps(li, externalProps); // Overriding the default role 'list' to 'listbox' for better // accessibility on ChromeOS. li.setAttribute('role', 'option'); Object.defineProperty(li, 'selected', { /** * @this {cr.ui.ListItem} * @return {boolean} True if the list item is selected. */ get: function() { return this.hasAttribute('selected'); }, /** * @this {cr.ui.ListItem} */ set: function(v) { if (v) this.setAttribute('selected', ''); else this.removeAttribute('selected'); } }); }; /** * Render the type column of the detail table. * @param {!Document} doc Owner document. * @param {!Entry} entry The Entry object to render. * @param {string=} opt_mimeType Optional mime type for the file. * @return {!HTMLDivElement} Created element. */ filelist.renderFileTypeIcon = function(doc, entry, opt_mimeType) { var icon = /** @type {!HTMLDivElement} */ (doc.createElement('div')); icon.className = 'detail-icon'; icon.setAttribute('file-type-icon', FileType.getIcon(entry, opt_mimeType)); return icon; }; /** * Render filename label for grid and list view. * @param {!Document} doc Owner document. * @param {!Entry} entry The Entry object to render. * @return {!HTMLDivElement} The label. */ filelist.renderFileNameLabel = function(doc, entry) { // Filename need to be in a '.filename-label' container for correct // work of inplace renaming. var box = /** @type {!HTMLDivElement} */ (doc.createElement('div')); box.className = 'filename-label'; var fileName = doc.createElement('span'); fileName.className = 'entry-name'; fileName.textContent = entry.name; box.appendChild(fileName); return box; }; /** * Updates grid item or table row for the externalProps. * @param {cr.ui.ListItem} li List item. * @param {Object} externalProps Metadata. */ filelist.updateListItemExternalProps = function(li, externalProps) { if (li.classList.contains('file')) { if (externalProps.availableOffline) li.classList.remove('dim-offline'); else li.classList.add('dim-offline'); // TODO(mtomasz): Consider adding some vidual indication for files which // are not cached on LTE. Currently we show them as normal files. // crbug.com/246611. } var iconDiv = li.querySelector('.detail-icon'); if (!iconDiv) return; if (externalProps.customIconUrl) iconDiv.style.backgroundImage = 'url(' + externalProps.customIconUrl + ')'; else iconDiv.style.backgroundImage = ''; // Back to the default image. if (li.classList.contains('directory')) iconDiv.classList.toggle('shared', !!externalProps.shared); }; /** * Handles mouseup/mousedown events on file list to change the selection state. * * Basically the content of this function is identical to * cr.ui.ListSelectionController's handlePointerDownUp(), but following * handlings are inserted to control the check-select mode. * * 1) When checkmark area is clicked, toggle item selection and enable the * check-select mode. * 2) When non-checkmark area is clicked in check-select mode, disable the * check-select mode. * * @param {!Event} e The browser mouse event. * @param {number} index The index that was under the mouse pointer, -1 if * none. * @this {cr.ui.ListSelectionController} */ filelist.handlePointerDownUp = function(e, index) { var sm = /** @type {!FileListSelectionModel|!FileListSingleSelectionModel} */ (this.selectionModel); var anchorIndex = sm.anchorIndex; var isDown = (e.type == 'mousedown'); var isTargetCheckmark = e.target.classList.contains('detail-checkmark') || e.target.classList.contains('checkmark'); // If multiple selection is allowed and the checkmark is clicked without // modifiers(Ctrl/Shift), the click should toggle the item's selection. // (i.e. same behavior as Ctrl+Click) var isClickOnCheckmark = isTargetCheckmark && sm.multiple && index != -1 && !e.shiftKey && !e.ctrlKey && e.button == 0; sm.beginChange(); if (index == -1) { sm.leadIndex = sm.anchorIndex = -1; sm.unselectAll(); } else { if (sm.multiple && (e.ctrlKey || isClickOnCheckmark) && !e.shiftKey) { // Selection is handled at mouseUp. if (!isDown) { // 1) When checkmark area is clicked, toggle item selection and enable // the check-select mode. if (isClickOnCheckmark) { // If a selected item's checkmark is clicked when the selection mode // is not check-select, we should avoid toggling(unselecting) the // item. It is done here by toggling the selection twice. if (!sm.getCheckSelectMode() && sm.getIndexSelected(index)) sm.setIndexSelected(index, !sm.getIndexSelected(index)); // Always enables check-select mode on clicks on checkmark. sm.setCheckSelectMode(true); } // Toggle the current one and make it anchor index. sm.setIndexSelected(index, !sm.getIndexSelected(index)); sm.leadIndex = index; sm.anchorIndex = index; } } else if (e.shiftKey && anchorIndex != -1 && anchorIndex != index) { // Shift is done in mousedown. if (isDown) { sm.unselectAll(); sm.leadIndex = index; if (sm.multiple) sm.selectRange(anchorIndex, index); else sm.setIndexSelected(index, true); } } else { // Right click for a context menu needs to not clear the selection. var isRightClick = e.button == 2; // If the index is selected this is handled in mouseup. var indexSelected = sm.getIndexSelected(index); if ((indexSelected && !isDown || !indexSelected && isDown) && !(indexSelected && isRightClick)) { // 2) When non-checkmark area is clicked in check-select mode, disable // the check-select mode. if (sm.getCheckSelectMode()) { // Unselect all items once to ensure that the check-select mode is // terminated. sm.endChange(); sm.unselectAll(); sm.beginChange(); } sm.selectedIndex = index; } } } sm.endChange(); }; /** * Handles key events on file list to change the selection state. * * Basically the content of this function is identical to * cr.ui.ListSelectionController's handleKeyDown(), but following handlings is * inserted to control the check-select mode. * * 1) When pressing direction key results in a single selection, the * check-select mode should be terminated. * * @param {Event} e The keydown event. * @this {cr.ui.ListSelectionController} */ filelist.handleKeyDown = function(e) { var SPACE_KEY_CODE = 32; var tagName = e.target.tagName; // If focus is in an input field of some kind, only handle navigation keys // that aren't likely to conflict with input interaction (e.g., text // editing, or changing the value of a checkbox or select). if (tagName == 'INPUT') { var inputType = e.target.type; // Just protect space (for toggling) for checkbox and radio. if (inputType == 'checkbox' || inputType == 'radio') { if (e.keyCode == SPACE_KEY_CODE) return; // Protect all but the most basic navigation commands in anything else. } else if (e.key != 'ArrowUp' && e.key != 'ArrowDown') { return; } } // Similarly, don't interfere with select element handling. if (tagName == 'SELECT') return; var sm = /** @type {!FileListSelectionModel|!FileListSingleSelectionModel} */ (this.selectionModel); var newIndex = -1; var leadIndex = sm.leadIndex; var prevent = true; // Ctrl/Meta+A if (sm.multiple && e.keyCode == 65 && (cr.isMac && e.metaKey || !cr.isMac && e.ctrlKey)) { sm.selectAll(); e.preventDefault(); return; } // Esc if (e.keyCode === 27 && !e.ctrlKey && !e.shiftKey) { sm.unselectAll(); e.preventDefault(); return; } // Space if (e.keyCode == SPACE_KEY_CODE) { if (leadIndex != -1) { var selected = sm.getIndexSelected(leadIndex); if (e.ctrlKey || !selected) { sm.setIndexSelected(leadIndex, !selected || !sm.multiple); return; } } } switch (e.key) { case 'Home': newIndex = this.getFirstIndex(); break; case 'End': newIndex = this.getLastIndex(); break; case 'ArrowUp': newIndex = leadIndex == -1 ? this.getLastIndex() : this.getIndexAbove(leadIndex); break; case 'ArrowDown': newIndex = leadIndex == -1 ? this.getFirstIndex() : this.getIndexBelow(leadIndex); break; case 'ArrowLeft': case 'MediaTrackPrevious': newIndex = leadIndex == -1 ? this.getLastIndex() : this.getIndexBefore(leadIndex); break; case 'ArrowRight': case 'MediaTrackNext': newIndex = leadIndex == -1 ? this.getFirstIndex() : this.getIndexAfter(leadIndex); break; default: prevent = false; } if (newIndex >= 0 && newIndex < sm.length) { sm.beginChange(); sm.leadIndex = newIndex; if (e.shiftKey) { var anchorIndex = sm.anchorIndex; if (sm.multiple) sm.unselectAll(); if (anchorIndex == -1) { sm.setIndexSelected(newIndex, true); sm.anchorIndex = newIndex; } else { sm.selectRange(anchorIndex, newIndex); } } else { // 1) When pressing direction key results in a single selection, the // check-select mode should be terminated. sm.setCheckSelectMode(false); if (sm.multiple) sm.unselectAll(); sm.setIndexSelected(newIndex, true); sm.anchorIndex = newIndex; } sm.endChange(); if (prevent) e.preventDefault(); } };
megadix/p5js-scratchpad
src/sketches/physics/HangingBodiesPage.js
<gh_stars>1-10 import Sketch from "../../common/Sketch"; import HangingBodiesScript from "./HangingBodiesScript"; import PageLayout from "../../common/PageLayout"; export default function HangingBodiesPage() { return ( <PageLayout title="Hanging Bodies" description="p5.js sketch illustrating the effect of gravity on bodies attached with a rope"> <p>This sketch illustrates the effect of gravity on bodies attached with a rope.</p> <p>Click anywhere to start / reset the simulation.</p> <Sketch sketch={HangingBodiesScript}/> </PageLayout> ); }
galacticgumshoe/scoozie
src/test/scala/org/antipathy/scoozie/action/EmailActionSpec.scala
<reponame>galacticgumshoe/scoozie<filename>src/test/scala/org/antipathy/scoozie/action/EmailActionSpec.scala /** * Copyright (C) 2019 <EMAIL> <<EMAIL>> * * 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 org.antipathy.scoozie.action import org.antipathy.scoozie.configuration.Credentials import org.scalatest.{FlatSpec, Matchers} import scala.collection.immutable._ class EmailActionSpec extends FlatSpec with Matchers { behavior of "EmailAction" it should "generate valid XML" in { implicit val credentialsOption: Option[Credentials] = None val result = EmailAction(name = "email", to = Seq("<EMAIL>", "<EMAIL>"), cc = Seq.empty, subject = "message subject", body = "message body", contentTypeOption = None).action scala.xml.Utility.trim(result.toXML) should be(scala.xml.Utility.trim(<email xmlns="uri:oozie:email-action:0.2"> <to>{"${email_to}"}</to> <subject>{"${email_subject}"}</subject> <body>{"${email_body}"}</body> </email>)) result.properties should be( Map("${email_to}" -> "<EMAIL>,<EMAIL>", "${email_subject}" -> "message subject", "${email_body}" -> "message body") ) } it should "generate valid XML when a CC list is defined" in { implicit val credentialsOption: Option[Credentials] = None val result = EmailAction(name = "email", to = Seq("<EMAIL>", "<EMAIL>"), cc = Seq("<EMAIL>", "<EMAIL>"), "message subject", "message body", contentTypeOption = None).action scala.xml.Utility.trim(result.toXML) should be(scala.xml.Utility.trim(<email xmlns="uri:oozie:email-action:0.2"> <to>{"${email_to}"}</to> <cc>{"${email_cc}"}</cc> <subject>{"${email_subject}"}</subject> <body>{"${email_body}"}</body> </email>)) result.properties should be( Map("${email_to}" -> "<EMAIL>,<EMAIL>", "${email_subject}" -> "message subject", "${email_body}" -> "message body", "${email_cc}" -> "<EMAIL>,<EMAIL>") ) } }
gitter-badger/jbock
examples/src/main/java/net/jbock/examples/OptionalIntArgumentsOptional.java
package net.jbock.examples; import net.jbock.Command; import net.jbock.Converter; import net.jbock.Option; import net.jbock.util.StringConverter; import java.util.OptionalInt; import java.util.function.Supplier; @Command abstract class OptionalIntArgumentsOptional { @Option(names = {"--a", "-a"}, converter = MyConverter.class) abstract OptionalInt a(); @Converter static class MyConverter implements Supplier<StringConverter<Integer>> { @Override public StringConverter<Integer> get() { return StringConverter.create(Integer::parseInt); } } }
OSADP/C2C-RI
C2CRIBuildDir/projects/C2C-RI/src/NTCIP2306v01_69/src/org/fhwa/c2cri/ntcip2306v109/messaging/QueueController.java
<filename>C2CRIBuildDir/projects/C2C-RI/src/NTCIP2306v01_69/src/org/fhwa/c2cri/ntcip2306v109/messaging/QueueController.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.fhwa.c2cri.ntcip2306v109.messaging; import org.fhwa.c2cri.ntcip2306v109.operations.OperationResultsQueueController; /** * The Interface QueueController ensures the functions provided by the RequestQueue, ResponseQueue and OperationResultsQueue are available through a single interface. * * @author TransCore ITS, LLC * Last Updated: 1/8/2014 */ public interface QueueController extends RequestQueueController, ResponseQueueController, OperationResultsQueueController{ }
rbkmoney/three-ds-server-domain-lib
src/main/java/com/rbkmoney/threeds/server/domain/device/DeviceRenderOptions.java
<filename>src/main/java/com/rbkmoney/threeds/server/domain/device/DeviceRenderOptions.java package com.rbkmoney.threeds.server.domain.device; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.rbkmoney.threeds.server.domain.sdk.SdkInterface; import com.rbkmoney.threeds.server.domain.sdk.SdkUiType; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @AllArgsConstructor @NoArgsConstructor @Data @JsonInclude(value = JsonInclude.Include.NON_ABSENT) public class DeviceRenderOptions { @JsonProperty("sdkInterface") private SdkInterface sdkInterface; @JsonProperty("sdkUiType") private List<SdkUiType> sdkUiType; }
BarbourSmith/JSxCAD
api/shape/log.js
import { hash as computeHash, emit, log as sysLog } from '@jsxcad/sys'; import Shape from './Shape.js'; import { realize } from '@jsxcad/geometry'; /** * * # Log * * Writes a string to the console. * * ``` * log("Hello, World") * ``` * **/ const toText = (value) => { if (typeof value === 'object') { return JSON.stringify(value); } else { return String(value); } }; export const log = (value, level) => { const text = toText(value); const log = { text, level }; const hash = computeHash(log); emit({ log, hash }); return sysLog({ op: 'text', text, level }); }; export const logOp = (shape, op) => { const text = String(op(shape)); const level = 'serious'; const log = { text, level }; const hash = computeHash(log); emit({ log, hash }); return sysLog({ op: 'text', text }); }; const logMethod = function (op = (shape) => JSON.stringify(shape)) { logOp(Shape.fromGeometry(realize(this.toGeometry())), op); return this; }; Shape.prototype.log = logMethod; export default log;
closer2/chrome-ec
test/kb_8042.c
/* Copyright 2013 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * * Tests for keyboard MKBP protocol */ #include "common.h" #include "console.h" #include "ec_commands.h" #include "gpio.h" #include "i8042_protocol.h" #include "keyboard_8042.h" #include "keyboard_protocol.h" #include "keyboard_scan.h" #include "lpc.h" #include "power_button.h" #include "system.h" #include "test_util.h" #include "timer.h" #include "util.h" static const char *action[2] = {"release", "press"}; #define BUF_SIZE 16 static char lpc_char_buf[BUF_SIZE]; static unsigned int lpc_char_cnt; /*****************************************************************************/ /* Mock functions */ int lid_is_open(void) { return 1; } void lpc_keyboard_put_char(uint8_t chr, int send_irq) { lpc_char_buf[lpc_char_cnt++] = chr; } /*****************************************************************************/ /* Test utilities */ static void press_key(int c, int r, int pressed) { ccprintf("Input %s (%d, %d)\n", action[pressed], c, r); keyboard_state_changed(r, c, pressed); } static void enable_keystroke(int enabled) { uint8_t data = enabled ? I8042_CMD_ENABLE : I8042_CMD_RESET_DIS; keyboard_host_write(data, 0); msleep(30); } static void reset_8042(void) { keyboard_host_write(I8042_CMD_RESET_DEF, 0); msleep(30); } static void set_typematic(uint8_t val) { keyboard_host_write(I8042_CMD_SETREP, 0); msleep(30); keyboard_host_write(val, 0); msleep(30); } static void set_scancode(uint8_t s) { keyboard_host_write(I8042_CMD_SSCANSET, 0); msleep(30); keyboard_host_write(s, 0); msleep(30); } static void write_cmd_byte(uint8_t val) { keyboard_host_write(I8042_WRITE_CMD_BYTE, 1); msleep(30); keyboard_host_write(val, 0); msleep(30); } static uint8_t read_cmd_byte(void) { lpc_char_cnt = 0; keyboard_host_write(I8042_READ_CMD_BYTE, 1); msleep(30); return lpc_char_buf[0]; } static int __verify_lpc_char(char *arr, unsigned int sz, int delay_ms) { int i; lpc_char_cnt = 0; for (i = 0; i < sz; ++i) lpc_char_buf[i] = 0; msleep(delay_ms); TEST_ASSERT_ARRAY_EQ(arr, lpc_char_buf, sz); return EC_SUCCESS; } #define VERIFY_LPC_CHAR(s) \ TEST_ASSERT(__verify_lpc_char(s, strlen(s), 30) == EC_SUCCESS) #define VERIFY_LPC_CHAR_DELAY(s, t) \ TEST_ASSERT(__verify_lpc_char(s, strlen(s), t) == EC_SUCCESS) static int __verify_no_char(void) { lpc_char_cnt = 0; msleep(30); TEST_CHECK(lpc_char_cnt == 0); } #define VERIFY_NO_CHAR() TEST_ASSERT(__verify_no_char() == EC_SUCCESS) /*****************************************************************************/ /* Tests */ static int test_single_key_press(void) { enable_keystroke(1); press_key(1, 1, 1); VERIFY_LPC_CHAR("\x01"); press_key(1, 1, 0); VERIFY_LPC_CHAR("\x81"); press_key(12, 6, 1); VERIFY_LPC_CHAR("\xe0\x4d"); press_key(12, 6, 0); VERIFY_LPC_CHAR("\xe0\xcd"); return EC_SUCCESS; } static int test_disable_keystroke(void) { enable_keystroke(0); press_key(1, 1, 1); VERIFY_NO_CHAR(); press_key(1, 1, 0); VERIFY_NO_CHAR(); return EC_SUCCESS; } static int test_typematic(void) { enable_keystroke(1); /* * 250ms delay, 8 chars / sec. */ set_typematic(0xf); press_key(1, 1, 1); VERIFY_LPC_CHAR_DELAY("\x01\x01\x01\x01\x01", 650); press_key(1, 1, 0); VERIFY_LPC_CHAR_DELAY("\x81", 300); /* * 500ms delay, 10.9 chars / sec. */ reset_8042(); press_key(1, 1, 1); VERIFY_LPC_CHAR_DELAY("\x01\x01\x01", 650); press_key(1, 1, 0); VERIFY_LPC_CHAR_DELAY("\x81", 200); return EC_SUCCESS; } static int test_scancode_set2(void) { set_scancode(2); write_cmd_byte(read_cmd_byte() | I8042_XLATE); press_key(1, 1, 1); VERIFY_LPC_CHAR("\x01"); press_key(1, 1, 0); VERIFY_LPC_CHAR("\x81"); write_cmd_byte(read_cmd_byte() & ~I8042_XLATE); press_key(1, 1, 1); VERIFY_LPC_CHAR("\x76"); press_key(1, 1, 0); VERIFY_LPC_CHAR("\xf0\x76"); return EC_SUCCESS; } static int test_power_button(void) { gpio_set_level(GPIO_POWER_BUTTON_L, 1); set_scancode(1); test_chipset_on(); gpio_set_level(GPIO_POWER_BUTTON_L, 0); VERIFY_LPC_CHAR_DELAY("\xe0\x5e", 100); gpio_set_level(GPIO_POWER_BUTTON_L, 1); VERIFY_LPC_CHAR_DELAY("\xe0\xde", 100); set_scancode(2); write_cmd_byte(read_cmd_byte() & ~I8042_XLATE); gpio_set_level(GPIO_POWER_BUTTON_L, 0); VERIFY_LPC_CHAR_DELAY("\xe0\x37", 100); gpio_set_level(GPIO_POWER_BUTTON_L, 1); VERIFY_LPC_CHAR_DELAY("\xe0\xf0\x37", 100); test_chipset_off(); gpio_set_level(GPIO_POWER_BUTTON_L, 0); VERIFY_NO_CHAR(); gpio_set_level(GPIO_POWER_BUTTON_L, 1); VERIFY_NO_CHAR(); return EC_SUCCESS; } static int test_sysjump(void) { set_scancode(2); enable_keystroke(1); system_run_image_copy(EC_IMAGE_RW); /* Shouldn't reach here */ return EC_ERROR_UNKNOWN; } static int test_sysjump_cont(void) { write_cmd_byte(read_cmd_byte() | I8042_XLATE); press_key(1, 1, 1); VERIFY_LPC_CHAR("\x01"); press_key(1, 1, 0); VERIFY_LPC_CHAR("\x81"); write_cmd_byte(read_cmd_byte() & ~I8042_XLATE); press_key(1, 1, 1); VERIFY_LPC_CHAR("\x76"); press_key(1, 1, 0); VERIFY_LPC_CHAR("\xf0\x76"); return EC_SUCCESS; } static const struct ec_response_keybd_config keybd_config = { .num_top_row_keys = 13, .action_keys = { TK_BACK, /* T1 */ TK_REFRESH, /* T2 */ TK_FULLSCREEN, /* T3 */ TK_OVERVIEW, /* T4 */ TK_SNAPSHOT, /* T5 */ TK_BRIGHTNESS_DOWN, /* T6 */ TK_BRIGHTNESS_UP, /* T7 */ TK_KBD_BKLIGHT_DOWN, /* T8 */ TK_KBD_BKLIGHT_UP, /* T9 */ TK_PLAY_PAUSE, /* T10 */ TK_VOL_MUTE, /* T11 */ TK_VOL_DOWN, /* T12 */ TK_VOL_UP, /* T13 */ }, }; __override const struct ec_response_keybd_config *board_vivaldi_keybd_config(void) { return &keybd_config; } static int test_ec_cmd_get_keybd_config(void) { struct ec_response_keybd_config resp; int rv; rv = test_send_host_command(EC_CMD_GET_KEYBD_CONFIG, 0, NULL, 0, &resp, sizeof(resp)); if (rv != EC_RES_SUCCESS) { ccprintf("Error: EC_CMD_GET_KEYBD_CONFIG cmd returns %d\n", rv); return EC_ERROR_INVAL; } if (memcmp(&resp, &keybd_config, sizeof(resp))) { ccprintf("Error: EC_CMD_GET_KEYBD_CONFIG returned bad cfg\n"); return EC_ERROR_INVAL; } ccprintf("EC_CMD_GET_KEYBD_CONFIG response is good\n"); return EC_SUCCESS; } static int test_vivaldi_top_keys(void) { set_scancode(2); /* Test REFRESH key */ write_cmd_byte(read_cmd_byte() | I8042_XLATE); press_key(2, 3, 1); /* Press T2 */ VERIFY_LPC_CHAR("\xe0\x67"); /* Check REFRESH scancode in set-1 */ /* Test SNAPSHOT key */ write_cmd_byte(read_cmd_byte() | I8042_XLATE); press_key(4, 3, 1); /* Press T2 */ VERIFY_LPC_CHAR("\xe0\x13"); /* Check SNAPSHOT scancode in set-1 */ /* Test VOL_UP key */ write_cmd_byte(read_cmd_byte() | I8042_XLATE); press_key(5, 3, 1); /* Press T2 */ VERIFY_LPC_CHAR("\xe0\x30"); /* Check VOL_UP scancode in set-1 */ return EC_SUCCESS; } void run_test(int argc, char **argv) { test_reset(); wait_for_task_started(); if (system_get_image_copy() == EC_IMAGE_RO) { RUN_TEST(test_single_key_press); RUN_TEST(test_disable_keystroke); RUN_TEST(test_typematic); RUN_TEST(test_scancode_set2); RUN_TEST(test_power_button); RUN_TEST(test_ec_cmd_get_keybd_config); RUN_TEST(test_vivaldi_top_keys); RUN_TEST(test_sysjump); } else { RUN_TEST(test_sysjump_cont); } test_print_result(); }
Amourspirit/ooo_uno_tmpl
ooobuild/cssdyn/bridge/oleautomation/__init__.py
<reponame>Amourspirit/ooo_uno_tmpl # coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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. # from ....dyn.bridge.oleautomation.application_registration import ApplicationRegistration as ApplicationRegistration from ....dyn.bridge.oleautomation.bridge_supplier import BridgeSupplier as BridgeSupplier from ....dyn.bridge.oleautomation.currency import Currency as Currency from ....dyn.bridge.oleautomation.date import Date as Date from ....dyn.bridge.oleautomation.decimal import Decimal as Decimal from ....dyn.bridge.oleautomation.factory import Factory as Factory from ....dyn.bridge.oleautomation.named_argument import NamedArgument as NamedArgument from ....dyn.bridge.oleautomation.property_put_argument import PropertyPutArgument as PropertyPutArgument from ....dyn.bridge.oleautomation.s_code import SCode as SCode from ....dyn.bridge.oleautomation.x_automation_object import XAutomationObject as XAutomationObject
JesusGranizo/oda
oda-datastreams/deviceinfofx30/src/test/java/es/amplia/oda/datastreams/deviceinfofx30/DeviceInfoFX30Test.java
<gh_stars>1-10 package es.amplia.oda.datastreams.deviceinfofx30; import es.amplia.oda.core.commons.entities.Software; import es.amplia.oda.core.commons.utils.CommandExecutionException; import es.amplia.oda.core.commons.utils.CommandProcessor; import es.amplia.oda.datastreams.deviceinfofx30.configuration.DeviceInfoFX30Configuration; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.internal.util.reflection.Whitebox; import org.osgi.framework.Bundle; import org.osgi.framework.Version; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.File; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.whenNew; @RunWith(PowerMockRunner.class) @PrepareForTest(DeviceInfoFX30.class) public class DeviceInfoFX30Test { private DeviceInfoFX30 deviceInfo; private Bundle[] bundles; private DeviceInfoFX30Configuration configuration; @Mock private CommandProcessor mockedCommandProcessor; @Mock private CommandExecutionException mockedCommandExecutionException; @Mock private Bundle mockedBundle; @Mock private File mockedFile; @Before public void beforeTests() { bundles = new Bundle[0]; configuration = new DeviceInfoFX30Configuration("deviceId", "apiKey", "source", "path"); deviceInfo = new DeviceInfoFX30(null, bundles); } @Test public void testLoadConfiguration() throws Exception { bundles = new Bundle[1]; bundles[0] = mockedBundle; Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "bundles", bundles); whenNew(File.class).withAnyArguments().thenReturn(mockedFile); when(mockedBundle.getSymbolicName()).thenReturn("MyName"); when(mockedBundle.getVersion()).thenReturn(new Version("1")); when(mockedFile.listFiles()).thenReturn(new File[0]); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.SERIAL_NUMBER_SCRIPT)).thenReturn("serialNumber"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.MODEL_SCRIPT)).thenReturn("model"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.IMEI_SCRIPT)).thenReturn("imei"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.IMSI_SCRIPT)).thenReturn("imsi"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.ICC_SCRIPT)).thenReturn("icc"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.RSSI_SCRIPT)).thenReturn("rssi"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.SOFTWARE_SCRIPT)).thenReturn(" : && Firmware Version:v"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.APN_SCRIPT)).thenReturn("apn"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.CPU_TOTAL_SCRIPT)).thenReturn("1000"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.RAM_TOTAL_SCRIPT)).thenReturn("2000"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.DISK_TOTAL_SCRIPT)).thenReturn("4000"); deviceInfo.loadConfiguration(configuration); assertEquals("deviceId", deviceInfo.getDeviceId()); assertEquals("apiKey", deviceInfo.getApiKey()); assertEquals("path", deviceInfo.getPath()); assertEquals("serialNumber", deviceInfo.getSerialNumber()); assertEquals("model", deviceInfo.getModel()); assertEquals("imei", deviceInfo.getImei()); assertEquals("imsi", deviceInfo.getImsi()); assertEquals("icc", deviceInfo.getIcc()); assertEquals("rssi", deviceInfo.getRssi()); List<Software> list = new ArrayList<>(); list.add(new Software(" "," ","SOFTWARE")); list.add(new Software("Firmware Version","v","FIRMWARE")); list.add(new Software("MyName","1.0.0","SOFTWARE")); assertEquals(list, deviceInfo.getSoftware()); assertEquals("apn", deviceInfo.getApn()); assertEquals(1000L, deviceInfo.getCpuTotal()); assertEquals(2000L, deviceInfo.getRamTotal()); assertEquals(4000L, deviceInfo.getDiskTotal()); } @Test public void testLoadConfigurationException() throws Exception { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "bundles", bundles); when(mockedCommandProcessor.execute(any())).thenThrow(mockedCommandExecutionException); whenNew(File.class).withAnyArguments().thenReturn(mockedFile); when(mockedFile.listFiles()).thenReturn(new File[0]); deviceInfo.loadConfiguration(configuration); assertNull(deviceInfo.getSerialNumber()); assertNull(deviceInfo.getModel()); assertNull(deviceInfo.getImei()); assertNull(deviceInfo.getImsi()); assertNull(deviceInfo.getIcc()); assertNull(deviceInfo.getRssi()); assertNull(deviceInfo.getSoftware()); assertNull(deviceInfo.getApn()); assertEquals(0, deviceInfo.getCpuTotal()); assertEquals(0, deviceInfo.getRamTotal()); assertEquals(0, deviceInfo.getDiskTotal()); } @Test public void testGetClock() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.CLOCK_SCRIPT)).thenReturn("clock"); String clock = deviceInfo.getClock(); assertEquals("clock", clock); } @Test public void testGetClockException() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.CLOCK_SCRIPT)).thenThrow(mockedCommandExecutionException); String clock = deviceInfo.getClock(); assertNull(clock); } @Test public void testGetUptime() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.UPTIME_SCRIPT)).thenReturn("200"); long uptime = deviceInfo.getUptime(); assertEquals(200, uptime); } @Test public void testGetUptimeException() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.UPTIME_SCRIPT)).thenThrow(mockedCommandExecutionException); long uptime = deviceInfo.getUptime(); assertEquals(0, uptime); } @Test public void testGetTemperatureValue() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.TEMPERATURE_VALUE_SCRIPT)).thenReturn("42"); int temperatureValue = deviceInfo.getTemperatureValue(); assertEquals(42, temperatureValue); } @Test public void testGetTemperatureValueException() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.TEMPERATURE_VALUE_SCRIPT)).thenThrow(mockedCommandExecutionException); int temperatureValue = deviceInfo.getTemperatureValue(); assertEquals(0, temperatureValue); } @Test public void testGetTemperatureStatus() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.TEMPERATURE_STATUS_SCRIPT)).thenReturn("OK"); String temperatureStatus = deviceInfo.getTemperatureStatus(); assertEquals("OK", temperatureStatus); } @Test public void testGetTemperatureStatusException() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.TEMPERATURE_STATUS_SCRIPT)).thenThrow(mockedCommandExecutionException); String temperatureStatus = deviceInfo.getTemperatureStatus(); assertNull(temperatureStatus); } @Test public void testGetCpuStatus() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.CPU_STATUS_SCRIPT)).thenReturn("OK"); String cpu = deviceInfo.getCpuStatus(); assertEquals("OK", cpu); } @Test public void testGetCpuStatusException() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.CPU_STATUS_SCRIPT)).thenThrow(mockedCommandExecutionException); String cpu = deviceInfo.getCpuStatus(); assertNull(cpu); } @Test public void testGetCpuUsage() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.CPU_USAGE_SCRIPT)).thenReturn("42"); int cpuUsage = deviceInfo.getCpuUsage(); assertEquals(42, cpuUsage); } @Test public void testGetCpuUsageException() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.CPU_USAGE_SCRIPT)).thenThrow(mockedCommandExecutionException); int cpuUsage = deviceInfo.getCpuUsage(); assertEquals(0, cpuUsage); } @Test public void testGetRamUsage() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.RAM_USAGE_SCRIPT)).thenReturn("42"); int ramUsage = deviceInfo.getRamUsage(); assertEquals(42, ramUsage); } @Test public void testGetRamUsageException() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.RAM_USAGE_SCRIPT)).thenThrow(mockedCommandExecutionException); int ramUsage = deviceInfo.getRamUsage(); assertEquals(0, ramUsage); } @Test public void testGetDiskUsage() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.DISK_USAGE_SCRIPT)).thenReturn("42"); int diskUsage = deviceInfo.getDiskUsage(); assertEquals(42, diskUsage); } @Test public void testGetDiskUsageException() throws CommandExecutionException { Whitebox.setInternalState(deviceInfo, "commandProcessor", mockedCommandProcessor); Whitebox.setInternalState(deviceInfo, "path", "path"); when(mockedCommandProcessor.execute("path/" + DeviceInfoFX30.DISK_USAGE_SCRIPT)).thenThrow(mockedCommandExecutionException); int diskUsage = deviceInfo.getDiskUsage(); assertEquals(0, diskUsage); } }
GeekerClub/thirdparty
lzo/lzo1f.h
#include "thirdparty/lzo-2.07/include/lzo/lzo1f.h"
github641/testRepo
CAGradientLayer/maskViewDemo-master/MaskViewDemo/ViewControllerDemoFour.h
// // ViewControllerDemoFour.h // MaskViewDemo // // Created by iOS_Developer on 16/2/25. // Copyright © 2016年 CoderJee. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewControllerDemoFour : UIViewController @end
KarrynS/Mend
client/src/components/Patients/ManagementPlan.js
<reponame>KarrynS/Mend import React, {useState} from 'react'; import API from '../../utils/API'; import "./treatmentplan.css" const ManagementPlan = (props) => { console.log("patient props", props.patient, props.patient._id) const [patientId, setPatientId] = useState(props.patient._id); const [formObject, setformObject] = useState({ diagnosis: "", treatment: "", review: "", patientId: patientId }) function handleInputChange(event) { const {name,value} = event.target; setformObject({ ...formObject, [name]: value }) } const handleFormSubmit = (e) => { e.preventDefault(); console.log("management plan", formObject) API.newManagement( { diagnosis: formObject.diagnosis, treatment: formObject.treatment, review: formObject.review, patient: patientId } ) .then(() => { setformObject({ diagnosis: "", treatment: "", review: "", patient: "" }) }) .catch(err => console.log(err)) console.log("New Management added", formObject) console.log("patientId" ,patientId) alert("Treatment plan recorded") } // const submitPlanModal = () => { // return ( // <> // <div className="modal" id="exampleModal" tabindex="-1" role="dialog"> // <div className="modal-dialog" role="document"> // <div className="modal-content"> // <div className="modal-header"> // <h5 className="modal-title">//Optom Name here//</h5> // <button type="button" className="close" data-dismiss="modal" aria-label="Close"> // <span aria-hidden="true">&times;</span> // </button> // </div> // <div className="modal-body"> // <p>We have submitted your plan which {props.patient.name} will now be able to view</p> // </div> // <div className="modal-footer"> // <button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button> // </div> // </div> // </div> // </div> // </> // ) // } // onClick={submitPlanModal()} return ( <> <div className="treatmentDiv"> <h1>Management Plan</h1> <form onSubmit={handleFormSubmit} > <div className="form-group row"> <label htmlFor="Diagnosis" className="col-sm-2 col-form-label">Diagnosis:</label> <div className="col-sm-10"> <input onChange={handleInputChange} value={formObject.diagnosis} name="diagnosis" type="text" className="form-control" id="inputdiagnosis" placeholder="Enter Diagnosis"/> </div> </div> <div className="form-group row"> <label htmlFor="Management" className="col-sm-2 col-form-label">Treatment:</label> <div className="col-sm-10"> <textarea onChange={handleInputChange} value={formObject.treatment} name="treatment" type="text" row="3" className="form-control" id="inputmanagement" placeholder="Enter Management Plan"></textarea> </div> </div> <div className="form-group row"> <label htmlFor="example-date-input" className="col-2 col-form-label">Review Date:</label> <div className="col-sm-10"> <input onChange={handleInputChange} value={formObject.review}name="review" type="text" className="form-control" id="inputreview" placeholder="Suggested review schedule"/> </div> </div> <div className="form-group row"> <div className="col-sm-10"> <button type="submit button" className="btn btn-primary mxplanBtn" data-toggle="modal" data-target="#exampleModal">Submit Plan</button> </div> </div> </form> </div> </> ) } export default ManagementPlan;
hackerlank/SourceCode
Game/Client/CEGUI/CEGUI/src/CEGUIString.cpp
<filename>Game/Client/CEGUI/CEGUI/src/CEGUIString.cpp /************************************************************************ filename: CEGUIString.cpp created: 26/2/2004 author: <NAME> purpose: Implements string class *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://www.cegui.org.uk) Copyright (C)2004 - 2005 <NAME> (<EMAIL>) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #include "CEGUIString.h" #include <iostream> // Start of CEGUI namespace section namespace CEGUI { // definition of 'no position' value const String::size_type String::npos = (String::size_type)(-1); ////////////////////////////////////////////////////////////////////////// // Destructor ////////////////////////////////////////////////////////////////////////// String::~String(void) { if (d_reserve > STR_QUICKBUFF_SIZE) { delete[] d_buffer; } if (d_encodedbufflen > 0) { delete[] d_encodedbuff; } } bool String::grow(size_type new_size) { // check for too big if (max_size() <= new_size) std::length_error("Resulting CEGUI::String would be too big"); // increase, as we always null-terminate the buffer. ++new_size; if (new_size > d_reserve) { utf32* temp = new utf32[new_size]; if (d_reserve > STR_QUICKBUFF_SIZE) { memcpy(temp, d_buffer, (d_cplength + 1) * sizeof(utf32)); delete[] d_buffer; } else { memcpy(temp, d_quickbuff, (d_cplength + 1) * sizeof(utf32)); } d_buffer = temp; d_reserve = new_size; return true; } return false; } // perform re-allocation to remove wasted space. void String::trim(void) { size_type min_size = d_cplength + 1; // only re-allocate when not using quick-buffer, and when size can be trimmed if ((d_reserve > STR_QUICKBUFF_SIZE) && (d_reserve > min_size)) { // see if we can trim to quick-buffer if (min_size <= STR_QUICKBUFF_SIZE) { memcpy(d_quickbuff, d_buffer, min_size * sizeof(utf32)); delete[] d_buffer; d_reserve = STR_QUICKBUFF_SIZE; } // re-allocate buffer else { utf32* temp = new utf32[min_size]; memcpy(temp, d_buffer, min_size * sizeof(utf32)); delete[] d_buffer; d_buffer = temp; d_reserve = min_size; } } } // build an internal buffer with the string encoded as utf8 (remains valid until string is modified). utf8* String::build_utf8_buff(void) const { size_type buffsize = encoded_size(ptr(), d_cplength) + 1; if (buffsize > d_encodedbufflen) { if (d_encodedbufflen > 0) { delete[] d_encodedbuff; } d_encodedbuff = new utf8[buffsize]; d_encodedbufflen = buffsize; } encode(ptr(), d_encodedbuff, buffsize, d_cplength); // always add a null at end d_encodedbuff[buffsize-1] = ((utf8)0); d_encodeddatlen = buffsize; return d_encodedbuff; } ////////////////////////////////////////////////////////////////////////// // Comparison operators ////////////////////////////////////////////////////////////////////////// bool operator==(const String& str1, const String& str2) { return (str1.compare(str2) == 0); } bool operator==(const String& str, const std::string& std_str) { return (str.compare(std_str) == 0); } bool operator==(const std::string& std_str, const String& str) { return (str.compare(std_str) == 0); } bool operator==(const String& str, const utf8* utf8_str) { return (str.compare(utf8_str) == 0); } bool operator==(const utf8* utf8_str, const String& str) { return (str.compare(utf8_str) == 0); } bool operator!=(const String& str1, const String& str2) { return (str1.compare(str2) != 0); } bool operator!=(const String& str, const std::string& std_str) { return (str.compare(std_str) != 0); } bool operator!=(const std::string& std_str, const String& str) { return (str.compare(std_str) != 0); } bool operator!=(const String& str, const utf8* utf8_str) { return (str.compare(utf8_str) != 0); } bool operator!=(const utf8* utf8_str, const String& str) { return (str.compare(utf8_str) != 0); } bool operator<(const String& str1, const String& str2) { return (str1.compare(str2) < 0); } bool operator<(const String& str, const std::string& std_str) { return (str.compare(std_str) < 0); } bool operator<(const std::string& std_str, const String& str) { return (str.compare(std_str) >= 0); } bool operator<(const String& str, const utf8* utf8_str) { return (str.compare(utf8_str) < 0); } bool operator<(const utf8* utf8_str, const String& str) { return (str.compare(utf8_str) >= 0); } bool operator>(const String& str1, const String& str2) { return (str1.compare(str2) > 0); } bool operator>(const String& str, const std::string& std_str) { return (str.compare(std_str) > 0); } bool operator>(const std::string& std_str, const String& str) { return (str.compare(std_str) <= 0); } bool operator>(const String& str, const utf8* utf8_str) { return (str.compare(utf8_str) > 0); } bool operator>(const utf8* utf8_str, const String& str) { return (str.compare(utf8_str) <= 0); } bool operator<=(const String& str1, const String& str2) { return (str1.compare(str2) <= 0); } bool operator<=(const String& str, const std::string& std_str) { return (str.compare(std_str) <= 0); } bool operator<=(const std::string& std_str, const String& str) { return (str.compare(std_str) >= 0); } bool operator<=(const String& str, const utf8* utf8_str) { return (str.compare(utf8_str) <= 0); } bool operator<=(const utf8* utf8_str, const String& str) { return (str.compare(utf8_str) >= 0); } bool operator>=(const String& str1, const String& str2) { return (str1.compare(str2) >= 0); } bool operator>=(const String& str, const std::string& std_str) { return (str.compare(std_str) >= 0); } bool operator>=(const std::string& std_str, const String& str) { return (str.compare(std_str) <= 0); } bool operator>=(const String& str, const utf8* utf8_str) { return (str.compare(utf8_str) >= 0); } bool operator>=(const utf8* utf8_str, const String& str) { return (str.compare(utf8_str) <= 0); } ////////////////////////////////////////////////////////////////////////// // c-string operators ////////////////////////////////////////////////////////////////////////// bool operator==(const String& str, const char* c_str) { return (str.compare(c_str) == 0); } bool operator==(const char* c_str, const String& str) { return (str.compare(c_str) == 0); } bool operator!=(const String& str, const char* c_str) { return (str.compare(c_str) != 0); } bool operator!=(const char* c_str, const String& str) { return (str.compare(c_str) != 0); } bool operator<(const String& str, const char* c_str) { return (str.compare(c_str) < 0); } bool operator<(const char* c_str, const String& str) { return (str.compare(c_str) >= 0); } bool operator>(const String& str, const char* c_str) { return (str.compare(c_str) > 0); } bool operator>(const char* c_str, const String& str) { return (str.compare(c_str) <= 0); } bool operator<=(const String& str, const char* c_str) { return (str.compare(c_str) <= 0); } bool operator<=(const char* c_str, const String& str) { return (str.compare(c_str) >= 0); } bool operator>=(const String& str, const char* c_str) { return (str.compare(c_str) >= 0); } bool operator>=(const char* c_str, const String& str) { return (str.compare(c_str) <= 0); } ////////////////////////////////////////////////////////////////////////// // Concatenation operator functions ////////////////////////////////////////////////////////////////////////// String operator+(const String& str1, const String& str2) { String temp(str1); temp.append(str2); return temp; } String operator+(const String& str, const std::string& std_str) { String temp(str); temp.append(std_str); return temp; } String operator+(const std::string& std_str, const String& str) { String temp(std_str); temp.append(str); return temp; } String operator+(const String& str, const utf8* utf8_str) { String temp(str); temp.append(utf8_str); return temp; } String operator+(const utf8* utf8_str, const String& str) { String temp(utf8_str); temp.append(str); return temp; } String operator+(const String& str, utf32 code_point) { String temp(str); temp.append(1, code_point); return temp; } String operator+(utf32 code_point, const String& str) { String temp(1, code_point); temp.append(str); return temp; } String operator+(const String& str, const char* c_str) { String tmp(str); tmp.append(c_str); return tmp; } String operator+(const char* c_str, const String& str) { String tmp(c_str); tmp.append(str); return tmp; } ////////////////////////////////////////////////////////////////////////// // Output (stream) functions ////////////////////////////////////////////////////////////////////////// std::ostream& operator<<(std::ostream& s, const String& str) { return s << str.c_str(); } ////////////////////////////////////////////////////////////////////////// // Modifying operations ////////////////////////////////////////////////////////////////////////// // swap the contents of str1 and str2 void swap(String& str1, String& str2) { str1.swap(str2); } } // End of CEGUI namespace section
RIPboilerplates/RIP-web
internals/scripts/helpers/xmark.js
const chalk = require('chalk') const print = require('./print') /** * Adds mark cross symbol */ function addXMark(callback) { print(chalk.red(' ✘')) if (callback) callback() } module.exports = addXMark
batosai/Tetra
packages/admin/resources/assets/javascripts/components/datepicker.js
<reponame>batosai/Tetra import bulmaCalendar from 'bulma-calendar' import 'bulma-calendar/dist/css/bulma-calendar.min.css' export default class Datepicker { constructor() { this.format = { fr: 'DD/MM/YYYY', en: 'YYYY-MM-DD', } this.init() } init() { const lang = document.querySelector('html').getAttribute('lang') bulmaCalendar.attach('[type="date"]', { lang, startDate: new Date(), dateFormat: this.format[lang], showFooter: false, displayMode: 'dialog', }) } }
biggerwang/geequery
orm-test/src/test/java/jef/database/covertformdb/UserTest.java
<reponame>biggerwang/geequery<filename>orm-test/src/test/java/jef/database/covertformdb/UserTest.java package jef.database.covertformdb; import java.sql.SQLException; import org.easyframe.enterprise.spring.CommonDao; import org.easyframe.enterprise.spring.CommonDaoImpl; import org.junit.Ignore; import org.junit.Test; import jef.database.DbClient; import jef.database.DbClientBuilder; public class UserTest { @Test @Ignore public void test() throws SQLException { DbClient db = new DbClientBuilder("jdbc:postgresql://pc-jiyi:5432/test","root","admin").build(); CommonDao dao=new CommonDaoImpl(db); db.refreshTable(User.class); db.dropTable(User.class); db.createTable(User.class); User user = new User(); user.setUsername("spling Test"); user.setFullname("12345"); user.setPassword("<PASSWORD>"); user.setFullname("dsdsds"); try { db.insert(user); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } User loaded=db.load(user); loaded.setEmail("<EMAIL>"); db.update(loaded); db.delete(loaded); } }
skratchdot/audio-editor
src/app/reducers/playbackPosition.js
import * as types from '../constants/ActionTypes'; export default function (state = { position: 0, source: null }, action) { switch (action.type) { case types.SET_PLAYBACK_POSITION: let position = parseFloat(action.position); position = Number.isFinite(position) ? position : 0; return Object.assign({}, state, { position: position, source: action.source }); default: return state; } }
Mhh123/spider
day08/shibie.py
<reponame>Mhh123/spider import pytesseract from PIL import Image def sb(image): # 打开图片 img = Image.open(image) # 将图片转化为灰度图片 img = img.convert('L') # 二值化处理 threshold = 140 table = [] for i in range(256): if i < threshold: table.append(0) else: table.append(1) out = img.point(table, '1') img = img.convert('RGB') return pytesseract.image_to_string(img)
luglio/hpx5
libhpx/actions/exit.h
// ============================================================================= // High Performance ParalleX Library (libhpx) // // Copyright (c) 2013-2017, Trustees of Indiana University, // All rights reserved. // // This software may be modified and distributed under the terms of the BSD // license. See the COPYING file for details. // // This software was created at the Indiana University Center for Research in // Extreme Scale Technologies (CREST). // ============================================================================= #ifndef LIBHPX_ACTION_EXIT_H #define LIBHPX_ACTION_EXIT_H /// @file libhpx/action/exit.h /// /// Declare two exit handlers that are used in the parcel management vtables. /// Forward declare the parcel to avoid including hpx.h here. /// @{ struct hpx_parcel; /// @} void exit_action(const void *obj, struct hpx_parcel *p); void exit_pinned_action(const void *obj, struct hpx_parcel *p); #endif // LIBHPX_ACTION_EXIT_H
xiaoazhe/Ferryman-cloud
ferry-core/src/main/java/com/ferry/core/file/entity/bean/FileConditionVO.java
package com.ferry.core.file.entity.bean; import com.ferry.core.file.object.BaseConditionVO; import lombok.Data; import lombok.EqualsAndHashCode; /** * @author innodev java team * @version 1.0 * @date 2018/12/14 09:23 * @since 1.8 */ @Data @EqualsAndHashCode(callSuper = false) public class FileConditionVO extends BaseConditionVO { }
Markus-Schwer/quarkus
extensions/smallrye-jwt/deployment/src/test/java/io/quarkus/jwt/test/TestConfigSource.java
package io.quarkus.jwt.test; import java.io.IOException; import java.util.Set; import org.eclipse.microprofile.config.spi.ConfigSource; import io.smallrye.jwt.util.KeyUtils; public class TestConfigSource implements ConfigSource { @Override public Set<String> getPropertyNames() { return Set.of("sign-key", "encrypt-key"); } @Override public String getValue(String propertyName) { if ("sign-key".equals(propertyName)) { return readKeyContent("/privateKey.pem"); } else if ("encrypt-key".equals(propertyName)) { return readKeyContent("/publicKey.pem"); } else { return null; } } private String readKeyContent(String keyLocation) { try { return KeyUtils.readKeyContent(keyLocation); } catch (IOException ex) { throw new RuntimeException(ex); } } @Override public String getName() { return "jwt"; } }
ifrguy/NHWG-MIMS
src/MbrAddresses-index.js
<filename>src/MbrAddresses-index.js db = db.getSiblingDB( "NHWG" ); db.MbrAddresses.createIndex( { CAPID : 1 } );
ctrlpz/SOMns
src/tools/dym/nodes/AllocationProfilingNode.java
package tools.dym.nodes; import som.vmobjects.SObjectWithClass; import tools.dym.profiles.AllocationProfile; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.instrumentation.ExecutionEventNode; public class AllocationProfilingNode extends ExecutionEventNode { protected final AllocationProfile profile; public AllocationProfilingNode(final AllocationProfile profile) { this.profile = profile; } @Override protected void onEnter(final VirtualFrame frame) { profile.inc(); } @Override protected void onReturnValue(final VirtualFrame frame, final Object result) { assert result instanceof SObjectWithClass : "WAT? this should only be tracking SObject allocations"; profile.recordResult((SObjectWithClass) result); } }
mohnbroetchen2/cykel_jenarad
bikesharing/migrations/0023_auto_20200326_1857.py
<reponame>mohnbroetchen2/cykel_jenarad # Generated by Django 2.2.4 on 2020-03-26 17:57 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("bikesharing", "0022_auto_20200326_1845"), ] operations = [ migrations.RenameField( model_name="location", old_name="internal_location", new_name="internal", ), ]
anicloud/captain
captain/src/main/java/com/ani/captain/infrastructure/persistence/repository/AccountDeviceJpaRepository.java
package com.ani.captain.infrastructure.persistence.repository; import com.ani.captain.domain.model.AccountDevice; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; /** * Created by huangbin on 8/24/16. */ public interface AccountDeviceJpaRepository extends CrudRepository<AccountDevice, Long> { @Query(value = "select a from AccountDevice a where a.accountId = ?1") AccountDevice findByAccountId(long accountId); @Query(value = "select a from AccountDevice a where a.vendor = ?1") AccountDevice findByVendor(String vendor); }
Gitman1989/chromium
chrome/browser/ui/cocoa/hover_close_button.h
<reponame>Gitman1989/chromium // Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Cocoa/Cocoa.h> #include "base/scoped_nsobject.h" #include "chrome/browser/ui/cocoa/hover_button.h" // The standard close button for our Mac UI which is the "x" that changes to a // dark circle with the "x" when you hover over it. At this time it is used by // the popup blocker, download bar, info bar and tabs. @interface HoverCloseButton : HoverButton { @private // Bezier path for drawing the 'x' within the button. scoped_nsobject<NSBezierPath> xPath_; // Bezier path for drawing the hover state circle behind the 'x'. scoped_nsobject<NSBezierPath> circlePath_; } // Sets up the button's tracking areas and accessibility info when instantiated // via initWithFrame or awakeFromNib. - (void)commonInit; @end
GuillaumeOj/P13-WOD-Board
backend/wod_board/seed.py
import typing import sqlalchemy.orm from wod_board import config from wod_board import exceptions from wod_board import models from wod_board.models import equipment from wod_board.models import movement from wod_board.models import unit from wod_board.models import user from wod_board.models import w_type def users(db: sqlalchemy.orm.Session) -> None: admin_password = "<PASSWORD>" hashed_admin_password = config.PASSWORD_CTXT.hash(admin_password) db.add( user.User( email="<EMAIL>", username="admin-bar", password=<PASSWORD>, is_admin=True, ) ) user_password = "<PASSWORD>" hashed_user_password = config.PASSWORD_CTXT.hash(user_password) db.add( user.User( email="<EMAIL>", username="foo-bar", password=<PASSWORD>, is_admin=False, ) ) db.commit() def units(db: sqlalchemy.orm.Session) -> None: db.add(unit.Unit(name="Unit", symbol="U")) db.add(unit.Unit(name="Kilogram", symbol="kg")) db.add(unit.Unit(name="Meter", symbol="m")) db.commit() def equipments(db: sqlalchemy.orm.Session) -> None: kilogram: typing.Optional[unit.Unit] = ( db.query(unit.Unit).filter(unit.Unit.name == "Kilogram").first() ) unit_u: typing.Optional[unit.Unit] = ( db.query(unit.Unit).filter(unit.Unit.name == "Unit").first() ) if kilogram is None or unit_u is None: raise exceptions.UnknownUnit db.add(equipment.Equipment(name="Dumbbell", unit_id=kilogram.id)) db.add(equipment.Equipment(name="Kettlebell", unit_id=kilogram.id)) db.add(equipment.Equipment(name="Barbell", unit_id=kilogram.id)) db.add(equipment.Equipment(name="Pull Bar", unit_id=unit_u.id)) db.commit() def movements(db: sqlalchemy.orm.Session) -> None: unit_u: typing.Optional[unit.Unit] = ( db.query(unit.Unit).filter(unit.Unit.name == "Unit").first() ) meter: typing.Optional[unit.Unit] = ( db.query(unit.Unit).filter(unit.Unit.name == "Meter").first() ) if unit_u is None or meter is None: raise exceptions.UnknownUnit dumbbell = ( db.query(equipment.Equipment) .filter(equipment.Equipment.name == "Dumbbell") .first() ) kettlebell = ( db.query(equipment.Equipment) .filter(equipment.Equipment.name == "Kettlebell") .first() ) barebell = ( db.query(equipment.Equipment) .filter(equipment.Equipment.name == "Barbell") .first() ) pull_bar = ( db.query(equipment.Equipment) .filter(equipment.Equipment.name == "Pull Bar") .first() ) db.add( movement.Movement( name="Devil Press", unit_id=unit_u.id, equipments=[dumbbell, kettlebell], ) ) db.add( movement.Movement( name="Dead Lift", unit_id=unit_u.id, equipments=[barebell], ) ) db.add(movement.Movement(name="Pull Up", unit_id=unit_u.id, equipments=[pull_bar])) db.add(movement.Movement(name="Burpees", unit_id=unit_u.id)) db.add(movement.Movement(name="Push Up", unit_id=unit_u.id)) db.add(movement.Movement(name="Run", unit_id=meter.id)) db.commit() def types(db: sqlalchemy.orm.Session) -> None: types = ["AMRAP", "EMOM", "For Time", "For Load", "TABATA"] for wod_type in types: db.add(w_type.WodType(name=wod_type)) db.commit() def seed_db() -> None: models.drop_all() models.create_all() db = models.Session() if config.WOD_BOARD_ENV == "production": return users(db) units(db) equipments(db) movements(db) types(db) if __name__ == "__main__": seed_db()
sola-da/LambdaTester
experiments/some/someGen/test642.js
<filename>experiments/some/someGen/test642.js var callbackArguments = []; var argument1 = function callback(a,b,c) { callbackArguments.push(JSON.stringify(arguments)) argument2['f9zgt4n!ZJR]W'] = {} return a+b+c }; var argument2 = null; var argument3 = false; var argument4 = function callback(a,b,c) { callbackArguments.push(JSON.stringify(arguments)) base_1[1][2] = false base_1[2][5e-324] = 618 argument6[9.551053197482062e+307] = [969,823,714,403,969,595] return a-b/c }; var argument5 = null; var argument6 = null; var argument7 = function callback(a,b,c) { callbackArguments.push(JSON.stringify(arguments)) argument8[618] = 1.770451437088392e+308 argument8 = [5e-324,"P"] argument8[3] = [893,893,157,595,59,0] return a-b+c }; var argument8 = null; var argument9 = null; var argument10 = function callback(a,b,c) { callbackArguments.push(JSON.stringify(arguments)) base_3[7] = {"5":"","242":"x","460":403,"655":1.4226576848728473e+308,"aMg":"","":"","2.2328615197842528e+307":9.181284151471662e+306,"!'":"","1.6784625853029251e+308":""} return a*b*c }; var argument11 = null; var argument12 = false; var base_0 = ["1",242,100,403,618,"c","#d","Ri"] var r_0= undefined try { r_0 = base_0.some(argument1,argument2,argument3) } catch(e) { r_0= "Error" } var base_1 = ["1",242,100,403,618,"c","#d","Ri"] var r_1= undefined try { r_1 = base_1.some(argument4,argument5,argument6) } catch(e) { r_1= "Error" } var base_2 = ["1",242,100,403,618,"c","#d","Ri"] var r_2= undefined try { r_2 = base_2.some(argument7,argument8,argument9) } catch(e) { r_2= "Error" } var base_3 = ["1",242,100,403,618,"c","#d","Ri"] var r_3= undefined try { r_3 = base_3.some(argument10,argument11,argument12) } catch(e) { r_3= "Error" } function serialize(array){ return array.map(function(a){ if (a === null || a == undefined) return a; var name = a.constructor.name; if (name==='Object' || name=='Boolean'|| name=='Array'||name=='Number'||name=='String') return JSON.stringify(a); return name; }); } setTimeout(function(){ require("fs").writeFileSync("./experiments/some/someGen/test642.json",JSON.stringify({"baseObjects":serialize([base_0,base_1,base_2,base_3]),"returnObjects":serialize([r_0,r_1,r_2,r_3]),"callbackArgs":callbackArguments})) },300)
pocketgems/XLE2
RenderCore/AppleMetal/Metal/Format.cpp
// Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "Format.h" #include "IncludeAppleMetal.h" namespace RenderCore { namespace Metal_AppleMetal { MTLPixelFormat AsMTLPixelFormat(RenderCore::Format fmt) { using namespace RenderCore; switch (fmt) { case Format::R32G32B32A32_FLOAT: return MTLPixelFormatRGBA32Float; case Format::R32G32B32A32_UINT: return MTLPixelFormatRGBA32Uint; case Format::R32G32B32A32_SINT: return MTLPixelFormatRGBA32Sint; case Format::R16G16B16A16_FLOAT: return MTLPixelFormatRGBA16Float; case Format::R16G16B16A16_UNORM: return MTLPixelFormatRGBA16Unorm; case Format::R16G16B16A16_UINT: return MTLPixelFormatRGBA16Uint; case Format::R16G16B16A16_SNORM: return MTLPixelFormatRGBA16Snorm; case Format::R16G16B16A16_SINT: return MTLPixelFormatRGBA16Sint; case Format::R32G32_FLOAT: return MTLPixelFormatRG32Float; case Format::R32G32_UINT: return MTLPixelFormatRG32Uint; case Format::R32G32_SINT: return MTLPixelFormatRG32Sint; case Format::R10G10B10A2_UNORM: return MTLPixelFormatRGB10A2Unorm; case Format::R10G10B10A2_UINT: return MTLPixelFormatRGB10A2Uint; case Format::R11G11B10_FLOAT: return MTLPixelFormatRG11B10Float; case Format::R8G8B8A8_UNORM: return MTLPixelFormatRGBA8Unorm; case Format::R8G8B8A8_UINT: return MTLPixelFormatRGBA8Uint; case Format::R8G8B8A8_SNORM: return MTLPixelFormatRGBA8Snorm; case Format::R8G8B8A8_SINT: return MTLPixelFormatRGBA8Sint; case Format::R16G16_FLOAT: return MTLPixelFormatRG16Float; case Format::R16G16_UNORM: return MTLPixelFormatRG16Unorm; case Format::R16G16_UINT: return MTLPixelFormatRG16Uint; case Format::R16G16_SNORM: return MTLPixelFormatRG16Snorm; case Format::R16G16_SINT: return MTLPixelFormatRG16Sint; case Format::D32_FLOAT: return MTLPixelFormatDepth32Float; case Format::R32_FLOAT: return MTLPixelFormatR32Float; case Format::R32_UINT: return MTLPixelFormatR32Uint; case Format::R32_SINT: return MTLPixelFormatR32Sint; case Format::R8G8_UNORM: return MTLPixelFormatRG8Unorm; case Format::R8G8_UINT: return MTLPixelFormatRG8Uint; case Format::R8G8_SNORM: return MTLPixelFormatRG8Snorm; case Format::R8G8_SINT: return MTLPixelFormatRG8Sint; case Format::R16_FLOAT: return MTLPixelFormatR16Float; case Format::R16_UNORM: return MTLPixelFormatR16Unorm; case Format::R16_UINT: return MTLPixelFormatR16Uint; case Format::R16_SNORM: return MTLPixelFormatR16Snorm; case Format::R16_SINT: return MTLPixelFormatR16Sint; case Format::R8_UNORM: return MTLPixelFormatR8Unorm; case Format::R8_UINT: return MTLPixelFormatR8Uint; case Format::R8_SNORM: return MTLPixelFormatR8Snorm; case Format::R8_SINT: return MTLPixelFormatR8Sint; case Format::A8_UNORM: return MTLPixelFormatA8Unorm; case Format::R9G9B9E5_SHAREDEXP: return MTLPixelFormatRGB9E5Float; case Format::D32_SFLOAT_S8_UINT: return MTLPixelFormatDepth32Float_Stencil8; case Format::R8G8B8A8_UNORM_SRGB: return MTLPixelFormatRGBA8Unorm_sRGB; case Format::B8G8R8A8_UNORM: return MTLPixelFormatBGRA8Unorm; case Format::B8G8R8A8_UNORM_SRGB: return MTLPixelFormatBGRA8Unorm_sRGB; //////////// missing formats //////////// case Format::R32G32B32_FLOAT: case Format::R32G32B32_UINT: case Format::R32G32B32_SINT: case Format::R8G8B8_UNORM: case Format::R8G8B8_UINT: case Format::R8G8B8_SNORM: case Format::R8G8B8_SINT: case Format::R8G8B8_UNORM_SRGB: case Format::RGB_ETC1_UNORM: case Format::RGB_ETC1_UNORM_SRGB: case Format::RGBA_ETC2_UNORM: case Format::RGBA_ETC2_UNORM_SRGB: default: break; } #if TARGET_OS_OSX const bool OSXOnlyFormats = true; if (OSXOnlyFormats) { switch (fmt) { case Format::D16_UNORM: return MTLPixelFormatDepth16Unorm; case Format::D24_UNORM_S8_UINT: return MTLPixelFormatDepth24Unorm_Stencil8; case Format::BC1_UNORM: return MTLPixelFormatBC1_RGBA; case Format::BC1_UNORM_SRGB: return MTLPixelFormatBC1_RGBA_sRGB; case Format::BC2_UNORM: return MTLPixelFormatBC2_RGBA; case Format::BC2_UNORM_SRGB: return MTLPixelFormatBC2_RGBA_sRGB; case Format::BC3_UNORM: return MTLPixelFormatBC3_RGBA; case Format::BC3_UNORM_SRGB: return MTLPixelFormatBC3_RGBA_sRGB; case Format::BC4_UNORM: return MTLPixelFormatBC4_RUnorm; case Format::BC4_SNORM: return MTLPixelFormatBC4_RSnorm; case Format::BC5_UNORM: return MTLPixelFormatBC5_RGUnorm; case Format::BC5_SNORM: return MTLPixelFormatBC5_RGSnorm; case Format::BC6H_UF16: return MTLPixelFormatBC6H_RGBUfloat; case Format::BC6H_SF16: return MTLPixelFormatBC6H_RGBFloat; case Format::BC7_UNORM: return MTLPixelFormatBC7_RGBAUnorm; case Format::BC7_UNORM_SRGB: return MTLPixelFormatBC7_RGBAUnorm_sRGB; default: break; } } #endif #if TARGET_OS_IPHONE const bool IOSOnlyFormats = true; if (IOSOnlyFormats) { switch (fmt) { case Format::B5G6R5_UNORM: return MTLPixelFormatB5G6R5Unorm; case Format::B5G5R5A1_UNORM: return MTLPixelFormatA1BGR5Unorm; case Format::R4G4B4A4_UNORM: return MTLPixelFormatABGR4Unorm; case Format::RGB_PVRTC1_2BPP_UNORM: return MTLPixelFormatPVRTC_RGB_2BPP; case Format::RGB_PVRTC1_4BPP_UNORM: return MTLPixelFormatPVRTC_RGB_4BPP; case Format::RGBA_PVRTC1_2BPP_UNORM: /* DavidJ -- assuming compatibility */ case Format::RGBA_PVRTC2_2BPP_UNORM: return MTLPixelFormatPVRTC_RGBA_2BPP; case Format::RGBA_PVRTC1_4BPP_UNORM: /* DavidJ -- assuming compatibility */ case Format::RGBA_PVRTC2_4BPP_UNORM: return MTLPixelFormatPVRTC_RGBA_4BPP; case Format::RGB_PVRTC1_2BPP_UNORM_SRGB: return MTLPixelFormatPVRTC_RGB_2BPP_sRGB; case Format::RGB_PVRTC1_4BPP_UNORM_SRGB: return MTLPixelFormatPVRTC_RGB_4BPP_sRGB; case Format::RGBA_PVRTC1_2BPP_UNORM_SRGB: /* DavidJ -- assuming compatibility */ case Format::RGBA_PVRTC2_2BPP_UNORM_SRGB: return MTLPixelFormatPVRTC_RGBA_2BPP_sRGB; case Format::RGBA_PVRTC1_4BPP_UNORM_SRGB: /* DavidJ -- assuming compatibility */ case Format::RGBA_PVRTC2_4BPP_UNORM_SRGB: return MTLPixelFormatPVRTC_RGBA_4BPP_sRGB; case Format::RGB_ETC2_UNORM: return MTLPixelFormatETC2_RGB8; case Format::RGBA1_ETC2_UNORM: return MTLPixelFormatETC2_RGB8A1_sRGB; case Format::RGB_ETC2_UNORM_SRGB: return MTLPixelFormatETC2_RGB8_sRGB; case Format::RGBA1_ETC2_UNORM_SRGB: return MTLPixelFormatETC2_RGB8A1; default: break; } } #endif // KenD -- Metal doesn't have a 24-bit format, which is quite unfortunate /* #if DEBUG static NSMutableSet* missingFormats = [[NSMutableSet set] retain]; NSUInteger c = missingFormats.count; [missingFormats addObject:[NSString stringWithCString:AsString(fmt) encoding:NSUTF8StringEncoding]]; if (missingFormats.count > c) { NSLog(@"================> Missing RenderCore::Formats %@", missingFormats); } #else assert(0); // aggressive failure for now #endif */ return MTLPixelFormatInvalid; } RenderCore::Format AsRenderCoreFormat(MTLPixelFormat fmt) { using namespace RenderCore; switch (fmt) { case MTLPixelFormatRGBA32Float: return Format::R32G32B32A32_FLOAT; case MTLPixelFormatRGBA32Uint: return Format::R32G32B32A32_UINT; case MTLPixelFormatRGBA32Sint: return Format::R32G32B32A32_SINT; case MTLPixelFormatRGBA16Float: return Format::R16G16B16A16_FLOAT; case MTLPixelFormatRGBA16Unorm: return Format::R16G16B16A16_UNORM; case MTLPixelFormatRGBA16Uint: return Format::R16G16B16A16_UINT; case MTLPixelFormatRGBA16Snorm: return Format::R16G16B16A16_SNORM; case MTLPixelFormatRGBA16Sint: return Format::R16G16B16A16_SINT; case MTLPixelFormatRG32Float: return Format::R32G32_FLOAT; case MTLPixelFormatRG32Uint: return Format::R32G32_UINT; case MTLPixelFormatRG32Sint: return Format::R32G32_SINT; case MTLPixelFormatRGB10A2Unorm: return Format::R10G10B10A2_UNORM; case MTLPixelFormatRGB10A2Uint: return Format::R10G10B10A2_UINT; case MTLPixelFormatRG11B10Float: return Format::R11G11B10_FLOAT; case MTLPixelFormatRGBA8Unorm: return Format::R8G8B8A8_UNORM; case MTLPixelFormatRGBA8Uint: return Format::R8G8B8A8_UINT; case MTLPixelFormatRGBA8Snorm: return Format::R8G8B8A8_SNORM; case MTLPixelFormatRGBA8Sint: return Format::R8G8B8A8_SINT; case MTLPixelFormatRG16Float: return Format::R16G16_FLOAT; case MTLPixelFormatRG16Unorm: return Format::R16G16_UNORM; case MTLPixelFormatRG16Uint: return Format::R16G16_UINT; case MTLPixelFormatRG16Snorm: return Format::R16G16_SNORM; case MTLPixelFormatRG16Sint: return Format::R16G16_SINT; case MTLPixelFormatDepth32Float: return Format::D32_FLOAT; case MTLPixelFormatR32Float: return Format::R32_FLOAT; case MTLPixelFormatR32Uint: return Format::R32_UINT; case MTLPixelFormatR32Sint: return Format::R32_SINT; case MTLPixelFormatRG8Unorm: return Format::R8G8_UNORM; case MTLPixelFormatRG8Uint: return Format::R8G8_UINT; case MTLPixelFormatRG8Snorm: return Format::R8G8_SNORM; case MTLPixelFormatRG8Sint: return Format::R8G8_SINT; case MTLPixelFormatR16Float: return Format::R16_FLOAT; case MTLPixelFormatR16Unorm: return Format::R16_UNORM; case MTLPixelFormatR16Uint: return Format::R16_UINT; case MTLPixelFormatR16Snorm: return Format::R16_SNORM; case MTLPixelFormatR16Sint: return Format::R16_SINT; case MTLPixelFormatR8Unorm: return Format::R8_UNORM; case MTLPixelFormatR8Uint: return Format::R8_UINT; case MTLPixelFormatR8Snorm: return Format::R8_SNORM; case MTLPixelFormatR8Sint: return Format::R8_SINT; case MTLPixelFormatA8Unorm: return Format::A8_UNORM; case MTLPixelFormatRGB9E5Float: return Format::R9G9B9E5_SHAREDEXP; case MTLPixelFormatDepth32Float_Stencil8: return Format::D32_SFLOAT_S8_UINT; case MTLPixelFormatBGRA8Unorm: return Format::B8G8R8A8_UNORM; case MTLPixelFormatBGRA8Unorm_sRGB: return Format::B8G8R8A8_UNORM_SRGB; case MTLPixelFormatRGBA8Unorm_sRGB: return Format::R8G8B8A8_UNORM_SRGB; #if 0 case {GL_RGB, GL_UNSIGNED_BYTE, GL_RGB8}: return Format::R8G8B8_UNORM; case {GL_RGB_INTEGER, GL_UNSIGNED_BYTE, GL_RGB8UI}: return Format::R8G8B8_UINT; case {GL_RGB, GL_BYTE, GL_RGB8_SNORM}: return Format::R8G8B8_SNORM; case {GL_RGB_INTEGER, GL_BYTE, GL_RGB8I}: return Format::R8G8B8_SINT; case {GL_RGB, GL_FLOAT, GL_RGB32F}: return Format::R32G32B32_FLOAT; case {GL_RGB_INTEGER, GL_UNSIGNED_INT, GL_RGB32UI}: return Format::R32G32B32_UINT; case {GL_RGB_INTEGER, GL_INT, GL_RGB32I}: return Format::R32G32B32_SINT; case {GL_RGBA, GL_BYTE, GL_RGB8_SNORM}: return Format::R8G8B8_UNORM_SRGB; case {0, 0, GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG}: return Format::RGB_PVRTC1_2BPP_UNORM; case {0, 0, GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}: return Format::RGBA_PVRTC1_2BPP_UNORM; case {0, 0, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG}: return Format::RGB_PVRTC1_4BPP_UNORM; case {0, 0, GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG}: return Format::RGBA_PVRTC1_4BPP_UNORM; case {0, 0, GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG}: return Format::RGBA_PVRTC2_2BPP_UNORM; case {0, 0, GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG}: return Format::RGBA_PVRTC2_4BPP_UNORM; case {0, 0, GL_ETC1_RGB8_OES}: return Format::RGB_ETC1_UNORM; case {0, 0, GL_COMPRESSED_RGB8_ETC2}: return Format::RGB_ETC2_UNORM; case {0, 0, GL_COMPRESSED_RGBA8_ETC2_EAC}: return Format::RGBA_ETC2_UNORM; case {0, 0, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2}: return Format::RGBA1_ETC2_UNORM; case {0, 0, GL_COMPRESSED_SRGB8_ETC2}: return Format::RGB_ETC2_UNORM_SRGB; case {0, 0, GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC}: return Format::RGBA_ETC2_UNORM_SRGB; case Format::RGBA1_ETC2_UNORM_SRGB: return {0, 0, GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2}; case Format::RGB_PVRTC1_2BPP_UNORM_SRGB: case Format::RGBA_PVRTC1_2BPP_UNORM_SRGB: case Format::RGB_PVRTC1_4BPP_UNORM_SRGB: case Format::RGBA_PVRTC1_4BPP_UNORM_SRGB: case Format::RGBA_PVRTC2_2BPP_UNORM_SRGB: case Format::RGBA_PVRTC2_4BPP_UNORM_SRGB: case Format::RGB_ETC1_UNORM_SRGB: #endif default: break; } #if TARGET_OS_OSX const bool OSXOnlyFormats = true; if (OSXOnlyFormats) { switch (fmt) { case MTLPixelFormatDepth16Unorm: return Format::D16_UNORM; case MTLPixelFormatDepth24Unorm_Stencil8: return Format::D24_UNORM_S8_UINT; case MTLPixelFormatBC1_RGBA: return Format::BC1_UNORM; case MTLPixelFormatBC1_RGBA_sRGB: return Format::BC1_UNORM_SRGB; case MTLPixelFormatBC2_RGBA: return Format::BC2_UNORM; case MTLPixelFormatBC2_RGBA_sRGB: return Format::BC2_UNORM_SRGB; case MTLPixelFormatBC3_RGBA: return Format::BC3_UNORM; case MTLPixelFormatBC3_RGBA_sRGB: return Format::BC3_UNORM_SRGB; case MTLPixelFormatBC4_RUnorm: return Format::BC4_UNORM; case MTLPixelFormatBC4_RSnorm: return Format::BC4_SNORM; case MTLPixelFormatBC5_RGUnorm: return Format::BC5_UNORM; case MTLPixelFormatBC5_RGSnorm: return Format::BC5_SNORM; case MTLPixelFormatBC6H_RGBUfloat: return Format::BC6H_UF16; case MTLPixelFormatBC6H_RGBFloat: return Format::BC6H_SF16; case MTLPixelFormatBC7_RGBAUnorm: return Format::BC7_UNORM; case MTLPixelFormatBC7_RGBAUnorm_sRGB: return Format::BC7_UNORM_SRGB; default: break; } } #endif #if TARGET_OS_IPHONE const bool IOSOnlyFormats = true; if (IOSOnlyFormats) { switch (fmt) { case MTLPixelFormatB5G6R5Unorm: return Format::B5G6R5_UNORM; case MTLPixelFormatA1BGR5Unorm: return Format::B5G5R5A1_UNORM; case MTLPixelFormatABGR4Unorm: return Format::R4G4B4A4_UNORM; case MTLPixelFormatPVRTC_RGB_2BPP: return Format::RGB_PVRTC1_2BPP_UNORM; case MTLPixelFormatPVRTC_RGB_4BPP: return Format::RGB_PVRTC1_4BPP_UNORM; case MTLPixelFormatPVRTC_RGBA_2BPP: return Format::RGBA_PVRTC2_2BPP_UNORM; case MTLPixelFormatPVRTC_RGBA_4BPP: return Format::RGBA_PVRTC2_4BPP_UNORM; case MTLPixelFormatPVRTC_RGB_2BPP_sRGB: return Format::RGB_PVRTC1_2BPP_UNORM_SRGB; case MTLPixelFormatPVRTC_RGB_4BPP_sRGB: return Format::RGB_PVRTC1_4BPP_UNORM_SRGB; case MTLPixelFormatPVRTC_RGBA_2BPP_sRGB: return Format::RGBA_PVRTC2_2BPP_UNORM_SRGB; case MTLPixelFormatPVRTC_RGBA_4BPP_sRGB: return Format::RGBA_PVRTC2_4BPP_UNORM_SRGB; case MTLPixelFormatETC2_RGB8: return Format::RGB_ETC2_UNORM; case MTLPixelFormatETC2_RGB8A1_sRGB: return Format::RGBA1_ETC2_UNORM; case MTLPixelFormatETC2_RGB8_sRGB: return Format::RGB_ETC2_UNORM_SRGB; case MTLPixelFormatETC2_RGB8A1: return Format::RGBA1_ETC2_UNORM_SRGB; default: break; } } #endif /* #if DEBUG static NSMutableSet* missingFormats = [[NSMutableSet set] retain]; NSUInteger c = missingFormats.count; [missingFormats addObject:@(fmt)]; if (missingFormats.count > c) { NSLog(@"================> Missing MTL formats %@", missingFormats); } #else assert(0); // aggressive failure for now #endif */ return Format::Unknown; } MTLVertexFormat AsMTLVertexFormat(RenderCore::Format fmt) { switch (fmt) { case Format::R32_FLOAT: return MTLVertexFormatFloat; case Format::R32G32_FLOAT: return MTLVertexFormatFloat2; case Format::R32G32B32_FLOAT: return MTLVertexFormatFloat3; case Format::R32G32B32A32_FLOAT: return MTLVertexFormatFloat4; case Format::R32_SINT: return MTLVertexFormatInt; case Format::R32G32_SINT: return MTLVertexFormatInt2; case Format::R32G32B32_SINT: return MTLVertexFormatInt3; case Format::R32G32B32A32_SINT: return MTLVertexFormatInt4; case Format::R32_UINT: return MTLVertexFormatUInt; case Format::R32G32_UINT: return MTLVertexFormatUInt2; case Format::R32G32B32_UINT: return MTLVertexFormatUInt3; case Format::R32G32B32A32_UINT: return MTLVertexFormatUInt4; case Format::R8G8_UNORM: return MTLVertexFormatUChar2Normalized; case Format::R8G8B8_UNORM: return MTLVertexFormatUChar3Normalized; case Format::R8G8B8A8_UNORM: return MTLVertexFormatUChar4Normalized; case Format::R8G8_SNORM: return MTLVertexFormatChar2Normalized; case Format::R8G8B8_SNORM: return MTLVertexFormatChar3Normalized; case Format::R8G8B8A8_SNORM: return MTLVertexFormatChar4Normalized; case Format::R16G16_UNORM: return MTLVertexFormatUShort2Normalized; case Format::R16G16B16A16_UNORM: return MTLVertexFormatUShort4Normalized; case Format::R16G16_SNORM: return MTLVertexFormatShort2Normalized; case Format::R16G16B16A16_SNORM: return MTLVertexFormatShort4Normalized; case Format::R16G16_FLOAT: return MTLVertexFormatHalf2; case Format::R16G16B16A16_FLOAT: return MTLVertexFormatHalf4; case Format::R16G16_UINT: return MTLVertexFormatUShort2; case Format::R16G16B16A16_UINT: return MTLVertexFormatUShort4; case Format::R16G16_SINT: return MTLVertexFormatShort2; case Format::R16G16B16A16_SINT: return MTLVertexFormatShort4; case Format::R8G8_UINT: return MTLVertexFormatUChar2; case Format::R8G8B8_UINT: return MTLVertexFormatUChar3; case Format::R8G8B8A8_UINT: return MTLVertexFormatUChar4; case Format::R8G8_SINT: return MTLVertexFormatChar2; case Format::R8G8B8_SINT: return MTLVertexFormatChar3; case Format::R8G8B8A8_SINT: return MTLVertexFormatChar4; default: break; } #if DEBUG static NSMutableSet* missingFormats = [[NSMutableSet set] retain]; NSUInteger c = missingFormats.count; [missingFormats addObject:[NSString stringWithCString:AsString(fmt) encoding:NSUTF8StringEncoding]]; if (missingFormats.count > c) { NSLog(@"================> Missing MTLVertexFormat for RenderCore::Formats %@", missingFormats); } #else assert(0); // aggressive failure for now #endif return MTLVertexFormatInvalid; } Utility::ImpliedTyping::TypeDesc AsTypeDesc(MTLDataType fmt) { switch(fmt) { case MTLDataTypeFloat: return { ImpliedTyping::TypeCat::Float }; case MTLDataTypeFloat2: return { ImpliedTyping::TypeCat::Float, uint16(2), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeFloat3: return { ImpliedTyping::TypeCat::Float, uint16(3), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeFloat4: return { ImpliedTyping::TypeCat::Float, uint16(4), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeFloat2x2: return { ImpliedTyping::TypeCat::Float, uint16(4), ImpliedTyping::TypeHint::Matrix }; case MTLDataTypeFloat2x3: return { ImpliedTyping::TypeCat::Float, uint16(6), ImpliedTyping::TypeHint::Matrix }; case MTLDataTypeFloat2x4: return { ImpliedTyping::TypeCat::Float, uint16(8), ImpliedTyping::TypeHint::Matrix }; case MTLDataTypeFloat3x2: return { ImpliedTyping::TypeCat::Float, uint16(6), ImpliedTyping::TypeHint::Matrix }; case MTLDataTypeFloat3x3: return { ImpliedTyping::TypeCat::Float, uint16(9), ImpliedTyping::TypeHint::Matrix }; case MTLDataTypeFloat3x4: return { ImpliedTyping::TypeCat::Float, uint16(12), ImpliedTyping::TypeHint::Matrix }; case MTLDataTypeFloat4x2: return { ImpliedTyping::TypeCat::Float, uint16(8), ImpliedTyping::TypeHint::Matrix }; case MTLDataTypeFloat4x3: return { ImpliedTyping::TypeCat::Float, uint16(12), ImpliedTyping::TypeHint::Matrix }; case MTLDataTypeFloat4x4: return { ImpliedTyping::TypeCat::Float, uint16(16), ImpliedTyping::TypeHint::Matrix }; case MTLDataTypeInt: return { ImpliedTyping::TypeCat::Int32 }; case MTLDataTypeInt2: return { ImpliedTyping::TypeCat::Int32, uint16(2), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeInt3: return { ImpliedTyping::TypeCat::Int32, uint16(3), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeInt4: return { ImpliedTyping::TypeCat::Int32, uint16(4), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeUInt: return { ImpliedTyping::TypeCat::UInt32 }; case MTLDataTypeUInt2: return { ImpliedTyping::TypeCat::UInt32, uint16(2), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeUInt3: return { ImpliedTyping::TypeCat::UInt32, uint16(3), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeUInt4: return { ImpliedTyping::TypeCat::UInt32, uint16(4), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeShort: return { ImpliedTyping::TypeCat::Int16 }; case MTLDataTypeShort2: return { ImpliedTyping::TypeCat::Int16, uint16(2), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeShort3: return { ImpliedTyping::TypeCat::Int16, uint16(3), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeShort4: return { ImpliedTyping::TypeCat::Int16, uint16(4), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeUShort: return { ImpliedTyping::TypeCat::UInt16 }; case MTLDataTypeUShort2: return { ImpliedTyping::TypeCat::UInt16, uint16(2), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeUShort3: return { ImpliedTyping::TypeCat::UInt16, uint16(3), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeUShort4: return { ImpliedTyping::TypeCat::UInt16, uint16(4), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeChar: return { ImpliedTyping::TypeCat::Int8 }; case MTLDataTypeChar2: return { ImpliedTyping::TypeCat::Int8, uint16(2), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeChar3: return { ImpliedTyping::TypeCat::Int8, uint16(3), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeChar4: return { ImpliedTyping::TypeCat::Int8, uint16(4), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeUChar: return { ImpliedTyping::TypeCat::UInt8 }; case MTLDataTypeUChar2: return { ImpliedTyping::TypeCat::UInt8, uint16(2), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeUChar3: return { ImpliedTyping::TypeCat::UInt8, uint16(3), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeUChar4: return { ImpliedTyping::TypeCat::UInt8, uint16(4), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeBool: return { ImpliedTyping::TypeCat::Bool }; case MTLDataTypeBool2: return { ImpliedTyping::TypeCat::Bool, uint16(2), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeBool3: return { ImpliedTyping::TypeCat::Bool, uint16(3), ImpliedTyping::TypeHint::Vector }; case MTLDataTypeBool4: return { ImpliedTyping::TypeCat::Bool, uint16(4), ImpliedTyping::TypeHint::Vector }; default: return {}; } } }}
shkir/sctp-refimpl
APPS/unpcode/unpv13e/server/lock_pthread.c
<filename>APPS/unpcode/unpv13e/server/lock_pthread.c<gh_stars>1-10 /* include my_lock_init */ #include "unpthread.h" #include <sys/mman.h> static pthread_mutex_t *mptr; /* actual mutex will be in shared memory */ void my_lock_init(char *pathname) { int fd; pthread_mutexattr_t mattr; fd = Open("/dev/zero", O_RDWR, 0); mptr = Mmap(0, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); Close(fd); Pthread_mutexattr_init(&mattr); Pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED); Pthread_mutex_init(mptr, &mattr); } /* end my_lock_init */ /* include my_lock_wait */ void my_lock_wait() { Pthread_mutex_lock(mptr); } void my_lock_release() { Pthread_mutex_unlock(mptr); } /* end my_lock_wait */
yuanweikang2020/canal
parse/src/main/java/com/alibaba/otter/canal/parse/exception/ServerIdNotMatchException.java
<reponame>yuanweikang2020/canal package com.alibaba.otter.canal.parse.exception; import com.alibaba.otter.canal.common.CanalException; /** * @author chengjin.lyf on 2018/8/8 下午1:07 * @since 1.0.25 */ public class ServerIdNotMatchException extends CanalException { private static final long serialVersionUID = -6124989280379293953L; public ServerIdNotMatchException(String errorCode){ super(errorCode); } public ServerIdNotMatchException(String errorCode, Throwable cause){ super(errorCode, cause); } public ServerIdNotMatchException(String errorCode, String errorDesc){ super(errorCode, errorDesc); } public ServerIdNotMatchException(String errorCode, String errorDesc, Throwable cause){ super(errorCode, errorDesc, cause); } public ServerIdNotMatchException(Throwable cause){ super(cause); } }