repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
TheTryton/rtti
rtti/include/reflection/template/template_info.hpp
<reponame>TheTryton/rtti<filename>rtti/include/reflection/template/template_info.hpp #pragma once #include "../common.hpp" REFLECTION_NAMESPACE_BEGIN class template_info { friend class reflection; template<class T> friend class template_type_info_impl; protected: template_info() = default; public: virtual ~template_info() = default; template_info(const template_info&) = delete; template_info(template_info&&) = delete; template_info& operator=(const template_info&) = delete; template_info& operator=(template_info&&) = delete; public: virtual type_index native_type_info() const = 0; virtual template_uuid uuid() const = 0; virtual string name() const = 0; bool is_same(const template_info* other) const; template<template<class...> class T> bool is_same() const; public: virtual size_t template_args_count() const = 0; public: vector<const template_type_info*> instantiations() const; protected: vector<const template_type_info*> _instantiations; }; template<template<class...> class T> class template_info_impl final : public template_info { friend class reflection; protected: template_info_impl(type_uuid uuid, string name, size_t args_count); public: virtual ~template_info_impl() override = default; template_info_impl(const template_info_impl&) = delete; template_info_impl(template_info_impl&&) = delete; template_info_impl& operator=(const template_info_impl&) = delete; template_info_impl& operator=(template_info_impl&&) = delete; public: virtual type_index native_type_info() const override; virtual template_uuid uuid() const override; virtual string name() const override; public: virtual size_t template_args_count() const override; private: template_uuid _uuid; string _name; size_t _args_count; }; REFLECTION_NAMESPACE_END
alvienzo720/Dep_Nadine
nadine-2.2.3/doors/threads.py
<filename>nadine-2.2.3/doors/threads.py<gh_stars>0 import sys import time import logging import threading from core import Messages class Heartbeat(threading.Thread): def __init__(self, connection, poll_delay_sec): threading.Thread.__init__(self) self.connection = connection self.poll_delay_sec = poll_delay_sec self.new_data = False self.error = None self.debug = False def run(self): self.running = True logging.info("Heartbeat: polling every %d seconds" % self.poll_delay_sec) try: while self.running: time.sleep(self.poll_delay_sec) if not self.new_data: logging.debug("Heartbeat: Contacting the Keymaster...") response = self.connection.send_message(Messages.CHECK_IN) if response == Messages.NEW_DATA: logging.info("Heartbeat: There is new data to be processed") self.new_data = True else: logging.debug("Heartbeat: No new door codes") # Mark this connection successfull response = self.connection.send_message(Messages.MARK_SUCCESS) if not response == Messages.SUCCESS_RESPONSE: raise Exception("Heartbeat: Did not receive proper success response!") except Exception as e: logging.error("Heartbeat Exception: %s" % e) self.error = e def all_clear(self): response = self.connection.send_message(Messages.MARK_SYNC) if not response == Messages.SUCCESS_RESPONSE: raise Exception("Heartbeat: Did not receive proper success response!") self.new_data = False def stop(self): self.poll_delay_sec = 0.1 self.running = False class EventWatcher(threading.Thread): def __init__(self, gatekeeper, poll_delay_sec): threading.Thread.__init__(self) self.gatekeeper = gatekeeper self.poll_delay_sec = poll_delay_sec self.new_data = False self.error = None def run(self): self.running = True logging.info("EventWatcher: Polling every %d seconds" % self.poll_delay_sec) try: while self.running: time.sleep(self.poll_delay_sec) if not self.new_data: logging.debug("EventWatcher: Polling the doors for events...") event_logs = self.gatekeeper.pull_event_logs(1) for door_name, logs in list(event_logs.items()): if logs and len(logs) == 1 and 'timestamp' in logs[0]: door = self.gatekeeper.get_door(door_name) last_event_ts = door.get("last_event_ts") if logs[0]['timestamp'] != last_event_ts: # If this is one of our magic keys, do some magic! cardNumber = logs[0].get('cardNumber', None) self.gatekeeper.magic_key_test(door_name, cardNumber) self.new_data = True break if not self.new_data: logging.debug("EventWatcher: No new event logs") except Exception as e: logging.error("EventWatcher Exception: %s" % e) self.error = e def all_clear(self): logging.info("EventWatcher: all clear") self.new_data = False def stop(self): logging.info("EventWatcher: stop") self.poll_delay_sec = 0.1 self.running = False # Copyright 2020 Office Nomads LLC (https://officenomads.com/) 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 https://opensource.org/licenses/Apache-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.
generative-fm/user
src/user-id/select-user-id.js
const selectUserId = ({ userId }) => userId; export default selectUserId;
MobileSeoul/2017seoul-15
seoulMarketDayAndroid/seoulMarketDayAndroid/app/src/main/java/com/stm/story/create/interactor/StoryCreateInteractor.java
package com.stm.story.create.interactor; import com.stm.common.dao.Story; import com.stm.common.dao.User; import com.stm.common.dto.FileDto; import java.util.ArrayList; /** * Created by ㅇㅇ on 2017-07-11. */ public interface StoryCreateInteractor { void setStoryRepository(String accessToken); User getUser(); void setUser(User user); void setFileDtosAdd(FileDto fileDto); void setFileDtosAddAll(ArrayList<FileDto> fileDtos); ArrayList<FileDto> getFileDtos(); void setFileDtos(ArrayList<FileDto> fileDtos); void getStoryIdByUploadingStoryAndFileDtos(Story story, ArrayList<FileDto> fIleDtos); void getStoryIdByUploadingStory(Story story); }
tao-pr/52-challenges
004-time-series-geo-data/libdata/wrangle.py
import pandas as pd import numpy as np from typing import List from libdata.func import collect, head def split_month_year(df: pd.DataFrame) -> pd.DataFrame: """ Split the `dt` column into `year` and `month` """ df['dt'] = pd.to_datetime(df['dt']) df['year'] = df['dt'].dt.to_period('Y').apply(lambda period: period.year) df['month'] = df['dt'].map(lambda d: d.month) df.reset_index(inplace=True, drop=True) return df def take_last_year(city_df: pd.DataFrame, num_years: int = 1) -> pd.DataFrame: """ Filter the last year only """ df = city_df[city_df['year'] >= max(city_df['year']) - num_years + 1] df = df[[ 'AverageTemperature','year','month','City','Country', 'Latitude','Longitude']] return df def agg_monthly_climate(city_df: pd.DataFrame) -> pd.DataFrame: """ Collect monthly climate over coordinates """ agg = city_df.groupby(['year','Latitude','Longitude']).agg({ 'AverageTemperature': [min, max, collect] }).reset_index(drop=False) return agg def create_city_latlng_map(city_df: pd.DataFrame) -> dict: """ Create a dictionary which maps from lat-lng coordinate to the city name """ agg = city_df.groupby(['Latitude','Longitude']).agg({ 'City': head, 'Country': head }).reset_index(drop=False) m = dict() for _,row in agg.iterrows(): key = '{}-{}'.format(row['Latitude'], row['Longitude']) m[key] = (row['City'], row['Country']) return m
mudbungie/NetExplorer
Config.py
<gh_stars>0 # This is a file that just parses the config # Gives a dict-like object to anything that imports it from configobj import ConfigObj import os.path whereAmI = os.path.dirname(os.path.abspath(__file__)) + '/' config = ConfigObj(whereAmI + 'netexplorer.conf')
plasticviking/fv-web-ui
modules/security/firstvoices-security/src/main/java/ca/firstvoices/security/securitypolicies/groups/LanguageRecorders.java
<filename>modules/security/firstvoices-security/src/main/java/ca/firstvoices/security/securitypolicies/groups/LanguageRecorders.java /* * * * * * Copyright 2020 First People's Cultural Council * * * * 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 ca.firstvoices.security.securitypolicies.groups; import static ca.firstvoices.data.schemas.DialectTypesConstants.FV_BOOK; import static ca.firstvoices.data.schemas.DialectTypesConstants.FV_BOOKS; import static ca.firstvoices.data.schemas.DialectTypesConstants.FV_BOOK_ENTRY; import static ca.firstvoices.data.schemas.DialectTypesConstants.FV_CATEGORIES; import static ca.firstvoices.data.schemas.DialectTypesConstants.FV_CONTRIBUTORS; import static ca.firstvoices.data.schemas.DialectTypesConstants.FV_DICTIONARY; import static ca.firstvoices.data.schemas.DialectTypesConstants.FV_LABEL_DICTIONARY; import static ca.firstvoices.data.schemas.DialectTypesConstants.FV_PORTAL; import static ca.firstvoices.data.schemas.DialectTypesConstants.FV_RESOURCES; import ca.firstvoices.security.utils.CustomSecurityConstants; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.NuxeoPrincipal; import org.nuxeo.ecm.core.api.security.ACE; import org.nuxeo.ecm.core.api.security.ACL; import org.nuxeo.ecm.core.api.security.ACP; import org.nuxeo.ecm.core.api.security.Access; import org.nuxeo.ecm.core.api.security.SecurityConstants; import org.nuxeo.ecm.core.model.Document; import org.nuxeo.ecm.core.query.sql.model.SQLQuery.Transformer; import org.nuxeo.ecm.core.security.AbstractSecurityPolicy; /** * Language recorders policies */ public class LanguageRecorders extends AbstractSecurityPolicy { private static final Log log = LogFactory.getLog(LanguageRecorders.class); // A list of document types with ReadWrite Permissions private static ArrayList<String> allowedDocumentTypes = new ArrayList<>(); /** * Check if recorder has permission on current document, to avoid using groups for filtering. * * @param mergedAcp * @param additionalPrincipalsList * @return */ private boolean hasRecordPermissionInACP(ACP mergedAcp, List<String> additionalPrincipalsList) { for (ACL acl : mergedAcp.getACLs()) { for (ACE ace : acl.getACEs()) { // get permission CAN be null if (ace.isGranted() && additionalPrincipalsList.contains(ace.getUsername()) && CustomSecurityConstants.RECORD.equals(ace.getPermission())) { return true; } } } return false; } @Override public boolean isRestrictingPermission(String permission) { return permission.equals(SecurityConstants.ADD_CHILDREN) || permission .equals(SecurityConstants.WRITE) || permission.equals(SecurityConstants.WRITE_PROPERTIES) || permission.equals(CustomSecurityConstants.CAN_ASK_FOR_PUBLISH) || permission .equals(SecurityConstants.REMOVE_CHILDREN) || permission.equals(SecurityConstants.REMOVE); } @Override public Access checkPermission(Document doc, ACP mergedAcp, NuxeoPrincipal principal, String permission, String[] resolvedPermissions, String[] additionalPrincipals) { List<String> resolvedPermissionsList = Arrays.asList(resolvedPermissions); List<String> additionalPrincipalsList = Arrays.asList(additionalPrincipals); log.debug("Checking permission: " + permission + " on doc: " + doc.getUUID() + " for user: " + principal.getName()); // Skip administrators, system and users who aren't recorders if (additionalPrincipalsList.contains("administrators") || principal.getName() .equals(SecurityConstants.SYSTEM_USERNAME) || !Arrays.asList(additionalPrincipals) .contains("recorders")) { return Access.UNKNOWN; } // Skip permissions that are READ, this policy will not limit them if ("BROWSE".equals(permission)) { return Access.UNKNOWN; } String docType = doc.getType().getName(); String docTypeParent = null; if (doc.getParent() != null) { docTypeParent = doc.getParent().getType().getName(); } // Permissions apply to recorders only if (hasRecordPermissionInACP(mergedAcp, additionalPrincipalsList)) { if (allowedDocumentTypes.isEmpty()) { allowedDocumentTypes.add(FV_CATEGORIES); allowedDocumentTypes.add(FV_CONTRIBUTORS); allowedDocumentTypes.add(FV_DICTIONARY); allowedDocumentTypes.add(FV_LABEL_DICTIONARY); allowedDocumentTypes.add(FV_RESOURCES); allowedDocumentTypes.add(FV_BOOK); allowedDocumentTypes.add(FV_BOOKS); allowedDocumentTypes.add(FV_BOOK_ENTRY); allowedDocumentTypes.add(FV_PORTAL); } // Allow adding children and removing children on allowed types if (allowedDocumentTypes.contains(docType) && ( resolvedPermissionsList.contains(SecurityConstants.ADD_CHILDREN) || resolvedPermissionsList.contains(SecurityConstants.REMOVE_CHILDREN))) { return Access.GRANT; } // Allow Publishing, Writing and Removing on allowed document type children if (docTypeParent != null && allowedDocumentTypes.contains(docTypeParent) && ( resolvedPermissionsList.contains(SecurityConstants.WRITE_PROPERTIES) || resolvedPermissionsList.contains(SecurityConstants.REMOVE) || resolvedPermissionsList.contains(SecurityConstants.WRITE))) { return Access.GRANT; } } // Recorders can only publish to their allowed types (OK to use groups as this is globally // applicable) if ((additionalPrincipalsList.contains(CustomSecurityConstants.RECORDERS_GROUP) || additionalPrincipalsList.contains(CustomSecurityConstants.RECORDERS_APPROVERS_GROUP)) && !allowedDocumentTypes.contains(docType) && (resolvedPermissionsList .contains(CustomSecurityConstants.CAN_ASK_FOR_PUBLISH)) ) { log.debug("Access denied on Resolvers: "); return Access.DENY; } return Access.UNKNOWN; } @Override public boolean isExpressibleInQuery(String repositoryName) { return true; } @Override public Transformer getQueryTransformer(String repositoryName) { return Transformer.IDENTITY; } }
dwtester88/jitsi_master
src/org/jitsi/android/gui/chat/JitsiProtocolReceiver.java
<reponame>dwtester88/jitsi_master<gh_stars>100-1000 /* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * 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.jitsi.android.gui.chat; import android.content.*; import android.os.*; import net.java.sip.communicator.util.*; import org.jitsi.service.osgi.*; import java.net.*; /** * @author <NAME> */ public class JitsiProtocolReceiver extends OSGiActivity { /** * The logger */ private final static Logger logger = Logger.getLogger(JitsiProtocolReceiver.class); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); logger.info("Jitsi protocol intent received " + intent); String urlStr = intent.getDataString(); if(urlStr != null) { try { URI url = new URI(urlStr); ChatSessionManager.notifyChatLinkClicked(url); } catch (URISyntaxException e) { logger.error("Error parsing clicked URL", e); } } else { logger.warn("No URL supplied in Jitsi link"); } finish(); } }
Elfo404/drivers
rtl8720dn/crc16.go
<filename>rtl8720dn/crc16.go package rtl8720dn // https://github.com/EmbeddedRPC/erpc/blob/develop/erpc_python/erpc/crc16.py const ( crcStart = 0xEF4A ) var table = [256]uint16{ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0, } func computeCRC16(data []byte) uint16 { crc := uint16(crcStart) for _, d := range data { crc = ((crc << 8) ^ table[((crc>>8)^uint16(d))&0xFF]) & 0xFFFF } return crc }
ghsecuritylab/tomato_egg
release/src-rt/linux/linux-2.6/include/asm-arm/cache.h
/* * linux/include/asm-arm/cache.h */ #ifndef __ASMARM_CACHE_H #define __ASMARM_CACHE_H #define L1_CACHE_SHIFT 5 #define L1_CACHE_BYTES (1 << L1_CACHE_SHIFT) #endif
guoshucan/mpaas
ghost.framework.web.context/src/main/java/ghost/framework/web/context/http/responseContent/SelectResponse.java
<reponame>guoshucan/mpaas<filename>ghost.framework.web.context/src/main/java/ghost/framework/web/context/http/responseContent/SelectResponse.java package ghost.framework.web.context.http.responseContent; /** * 分页响应。 */ public class SelectResponse extends DataResponse { private static final long serialVersionUID = 7426957949298149551L; private long count; public long getCount() { return count; } public void setCount(long count) { this.count = count; } private long pages; public long getPages() { return pages; } public void setPages(long pages) { this.pages = pages; } private int length; public void setLength(int length) { this.length = length; } public int getLength() { return length; } }
wuzhun1001/TinyEngine
scripts/drivers/ir/hxd091/src/index.js
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ var hxd091 = function(scl_id,sda_id,busy_id) { this.sclHandle = GPIO.open(scl_id); this.sdaHandle = GPIO.open(sda_id); this.busyHandle = GPIO.open(busy_id); this.init = function() { GPIO.write(this.sdaHandle, 1); GPIO.write(this.sclHandle, 1); }; this.send = function(buf) { this.init(); IR.send(this.sdaHandle, this.sclHandle, buf); }; this.learn = function() { var arr = IR.learn(this.sdaHandle, this.sclHandle, this.busyHandle); return arr; }; }; module.exports = hxd091;
phatblat/macOSPrivateFrameworks
PrivateFrameworks/NotesShared/NSManagedObjectContext-IC.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSManagedObjectContext.h" @class NSString; @interface NSManagedObjectContext (IC) - (void)ic_performBlockAndWait:(CDUnknownBlockType)arg1 andPerformBlockAndWaitOnMainThread:(CDUnknownBlockType)arg2; - (void)ic_performBlock:(CDUnknownBlockType)arg1 andPerformBlockOnMainThread:(CDUnknownBlockType)arg2; - (BOOL)ic_saveWithLogDescription:(id)arg1; - (BOOL)ic_save; @property(readonly, nonatomic) BOOL ic_isMainThreadContext; @property(retain, nonatomic) NSString *ic_debugName; @end
tkddlf4209/iotivity2.0.1
resource/docs/cpp-doc/docs/html/class_o_i_c_1_1_service_1_1_r_c_s_resource_attributes_1_1_type.js
var class_o_i_c_1_1_service_1_1_r_c_s_resource_attributes_1_1_type = [ [ "Type", "class_o_i_c_1_1_service_1_1_r_c_s_resource_attributes_1_1_type.html#a18ff9feb7f9d17613cad98d7809566a5", null ], [ "Type", "class_o_i_c_1_1_service_1_1_r_c_s_resource_attributes_1_1_type.html#a2fd82f04ee2564933effb70c1a3ce1e6", null ], [ "getId", "class_o_i_c_1_1_service_1_1_r_c_s_resource_attributes_1_1_type.html#a2ae2a2b48ea1ed1c4c5e631bd731a6d6", null ], [ "operator=", "class_o_i_c_1_1_service_1_1_r_c_s_resource_attributes_1_1_type.html#aee54debfe880daa84e070d58f415a5bc", null ], [ "operator=", "class_o_i_c_1_1_service_1_1_r_c_s_resource_attributes_1_1_type.html#a7b05dee99d87361cadaa23ca89c3b0de", null ], [ "operator!=", "class_o_i_c_1_1_service_1_1_r_c_s_resource_attributes_1_1_type.html#a7a69498bd341fe6aa9427e4fe915cfeb", null ], [ "operator==", "class_o_i_c_1_1_service_1_1_r_c_s_resource_attributes_1_1_type.html#ad629d8813958a73da014de386d362dba", null ] ];
Vesna1971/babel
packages/babel-plugin-transform-es2015-instanceof/src/index.js
<reponame>Vesna1971/babel<gh_stars>1-10 export default function ({ types: t }) { return { visitor: { BinaryExpression(path) { const { node } = path; if (node.operator === "instanceof") { path.replaceWith(t.callExpression(this.addHelper("instanceof"), [node.left, node.right])); } } } }; }
ScalablyTyped/SlinkyTyped
g/googleapis/src/main/scala/typingsSlinky/googleapis/visionV1Mod/visionV1/SchemaGoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponse.scala
package typingsSlinky.googleapis.visionV1Mod.visionV1 import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} /** * Response to an async batch file annotation request. */ @js.native trait SchemaGoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponse extends StObject { /** * The list of file annotation responses, one for each request in * AsyncBatchAnnotateFilesRequest. */ var responses: js.UndefOr[js.Array[SchemaGoogleCloudVisionV1p4beta1AsyncAnnotateFileResponse]] = js.native } object SchemaGoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponse { @scala.inline def apply(): SchemaGoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponse = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[SchemaGoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponse] } @scala.inline implicit class SchemaGoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponseMutableBuilder[Self <: SchemaGoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponse] (val x: Self) extends AnyVal { @scala.inline def setResponses(value: js.Array[SchemaGoogleCloudVisionV1p4beta1AsyncAnnotateFileResponse]): Self = StObject.set(x, "responses", value.asInstanceOf[js.Any]) @scala.inline def setResponsesUndefined: Self = StObject.set(x, "responses", js.undefined) @scala.inline def setResponsesVarargs(value: SchemaGoogleCloudVisionV1p4beta1AsyncAnnotateFileResponse*): Self = StObject.set(x, "responses", js.Array(value :_*)) } }
lihuibng/marshmallow
art/runtime/gc/accounting/mod_union_table_test.cc
<filename>art/runtime/gc/accounting/mod_union_table_test.cc /* * Copyright (C) 2015 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. */ #include "mod_union_table-inl.h" #include "class_linker-inl.h" #include "common_runtime_test.h" #include "gc/space/space-inl.h" #include "mirror/array-inl.h" #include "space_bitmap-inl.h" #include "thread-inl.h" namespace art { namespace gc { namespace accounting { class ModUnionTableFactory { public: enum TableType { kTableTypeCardCache, kTableTypeReferenceCache, kTableTypeCount, // Number of values in the enum. }; // Target space is ignored for the card cache implementation. static ModUnionTable* Create( TableType type, space::ContinuousSpace* space, space::ContinuousSpace* target_space); }; class ModUnionTableTest : public CommonRuntimeTest { public: ModUnionTableTest() : java_lang_object_array_(nullptr) { } mirror::ObjectArray<mirror::Object>* AllocObjectArray( Thread* self, space::ContinuousMemMapAllocSpace* space, size_t component_count) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { auto* klass = GetObjectArrayClass(self, space); const size_t size = mirror::ComputeArraySize(component_count, 2); size_t bytes_allocated = 0, bytes_tl_bulk_allocated; auto* obj = down_cast<mirror::ObjectArray<mirror::Object>*>( space->Alloc(self, size, &bytes_allocated, nullptr, &bytes_tl_bulk_allocated)); if (obj != nullptr) { obj->SetClass(klass); obj->SetLength(static_cast<int32_t>(component_count)); space->GetLiveBitmap()->Set(obj); EXPECT_GE(bytes_allocated, size); } return obj; } void ResetClass() { java_lang_object_array_ = nullptr; } void RunTest(ModUnionTableFactory::TableType type); private: mirror::Class* GetObjectArrayClass(Thread* self, space::ContinuousMemMapAllocSpace* space) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { if (java_lang_object_array_ == nullptr) { java_lang_object_array_ = Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kObjectArrayClass); // Since the test doesn't have an image, the class of the object array keeps cards live // inside the card cache mod-union table and causes the check // ASSERT_FALSE(table->ContainsCardFor(reinterpret_cast<uintptr_t>(obj3))); // to fail since the class ends up keeping the card dirty. To get around this, we make a fake // copy of the class in the same space that we are allocating in. DCHECK(java_lang_object_array_ != nullptr); const size_t class_size = java_lang_object_array_->GetClassSize(); size_t bytes_allocated = 0, bytes_tl_bulk_allocated; auto* klass = down_cast<mirror::Class*>(space->Alloc(self, class_size, &bytes_allocated, nullptr, &bytes_tl_bulk_allocated)); DCHECK(klass != nullptr); memcpy(klass, java_lang_object_array_, class_size); Runtime::Current()->GetHeap()->GetCardTable()->MarkCard(klass); java_lang_object_array_ = klass; } return java_lang_object_array_; } mirror::Class* java_lang_object_array_; }; // Collect visited objects into container. static void CollectVisitedCallback(mirror::HeapReference<mirror::Object>* ref, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { DCHECK(ref != nullptr); DCHECK(arg != nullptr); reinterpret_cast<std::set<mirror::Object*>*>(arg)->insert(ref->AsMirrorPtr()); } // A mod union table that only holds references to a specified target space. class ModUnionTableRefCacheToSpace : public ModUnionTableReferenceCache { public: explicit ModUnionTableRefCacheToSpace( const std::string& name, Heap* heap, space::ContinuousSpace* space, space::ContinuousSpace* target_space) : ModUnionTableReferenceCache(name, heap, space), target_space_(target_space) {} bool ShouldAddReference(const mirror::Object* ref) const OVERRIDE { return target_space_->HasAddress(ref); } private: space::ContinuousSpace* const target_space_; }; std::ostream& operator<<(std::ostream& oss, ModUnionTableFactory::TableType type) { switch (type) { case ModUnionTableFactory::kTableTypeCardCache: { oss << "CardCache"; break; } case ModUnionTableFactory::kTableTypeReferenceCache: { oss << "ReferenceCache"; break; } default: { UNIMPLEMENTED(FATAL) << static_cast<size_t>(type); } } return oss; } ModUnionTable* ModUnionTableFactory::Create( TableType type, space::ContinuousSpace* space, space::ContinuousSpace* target_space) { std::ostringstream name; name << "Mod union table: " << type; switch (type) { case kTableTypeCardCache: { return new ModUnionTableCardCache(name.str(), Runtime::Current()->GetHeap(), space); } case kTableTypeReferenceCache: { return new ModUnionTableRefCacheToSpace(name.str(), Runtime::Current()->GetHeap(), space, target_space); } default: { UNIMPLEMENTED(FATAL) << "Invalid type " << type; } } return nullptr; } TEST_F(ModUnionTableTest, TestCardCache) { RunTest(ModUnionTableFactory::kTableTypeCardCache); } TEST_F(ModUnionTableTest, TestReferenceCache) { RunTest(ModUnionTableFactory::kTableTypeReferenceCache); } void ModUnionTableTest::RunTest(ModUnionTableFactory::TableType type) { Thread* const self = Thread::Current(); ScopedObjectAccess soa(self); Runtime* const runtime = Runtime::Current(); gc::Heap* const heap = runtime->GetHeap(); // Use non moving space since moving GC don't necessarily have a primary free list space. auto* space = heap->GetNonMovingSpace(); ResetClass(); // Create another space that we can put references in. std::unique_ptr<space::DlMallocSpace> other_space(space::DlMallocSpace::Create( "other space", 128 * KB, 4 * MB, 4 * MB, nullptr, false)); ASSERT_TRUE(other_space.get() != nullptr); heap->AddSpace(other_space.get()); std::unique_ptr<ModUnionTable> table(ModUnionTableFactory::Create( type, space, other_space.get())); ASSERT_TRUE(table.get() != nullptr); // Create some fake objects and put the main space and dirty cards in the non moving space. auto* obj1 = AllocObjectArray(self, space, CardTable::kCardSize); ASSERT_TRUE(obj1 != nullptr); auto* obj2 = AllocObjectArray(self, space, CardTable::kCardSize); ASSERT_TRUE(obj2 != nullptr); auto* obj3 = AllocObjectArray(self, space, CardTable::kCardSize); ASSERT_TRUE(obj3 != nullptr); auto* obj4 = AllocObjectArray(self, space, CardTable::kCardSize); ASSERT_TRUE(obj4 != nullptr); // Dirty some cards. obj1->Set(0, obj2); obj2->Set(0, obj3); obj3->Set(0, obj4); obj4->Set(0, obj1); // Dirty some more cards to objects in another space. auto* other_space_ref1 = AllocObjectArray(self, other_space.get(), CardTable::kCardSize); ASSERT_TRUE(other_space_ref1 != nullptr); auto* other_space_ref2 = AllocObjectArray(self, other_space.get(), CardTable::kCardSize); ASSERT_TRUE(other_space_ref2 != nullptr); obj1->Set(1, other_space_ref1); obj2->Set(3, other_space_ref2); table->ClearCards(); std::set<mirror::Object*> visited_before; table->UpdateAndMarkReferences(&CollectVisitedCallback, &visited_before); // Check that we visited all the references in other spaces only. ASSERT_GE(visited_before.size(), 2u); ASSERT_TRUE(visited_before.find(other_space_ref1) != visited_before.end()); ASSERT_TRUE(visited_before.find(other_space_ref2) != visited_before.end()); // Verify that all the other references were visited. // obj1, obj2 cards should still be in mod union table since they have references to other // spaces. ASSERT_TRUE(table->ContainsCardFor(reinterpret_cast<uintptr_t>(obj1))); ASSERT_TRUE(table->ContainsCardFor(reinterpret_cast<uintptr_t>(obj2))); // obj3, obj4 don't have a reference to any object in the other space, their cards should have // been removed from the mod union table during UpdateAndMarkReferences. ASSERT_FALSE(table->ContainsCardFor(reinterpret_cast<uintptr_t>(obj3))); ASSERT_FALSE(table->ContainsCardFor(reinterpret_cast<uintptr_t>(obj4))); { // Currently no-op, make sure it still works however. ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_); table->Verify(); } // Verify that dump doesn't crash. std::ostringstream oss; table->Dump(oss); // Set all the cards, then verify. table->SetCards(); // TODO: Check that the cards are actually set. for (auto* ptr = space->Begin(); ptr < AlignUp(space->End(), CardTable::kCardSize); ptr += CardTable::kCardSize) { ASSERT_TRUE(table->ContainsCardFor(reinterpret_cast<uintptr_t>(ptr))); } // Visit again and make sure the cards got cleared back to their sane state. std::set<mirror::Object*> visited_after; table->UpdateAndMarkReferences(&CollectVisitedCallback, &visited_after); // Check that we visited a superset after. for (auto* obj : visited_before) { ASSERT_TRUE(visited_after.find(obj) != visited_after.end()) << obj; } // Verify that the dump still works. std::ostringstream oss2; table->Dump(oss2); // Remove the space we added so it doesn't persist to the next test. heap->RemoveSpace(other_space.get()); } } // namespace accounting } // namespace gc } // namespace art
LukasHabring/api
java/src/org/thethingsnetwork/api/networkserver/NetworkServerGrpc.java
package org.thethingsnetwork.api.networkserver; import static io.grpc.MethodDescriptor.generateFullMethodName; import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall; import static io.grpc.stub.ClientCalls.asyncClientStreamingCall; import static io.grpc.stub.ClientCalls.asyncServerStreamingCall; import static io.grpc.stub.ClientCalls.asyncUnaryCall; import static io.grpc.stub.ClientCalls.blockingServerStreamingCall; import static io.grpc.stub.ClientCalls.blockingUnaryCall; import static io.grpc.stub.ClientCalls.futureUnaryCall; import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall; import static io.grpc.stub.ServerCalls.asyncClientStreamingCall; import static io.grpc.stub.ServerCalls.asyncServerStreamingCall; import static io.grpc.stub.ServerCalls.asyncUnaryCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall; /** */ @javax.annotation.Generated( value = "by gRPC proto compiler", comments = "Source: github.com/TheThingsNetwork/api/networkserver/networkserver.proto") public final class NetworkServerGrpc { private NetworkServerGrpc() {} public static final String SERVICE_NAME = "networkserver.NetworkServer"; // Static method descriptors that strictly reflect the proto. private static volatile io.grpc.MethodDescriptor<org.thethingsnetwork.api.networkserver.DevicesRequest, org.thethingsnetwork.api.networkserver.DevicesResponse> getGetDevicesMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "GetDevices", requestType = org.thethingsnetwork.api.networkserver.DevicesRequest.class, responseType = org.thethingsnetwork.api.networkserver.DevicesResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<org.thethingsnetwork.api.networkserver.DevicesRequest, org.thethingsnetwork.api.networkserver.DevicesResponse> getGetDevicesMethod() { io.grpc.MethodDescriptor<org.thethingsnetwork.api.networkserver.DevicesRequest, org.thethingsnetwork.api.networkserver.DevicesResponse> getGetDevicesMethod; if ((getGetDevicesMethod = NetworkServerGrpc.getGetDevicesMethod) == null) { synchronized (NetworkServerGrpc.class) { if ((getGetDevicesMethod = NetworkServerGrpc.getGetDevicesMethod) == null) { NetworkServerGrpc.getGetDevicesMethod = getGetDevicesMethod = io.grpc.MethodDescriptor.<org.thethingsnetwork.api.networkserver.DevicesRequest, org.thethingsnetwork.api.networkserver.DevicesResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetDevices")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( org.thethingsnetwork.api.networkserver.DevicesRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( org.thethingsnetwork.api.networkserver.DevicesResponse.getDefaultInstance())) .setSchemaDescriptor(new NetworkServerMethodDescriptorSupplier("GetDevices")) .build(); } } } return getGetDevicesMethod; } private static volatile io.grpc.MethodDescriptor<org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest, org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest> getPrepareActivationMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "PrepareActivation", requestType = org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest.class, responseType = org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest, org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest> getPrepareActivationMethod() { io.grpc.MethodDescriptor<org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest, org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest> getPrepareActivationMethod; if ((getPrepareActivationMethod = NetworkServerGrpc.getPrepareActivationMethod) == null) { synchronized (NetworkServerGrpc.class) { if ((getPrepareActivationMethod = NetworkServerGrpc.getPrepareActivationMethod) == null) { NetworkServerGrpc.getPrepareActivationMethod = getPrepareActivationMethod = io.grpc.MethodDescriptor.<org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest, org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "PrepareActivation")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest.getDefaultInstance())) .setSchemaDescriptor(new NetworkServerMethodDescriptorSupplier("PrepareActivation")) .build(); } } } return getPrepareActivationMethod; } private static volatile io.grpc.MethodDescriptor<org.thethingsnetwork.api.handler.DeviceActivationResponse, org.thethingsnetwork.api.handler.DeviceActivationResponse> getActivateMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "Activate", requestType = org.thethingsnetwork.api.handler.DeviceActivationResponse.class, responseType = org.thethingsnetwork.api.handler.DeviceActivationResponse.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<org.thethingsnetwork.api.handler.DeviceActivationResponse, org.thethingsnetwork.api.handler.DeviceActivationResponse> getActivateMethod() { io.grpc.MethodDescriptor<org.thethingsnetwork.api.handler.DeviceActivationResponse, org.thethingsnetwork.api.handler.DeviceActivationResponse> getActivateMethod; if ((getActivateMethod = NetworkServerGrpc.getActivateMethod) == null) { synchronized (NetworkServerGrpc.class) { if ((getActivateMethod = NetworkServerGrpc.getActivateMethod) == null) { NetworkServerGrpc.getActivateMethod = getActivateMethod = io.grpc.MethodDescriptor.<org.thethingsnetwork.api.handler.DeviceActivationResponse, org.thethingsnetwork.api.handler.DeviceActivationResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "Activate")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( org.thethingsnetwork.api.handler.DeviceActivationResponse.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( org.thethingsnetwork.api.handler.DeviceActivationResponse.getDefaultInstance())) .setSchemaDescriptor(new NetworkServerMethodDescriptorSupplier("Activate")) .build(); } } } return getActivateMethod; } private static volatile io.grpc.MethodDescriptor<org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage, org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage> getUplinkMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "Uplink", requestType = org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage.class, responseType = org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage, org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage> getUplinkMethod() { io.grpc.MethodDescriptor<org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage, org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage> getUplinkMethod; if ((getUplinkMethod = NetworkServerGrpc.getUplinkMethod) == null) { synchronized (NetworkServerGrpc.class) { if ((getUplinkMethod = NetworkServerGrpc.getUplinkMethod) == null) { NetworkServerGrpc.getUplinkMethod = getUplinkMethod = io.grpc.MethodDescriptor.<org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage, org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "Uplink")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage.getDefaultInstance())) .setSchemaDescriptor(new NetworkServerMethodDescriptorSupplier("Uplink")) .build(); } } } return getUplinkMethod; } private static volatile io.grpc.MethodDescriptor<org.thethingsnetwork.api.broker.DownlinkMessage, org.thethingsnetwork.api.broker.DownlinkMessage> getDownlinkMethod; @io.grpc.stub.annotations.RpcMethod( fullMethodName = SERVICE_NAME + '/' + "Downlink", requestType = org.thethingsnetwork.api.broker.DownlinkMessage.class, responseType = org.thethingsnetwork.api.broker.DownlinkMessage.class, methodType = io.grpc.MethodDescriptor.MethodType.UNARY) public static io.grpc.MethodDescriptor<org.thethingsnetwork.api.broker.DownlinkMessage, org.thethingsnetwork.api.broker.DownlinkMessage> getDownlinkMethod() { io.grpc.MethodDescriptor<org.thethingsnetwork.api.broker.DownlinkMessage, org.thethingsnetwork.api.broker.DownlinkMessage> getDownlinkMethod; if ((getDownlinkMethod = NetworkServerGrpc.getDownlinkMethod) == null) { synchronized (NetworkServerGrpc.class) { if ((getDownlinkMethod = NetworkServerGrpc.getDownlinkMethod) == null) { NetworkServerGrpc.getDownlinkMethod = getDownlinkMethod = io.grpc.MethodDescriptor.<org.thethingsnetwork.api.broker.DownlinkMessage, org.thethingsnetwork.api.broker.DownlinkMessage>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "Downlink")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( org.thethingsnetwork.api.broker.DownlinkMessage.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( org.thethingsnetwork.api.broker.DownlinkMessage.getDefaultInstance())) .setSchemaDescriptor(new NetworkServerMethodDescriptorSupplier("Downlink")) .build(); } } } return getDownlinkMethod; } /** * Creates a new async stub that supports all call types for the service */ public static NetworkServerStub newStub(io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<NetworkServerStub> factory = new io.grpc.stub.AbstractStub.StubFactory<NetworkServerStub>() { @java.lang.Override public NetworkServerStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkServerStub(channel, callOptions); } }; return NetworkServerStub.newStub(factory, channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static NetworkServerBlockingStub newBlockingStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<NetworkServerBlockingStub> factory = new io.grpc.stub.AbstractStub.StubFactory<NetworkServerBlockingStub>() { @java.lang.Override public NetworkServerBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkServerBlockingStub(channel, callOptions); } }; return NetworkServerBlockingStub.newStub(factory, channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static NetworkServerFutureStub newFutureStub( io.grpc.Channel channel) { io.grpc.stub.AbstractStub.StubFactory<NetworkServerFutureStub> factory = new io.grpc.stub.AbstractStub.StubFactory<NetworkServerFutureStub>() { @java.lang.Override public NetworkServerFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkServerFutureStub(channel, callOptions); } }; return NetworkServerFutureStub.newStub(factory, channel); } /** */ public static abstract class NetworkServerImplBase implements io.grpc.BindableService { /** * <pre> * Broker requests devices with DevAddr and matching FCnt (or disabled FCnt check) * </pre> */ public void getDevices(org.thethingsnetwork.api.networkserver.DevicesRequest request, io.grpc.stub.StreamObserver<org.thethingsnetwork.api.networkserver.DevicesResponse> responseObserver) { asyncUnimplementedUnaryCall(getGetDevicesMethod(), responseObserver); } /** * <pre> * Broker requests device activation "template" from Network Server * </pre> */ public void prepareActivation(org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest request, io.grpc.stub.StreamObserver<org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest> responseObserver) { asyncUnimplementedUnaryCall(getPrepareActivationMethod(), responseObserver); } /** * <pre> * Broker confirms device activation (after response from Handler) * </pre> */ public void activate(org.thethingsnetwork.api.handler.DeviceActivationResponse request, io.grpc.stub.StreamObserver<org.thethingsnetwork.api.handler.DeviceActivationResponse> responseObserver) { asyncUnimplementedUnaryCall(getActivateMethod(), responseObserver); } /** * <pre> * Broker informs Network Server about Uplink * </pre> */ public void uplink(org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage request, io.grpc.stub.StreamObserver<org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage> responseObserver) { asyncUnimplementedUnaryCall(getUplinkMethod(), responseObserver); } /** * <pre> * Broker informs Network Server about Downlink, NetworkServer may add MAC commands and re-set MIC * </pre> */ public void downlink(org.thethingsnetwork.api.broker.DownlinkMessage request, io.grpc.stub.StreamObserver<org.thethingsnetwork.api.broker.DownlinkMessage> responseObserver) { asyncUnimplementedUnaryCall(getDownlinkMethod(), responseObserver); } @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( getGetDevicesMethod(), asyncUnaryCall( new MethodHandlers< org.thethingsnetwork.api.networkserver.DevicesRequest, org.thethingsnetwork.api.networkserver.DevicesResponse>( this, METHODID_GET_DEVICES))) .addMethod( getPrepareActivationMethod(), asyncUnaryCall( new MethodHandlers< org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest, org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest>( this, METHODID_PREPARE_ACTIVATION))) .addMethod( getActivateMethod(), asyncUnaryCall( new MethodHandlers< org.thethingsnetwork.api.handler.DeviceActivationResponse, org.thethingsnetwork.api.handler.DeviceActivationResponse>( this, METHODID_ACTIVATE))) .addMethod( getUplinkMethod(), asyncUnaryCall( new MethodHandlers< org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage, org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage>( this, METHODID_UPLINK))) .addMethod( getDownlinkMethod(), asyncUnaryCall( new MethodHandlers< org.thethingsnetwork.api.broker.DownlinkMessage, org.thethingsnetwork.api.broker.DownlinkMessage>( this, METHODID_DOWNLINK))) .build(); } } /** */ public static final class NetworkServerStub extends io.grpc.stub.AbstractAsyncStub<NetworkServerStub> { private NetworkServerStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected NetworkServerStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkServerStub(channel, callOptions); } /** * <pre> * Broker requests devices with DevAddr and matching FCnt (or disabled FCnt check) * </pre> */ public void getDevices(org.thethingsnetwork.api.networkserver.DevicesRequest request, io.grpc.stub.StreamObserver<org.thethingsnetwork.api.networkserver.DevicesResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(getGetDevicesMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Broker requests device activation "template" from Network Server * </pre> */ public void prepareActivation(org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest request, io.grpc.stub.StreamObserver<org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest> responseObserver) { asyncUnaryCall( getChannel().newCall(getPrepareActivationMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Broker confirms device activation (after response from Handler) * </pre> */ public void activate(org.thethingsnetwork.api.handler.DeviceActivationResponse request, io.grpc.stub.StreamObserver<org.thethingsnetwork.api.handler.DeviceActivationResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(getActivateMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Broker informs Network Server about Uplink * </pre> */ public void uplink(org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage request, io.grpc.stub.StreamObserver<org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage> responseObserver) { asyncUnaryCall( getChannel().newCall(getUplinkMethod(), getCallOptions()), request, responseObserver); } /** * <pre> * Broker informs Network Server about Downlink, NetworkServer may add MAC commands and re-set MIC * </pre> */ public void downlink(org.thethingsnetwork.api.broker.DownlinkMessage request, io.grpc.stub.StreamObserver<org.thethingsnetwork.api.broker.DownlinkMessage> responseObserver) { asyncUnaryCall( getChannel().newCall(getDownlinkMethod(), getCallOptions()), request, responseObserver); } } /** */ public static final class NetworkServerBlockingStub extends io.grpc.stub.AbstractBlockingStub<NetworkServerBlockingStub> { private NetworkServerBlockingStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected NetworkServerBlockingStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkServerBlockingStub(channel, callOptions); } /** * <pre> * Broker requests devices with DevAddr and matching FCnt (or disabled FCnt check) * </pre> */ public org.thethingsnetwork.api.networkserver.DevicesResponse getDevices(org.thethingsnetwork.api.networkserver.DevicesRequest request) { return blockingUnaryCall( getChannel(), getGetDevicesMethod(), getCallOptions(), request); } /** * <pre> * Broker requests device activation "template" from Network Server * </pre> */ public org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest prepareActivation(org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest request) { return blockingUnaryCall( getChannel(), getPrepareActivationMethod(), getCallOptions(), request); } /** * <pre> * Broker confirms device activation (after response from Handler) * </pre> */ public org.thethingsnetwork.api.handler.DeviceActivationResponse activate(org.thethingsnetwork.api.handler.DeviceActivationResponse request) { return blockingUnaryCall( getChannel(), getActivateMethod(), getCallOptions(), request); } /** * <pre> * Broker informs Network Server about Uplink * </pre> */ public org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage uplink(org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage request) { return blockingUnaryCall( getChannel(), getUplinkMethod(), getCallOptions(), request); } /** * <pre> * Broker informs Network Server about Downlink, NetworkServer may add MAC commands and re-set MIC * </pre> */ public org.thethingsnetwork.api.broker.DownlinkMessage downlink(org.thethingsnetwork.api.broker.DownlinkMessage request) { return blockingUnaryCall( getChannel(), getDownlinkMethod(), getCallOptions(), request); } } /** */ public static final class NetworkServerFutureStub extends io.grpc.stub.AbstractFutureStub<NetworkServerFutureStub> { private NetworkServerFutureStub( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected NetworkServerFutureStub build( io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new NetworkServerFutureStub(channel, callOptions); } /** * <pre> * Broker requests devices with DevAddr and matching FCnt (or disabled FCnt check) * </pre> */ public com.google.common.util.concurrent.ListenableFuture<org.thethingsnetwork.api.networkserver.DevicesResponse> getDevices( org.thethingsnetwork.api.networkserver.DevicesRequest request) { return futureUnaryCall( getChannel().newCall(getGetDevicesMethod(), getCallOptions()), request); } /** * <pre> * Broker requests device activation "template" from Network Server * </pre> */ public com.google.common.util.concurrent.ListenableFuture<org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest> prepareActivation( org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest request) { return futureUnaryCall( getChannel().newCall(getPrepareActivationMethod(), getCallOptions()), request); } /** * <pre> * Broker confirms device activation (after response from Handler) * </pre> */ public com.google.common.util.concurrent.ListenableFuture<org.thethingsnetwork.api.handler.DeviceActivationResponse> activate( org.thethingsnetwork.api.handler.DeviceActivationResponse request) { return futureUnaryCall( getChannel().newCall(getActivateMethod(), getCallOptions()), request); } /** * <pre> * Broker informs Network Server about Uplink * </pre> */ public com.google.common.util.concurrent.ListenableFuture<org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage> uplink( org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage request) { return futureUnaryCall( getChannel().newCall(getUplinkMethod(), getCallOptions()), request); } /** * <pre> * Broker informs Network Server about Downlink, NetworkServer may add MAC commands and re-set MIC * </pre> */ public com.google.common.util.concurrent.ListenableFuture<org.thethingsnetwork.api.broker.DownlinkMessage> downlink( org.thethingsnetwork.api.broker.DownlinkMessage request) { return futureUnaryCall( getChannel().newCall(getDownlinkMethod(), getCallOptions()), request); } } private static final int METHODID_GET_DEVICES = 0; private static final int METHODID_PREPARE_ACTIVATION = 1; private static final int METHODID_ACTIVATE = 2; private static final int METHODID_UPLINK = 3; private static final int METHODID_DOWNLINK = 4; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final NetworkServerImplBase serviceImpl; private final int methodId; MethodHandlers(NetworkServerImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_GET_DEVICES: serviceImpl.getDevices((org.thethingsnetwork.api.networkserver.DevicesRequest) request, (io.grpc.stub.StreamObserver<org.thethingsnetwork.api.networkserver.DevicesResponse>) responseObserver); break; case METHODID_PREPARE_ACTIVATION: serviceImpl.prepareActivation((org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest) request, (io.grpc.stub.StreamObserver<org.thethingsnetwork.api.broker.DeduplicatedDeviceActivationRequest>) responseObserver); break; case METHODID_ACTIVATE: serviceImpl.activate((org.thethingsnetwork.api.handler.DeviceActivationResponse) request, (io.grpc.stub.StreamObserver<org.thethingsnetwork.api.handler.DeviceActivationResponse>) responseObserver); break; case METHODID_UPLINK: serviceImpl.uplink((org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage) request, (io.grpc.stub.StreamObserver<org.thethingsnetwork.api.broker.DeduplicatedUplinkMessage>) responseObserver); break; case METHODID_DOWNLINK: serviceImpl.downlink((org.thethingsnetwork.api.broker.DownlinkMessage) request, (io.grpc.stub.StreamObserver<org.thethingsnetwork.api.broker.DownlinkMessage>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } private static abstract class NetworkServerBaseDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { NetworkServerBaseDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return org.thethingsnetwork.api.networkserver.NetworkServerProto.getDescriptor(); } @java.lang.Override public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { return getFileDescriptor().findServiceByName("NetworkServer"); } } private static final class NetworkServerFileDescriptorSupplier extends NetworkServerBaseDescriptorSupplier { NetworkServerFileDescriptorSupplier() {} } private static final class NetworkServerMethodDescriptorSupplier extends NetworkServerBaseDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; NetworkServerMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getServiceDescriptor().findMethodByName(methodName); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (NetworkServerGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new NetworkServerFileDescriptorSupplier()) .addMethod(getGetDevicesMethod()) .addMethod(getPrepareActivationMethod()) .addMethod(getActivateMethod()) .addMethod(getUplinkMethod()) .addMethod(getDownlinkMethod()) .build(); } } } return result; } }
evelinamorim/cogroo4
cogroo-nlp/src/main/java/org/cogroo/tools/featurizer/DefaultFeaturizerContextGenerator.java
<gh_stars>10-100 /** * Copyright (C) 2012 cogroo <<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.cogroo.tools.featurizer; import java.text.NumberFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; import opennlp.tools.util.TokenTag; import opennlp.tools.util.featuregen.StringPattern; import opennlp.tools.util.featuregen.TokenClassFeatureGenerator; /** * A context generator for the Featurizer. */ public class DefaultFeaturizerContextGenerator implements FeaturizerContextGenerator { protected final String SE = "*SE*"; protected final String SB = "*SB*"; private static final int PREFIX_LENGTH = 4; private static final int SUFFIX_LENGTH = 4; private TokenClassFeatureGenerator tokenClassFeatureGenerator = new TokenClassFeatureGenerator(); // TODO: this is language dependent! private NumberFormat nf = NumberFormat.getInstance(new Locale("pt")); private boolean isWiderContext; private boolean isSuffixFeats; private boolean isHiphenedFeats; private boolean isNumberFeats; private boolean isClassFeatures; /** * Default is shnc * @param flags */ public DefaultFeaturizerContextGenerator(String flags) { this.isWiderContext = flags.contains("w"); this.isSuffixFeats = flags.contains("s"); this.isHiphenedFeats = flags.contains("h"); this.isNumberFeats = flags.contains("n"); this.isClassFeatures = flags.contains("c"); } protected static String[] getPrefixes(String lex) { String[] prefs = new String[PREFIX_LENGTH]; for (int li = 0, ll = PREFIX_LENGTH; li < ll; li++) { prefs[li] = lex.substring(0, Math.min(li + 1, lex.length())); } return prefs; } protected static String[] getSuffixes(String lex) { String[] suffs = new String[SUFFIX_LENGTH]; for (int li = 0, ll = SUFFIX_LENGTH; li < ll; li++) { suffs[li] = lex.substring(Math.max(lex.length() - li - 1, 0)); } return suffs; } public String[] getContext(int index, TokenTag[] sequence, String[] priorDecisions, Object[] additionalContext) { String[] w = TokenTag.extractTokens(sequence); String[] t = TokenTag.extractTags(sequence); return getContext(index, w, t, priorDecisions); } /** * Returns the context for making a pos tag decision at the specified token * index given the specified tokens and previous tags. * * @param i * The index of the token for which the context is provided. * @param toks * The tokens in the sentence. * @param tags * pos-tags * @param preds * The tags assigned to the previous words in the sentence. * @return The context for making a pos tag decision at the specified token * index given the specified tokens and previous tags. */ public String[] getContext(int i, String[] toks, String[] tags, String[] preds) { List<String> e = new ArrayList<String>(); if(isWiderContext) createWindowFeats(i, toks, tags, preds, e); else create3WindowFeats(i, toks, tags, preds, e); if(i > 0) wrappWindowFeatures("prev_", i-1, toks, tags, preds, e); wrappWindowFeatures("", i, toks, tags, preds, e); if(i < toks.length - 1) wrappWindowFeatures("nxt_", i+1, toks, tags, preds, e); String[] context = e.toArray(new String[e.size()]); return context; } private void wrappWindowFeatures(String prefix, int i, String[] toks, String[] tags, String[] preds, List<String> e) { String lex = toks[i]; List<String> features = new ArrayList<String>(); if(isClassFeatures) tokenClassFeatureGenerator.createFeatures(features, toks, i, preds); if(isNumberFeats) createNumberFeats(i, toks, features); boolean suffixesCollected = false; if(isHiphenedFeats) { if(lex.length() >= 3) { if (lex.contains("_")) { createGroupSuffixex("us_", lex, features); suffixesCollected = true; } if (lex.contains("-")) { createGroupSuffixex("hf_", lex, features); suffixesCollected = true; } } } if(!suffixesCollected && isSuffixFeats) { createSuffixFeats(i, toks, tags, preds, features); } for (String f : features) { e.add(prefix + f); } } private static final Pattern UNDERLINE_PATTERN = Pattern.compile("[_-]"); private void createGroupSuffixex(String pre, String lex, List<String> e) { String[] parts = UNDERLINE_PATTERN.split(lex); if (parts.length < 2) // this is handled already return; for (int i = 0; i < parts.length; i++) { e.add(pre + "up_" + i + "=" + parts[i]); String prefix = pre + "prsf_" + i + "="; String[] suffixes = getSuffixes(parts[i]); for (String suf : suffixes) { e.add(prefix + suf); } } } private void createNumberFeats(int i, String[] toks, List<String> e) { String lex = toks[i]; // numbers would benefit from this StringPattern sp = StringPattern.recognize(lex); if (sp.containsDigit() && !sp.containsLetters()) { // TODO: make it generic !! this is only for Portuguese! String num = lex; // we need only the decimal separator try { Number number = nf.parse(num); if (number != null) { Double value = Math.abs(number.doubleValue()); if (value >= 2) { e.add("num=h2"); } else if (value >= 1) { e.add("num=h1"); } else if (value > 0) { e.add("num=h0"); } else { e.add("num=zero"); } } else { e.add("numNull"); } } catch (ParseException e1) { // nothing to do... // System.err.println("failed to parse num: " + num); e.add("notNum"); } } } private void createSuffixFeats(int i, String[] toks, String[] tags, String[] preds, List<String> e) { String lex = toks[i]; // do some basic suffix analysis String[] suffs = getSuffixes(lex); for (int j = 0; j < suffs.length; j++) { e.add("suf=" + suffs[j]); } String[] prefs = getPrefixes(lex); for (int j = 0; j < prefs.length; j++) { e.add("pre=" + prefs[j]); } // see if the word has any special characters if (lex.indexOf('-') != -1) { e.add("h"); } } // 0.9674293472168595 private void createWindowFeats(int i, String[] toks, String[] tags, String[] preds, List<String> feats) { // Words in a 5-word window String w_2, w_1, w0, w1, w2; // Tags in a 5-word window String t_2, t_1, t0, t1, t2; // Previous predictions String p_2, p_1; w_2 = w_1 = w0 = w1 = w2 = null; t_2 = t_1 = t0 = t1 = t2 = null; p_1 = p_2 = null; if (i < 2) { w_2 = "w_2=bos"; t_2 = "t_2=bos"; p_2 = "p_2=bos"; } else { w_2 = "w_2=" + toks[i - 2]; t_2 = "t_2=" + tags[i - 2]; p_2 = "p_2" + preds[i - 2]; } if (i < 1) { w_1 = "w_1=bos"; t_1 = "t_1=bos"; p_1 = "p_1=bos"; } else { w_1 = "w_1=" + toks[i - 1]; t_1 = "t_1=" + tags[i - 1]; p_1 = "p_1=" + preds[i - 1]; } w0 = "w0=" + toks[i]; t0 = "t0=" + tags[i]; if (i + 1 >= toks.length) { w1 = "w1=eos"; t1 = "t1=eos"; } else { w1 = "w1=" + toks[i + 1]; t1 = "t1=" + tags[i + 1]; } if (i + 2 >= toks.length) { w2 = "w2=eos"; t2 = "t2=eos"; } else { w2 = "w2=" + toks[i + 2]; t2 = "t2=" + tags[i + 2]; } String[] features = new String[] { // add word features w_2, w_1, w0, w1, w2, w_1 + w0, w0 + w1, // add tag features t_2, t_1, t0, t1, t2, t_2 + t_1, t_1 + t0, t0 + t1, t1 + t2, t_2 + t_1 + t0, t_1 + t0 + t1, t0 + t1 + t2, // add pred tags p_2, p_1, p_2 + p_1, // add pred and tag p_1 + t_2, p_1 + t_1, p_1 + t0, p_1 + t1, p_1 + t2, p_1 + t_2 + t_1, p_1 + t_1 + t0, p_1 + t0 + t1, p_1 + t1 + t2, p_1 + t_2 + t_1 + t0, p_1 + t_1 + t0 + t1, p_1 + t0 + t1 + t2, // add pred and word p_1 + w_2, p_1 + w_1, p_1 + w0, p_1 + w1, p_1 + w2, p_1 + w_1 + w0, p_1 + w0 + w1 }; feats.addAll(Arrays.asList(features)); } //0.9670307770871996 private void create3WindowFeats(int i, String[] toks, String[] tags, String[] preds, List<String> feats) { // Words in a 5-word window String w_1, w0, w1; // Tags in a 5-word window String t_1, t0, t1; // Previous predictions String p_2, p_1; w0 = w1 = null; t_1 = t0 = t1 = null; p_1 = p_2 = null; if (i < 2) { p_2 = "p_2=bos"; } else { p_2 = "p_2" + preds[i - 2]; } if (i < 1) { w_1 = "w_1=bos"; t_1 = "t_1=bos"; p_1 = "p_1=bos"; } else { w_1 = "w_1=" + toks[i - 1]; t_1 = "t_1=" + tags[i - 1]; p_1 = "p_1=" + preds[i - 1]; } w0 = "w0=" + toks[i]; t0 = "t0=" + tags[i]; if (i + 1 >= toks.length) { w1 = "w1=eos"; t1 = "t1=eos"; } else { w1 = "w1=" + toks[i + 1]; t1 = "t1=" + tags[i + 1]; } String[] features = new String[] { // add word features w_1, w0, w1, w_1 + w0, w0 + w1, // add tag features t_1, t0, t1, t_1 + t0, t0 + t1, t_1 + t0 + t1, // add pred tags p_2, p_1, p_2 + p_1, // add pred and tag p_1 + t_1, p_1 + t0, p_1 + t1, p_1 + t_1 + t0, p_1 + t0 + t1, p_1 + t_1 + t0 + t1, // add pred and word p_1 + w_1, p_1 + w0, p_1 + w1, p_1 + w_1 + w0, p_1 + w0 + w1 }; feats.addAll(Arrays.asList(features)); } }
landv/golang-test
dog-tunnel/nat/nat.go
package nat import ( "errors" "net" "strings" "time" "golang-test/dog-tunnel/nat/stun" ) func Init(outIpList string, buster bool, id int, udpAddr string) (*AttemptEngine, error) { sock, err := net.ListenUDP("udp", &net.UDPAddr{}) if err != nil { return nil, err } engine := &AttemptEngine{sock: sock, buster: buster, id: id} if err := engine.init(outIpList, udpAddr); err != nil { return nil, err } return engine, nil } type attempt struct { candidate tid []byte timeout time.Time success bool // did we get a STUN response from this addr chosen bool // Has this channel been picked for the connection? localaddr net.Addr } type AttemptEngine struct { id int buster bool sock *net.UDPConn attempts []attempt local_attempts []attempt p2pconn net.Conn otherReady bool status string Kcp *KcpSetting D, P int } const probeTimeout = 500 * time.Millisecond const probeInterval = 100 * time.Millisecond const decisionTime = 2 * time.Second func (e *AttemptEngine) SetOtherAddrList(addrList string) { arr := strings.Split(addrList, "\n") e.attempts = make([]attempt, 0) for _, addrStr := range arr { if addrStr != "" { addr, err := net.ResolveUDPAddr("udp", addrStr) if err != nil { debug("resolve udp addr err", err.Error()) } else { e.attempts = append(e.attempts, attempt{candidate: candidate{Addr: addr}}) } } } } func (e *AttemptEngine) GetAddrList() string { tmp := "" for _, attempt := range e.local_attempts { tmp += attempt.Addr.String() + "\n" } return tmp } func (e *AttemptEngine) Fail() { e.status = "quit" if e.sock != nil { //debug("close udp sock") e.sock.Close() } } func (e *AttemptEngine) GetConn(f func(), encode, decode func([]byte) []byte) (net.Conn, error) { var conn net.Conn var err error if conn, err = e.run(f, encode, decode); err != nil { return nil, err } return conn, nil } func (e *AttemptEngine) init(outIpList string, udpAddr string) error { candidates, err := GatherCandidates(e.sock, outIpList, udpAddr) if err != nil { return err } e.local_attempts = make([]attempt, len(candidates)) for i := range candidates { e.local_attempts[i].candidate = candidates[i] debug("init addr", candidates[i].Addr.String()) } e.sock.SetWriteDeadline(time.Time{}) return nil } func (e *AttemptEngine) xmit() (time.Time, error) { now := time.Now() var ret time.Time var err error if e.p2pconn != nil { return ret, nil } for i := range e.attempts { if e.attempts[i].timeout.Before(now) { e.attempts[i].timeout = time.Now().Add(probeTimeout) e.attempts[i].tid, err = stun.RandomTid() if err != nil { return time.Time{}, err } packet, err := stun.BindRequest(e.attempts[i].tid, e.attempts[i].Addr, nil, false, e.attempts[i].chosen) if err != nil { return time.Time{}, err } //debug("===send", i,e.attempts[i].Addr.String()) e.sock.WriteToUDP(packet, e.attempts[i].Addr) for j := range e.local_attempts { if e.local_attempts[j].success { packet, err := stun.BindRequest(e.attempts[i].tid, e.attempts[i].Addr, nil, false, e.attempts[i].chosen) if err != nil { return time.Time{}, err } //debug("===send local", i,e.local_attempts[j].localaddr.String()) e.sock.WriteToUDP(packet, e.local_attempts[j].localaddr.(*net.UDPAddr)) } } } if ret.IsZero() || e.attempts[i].timeout.Before(ret) { ret = e.attempts[i].timeout } } return ret, nil } func (e *AttemptEngine) read() error { if e.status == "over" { return nil } buf := make([]byte, 512) n, from, err := e.sock.ReadFromUDP(buf) //println("read", n, from, err) if err != nil { if neterr, ok := err.(net.Error); ok && neterr.Timeout() { return nil } return err } if string(buf[0:n]) == "makeholeover" { if e.status == "wait" { debug("wait client !!!!!!! close") e.status = "over" e.sock.WriteToUDP([]byte("makeholeover2"), from) } return nil } if string(buf[0:n]) == "makeholeover2" { if e.status == "wait" { debug("wait server !!!!!!! close") e.status = "over" } return nil } //debug("========", string(buf[0:n])) packet, err := stun.ParsePacket(buf[:n], nil) if err != nil { return nil } if packet.Method != stun.MethodBinding { return nil } validAddr := packet.Addr for i := range e.local_attempts { my_local_addr := e.local_attempts[i].Addr //debug("check local",i, validAddr.String(), packet.Class, from.String(), my_local_addr.String()) if validAddr.String() == my_local_addr.String() { e.local_attempts[i].localaddr = from e.local_attempts[i].success = true //debug("find the addr from request", packet.Class, from.String()) if packet.Class == stun.ClassRequest { for j := range e.attempts { my_remote_addr := e.attempts[j].Addr response, err := stun.BindResponse(packet.Tid[:], my_remote_addr, nil, false) if err != nil { return nil } debug("write to succ", from.String(), j, my_remote_addr.String()) e.sock.WriteToUDP(response, from) } } else if packet.Class == stun.ClassSuccess { if e.p2pconn == nil { debug("make conn success", from.String(), e.local_attempts[i].localaddr.String()) e.p2pconn = newConn(e.sock, e.local_attempts[i].Addr, e.local_attempts[i].localaddr, e.id) if e.Kcp != nil { e.p2pconn.(*Conn).SetKcp(e.Kcp) } if e.D > 0 && e.P > 0 { e.p2pconn.(*Conn).SetFec(e.D, e.P) } for j := range e.attempts { my_remote_addr := e.attempts[j].Addr response, err := stun.InformReady(packet.Tid[:], my_remote_addr, nil) if err != nil { return nil } debug("write to ready", from.String(), j, my_remote_addr.String()) e.sock.WriteToUDP(response, from) } } } else if packet.Class == stun.ClassIndication { debug("recv other ready") e.otherReady = true /* for j := range e.attempts { debug("write !!!!!!", from.String(),j) e.sock.WriteToUDP([]byte("wocao,okokokook1!!"), from) }*/ } else if packet.Class == stun.ClassError { // debug("!!!!!!!!!!!!!") } } } return nil } func (e *AttemptEngine) run(f func(), encode, decode func([]byte) []byte) (net.Conn, error) { bInform := false beginTime := time.Now().Unix() for { if time.Now().Unix()-beginTime > 10 { e.status = "fail" } if e.status == "fail" || e.status == "quit" { break } timeout, err := e.xmit() if err != nil { return nil, err } if !bInform { f() bInform = true beginTime = time.Now().Unix() } e.sock.SetReadDeadline(timeout) if err = e.read(); err != nil { //return nil, err } if e.p2pconn != nil && e.otherReady { if e.buster && e.status == "" { debug("write final!!!!!!") e.sock.WriteToUDP([]byte("makeholeover"), e.p2pconn.RemoteAddr().(*net.UDPAddr)) } if e.status != "over" { e.status = "wait" } } if e.status == "over" { e.p2pconn.(*Conn).SetCrypt(encode, decode) e.p2pconn.(*Conn).Run() return e.p2pconn, nil } } return nil, errors.New(e.status) }
zshnb/qiangdongserver
src/main/java/com/qiangdong/reader/service/IBlockUserService.java
package com.qiangdong.reader.service; import com.qiangdong.reader.dto.BlockUserDto; import com.qiangdong.reader.entity.BlockUser; import com.baomidou.mybatisplus.extension.service.IService; import com.qiangdong.reader.request.BaseRequest; import com.qiangdong.reader.request.block_user.AddBlockUserRequest; import com.qiangdong.reader.request.block_user.DeleteBlockUserRequest; import com.qiangdong.reader.response.PageResponse; import com.qiangdong.reader.response.Response; import org.springframework.transaction.annotation.Transactional; /** * <p> * 服务类 * </p> * * @author <NAME> * @since 2020-07-27 */ public interface IBlockUserService extends IService<BlockUser> { @Transactional(rollbackFor = RuntimeException.class) Response<BlockUser> addBlockUser(AddBlockUserRequest request); @Transactional(rollbackFor = RuntimeException.class) Response<String> deleteBlockUser(DeleteBlockUserRequest request, BlockUser blockUser); PageResponse<BlockUserDto> listBlockUser(BaseRequest request); }
emarc99/SLib
src/slib/core/charset_windows.cpp
<reponame>emarc99/SLib /* * Copyright (c) 2008-2019 SLIBIO <https://github.com/SLIBIO> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "slib/core/definition.h" #ifdef SLIB_PLATFORM_IS_WINDOWS #include "slib/core/charset.h" #include <windows.h> namespace slib { namespace priv { namespace charset { sl_size Encode16(const sl_char16* utf16, sl_size lenUtf16, sl_uint32 codepage, void* output, sl_reg sizeOutputBuffer) { if (lenUtf16 && lenUtf16 <= 0x40000000 && sizeOutputBuffer != 0) { if (sizeOutputBuffer > 0x40000000) { sizeOutputBuffer = 0x40000000; } if (sizeOutputBuffer < 0) { sizeOutputBuffer = 0; } int ret = WideCharToMultiByte( (UINT)codepage, 0, // Flags (WCHAR*)utf16, (int)lenUtf16, (char*)output, (int)sizeOutputBuffer, NULL, // default char NULL // Flag used default char ); if (ret > 0) { return (sl_size)ret; } } return 0; } sl_size Decode16(sl_uint32 codepage, const void* input, sl_size sizeInput, sl_char16* utf16, sl_reg lenUtf16Buffer) { if (sizeInput && sizeInput <= 0x40000000 && lenUtf16Buffer != 0) { if (lenUtf16Buffer > 0x20000000) { lenUtf16Buffer = 0x20000000; } if (lenUtf16Buffer < 0) { lenUtf16Buffer = 0; } int ret = MultiByteToWideChar( (UINT)codepage, 0, // Flags (char*)input, (int)sizeInput, (WCHAR*)utf16, (int)lenUtf16Buffer ); if (ret) { return (sl_size)ret; } } return 0; } } } } #endif
dusenberrymw/IBM-SystemML
system-ml/src/test/java/com/ibm/bi/dml/test/integration/functions/unary/matrix/MatrixInverseTest.java
<reponame>dusenberrymw/IBM-SystemML<filename>system-ml/src/test/java/com/ibm/bi/dml/test/integration/functions/unary/matrix/MatrixInverseTest.java /** * (C) Copyright IBM Corp. 2010, 2015 * * 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.ibm.bi.dml.test.integration.functions.unary.matrix; import org.junit.Test; import com.ibm.bi.dml.api.DMLScript.RUNTIME_PLATFORM; import com.ibm.bi.dml.runtime.matrix.MatrixCharacteristics; import com.ibm.bi.dml.test.integration.AutomatedTestBase; import com.ibm.bi.dml.test.integration.TestConfiguration; public class MatrixInverseTest extends AutomatedTestBase { private final static String TEST_NAME = "Inverse"; private final static String TEST_DIR = "functions/unary/matrix/"; private final static int rows = 1001; private final static int cols = 1001; private final static double sparsity = 0.7; @Override public void setUp() { addTestConfiguration( TEST_NAME, new TestConfiguration(TEST_DIR, TEST_NAME, new String[] { "AI" }) ); // *** GENERATE data ONCE, and use it FOR ALL tests involving w/ different platforms // Therefore, data generation is done in setUp() method. TestConfiguration config = getTestConfiguration(TEST_NAME); String HOME = SCRIPT_DIR + TEST_DIR; fullDMLScriptName = HOME + TEST_NAME + ".dml"; programArgs = new String[]{"-args", HOME + INPUT_DIR + "A" , HOME + OUTPUT_DIR + config.getOutputFiles()[0] }; fullRScriptName = HOME + TEST_NAME + ".R"; rCmd = "Rscript" + " " + fullRScriptName + " " + HOME + INPUT_DIR + "A.mtx" + " " + HOME + EXPECTED_DIR + config.getOutputFiles()[0]; loadTestConfiguration(config); double[][] A = getRandomMatrix(rows, cols, 0, 1, sparsity, 10); MatrixCharacteristics mc = new MatrixCharacteristics(rows, cols, -1, -1, -1); writeInputMatrixWithMTD("A", A, true, mc); } @Test public void testInverseCP() { runTestMatrixInverse( RUNTIME_PLATFORM.SINGLE_NODE ); } @Test public void testInverseSP() { if(rtplatform == RUNTIME_PLATFORM.SPARK) runTestMatrixInverse( RUNTIME_PLATFORM.SPARK ); } @Test public void testInverseMR() { runTestMatrixInverse( RUNTIME_PLATFORM.HADOOP ); } @Test public void testInverseHybrid() { runTestMatrixInverse( RUNTIME_PLATFORM.HYBRID ); } private void runTestMatrixInverse( RUNTIME_PLATFORM rt ) { RUNTIME_PLATFORM rtold = rtplatform; rtplatform = rt; boolean exceptionExpected = false; runTest(true, exceptionExpected, null, -1); runRScript(true); compareResultsWithR(1e-5); rtplatform = rtold; } }
timothyhinrichs/opa
topdown/example_test.go
// Copyright 2016 The OPA Authors. All rights reserved. // Use of this source code is governed by an Apache2 // license that can be found in the LICENSE file. package topdown_test import ( "bytes" "context" "encoding/json" "fmt" "strings" "github.com/open-policy-agent/opa/ast" "github.com/open-policy-agent/opa/storage" "github.com/open-policy-agent/opa/topdown" "github.com/open-policy-agent/opa/topdown/builtins" "github.com/open-policy-agent/opa/types" ) func ExampleEval() { // Initialize context for the example. Normally the caller would obtain the // context from an input parameter or instantiate their own. ctx := context.Background() compiler := ast.NewCompiler() // Define a dummy query and some data that the query will execute against. query, err := compiler.QueryCompiler().Compile(ast.MustParseBody(`data.a[_] = x; x >= 2`)) if err != nil { // Handle error. } var data map[string]interface{} // OPA uses Go's standard JSON library but assumes that numbers have been // decoded as json.Number instead of float64. You MUST decode with UseNumber // enabled. decoder := json.NewDecoder(bytes.NewBufferString(`{"a": [1,2,3,4]}`)) decoder.UseNumber() if err := decoder.Decode(&data); err != nil { // Handle error. } // Instantiate the policy engine's storage layer. store := storage.New(storage.InMemoryWithJSONConfig(data)) // Create a new transaction. Transactions allow the policy engine to // evaluate the query over a consistent snapshot fo the storage layer. txn, err := store.NewTransaction(ctx) if err != nil { // Handle error. } defer store.Close(ctx, txn) // Prepare the evaluation parameters. Evaluation executes against the policy // engine's storage. In this case, we seed the storage with a single array // of number. Other parameters such as the input, tracing configuration, // etc. can be set on the Topdown object. t := topdown.New(ctx, query, compiler, store, txn) result := []interface{}{} // Execute the query and provide a callbakc function to accumulate the results. err = topdown.Eval(t, func(t *topdown.Topdown) error { // Each variable in the query will have an associated "binding". x := t.Binding(ast.Var("x")) // Alternatively, you can get a mapping of all bound variables. x = t.Vars()[ast.Var("x")] // The bindings are ast.Value types so we will convert to a native Go value here. v, err := ast.ValueToInterface(x, t) if err != nil { return err } result = append(result, v) return nil }) // Inspect the query result. fmt.Println("result:", result) fmt.Println("err:", err) // Output: // result: [2 3 4] // err: <nil> } func ExampleQuery() { // Initialize context for the example. Normally the caller would obtain the // context from an input parameter or instantiate their own. ctx := context.Background() compiler := ast.NewCompiler() // Define a dummy module with rules that produce documents that we will query below. module, err := ast.ParseModule("my_module.rego", `package opa.example p[x] { q[x]; not r[x] } q[y] { a = [1, 2, 3]; y = a[_] } r[z] { b = [2, 4]; z = b[_] }`, ) mods := map[string]*ast.Module{ "my_module": module, } if compiler.Compile(mods); compiler.Failed() { fmt.Println(compiler.Errors) } if err != nil { // Handle error. } // Instantiate the policy engine's storage layer. store := storage.New(storage.InMemoryConfig()) // Create a new transaction. Transactions allow the policy engine to // evaluate the query over a consistent snapshot fo the storage layer. txn, err := store.NewTransaction(ctx) if err != nil { // Handle error. } defer store.Close(ctx, txn) // Prepare query parameters. In this case, there are no additional documents // required by the policy so the input is nil. var input ast.Value params := topdown.NewQueryParams(ctx, compiler, store, txn, input, ast.MustParseRef("data.opa.example.p")) // Execute the query against "p". v1, err1 := topdown.Query(params) // Inspect the result. fmt.Println("v1:", v1[0].Result) fmt.Println("err1:", err1) // Output: // v1: [1 3] // err1: <nil> } func ExampleRegisterFunctionalBuiltin1() { // Rego includes a number of built-in functions ("built-ins") for performing // standard operations like string manipulation, regular expression // matching, and computing aggregates. // // This test shows how to add a new built-in to Rego and OPA. // Initialize context for the example. Normally the caller would obtain the // context from an input parameter or instantiate their own. ctx := context.Background() // The ast package contains a registry that enumerates the built-ins // included in Rego. When adding a new built-in, you must update the // registry to include your built-in. Otherwise, the compiler will complain // when it encounters your built-in. builtin := &ast.Builtin{ Name: ast.Var("selective_upper"), Args: []types.Type{ types.S, types.S, }, TargetPos: []int{1}, } ast.RegisterBuiltin(builtin) // This is the implementation of the built-in that will be called during // query evaluation. builtinImpl := func(a ast.Value) (ast.Value, error) { str, err := builtins.StringOperand(a, 1) if err != nil { return nil, err } if str.Equal(ast.String("magic")) { // topdown.BuiltinEmpty indicates to the evaluation engine that the // expression is false/not defined. return nil, topdown.BuiltinEmpty{} } return ast.String(strings.ToUpper(string(str))), nil } // See documentation for registering functions that take different numbers // of arguments. topdown.RegisterFunctionalBuiltin1(builtin.Name, builtinImpl) // At this point, the new built-in has been registered and can be used in // queries. Our custom built-in converts strings to upper case but is not // defined for the input "magic". compiler := ast.NewCompiler() query, err := compiler.QueryCompiler().Compile(ast.MustParseBody(`selective_upper("custom", x); not selective_upper("magic", "MAGIC")`)) if err != nil { // Handle error. } // Evaluate the query. t := topdown.New(ctx, query, compiler, nil, nil) topdown.Eval(t, func(t *topdown.Topdown) error { fmt.Println("x:", t.Binding(ast.Var("x"))) return nil }) // If you are adding new built-in functions to upstream OPA, you must also // update the [Language // Reference](http://www.openpolicyagent.org/documentation/references/language/) // and [How Do I Write // Policies](http://www.openpolicyagent.org/documentation/how-do-i-write-policies/) // documents. In addition, you must add tests for your new built-in. See the // existing integration tests in the topdown package. // Output: // // x: "CUSTOM" }
ajaypp123/DataStructure_Competative_Programing
Compatative_Programing/Graph/KruskalSpanningTree.java
<filename>Compatative_Programing/Graph/KruskalSpanningTree.java<gh_stars>0 /* Spanning Tree: - It is part of graph having V-1 edges and cover all points. - It is sub part of graph, there can be multiple combination possible. Minimum Cost Spanning Tree: - Spanning Tree whose edge cost is minimum called minimum cost spanning tree. Algorithm to find Minimum Cost Spanning Tree in Undirected graph: - Kruskal - Prims ================================================================================== Prims: - Here, select first sort edge from any source point. - Then keep select minimum adjecent edge, till selected count became V-1. - Skip edge if all point are already selected and not creating cycle. Kruskal: - Algorithm to find minimum cost spanning tree. - Here, we select edges having minimum cost, one by one till all node are visited. 1. Create visited array and all all edges to priority queue. 2. count = 0 3. while queue empty or count < V-1 if(any one point not visited and no cycle by considering edge) cost+= edge.cost count++ // AS it is for undirected graph we can use Uninon Find for cycle detection ========================================================================================== Complexity: Time: O(Edges * log(n)) // for each edge -> union find */ import java.util.*; class Edge implements Comparable<Edge>{ int src, dest, weight; public Edge(int src, int dest, int weight) { this.src = src; this.dest = dest; this.weight = weight; } public int compareTo(Edge e) { if(this.weight < e.weight) { return -1; } else if(this.weight > e.weight){ return 1; } else { return 0; } } @Override public String toString() { return "(" + src + ", " + dest + ", " + weight + ")"; } } public class KruskalSpanningTree { private static void makeSet(int[] parent, int[] rank) { for(int i=0; i<parent.length; i++) { parent[i] = i; } Arrays.fill(rank, 0); } private static void Union(int a, int b, int[] parent, int[] rank) { int x = Find(a, parent); int y = Find(b, parent); // If x==y, they already in same set if(x==y){return;} // make higher rank as parent and lower rank as child to keep low depth if(rank[x] > rank[y]) { parent[y] = x; } else if(rank[x] < rank[y]) { parent[x] = y; } else { // both have same rank so make any one as parent and increase rank parent[x] = y; rank[y] += 1; } } private static int Find(int x, int[] parent) { if(x == parent[x]) { return x; } return Find(parent[x], parent); } private static List<Edge> kruskalAlgo(List<Edge> edges, int N) { // Add all edge in priority queue PriorityQueue<Edge> pq = new PriorityQueue<>(); for(Edge e: edges) { pq.add(e); } // count edge selected int count = 0; int cost = 0; // makeset to detect cycle int[] parent = new int[N]; int[] rank = new int[N]; makeSet(parent, rank); // Add seleted edges in list List<Edge> list = new ArrayList<>(); while(pq.size()!=0 || count!=N-1) { Edge e = pq.remove(); int x = Find(e.src, parent); int y = Find(e.dest, parent); if(x!=y) { Union(x, y, parent, rank); list.add(e); cost += e.weight; count++; } } System.out.println("Minimum Cost Spanning Tree: " + cost); return list; } public static void main(String[] args) { // `(u, v, w)` triplet represent undirected edge from // vertex `u` to vertex `v` having weight `w` List<Edge> edges = Arrays.asList( new Edge(0, 1, 7), new Edge(1, 2, 8), new Edge(0, 3, 5), new Edge(1, 3, 9), new Edge(1, 4, 7), new Edge(2, 4, 5), new Edge(3, 4, 15), new Edge(3, 5, 6), new Edge(4, 5, 8), new Edge(4, 6, 9), new Edge(5, 6, 11) ); // total number of nodes in the graph final int N = 7; // construct graph List<Edge> e = kruskalAlgo(edges, N); System.out.println(e); } }
Simmesimme/illusion-3d
test/Core/TestProperty.cpp
<gh_stars>1-10 //////////////////////////////////////////////////////////////////////////////////////////////////// // // // _) | | _) This code may be used and modified under the terms // // | | | | | (_-< | _ \ \ of the MIT license. See the LICENSE file for details. // // _| _| _| \_,_| ___/ _| \___/ _| _| Copyright (c) 2018-2019 <NAME> // // // //////////////////////////////////////////////////////////////////////////////////////////////////// #include <Illusion/Core/Property.hpp> #include <doctest.h> namespace Illusion::Core { TEST_CASE("Illusion::Core::Property") { Double pDouble; Float pFloat; Int8 pInt8; Int16 pInt16; Int32 pInt32; Int64 pInt64; UInt8 pUInt8; UInt16 pUInt16; UInt32 pUInt32; UInt64 pUInt64; Bool pBool; String pString; FVec2 pFVec2; FVec3 pFVec3; FVec4 pFVec4; DVec2 pDVec2; DVec3 pDVec3; DVec4 pDVec4; IVec2 pIVec2; IVec3 pIVec3; IVec4 pIVec4; UVec2 pUVec2; UVec3 pUVec3; UVec4 pUVec4; FMat3 pFMat3; FMat4 pFMat4; DMat3 pDMat3; DMat4 pDMat4; SUBCASE("Checking default constructors") { CHECK(pDouble.get() == 0.0); CHECK(pFloat.get() == 0.f); CHECK(pInt8.get() == 0); CHECK(pInt16.get() == 0); CHECK(pInt32.get() == 0); CHECK(pInt64.get() == 0); CHECK(pUInt8.get() == 0u); CHECK(pUInt16.get() == 0u); CHECK(pUInt32.get() == 0u); CHECK(pUInt64.get() == 0u); CHECK(pBool.get() == false); CHECK(pString.get() == ""); CHECK(pFVec2.get() == glm::fvec2()); CHECK(pFVec3.get() == glm::fvec3()); CHECK(pFVec4.get() == glm::fvec4()); CHECK(pDVec2.get() == glm::dvec2()); CHECK(pDVec3.get() == glm::dvec3()); CHECK(pDVec4.get() == glm::dvec4()); CHECK(pIVec2.get() == glm::ivec2()); CHECK(pIVec3.get() == glm::ivec3()); CHECK(pIVec4.get() == glm::ivec4()); CHECK(pUVec2.get() == glm::uvec2()); CHECK(pUVec3.get() == glm::uvec3()); CHECK(pUVec4.get() == glm::uvec4()); CHECK(pFMat3.get() == glm::fmat3()); CHECK(pFMat4.get() == glm::fmat4()); CHECK(pDMat3.get() == glm::dmat3()); CHECK(pDMat4.get() == glm::dmat4()); } SUBCASE("Testing property connections") { Double otherDouble(42.0); pDouble.connectFrom(otherDouble); // There should be an initial value transfer. CHECK(pDouble.get() == 42.0); // When we set otherDouble, pDouble should reflect this change. otherDouble = -1.0; CHECK(pDouble.get() == -1.0); // When we disconnect again, pDouble should should not change anymore. pDouble.disconnect(); otherDouble = 128.0; CHECK(pDouble.get() == -1.0); // We can also disconnect the other way around. pDouble.connectFrom(otherDouble); otherDouble.disconnectAuditors(); otherDouble = 42.0; CHECK(pDouble.get() == 128.0); } } } // namespace Illusion::Core
shetouane/armitage-android-client
Armitage-Client/src/main/java/com/shetouane/armitage/structures/SessionCommandsAdapter.java
package com.shetouane.armitage.structures; import java.util.HashMap; import java.util.Map; import com.shetouane.armitage.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; public class SessionCommandsAdapter extends BaseAdapter implements Filterable { private static Map<String, SessionCommand> itemDetailsrrayList, originalFilter; private LayoutInflater l_Inflater; private Filter filter; //private Map<String, SessionCommand> filtered = new HashMap<String, SessionCommand>(); public SessionCommandsAdapter(Context context, Map<String, SessionCommand> results) { //filterMap(results); itemDetailsrrayList = results;//filtered; originalFilter = results;//filtered; l_Inflater = LayoutInflater.from(context); } /*private void filterMap(Map<String, SessionCommand> all) { filtered.clear(); for (Map.Entry<String, SessionCommand> entry : all.entrySet()) { if (entry.getValue().isImplemented()) filtered.put(entry.getKey(), entry.getValue()); } }*/ public int getCount() { try { return itemDetailsrrayList.size(); } catch (Exception e) { return 0; } } public Object getItem(int position) { return itemDetailsrrayList.values().toArray()[position]; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = l_Inflater.inflate(R.layout.sessioncommand_item, null); holder = new ViewHolder(); holder.txt_itemTitle = (TextView) convertView.findViewById(R.id.commandTitle); holder.txt_itemDisc = (TextView) convertView.findViewById(R.id.commandDisc); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.txt_itemTitle.setText(((SessionCommand)(itemDetailsrrayList.values().toArray()[position])).getTitle()); holder.txt_itemDisc.setText(((SessionCommand)(itemDetailsrrayList.values().toArray()[position])).getDescription()); return convertView; } static class ViewHolder { TextView txt_itemTitle; TextView txt_itemDisc; } @Override public Filter getFilter() { if (filter == null) { filter = new Filter() { @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { if (results.count == 0) { itemDetailsrrayList = originalFilter; notifyDataSetChanged(); // notifyDataSetInvalidated(); } else { itemDetailsrrayList = (Map<String, SessionCommand>) results.values; notifyDataSetChanged(); } } @Override protected FilterResults performFiltering(CharSequence constraint) { constraint = constraint.toString().toLowerCase(); FilterResults newFilterResults = new FilterResults(); if (constraint == null || constraint.length() == 0) { newFilterResults.count = originalFilter.size(); newFilterResults.values = originalFilter; } else { Map<String, SessionCommand> filteredList = new HashMap<String, SessionCommand>(); for (int i = 0; i < originalFilter.size(); i++) { SessionCommand item = (SessionCommand)(originalFilter.values().toArray()[i]); if (item.getTitle().toLowerCase().contains(constraint) || item.getDescription().toLowerCase().contains(constraint)) { filteredList.put(item.getCodename(), item); } } newFilterResults.count = filteredList.size(); newFilterResults.values = filteredList; } return newFilterResults; } }; } return filter; } }
vietnamz/quod_challange
src/test/java/fileutil/FileUtilTest.java
package fileutil; import github.Project; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.stream.Stream; public class FileUtilTest { @Test public void fileUtil_unzipfile_success() { Optional<String> outFile = FileUtil.gunzipIt("src/test/resources/test.json.gz"); } @Test public void fileUtil_unzipfile_failed_whenFileNotFound() { Optional<String> outFile = FileUtil.gunzipIt("src/test/resources/test1.json.gz"); if (!outFile.isPresent()) { System.out.println("Problem with unzip file"); } } @Test public void fileUtil_unzipfile_failed_whenWrongFormat() { Optional<String> outFile = FileUtil.gunzipIt("src/test/resources/test_fail.json.gz"); if (!outFile.isPresent()) { System.out.println("Problem with unzip file"); } } @Test public void fileUtil_getline_success() { Assert.assertEquals(11351, Stream.of(("src/test/resources/test.json")) .map(s -> FileUtil.getLines(s)) .peek(o -> { if (!o.isPresent()) { System.out.println("Problem with opening file"); } }) .filter(o -> o.isPresent()) .flatMap(o -> o.get()) .count()); } @Test public void fileUtil_getline_success_whenArrayFile() { Assert.assertEquals(11352, Arrays.asList("src/test/resources/test.json", "src/test/resources/test_individual_1.json").stream() .map(s -> FileUtil.getLines(s)) .peek(o -> { if (!o.isPresent()) { System.out.println("Problem with opening file"); } }) .filter(o -> o.isPresent()) .flatMap(o -> o.get()) .count()); } @Test public void fileUtil_writeOutToCSV_success() { Map<Long, Project> projects = new HashMap<>(); projects.put(1L, new Project(1L, "testOrg1", "Test1", 0.98F, 178784)); projects.put(2L, new Project(2L, "testOrg1", "Test1", 1.2F, 178784)); FileUtil.writeOutToCSV(projects, null); } }
LeonelMenendez/meetups
backend/src/main/java/io/github/lzmz/meetups/dto/response/InvitationDto.java
<reponame>LeonelMenendez/meetups package io.github.lzmz.meetups.dto.response; import io.github.lzmz.meetups.model.InvitationModel; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.time.LocalDate; @Getter @Setter public class InvitationDto implements Serializable { private long id; private long userId; private long meetupId; private String meetupOwnerName; private String meetupOwnerEmail; private LocalDate meetupDay; private double meetupTemperature; private InvitationModel.Status status; }
apaqi/sharkstore
proxy/store/dskv/rawkv.go
<reponame>apaqi/sharkstore package dskv import ( "model/pkg/kvrpcpb" "golang.org/x/net/context" ) func (p *KvProxy) RawPut(req *kvrpcpb.KvRawPutRequest) (*kvrpcpb.KvRawPutResponse, error) { in := &Request{ Type: Type_RawPut, RawPutReq: &kvrpcpb.DsKvRawPutRequest{ Header: &kvrpcpb.RequestHeader{}, Req: req, }, } bo := NewBackoffer(RawkvMaxBackoff, context.Background()) resp, _, err := p.do(bo, in, req.GetKey()) if err != nil { return nil, err } return resp.GetRawPutResp().GetResp(), nil } func (p *KvProxy) RawGet(req *kvrpcpb.KvRawGetRequest) (*kvrpcpb.KvRawGetResponse, error) { in := &Request{ Type: Type_RawGet, RawGetReq: &kvrpcpb.DsKvRawGetRequest{ Header: &kvrpcpb.RequestHeader{}, Req: req, }, } bo := NewBackoffer(RawkvMaxBackoff, context.Background()) resp, _, err := p.do(bo, in, req.GetKey()) if err != nil { return nil, err } return resp.GetRawGetResp().GetResp(), nil } func (p *KvProxy) RawDelete(req *kvrpcpb.KvRawDeleteRequest) (*kvrpcpb.KvRawDeleteResponse, error) { in := &Request{ Type: Type_RawDelete, RawDeleteReq: &kvrpcpb.DsKvRawDeleteRequest{ Header: &kvrpcpb.RequestHeader{}, Req: req, }, } bo := NewBackoffer(RawkvMaxBackoff, context.Background()) resp, _, err := p.do(bo, in, req.GetKey()) if err != nil { return nil, err } return resp.GetRawDeleteResp().GetResp(), nil }
qiangwushuang/ParaView
Plugins/pvNVIDIAIndeX/src/vtknvindex_instance.cxx
<filename>Plugins/pvNVIDIAIndeX/src/vtknvindex_instance.cxx /* Copyright 2020 NVIDIA Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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. */ #include "vtknvindex_instance.h" #include <cassert> #include <sstream> #ifdef _WIN32 #define NOMINMAX #include <windows.h> #else // _WIN32 #include <dlfcn.h> #include <ifaddrs.h> #include <netdb.h> #endif // _WIN32 #include "vtkMultiProcessController.h" #include "vtksys/SystemInformation.hxx" #include "vtksys/SystemTools.hxx" #include <nv/index/icolormap.h> #include <nv/index/iindex_debug_configuration.h> #include <nv/index/ilight.h> #include <nv/index/iscene.h> #include <nv/index/isession.h> #include <nv/index/version.h> #include "vtknvindex_affinity.h" #include "vtknvindex_colormap_utility.h" #include "vtknvindex_config_settings.h" #include "vtknvindex_forwarding_logger.h" #include "vtknvindex_host_properties.h" #include "vtknvindex_irregular_volume_importer.h" #include "vtknvindex_receiving_logger.h" #include "vtknvindex_sparse_volume_importer.h" #include "vtknvindex_volume_compute.h" namespace { #ifdef _WIN32 //------------------------------------------------------------------------------------------------- // Create a string with last error message static std::string get_last_error_as_str() { DWORD error = GetLastError(); if (error) { LPVOID lpMsgBuf; DWORD bufLen = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); if (bufLen) { LPCSTR lpMsgStr = (LPCSTR)lpMsgBuf; std::string result(lpMsgStr, lpMsgStr + bufLen); LocalFree(lpMsgBuf); return result; } } return std::string(); } #else std::string get_interface_address(const std::string interface_name, bool ipv6 = false) { std::string result; ifaddrs* if_list; if (getifaddrs(&if_list) == 0) { for (ifaddrs* i = if_list; i; i = i->ifa_next) { if (i->ifa_addr != 0 && i->ifa_name != 0 && ((i->ifa_addr->sa_family == AF_INET && !ipv6) || (i->ifa_addr->sa_family == AF_INET6 && ipv6)) && std::string(i->ifa_name) == interface_name) { char buf[1025]; int s = getnameinfo(i->ifa_addr, (i->ifa_addr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), buf, 1025, 0, 0, NI_NUMERICHOST); if (s == 0) { result = buf; break; } } } freeifaddrs(if_list); } return result; } #endif // _WIN32 } // namespace const std::string vtknvindex_instance::s_config_filename = "nvindex_config.xml"; //------------------------------------------------------------------------------------------------- vtknvindex_instance::vtknvindex_instance() : m_is_index_rank(false) , m_is_index_viewer(false) , m_is_index_initialized(false) , m_nvindex_colormaps(nullptr) { // Build cluster information build_cluster_info(); // Use one IndeX instance per host (running on the local rank 0) if (is_index_rank()) { // Load NVIDIA IndeX library if (!load_nvindex()) return; } } //------------------------------------------------------------------------------------------------- vtknvindex_instance::~vtknvindex_instance() { if (is_index_rank() && m_nvindex_interface) { // Shut down forwarding logger. vtknvindex::logger::vtknvindex_forwarding_logger_factory::delete_instance(); // Shut down the NVIDIA IndeX library. shutdown_nvindex(); // Unload the libraries. unload_nvindex(); } if (m_is_index_viewer && m_nvindex_colormaps) delete m_nvindex_colormaps; delete s_index_instance; } //------------------------------------------------------------------------------------------------- bool vtknvindex_instance::is_index_viewer() const { return m_is_index_viewer; } //------------------------------------------------------------------------------------------------- bool vtknvindex_instance::is_index_rank() const { return m_is_index_rank; } //------------------------------------------------------------------------------------------------- mi::Sint32 vtknvindex_instance::get_cur_local_rank_id() const { vtkMultiProcessController* controller = vtkMultiProcessController::GetGlobalController(); mi::Sint32 cur_rank_id = controller->GetLocalProcessId(); vtksys::SystemInformation sys_info; std::string cur_host = sys_info.GetHostname(); std::map<std::string, std::vector<mi::Sint32> >::const_iterator it = m_hostname_to_rankids.find(cur_host); if (it == m_hostname_to_rankids.end()) return -1; for (mi::Size j = 0; j < it->second.size(); ++j) { if (it->second[j] == cur_rank_id) return j; } return -1; } //------------------------------------------------------------------------------------------------- vtknvindex_instance* vtknvindex_instance::get() { return s_index_instance; } //------------------------------------------------------------------------------------------------- vtknvindex_instance* vtknvindex_instance::create() { return new vtknvindex_instance(); } //------------------------------------------------------------------------------------------------- void vtknvindex_instance::init_index() { // Start one IndeX instance per host (running on the local rank 0) if (m_nvindex_interface && !is_index_initialized() && is_index_rank()) { // Setup NVIDIA IndeX if (!setup_nvindex()) { return; } // Initialize IndeX session initialize_session(); // Initialize scene graph if (m_is_index_viewer) init_scene_graph(); m_is_index_initialized = true; } } //------------------------------------------------------------------------------------------------- bool vtknvindex_instance::is_index_initialized() const { return m_is_index_initialized; } //------------------------------------------------------------------------------------------------- mi::neuraylib::Tag vtknvindex_instance::get_perspective_camera() const { return m_perspective_camera_tag; } //------------------------------------------------------------------------------------------------- mi::neuraylib::Tag vtknvindex_instance::get_parallel_camera() const { return m_parallel_camera_tag; } //------------------------------------------------------------------------------------------------- vtknvindex_colormap* vtknvindex_instance::get_index_colormaps() const { return m_nvindex_colormaps; } //------------------------------------------------------------------------------------------------- mi::neuraylib::Tag vtknvindex_instance::get_slice_colormap() const { return m_slice_colormap_tag; } //------------------------------------------------------------------------------------------------- mi::neuraylib::Tag vtknvindex_instance::get_scene_geom_group() const { return m_geom_group_tag; } //------------------------------------------------------------------------------------------------- mi::base::Handle<nv::index::IIndex>& vtknvindex_instance::get_interface() { return m_nvindex_interface; } //------------------------------------------------------------------------------------------------- void vtknvindex_instance::build_cluster_info() { vtkMultiProcessController* controller = vtkMultiProcessController::GetGlobalController(); mi::Sint32 nb_ranks = controller->GetNumberOfProcesses(); // Gather all the rank ids. std::vector<mi::Sint32> rank_ids; rank_ids.resize(nb_ranks); mi::Sint32 cur_rank_id = controller->GetLocalProcessId(); controller->AllGather(&cur_rank_id, &rank_ids[0], 1); // Gather host names from all the ranks. std::vector<std::string> host_names; vtksys::SystemInformation sys_info; std::string cur_host_name = sys_info.GetHostname() + std::string(" "); char* all_hosts = (char*)calloc(nb_ranks, cur_host_name.length() + 1); controller->AllGather(cur_host_name.c_str(), all_hosts, cur_host_name.length()); std::string str(all_hosts); std::string buf; std::stringstream ss(str); while (ss >> buf) host_names.push_back(buf); free(all_hosts); controller->Barrier(); // Get host ranks distribution for (mi::Sint32 i = 0; i < nb_ranks; i++) m_hostname_to_rankids[host_names[i]].push_back(rank_ids[i]); // Find index ranks if (cur_rank_id == 0) { m_is_index_viewer = true; m_is_index_rank = true; } else { m_is_index_viewer = false; cur_host_name = sys_info.GetHostname(); std::map<std::string, std::vector<mi::Sint32> >::const_iterator it = m_hostname_to_rankids.find(cur_host_name); m_is_index_rank = (it != m_hostname_to_rankids.cend() && it->second[0] == cur_rank_id); } // Get host list m_host_list.clear(); for (mi::Uint32 i = 0; i < host_names.size(); ++i) { if (find(m_host_list.begin(), m_host_list.end(), host_names[i]) == m_host_list.end()) m_host_list.push_back(host_names[i]); } controller->Barrier(); } //------------------------------------------------------------------------------------------------- bool vtknvindex_instance::load_nvindex() { // Load shared libraries. const char* lib_name = "libnvindex" MI_BASE_DLL_FILE_EXT; const char* entry_point_name = "nv_index_factory"; void* index_lib_symbol = nullptr; #ifdef _WIN32 m_p_handle = LoadLibrary(TEXT(lib_name)); if (m_p_handle) index_lib_symbol = GetProcAddress((HMODULE)m_p_handle, entry_point_name); #else m_p_handle = dlopen(lib_name, RTLD_LAZY); if (m_p_handle) index_lib_symbol = dlsym(m_p_handle, entry_point_name); #endif if (!index_lib_symbol) { #ifdef _WIN32 const std::string error_str = get_last_error_as_str(); const std::string path_env = "PATH"; #else const std::string error_str = dlerror(); const std::string path_env = "LD_LIBRARY_PATH"; #endif ERROR_LOG << "Failed to load the NVIDIA IndeX library: '" << error_str << "'."; ERROR_LOG << "Please verify that the environment variable " << path_env << " contains the location of the NVIDIA IndeX libraries."; return false; } m_nvindexlib_fname = lib_name; typedef nv::index::IIndex*(IIndex_factory()); IIndex_factory* factory = (IIndex_factory*)index_lib_symbol; m_nvindex_interface = factory(); if (!m_nvindex_interface.is_valid_interface()) { ERROR_LOG << "Failed to initialize the NVIDIA IndeX library interface."; return false; } // Check that this IndeX library is compatible with this plugin version const std::string build_revision_str = NVIDIA_INDEX_LIBRARY_REVISION_STRING; const std::string library_revision_full_str = m_nvindex_interface->get_revision(); bool revision_mismatch = false; { // Extract just the revision, without build date and platform std::string library_revision_str = library_revision_full_str; const std::size_t pos = library_revision_str.find(','); if (pos != std::string::npos) { library_revision_str = library_revision_str.substr(0, pos); } revision_mismatch = (library_revision_str != build_revision_str); if (revision_mismatch) { // Split up revision into its components std::vector<std::string> library_revision; std::stringstream str(library_revision_str); while (str.good()) { std::string component; std::getline(str, component, '.'); library_revision.push_back(component); } std::vector<std::string> build_revision = { std::to_string( NVIDIA_INDEX_LIBRARY_REVISION_MAJOR) }; if (NVIDIA_INDEX_LIBRARY_REVISION_MINOR > 0) { build_revision.push_back(std::to_string(NVIDIA_INDEX_LIBRARY_REVISION_MINOR)); if (NVIDIA_INDEX_LIBRARY_REVISION_SUBMINOR > 0) { build_revision.push_back(std::to_string(NVIDIA_INDEX_LIBRARY_REVISION_SUBMINOR)); } } bool is_compatible = false; if (build_revision.size() == 1 || library_revision.size() == 1) { // No branch, meaning development version. Let's assume users know what they're doing. is_compatible = true; } else if (build_revision.size() != library_revision.size()) { is_compatible = false; } else if (build_revision.size() >= 2) { // It's a release branch, verify that the major revision is the same is_compatible = (build_revision[0] == library_revision[0]); } if (!is_compatible) { // Note that this doesn't automatically open the "Output Messages" window if it happens // during ParaView startup. The message will however become visible when another error is // later triggered in Render(). ERROR_LOG << "The loaded NVIDIA IndeX library build '" << library_revision_full_str << "' is not compatible with this plugin version '" << get_version() << "', which was built against revision '" << build_revision_str << "' " << "Please check your ParaView installation or get the matching IndeX libraries " << "from the ParaView dependencies repository: " << "https://www.paraview.org/files/dependencies/"; INFO_LOG << "Shutting down NVIDIA IndeX..."; m_nvindex_interface->shutdown(); m_nvindex_interface.reset(); unload_nvindex(); return false; } } } // Check for license and authenticate. const mi::Sint32 auth_result = authenticate_nvindex(); if (auth_result != 0) { ERROR_LOG << "Failed to authenticate NVIDIA IndeX library (result " << auth_result << "), please provide a valid license."; m_nvindex_interface->shutdown(); m_nvindex_interface.reset(); unload_nvindex(); return false; } // Initialize logging through NVIDIA IndeX. vtknvindex::logger::vtknvindex_forwarding_logger_factory::instance()->initialize( m_nvindex_interface); { mi::base::Handle<mi::neuraylib::ILogging_configuration> logging_configuration( m_nvindex_interface->get_api_component<mi::neuraylib::ILogging_configuration>()); assert(logging_configuration.is_valid_interface()); logging_configuration->set_log_locally(true); // local logging // Install the receiving logger. mi::base::Handle<mi::base::ILogger> receiving_logger(new vtknvindex_receiving_logger()); assert(receiving_logger.is_valid_interface()); logging_configuration->set_receiving_logger(receiving_logger.get()); } // Access and log NVIDIA IndeX version. INFO_LOG << "NVIDIA IndeX ParaView plugin " << get_version() << " " << (revision_mismatch ? "(compiled against " + build_revision_str + ") " : "") << "using NVIDIA IndeX library " << m_nvindex_interface->get_version() << " (build " << library_revision_full_str << ")."; return true; } //------------------------------------------------------------------------------------------------- bool vtknvindex_instance::unload_nvindex() { assert(m_p_handle != 0); #ifdef _WIN32 if (TRUE != FreeLibrary((HMODULE)m_p_handle)) { const std::string nvindex_fname = m_nvindexlib_fname; ERROR_LOG << "Failed to unload the NVIDIA IndeX library (" << nvindex_fname << ")."; return false; } #else // _WIN32 int result = dlclose(m_p_handle); if (result != 0) { ERROR_LOG << "Failed to unload the NVIDIA IndeX library: " << dlerror() << "."; return false; } #endif // _WIN32 return true; } //------------------------------------------------------------------------------------------------- mi::Sint32 vtknvindex_instance::authenticate_nvindex() { std::string index_vendor_key; std::string index_secret_key; bool found_license = false; // Try reading license from environment. const char* env_vendor_key = vtksys::SystemTools::GetEnv("NVINDEX_VENDOR_KEY"); const char* env_secret_key = vtksys::SystemTools::GetEnv("NVINDEX_SECRET_KEY"); if (env_vendor_key != nullptr && env_secret_key != nullptr) { index_vendor_key = env_vendor_key; index_secret_key = env_secret_key; found_license = (!index_vendor_key.empty() && !index_secret_key.empty()); if (found_license) { INFO_LOG << "Using NVIDIA IndeX license from environment variables NVINDEX_VENDOR_KEY and " << "NVINDEX_SECRET_KEY."; } } if (!found_license) { // Try reading license from config file. vtknvindex_xml_config_parser xml_parser; const std::string config_full_path = xml_parser.get_config_full_path(s_config_filename); if (xml_parser.open_config_file(s_config_filename)) { if (xml_parser.get_license_strings(index_vendor_key, index_secret_key)) { if (!index_vendor_key.empty() && !index_secret_key.empty()) { found_license = true; INFO_LOG << "Using NVIDIA IndeX license from configuration file '" << config_full_path << "'."; } else { ERROR_LOG << "Empty vendor or secret license key defined in '" << config_full_path << "', falling back to default license."; found_license = false; } } } } // No explicit license was specified, fall back to default license. if (!found_license) { #if (NVIDIA_INDEX_LIBRARY_REVISION_MAJOR > 327600) return 0; #else index_vendor_key = "NVIDIA IndeX License for Paraview IndeX:PV:Free:v1 - 20200427 (oem:retail_cloud.20220630)"; index_secret_key = "10e9ce315607f2d230e82647682d250a176ddd4e3d05c49401b5556a6794c72c"; #endif } // Retrieve Flex license path. std::string flexnet_lic_path; // Try reading Flex license path from environment. const char* env_flexnet_lic_path = vtksys::SystemTools::GetEnv("NVINDEX_FLEXNET_PATH"); if (env_flexnet_lic_path != nullptr) { flexnet_lic_path = env_flexnet_lic_path; } else // Try reading Flex license path from config file. { vtknvindex_xml_config_parser xml_parser; if (xml_parser.open_config_file(s_config_filename)) { xml_parser.get_flex_license_path(flexnet_lic_path); } } return m_nvindex_interface->authenticate(index_vendor_key.c_str(), static_cast<mi::Sint32>(index_vendor_key.length()), index_secret_key.c_str(), static_cast<mi::Sint32>(index_secret_key.length()), flexnet_lic_path.c_str(), static_cast<mi::Sint32>(flexnet_lic_path.length())); } //------------------------------------------------------------------------------------------------- bool vtknvindex_instance::setup_nvindex() { vtknvindex_xml_config_parser xml_parser; bool use_config_file = xml_parser.open_config_file(s_config_filename); // Configure networking before starting the IndeX library. mi::base::Handle<mi::neuraylib::INetwork_configuration> inetwork_configuration( m_nvindex_interface->get_api_component<mi::neuraylib::INetwork_configuration>()); assert(inetwork_configuration.is_valid_interface()); // Networking is off by default. inetwork_configuration->set_mode(mi::neuraylib::INetwork_configuration::MODE_OFF); if (m_host_list.size() > 1) { bool use_default_cluster_configuration = true; if (use_config_file) { std::map<std::string, std::string> network_params; if (xml_parser.get_section_settings(network_params, "network")) { std::map<std::string, std::string>::iterator it; // Cluster network mode (protocol). it = network_params.find("cluster_mode"); if (it != network_params.end()) { use_default_cluster_configuration = false; const std::string cluster_mode(it->second); if (cluster_mode == "OFF") { inetwork_configuration->set_mode(mi::neuraylib::INetwork_configuration::MODE_OFF); } else if (cluster_mode == "TCP") { // This is the default configuration use_default_cluster_configuration = true; } else if (cluster_mode == "UDP") { inetwork_configuration->set_mode(mi::neuraylib::INetwork_configuration::MODE_UDP); // Multicast address. it = network_params.find("multicast_address"); if (it != network_params.end()) { const std::string multicast_address(it->second); if (inetwork_configuration->set_multicast_address(multicast_address.c_str()) != 0) { ERROR_LOG << "Could not set the multicast address to value '" << multicast_address << "' specified in configuration file '" << s_config_filename << "'."; } } else { // Use default multicast address. const std::string multicast_address = "172.16.17.32"; WARN_LOG << "Using default multicast address " << multicast_address << "."; inetwork_configuration->set_multicast_address(multicast_address.c_str()); } } else if (cluster_mode == "TCP_WITH_DISCOVERY") { inetwork_configuration->set_mode( mi::neuraylib::INetwork_configuration::MODE_TCP_WITH_DISCOVERY); // Discovery address (required when cluster_mode is "TCP_WITH_DISCOVERY"). it = network_params.find("discovery_address"); if (it != network_params.end()) { const std::string discovery_address(it->second); if (inetwork_configuration->set_discovery_address(discovery_address.c_str()) != 0) { ERROR_LOG << "Could not set the discovery address to value '" << discovery_address << "' specified in configuration file '" << s_config_filename << "'."; } } else { // Use default discovery address: first host in the host list const std::string discovery_address = std::string(m_host_list[0].c_str()) + ":5555"; inetwork_configuration->set_discovery_address(discovery_address.c_str()); } } else { ERROR_LOG << "Unsupported value '" << cluster_mode << "' for 'cluster_mode' specified in configuration file '" << s_config_filename << "'."; } } // Cluster interface address. it = network_params.find("cluster_interface_address"); if (it != network_params.end()) { const std::string cluster_interface_address(it->second); if (inetwork_configuration->set_cluster_interface(cluster_interface_address.c_str()) != 0) { ERROR_LOG << "Could not set the cluster interface address to value '" << cluster_interface_address << "' specified in configuration file '" << s_config_filename << "'. " << "Please ensure to specify a network interface that is valid on all hosts."; } } // RDMA. it = network_params.find("use_rdma"); if (it != network_params.end()) { const std::string use_rdma(it->second); inetwork_configuration->set_use_rdma(use_rdma == "1" || use_rdma == "yes"); } // Set RDMA interface if (inetwork_configuration->get_use_rdma()) { it = network_params.find("rdma_interface"); if (it != network_params.end()) { const std::string rdma_interface(it->second); if (inetwork_configuration->set_rdma_interface(rdma_interface.c_str()) != 0) { ERROR_LOG << "Could not set the RDMA interface to value '" << rdma_interface << "' specified in configuration file '" << s_config_filename << "'."; } } #ifndef _WIN32 // Set alternative RDMA interface by name it = network_params.find("rdma_interface_by_name"); if (it != network_params.end()) { const std::string rdma_interface_name(it->second); const std::string rdma_interface_address = get_interface_address(rdma_interface_name); if (inetwork_configuration->set_rdma_interface(rdma_interface_address.c_str()) != 0) { ERROR_LOG << "Could not set the RDMA interface name to value '" << rdma_interface_name << "' specified in configuration file '" << s_config_filename << "'."; } } #endif // _WIN32 } } } if (use_default_cluster_configuration) { inetwork_configuration->set_mode(mi::neuraylib::INetwork_configuration::MODE_TCP); for (mi::Uint32 i = 0; i < m_host_list.size(); ++i) { inetwork_configuration->add_configured_host(m_host_list[i].c_str()); } } if (inetwork_configuration->get_mode() != mi::neuraylib::INetwork_configuration::MODE_OFF) { // Define service mode. mi::base::Handle<nv::index::ICluster_configuration> icluster_configuration( m_nvindex_interface->get_api_component<nv::index::ICluster_configuration>()); icluster_configuration->set_service_mode("rendering_and_compositing"); // Debug configuration. mi::base::Handle<mi::neuraylib::IDebug_configuration> idebug_configuration( m_nvindex_interface->get_api_component<mi::neuraylib::IDebug_configuration>()); assert(idebug_configuration.is_valid_interface()); { std::map<std::string, std::string> network_params; std::map<std::string, std::string>::iterator it; if (use_config_file) xml_parser.get_section_settings(network_params, "network"); // Setting max bandwidth. it = network_params.find("max_bandwidth"); if (it != network_params.end()) { std::string max_bandwidth = std::string("max_bandwidth=") + it->second; idebug_configuration->set_option(max_bandwidth.c_str()); } // Setting unicast nak interval. it = network_params.find("unicast_nak_interval"); if (it != network_params.end()) { std::string unicast_nak_interval = std::string("unicast_nak_interval=") + it->second; idebug_configuration->set_option(unicast_nak_interval.c_str()); } // Bandwidth increment. it = network_params.find("bandwidth_increment"); if (it != network_params.end()) { std::string bandwidth_increment = std::string("bandwidth_increment=") + it->second; idebug_configuration->set_option(bandwidth_increment.c_str()); } // Bandwidth decrement. it = network_params.find("bandwidth_decrement"); if (it != network_params.end()) { std::string bandwidth_decrement = std::string("bandwidth_decrement=") + it->second; idebug_configuration->set_option(bandwidth_decrement.c_str()); } // Retransmission interval. it = network_params.find("retransmission_interval"); if (it != network_params.end()) { std::string retransmission_interval = std::string("retransmission_interval=") + it->second; idebug_configuration->set_option(retransmission_interval.c_str()); } // Additional unicast sockets. it = network_params.find("additional_unicast_sockets"); if (it != network_params.end()) { std::string additional_unicast_sockets = std::string("additional_unicast_sockets=") + it->second; idebug_configuration->set_option(additional_unicast_sockets.c_str()); } // Retention time. it = network_params.find("retention"); if (it != network_params.end()) { std::string retention = std::string("retention=") + it->second; idebug_configuration->set_option(retention.c_str()); } // Alive factor. it = network_params.find("alive_factor"); if (it != network_params.end()) { std::string alive_factor = std::string("alive_factor=") + it->second; idebug_configuration->set_option(alive_factor.c_str()); } } } } { // Debug configuration. mi::base::Handle<nv::index::IIndex_debug_configuration> idebug_configuration( m_nvindex_interface->get_api_component<nv::index::IIndex_debug_configuration>()); assert(idebug_configuration.is_valid_interface()); #if (NVIDIA_INDEX_LIBRARY_REVISION_MAJOR > 327600) // Reduce log output idebug_configuration->set_option("debug_configuration_quiet=yes"); // Set optimized flags idebug_configuration->set_option("integration_flags=8"); #endif // Don't pre-allocate buffers for rasterizer idebug_configuration->set_option("rasterizer_memory_allocation=-1"); // Disable timeseries data prefetch. idebug_configuration->set_option("timeseries_data_prefetch_disable=1"); // Disable IndeX parallel importing, given importeres are already parallelized. idebug_configuration->set_option("async_subset_load=0"); // Use strict domain subdivision only with multiple ranks. if (vtkMultiProcessController::GetGlobalController()->GetNumberOfProcesses() > 1) idebug_configuration->set_option("use_strict_domain_subdivision=1"); #ifdef VTKNVINDEX_USE_KDTREE // Enable kd-tree affinity idebug_configuration->set_option("use_kdtree_subdivision=1"); // TODO: Should this be set based on the number of GPUs when no MPI. idebug_configuration->set_option("subdivision_parts=4"); #if 0 // Debug kd-tree idebug_configuration->set_option("debug_kdtree_subdivision=1"); idebug_configuration->set_option("dump_kdtree_subdivision=1"); #endif #endif // Use pinned memory for staging buffer (enabled by default). if (use_config_file) { std::map<std::string, std::string> index_params; if (xml_parser.get_section_settings(index_params, "index")) { std::map<std::string, std::string>::iterator it; it = index_params.find("use_pinned_staging_buffer"); if (it != index_params.end()) { std::string use_pinned_staging_buffer("svol_disable_pinned_staging_buffer="); if (it->second == std::string("1") || it->second == std::string("yes")) use_pinned_staging_buffer += std::string("1"); else use_pinned_staging_buffer += std::string("0"); idebug_configuration->set_option(use_pinned_staging_buffer.c_str()); } } } } // Register serializable classes. { bool is_registered = false; is_registered = m_nvindex_interface->register_serializable_class<vtknvindex_irregular_volume_importer>(); assert(is_registered); is_registered = m_nvindex_interface->register_serializable_class<vtknvindex_sparse_volume_importer>(); assert(is_registered); is_registered = m_nvindex_interface->register_serializable_class<vtknvindex_affinity>(); assert(is_registered); is_registered = m_nvindex_interface->register_serializable_class<vtknvindex_KDTree_affinity>(); assert(is_registered); is_registered = m_nvindex_interface->register_serializable_class<vtknvindex_volume_compute>(); assert(is_registered); } // Start the NVIDIA IndeX library. const mi::Uint32 start_result = m_nvindex_interface->start(true); if (start_result != 0) { ERROR_LOG << "Fatal: Could not start NVIDIA IndeX library (error code " << start_result << "), " << "see log messages above for details."; return false; } // Synchronize IndeX viewer with remote instances. if (inetwork_configuration->get_mode() != mi::neuraylib::INetwork_configuration::MODE_OFF) { // IndeX viewer must wait until the remote nodes are connected if (vtkMultiProcessController::GetGlobalController()->GetLocalProcessId() == 0) { mi::base::Handle<nv::index::ICluster_configuration> icluster_configuration( m_nvindex_interface->get_api_component<nv::index::ICluster_configuration>()); const mi::Uint32 cluster_size = static_cast<mi::Uint32>(m_host_list.size()); if (cluster_size > 0) { mi::Uint32 old_nb_hosts = 0; mi::Uint32 nb_hosts = 0; INFO_LOG << "Waiting until cluster size reaches " << cluster_size << " hosts"; while (nb_hosts < cluster_size) { nb_hosts = icluster_configuration->get_number_of_hosts(); if (nb_hosts > old_nb_hosts) { INFO_LOG << "Cluster now has " << nb_hosts << " host" << (nb_hosts == 1 ? "" : "s") << ", need " << (cluster_size - std::min(nb_hosts, cluster_size)) << " more to continue"; old_nb_hosts = nb_hosts; } else if (nb_hosts < old_nb_hosts) { INFO_LOG << "Aborting because at least one host has left - had " << old_nb_hosts << " hosts, only " << nb_hosts << " left"; return false; } vtknvindex::util::sleep(0.5f); } INFO_LOG << "Cluster size " << cluster_size << " reached, continuing..."; } } } return true; } //------------------------------------------------------------------------------------------------- bool vtknvindex_instance::shutdown_nvindex() { if (m_nvindex_interface.is_valid_interface()) { // Unregister receiving logger. mi::base::Handle<mi::neuraylib::ILogging_configuration> logging_configuration( m_nvindex_interface->get_api_component<mi::neuraylib::ILogging_configuration>()); logging_configuration->set_receiving_logger(0); } m_database = 0; m_global_scope = 0; m_iindex_session = 0; m_iindex_rendering = 0; m_icluster_configuration = 0; m_iindex_debug_configuration = 0; m_session_tag = mi::neuraylib::NULL_TAG; const mi::Sint32 nvindex_shutdown = m_nvindex_interface->shutdown(); if (nvindex_shutdown != 0) ERROR_LOG << "Failed to shutdown the NVIDIA IndeX library (code: " << nvindex_shutdown << ")."; m_nvindex_interface = 0; return nvindex_shutdown == 0; } //------------------------------------------------------------------------------------------------- void vtknvindex_instance::initialize_session() { { m_database = m_nvindex_interface->get_api_component<mi::neuraylib::IDatabase>(); assert(m_database.is_valid_interface()); m_global_scope = m_database->get_global_scope(); assert(m_global_scope.is_valid_interface()); m_iindex_session = m_nvindex_interface->get_api_component<nv::index::IIndex_session>(); assert(m_iindex_session.is_valid_interface()); m_iindex_rendering = m_nvindex_interface->create_rendering_interface(); assert(m_iindex_rendering.is_valid_interface()); m_icluster_configuration = m_nvindex_interface->get_api_component<nv::index::ICluster_configuration>(); assert(m_icluster_configuration.is_valid_interface()); m_iindex_debug_configuration = m_nvindex_interface->get_api_component<nv::index::IIndex_debug_configuration>(); assert(m_iindex_debug_configuration.is_valid_interface()); } { mi::base::Handle<mi::neuraylib::IDice_transaction> dice_transaction( m_global_scope->create_transaction<mi::neuraylib::IDice_transaction>()); assert(dice_transaction.is_valid_interface()); m_session_tag = m_iindex_session->create_session(dice_transaction.get()); assert(m_session_tag.is_valid()); dice_transaction->commit(); } } //------------------------------------------------------------------------------------------------- void vtknvindex_instance::init_scene_graph() { // DiCE database access. mi::base::Handle<mi::neuraylib::IDice_transaction> dice_transaction( m_global_scope->create_transaction<mi::neuraylib::IDice_transaction>()); assert(dice_transaction.is_valid_interface()); // Create scene graph { // Access the session instance from the database. mi::base::Handle<const nv::index::ISession> session( dice_transaction->access<const nv::index::ISession>(m_session_tag)); assert(session.is_valid_interface()); // Access (edit mode) the scene instance from the database. mi::base::Handle<nv::index::IScene> scene( dice_transaction->edit<nv::index::IScene>(session->get_scene())); assert(scene.is_valid_interface()); // Create volumes colormap mi::base::Handle<nv::index::IColormap> volume_colormap( scene->create_attribute<nv::index::IColormap>()); assert(volume_colormap.is_valid_interface()); m_volume_colormap_tag = dice_transaction->store_for_reference_counting( volume_colormap.get(), mi::neuraylib::NULL_TAG, "volume_colormap"); assert(m_volume_colormap_tag.is_valid()); // Create slices colormap mi::base::Handle<nv::index::IColormap> slice_colormap( scene->create_attribute<nv::index::IColormap>()); assert(volume_colormap.is_valid_interface()); m_slice_colormap_tag = dice_transaction->store_for_reference_counting( slice_colormap.get(), mi::neuraylib::NULL_TAG, "slice_colormap"); assert(m_slice_colormap_tag.is_valid()); // Create geom group, parent for all volumes and slices in the scene mi::base::Handle<nv::index::IStatic_scene_group> geom_group( scene->create_scene_group<nv::index::IStatic_scene_group>()); assert(geom_group.is_valid_interface()); m_geom_group_tag = dice_transaction->store_for_reference_counting( geom_group.get(), mi::neuraylib::NULL_TAG, "geom_group"); assert(m_geom_group_tag.is_valid()); // Create scene light (head light). mi::base::Handle<nv::index::IDirectional_headlight> light( scene->create_attribute<nv::index::IDirectional_headlight>()); mi::math::Vector_struct<mi::Float32, 3> light_direction = { 0, 0, 1 }; light->set_direction(light_direction); mi::math::Color_struct light_intensity = { 1, 1, 1 }; light->set_intensity(light_intensity); const mi::neuraylib::Tag light_tag = dice_transaction->store_for_reference_counting( light.get(), mi::neuraylib::NULL_TAG, "scene_light"); assert(light_tag.is_valid()); // Create colormaps groups mi::base::Handle<nv::index::IStatic_scene_group> colormaps_group( scene->create_scene_group<nv::index::IStatic_scene_group>()); assert(colormaps_group.is_valid_interface()); colormaps_group->append(m_slice_colormap_tag, dice_transaction.get()); const mi::neuraylib::Tag colormaps_group_tag = dice_transaction->store_for_reference_counting( colormaps_group.get(), mi::neuraylib::NULL_TAG, "colormaps_group"); assert(colormaps_group_tag.is_valid()); // Add all new created elements to scene graph scene->append(m_volume_colormap_tag, dice_transaction.get()); scene->append(light_tag, dice_transaction.get()); scene->append(m_geom_group_tag, dice_transaction.get()); scene->append(colormaps_group_tag, dice_transaction.get()); // Create perspective and parallel cameras to be exchangables. m_perspective_camera_tag = session->create_camera(dice_transaction.get(), nv::index::IPerspective_camera::IID()); assert(m_perspective_camera_tag.is_valid()); m_parallel_camera_tag = session->create_camera(dice_transaction.get(), nv::index::IOrthographic_camera::IID()); assert(m_parallel_camera_tag.is_valid()); } if (m_is_index_viewer) m_nvindex_colormaps = new vtknvindex_colormap(m_volume_colormap_tag, m_slice_colormap_tag); dice_transaction->commit(); } //------------------------------------------------------------------------------------------------- const char* vtknvindex_instance::get_version() const { return "5.9"; } //------------------------------------------------------------------------------------------------- vtknvindex_instance* vtknvindex_instance::s_index_instance = vtknvindex_instance::create();
yegor256/codexia
objects/projects.rb
<filename>objects/projects.rb # frozen_string_literal: true # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'loog' require 'veil' require_relative 'xia' require_relative 'project' require_relative 'rank' require_relative 'bots' require_relative 'sieve' # Projects. # Author:: <NAME> (<EMAIL>) # Copyright:: Copyright (c) 2020 <NAME> # License:: MIT class Xia::Projects def initialize(pgsql, author, log: Loog::NULL, telepost: Telepost::Fake.new) @pgsql = pgsql @author = author @log = log @telepost = telepost end def get(id) Xia::Sieve.new( Xia::Project.new(@pgsql, @author, id, log: @log, telepost: @telepost), :id, :coordinates, :platform, :created, :deleter, :submitter, :badges, :meta ) end def submit(platform, coordinates) Xia::Rank.new(@author).enter('projects.submit') Xia::Rank.new(@author).quota('project', 'submit') unless %r{^[A-Za-z0-9\-\.]+/[A-Za-z0-9\-_\.]+$}.match?(coordinates) raise Xia::Urror, "Coordinates #{coordinates.inspect} are wrong" end %w[ google facebook facebookresearch facebookincubator ibm oracle intel alibaba aws pivotal mozilla uber netflix ].each do |org| if %r{^#{org}/}i.match?(coordinates) raise Xia::Urror, "This project most likely is already sponsored by a large enterprise '#{org}'" end end raise Xia::Urror, 'The only possible platform now is "github"' unless platform == 'github' row = @pgsql.exec( 'SELECT id FROM project WHERE platform=$1 AND coordinates=$2', [platform, coordinates] )[0] return get(row['id'].to_i) unless row.nil? id = @pgsql.exec( 'INSERT INTO project (platform, coordinates, author) VALUES ($1, $2, $3) RETURNING id', [platform, coordinates, @author.id] )[0]['id'].to_i project = get(id) project.badges.attach('newbie') unless Xia::Bots.new.is?(@author) @telepost.spam( "😍 New #{platform} project [#{coordinates}](https://www.codexia.org/p/#{id}) has been submitted", "by [@#{@author.login}](https://www.codexia.org/a/#{@author.login})" ) end project end def recent(badges: [], limit: 10, offset: 0, show_deleted: false) terms = [] terms << 'p.deleter IS NULL' unless show_deleted terms << 'badge.text IN (' + badges.map { |b| "'#{b}'" }.join(',') + ')' unless badges.empty? q = [ 'SELECT DISTINCT p.*, author.login AS author_login, author.id AS author_id,', 'deleter.id AS deleter_id, deleter.login AS deleter_login,', 'ARRAY(SELECT CONCAT(id,\':\',text) FROM badge WHERE project=p.id) as badges,', '(SELECT COUNT(*) FROM review WHERE review.project=p.id) AS reviews_count', 'FROM project AS p', 'LEFT JOIN author AS deleter ON deleter.id=p.deleter', 'LEFT JOIN badge ON p.id=badge.project', 'JOIN author ON author.id=p.author', terms.empty? ? '' : 'WHERE ' + terms.join(' AND '), 'ORDER BY p.created DESC' ].join(' ') Veil.new( @pgsql.exec(q + ' LIMIT $1 OFFSET $2', [limit, offset]).map { |r| to_obj(r) }, count: @pgsql.exec("SELECT COUNT(*) FROM (#{q}) AS x")[0]['count'].to_i ) end def inbox(limit: 10, offset: 0) q = [ 'SELECT DISTINCT p.*, author.login AS author_login, author.id AS author_id,', 'deleter.id AS deleter_id, deleter.login AS deleter_login,', 'ARRAY(SELECT CONCAT(id,\':\',text) FROM badge WHERE project=p.id) as badges,', '(SELECT COUNT(*) FROM review WHERE review.project=p.id) AS reviews_count', 'FROM project AS p', 'LEFT JOIN badge ON p.id=badge.project', 'JOIN author ON author.id=p.author', 'LEFT JOIN author AS deleter ON deleter.id=p.deleter', 'LEFT JOIN seen ON p.id=seen.project AND seen.author=$1', 'WHERE seen.id IS NULL', 'ORDER BY p.created DESC' ].join(' ') Veil.new( @pgsql.exec(q + ' LIMIT $2 OFFSET $3', [@author.id, limit, offset]).map { |r| to_obj(r) }, count: @pgsql.exec("SELECT COUNT(*) FROM (#{q}) AS x", [@author.id])[0]['count'].to_i ) end private def to_obj(r) p = get(r['id'].to_i) Xia::Sieve.new( Veil.new( p, id: p.id, coordinates: r['coordinates'], platform: r['platform'], deleter: r['deleter_id'].nil? ? nil : Xia::Sieve.new( Veil.new( Xia::Author.new(@pgsql, r['deleter_id'].to_i, log: @log, telepost: @telepost), id: r['deleter_id'].to_i, login: r['deleter_login'] ), :id, :login ), created: Time.parse(r['created']), submitter: Xia::Sieve.new( Veil.new( Xia::Author.new(@pgsql, r['author_id'].to_i, log: @log, telepost: @telepost), id: r['author_id'].to_i, login: r['author_login'] ), :id, :login ), reviews_count: r['reviews_count'].to_i, badges: Xia::Sieve.new( Veil.new( Xia::Badges.new(@pgsql, p, log: @log), to_a: r['badges'][1..-2].split(',').map do |t| id, text = t.split(':', 2) Xia::Sieve.new( Veil.new( Xia::Badge.new(@pgsql, p, id, log: @log), id: id, text: text ), :id, :text ) end ), :to_a ) ), :id, :coordinates, :platform, :created, :deleter, :submitter, :badges, :reviews_count ) end end
KLumy/Basic-Algorithm
programmers/lv2/72411.py
from typing import List from collections import Counter from itertools import combinations def solution(orders: List[str], courses: List[int]) -> List[str]: answer = [] for c in courses: order = [] for o in orders: if c > len(o): continue order += combinations(sorted(o), c) c = Counter(order) if not c: continue m = max(c.values()) if m < 2: continue for course in filter(lambda x: c[x] == m, c.keys()): answer.append("".join(course)) answer.sort() return answer """ import collections import itertools def solution(orders, course): result = [] for course_size in course: order_combinations = [] for order in orders: order_combinations += itertools.combinations(sorted(order), course_size) most_ordered = collections.Counter(order_combinations).most_common() result += [ k for k, v in most_ordered if v > 1 and v == most_ordered[0][1] ] return [ ''.join(v) for v in sorted(result) ] """ if __name__ == "__main__": i = ["XYZ", "XWY", "WXA"] r = [2, 3, 4] print(solution(i, r))
ng-eneter/eneter-java
IntegrationTests/CalculatorClient/calculatorclient/program.java
<gh_stars>1-10 package calculatorclient; import java.io.BufferedReader; import java.io.InputStreamReader; import eneter.messaging.diagnostic.EneterTrace; import eneter.messaging.endpoints.typedmessages.*; import eneter.messaging.messagingsystems.composites.bufferedmessagingcomposit.BufferedMessagingFactory; import eneter.messaging.messagingsystems.messagingsystembase.*; import eneter.messaging.messagingsystems.tcpmessagingsystem.*; public class program { public static class RequestMessage { public int Number1; public int Number2; } public static class ResponseMessage { public int Result; } public static void main(String[] args) { try { // Create the synchronous message sender. // It will wait max 5 seconds for the response. // To wait infinite time use TimeSpan.FromMiliseconds(-1) or // default constructor new DuplexTypedMessagesFactory() IDuplexTypedMessagesFactory aSenderFactory = new DuplexTypedMessagesFactory() .setSyncResponseReceiveTimeout(2000); ISyncDuplexTypedMessageSender<ResponseMessage, RequestMessage> mySender = aSenderFactory.createSyncDuplexTypedMessageSender(ResponseMessage.class, RequestMessage.class); // Use Websocket for the communication. // If you want to use TCP then use TcpMessagingSystemFactory(). //IMessagingSystemFactory aMessaging = new WebSocketMessagingSystemFactory(); //IDuplexOutputChannel anOutputChannel = // aMessaging.CreateDuplexOutputChannel("ws://127.0.0.1:8099/Calculator/"); IMessagingSystemFactory aMessaging1 = new TcpMessagingSystemFactory(); IMessagingSystemFactory aMessaging = new BufferedMessagingFactory(aMessaging1, 20000); IDuplexOutputChannel anOutputChannel = aMessaging.createDuplexOutputChannel("tcp://127.0.0.1:4502/"); // Attach the output channel and be able to send messages // and receive response messages. mySender.attachDuplexOutputChannel(anOutputChannel); RequestMessage aRequest = new RequestMessage(); aRequest.Number1 = 10; aRequest.Number2 = 20; ResponseMessage aResponse = mySender.sendRequestMessage(aRequest); System.out.format("Result: %d", aResponse.Result); System.out.println("Restart the service."); new BufferedReader(new InputStreamReader(System.in)).readLine(); aRequest.Number1 = 1; aRequest.Number2 = 2; aResponse = mySender.sendRequestMessage(aRequest); System.out.format("Result: %d", aResponse.Result); mySender.detachDuplexOutputChannel(); } catch (Exception err) { EneterTrace.error("Detected exception", err); } } }
shreejitverma/GeeksforGeeks
LeetCode/C++/139. Word Break.cpp
<reponame>shreejitverma/GeeksforGeeks<gh_stars>1-10 //DP //Runtime: 28 ms, faster than 48.19% of C++ online submissions for Word Break. //Memory Usage: 10.8 MB, less than 61.87% of C++ online submissions for Word Break. //time: O(N^3), substr takes O(N) //space: O(N) class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { int n = s.size(); vector<bool> dp(n+1, false); //padding, assume empty string is a valid dictionary word dp[n] = true; for(int i = n-1; i >= 0; --i){ dp[i] = find(wordDict.begin(), wordDict.end(), s.substr(i)) != wordDict.end(); /* split s[i:] into s[i:j-1] and s[j:], and see if the split is valid */ for(int j = n; j >= i+1; --j){ //s[j:] is composed by valid dictionary words //and s[i:j-1] is a valid dictionary word dp[i] = dp[j] && find(wordDict.begin(), wordDict.end(), s.substr(i, j-i)) != wordDict.end(); if(dp[i]) break; } } return dp[0]; } }; //DP optimized from above //Runtime: 12 ms, faster than 79.03% of C++ online submissions for Word Break. //Memory Usage: 9.6 MB, less than 68.61% of C++ online submissions for Word Break. class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { int n = s.size(); vector<bool> dp(n+1, false); dp[n] = true; for(int i = n-1; i >= 0; --i){ for(int j = i+1; j <= n; ++j){ // cout << i << ", " << j << ", " << s.substr(i, j-i) << endl; if(dp[j] && find(wordDict.begin(), wordDict.end(), s.substr(i, j-i)) != wordDict.end()){ dp[i] = true; break; } } } return dp[0]; } }; //DP //https://leetcode.com/problems/concatenated-words/discuss/348972/Java-Common-template-Word-Break-I-Word-Break-II-Concatenated-Words //Runtime: 28 ms, faster than 49.06% of C++ online submissions for Word Break. //Memory Usage: 12.9 MB, less than 52.89% of C++ online submissions for Word Break. class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { int n = s.size(); //key: end index, 1-based vector<bool> dp(n+1, false); //empty string dp[0] = true; for(int end = 1; end <= n; ++end){ for(int start = 0; start < end; ++start){ //dp[start]: s[0...start-1] if(dp[start] && find(wordDict.begin(), wordDict.end(), s.substr(start, end-start)) != wordDict.end()){ //s[0...end-1] can be split into s[0...start-1] and s[start...end-1] dp[end] = true; break; } } } return dp[n]; } }; //trie //Runtime: 24 ms, faster than 56.77% of C++ online submissions for Word Break. //Memory Usage: 13.7 MB, less than 26.97% of C++ online submissions for Word Break. class TrieNode { public: vector<TrieNode*> children; bool end; TrieNode(){ children = vector<TrieNode*>(26, nullptr); end = false; } }; class Trie { public: TrieNode* root; Trie(){ root = new TrieNode(); } void add(string& word){ TrieNode* cur = root; for(char c : word){ if(!cur->children[c-'a']){ cur->children[c-'a'] = new TrieNode(); } cur = cur->children[c-'a']; } cur->end = true; } bool find(string word){ TrieNode* cur = root; for(char c : word){ if(!cur->children[c-'a']){ return false; } cur = cur->children[c-'a']; } return cur->end; } }; class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { int n = s.size(); vector<bool> dp(n+1, false); dp[n] = true; Trie* trie = new Trie(); for(string& word : wordDict){ trie->add(word); } for(int i = n-1; i >= 0; --i){ dp[i] = trie->find(s.substr(i)); for(int j = n; j >= i+1; --j){ dp[i] = dp[j] && trie->find(s.substr(i, j-i)); if(dp[i]) break; } } return dp[0]; } };
roscopecoltran/SniperKit-Core
.References/src/github.com/ndob/yarrar_u3d_ar_pipeline/src/yarrar/PipelineStage.h
<reponame>roscopecoltran/SniperKit-Core<gh_stars>0 #pragma once #include "Types.h" #include "Scene.h" #include "LockableData.h" #include <json11.hpp> #include <opencv2/opencv.hpp> #include <functional> #include <map> #include <vector> namespace yarrar { class PipelineStage { public: PipelineStage(const json11::Json& config){}; virtual ~PipelineStage(){}; }; class DataProvider : public PipelineStage { public: DataProvider(const json11::Json& config) : PipelineStage(config){}; virtual const LockableData<Datapoint>& getData() = 0; virtual Dimensions getDimensions() = 0; virtual DatatypeFlags provides() = 0; }; class Tracker : public PipelineStage { public: Tracker(const json11::Json& config) : PipelineStage(config){}; virtual DatatypeFlags depends() = 0; virtual void getPoses(const Datapoint& rawData, std::vector<Pose>& output) = 0; }; class SensorFusion : public PipelineStage { public: SensorFusion(const json11::Json& config) : PipelineStage(config){}; virtual void getFusedPoses(const std::vector<std::reference_wrapper<const LockableData<Datapoint>>>& datapoints, const std::map<size_t, std::vector<Pose>>& poseLists, std::vector<Pose>& output) = 0; }; class Renderer : public PipelineStage { public: Renderer(const json11::Json& config) : PipelineStage(config){}; virtual void loadModel(const Model& model) = 0; virtual void draw(const std::vector<Pose>& cameraPoses, const Scene& scene, const Datapoint& rawData) = 0; }; }
reels-research/iOS-Private-Frameworks
CloudPhotoLibrary.framework/CPLPushToTransportScopeTask.h
<gh_stars>1-10 /* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/CloudPhotoLibrary.framework/CloudPhotoLibrary */ @interface CPLPushToTransportScopeTask : CPLEngineScopedTask { NSMutableDictionary * _additionalTransportScopes; CPLChangeBatch * _batchToCommit; <CPLEngineTransportCheckRecordsExistenceTask> * _checkExistenceTask; unsigned long long _countOfPushedChanges; CPLBatchExtractionStrategy * _currentStrategy; NSString * _currentTaskKey; bool _deferredCancel; unsigned long long _estimatedCount; unsigned long long _estimatedSize; CPLExtractedBatch * _extractedBatch; bool _generatingSomeDerivatives; bool _hasCachedShouldCheckResourcesAhead; bool _hasDroppedSomeResources; bool _hasPushedSomeChanges; bool _highPriority; bool _isUsingOverQuotaStrategy; unsigned long long _lastReportedProgress; double _latestApproximativeUploadRate; NSObject<OS_dispatch_queue> * _lock; bool _mightPushSomeResources; NSError * _preparationError; CPLEnginePushRepository * _pushRepository; unsigned long long _recordCount; NSMutableDictionary * _recordsCopyingDerivativesFromSource; NSMutableSet * _recordsNeedingToBeFullyFetched; NSMutableDictionary * _recordsToCheckForExistence; NSMutableDictionary * _recordsWithForwardCompatibilityCheck; NSDictionary * _recordsWithGeneratedResources; NSMutableDictionary * _recordsWithResourcesToLookAhead; NSMutableDictionary * _recordsWithSparseResources; NSMutableDictionary * _recordsWithUntrustedCloudCache; bool _resetStrategy; CPLEngineScheduler * _scheduler; CPLEngineScopeStorage * _scopes; bool _shouldCheckResourcesAhead; bool _shouldResetExceedingQuotaOnSuccess; bool _shouldSetupEstimatedSize; double _startOfDerivativesGeneration; double _startOfIteration; long long _taskItem; NSDate * _taskStartDate; CPLEngineTransport * _transport; <CPLEngineTransportGroup> * _transportGroup; CPLChangeBatch * _uploadBatch; NSArray * _uploadResourceTasks; <CPLEngineTransportUploadBatchTask> * _uploadTask; } @property (nonatomic) bool highPriority; - (void).cxx_destruct; - (void)_checkForRecordExistence; - (void)_clearUploadBatch; - (void)_deleteGeneratedResourcesAfterError:(id)arg1; - (void)_detectUpdatesNeedingExistenceCheck:(id)arg1; - (void)_didFinishTaskWithKey:(id)arg1 error:(bool)arg2; - (void)_didStartTaskWithKey:(id)arg1 recordCount:(unsigned long long)arg2; - (bool)_discardUploadedExtractedBatchWithError:(id*)arg1; - (void)_doOneIteration; - (void)_generateDerivativesForNextRecord:(id)arg1; - (void)_generateNeededDerivatives; - (bool)_markUploadedTasksDidFinishWithError:(id)arg1 error:(id*)arg2; - (void)_popNextBatchAndContinue; - (bool)_prepareResourcesToUploadInBatch:(id)arg1 error:(id*)arg2; - (void)_prepareUploadBatchWithTransaction:(id)arg1 andStore:(id)arg2; - (void)_pushTaskDidFinishWithError:(id)arg1; - (bool)_reenqueueExtractedBatchWithRejectedRecords:(id)arg1 error:(id*)arg2; - (void)_requireExistenceCheckForRecords:(id)arg1; - (bool)_shouldCheckResourcesAheadForChange:(id)arg1; - (void)_updateChangeProperties:(id)arg1 withBaseChange:(id)arg2 withCopyProperty:(id /* block */)arg3; - (void)_updateQuotaStrategyAfterSuccessInTransaction:(id)arg1; - (void)_uploadBatch; - (void)cancel; - (void)cancel:(bool)arg1; - (bool)highPriority; - (id)initWithEngineLibrary:(id)arg1 clientCacheIdentifier:(id)arg2 scope:(id)arg3 transportScope:(id)arg4; - (void)launch; - (void)setHighPriority:(bool)arg1; - (id)taskIdentifier; @end
neerajkumar101/CustomEthereumTokenWalletApp
node_modules/dapple/lib/package_build_filter.js
<reponame>neerajkumar101/CustomEthereumTokenWalletApp 'use strict'; var _ = require('lodash'); module.exports = class PackageBuildFilter { filter (names) { if (!this.contractNames) return []; return _.intersection(this.contractNames, names); } seed (workspace, sources) { this.contractNames = []; let localSources = _.pickBy(sources, (_, path) => { return (path.startsWith(workspace.getSourcePath()) || path.startsWith('dapple')); }); // TODO: Find a clean way to share this regex with Linker. let contractRegex = /(^\s*(contract|library)\s*)([^\{\s]+)/gm; for (let path in localSources) { let source = localSources[path]; let match; while ((match = contractRegex.exec(source)) !== null) { this.contractNames.push(match[3]); } } } };
nagineni/chromium-crosswalk
cc/layers/contents_scaling_layer.cc
<gh_stars>100-1000 // Copyright 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. #include "cc/layers/contents_scaling_layer.h" #include "ui/gfx/size_conversions.h" namespace cc { gfx::Size ContentsScalingLayer::ComputeContentBoundsForScale( float scale_x, float scale_y) const { return gfx::ToCeiledSize(gfx::ScaleSize(bounds(), scale_x, scale_y)); } ContentsScalingLayer::ContentsScalingLayer() : last_update_contents_scale_x_(0.f), last_update_contents_scale_y_(0.f) {} ContentsScalingLayer::~ContentsScalingLayer() { } void ContentsScalingLayer::CalculateContentsScale( float ideal_contents_scale, float device_scale_factor, float page_scale_factor, bool animating_transform_to_screen, float* contents_scale_x, float* contents_scale_y, gfx::Size* content_bounds) { *contents_scale_x = ideal_contents_scale; *contents_scale_y = ideal_contents_scale; *content_bounds = ComputeContentBoundsForScale( ideal_contents_scale, ideal_contents_scale); } bool ContentsScalingLayer::Update( ResourceUpdateQueue* queue, const OcclusionTracker* occlusion) { bool updated = Layer::Update(queue, occlusion); if (draw_properties().contents_scale_x == last_update_contents_scale_x_ && draw_properties().contents_scale_y == last_update_contents_scale_y_) return updated; last_update_contents_scale_x_ = draw_properties().contents_scale_x; last_update_contents_scale_y_ = draw_properties().contents_scale_y; // Invalidate the whole layer if scale changed. SetNeedsDisplayRect(gfx::Rect(paint_properties().bounds)); return updated; } } // namespace cc
patrickb42/backend-vbb-portal
vbb_backend/program/api/serializers/slotStudent.py
<reponame>patrickb42/backend-vbb-portal from rest_framework import serializers from vbb_backend.program.models import StudentSlotAssociation from vbb_backend.users.models import Student from vbb_backend.users.api.serializers.user import UserBareMinimumSerializer from rest_framework.exceptions import ValidationError class StudentSlotBaseSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source="external_id", read_only=True) profile = UserBareMinimumSerializer(source="user") class Meta: model = Student exclude = ("deleted", "external_id") class StudentSlotListSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source="external_id", read_only=True) student = StudentSlotBaseSerializer(read_only=True) class Meta: model = StudentSlotAssociation exclude = ("deleted", "external_id", "slot") class StudentSlotSerializer(StudentSlotListSerializer): id = serializers.UUIDField(source="external_id", read_only=True) student = serializers.UUIDField(write_only=True, allow_null=False) class Meta: model = StudentSlotAssociation exclude = ("deleted", "slot", "external_id") def validate(self, attrs): # Clean up Attributes based on what the user can access if "student" in attrs: student = attrs.pop("student") student_obj = Student.objects.filter(external_id=student).first() if not student_obj: raise ValidationError( { "student": "Does not Exist. Are you sure the supplied value is a valid UUID" } ) attrs["program_director"] = student_obj return super().validate(attrs)
cosmin-ionita/Diploma-Project
SourceCode/Client/src/main/java/Commands/InitCommand.java
<filename>SourceCode/Client/src/main/java/Commands/InitCommand.java package Commands; import Exceptions.IncorrectParameterException; import Interfaces.Command; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class InitCommand implements Command { public void setParams(String[] params) throws IncorrectParameterException {} public void execute() { try { Process p = Runtime.getRuntime().exec("/bin/bash ./out/artifacts/Client_jar/script.sh"); System.out.println("loGrep was successfully initialized!"); }catch (IOException exception) { exception.printStackTrace(); } } }
wufeiafei/xuperunion
pluginmgr/pluginmgr.go
// Package pluginmgr is a plugin manager which keeps all plugins' instance // Notice: any plugin using this framework should implements // a func named 'GetInstance' to return there instance package pluginmgr import ( "encoding/json" "errors" "os" "path" "plugin" "github.com/xuperchain/log15" ) // PluginMgr defines the data struct of plugin manager type PluginMgr struct { pluginConf map[string]map[string]confNode xlog log.Logger rootFolder string } type confNode struct { SubType string `json:"subtype"` Path string `json:"path"` Version string `json:"version"` OnDemand bool `json:"ondemand"` } // public functions start from here // CreateMgr returns instance of PluginMgr func CreateMgr(rootFolder string, confPath string, logger log.Logger) (pm *PluginMgr, err error) { pm = new(PluginMgr) // init config struct pm.pluginConf = make(map[string]map[string]confNode) pm.xlog = logger pm.rootFolder = rootFolder // Read conf file to get all plugins err = pm.readPluginConfig(confPath) return } // CreatePluginInstance always create new plugin instance func (pm *PluginMgr) CreatePluginInstance(name string, subtype string) (pluginInstance interface{}, err error) { if _, ok := pm.pluginConf[name]; !ok { pm.xlog.Warn("Invalid plugin name", "name", name) return nil, errors.New("Invalid plugin name") } if _, ok := pm.pluginConf[name][subtype]; !ok { pm.xlog.Warn("Invalid plugin subtype", "name", name, "subtype", subtype) return nil, errors.New("Invalid plugin subtype") } return pm.loadOnePlugin(name, subtype) } // internal functions start from here func (pm *PluginMgr) readPluginConfig(confPath string) error { // get config file confPath = path.Join(pm.rootFolder, confPath) f, err := os.Open(confPath) if err != nil { pm.xlog.Warn("load plugin conf file failed, cannot open file", "confPath", confPath) return err } defer f.Close() tmpConf := make(map[string][]confNode) // read config decoder := json.NewDecoder(f) err = decoder.Decode(&tmpConf) if err != nil { pm.xlog.Warn("load plugin conf file failed while parsing") return err } pluginCount := 0 for pname, pconfs := range tmpConf { if pm.pluginConf[pname] == nil { pm.pluginConf[pname] = make(map[string]confNode) } for _, pconf := range pconfs { pm.pluginConf[pname][pconf.SubType] = pconf pluginCount++ } } pm.xlog.Trace("Plugin conf load successfully!", "pluginCount", pluginCount) return nil } func (pm *PluginMgr) loadOnePlugin(name string, subtype string) (pi interface{}, err error) { // open plugin conf := pm.pluginConf[name][subtype] pluginPath := path.Join(pm.rootFolder, conf.Path) pg, err := plugin.Open(pluginPath) if err != nil { pm.xlog.Warn("Warn: plugin open failed!", "pluginname", name, "err", err) err = errors.New("plugin open failed") return } // get instance iSymbol, err := pg.Lookup("GetInstance") if err != nil { pm.xlog.Warn("Warn: plugin don't have func named GetInstance!", "pluginname", name) err = errors.New("Invalid plugin, it doesn't meet our requirements") return } pi = iSymbol.(func() interface{})() pm.xlog.Trace("Load a plugin successfully", "name", name, "subtype", subtype) // TODO: verify the plugin's signature, make sure it's authorized by us return }
shalk/TIJ4Code
initialization/solution/Ex1.java
package initialization.solution; class Ex11 { String s; } public class Ex1 { public static void main(String[] args){ Ex11 a = new Ex11(); System.out.println(a.s); } }
Mopolino8/feltor
inc/dg/backend/functions.h
<reponame>Mopolino8/feltor #pragma once /*! @file * * Contains some utility functions for the evaluation() routines */ namespace dg{ ///@cond /** * @brief The delta function * * @param i Index * @param j Index * * @return delta_{ij} */ inline double delta( unsigned i, unsigned j) { if( i==j ) return 1.; return 0.; } /** * @brief Scalar product of two Legendre functions * * Corresponds to the S - Matrix * @param i Index of Legendre function * @param j Index of Legendre function * * @return L2 scalar product */ inline double pipj( unsigned i, unsigned j) { if( i==j) return 2./(2.*(double)i+1.); return 0; } /** * @brief Inverse of the scalar product matrix * * Corresponds to the T - Matrix * @param i Index of Legendre function * @param j Index of Legendre function * * @return Inverse of L2 scalar product */ inline double pipj_inv( unsigned i, unsigned j) { if( i==j) return (2.*(double)i+1.)/2.; return 0; } /** * @brief Scalar product between Legendre function and a derivative * * Corresponds to the D - Matrix * @param i Index of first Legendre function * @param j Index of second Legendre function * * @return Scalar product of p_i(x) and partial_x p_j(x) */ inline double pidxpj( unsigned i, unsigned j) { if( i < j) { if( (i+j)%2 == 0) return 0; else return 2; } return 0; } /** * @brief Evaluation of Legendre-functions left and right of an edge point * * Corresponds to the R - Matrix * @param i Index of first Legendre function * @param j Index of second Legendre function * * @return 1 */ inline double rirj( unsigned i, unsigned j) { return 1.; } /** * @brief Evaluation of Legendre-functions left and right of an edge point * * Corresponds to the RL - Matrix * @param i Index of first Legendre function * @param j Index of second Legendre function * * @return (-1)^j */ inline double rilj( unsigned i, unsigned j) { if( j%2==0) return 1.; return -1.; } /** * @brief Evaluation of Legendre-functions left and right of an edge point * * Corresponds to the LR - Matrix * @param i Index of first Legendre function * @param j Index of second Legendre function * * @return (-1)^i */ inline double lirj( unsigned i, unsigned j) { return rilj(j,i); } /** * @brief Evaluation of Legendre-functions left and right of an edge point * * Corresponds to the L - Matrix * @param i Index of first Legendre function * @param j Index of second Legendre function * * @return (-1)^{i+j} */ inline double lilj( unsigned i, unsigned j) { if( (i+j)%2 ==0) return 1.; return -1.; } ///@endcond ///@addtogroup functions ///@{ /** * @brief * \f[ f(x) = 1\f] * * Useful for integration. * @param x x-value * * @return 1 */ inline double one( double x) {return 1;} /** * @brief * \f[ f(x,y) = 1\f] * * Useful for integration. * @param x x-value * @param y y-value * * @return 1 */ inline double one( double x, double y) {return 1;} /** * @brief * \f[ f(x,y,z) = 1\f] * * Useful for integration. * @param x x-value * @param y x-value * @param z x-value * * @return 1 */ inline double one( double x, double y, double z) {return 1;} /** * @brief * \f[ f(x) = 0\f] * * Useful for integration. * @param x x-value * * @return 0 */ inline double zero( double x) {return 0.;} /** * @brief * \f[ f(x,y) = 0\f] * * Useful for integration. * @param x x-value * @param y y-value * * @return 0 */ inline double zero( double x, double y) {return 0.;} /** * @brief * \f[ f(x,y,z) = 0\f] * * Useful for integration. * @param x x-value * @param y x-value * @param z x-value * * @return 0 */ inline double zero( double x, double y, double z) {return 0.;} /** * @brief * \f[ f(x) = x\f] * * @param x * * @return */ double cooX1d( double x) {return x;} /** * @brief * \f[ f(x,y) = x\f] * * @param x * @param y * * @return */ double cooX2d( double x, double y) {return x;} /** * @brief * \f[ f(x,y,z) = x\f] * * @param x * @param y * @param z * * @return */ double cooX3d( double x, double y, double z) {return x;} /** * @brief * \f[ f(x,y) = y\f] * * @param x * @param y * * @return */ double cooY2d( double x, double y) {return y;} /** * @brief * \f[ f(x,y,z) = y\f] * * @param x * @param y * @param z * * @return */ double cooY3d( double x, double y, double z) {return y;} /** * @brief * \f[ f(x,y,z) = z\f] * * @param x * @param y * @param z * * @return */ double cooZ3d( double x, double y, double z) {return z;} } //namespace dg ///@}
sjdv1982/seamless
tests/highlevel/simpler-ipython.py
<reponame>sjdv1982/seamless from seamless.highlevel import Context, Transformer ctx = Context() ctx.a = 12 ipycode = """ %%timeit def triple_it(a): return 3 * a result = _ """ ctx.transform = Transformer() ctx.transform.language = "ipython" ctx.transform.code = ipycode ctx.transform.a = ctx.a ctx.transform.debug.direct_print = True ctx.myresult = ctx.transform ctx.compute() print(ctx.myresult.value) # None ctx.a = 13 ctx.compute() print(ctx.myresult.value) # None print(ctx.transform.status)
wereHuang/kripton
kripton-arch-integration/src/main/java/net/sqlcipher/database/SQLiteCursor.java
<reponame>wereHuang/kripton package net.sqlcipher.database; import android.content.ContentResolver; import android.database.CharArrayBuffer; import android.database.ContentObserver; import android.database.DataSetObserver; import android.net.Uri; import android.os.Bundle; import net.sqlcipher.Cursor; public class SQLiteCursor implements Cursor { public SQLiteCursor(SQLiteDatabase db, SQLiteCursorDriver masterQuery, String editTable, SQLiteQuery query) { // TODO Auto-generated constructor stub } @Override public int getCount() { // TODO Auto-generated method stub return 0; } @Override public int getPosition() { // TODO Auto-generated method stub return 0; } @Override public boolean move(int offset) { // TODO Auto-generated method stub return false; } @Override public boolean moveToPosition(int position) { // TODO Auto-generated method stub return false; } @Override public boolean moveToFirst() { // TODO Auto-generated method stub return false; } @Override public boolean moveToLast() { // TODO Auto-generated method stub return false; } @Override public boolean moveToNext() { // TODO Auto-generated method stub return false; } @Override public boolean moveToPrevious() { // TODO Auto-generated method stub return false; } @Override public boolean isFirst() { // TODO Auto-generated method stub return false; } @Override public boolean isLast() { // TODO Auto-generated method stub return false; } @Override public boolean isBeforeFirst() { // TODO Auto-generated method stub return false; } @Override public boolean isAfterLast() { // TODO Auto-generated method stub return false; } @Override public int getColumnIndex(String columnName) { // TODO Auto-generated method stub return 0; } @Override public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException { // TODO Auto-generated method stub return 0; } @Override public String getColumnName(int columnIndex) { // TODO Auto-generated method stub return null; } @Override public String[] getColumnNames() { // TODO Auto-generated method stub return null; } @Override public int getColumnCount() { // TODO Auto-generated method stub return 0; } @Override public byte[] getBlob(int columnIndex) { // TODO Auto-generated method stub return null; } @Override public String getString(int columnIndex) { // TODO Auto-generated method stub return null; } @Override public void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) { // TODO Auto-generated method stub } @Override public short getShort(int columnIndex) { // TODO Auto-generated method stub return 0; } @Override public int getInt(int columnIndex) { // TODO Auto-generated method stub return 0; } @Override public long getLong(int columnIndex) { // TODO Auto-generated method stub return 0; } @Override public float getFloat(int columnIndex) { // TODO Auto-generated method stub return 0; } @Override public double getDouble(int columnIndex) { // TODO Auto-generated method stub return 0; } @Override public boolean isNull(int columnIndex) { // TODO Auto-generated method stub return false; } @Override public void deactivate() { // TODO Auto-generated method stub } @Override public boolean requery() { // TODO Auto-generated method stub return false; } @Override public void close() { // TODO Auto-generated method stub } @Override public boolean isClosed() { // TODO Auto-generated method stub return false; } @Override public void registerContentObserver(ContentObserver observer) { // TODO Auto-generated method stub } @Override public void unregisterContentObserver(ContentObserver observer) { // TODO Auto-generated method stub } @Override public void registerDataSetObserver(DataSetObserver observer) { // TODO Auto-generated method stub } @Override public void unregisterDataSetObserver(DataSetObserver observer) { // TODO Auto-generated method stub } @Override public void setNotificationUri(ContentResolver cr, Uri uri) { // TODO Auto-generated method stub } @Override public Uri getNotificationUri() { // TODO Auto-generated method stub return null; } @Override public boolean getWantsAllOnMoveCalls() { // TODO Auto-generated method stub return false; } @Override public Bundle getExtras() { // TODO Auto-generated method stub return null; } @Override public Bundle respond(Bundle extras) { // TODO Auto-generated method stub return null; } @Override public int getType(int columnIndex) { // TODO Auto-generated method stub return 0; } }
mtheory101/hybrid-rendering-thesis
branches/rev71/Raytracer/OptixRender.h
#pragma once #include "../Scene/Quad.h" #include "../File/ShaderLoader.h" #include <Optix/optixu/optixpp_namespace.h> #include <memory> namespace Render { class GBuffer; typedef std::shared_ptr<GBuffer> GBufferPtr; } namespace Raytracer { class OptixRender; typedef std::shared_ptr<OptixRender> OptixRenderRenderPtr; class OptixRender { public: OptixRender(const Render::GBufferPtr &g_buffer, unsigned int w, unsigned int h, const std::string& baseDir); void render(); void reshape(unsigned int w, unsigned int h); private: Render::GBufferPtr g_buffer; unsigned int w; unsigned int h; optix::Context context; optix::Geometry sphere; optix::Material material; std::string baseDir; private: optix::Context createContext(); optix::Material createMaterial( optix::Context context ); optix::Geometry createGeometry( optix::Context context ); void createInstance( optix::Context context, optix::Geometry sphere, optix::Material material ); }; }
lstyles/nsgflowlogsbeat
vendor/github.com/elastic/beats/vendor/github.com/shirou/gopsutil/process/process_freebsd_amd64.go
// Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_freebsd.go package process const ( CTLKern = 1 KernProc = 14 KernProcPID = 1 KernProcProc = 8 KernProcPathname = 12 KernProcArgs = 7 ) const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 ) const ( sizeOfKinfoVmentry = 0x488 sizeOfKinfoProc = 0x440 ) const ( SIDL = 1 SRUN = 2 SSLEEP = 3 SSTOP = 4 SZOMB = 5 SWAIT = 6 SLOCK = 7 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int64 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur int64 Max int64 } type KinfoProc struct { Structsize int32 Layout int32 Args int64 /* pargs */ Paddr int64 /* proc */ Addr int64 /* user */ Tracep int64 /* vnode */ Textvp int64 /* vnode */ Fd int64 /* filedesc */ Vmspace int64 /* vmspace */ Wchan int64 Pid int32 Ppid int32 Pgid int32 Tpgid int32 Sid int32 Tsid int32 Jobc int16 Spare_short1 int16 Tdev uint32 Siglist [16]byte /* sigset */ Sigmask [16]byte /* sigset */ Sigignore [16]byte /* sigset */ Sigcatch [16]byte /* sigset */ Uid uint32 Ruid uint32 Svuid uint32 Rgid uint32 Svgid uint32 Ngroups int16 Spare_short2 int16 Groups [16]uint32 Size uint64 Rssize int64 Swrss int64 Tsize int64 Dsize int64 Ssize int64 Xstat uint16 Acflag uint16 Pctcpu uint32 Estcpu uint32 Slptime uint32 Swtime uint32 Cow uint32 Runtime uint64 Start Timeval Childtime Timeval Flag int64 Kiflag int64 Traceflag int32 Stat int8 Nice int8 Lock int8 Rqindex int8 Oncpu uint8 Lastcpu uint8 Tdname [17]int8 Wmesg [9]int8 Login [18]int8 Lockname [9]int8 Comm [20]int8 Emul [17]int8 Loginclass [18]int8 Sparestrings [50]int8 Spareints [7]int32 Flag2 int32 Fibnum int32 Cr_flags uint32 Jid int32 Numthreads int32 Tid int32 Pri Priority Rusage Rusage Rusage_ch Rusage Pcb int64 /* pcb */ Kstack int64 Udata int64 Tdaddr int64 /* thread */ Spareptrs [6]int64 Sparelongs [12]int64 Sflag int64 Tdflags int64 } type Priority struct { Class uint8 Level uint8 Native uint8 User uint8 } type KinfoVmentry struct { Structsize int32 Type int32 Start uint64 End uint64 Offset uint64 Vn_fileid uint64 Vn_fsid uint32 Flags int32 Resident int32 Private_resident int32 Protection int32 Ref_count int32 Shadow_count int32 Vn_type int32 Vn_size uint64 Vn_rdev uint32 Vn_mode uint16 Status uint16 X_kve_ispare [12]int32 Path [1024]int8 }
toofuns/codeituk-ccd-data-store-api
src/test/java/uk/gov/hmcts/ccd/v2/internal/controller/UIStartEventControllerCaseRolesIT.java
package uk.gov.hmcts.ccd.v2.internal.controller; import org.junit.Before; import org.junit.Test; import org.springframework.http.HttpHeaders; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import uk.gov.hmcts.ccd.MockUtils; import uk.gov.hmcts.ccd.WireMockBaseTest; import uk.gov.hmcts.ccd.domain.model.aggregated.CaseViewField; import uk.gov.hmcts.ccd.domain.model.definition.CaseFieldDefinition; import uk.gov.hmcts.ccd.v2.V2; import uk.gov.hmcts.ccd.v2.internal.resource.CaseUpdateViewEventResource; import javax.inject.Inject; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.springframework.http.HttpHeaders.AUTHORIZATION; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static uk.gov.hmcts.ccd.MockUtils.CASE_ROLE_CAN_CREATE; import static uk.gov.hmcts.ccd.MockUtils.CASE_ROLE_CAN_DELETE; import static uk.gov.hmcts.ccd.MockUtils.CASE_ROLE_CAN_READ; import static uk.gov.hmcts.ccd.MockUtils.CASE_ROLE_CAN_UPDATE; public class UIStartEventControllerCaseRolesIT extends WireMockBaseTest { private static final String GET_EVENT_TRIGGER_FOR_CASE_TYPE_INTERNAL = "/internal/case-types/CaseRolesCase/event-triggers/CREATE-CASE"; private static final String GET_EVENT_TRIGGER_FOR_CASE = "/internal/cases/1504259907353529/" + "/event-triggers/HAS_PRE_STATES_EVENT"; @Inject private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); } @Test public void internalGetStartCaseTrigger_200_shouldAddFieldsWithCreatorCaseRole() throws Exception { MockUtils.setSecurityAuthorities(authentication, MockUtils.ROLE_CASEWORKER_PUBLIC); HttpHeaders headers = new HttpHeaders(); headers.add(AUTHORIZATION, "Bearer user1"); headers.add(V2.EXPERIMENTAL_HEADER, "true"); final MvcResult result = mockMvc.perform(get(GET_EVENT_TRIGGER_FOR_CASE_TYPE_INTERNAL) .contentType(JSON_CONTENT_TYPE) .accept(V2.MediaType.CASE_TYPE_UPDATE_VIEW_EVENT) .headers(headers)) .andExpect(status().is(200)) .andReturn(); final CaseUpdateViewEventResource caseUpdateViewEventResource = mapper.readValue(result.getResponse().getContentAsString(), CaseUpdateViewEventResource.class); assertNotNull("UI Start Trigger Resource is null", caseUpdateViewEventResource); assertThat("Unexpected Case ID", caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseId(), is(nullValue())); assertEquals("Unexpected Event Name", "CREATE-CASE", caseUpdateViewEventResource.getCaseUpdateViewEvent().getName()); assertEquals("Unexpected Event Show Event Notes", true, caseUpdateViewEventResource.getCaseUpdateViewEvent().getShowEventNotes()); assertEquals("Unexpected Event Description", "Creation event", caseUpdateViewEventResource.getCaseUpdateViewEvent().getDescription()); assertEquals("Unexpected Case Fields", 1, caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseFields().size()); final CaseViewField field1 = caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseFields().get(0); assertThat(field1.getId(), equalTo("PersonFirstName")); assertThat(field1.getAccessControlLists().get(0).getRole(), equalTo("caseworker-probate-public")); assertThat(field1.getAccessControlLists().get(0).isCreate(), is(false)); assertThat(field1.getAccessControlLists().get(0).isRead(), is(false)); assertThat(field1.getAccessControlLists().get(0).isUpdate(), is(false)); assertThat(field1.getAccessControlLists().get(0).isDelete(), is(false)); assertThat(field1.getAccessControlLists().get(1).getRole(), equalTo("[CREATOR]")); assertThat(field1.getAccessControlLists().get(1).isCreate(), is(true)); assertThat(field1.getAccessControlLists().get(1).isRead(), is(true)); assertThat(field1.getAccessControlLists().get(1).isUpdate(), is(true)); assertThat(field1.getAccessControlLists().get(1).isDelete(), is(false)); } @Test public void internalGetStartCaseTrigger_200_shouldSetCollectionDisplayContextParameterForCreateCaseRole() throws Exception { MockUtils.setSecurityAuthorities(authentication, MockUtils.ROLE_CASEWORKER_PUBLIC, CASE_ROLE_CAN_CREATE); HttpHeaders headers = new HttpHeaders(); headers.add(AUTHORIZATION, "Bearer user1"); headers.add(V2.EXPERIMENTAL_HEADER, "true"); final MvcResult result = mockMvc.perform(get(GET_EVENT_TRIGGER_FOR_CASE_TYPE_INTERNAL) .contentType(JSON_CONTENT_TYPE) .accept(V2.MediaType.CASE_TYPE_UPDATE_VIEW_EVENT) .headers(headers)) .andExpect(status().is(200)) .andReturn(); final CaseUpdateViewEventResource caseUpdateViewEventResource = mapper.readValue(result.getResponse().getContentAsString(), CaseUpdateViewEventResource.class); assertNotNull("UI Start Trigger Resource is null", caseUpdateViewEventResource); assertEquals("Unexpected Case Fields", 2, caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseFields().size()); final CaseViewField children = caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseFields().get(1); assertThat(children.getFieldTypeDefinition().getType(), equalTo("Collection")); assertThat(children.getDisplayContextParameter(), equalTo("#COLLECTION(allowInsert)")); final CaseFieldDefinition hobby = children.getFieldTypeDefinition().getCollectionFieldTypeDefinition().getChildren().get(1); assertThat(hobby.getId(), equalTo("hobbies")); assertThat(hobby.getDisplayContextParameter(), equalTo("#COLLECTION(allowInsert)")); } @Test public void internalGetStartCaseTrigger_200_shouldSetCollectionDisplayContextParameterForReadCaseRole() throws Exception { MockUtils.setSecurityAuthorities(authentication, MockUtils.ROLE_CASEWORKER_PUBLIC, CASE_ROLE_CAN_CREATE, CASE_ROLE_CAN_READ); HttpHeaders headers = new HttpHeaders(); headers.add(AUTHORIZATION, "Bearer user1"); headers.add(V2.EXPERIMENTAL_HEADER, "true"); final MvcResult result = mockMvc.perform(get(GET_EVENT_TRIGGER_FOR_CASE_TYPE_INTERNAL) .contentType(JSON_CONTENT_TYPE) .accept(V2.MediaType.CASE_TYPE_UPDATE_VIEW_EVENT) .headers(headers)) .andExpect(status().is(200)) .andReturn(); final CaseUpdateViewEventResource caseUpdateViewEventResource = mapper.readValue(result.getResponse().getContentAsString(), CaseUpdateViewEventResource.class); assertNotNull("UI Start Trigger Resource is null", caseUpdateViewEventResource); assertEquals("Unexpected Case Fields", 2, caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseFields().size()); final CaseViewField children = caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseFields().get(1); assertThat(children.getFieldTypeDefinition().getType(), equalTo("Collection")); assertThat(children.getDisplayContextParameter(), equalTo("#COLLECTION(allowInsert)")); final CaseFieldDefinition hobby = children.getFieldTypeDefinition().getCollectionFieldTypeDefinition().getChildren().get(1); assertThat(hobby.getId(), equalTo("hobbies")); assertThat(hobby.getDisplayContextParameter(), equalTo("#COLLECTION(allowInsert)")); // hobbies ACLs are being overridden from the parent assertThat(hobby.getAccessControlLists().get(0).getRole(), equalTo("[CAN_CREATE]")); assertThat(hobby.getAccessControlLists().get(0).isCreate(), is(true)); assertThat(hobby.getAccessControlLists().get(0).isRead(), is(false)); assertThat(hobby.getAccessControlLists().get(0).isUpdate(), is(false)); assertThat(hobby.getAccessControlLists().get(0).isDelete(), is(false)); } @Test public void internalGetStartCaseTrigger_200_shouldSetCollectionDisplayContextParameterForUpdateCaseRole() throws Exception { MockUtils.setSecurityAuthorities(authentication, MockUtils.ROLE_CASEWORKER_PUBLIC, CASE_ROLE_CAN_CREATE, CASE_ROLE_CAN_UPDATE); HttpHeaders headers = new HttpHeaders(); headers.add(AUTHORIZATION, "Bearer user1"); headers.add(V2.EXPERIMENTAL_HEADER, "true"); final MvcResult result = mockMvc.perform(get(GET_EVENT_TRIGGER_FOR_CASE_TYPE_INTERNAL) .contentType(JSON_CONTENT_TYPE) .accept(V2.MediaType.CASE_TYPE_UPDATE_VIEW_EVENT) .headers(headers)) .andExpect(status().is(200)) .andReturn(); final CaseUpdateViewEventResource caseUpdateViewEventResource = mapper.readValue(result.getResponse().getContentAsString(), CaseUpdateViewEventResource.class); assertNotNull("UI Start Trigger Resource is null", caseUpdateViewEventResource); assertEquals("Unexpected Case Fields", 2, caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseFields().size()); final CaseViewField children = caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseFields().get(1); assertThat(children.getFieldTypeDefinition().getType(), equalTo("Collection")); assertThat(children.getDisplayContextParameter(), equalTo("#COLLECTION(allowDelete,allowInsert)")); final CaseFieldDefinition hobby = children.getFieldTypeDefinition().getCollectionFieldTypeDefinition().getChildren().get(1); assertThat(hobby.getId(), equalTo("hobbies")); assertThat(hobby.getDisplayContextParameter(), equalTo("#COLLECTION(allowDelete,allowInsert)")); } @Test public void internalGetStartCaseTrigger_200_shouldSetCollectionDisplayContextParameterForDeleteCaseRole() throws Exception { MockUtils.setSecurityAuthorities(authentication, MockUtils.ROLE_CASEWORKER_PUBLIC, CASE_ROLE_CAN_CREATE, CASE_ROLE_CAN_DELETE); HttpHeaders headers = new HttpHeaders(); headers.add(AUTHORIZATION, "Bearer user1"); headers.add(V2.EXPERIMENTAL_HEADER, "true"); final MvcResult result = mockMvc.perform(get(GET_EVENT_TRIGGER_FOR_CASE_TYPE_INTERNAL) .contentType(JSON_CONTENT_TYPE) .accept(V2.MediaType.CASE_TYPE_UPDATE_VIEW_EVENT) .headers(headers)) .andExpect(status().is(200)) .andReturn(); final CaseUpdateViewEventResource caseUpdateViewEventResource = mapper.readValue(result.getResponse().getContentAsString(), CaseUpdateViewEventResource.class); assertNotNull("UI Start Trigger Resource is null", caseUpdateViewEventResource); assertEquals("Unexpected Case Fields", 2, caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseFields().size()); final CaseViewField children = caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseFields().get(1); assertThat(children.getFieldTypeDefinition().getType(), equalTo("Collection")); assertThat(children.getDisplayContextParameter(), equalTo("#COLLECTION(allowDelete,allowInsert)")); final CaseFieldDefinition hobby = children.getFieldTypeDefinition().getCollectionFieldTypeDefinition().getChildren().get(1); assertThat(hobby.getId(), equalTo("hobbies")); assertThat(hobby.getDisplayContextParameter(), equalTo("#COLLECTION(allowDelete,allowInsert)")); } @Test @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = { "classpath:sql/insert_cases_event_access_case_roles.sql" }) public void shouldStartEventTrigger() throws Exception { MockUtils.setSecurityAuthorities(authentication, MockUtils.ROLE_CASEWORKER_PUBLIC); HttpHeaders headers = new HttpHeaders(); headers.add(AUTHORIZATION, "Bearer user1"); headers.add(V2.EXPERIMENTAL_HEADER, "true"); final MvcResult result = mockMvc.perform(get(GET_EVENT_TRIGGER_FOR_CASE) .contentType(JSON_CONTENT_TYPE) .accept(V2.MediaType.CASE_UPDATE_VIEW_EVENT) .headers(headers)) .andExpect(status().is(200)) .andReturn(); final CaseUpdateViewEventResource caseUpdateViewEventResource = mapper.readValue(result.getResponse().getContentAsString(), CaseUpdateViewEventResource.class); assertNotNull("UI Start Trigger Resource is null", caseUpdateViewEventResource); assertThat(caseUpdateViewEventResource.getCaseUpdateViewEvent().getCaseId(), is("1504259907353529")); } }
ethansaxenian/RosettaDecode
lang/C/guess-the-number-with-feedback--player--1.c
<filename>lang/C/guess-the-number-with-feedback--player--1.c #include <stdio.h> int main(){ int bounds[ 2 ] = {1, 100}; char input[ 2 ] = " "; /* second char is for the newline from hitting [return] */ int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; /* using a binary search */ printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] ); do{ switch( input[ 0 ] ){ case 'H': bounds[ 1 ] = choice; break; case 'L': bounds[ 0 ] = choice; break; case 'Y': printf( "\nAwwwright\n" ); return 0; } choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; printf( "Is the number %d? (Y/H/L) ", choice ); }while( scanf( "%1s", input ) == 1 ); return 0; }
netfighter/openproject
app/helpers/i18n_js_helper.rb
<reponame>netfighter/openproject #-- encoding: UTF-8 #-- copyright # OpenProject is a project management system. # Copyright (C) 2012-2014 the OpenProject Foundation (OPF) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2013 <NAME> # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See doc/COPYRIGHT.rdoc for more details. #++ module I18nJsHelper def i18n_js_tags fallbacks = I18n.fallbacks[I18n.locale].map(&:to_s) fallbacks.shift s = "" s << javascript_include_tag("i18n") s << javascript_include_tag("i18n/translations") s << javascript_tag(%Q{ I18n.defaultLocale = "#{I18n.default_locale}"; I18n.locale = "#{I18n.locale}"; I18n.fallbacks = true; I18n.fallbackRules = I18n.fallbackRules || {}; I18n.fallbackRules['#{I18n.locale}'] = #{fallbacks.to_json}; }) s end end
silenc3502/MYSQL-Arch-Doc-Summary
mysql-server/sql/records.h
#ifndef SQL_RECORDS_H #define SQL_RECORDS_H /* Copyright (c) 2008, 2020, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <sys/types.h> #include <memory> #include <string> #include "my_alloc.h" #include "my_base.h" #include "sql/basic_row_iterators.h" #include "sql/composite_iterators.h" #include "sql/ref_row_iterators.h" #include "sql/row_iterator.h" #include "sql/sorting_iterator.h" class QEP_TAB; class THD; struct AccessPath; struct TABLE; AccessPath *create_table_access_path(THD *thd, TABLE *table, QEP_TAB *qep_tab, bool count_examined_rows); /** Creates an iterator for the given table, then calls Init() on the resulting iterator. Unlike create_table_iterator(), this can create iterators for sort buffer results (which are set in the TABLE object during query execution). Returns nullptr on failure. */ unique_ptr_destroy_only<RowIterator> init_table_iterator( THD *thd, TABLE *table, QEP_TAB *qep_tab, bool ignore_not_found_rows, bool count_examined_rows); #endif /* SQL_RECORDS_H */
lvsgate/lvs-dpdk
tools/keepalived/keepalived/check/check_smtp.c
<reponame>lvsgate/lvs-dpdk /* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: SMTP CHECK. Check an SMTP-server. * * Authors: <NAME>, <<EMAIL>> * <NAME>, <<EMAIL>> * * 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. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2011 <NAME>, <<EMAIL>> */ #include <ctype.h> #include "check_smtp.h" #include "check_api.h" #include "logger.h" #include "memory.h" #include "ipwrapper.h" #include "utils.h" #include "parser.h" #include "daemon.h" int smtp_connect_thread(thread_t *); /* module variables */ static smtp_host_t *default_host = NULL; /* * Used as a callback from free_list() to free all * the list elements in smtp_checker->host before we * free smtp_checker itself. */ void smtp_free_host(void *data) { FREE(data); } /* Used as a callback from the checker api, queue_checker(), * to free up a checker entry and all its associated data. */ void free_smtp_check(void *data) { smtp_checker_t *smtp_checker = CHECKER_DATA(data); free_list(smtp_checker->host); FREE(smtp_checker->helo_name); FREE(smtp_checker); FREE(data); } /* * Used as a callback from dump_list() to print out all * the list elements in smtp_checker->host. */ void smtp_dump_host(void *data) { smtp_host_t *smtp_host = data; log_message(LOG_INFO, " Checked ip = %s", inet_sockaddrtos(&smtp_host->dst)); log_message(LOG_INFO, " port = %d", ntohs(ntohs(inet_sockaddrport(&smtp_host->dst)))); if (smtp_host->bindto.ss_family) log_message(LOG_INFO, " bindto = %s", inet_sockaddrtos(&smtp_host->bindto)); } /* * Callback for whenever we've been requested to dump our * configuration. */ void dump_smtp_check(void *data) { smtp_checker_t *smtp_checker = CHECKER_DATA(data); log_message(LOG_INFO, " Keepalive method = SMTP_CHECK"); log_message(LOG_INFO, " helo = %s", smtp_checker->helo_name); log_message(LOG_INFO, " timeout = %ld", smtp_checker->timeout/TIMER_HZ); log_message(LOG_INFO, " retry = %d", smtp_checker->retry); log_message(LOG_INFO, " delay before retry = %ld", smtp_checker->db_retry/TIMER_HZ); dump_list(smtp_checker->host); } /* Allocates a default host structure */ smtp_host_t * smtp_alloc_host(void) { smtp_host_t *new; /* Allocate the new host data structure */ new = (smtp_host_t *)MALLOC(sizeof(smtp_host_t)); /* * By default we set the ip to connect to as the same ip as the current real server * in the rs config. This might be overridden later on by a "connect_ip" keyword. */ checker_set_dst(&new->dst); checker_set_dst_port(&new->dst, htons(SMTP_DEFAULT_PORT)); return new; } /* * Callback for whenever an SMTP_CHECK keyword is encountered * in the config file. */ void smtp_check_handler(vector strvec) { smtp_checker_t *smtp_checker = (smtp_checker_t *)MALLOC(sizeof(smtp_checker_t)); /* * Set something sane for the default HELO banner * May be overridden by a "helo_name" keyword later. */ smtp_checker->helo_name = (char *)MALLOC(strlen(SMTP_DEFAULT_HELO) + 1); memcpy(smtp_checker->helo_name, SMTP_DEFAULT_HELO, strlen(SMTP_DEFAULT_HELO) + 1); /* some other sane values */ smtp_checker->timeout = 5 * TIMER_HZ; smtp_checker->db_retry = 1 * TIMER_HZ; smtp_checker->retry = 1; /* * Have the checker queue code put our checker into the checkers_queue * list. * * queue_checker(void (*free) (void *), void (*dump) (void *), * int (*launch) (thread_t *), * void *data) */ queue_checker(free_smtp_check, dump_smtp_check, smtp_connect_thread, smtp_checker); /* * Last, allocate/setup the list that will hold all the per host * configuration structures. We'll set a "default host", which * is the same ip as the real server. If there are additional "host" * sections in the config, the default will be deleted and overridden. * If the default is still set by a previous "SMTP_CHECK" section, * we must simply overwrite the old value: * - it must not be reused, because it was probably located in a * different "real_server" section and * - it must not be freed, because it is still referenced * by some other smtp_checker->host. * This must come after queue_checker()! */ smtp_checker->host = alloc_list(smtp_free_host, smtp_dump_host); default_host = smtp_alloc_host(); list_add(smtp_checker->host, default_host); } /* * Callback for whenever the "host" keyword is encountered * in the config file. */ void smtp_host_handler(vector strvec) { smtp_checker_t *smtp_checker = CHECKER_GET(); /* * If the default host is still allocated, delete it * before we stick user defined hosts in the list. */ if (default_host) { list_del(smtp_checker->host, default_host); FREE(default_host); default_host = NULL; } /* add an empty host to the list, smtp_checker->host */ list_add(smtp_checker->host, smtp_alloc_host()); } /* "connect_ip" keyword */ void smtp_ip_handler(vector strvec) { smtp_checker_t *smtp_checker = CHECKER_GET(); smtp_host_t *smtp_host = LIST_TAIL_DATA(smtp_checker->host); inet_stosockaddr(VECTOR_SLOT(strvec, 1), NULL, &smtp_host->dst); } /* "connect_port" keyword */ void smtp_port_handler(vector strvec) { smtp_checker_t *smtp_checker = CHECKER_GET(); smtp_host_t *smtp_host = LIST_TAIL_DATA(smtp_checker->host); checker_set_dst_port(&smtp_host->dst, htons(CHECKER_VALUE_INT(strvec))); } /* "helo_name" keyword */ void smtp_helo_name_handler(vector strvec) { smtp_checker_t *smtp_checker = CHECKER_GET(); smtp_checker->helo_name = CHECKER_VALUE_STRING(strvec); } /* "connect_timeout" keyword */ void smtp_timeout_handler(vector strvec) { smtp_checker_t *smtp_checker = CHECKER_GET(); smtp_checker->timeout = CHECKER_VALUE_INT(strvec) * TIMER_HZ; } /* "retry" keyword */ void smtp_retry_handler(vector strvec) { smtp_checker_t *smtp_checker = CHECKER_GET(); smtp_checker->retry = CHECKER_VALUE_INT(strvec); } /* "delay_before_retry" keyword */ void smtp_db_retry_handler(vector strvec) { smtp_checker_t *smtp_checker = CHECKER_GET(); smtp_checker->db_retry = CHECKER_VALUE_INT(strvec) * TIMER_HZ; } /* "bindto" keyword */ void smtp_bindto_handler(vector strvec) { smtp_checker_t *smtp_checker = CHECKER_GET(); smtp_host_t *smtp_host = LIST_TAIL_DATA(smtp_checker->host); inet_stosockaddr(VECTOR_SLOT(strvec, 1), 0, &smtp_host->bindto); } /* Config callback installer */ void install_smtp_check_keyword(void) { /* * Notify the config log parser that we need to be notified via * callbacks when the following keywords are encountered in the * keepalive.conf file. */ install_keyword("SMTP_CHECK", &smtp_check_handler); install_sublevel(); install_keyword("helo_name", &smtp_helo_name_handler); install_keyword("connect_timeout", &smtp_timeout_handler); install_keyword("delay_before_retry", &smtp_db_retry_handler); install_keyword("retry", &smtp_retry_handler); install_keyword("host", &smtp_host_handler); install_sublevel(); install_keyword("connect_ip", &smtp_ip_handler); install_keyword("connect_port", &smtp_port_handler); install_keyword("bindto", &smtp_bindto_handler); install_sublevel_end(); install_sublevel_end(); } /* * Final handler. Determines if we need a retry or not. * Also has to make a decision if we need to bring the resulting * service down in case of error. */ int smtp_final(thread_t *thread, int error, const char *format, ...) { checker_t *checker = THREAD_ARG(thread); smtp_checker_t *smtp_checker = CHECKER_ARG(checker); char error_buff[512]; char smtp_buff[542]; va_list varg_list; /* Error or no error we should always have to close the socket */ close(thread->u.fd); /* If we're here, an attempt HAS been made already for the current host */ smtp_checker->attempts++; if (error) { /* Always syslog the error when the real server is up */ if (svr_checker_up(checker->id, checker->rs)) { if (format != NULL) { memcpy(error_buff, "SMTP_CHECK ", 11); va_start(varg_list, format); vsnprintf(error_buff + 11, 512 - 11, format, varg_list); va_end(varg_list); error_buff[512 - 1] = '\0'; log_message(LOG_INFO, error_buff); } else { log_message(LOG_INFO, "SMTP_CHECK Unknown error"); } } /* * If we still have retries left, try this host again by * scheduling the main thread to check it again after the * configured backoff delay. Otherwise down the RS. */ if (smtp_checker->attempts < smtp_checker->retry) { thread_add_timer(thread->master, smtp_connect_thread, checker, smtp_checker->db_retry); return 0; } /* * No more retries, pull the real server from the virtual server. * Only smtp_alert if it wasn't previously down. It should * be noted that smtp_alert makes a copy of the string arguments, so * we don't have to keep them statically allocated. */ if (svr_checker_up(checker->id, checker->rs)) { if (format != NULL) { snprintf(smtp_buff, 542, "=> CHECK failed on service : %s <=", error_buff + 11); } else { snprintf(smtp_buff, 542, "=> CHECK failed on service <="); } smtp_buff[542 - 1] = '\0'; smtp_alert(checker->rs, NULL, NULL, "DOWN", smtp_buff); update_svr_checker_state(DOWN, checker->id, checker->vs, checker->rs); } /* Reset everything back to the first host in the list */ smtp_checker->attempts = 0; smtp_checker->host_ctr = 0; /* Reschedule the main thread using the configured delay loop */; thread_add_timer(thread->master, smtp_connect_thread, checker, checker->vs->delay_loop); return 0; } /* * Ok this host was successful, increment to the next host in the list * and reset the attempts counter. We'll then reschedule the main thread again. * If host_ctr exceeds the number of hosts in the list, http_main_thread will * take note and bring up the real server as well as inject the delay_loop. */ smtp_checker->attempts = 0; smtp_checker->host_ctr++; thread_add_timer(thread->master, smtp_connect_thread, checker, 1); return 0; } /* * Zeros out the rx/tx buffer */ void smtp_clear_buff(thread_t *thread) { checker_t *checker = THREAD_ARG(thread); smtp_checker_t *smtp_checker = CHECKER_ARG(checker); memset(smtp_checker->buff, 0, SMTP_BUFF_MAX); smtp_checker->buff_ctr = 0; } /* * One thing to note here is we do a very cheap check for a newline. * We could receive two lines (with two newline characters) in a * single packet, but we don't care. We are only looking at the * SMTP response codes at the beginning anyway. */ int smtp_get_line_cb(thread_t *thread) { checker_t *checker = THREAD_ARG(thread); smtp_checker_t *smtp_checker = CHECKER_ARG(checker); smtp_host_t *smtp_host = smtp_checker->host_ptr; int f, r, x; /* Handle read timeout */ if (thread->type == THREAD_READ_TIMEOUT) { smtp_final(thread, 1, "Read timeout from server [%s:%d]" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst))); return 0; } /* wrap the buffer, if full, by clearing it */ if (SMTP_BUFF_MAX - smtp_checker->buff_ctr <= 0) { log_message(LOG_INFO, "SMTP_CHECK Buffer overflow reading from server [%s:%d]. " "Increase SMTP_BUFF_MAX in smtp_check.h" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst))); smtp_clear_buff(thread); } /* Set descriptor non blocking */ f = fcntl(thread->u.fd, F_GETFL, 0); fcntl(thread->u.fd, F_SETFL, f | O_NONBLOCK); /* read the data */ r = read(thread->u.fd, smtp_checker->buff + smtp_checker->buff_ctr, SMTP_BUFF_MAX - smtp_checker->buff_ctr); if (r == -1 && (errno == EAGAIN || errno == EINTR)) { thread_add_read(thread->master, smtp_get_line_cb, checker, thread->u.fd, smtp_checker->timeout); fcntl(thread->u.fd, F_SETFL, f); return 0; } else if (r > 0) smtp_checker->buff_ctr += r; /* restore descriptor flags */ fcntl(thread->u.fd, F_SETFL, f); /* check if we have a newline, if so, callback */ for (x = 0; x < SMTP_BUFF_MAX; x++) { if (smtp_checker->buff[x] == '\n') { smtp_checker->buff[SMTP_BUFF_MAX - 1] = '\0'; DBG("SMTP_CHECK [%s:%d] < %s" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst)) , smtp_checker->buff); (smtp_checker->buff_cb)(thread); return 0; } } /* * If the connection was closed or there was * some sort of error, notify smtp_final() */ if (r <= 0) { smtp_final(thread, 1, "Read failure from server [%s:%d]" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst))); return 0; } /* * Last case, we haven't read enough data yet * to pull a newline. Schedule ourselves for * another round. */ thread_add_read(thread->master, smtp_get_line_cb, checker, thread->u.fd, smtp_checker->timeout); return 0; } /* * Ok a caller has asked us to asyncronously schedule a single line * to be received from the server. They have also passed us a call back * function that we'll call once we have the newline. If something bad * happens, the caller assumes we'll pass the error off to smtp_final(), * which will either down the real server or schedule a retry. The * function smtp_get_line_cb is what does the dirty work since the * sceduler can only accept a single *thread argument. */ void smtp_get_line(thread_t *thread, int (*callback) (thread_t *)) { checker_t *checker = THREAD_ARG(thread); smtp_checker_t *smtp_checker = CHECKER_ARG(checker); /* clear the buffer */ smtp_clear_buff(thread); /* set the callback */ smtp_checker->buff_cb = callback; /* schedule the I/O with our helper function */ thread_add_read(thread->master, smtp_get_line_cb, checker, thread->u.fd, smtp_checker->timeout); return; } /* * The scheduler function that puts the data out on the wire. * All our data will fit into one packet, so we only check if * the current write would block or not. If it wants to block, * we'll return to the scheduler and try again later. */ int smtp_put_line_cb(thread_t *thread) { checker_t *checker = THREAD_ARG(thread); smtp_checker_t *smtp_checker = CHECKER_ARG(checker); smtp_host_t *smtp_host = smtp_checker->host_ptr; int f, w; /* Handle read timeout */ if (thread->type == THREAD_WRITE_TIMEOUT) { smtp_final(thread, 1, "Write timeout to server [%s:%d]" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst))); return 0; } /* Set descriptor non blocking */ f = fcntl(thread->u.fd, F_GETFL, 0); fcntl(thread->u.fd, F_SETFL, f | O_NONBLOCK); /* write the data */ w = write(thread->u.fd, smtp_checker->buff, smtp_checker->buff_ctr); if (w == -1 && (errno == EAGAIN || errno == EINTR)) { thread_add_write(thread->master, smtp_put_line_cb, checker, thread->u.fd, smtp_checker->timeout); fcntl(thread->u.fd, F_SETFL, f); return 0; } /* restore descriptor flags */ fcntl(thread->u.fd, F_SETFL, f); DBG("SMTP_CHECK [%s:%d] > %s" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst)) , smtp_checker->buff); /* * If the connection was closed or there was * some sort of error, notify smtp_final() */ if (w <= 0) { smtp_final(thread, 1, "Write failure to server [%s:%d]" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst))); return 0; } /* Execute the callback */ (smtp_checker->buff_cb)(thread); return 0; } /* * This is the same as smtp_get_line() except that we're sending a * line of data instead of receiving one. */ void smtp_put_line(thread_t *thread, int (*callback) (thread_t *)) { checker_t *checker = THREAD_ARG(thread); smtp_checker_t *smtp_checker = CHECKER_ARG(checker); smtp_checker->buff[SMTP_BUFF_MAX - 1] = '\0'; smtp_checker->buff_ctr = strlen(smtp_checker->buff); /* set the callback */ smtp_checker->buff_cb = callback; /* schedule the I/O with our helper function */ thread_add_write(thread->master, smtp_put_line_cb, checker, thread->u.fd, smtp_checker->timeout); return; } /* * Ok, our goal here is to snag the status code out of the * buffer and return it as an integer. If it's not legible, * return -1. */ int smtp_get_status(thread_t *thread) { checker_t *checker = THREAD_ARG(thread); smtp_checker_t *smtp_checker = CHECKER_ARG(checker); char *buff = smtp_checker->buff; /* First make sure they're all digits */ if (isdigit(buff[0]) && isdigit(buff[1]) && isdigit(buff[2])) { /* Truncate the string and convert */ buff[3] = '\0'; return atoi(buff); } return -1; } /* * We have a connected socket and are ready to begin * the conversation. This function schedules itself to * be called via callbacks and tracking state in * smtp_checker->state. Upon first calling, smtp_checker->state * should be set to SMTP_START. */ int smtp_engine_thread(thread_t *thread) { checker_t *checker = THREAD_ARG(thread); smtp_checker_t *smtp_checker = CHECKER_ARG(checker); smtp_host_t *smtp_host = smtp_checker->host_ptr; switch (smtp_checker->state) { /* First step, schedule to receive the greeting banner */ case SMTP_START: /* * Ok, if smtp_get_line schedules us back, we will * have data to analyze. Otherwise, smtp_get_line * will defer directly to smtp_final. */ smtp_checker->state = SMTP_HAVE_BANNER; smtp_get_line(thread, smtp_engine_thread); return 0; break; /* Second step, analyze banner, send HELO */ case SMTP_HAVE_BANNER: /* Check for "220 some.mailserver.com" in the greeting */ if (smtp_get_status(thread) != 220) { smtp_final(thread, 1, "Bad greeting banner from server [%s:%d]" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst))); return 0; } /* * Schedule to send the HELO, smtp_put_line will * defer directly to smtp_final on error. */ smtp_checker->state = SMTP_SENT_HELO; snprintf(smtp_checker->buff, SMTP_BUFF_MAX, "HELO %s\r\n", smtp_checker->helo_name); smtp_put_line(thread, smtp_engine_thread); return 0; break; /* Third step, schedule to read the HELO response */ case SMTP_SENT_HELO: smtp_checker->state = SMTP_RECV_HELO; smtp_get_line(thread, smtp_engine_thread); return 0; break; /* Fourth step, analyze HELO return, send QUIT */ case SMTP_RECV_HELO: /* Check for "250 Please to meet you..." */ if (smtp_get_status(thread) != 250) { smtp_final(thread, 1, "Bad HELO response from server [%s:%d]" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst))); return 0; } smtp_checker->state = SMTP_SENT_QUIT; snprintf(smtp_checker->buff, SMTP_BUFF_MAX, "QUIT\r\n"); smtp_put_line(thread, smtp_engine_thread); return 0; break; /* Fifth step, schedule to receive QUIT confirmation */ case SMTP_SENT_QUIT: smtp_checker->state = SMTP_RECV_QUIT; smtp_get_line(thread, smtp_engine_thread); return 0; break; /* Sixth step, wrap up success to smtp_final */ case SMTP_RECV_QUIT: smtp_final(thread, 0, NULL); return 0; break; } /* We shouldn't be here */ smtp_final(thread, 1, "Unknown smtp engine state encountered"); return 0; } /* * Second step in the process. Here we'll see if the connection * to the host we're checking was successful or not. */ int smtp_check_thread(thread_t *thread) { checker_t *checker = THREAD_ARG(thread); smtp_checker_t *smtp_checker = CHECKER_ARG(checker); smtp_host_t *smtp_host = smtp_checker->host_ptr; int status; status = tcp_socket_state(thread->u.fd, thread, smtp_check_thread); switch (status) { case connect_error: smtp_final(thread, 1, "Error connecting to server [%s:%d]" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst))); return 0; break; case connect_timeout: smtp_final(thread, 1, "Connection timeout to server [%s:%d]" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst))); return 0; break; case connect_success: DBG("SMTP_CHECK Remote SMTP server [%s:%d] connected" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst))); /* Enter the engine at SMTP_START */ smtp_checker->state = SMTP_START; smtp_engine_thread(thread); return 0; break; } /* we shouldn't be here */ smtp_final(thread, 1, "Unknown connection error to server [%s:%d]" , inet_sockaddrtos(&smtp_host->dst) , ntohs(inet_sockaddrport(&smtp_host->dst))); return 0; } /* * This is the main thread, where all the action starts. * When the check daemon comes up, it goes down the checkers_queue * and launches a thread for each checker that got registered. * This is the callback/event function for that initial thread. * * It should be noted that we ARE responsible for sceduling * ourselves to run again. It doesn't have to be right here, * but eventually has to happen. */ int smtp_connect_thread(thread_t *thread) { checker_t *checker = THREAD_ARG(thread); smtp_checker_t *smtp_checker = CHECKER_ARG(checker); smtp_host_t *smtp_host; enum connect_result status; int sd; /* Let's review our data structures. * * Thread is the structure used by the sceduler * for sceduling many types of events. thread->arg in this * case points to a checker structure. The checker * structure holds data about the vs and rs configurations * as well as the delay loop, etc. Each real server * defined in the keepalived.conf will more than likely have * a checker structure assigned to it. Each checker structure * has a data element that is meant to hold per checker * configurations. So thread->arg(checker)->data points to * a smtp_checker structure. In the smtp_checker structure * we hold global configuration data for the smtp check. * Smtp_checker has a list of per host (smtp_host) configuration * data in smtp_checker->host. * * So this whole thing looks like this: * thread->arg(checker)->data(smtp_checker)->host(smtp_host) * * To make life simple, we'll break the structures out so * that "checker" always points to the current checker structure, * "smtp_checker" points to the current smtp_checker structure, * and "smtp_host" points to the current smtp_host structure. */ /* * If we're disabled, we'll do nothing at all. * But we still have to register ourselves again so * we don't fall of the face of the earth. */ if (!CHECKER_ENABLED(checker)) { thread_add_timer(thread->master, smtp_connect_thread, checker, checker->vs->delay_loop); return 0; } /* * Set the internal host pointer to the host that well be * working on. If it's NULL, we've successfully tested all hosts. * We'll bring the service up (if it's not already), reset the host list, * and insert the delay loop. When we get scheduled again the host list * will be reset and we will continue on checking them one by one. */ if ((smtp_checker->host_ptr = list_element(smtp_checker->host, smtp_checker->host_ctr)) == NULL) { if (!svr_checker_up(checker->id, checker->rs)) { log_message(LOG_INFO, "Remote SMTP server [%s:%d] succeed on service." , inet_sockaddrtos(&checker->rs->addr) , ntohs(inet_sockaddrport(&checker->rs->addr))); smtp_alert(checker->rs, NULL, NULL, "UP", "=> CHECK succeed on service <="); update_svr_checker_state(UP, checker->id, checker->vs, checker->rs); } smtp_checker->attempts = 0; smtp_checker->host_ctr = 0; smtp_checker->host_ptr = list_element(smtp_checker->host, 0); thread_add_timer(thread->master, smtp_connect_thread, checker, checker->vs->delay_loop); return 0; } smtp_host = smtp_checker->host_ptr; /* Create the socket, failling here should be an oddity */ if ((sd = socket(smtp_host->dst.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) { DBG("SMTP_CHECK connection failed to create socket."); thread_add_timer(thread->master, smtp_connect_thread, checker, checker->vs->delay_loop); return 0; } status = tcp_bind_connect(sd, &smtp_host->dst, &smtp_host->bindto); if (status == connect_error) { thread_add_timer(thread->master, smtp_connect_thread, checker, checker->vs->delay_loop); } /* handle tcp connection status & register callback the next setp in the process */ tcp_connection_state(sd, status, thread, smtp_check_thread, smtp_checker->timeout); return 0; }
zhangzhizhong520/super-devops
super-devops-umc/super-devops-umc-receiver/src/main/java/com/wl4g/devops/umc/config/UmcReceiveAutoConfiguration.java
<filename>super-devops-umc/super-devops-umc-receiver/src/main/java/com/wl4g/devops/umc/config/UmcReceiveAutoConfiguration.java /* * Copyright 2017 ~ 2025 the original author or authors. <<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 com.wl4g.devops.umc.config; import com.wl4g.devops.common.config.AbstractOptionalControllerConfiguration; import com.wl4g.devops.umc.annotation.EnableHttpCollectReceiver; import com.wl4g.devops.umc.annotation.EnableKafkaCollectReceiver; import com.wl4g.devops.umc.console.ReceiveConsole; import com.wl4g.devops.umc.receiver.HttpMetricReceiver; import com.wl4g.devops.umc.receiver.KafkaMetricReceiver; import com.wl4g.devops.umc.store.*; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.config.KafkaListenerContainerFactory; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.listener.AbstractMessageListenerContainer.AckMode; import org.springframework.kafka.listener.config.ContainerProperties; import java.lang.annotation.Annotation; import java.util.Map; import java.util.Properties; import static com.wl4g.devops.common.constants.UMCDevOpsConstants.URI_HTTP_RECEIVER_BASE; import static com.wl4g.devops.umc.config.ReceiverProperties.KEY_RECEIVER_PREFIX; /** * UMC receiver auto configuration * * @author wangl.sir * @version v1.0 2019年6月17日 * @since */ @Configuration @ImportAutoConfiguration(UmcWatchAutoConfiguration.class) public class UmcReceiveAutoConfiguration extends AbstractOptionalControllerConfiguration { final public static String BEAN_HTTP_RECEIVER = "httpCollectReceiver"; final public static String BEAN_KAFKA_RECEIVER = "kafkaCollectReceiver"; final public static String BEAN_KAFKA_BATCH_FACTORY = "kafkaBatchFactory"; @Bean @ConfigurationProperties(prefix = KEY_RECEIVER_PREFIX) public ReceiverProperties receiverProperties() { return new ReceiverProperties(); } // // HTTP receiver. // @Bean(BEAN_HTTP_RECEIVER) @EnableHttpCollectReceiver public HttpMetricReceiver httpCollectReceiver(MetricStore store) { return new HttpMetricReceiver(store); } @Bean @EnableHttpCollectReceiver public PrefixHandlerMapping httpCollectReceiverPrefixHandlerMapping() { return createPrefixHandlerMapping(); } @Override protected String getMappingPrefix() { return URI_HTTP_RECEIVER_BASE; } @Override protected Class<? extends Annotation> annotationClass() { return com.wl4g.devops.umc.annotation.HttpCollectReceiver.class; } // // KAFKA receiver. // @Bean(BEAN_KAFKA_RECEIVER) @EnableKafkaCollectReceiver public KafkaMetricReceiver kafkaCollectReceiver(MetricStore store) { return new KafkaMetricReceiver(store); } @Bean(BEAN_KAFKA_BATCH_FACTORY) @EnableKafkaCollectReceiver @SuppressWarnings({ "unchecked", "rawtypes" }) public KafkaListenerContainerFactory<?> batchFactory(ReceiverProperties conf) { // Create consumer factory. Properties properties = conf.getKafka().getProperties(); Map<String, Object> config = (Map) properties; ConsumerFactory<String, String> cf = new DefaultKafkaConsumerFactory<>(config); // Create concurrent consumer container factory. ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(cf); factory.setConcurrency(conf.getKafka().getConcurrency()); factory.setBatchListener(true); // Spring kafka container properties. ContainerProperties containerProps = factory.getContainerProperties(); containerProps.setPollTimeout(conf.getKafka().getPollTimeout()); // Bulk consumption change buffer queue size. containerProps.setQueueDepth(conf.getKafka().getQueueDepth()); containerProps.setAckMode(AckMode.MANUAL_IMMEDIATE); return factory; } // // Receive console. // @Bean public ReceiveConsole receiveConsole() { return new ReceiveConsole(); } }
agustinhenze/mibs.snmplabs.com
pysnmp/WATCHGUARD-SMI.py
# # PySNMP MIB module WATCHGUARD-SMI (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WATCHGUARD-SMI # Produced by pysmi-0.3.4 at Mon Apr 29 21:29:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") TimeTicks, Bits, enterprises, Gauge32, ObjectIdentity, NotificationType, Counter32, IpAddress, Integer32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Counter64, ModuleIdentity, iso = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Bits", "enterprises", "Gauge32", "ObjectIdentity", "NotificationType", "Counter32", "IpAddress", "Integer32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Counter64", "ModuleIdentity", "iso") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") watchguard = ModuleIdentity((1, 3, 6, 1, 4, 1, 3097)) watchguard.setRevisions(('2008-11-10 00:00',)) if mibBuilder.loadTexts: watchguard.setLastUpdated('200811100000Z') if mibBuilder.loadTexts: watchguard.setOrganization('WatchGuard Technologies, Inc.') wgProducts = ObjectIdentity((1, 3, 6, 1, 4, 1, 3097, 1)) if mibBuilder.loadTexts: wgProducts.setStatus('current') wgSystemConfigMIB = ObjectIdentity((1, 3, 6, 1, 4, 1, 3097, 2)) if mibBuilder.loadTexts: wgSystemConfigMIB.setStatus('current') mibBuilder.exportSymbols("WATCHGUARD-SMI", wgProducts=wgProducts, PYSNMP_MODULE_ID=watchguard, watchguard=watchguard, wgSystemConfigMIB=wgSystemConfigMIB)
lafaspot/imapnioclient
core/src/test/java/com/yahoo/imapnio/async/request/ImapRFCSupportedCommandTypeTest.java
package com.yahoo.imapnio.async.request; import org.testng.Assert; import org.testng.annotations.Test; /** * Unit test for {@link ImapRFCSupportedCommandType}. */ public class ImapRFCSupportedCommandTypeTest { /** * Tests CommandType enum. */ @Test public void testCommandTypeEnum() { final ImapRFCSupportedCommandType[] enumList = ImapRFCSupportedCommandType.values(); Assert.assertEquals(enumList.length, 37, "The enum count mismatched."); final ImapRFCSupportedCommandType uidFetch = ImapRFCSupportedCommandType.valueOf("UID_FETCH"); Assert.assertSame(uidFetch, ImapRFCSupportedCommandType.UID_FETCH, "Enum does not match."); } }
jnthn/intellij-community
java/java-tests/testData/codeInsight/joinLines/LeaveTrailingComment.java
<reponame>jnthn/intellij-community<filename>java/java-tests/testData/codeInsight/joinLines/LeaveTrailingComment.java public class Foo { { String a = null;<caret> a = "sss"; //stupid test } }
hawesome512/EDSOnline
app/src/main/java/com/xseec/eds/fragment/DataLogFragment.java
<gh_stars>0 package com.xseec.eds.fragment; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.github.mikephil.charting.charts.LineChart; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.formatter.IAxisValueFormatter; import com.squareup.okhttp.Callback; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import com.xseec.eds.R; import com.xseec.eds.activity.DataLogSettingActivity; import com.xseec.eds.model.DataLogFactor; import com.xseec.eds.model.tags.StoredTag; import com.xseec.eds.util.Generator; import com.xseec.eds.util.ViewHelper; import com.xseec.eds.util.WAJsonHelper; import com.xseec.eds.util.WAServiceHelper; import com.xseec.eds.widget.MyMarkerView; import com.xseec.eds.widget.TimeXAxisValueFormatter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import butterknife.ButterKnife; import butterknife.InjectView; import static android.app.Activity.RESULT_OK; /** * A simple {@link Fragment} subclass. */ public class DataLogFragment extends BaseFragment { @InjectView(R.id.line_chart) LineChart lineChart; @InjectView(R.id.toolbar) Toolbar toolbar; @InjectView(R.id.text_first) TextView textFrist; @InjectView(R.id.text_secend) TextView textSecend; @InjectView(R.id.text_last) TextView textLast; @InjectView(R.id.progress_data_log) ProgressBar progressDataLog; @InjectView(R.id.text_item_first) TextView textItemFirst; @InjectView(R.id.text_item_secend) TextView textItemSecend; @InjectView(R.id.text_item_last) TextView textItemLast; private List<StoredTag> storedTagList; private DataLogFactor defaultFactor; private boolean customYAxisRange=false; private static final String EXT_TAG = "tags"; private static final String EXT_FACTOR = "default_factor"; public static final String KEY_FACTOR = "factor"; private static final int REQUEST_CODE_TIME = 1; public static DataLogFragment newInstance(List<String> tagNames, DataLogFactor factor) { Bundle bundle = new Bundle(); bundle.putStringArrayList(EXT_TAG, (ArrayList<String>) tagNames); bundle.putParcelable(EXT_FACTOR, factor); DataLogFragment fragment = new DataLogFragment(); fragment.setArguments(bundle); return fragment; } public DataLogFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment //必须添加此语句,方能触发onCreateOptionsMenu setHasOptionsMenu(true); View view = inflater.inflate(R.layout.fragment_data_log, container, false); ButterKnife.inject(this, view); getActivity().setTitle(R.string.detail_trend); ViewHelper.initToolbar((AppCompatActivity) getActivity(), toolbar, R.drawable .ic_arrow_back_white_24dp); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); List<String> tagNames = getArguments().getStringArrayList(EXT_TAG); storedTagList = new ArrayList<>(); for (String tagName : tagNames) { storedTagList.add(new StoredTag(tagName, StoredTag.DataType.MAX)); } defaultFactor = getArguments().getParcelable(EXT_FACTOR); // initFactor(); initChart(); } private void initChart() { //lineChart.animateX(2000); lineChart.getDescription().setEnabled(false); MyMarkerView mv = new MyMarkerView(getContext(), R.layout.custom_marker_view); mv.setChartView(lineChart); // For bounds control lineChart.setMarker(mv); YAxis yAxis = lineChart.getAxisRight(); yAxis.setEnabled(false); setData(); } private void setData() { progressDataLog.setVisibility(View.VISIBLE); //横坐标设定 XAxis xAxis = lineChart.getXAxis(); IAxisValueFormatter iAxisValueFormatter = new TimeXAxisValueFormatter(lineChart,defaultFactor); xAxis.setValueFormatter(iAxisValueFormatter); LineData data = lineChart.getData(); if (data != null) { data.clearValues(); } for (StoredTag tag : storedTagList) { tag.setDataType(defaultFactor.getDataType()); } //取消曲线上已经高亮的点,否则重绘(如查询其他时间)时因找不到高亮点而闪退 lineChart.highlightValues(null); //累加值需要相减,应多取一点 if(isEnergy()){ defaultFactor.setRecords(defaultFactor.getRecords()+1); } WAServiceHelper.sendTagLogRequest(defaultFactor.getStartTimeString(), defaultFactor.getIntervalType(), defaultFactor.getInterval(), defaultFactor.getRecords(), storedTagList, new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { refreshViewsInThread(response); } }); } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.reset(this); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { //super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.query_menu, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.query_time: if (defaultFactor != null) { if(isEnergy()){ //查询前做+1操作 defaultFactor.setRecords(defaultFactor.getRecords()-1); } DataLogSettingActivity.start(getActivity(), REQUEST_CODE_TIME, defaultFactor); } break; case R.id.query_config: customYAxisRange=!customYAxisRange; YAxis yAxis=lineChart.getAxisLeft(); if(customYAxisRange){ LineData lineData=lineChart.getLineData(); float range=Math.abs(lineData.getYMax()-lineData.getYMin()); float min=lineData.getYMin()-9*range; yAxis.setAxisMinimum(min<0?0:min); Toast.makeText(getContext(),R.string.detail_percision_low,Toast.LENGTH_SHORT).show(); }else { yAxis.resetAxisMinimum(); LineData lineData=lineChart.getLineData(); yAxis.calculate(lineData.getYMin(),lineData.getYMax()); Toast.makeText(getContext(),R.string.detail_percision_hight,Toast.LENGTH_SHORT).show(); } lineChart.resetZoom(); lineChart.animateX(2000); lineChart.invalidate(); break; default: break; } return super.onOptionsItemSelected(item); } //在Activity中重写onActivityResult方法触发Fragment @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_CODE_TIME: if (resultCode == RESULT_OK) { defaultFactor = data.getParcelableExtra(KEY_FACTOR); setData(); } break; default: break; } } private boolean isEnergy() { String tagName = storedTagList.get(0).getTagName(); return Pattern.compile("E[PQS]").matcher(tagName).find(); } private boolean hasLinkRadio() { return isEnergy() && defaultFactor.getIntervalType() == StoredTag.IntervalType.H &&defaultFactor.getRecords() == DataLogFactor.INTERVAL_ENERGY_LINK_RADIO+1; } @Override protected void onRefreshViews(String jsonData) { //查询时间可能包含尚未发生的"未来时间区段"数据 jsonData = Generator.removeFuture(jsonData); List<String>[] values = WAJsonHelper.getTagLog(jsonData); if (values == null || values.length == 0) { return; } //电能累加值换算 if (isEnergy()) { values[0] = Generator.genPerEnergyEntryList(values[0]); } progressDataLog.setVisibility(View.GONE); LineData lineData = new LineData(); String legenName = null; LineDataSet lineDataSet1 = null; //今日值曲线+昨日环比 if (hasLinkRadio() && values[0].size() > 24) { List<String> value = values[0];// Generator.genPerEnergyEntryList(values[0]); List<String> today = value.subList(24, value.size()); legenName = getString(R.string.detail_yesterday); value = value.subList(0, 24); //新增今日值曲线 List<Entry> entryList1 = Generator.convertEntryList(today, 0); lineDataSet1 = new LineDataSet(entryList1, getString(R.string.detail_today)); lineDataSet1.setColor(ContextCompat.getColor(getContext(), R.color.colorAccent)); lineDataSet1.setCircleColor(ContextCompat.getColor(getContext(), R.color .colorAccent)); lineDataSet1.setLineWidth(2f); lineDataSet1.setCircleRadius(4f); //lineChart.getAxisLeft().setAxisMinimum(0); //lineData.addDataSet(lineDataSet1); //赋值 float totalToday = Generator.getSumFromEntryList(entryList1, entryList1.size()); //此语句与下面语句重复计算 List<Entry> yesterdayEntryList = Generator.convertEntryList(value, 0); float totalYesterday = Generator.getSumFromEntryList(yesterdayEntryList, entryList1.size()); float linkRadio = Math.round((totalToday - totalYesterday) / totalYesterday * 10000) / 100f; textItemFirst.setText(getString(R.string.detail_today)); textItemSecend.setText(getString(R.string.detail_yesterday_same)); textItemLast.setText(getString(R.string.detail_link_ratio)); textFrist.setText(String.valueOf(totalToday)); textSecend.setText(String.valueOf(totalYesterday)); textLast.setText(linkRadio + "%"); int resId = linkRadio < 0 ? R.drawable.ic_arrow_downward_green_a700_24dp : R .drawable.ic_arrow_upward_red_a200_24dp; ViewHelper.drawTextBounds(textLast, resId, 0, 0, 0); values[0] = value; } else { textItemFirst.setText(getString(R.string.detail_max)); textItemSecend.setText(getString(R.string.detail_min)); textItemLast.setText(getString(R.string.detail_avg)); ViewHelper.drawTextBounds(textLast, 0, 0, 0, 0); } int[] colors = new int[]{R.color.colorPhaseA, R.color.colorPhaseB, R.color .colorPhaseC, R .color.colorAlarm}; List<Entry> entryLists = new ArrayList<>(); for (int i = 0; i < values.length; i++) { List<String> value = values[i]; if(value.size()==0){ continue; } List<Entry> entryList = Generator.convertEntryList(value, 0); legenName = (i == 0 && legenName != null) ? legenName : storedTagList.get(i) .getTagAlias(); LineDataSet lineDataSet = new LineDataSet(entryList, legenName); int colorIndex; if (values.length == 1) { colorIndex = 1; lineDataSet.setDrawFilled(true); Drawable drawable = ContextCompat.getDrawable(getContext(), R.drawable .chart_fade_blue); lineDataSet.setFillDrawable(drawable); } else { colorIndex = i % colors.length; lineDataSet.setLineWidth(2f); } lineDataSet.setColor(ContextCompat.getColor(getContext(), colors[colorIndex])); lineDataSet.setCircleColor(ContextCompat.getColor(getContext(), colors[colorIndex])); //临时方案:Ir,不能计入均值计算列中 if (i >= 3) { lineDataSet.setDrawCircles(false); } else { entryLists.addAll(entryList); } lineData.addDataSet(lineDataSet); } //保证今日值曲线置于顶层 if (lineDataSet1 != null) { lineData.addDataSet(lineDataSet1); } lineData.setDrawValues(false); lineChart.setData(lineData); //动画 lineChart.animateX(2000); lineChart.invalidate(); //赋值 if (!hasLinkRadio()) { textFrist.setText(String.valueOf(lineData.getYMax())); textSecend.setText(String.valueOf(lineData.getYMin())); textLast.setText(String.valueOf(Generator.getAvgFromEntryList(entryLists))); } } }
qikaifzj/ludwig
src/lc_droplet.h
<filename>src/lc_droplet.h /***************************************************************************** * * lc_droplet.h * * Routines related to liquid crystal droplet free energy * and molecular field. * * Edinburgh Soft Matter and Statistical Physics Group and * Edinburgh Parallel Computing Centre * * (c) 2012-2018 The University of Edinburgh * * Contributing authors: * <NAME> * <NAME> (<EMAIL>) * *****************************************************************************/ #ifndef LUDWIG_LC_DROPLET_H #define LUDWIG_LC_DROPLET_H #include "coords.h" #include "blue_phase.h" #include "symmetric.h" #include "field.h" #include "field_grad.h" #include "hydro.h" #include "map_s.h" #include "wall.h" typedef struct fe_lc_droplet_s fe_lc_droplet_t; typedef struct fe_lc_droplet_param_s fe_lc_droplet_param_t; struct fe_lc_droplet_s { fe_t super; pe_t * pe; /* Parallel environment */ cs_t * cs; /* Coordinate system */ fe_lc_droplet_param_t * param; /* Coupling parameters */ fe_lc_t * lc; /* LC free energy etc */ fe_symm_t * symm; /* Symmetric free energy etc */ fe_lc_droplet_t * target; /* Target pointer */ }; struct fe_lc_droplet_param_s { double gamma0; /* \gamma(phi) = gamma0 + delta x (1 + phi) */ double delta; /* As above */ double w; /* Surface anchoring constant */ }; __host__ int fe_lc_droplet_create(pe_t * pe, cs_t * cs, fe_lc_t * lc, fe_symm_t * symm, fe_lc_droplet_t ** p); __host__ int fe_lc_droplet_free(fe_lc_droplet_t * fe); __host__ int fe_lc_droplet_param(fe_lc_droplet_t * fe, fe_lc_droplet_param_t * param); __host__ int fe_lc_droplet_param_set(fe_lc_droplet_t * fe, fe_lc_droplet_param_t param); __host__ int fe_lc_droplet_target(fe_lc_droplet_t * fe, fe_t ** target); __host__ int fe_lc_droplet_bodyforce(fe_lc_droplet_t * fe, hydro_t * hydro); __host__ __device__ int fe_lc_droplet_gamma(fe_lc_droplet_t * fe, int index, double * gamma); __host__ __device__ int fe_lc_droplet_fed(fe_lc_droplet_t * fe, int index, double * fed); __host__ __device__ int fe_lc_droplet_stress(fe_lc_droplet_t * fe, int index, double s[3][3]); __host__ __device__ void fe_lc_droplet_stress_v(fe_lc_droplet_t * fe, int index, double s[3][3][NSIMDVL]); __host__ __device__ int fe_lc_droplet_mol_field(fe_lc_droplet_t * fe, int index, double h[3][3]); __host__ __device__ void fe_lc_droplet_mol_field_v(fe_lc_droplet_t * fe, int index, double h[3][3][NSIMDVL]); __host__ __device__ int fe_lc_droplet_mu(fe_lc_droplet_t * fe, int index, double * mu); __host__ __device__ int fe_lc_droplet_str_symm(fe_lc_droplet_t * fe, int index, double s[3][3]); __host__ __device__ int fe_lc_droplet_str_anti(fe_lc_droplet_t * fe, int index, double s[3][3]); __host__ __device__ void fe_lc_droplet_str_symm_v(fe_lc_droplet_t * fe, int index, double s[3][3][NSIMDVL]); __host__ __device__ void fe_lc_droplet_str_anti_v(fe_lc_droplet_t * fe, int index, double s[3][3][NSIMDVL]); __host__ int fe_lc_droplet_bodyforce_wall(fe_lc_droplet_t * fe, lees_edw_t * le, hydro_t * hydro, map_t * map, wall_t * wall); #endif
avelez93/tfx
tfx/dsl/input_resolution/ops/unnest_op.py
# Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # 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. """Module for Unnest operator.""" from tfx.dsl.input_resolution import resolver_op from tfx.orchestration.portable.input_resolution import exceptions from tfx.utils import typing_utils class Unnest( resolver_op.ResolverOp, arg_data_types=(resolver_op.DataTypes.ARTIFACT_MULTIMAP,), return_data_type=resolver_op.DataTypes.ARTIFACT_MULTIMAP_LIST, ): """Unnest operator. Unnest operator split a *`key` channel* of multiple artifacts into multiple dicts each with a channel with single artifact. Pseudo code example: Unnest({x: [x1, x2, x3]}, key=x) = [{x: [x1]}, {x: [x2]}, {x: [x3]}] For channels other than key channel remains the same. Pseudo code example: Unnest({x: [x1, x2, x3], y: [y1]}, key=x) = [{x: [x1], y: [y1]}, {x: [x2], y: [y1]}, {x: [x3], y: [y1]}] """ key = resolver_op.ResolverOpProperty(type=str) def apply(self, input_dict: typing_utils.ArtifactMultiMap): if self.key not in input_dict: raise exceptions.FailedPreconditionError( f'Input dict does not contain the key {self.key}. ' f'Available: {list(input_dict.keys())}') main_channel = input_dict.get(self.key) rest = {k: v for k, v in input_dict.items() if k != self.key} result = [] for main_artifact in main_channel: result.append({self.key: [main_artifact], **rest}) return result
freestyle076/MyMsInspect
src/org/fhcrc/cpl/viewer/quant/gui/ProteinQuantSummaryFrame.java
/* * Copyright (c) 2003-2012 <NAME> Cancer Research Center * * 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.fhcrc.cpl.viewer.quant.gui; import org.apache.log4j.Level; import org.fhcrc.cpl.toolbox.proteomics.feature.filehandler.PepXMLFeatureFileHandler; import org.fhcrc.cpl.toolbox.proteomics.feature.FeatureSet; import org.fhcrc.cpl.toolbox.proteomics.feature.Feature; import org.fhcrc.cpl.toolbox.proteomics.feature.AnalyzeICAT; import org.fhcrc.cpl.toolbox.proteomics.feature.extraInfo.MS2ExtraInfoDef; import org.fhcrc.cpl.toolbox.proteomics.feature.extraInfo.IsotopicLabelExtraInfoDef; import org.fhcrc.cpl.viewer.quant.QuantEvent; import org.fhcrc.cpl.viewer.quant.QuantEventAssessor; import org.fhcrc.cpl.viewer.gui.WorkbenchFrame; import org.fhcrc.cpl.viewer.gui.ViewerInteractiveModuleFrame; import org.fhcrc.cpl.viewer.Localizer; import org.fhcrc.cpl.viewer.ViewerUserManualGenerator; import org.fhcrc.cpl.viewer.qa.QAUtilities; import org.fhcrc.cpl.viewer.commandline.ViewerCommandModuleUtilities; import org.fhcrc.cpl.viewer.commandline.modules.BaseViewerCommandLineModuleImpl; import org.fhcrc.cpl.toolbox.proteomics.filehandler.ProtXmlReader; import org.fhcrc.cpl.toolbox.proteomics.QuantitationUtilities; import org.fhcrc.cpl.toolbox.proteomics.ProteinUtilities; import org.fhcrc.cpl.toolbox.proteomics.MSRun; import org.fhcrc.cpl.toolbox.ApplicationContext; import org.fhcrc.cpl.toolbox.Rounder; import org.fhcrc.cpl.toolbox.commandline.BaseCommandLineModuleImpl; import org.fhcrc.cpl.toolbox.commandline.CommandLineModule; import org.fhcrc.cpl.toolbox.commandline.CommandLineModuleExecutionException; import org.fhcrc.cpl.toolbox.commandline.arguments.*; import org.fhcrc.cpl.toolbox.gui.ListenerHelper; import org.fhcrc.cpl.toolbox.gui.chart.PanelWithScatterPlot; import org.fhcrc.cpl.toolbox.gui.chart.PanelWithHistogram; import org.fhcrc.cpl.toolbox.gui.widget.SwingWorkerWithProgressBarDialog; import org.apache.log4j.Logger; import org.jfree.chart.plot.XYPlot; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import javax.swing.event.ListSelectionListener; import javax.swing.event.ListSelectionEvent; import javax.imageio.ImageIO; import javax.xml.stream.XMLStreamException; import java.io.*; import java.util.*; import java.util.List; import java.util.concurrent.ExecutionException; import java.awt.*; import java.awt.event.*; /** * A dialog box with a table of quantitative events for a single protein, or a few. Controls for viewing * event details and for generating charts from a list of events. The latter action closes the dialog * and adds the events to the events in the main Qurate window */ public class ProteinQuantSummaryFrame extends JDialog { protected static Logger _log = Logger.getLogger(ProteinQuantSummaryFrame.class); protected int width = 900; protected int height = 900; protected int LOGRATIO_HISTOGRAM_PANEL_HEIGHT = 150; //min and max ratio for display in table. Ratio must be > min OR < max, or both protected float minHighRatio = 0f; protected float maxLowRatio = 999f; protected int proteinDialogWidth = 500; protected int proteinDialogHeight = 800; Map<String, List<QuantEvent>> proteinEventsMap; protected String proteinTableSelectedProtein; //protein-level info protected List<String> proteinNames; protected List<Float> proteinRatio; //Quantitative events protected List<QuantEvent> quantEvents; protected List<QuantEvent> selectedQuantEvents; //SILAC or Acrylamide // protected int labelType = -1; // protected String labeledResidue = null; // protected float labelMassDiff = 0f; //needed for chart generation protected File mzXmlDir; //Output location // protected File outDir; // protected File outFile; //If the output file exists already, do we append to it? // protected boolean appendOutput = true; //dimensions protected int fullWidth = 1000; protected int fullHeight = 500; protected int summaryPanelHeight = 100; protected int propertiesWidth = 400; protected int propertiesHeight = 500; //This is hacky. It's for sizing the window appropriately when we know the number of table rows. There //is probably a much more reasonable way to do this in AWT, but I don't know it. protected final int TITLEBAR_HEIGHT = 55; protected final int STATUSPANEL_HEIGHT = 25; protected final int SUMMARYPANEL_HEIGHT = 41; protected final int TABLEROW_HEIGHT = 17; protected final int PROTEINTABLE_HISTPANEL_HEIGHT = 150; protected final int PROTEINTABLE_SCATTERPLOTPANEL_HEIGHT = 100; //container declarations public JPanel contentPanel; public JPanel summaryPanel; public JPanel mainPanel; public JScrollPane eventsScrollPane; public JPanel eventsPanel; public PanelWithLogRatioHistAndFields logRatioHistogramPanel; public PanelWithLogRatioHistAndFields perProteinLogRatioHistogramPanel; public JPanel perProteinPeptideLogRatioPanel; protected Map<String, List<String>> proteinGenesMap; //single event details components protected QuantEvent.QuantEventPropertiesTable eventPropertiesTable; protected JDialog eventPropertiesDialog; //Should we roll in events that overlap the selected events? protected boolean shouldAddOverlappingEvents = true; protected JTextArea proteinNameTextArea; protected JTextArea proteinRatioTextArea; protected JButton buttonSelectAllVisible = new JButton("Select All Visible"); protected JButton buttonDeselectAll = new JButton("Clear All"); protected JButton showProteinRatiosButton = new JButton("Show Protein Table"); protected JButton loadSelectedEventsButton = new JButton("Load Selected"); protected JButton autoAssessSelectedEventsButton = new JButton("Auto-Assess Selected"); protected JButton buildTurkHITsButton = new JButton("Build Mechanical Turk HITs"); protected JButton showPropertiesButton = new JButton("Show Event Properties"); //an array of quantitation events that are already built. These will be shown as already selected, //and un-unselectable, and will not be rebuilt. protected List<QuantEvent> existingQuantEvents; //Status message public JPanel statusPanel; public JLabel messageLabel; // ratio filter control public JLabel maxLowRatioLabel; public JLabel minHighRatioLabel; public JLabel numPassingEventsLabel; //event properties protected QuantEventsSummaryTable eventsTable; protected JTable proteinRatiosTable; protected JDialog proteinRatiosDialog; //variables that tell us what to do after events are loaded protected boolean shouldMarkAlgGoodAsGood = true; protected boolean shouldMarkAlgBadAsBad = false; protected boolean shouldMarkAlgBadAsBadIfOtherProteinSupport = true; protected File protXmlFile; protected File pepXmlFile; public ProteinQuantSummaryFrame() { initGUI(); } public ProteinQuantSummaryFrame(File mzXmlDir) throws IllegalArgumentException { this(); this.mzXmlDir = mzXmlDir; } /** * Initialize the GUI components */ protected void initGUI() { //Global stuff setSize(fullWidth, fullHeight); eventPropertiesTable = new QuantEvent.QuantEventPropertiesTable(); eventPropertiesTable.setVisible(true); JScrollPane eventPropsScrollPane = new JScrollPane(); eventPropsScrollPane.setViewportView(eventPropertiesTable); eventPropsScrollPane.setSize(propertiesWidth, propertiesHeight); eventPropertiesDialog = new JDialog(this, "Event Properties"); eventPropertiesDialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); eventPropertiesDialog.setSize(propertiesWidth, propertiesHeight); eventPropertiesDialog.setContentPane(eventPropsScrollPane); ListenerHelper helper = new ListenerHelper(this); setTitle("Protein Summary"); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.anchor = GridBagConstraints.PAGE_START; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.insets = new Insets(5,5,5,5); gbc.weighty = 1; gbc.weightx = 1; try { (getOwner()).setIconImage(ImageIO.read(WorkbenchFrame.class.getResourceAsStream("icon.gif"))); } catch (Exception e) { } try { Localizer.renderSwixml("org/fhcrc/cpl/viewer/quant/gui/ProteinQuantSummaryFrame.xml",this); assert null != contentPanel; setContentPane(contentPanel); } catch (Exception x) { ApplicationContext.errorMessage("error creating dialog", x); throw new RuntimeException(x); } buttonSelectAllVisible.setEnabled(false); helper.addListener(buttonSelectAllVisible, "buttonSelectAllVisible_actionPerformed"); buttonDeselectAll.setEnabled(false); helper.addListener(buttonDeselectAll, "buttonDeselectAll_actionPerformed"); buildTurkHITsButton.setEnabled(false); helper.addListener(buildTurkHITsButton, "buttonBuildTurkHITs_actionPerformed"); loadSelectedEventsButton.setEnabled(false); helper.addListener(loadSelectedEventsButton, "buttonLoadSelected_actionPerformed"); autoAssessSelectedEventsButton.setEnabled(false); helper.addListener(autoAssessSelectedEventsButton, "buttonAutoAssess_actionPerformed"); showPropertiesButton.setEnabled(false); helper.addListener(showPropertiesButton, "buttonShowProperties_actionPerformed"); showProteinRatiosButton.setEnabled(false); helper.addListener(showProteinRatiosButton, "buttonShowProteinRatios_actionPerformed"); //summary panel summaryPanel.setBorder(BorderFactory.createLineBorder(Color.gray)); summaryPanel.setPreferredSize(new Dimension(fullWidth, summaryPanelHeight)); summaryPanel.setMinimumSize(new Dimension(200, summaryPanelHeight)); gbc.fill = GridBagConstraints.NONE; gbc.gridwidth = 1; summaryPanel.add(buttonSelectAllVisible, gbc); summaryPanel.add(buttonDeselectAll, gbc); gbc.gridwidth = GridBagConstraints.RELATIVE; summaryPanel.add(showPropertiesButton, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; summaryPanel.add(showProteinRatiosButton, gbc); gbc.gridwidth = 1; summaryPanel.add(loadSelectedEventsButton, gbc); gbc.gridwidth = GridBagConstraints.RELATIVE; summaryPanel.add(autoAssessSelectedEventsButton, gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; summaryPanel.add(buildTurkHITsButton, gbc); gbc.fill = GridBagConstraints.BOTH; eventsScrollPane = new JScrollPane(); eventsScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); eventsScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); eventsPanel = new JPanel(); eventsPanel.setLayout(new GridBagLayout()); eventsTable = new QuantEventsSummaryTable(); eventsTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); eventsTable.getSelectionModel().addListSelectionListener(new EventsTableListSelectionHandler()); eventsScrollPane.setViewportView(eventsTable); eventsScrollPane.setMinimumSize(new Dimension(400, 400)); gbc.insets = new Insets(0,0,0,0); mainPanel.add(eventsScrollPane, gbc); logRatioHistogramPanel = new PanelWithLogRatioHistAndFields(); logRatioHistogramPanel.setBorder(BorderFactory.createTitledBorder("Log Ratios")); logRatioHistogramPanel.setPreferredSize(new Dimension(width-10, 300)); gbc.fill = GridBagConstraints.BOTH; gbc.weighty=100; gbc.gridwidth = GridBagConstraints.REMAINDER; add(logRatioHistogramPanel, gbc); //status message messageLabel = new JLabel(); messageLabel.setBackground(Color.WHITE); messageLabel.setFont(Font.decode("verdana plain 12")); messageLabel.setText(" "); statusPanel = new JPanel(); gbc.weighty=1; statusPanel.setPreferredSize(new Dimension(width-10, 50)); statusPanel.add(messageLabel, gbc); add(statusPanel, gbc); //per-protein event summary table; disembodied //todo: move this into its own class? it's getting kind of complicated proteinRatiosTable = new JTable(); proteinRatiosTable.setVisible(true); ListSelectionModel proteinTableSelectionModel = proteinRatiosTable.getSelectionModel(); proteinTableSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); proteinTableSelectionModel.addListSelectionListener(new ProteinTableListSelectionHandler()); JScrollPane proteinRatiosScrollPane = new JScrollPane(); proteinRatiosScrollPane.setViewportView(proteinRatiosTable); proteinRatiosScrollPane.setPreferredSize(new Dimension(proteinDialogWidth, proteinDialogHeight - PROTEINTABLE_HISTPANEL_HEIGHT - PROTEINTABLE_SCATTERPLOTPANEL_HEIGHT - 70)); proteinRatiosDialog = new JDialog(this, "Protein Ratios"); proteinRatiosDialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); proteinRatiosDialog.setSize(proteinDialogWidth, proteinDialogHeight); JPanel proteinRatiosContentPanel = new JPanel(); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.fill = GridBagConstraints.BOTH; proteinRatiosContentPanel.add(proteinRatiosScrollPane, gbc); proteinRatiosDialog.setContentPane(proteinRatiosContentPanel); perProteinLogRatioHistogramPanel = new PanelWithLogRatioHistAndFields(); perProteinLogRatioHistogramPanel.addRangeUpdateListener(new ProteinTableLogRatioHistogramListener()); perProteinLogRatioHistogramPanel.setBorder(BorderFactory.createTitledBorder("Log Ratios")); perProteinLogRatioHistogramPanel.setPreferredSize(new Dimension(proteinDialogWidth-10, PROTEINTABLE_HISTPANEL_HEIGHT)); gbc.fill = GridBagConstraints.BOTH; gbc.gridwidth = GridBagConstraints.REMAINDER; proteinRatiosDialog.add(perProteinLogRatioHistogramPanel, gbc); perProteinPeptideLogRatioPanel = new JPanel(); perProteinPeptideLogRatioPanel.setBorder(BorderFactory.createTitledBorder("By Peptide")); perProteinPeptideLogRatioPanel.setPreferredSize(new Dimension(proteinDialogWidth-10, PROTEINTABLE_SCATTERPLOTPANEL_HEIGHT)); proteinRatiosDialog.add(perProteinPeptideLogRatioPanel, gbc); } public void buttonShowProteinRatios_actionPerformed(ActionEvent event) { proteinRatiosDialog.setVisible(true); } /** * display the ratios for the selected event */ public class ProteinTableListSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { ListSelectionModel lsm = proteinRatiosTable.getSelectionModel(); if (lsm.isSelectionEmpty() || (lsm.getMinSelectionIndex() != lsm.getMaxSelectionIndex()) || lsm.getMinSelectionIndex() < 0) return; proteinTableSelectedProtein = (String) proteinRatiosTable.getValueAt(lsm.getMinSelectionIndex(), 0); List<QuantEvent> proteinEvents = proteinEventsMap.get(proteinTableSelectedProtein); List<Float> eventLogRatios = new ArrayList<Float>(); Map<String, List<Float>> perPeptideLogRatios = new HashMap<String, List<Float>>(); for (QuantEvent event : proteinEvents) { float logRatio = (float) Math.log(event.getRatio()); eventLogRatios.add(logRatio); List<Float> peptideLogRatios = perPeptideLogRatios.get(event.getPeptide()); if (peptideLogRatios == null) { peptideLogRatios = new ArrayList<Float>(); perPeptideLogRatios.put(event.getPeptide(), peptideLogRatios); } peptideLogRatios.add(logRatio); } //Add a crosshair at the value of the protein log ratio perProteinLogRatioHistogramPanel.setDomainCrosshairValue((float) Math.log( (Double) proteinRatiosTable.getValueAt(lsm.getMinSelectionIndex(), 1))); perProteinLogRatioHistogramPanel.setLogRatios(eventLogRatios); perProteinLogRatioHistogramPanel.setSize(proteinDialogWidth-10, PROTEINTABLE_HISTPANEL_HEIGHT); perProteinLogRatioHistogramPanel.setMaxLowRatio(1000); perProteinLogRatioHistogramPanel.setMinHighRatio(0.0001f); //Scatterplot of per-peptide log-ratios perProteinPeptideLogRatioPanel.removeAll(); PanelWithScatterPlot peptideProteinLogRatioScatterPlot = new PanelWithScatterPlot(); int peptideIndex = 0; for (List<Float> peptideLogRatios : perPeptideLogRatios.values()) { List<Float> dummyYValues = new ArrayList<Float>(peptideLogRatios.size()); for (int i=0; i<peptideLogRatios.size(); i++) dummyYValues.add((float)peptideIndex); peptideProteinLogRatioScatterPlot.addData(peptideLogRatios, dummyYValues, "asdf"); peptideIndex++; } //remove axes from chart ((XYPlot)peptideProteinLogRatioScatterPlot.getPlot()).getRangeAxis().setVisible(false); ((XYPlot)peptideProteinLogRatioScatterPlot.getPlot()).getDomainAxis().setVisible(false); peptideProteinLogRatioScatterPlot.setPointSize(6); peptideProteinLogRatioScatterPlot.getChart().removeLegend(); peptideProteinLogRatioScatterPlot.getChart().getXYPlot().setDomainGridlinesVisible(false); peptideProteinLogRatioScatterPlot.getChart().getXYPlot().setRangeGridlinesVisible(false); peptideProteinLogRatioScatterPlot.getChart().getXYPlot().getDomainAxis().setLowerBound( Math.log(perProteinLogRatioHistogramPanel.getMinRatioBound())); peptideProteinLogRatioScatterPlot.getChart().getXYPlot().getDomainAxis().setUpperBound( Math.log(perProteinLogRatioHistogramPanel.getMaxRatioBound())); peptideProteinLogRatioScatterPlot.getChart().getXYPlot().getRangeAxis().setLowerBound(-1); peptideProteinLogRatioScatterPlot.getChart().getXYPlot().getRangeAxis().setUpperBound( perPeptideLogRatios.size()+1); peptideProteinLogRatioScatterPlot.setPreferredSize( new Dimension(proteinDialogWidth-20, PROTEINTABLE_SCATTERPLOTPANEL_HEIGHT-30)); peptideProteinLogRatioScatterPlot.updateUI(); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.anchor = GridBagConstraints.PAGE_START; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.insets = new Insets(5,5,5,5); gbc.weighty = 1; gbc.weightx = 1; perProteinPeptideLogRatioPanel.add(peptideProteinLogRatioScatterPlot, gbc); } } } /** * Find all the peptides contributing to the ratio for the FIRST OCCURRENCE of a * protein in the pepXML file, find all quantitative events for those peptides in the * pepXML file, and show them * @param pepXmlFile * @param proteins */ public void displayData(File pepXmlFile, File protXmlFile, List<ProtXmlReader.Protein> proteins) { _log.debug("displayData 1***"); this.protXmlFile = protXmlFile; this.pepXmlFile = pepXmlFile; Collections.sort(proteins, new Comparator<ProtXmlReader.Protein>() { public int compare(ProtXmlReader.Protein o1, ProtXmlReader.Protein o2) { return o1.getProteinName().compareTo(o2.getProteinName()); } }); DefaultTableModel proteinRatiosTableModel = new DefaultTableModel(0, 4) { //all cells uneditable public boolean isCellEditable(int row, int column) { return false; } public Class getColumnClass(int columnIndex) { switch (columnIndex) { case 0:return String.class; case 1: return Float.class; case 2: case 3: return Integer.class; } return String.class; } }; proteinRatiosTable.setModel(proteinRatiosTableModel); proteinRatiosTable.getColumnModel().getColumn(0).setHeaderValue("Protein"); proteinRatiosTable.getColumnModel().getColumn(1).setHeaderValue("Ratio"); proteinRatiosTable.getColumnModel().getColumn(2).setHeaderValue("Quant Peptides"); proteinRatiosTable.getColumnModel().getColumn(3).setHeaderValue("Events"); _log.debug("displayData getting protein info"); this.proteinNames = new ArrayList<String>(); List<ProtXmlReader.QuantitationRatio> quantRatios = new ArrayList<ProtXmlReader.QuantitationRatio>(); proteinRatiosTableModel.setRowCount(proteins.size()); for (int i=0; i<proteins.size(); i++) { String proteinName = proteins.get(i).getProteinName(); ProtXmlReader.QuantitationRatio quantRatio = proteins.get(i).getQuantitationRatio(); quantRatios.add(quantRatio); proteinNames.add(proteinName); //careful -- the 3rd column values are populated below proteinRatiosTableModel.setValueAt(proteinName, i, 0); proteinRatiosTableModel.setValueAt(Rounder.round(quantRatio.getRatioMean(),2), i, 1); } if (proteinNames.size() == 1) eventsTable.hideProteinColumn(); if (proteinGenesMap == null) eventsTable.hideGeneColumn(); else { eventsTable.setProteinGenesMap(proteinGenesMap); } TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(proteinRatiosTableModel); proteinRatiosTable.setRowSorter(sorter); contentPanel.updateUI(); _log.debug("displayData getting quant events"); quantEvents = new ArrayList<QuantEvent>(); Map<String, Set<String>> peptideProteinsQuantMap = new HashMap<String, Set<String>>(); for (int i=0; i<proteins.size(); i++) { for (String peptide : quantRatios.get(i).getPeptides()) { Set<String> proteinsThisPep = peptideProteinsQuantMap.get(peptide); if (proteinsThisPep == null) { proteinsThisPep = new HashSet<String>(); peptideProteinsQuantMap.put(peptide, proteinsThisPep); } proteinsThisPep.add(proteins.get(i).getProteinName()); } } _log.debug("peptideProteinsQuantMap has " + peptideProteinsQuantMap.size() + " peptides."); System.err.println("Contains the one? " + peptideProteinsQuantMap.containsKey("QCPYCLLYK")); proteinEventsMap = new HashMap<String, List<QuantEvent>>(); Map<String, Set<String>> proteinPeptidesMap = new HashMap<String, Set<String>>(); try { PepXMLFeatureFileHandler.PepXMLFeatureSetIterator fsi = new PepXMLFeatureFileHandler.PepXMLFeatureSetIterator(pepXmlFile); int numFractions = 0; setMessage("Loading all pepXML fractions..."); _log.debug("Loading all pepXML fractions..."); while (fsi.hasNext()) { boolean thisFracHasEvents = false; FeatureSet featureSet = fsi.next(); setMessage("Checking fraction " + MS2ExtraInfoDef.getFeatureSetBaseName(featureSet)); _log.debug("Checking fraction " + MS2ExtraInfoDef.getFeatureSetBaseName(featureSet)); String featureSetBaseName = MS2ExtraInfoDef.getFeatureSetBaseName(featureSet); //check all features to see if they're in our list of peptides. If so, add to quantEvents for (Feature feature : featureSet.getFeatures()) { String peptide = MS2ExtraInfoDef.getFirstPeptide(feature); if (peptideProteinsQuantMap.containsKey(peptide) && IsotopicLabelExtraInfoDef.hasRatio(feature)) { thisFracHasEvents = true; //pick up the labeled residue from the first feature // if (labeledResidue == null) // { // AnalyzeICAT.IsotopicLabel label = IsotopicLabelExtraInfoDef.getLabel(feature); // if (label != null) // { // labeledResidue = "" + label.getResidue(); // labelMassDiff = label.getHeavy() - label.getLight(); // _log.debug("Found label: " + labeledResidue + ", " + labelMassDiff); // } // } QuantEvent quantEvent = new QuantEvent(feature, featureSetBaseName); quantEvent.setProtein(new ArrayList<String>(peptideProteinsQuantMap.get(peptide)).get(0)); quantEvents.add(quantEvent); for (String protein : peptideProteinsQuantMap.get(peptide)) { Set<String> peptidesThisProtein = proteinPeptidesMap.get(protein); if (peptidesThisProtein == null) { peptidesThisProtein = new HashSet<String>(); proteinPeptidesMap.put(protein, peptidesThisProtein); } peptidesThisProtein.add(quantEvent.getPeptide()); List<QuantEvent> eventsThisProtein = proteinEventsMap.get(protein); if (eventsThisProtein == null) { eventsThisProtein = new ArrayList<QuantEvent>(); proteinEventsMap.put(protein, eventsThisProtein); } eventsThisProtein.add(quantEvent); } } } if (thisFracHasEvents) numFractions++; } _log.debug("Processed all pepXML fractions "); for (int i=0; i<proteins.size(); i++) { String protein = proteinNames.get(i); if (proteinPeptidesMap.get(proteinNames.get(i)) != null) proteinRatiosTableModel.setValueAt(proteinPeptidesMap.get(protein).size(), i, 2); if (proteinEventsMap.get(proteinNames.get(i)) != null) proteinRatiosTableModel.setValueAt(proteinEventsMap.get(protein).size(), i, 3); } if (numFractions < 2) { setMessage("Loaded all quantitation events from 1 fraction"); _log.debug("Loaded all quantitation events from 1 fraction"); } else { setMessage("Loaded all quantitation events from " + numFractions + " separate fractions"); _log.debug("Loaded all quantitation events from " + numFractions + " separate fractions"); } // if (labeledResidue == null) // infoMessage("WARNING: unable to determine modification used for quantitation. " + // "Cannot collapse light and heavy states or perform assessment."); // else // { // labelType = QuantitationUtilities.inferLabelType(labeledResidue, labelMassDiff); // } } catch (Exception e) { //check if the file has a .pep.xml extension, in case someone put the wrong file in if (pepXmlFile.getName().toLowerCase().endsWith("pep.xml")) errorMessage("Failed to load features from pepXML file: " + e.getMessage(), e); else { infoMessage("Failed to load pepXML file " + pepXmlFile.getName() + ". Extension is not .pep.xml... did you specify the wrong file?"); e.printStackTrace(System.err); } return; } _log.debug("Done loading quant events. Events: " + quantEvents.size()); if (quantEvents.isEmpty()) { throw new RuntimeException("No quantitation events found!"); } //sort by peptide, then fraction, then charge, then modifications Collections.sort(quantEvents, new QuantEvent.ProteinPeptideFractionChargeModificationsRatioAscComparator()); _log.debug("About to display events..."); displayEvents(); if (quantRatios.size() == 1) { eventsTable.setLogRatioHeaderRatio(quantRatios.get(0).getRatioMean()); } _log.debug("About to update extreme ratio GUI..."); updateExtremeRatioGUI(); } /** * Chart-building is long-running and needs to provide user feedback on status, so it * runs in a SwingWorker that displays a progress bar. * * This disposes the parent (ProteinQuantSummaryFrame) at the end if disposeWhenDone is true, which is a bit goofy, * but that's the signal for the charts that we build here to be added to the QuantitationReviewer. * Would probably be cleaner to send that signal some other way. * * */ protected class ChartBuilderWorker extends SwingWorkerWithProgressBarDialog<Throwable, String> { protected QuantitationVisualizer quantVisualizer; protected static final String expressionForLabel = "Processed " + SwingWorkerWithProgressBarDialog.CURRENT_VALUE_TOKEN + " of " + SwingWorkerWithProgressBarDialog.MAX_VALUE_TOKEN + " events"; protected boolean disposeWhenDone = true; protected boolean touchUpEventsWhenDone = true; ChartBuilderWorker(JDialog parent, QuantitationVisualizer quantVisualizer) { super(parent, 0, selectedQuantEvents.size(), 0, expressionForLabel, "Building Charts..."); this.quantVisualizer = quantVisualizer; // this.quantVisualizer.setLabelType(labelType); quantVisualizer.addProgressListener(new ProgressBarUpdater(progressBar)); } protected class ProgressBarUpdater implements ActionListener { protected JProgressBar progressBar; public ProgressBarUpdater(JProgressBar progressBar) { this.progressBar = progressBar; } public void actionPerformed(ActionEvent event) { int numProcessed = Integer.parseInt(event.getActionCommand()); updateLabelText(numProcessed); progressBar.setValue(numProcessed); } } public Throwable doInBackground() { try { selectedQuantEvents = quantVisualizer.visualizeQuantEvents(selectedQuantEvents, true); } catch (IOException e) { ApplicationContext.errorMessage(e.getMessage(),e); return e; } finally { if (progressDialog != null) progressDialog.dispose(); } return null; } protected void done() { Throwable throwable = null; try { throwable = get(); } catch (Exception ex) { throwable = null; ApplicationContext.infoMessage("NOTE: Error calling get()"); } if (throwable == null) { // infoMessage("Saved chart summary to file " + quantVisualizer.getOutTsvFile().getAbsolutePath()); if (touchUpEventsWhenDone) ((ProteinQuantSummaryFrame) parent).postEventLoad(disposeWhenDone); else { if (disposeWhenDone) parent.dispose(); else infoMessage("Done building charts"); } } else { errorMessage("Error building charts", throwable); } } } public void buttonShowProperties_actionPerformed(ActionEvent event) { eventPropertiesDialog.setVisible(true); } /** * Build HITs for the Mechanical Turk * @param event */ public void buttonBuildTurkHITs_actionPerformed(ActionEvent event) { loadSelectedEventsFromTable(); if (selectedQuantEvents.isEmpty()) { infoMessage("No new events selected"); return; } ApplicationContext.infoMessage(selectedQuantEvents.size() + " events selected for charts"); setMessage("Building charts for " + selectedQuantEvents.size() + " events..."); QuantitationVisualizer quantVisualizer = new QuantitationVisualizer(); quantVisualizer.setMzXmlDir(mzXmlDir); BuildTurkParametersCLM turkParmsCLM = new BuildTurkParametersCLM(); ViewerInteractiveModuleFrame interactFrame = new ViewerInteractiveModuleFrame(turkParmsCLM, true, null); interactFrame.setModal(true); interactFrame.setTitle("Turk HIT Creation Settings"); interactFrame.setUserManualGenerator(new ViewerUserManualGenerator()); boolean hasRunSuccessfully = interactFrame.collectArguments(); interactFrame.dispose(); if (!hasRunSuccessfully) return; quantVisualizer.setOutDir(turkParmsCLM.outDir); quantVisualizer.setOutTurkFile(new File(turkParmsCLM.outDir, "hits.tsv")); quantVisualizer.setOutTsvFile(new File(turkParmsCLM.outDir, "qurate.tsv")); quantVisualizer.setShouldCreateCharts(turkParmsCLM.buildOtherCharts); quantVisualizer.setTurkImageURLPrefix(turkParmsCLM.imageUrlPrefix); quantVisualizer.setShow3DPlots(turkParmsCLM.buildOtherCharts && turkParmsCLM.build3DCharts); quantVisualizer.setWriteHTMLAndText(true); ChartBuilderWorker swingWorker = new ChartBuilderWorker(this, quantVisualizer); swingWorker.disposeWhenDone = false; swingWorker.touchUpEventsWhenDone = false; swingWorker.execute(); } /** * Trivial class for capturing arguments for the turk HIT creator */ protected class BuildTurkParametersCLM extends BaseCommandLineModuleImpl { protected File outDir; protected boolean buildOtherCharts = false; protected String imageUrlPrefix = ""; protected boolean build3DCharts = false; public BuildTurkParametersCLM() { init(); } protected void init() { mCommandName = "dummybtp"; mHelpMessage =""; mShortDescription = ""; CommandLineArgumentDefinition[] argDefs = { new BooleanArgumentDefinition("buildothercharts", true, "Build other Qurate charts, in addition to Turk Image?", buildOtherCharts), new BooleanArgumentDefinition("build3dcharts", false, "Build 3D Qurate charts? (ignored if buildothercharts is false) This is called out " + "separately because 3D charts take extra time to build.", build3DCharts), new DirectoryToWriteArgumentDefinition("outdir", true, "output directory for Turk images, HIT file hits.tsv, and event file qurate.tsv"), new StringArgumentDefinition("imageurlprefix", false, "URL prefix for Turk images. I.e., the complete URL for the directory in " + "which the images will be hosted, starting with http:// and ending in '/'", imageUrlPrefix), }; addArgumentDefinitions(argDefs); } public void assignArgumentValues() { buildOtherCharts = getBooleanArgumentValue("buildothercharts"); build3DCharts = getBooleanArgumentValue("build3dcharts"); outDir = getFileArgumentValue("outdir"); imageUrlPrefix = getStringArgumentValue("imageurlprefix"); } public void execute() {} } /** * Load the appropriate events from the table, rationalizing overlap if necessary */ protected void loadSelectedEventsFromTable() { selectedQuantEvents = eventsTable.getSelectedEvents(); if (selectedQuantEvents.isEmpty()) return; if (shouldAddOverlappingEvents) { QuantitationVisualizer quantVisualizer = new QuantitationVisualizer(); ApplicationContext.infoMessage("Finding all overlapping events, starting with " + selectedQuantEvents.size()); //This is not as efficient as it could be. Rather than looking for overlapping events //just for our selected events, I find all sets of overlapping events and then look //for selected events in them. Doing it in a more targeted way would get pretty complicated, //though, and it's not a big burden to check them all. List<QuantEvent> allOverlappingEvents = quantVisualizer.findNonOverlappingQuantEventsAllPeptides(quantEvents); _log.debug("Got overlapping events, " + allOverlappingEvents.size()); List<QuantEvent> eventsRepresentingSelectedAndOverlap = new ArrayList<QuantEvent>(); for (QuantEvent quantEvent : allOverlappingEvents) { //if the main event was selected, great: add it and move on if (selectedQuantEvents.contains(quantEvent)) { eventsRepresentingSelectedAndOverlap.add(quantEvent); continue; } //if any of the subsumed events was selected, add the main event and move on for (QuantEvent otherEvent : quantEvent.getOtherEvents()) { if (selectedQuantEvents.contains(otherEvent)) { eventsRepresentingSelectedAndOverlap.add(quantEvent); break; } } } selectedQuantEvents = eventsRepresentingSelectedAndOverlap; ApplicationContext.infoMessage("Including overlapping events, selected events: " + selectedQuantEvents.size()); } } protected class EventAssessorWorker extends SwingWorkerWithProgressBarDialog<Throwable, String> { protected QuantEventAssessor quantAssessor; protected List<QuantEvent> eventsToAssess; protected List<Float> goodEventLogRatios = new ArrayList<Float>(); protected List<Float> badEventLogRatios = new ArrayList<Float>(); EventAssessorWorker(JDialog parent, QuantEventAssessor quantAssessor, List<QuantEvent> eventsToAssess) { super(parent, 0, eventsToAssess.size(), 0, "Processed " + SwingWorkerWithProgressBarDialog.CURRENT_VALUE_TOKEN + " of " + SwingWorkerWithProgressBarDialog.MAX_VALUE_TOKEN + " events", "Analyzing events..."); this.quantAssessor = quantAssessor; this.eventsToAssess = eventsToAssess; progressDialog.update(progressDialog.getGraphics()); } public Throwable doInBackground() { String fraction = ""; MSRun run = null; //Identify overlapping events, only asses one of each set, then update the others with assessment List<QuantEvent> representativeEvents = new QuantitationVisualizer().findNonOverlappingQuantEventsAllPeptides(eventsToAssess); Collections.sort(representativeEvents, new QuantEvent.FractionAscComparator()); int numGood = 0; int numTotalEventsAssessed = 0; for (QuantEvent quantEvent : representativeEvents) { if (quantEvent.getAlgorithmicAssessment() != null) continue; if (!fraction.equals(quantEvent.getFraction())) { fraction = quantEvent.getFraction(); try { File mzXmlFile = ViewerCommandModuleUtilities.findCorrespondingMzXmlFile( new File(fraction + ".pep.xml"), mzXmlDir); ApplicationContext.infoMessage("Loading mzXml file " + mzXmlFile.getAbsolutePath()); run = MSRun.load(mzXmlFile.getAbsolutePath()); ApplicationContext.infoMessage("Loaded."); } catch (IOException e) { errorMessage("ERROR! Problem loading mzXML file. Failed to load run for fraction " + fraction + ". " + "Remaining events will be left as unknown",e); if (progressDialog != null) progressDialog.dispose(); return null; } } QuantEventAssessor.QuantEventAssessment assessment = quantAssessor.assessQuantEvent(quantEvent, run); float logRatio = (float) Math.log(quantEvent.getRatio()); if (assessment.isGood()) { numGood++; if (!Float.isNaN(logRatio) && !Float.isInfinite(logRatio)) goodEventLogRatios.add((float) Math.log(quantEvent.getRatio())); } else { if (!Float.isNaN(logRatio) && !Float.isInfinite(logRatio)) badEventLogRatios.add((float) Math.log(quantEvent.getRatio())); } int numEventsRepresented = 1; //update the other events that overlap this one for (QuantEvent representedEvent : quantEvent.getOtherEvents()) { numEventsRepresented++; representedEvent.setAlgorithmicAssessment(assessment); if (assessment.isGood()) numGood++; } numTotalEventsAssessed += numEventsRepresented; updateLabelText(numTotalEventsAssessed); progressBar.setValue(numTotalEventsAssessed); progressDialog.update(progressDialog.getGraphics()); //System.err.println("Assessed event " + (i+1) + ": " + quantEvent.getAlgorithmicAssessment()); } if (progressDialog != null) progressDialog.dispose(); //Can't get this to work. Chart displays, but I can't dismiss it. if (badEventLogRatios.size() >= 5 && goodEventLogRatios.size() >= 5) { PanelWithHistogram pwh = new PanelWithHistogram(goodEventLogRatios, "Good log ratios", 200); pwh.addData(badEventLogRatios, "Bad log ratios"); JFrame frame = new JFrame("Assessed log ratios"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setPreferredSize(new Dimension(pwh.getPreferredSize().width + 10, pwh.getPreferredSize().height + 50)); frame.setSize(new Dimension(pwh.getPreferredSize().width + 10, pwh.getPreferredSize().height + 50)); frame.add(pwh); frame.setVisible(true); frame.toFront(); // JDialog dialog = pwh.displayDialog("Assessed log ratios"); // dialog.setModalityType(ModalityType.MODELESS); } infoMessage("Done. " + numGood + " out of " + numTotalEventsAssessed + " events (" + (Rounder.round(numGood * 100f / numTotalEventsAssessed, 1))+ "%) were good."); return null; } protected void done() { } } public void buttonAutoAssess_actionPerformed(ActionEvent event) { List<QuantEvent> selectedEventsByFraction = new ArrayList<QuantEvent>(eventsTable.getSelectedEvents()); if (selectedEventsByFraction.isEmpty()) { infoMessage("No events selected!"); return; } Collections.sort(selectedEventsByFraction, new QuantEvent.FractionAscComparator()); QuantEventAssessor quantAssessor = new QuantEventAssessor(); EventAssessorWorker assessorWorker = new EventAssessorWorker(this, quantAssessor, selectedEventsByFraction); assessorWorker.doInBackground(); } /** * Build charts (in a separate worker thread) and dispose() * @param event */ public void buttonLoadSelected_actionPerformed(ActionEvent event) { loadSelectedEventsFromTable(); if (selectedQuantEvents.isEmpty()) { infoMessage("No new events selected"); return; } LoadSelectedEventsCLM loadSelectedEventsCLM = new LoadSelectedEventsCLM(); ViewerInteractiveModuleFrame interactFrame = new ViewerInteractiveModuleFrame(loadSelectedEventsCLM, true, null, 80); interactFrame.setModal(true); interactFrame.setTitle("Settings for Loading Events"); interactFrame.setUserManualGenerator(new ViewerUserManualGenerator()); interactFrame.setShouldStoreAlgValues(false); boolean hasRunSuccessfully = interactFrame.collectArguments(); interactFrame.dispose(); if (!hasRunSuccessfully) return; File outDir = loadSelectedEventsCLM.outDir; ApplicationContext.infoMessage(selectedQuantEvents.size() + " events selected for charts"); setMessage("Building charts for " + selectedQuantEvents.size() + " events..."); QuantitationVisualizer quantVisualizer = new QuantitationVisualizer(); quantVisualizer.setMzXmlDir(mzXmlDir); String allProteinNamesUnderscores = concatProteinNamesMax3("_"); File proteinOutDir = new File(outDir, allProteinNamesUnderscores); proteinOutDir.mkdir(); quantVisualizer.setOutDir(outDir); File outputFile = loadSelectedEventsCLM.outFile; if (outputFile == null) outputFile = (new File(outDir, "quantitation_" + allProteinNamesUnderscores + ".tsv")); quantVisualizer.setOutTsvFile(outputFile); quantVisualizer.setOutHtmlFile(new File(outDir, "quantitation_" +allProteinNamesUnderscores + ".html")); quantVisualizer.setAppendTsvOutput(false); quantVisualizer.setShow3DPlots(loadSelectedEventsCLM.shouldBuild3DCharts); ChartBuilderWorker swingWorker = new ChartBuilderWorker(this, quantVisualizer); swingWorker.touchUpEventsWhenDone = true; swingWorker.disposeWhenDone = true; swingWorker.execute(); } protected class LoadSelectedEventsCLM extends BaseCommandLineModuleImpl { protected boolean shouldBuild3DCharts = false; protected File outDir = null; protected File outFile = null; public LoadSelectedEventsCLM() { init(); } protected void init() { mCommandName = "dummybtp"; mHelpMessage =""; mShortDescription = ""; CommandLineArgumentDefinition[] argDefs = { new BooleanArgumentDefinition("markgoodifalggood", true, "Mark events good if algorithm says they're good? Otherwise, marked unknown. " + "You can override this setting manually.", shouldMarkAlgGoodAsGood), new BooleanArgumentDefinition( "markbadifalgbad", true, "Mark events bad if algorithm says they're bad. Otherwise, marked unknown. " + "You can override this setting manually. Incompatible with markbadifalgbadandothersupport.", shouldMarkAlgBadAsBad), new BooleanArgumentDefinition( "markbadifalgbadandothersupport", true, "Mark events bad if algorithm says they're bad AND all protein ratios depending on " + "them have support from other events that the algorithm says are good? " + "Otherwise, marked unknown. You can override this setting manually. " + "Incompatible with markbadifalgbad. Setting this to 'True' will take " + "quite some time, because the algorithm will need to be run on all " + "quantitative events for all proteins in question.", shouldMarkAlgBadAsBadIfOtherProteinSupport), new BooleanArgumentDefinition("build3dcharts", false, "Build 3D Qurate charts? (ignored if buildothercharts is false) This is called out " + "separately because 3D charts take extra time to build.", shouldBuild3DCharts), }; addArgumentDefinitions(argDefs); addArgumentDefinition(new DirectoryToWriteArgumentDefinition("outdir", true, "Base output directory for charts (protein-specific charts will be created in " + "protein-specific subdirectories)")); addArgumentDefinition(new FileToWriteArgumentDefinition("out", false, "Output .tsv file location (if blank, output will be written to a temporary file)")); } public void assignArgumentValues() throws ArgumentValidationException { shouldMarkAlgGoodAsGood = getBooleanArgumentValue("markgoodifalggood"); shouldMarkAlgBadAsBad = getBooleanArgumentValue("markbadifalgbad"); shouldMarkAlgBadAsBadIfOtherProteinSupport = getBooleanArgumentValue("markbadifalgbadandothersupport"); if (shouldMarkAlgBadAsBadIfOtherProteinSupport && shouldMarkAlgBadAsBad) throw new ArgumentValidationException("Please choose only one action (at most) for events the " + "algorithm thinks are bad"); shouldBuild3DCharts = getBooleanArgumentValue("build3dcharts"); outFile = getFileArgumentValue("out"); outDir = getFileArgumentValue("outdir"); } public void execute() {} } /** * This gets called after selected events are loaded, before deferring control back to QuantReviewer. Here's * where we might mark events as Qurated good or bad, if the user has asked us to do that, based on the * algorithmic assessment. *todo: some of this stuff, particularly ID-ing events with no other support, should probably be made modular, * at least for clarity * @param shouldDispose */ public void postEventLoad(boolean shouldDispose) { if (shouldMarkAlgGoodAsGood) for (QuantEvent quantEvent : selectedQuantEvents) { if (quantEvent == null) System.err.println("************NULL EVENT!"); if (quantEvent.getAlgorithmicAssessment() == null) System.err.println("NULL ASSESSMENT!"); if (quantEvent.getAlgorithmicAssessment().isGood()) { quantEvent.setQuantCurationStatus(QuantEvent.CURATION_STATUS_GOOD); quantEvent.setComment("Auto-marked good because of algorithm"); } } if (shouldMarkAlgBadAsBad) for (QuantEvent quantEvent : selectedQuantEvents) if (!quantEvent.getAlgorithmicAssessment().isGood()) { quantEvent.setQuantCurationStatus(QuantEvent.CURATION_STATUS_BAD); quantEvent.setComment("Auto-marked bad because of algorithm"); } if (shouldMarkAlgBadAsBadIfOtherProteinSupport) { //Load a map from peptides to all the proteins that they help ID. Hardcoded ProteinProphet threshold Map<String, Set<String>> peptideProteinMap = null; try { peptideProteinMap = ProteinUtilities.loadPeptideProteinMapFromProtXML(protXmlFile, 0.1f, true); } catch (Exception e) { errorMessage("ERROR! Problem loading ProtXML file. Failed to locate all other proteins from 'bad' events. " + "'bad' events will be left as unknown",e); return; } //Build a list of proteins that only have bad selected events. These are the ones that look like they //have no other support; we need to look for other support for them, outside the selected events. //To do this, we just populate two sets: proteins with good events, and proteins with bad events. When //we've looked at all the selected events, we remove all proteins from the "good" list from the "bad" list, //leaving us with only proteins with bad events and no good events. //This just keeps track of the fractions and scans of events we've already looked at, so we don't //waste time on them Map<String, List<Integer>> selectedEventFractionScansMap = new HashMap<String, List<Integer>>(); //This will actually contain /all/ proteins with bad events (even if they have good events, too) until //the removeAll statement after the loop Set<String> proteinsWithOnlyBadEvents = new HashSet<String>(); Set<String> proteinsWithGoodEvents = new HashSet<String>(); //This just keeps track of which events are bad, since those are the ones we'll potentially need to update //later. Convenience. List<QuantEvent> badSelectedQuantEvents = new ArrayList<QuantEvent>(); for (QuantEvent quantEvent : selectedQuantEvents) { List<Integer> scansThisFraction = selectedEventFractionScansMap.get(quantEvent.getFraction()); if (scansThisFraction == null) { scansThisFraction = new ArrayList<Integer>(); selectedEventFractionScansMap.put(quantEvent.getFraction(), scansThisFraction); } scansThisFraction.add(quantEvent.getScan()); //don't bother looking at subsumed QuantEvents, either. There's no point -- if we found good ones, //we would remove them all, including this one, which would be bad. //todo: properly I /should/ look at subsumed QuantEvents, and if any is good, mark this one good. //Lots of time spent on that, though. if (quantEvent.getOtherEvents() != null && !quantEvent.getOtherEvents().isEmpty()) { for (QuantEvent subsumedEvent : quantEvent.getOtherEvents()) scansThisFraction.add(subsumedEvent.getScan()); } //If good, add all proteins associated with this peptide to good set. If bad, add them to //bad set and add this event to bad selected events list String peptide = quantEvent.getPeptide(); if (quantEvent.getAlgorithmicAssessment().isGood()) { proteinsWithGoodEvents.addAll(peptideProteinMap.get(peptide)); } else { badSelectedQuantEvents.add(quantEvent); proteinsWithOnlyBadEvents.addAll(peptideProteinMap.get(peptide)); } } //Make the bad list into a bad-only list proteinsWithOnlyBadEvents.removeAll(proteinsWithGoodEvents); ApplicationContext.infoMessage(badSelectedQuantEvents.size() + " bad selected quant events."); ApplicationContext.infoMessage(proteinsWithOnlyBadEvents.size() + " selected proteins with only bad selected events"); _log.debug("Proteins with only bad events: "); for (String protein : proteinsWithOnlyBadEvents) _log.debug("\t" + protein); setMessage("Examining all events for " + proteinsWithOnlyBadEvents.size() + " proteins with bad events..."); PepXMLFeatureFileHandler.PepXMLFeatureSetIterator fsi = null; try { fsi = new PepXMLFeatureFileHandler.PepXMLFeatureSetIterator(pepXmlFile); } catch (Exception e) { errorMessage("ERROR! Problem loading fractions from pepXML file. Failed to locate all other proteins from 'bad' events. " + "'bad' events will be left as unknown",e); return; } QuantEventAssessor eventAssessor = new QuantEventAssessor(); // eventAssessor.setLabelType(labelType); int numFeaturesExamined = 0; while (fsi.hasNext()) { if (proteinsWithOnlyBadEvents.isEmpty()) { _log.debug("Stopping early: found good events for all proteins"); break; } FeatureSet featureSet = fsi.next(); String fraction = MS2ExtraInfoDef.getFeatureSetBaseName(featureSet); _log.debug("Processing fraction " + fraction + ". " + proteinsWithOnlyBadEvents.size() + " proteins remain"); //scans we can ignore because they were on the selected list -- they've already been examined List<Integer> alreadySelectedScansThisFraction = selectedEventFractionScansMap.get(fraction); MSRun run = null; for (Feature feature : featureSet.getFeatures()) { //if, at any time, no more proteins to examine, stop immediately if (proteinsWithOnlyBadEvents.isEmpty()) break; //if no ratio, nothing to do if (!IsotopicLabelExtraInfoDef.hasRatio(feature)) continue; //if this was a selected event, no need to examine if (alreadySelectedScansThisFraction != null && alreadySelectedScansThisFraction.contains(feature.getScan())) continue; String peptide = MS2ExtraInfoDef.getFirstPeptide(feature); //This actually shouldn't be possible, but maybe with different probability tolerances.... if (!peptideProteinMap.containsKey(peptide)) continue; //check if this peptide contributes to any of our bad-only proteins boolean hasBadProteins = false; for (String protein : peptideProteinMap.get(peptide)) if (proteinsWithOnlyBadEvents.contains(protein)) { hasBadProteins = true; break; } if (!hasBadProteins) continue; //OK, we actually have to load the run (unless we already have) and look at this feature if (run == null) { try { File featureSetFile = featureSet.getSourceFile(); if (MS2ExtraInfoDef.getFeatureSetBaseName(featureSet) != null) featureSetFile = new File(MS2ExtraInfoDef.getFeatureSetBaseName(featureSet) + ".pep.xml"); File mzXmlFile = ViewerCommandModuleUtilities.findCorrespondingMzXmlFile( featureSetFile, mzXmlDir); ApplicationContext.infoMessage("Loading mzXml file " + mzXmlFile.getAbsolutePath()); run = MSRun.load(mzXmlFile.getAbsolutePath()); ApplicationContext.infoMessage("Loaded."); } catch (IOException e) { errorMessage("ERROR! Problem loading mzXML file. Failed to locate all other proteins from 'bad' events. " + "'bad' events will be left as unknown",e); return; } } //assess the feature. If good, remove all its proteins from the bad-only list QuantEventAssessor.QuantEventAssessment assessment = eventAssessor.assessFeature(feature, run); if (assessment.isGood()) { _log.debug("Found a good event for peptide " + peptide + ", removing proteins"); numFeaturesExamined++; Set<String> proteinsThisPeptide = peptideProteinMap.get(peptide); for (String protein : proteinsThisPeptide) { if (proteinsWithOnlyBadEvents.contains(protein)) { _log.debug("\tRemoving protein " + protein); proteinsWithOnlyBadEvents.remove(protein); } } } } } ApplicationContext.infoMessage("Checked all fractions, examined " + numFeaturesExamined + " events. " + proteinsWithOnlyBadEvents.size() + " proteins remain with no good events"); if (_log.isDebugEnabled()) { for (String protein : proteinsWithOnlyBadEvents) _log.debug("\t" + protein); } //mark any of our algorithm-bad events bad if any of their proteins have good event support int numEventsMarkedBad = 0; for (QuantEvent quantEvent : badSelectedQuantEvents) { boolean hasBadProteins = false; for (String protein : peptideProteinMap.get(quantEvent.getPeptide())) { if (proteinsWithOnlyBadEvents.contains(protein)) { hasBadProteins = true; break; } } if (hasBadProteins) quantEvent.setComment("Not auto-marked: only quant event for this protein"); else { quantEvent.setQuantCurationStatus(QuantEvent.CURATION_STATUS_BAD); quantEvent.setComment("Auto-marked bad: algorithm bad and good events exist for protein"); numEventsMarkedBad++; } } ApplicationContext.infoMessage(numEventsMarkedBad + " out of " + badSelectedQuantEvents.size() + " marked bad because all their proteins had other good events"); setMessage("Examined " + numFeaturesExamined + " events."); } if (shouldDispose) dispose(); } /** * Shut down any stray children and die */ public void dispose() { if (eventPropertiesDialog != null) eventPropertiesDialog.dispose(); super.dispose(); } /** * Concatenate all values in proteinNames, separated by separatorString * @param separatorString * @return */ protected String concatProteinNamesMax3(String separatorString) { StringBuffer allProteinNamesStringBuf = new StringBuffer(); for (int i=0; i<proteinNames.size(); i++) { if (i > 0) allProteinNamesStringBuf.append(separatorString); if (i>2) { allProteinNamesStringBuf.append("etc"); break; } allProteinNamesStringBuf.append(proteinNames.get(i)); } String result = allProteinNamesStringBuf.toString(); if (result.length() > 100) result = result.substring(0,100); return result; } /** * Populate the table with the current quantEvents */ protected void displayEvents() { _log.debug("displayEvents 1, quant events: " + quantEvents.size()); String proteinOrProteins = "Protein"; if (proteinNames.size() > 1) proteinOrProteins = "Proteins"; if (proteinNames.size() > 4) setTitle("Event Summary for " + proteinNames.size() + " Proteins"); else setTitle("Event Summary for " + proteinOrProteins + " " + concatProteinNamesMax3(",")); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.anchor = GridBagConstraints.PAGE_START; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.insets = new Insets(0,0,0,0); gbc.weighty = 1; gbc.weightx = 1; List<Integer> alreadySelectedEventIndices = new ArrayList<Integer>(); if (existingQuantEvents != null) { for (int i=0; i<quantEvents.size(); i++) { for (QuantEvent existingEvent : existingQuantEvents) { //check the events for identity with already-loaded events. If we get it, grey out and //replace the new one with the old one (to pick up curation statuses if (quantEvents.get(i).isSameEvent(existingEvent)) { alreadySelectedEventIndices.add(i); quantEvents.set(i, existingEvent); break; } } } } _log.debug("displayEvents 2"); List<Float> eventLogRatios = new ArrayList<Float>(); for (QuantEvent event : quantEvents) eventLogRatios.add((float) Math.log(event.getRatio())); eventsTable.displayEvents(quantEvents, alreadySelectedEventIndices); _log.debug("displayEvents 3"); buttonSelectAllVisible.setEnabled(true); buttonDeselectAll.setEnabled(true); loadSelectedEventsButton.setEnabled(true); autoAssessSelectedEventsButton.setEnabled(true); buildTurkHITsButton.setEnabled(true); showPropertiesButton.setEnabled(true); showProteinRatiosButton.setEnabled(true); _log.debug("displayEvents 4"); logRatioHistogramPanel.setMaxLowRatio(maxLowRatio); _log.debug("displayEvents a"); logRatioHistogramPanel.setMinHighRatio(minHighRatio); _log.debug("displayEvents a, eventlogratios: " + eventLogRatios.size()); logRatioHistogramPanel.setLogRatios(eventLogRatios); _log.debug("displayEvents a"); logRatioHistogramPanel.setSize(width-5, LOGRATIO_HISTOGRAM_PANEL_HEIGHT-20); _log.debug("displayEvents 4.0.1"); logRatioHistogramPanel.addRangeUpdateListener(new LogRatioHistogramListener()); _log.debug("displayEvents 4.1"); logRatioHistogramPanel.updateUI(); _log.debug("displayEvents 4.2"); contentPanel.updateUI(); _log.debug("displayEvents 5"); fullHeight = Math.min(800, Math.max(600,(quantEvents.size() + 1) * TABLEROW_HEIGHT) + SUMMARYPANEL_HEIGHT + LOGRATIO_HISTOGRAM_PANEL_HEIGHT + STATUSPANEL_HEIGHT + TITLEBAR_HEIGHT); setSize(fullWidth, fullHeight); _log.debug("displayEvents end"); } /** * Select all currently-visible (i.e., passes filter) rows * @param event */ public void buttonSelectAllVisible_actionPerformed(ActionEvent event) { for (int i=0; i<eventsTable.getRowCount(); i++) { eventsTable.getSelectionModel().addSelectionInterval(i, i); } } /** * Deselect all currently-selected rows, whether or not they're currently passing the filter * @param event */ public void buttonDeselectAll_actionPerformed(ActionEvent event) { eventsTable.getSelectionModel().clearSelection(); } /** * A chart listener that picks up events indicating changes to the selected area */ protected class LogRatioHistogramListener implements ActionListener { public LogRatioHistogramListener() { } public void actionPerformed(ActionEvent e) { PanelWithLogRatioHistAndFields logRatioHistAndFields = (PanelWithLogRatioHistAndFields) e.getSource(); minHighRatio = logRatioHistAndFields.getMinHighRatio(); maxLowRatio = logRatioHistAndFields.getMaxLowRatio(); updateExtremeRatioGUI(); } } /** * A chart listener that picks up events indicating changes to the selected area on the protein table */ protected class ProteinTableLogRatioHistogramListener implements ActionListener { public ProteinTableLogRatioHistogramListener() { } public void actionPerformed(ActionEvent e) { PanelWithLogRatioHistAndFields logRatioHistAndFields = (PanelWithLogRatioHistAndFields) e.getSource(); List<QuantEvent> thisProteinEvents = proteinEventsMap.get(proteinTableSelectedProtein); float minRatio = logRatioHistAndFields.getMinHighRatio(); float maxRatio = logRatioHistAndFields.getMaxLowRatio(); for (int i=0; i<quantEvents.size(); i++) { QuantEvent quantEvent = quantEvents.get(i); if (thisProteinEvents.contains(quantEvent)) { boolean shouldSelect = false; if (quantEvent.getRatio() >= minRatio || quantEvent.getRatio() <= maxRatio) shouldSelect = true; eventsTable.getModel().setValueAt(shouldSelect, i, 0); } } } } protected void updateExtremeRatioGUI() { eventsTable.showOnlyExtremeRatios(maxLowRatio, minHighRatio); // numPassingEventsLabel.setText("Events Retained: " + eventsTable.getRowCount() + " / " + // quantEvents.size() + " (" + Rounder.round(100f * eventsTable.getRowCount() / quantEvents.size(),1) + // "%)"); } /** * Display a dialog box with info message * @param message */ protected void infoMessage(String message) { if (message.length() > 2000) message = message.substring(0,1997) + "..."; JOptionPane.showMessageDialog(ApplicationContext.getFrame(), message, "Information", JOptionPane.INFORMATION_MESSAGE); } /** * Display a dialog box with info message and stack trace * @param message * @param t */ protected void errorMessage(String message, Throwable t) { ApplicationContext.errorMessage(message, t); if (null != t) { message = message + "\n" + t.getMessage() + "\n"; StringWriter sw = new StringWriter(); PrintWriter w = new PrintWriter(sw); t.printStackTrace(w); w.flush(); message += "\n"; message += sw.toString(); } infoMessage(message); } /** * Set status message. Separate thread necessary or UI hangs * @param message */ public void setMessage(String message) { if (EventQueue.isDispatchThread()) { if (null == message || 0 == message.length()) message = " "; if (message.length() > 500) message = message.substring(0,500); messageLabel.setText(message); } else { final String msg = message; EventQueue.invokeLater(new Runnable() { public void run() { setMessage(msg); } }); } statusPanel.updateUI(); } public List<QuantEvent> getSelectedQuantEvents() { return selectedQuantEvents; } /** * display the properties for the selected event, if only one's selected */ public class EventsTableListSelectionHandler implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { int selectedIndex = eventsTable.getSelectedIndex(); if (selectedIndex >= 0) eventPropertiesTable.displayQuantEvent(quantEvents.get(selectedIndex)); else eventPropertiesTable.clearProperties(); } } } public List<QuantEvent> getExistingQuantEvents() { return existingQuantEvents; } public void setExistingQuantEvents(List<QuantEvent> existingQuantEvents) { this.existingQuantEvents = existingQuantEvents; } public Map<String, List<String>> getProteinGeneMap() { return proteinGenesMap; } public void setProteinGeneMap(Map<String, List<String>> proteinGeneMap) { this.proteinGenesMap = proteinGeneMap; } }
wiresboy/Java-Game-APCS
src/web/Shareable.java
<reponame>wiresboy/Java-Game-APCS /** Shareable.java <NAME> 2/18/2015 * defines the methods that will be used to pack and unpack data being transfered with another player. */ package web; public interface Shareable{ int getIdentifier(); //get a unique identifier so that the WebInterface knows where to send what data. This should be initialized somewhere in the main initialization place. String[][] packData(); /*gather any data to share with other player and package it, returning a 2D String array, containing key,value pairs. * All values will be formatted by Web.java {{"Key1","Value1"}, {"Key2","Value2"}, {"Key3","Value3"}} */ void unpackData(String[][] update); /* update all internal variables to new values based on data packed by a different client. * Should follow exact same pattern for decoding as it does for encoding. */ }
JuDFTteam/masci-tools
masci_tools/io/parsers/fleur/outxml_conversions.py
# -*- coding: utf-8 -*- ############################################################################### # Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. # # All rights reserved. # # This file is part of the Masci-tools package. # # (Material science tools) # # # # The code is hosted on GitHub at https://github.com/judftteam/masci-tools. # # For further information on the license, see the LICENSE.txt file. # # For further information please visit http://judft.de/. # # # ############################################################################### """ This module contains custom conversion functions for the outxml_parser, which cannot be handled by the standard parsing framework """ from datetime import date import numpy as np from pprint import pprint from masci_tools.util.constants import HTR_TO_EV from masci_tools.util.parse_tasks_decorators import conversion_function from masci_tools.io.common_functions import convert_to_pystd from typing import Dict, Any from logging import Logger @conversion_function def convert_total_energy(out_dict: Dict[str, Any], logger: Logger) -> Dict[str, Any]: """ Convert total energy to eV """ total_energy = out_dict.get('energy_hartree', None) if total_energy is None: if 'energy_hartree' in out_dict: if logger is not None: logger.warning('convert_total_energy cannot convert None to eV') out_dict['energy'] = None out_dict['energy_units'] = 'eV' return out_dict total_energy = total_energy[-1] if 'energy' not in out_dict: out_dict['energy'] = [] out_dict['energy_units'] = 'eV' if total_energy is not None: out_dict['energy'].append(total_energy * HTR_TO_EV) else: if logger is not None: logger.warning('convert_total_energy cannot convert None to eV') out_dict['energy'].append(None) return out_dict @conversion_function def calculate_total_magnetic_moment(out_dict: Dict[str, Any], logger: Logger) -> Dict[str, Any]: """ Calculate the the total magnetic moment per cell :param out_dict: dict with the already parsed information """ total_charge = out_dict.get('spin_dependent_charge_total', None) if total_charge is None: if logger is not None: logger.warning('calculate_total_magnetic_moment got None') return out_dict total_charge = total_charge[-1] if isinstance(total_charge, list): if 'total_magnetic_moment_cell' not in out_dict: out_dict['total_magnetic_moment_cell'] = [] out_dict['total_magnetic_moment_cell'].append(convert_to_pystd(np.abs(total_charge[0] - total_charge[1]))) return out_dict @conversion_function def calculate_walltime(out_dict: Dict[str, Any], logger: Logger) -> Dict[str, Any]: """ Calculate the walltime from start and end time :param out_dict: dict with the already parsed information :param logger: logger object for logging warnings, errors, if not provided all errors will be raised """ if out_dict['start_date']['time'] is not None: starttimes = out_dict['start_date']['time'].split(':') else: starttimes = [0, 0, 0] msg = 'Starttime was unparsed, inp.xml prob not complete, do not believe the walltime!' if logger is not None: logger.warning(msg) if out_dict['end_date']['time'] is not None: endtimes = out_dict['end_date']['time'].split(':') else: endtimes = [0, 0, 0] msg = 'Endtime was unparsed, inp.xml prob not complete, do not believe the walltime!' if logger is not None: logger.warning(msg) if out_dict['start_date']['date'] is not None: start_date = out_dict['start_date']['date'] else: start_date = None msg = 'Startdate was unparsed, inp.xml prob not complete, do not believe the walltime!' if logger is not None: logger.warning(msg) if out_dict['end_date']['date'] is not None: end_date = out_dict['end_date']['date'] else: end_date = None msg = 'Enddate was unparsed, inp.xml prob not complete, do not believe the walltime!' if logger is not None: logger.warning(msg) offset = 0 if start_date is not None and end_date is not None: if start_date != end_date: date_sl = [int(ent) for ent in start_date.split('/')] date_el = [int(ent) for ent in end_date.split('/')] date_s = date(*date_sl) date_e = date(*date_el) diff = date_e - date_s offset = diff.days * 86400 time = offset + (int(endtimes[0]) - int(starttimes[0])) * 60 * 60 + ( int(endtimes[1]) - int(starttimes[1])) * 60 + int(endtimes[2]) - int(starttimes[2]) out_dict['walltime'] = time out_dict['walltime_units'] = 'seconds' return out_dict @conversion_function def convert_ldau_definitions(out_dict: Dict[str, Any], logger: Logger) -> Dict[str, Any]: """ Convert the parsed information from LDA+U into a more readable dict ldau_info has keys for each species with LDA+U ({species_name}/{atom_number}) and this in turn contains a dict with the LDA+U definition for the given orbital (spdf) :param out_dict: dict with the already parsed information """ parsed_ldau = out_dict['ldau_info'].pop('parsed_ldau') ldau_species = out_dict['ldau_info'].pop('ldau_species') if isinstance(ldau_species['name'], str): ldau_species = {key: [val] for key, val in ldau_species.items()} if isinstance(parsed_ldau['l'], int): parsed_ldau = {key: [val] for key, val in parsed_ldau.items()} ldau_definitions = zip(ldau_species['name'], ldau_species['atomic_number'], parsed_ldau['l']) for index, ldau_def in enumerate(ldau_definitions): species_name, atom_number, orbital = ldau_def species_key = f'{species_name}/{atom_number}' orbital_key = 'spdf'[orbital] if species_key not in out_dict['ldau_info']: ldau_dict = out_dict['ldau_info'].get(species_key, {}) ldau_dict[orbital_key] = {} ldau_dict[orbital_key]['u'] = parsed_ldau['u'][index] ldau_dict[orbital_key]['j'] = parsed_ldau['j'][index] ldau_dict[orbital_key]['unit'] = 'eV' if parsed_ldau['l_amf'][index]: ldau_dict[orbital_key]['double_counting'] = 'AMF' else: ldau_dict[orbital_key]['double_counting'] = 'FLL' out_dict['ldau_info'][species_key] = ldau_dict return out_dict @conversion_function def convert_relax_info(out_dict: Dict[str, Any], logger: Logger) -> Dict[str, Any]: """ Convert the general relaxation information :param out_dict: dict with the already parsed information """ v_1 = out_dict.pop('lat_row1') v_2 = out_dict.pop('lat_row2') v_3 = out_dict.pop('lat_row3') out_dict['relax_brav_vectors'] = [v_1, v_2, v_3] out_dict['relax_atom_positions'] = out_dict.pop('atom_positions') species = out_dict.pop('position_species') species = species['species'] species_info = out_dict.pop('element_species') if isinstance(species_info['name'], str): species_info = {key: [val] for key, val in species_info.items()} species_info = dict(zip(species_info['name'], species_info['element'])) out_dict['relax_atomtype_info'] = [] for specie in species: out_dict['relax_atomtype_info'].append((specie, species_info[specie])) return out_dict @conversion_function def convert_forces(out_dict: Dict[str, Any], logger: Logger) -> Dict[str, Any]: """ Convert the parsed forces from a iteration :param out_dict: dict with the already parsed information """ parsed_forces = out_dict.pop('parsed_forces') if 'force_largest_component' not in out_dict: out_dict['force_largest_component'] = [] out_dict['force_atoms'] = [] out_dict['abspos_atoms'] = [] if isinstance(parsed_forces['atom_type'], int): parsed_forces = {key: [val] for key, val in parsed_forces.items()} largest_force = 0.0 forces = [] abspos = [] for index, atomType in enumerate(parsed_forces['atom_type']): force_x = parsed_forces['f_x'][index] force_y = parsed_forces['f_y'][index] force_z = parsed_forces['f_z'][index] x = parsed_forces['x'][index] y = parsed_forces['y'][index] z = parsed_forces['z'][index] forces.append((atomType, [force_x, force_y, force_z])) abspos.append((atomType, [x, y, z])) if abs(force_x) > largest_force: largest_force = abs(force_x) if abs(force_y) > largest_force: largest_force = abs(force_y) if abs(force_z) > largest_force: largest_force = abs(force_z) out_dict['force_largest_component'].append(largest_force) out_dict['force_atoms'].append(forces) out_dict['abspos_atoms'].append(abspos) return out_dict
Neusoft-Technology-Solutions/aws-sdk-cpp
aws-cpp-sdk-lakeformation/include/aws/lakeformation/model/Resource.h
<gh_stars>0 /** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/lakeformation/LakeFormation_EXPORTS.h> #include <aws/lakeformation/model/CatalogResource.h> #include <aws/lakeformation/model/DatabaseResource.h> #include <aws/lakeformation/model/TableResource.h> #include <aws/lakeformation/model/TableWithColumnsResource.h> #include <aws/lakeformation/model/DataLocationResource.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace LakeFormation { namespace Model { /** * <p>A structure for the resource.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/lakeformation-2017-03-31/Resource">AWS * API Reference</a></p> */ class AWS_LAKEFORMATION_API Resource { public: Resource(); Resource(Aws::Utils::Json::JsonView jsonValue); Resource& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your AWS Lake * Formation environment. </p> */ inline const CatalogResource& GetCatalog() const{ return m_catalog; } /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your AWS Lake * Formation environment. </p> */ inline bool CatalogHasBeenSet() const { return m_catalogHasBeenSet; } /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your AWS Lake * Formation environment. </p> */ inline void SetCatalog(const CatalogResource& value) { m_catalogHasBeenSet = true; m_catalog = value; } /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your AWS Lake * Formation environment. </p> */ inline void SetCatalog(CatalogResource&& value) { m_catalogHasBeenSet = true; m_catalog = std::move(value); } /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your AWS Lake * Formation environment. </p> */ inline Resource& WithCatalog(const CatalogResource& value) { SetCatalog(value); return *this;} /** * <p>The identifier for the Data Catalog. By default, the account ID. The Data * Catalog is the persistent metadata store. It contains database definitions, * table definitions, and other control information to manage your AWS Lake * Formation environment. </p> */ inline Resource& WithCatalog(CatalogResource&& value) { SetCatalog(std::move(value)); return *this;} /** * <p>The database for the resource. Unique to the Data Catalog. A database is a * set of associated table definitions organized into a logical group. You can * Grant and Revoke database permissions to a principal. </p> */ inline const DatabaseResource& GetDatabase() const{ return m_database; } /** * <p>The database for the resource. Unique to the Data Catalog. A database is a * set of associated table definitions organized into a logical group. You can * Grant and Revoke database permissions to a principal. </p> */ inline bool DatabaseHasBeenSet() const { return m_databaseHasBeenSet; } /** * <p>The database for the resource. Unique to the Data Catalog. A database is a * set of associated table definitions organized into a logical group. You can * Grant and Revoke database permissions to a principal. </p> */ inline void SetDatabase(const DatabaseResource& value) { m_databaseHasBeenSet = true; m_database = value; } /** * <p>The database for the resource. Unique to the Data Catalog. A database is a * set of associated table definitions organized into a logical group. You can * Grant and Revoke database permissions to a principal. </p> */ inline void SetDatabase(DatabaseResource&& value) { m_databaseHasBeenSet = true; m_database = std::move(value); } /** * <p>The database for the resource. Unique to the Data Catalog. A database is a * set of associated table definitions organized into a logical group. You can * Grant and Revoke database permissions to a principal. </p> */ inline Resource& WithDatabase(const DatabaseResource& value) { SetDatabase(value); return *this;} /** * <p>The database for the resource. Unique to the Data Catalog. A database is a * set of associated table definitions organized into a logical group. You can * Grant and Revoke database permissions to a principal. </p> */ inline Resource& WithDatabase(DatabaseResource&& value) { SetDatabase(std::move(value)); return *this;} /** * <p>The table for the resource. A table is a metadata definition that represents * your data. You can Grant and Revoke table privileges to a principal. </p> */ inline const TableResource& GetTable() const{ return m_table; } /** * <p>The table for the resource. A table is a metadata definition that represents * your data. You can Grant and Revoke table privileges to a principal. </p> */ inline bool TableHasBeenSet() const { return m_tableHasBeenSet; } /** * <p>The table for the resource. A table is a metadata definition that represents * your data. You can Grant and Revoke table privileges to a principal. </p> */ inline void SetTable(const TableResource& value) { m_tableHasBeenSet = true; m_table = value; } /** * <p>The table for the resource. A table is a metadata definition that represents * your data. You can Grant and Revoke table privileges to a principal. </p> */ inline void SetTable(TableResource&& value) { m_tableHasBeenSet = true; m_table = std::move(value); } /** * <p>The table for the resource. A table is a metadata definition that represents * your data. You can Grant and Revoke table privileges to a principal. </p> */ inline Resource& WithTable(const TableResource& value) { SetTable(value); return *this;} /** * <p>The table for the resource. A table is a metadata definition that represents * your data. You can Grant and Revoke table privileges to a principal. </p> */ inline Resource& WithTable(TableResource&& value) { SetTable(std::move(value)); return *this;} /** * <p>The table with columns for the resource. A principal with permissions to this * resource can select metadata from the columns of a table in the Data Catalog and * the underlying data in Amazon S3.</p> */ inline const TableWithColumnsResource& GetTableWithColumns() const{ return m_tableWithColumns; } /** * <p>The table with columns for the resource. A principal with permissions to this * resource can select metadata from the columns of a table in the Data Catalog and * the underlying data in Amazon S3.</p> */ inline bool TableWithColumnsHasBeenSet() const { return m_tableWithColumnsHasBeenSet; } /** * <p>The table with columns for the resource. A principal with permissions to this * resource can select metadata from the columns of a table in the Data Catalog and * the underlying data in Amazon S3.</p> */ inline void SetTableWithColumns(const TableWithColumnsResource& value) { m_tableWithColumnsHasBeenSet = true; m_tableWithColumns = value; } /** * <p>The table with columns for the resource. A principal with permissions to this * resource can select metadata from the columns of a table in the Data Catalog and * the underlying data in Amazon S3.</p> */ inline void SetTableWithColumns(TableWithColumnsResource&& value) { m_tableWithColumnsHasBeenSet = true; m_tableWithColumns = std::move(value); } /** * <p>The table with columns for the resource. A principal with permissions to this * resource can select metadata from the columns of a table in the Data Catalog and * the underlying data in Amazon S3.</p> */ inline Resource& WithTableWithColumns(const TableWithColumnsResource& value) { SetTableWithColumns(value); return *this;} /** * <p>The table with columns for the resource. A principal with permissions to this * resource can select metadata from the columns of a table in the Data Catalog and * the underlying data in Amazon S3.</p> */ inline Resource& WithTableWithColumns(TableWithColumnsResource&& value) { SetTableWithColumns(std::move(value)); return *this;} /** * <p>The location of an Amazon S3 path where permissions are granted or revoked. * </p> */ inline const DataLocationResource& GetDataLocation() const{ return m_dataLocation; } /** * <p>The location of an Amazon S3 path where permissions are granted or revoked. * </p> */ inline bool DataLocationHasBeenSet() const { return m_dataLocationHasBeenSet; } /** * <p>The location of an Amazon S3 path where permissions are granted or revoked. * </p> */ inline void SetDataLocation(const DataLocationResource& value) { m_dataLocationHasBeenSet = true; m_dataLocation = value; } /** * <p>The location of an Amazon S3 path where permissions are granted or revoked. * </p> */ inline void SetDataLocation(DataLocationResource&& value) { m_dataLocationHasBeenSet = true; m_dataLocation = std::move(value); } /** * <p>The location of an Amazon S3 path where permissions are granted or revoked. * </p> */ inline Resource& WithDataLocation(const DataLocationResource& value) { SetDataLocation(value); return *this;} /** * <p>The location of an Amazon S3 path where permissions are granted or revoked. * </p> */ inline Resource& WithDataLocation(DataLocationResource&& value) { SetDataLocation(std::move(value)); return *this;} private: CatalogResource m_catalog; bool m_catalogHasBeenSet; DatabaseResource m_database; bool m_databaseHasBeenSet; TableResource m_table; bool m_tableHasBeenSet; TableWithColumnsResource m_tableWithColumns; bool m_tableWithColumnsHasBeenSet; DataLocationResource m_dataLocation; bool m_dataLocationHasBeenSet; }; } // namespace Model } // namespace LakeFormation } // namespace Aws
IsraelAugusto0110/Linguagens-de-Programacao
C/Iniciante/1133restodadivisao.c
<reponame>IsraelAugusto0110/Linguagens-de-Programacao #include<stdio.h> void main(){ int x, y; scanf("%d\n", &x); scanf("%d", &y); if(x < y){ for(int i = x + 1; i < y; i++){ if(i%5 == 2 || i%5 == 3){ printf("%d\n", i); } } } if(x > y){ for(int i = y + 1; i < x; i++){ if(i%5 == 2 || i%5 == 3){ printf("%d\n", i); } } } }
Pedrioko/FAWSAC
core/src/main/java/com/gitlab/pedrioko/core/zk/component/rangebox/LongRangeBox.java
package com.gitlab.pedrioko.core.zk.component.rangebox; import com.gitlab.pedrioko.core.lang.LongRange; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zul.Div; import org.zkoss.zul.Longbox; public class LongRangeBox extends Div { Longbox fin = new Longbox(); Longbox inicio = new Longbox(); private LongRange value; public LongRangeBox() { value = new LongRange(); this.setSclass("ats-rangebox"); load(); } private void load() { inicio.setClass("ats-rangebox-input"); fin.setClass("ats-rangebox-input"); appendChild(inicio); appendChild(fin); } public LongRange getValue() { Long inicio = this.inicio.getValue(); Long fin = this.fin.getValue(); if (inicio != null && fin != null) { this.value.setInicio(inicio); this.value.setFin(fin); return this.value; } else { return null; } } public void setValue(LongRange value) { this.value = value; value.setInicio(inicio.getValue()); value.setFin(fin.getValue()); } @Override public boolean addEventListener(String evtnm, EventListener<? extends Event> listener) { switch (evtnm) { case Events.ON_CHANGE: case Events.ON_CHANGING: { fin.addEventListener(evtnm, listener); break; } } return super.addEventListener(evtnm, listener); } }
ResonanceGroup/FEMM
femm/viewpref.cpp
// Pref.cpp : implementation file // #include "stdafx.h" #include "femm.h" #include "ViewPref.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define SelColor clist[0] #define BackColor clist[1] #define MeshColor clist[2] #define BlockColor clist[3] #define LineColor clist[4] #define GridColor clist[5] #define NodeColor clist[6] #define RegionColor clist[7] #define TextColor clist[8] #define RealFluxLineColor clist[9] #define ImagFluxLineColor clist[10] #define MaskLineColor clist[11] #define NameColor clist[12] #define RealVectorColor clist[13] #define ImagVectorColor clist[14] #define Color00 clist[15] #define Color01 clist[16] #define Color02 clist[17] #define Color03 clist[18] #define Color04 clist[19] #define Color05 clist[20] #define Color06 clist[21] #define Color07 clist[22] #define Color08 clist[23] #define Color09 clist[24] #define Color10 clist[25] #define Color11 clist[26] #define Color12 clist[27] #define Color13 clist[28] #define Color14 clist[29] #define Color15 clist[30] #define Color16 clist[31] #define Color17 clist[32] #define Color18 clist[33] #define Color19 clist[34] #define Grey00 clist[35] #define Grey01 clist[36] #define Grey02 clist[37] #define Grey03 clist[38] #define Grey04 clist[39] #define Grey05 clist[40] #define Grey06 clist[41] #define Grey07 clist[42] #define Grey08 clist[43] #define Grey09 clist[44] #define Grey10 clist[45] #define Grey11 clist[46] #define Grey12 clist[47] #define Grey13 clist[48] #define Grey14 clist[49] #define Grey15 clist[50] #define Grey16 clist[51] #define Grey17 clist[52] #define Grey18 clist[53] #define Grey19 clist[54] ///////////////////////////////////////////////////////////////////////////// //CViewPref dialog CViewPref::CViewPref(CWnd* pParent /*=NULL*/) : CDialog(CViewPref::IDD, pParent) { //{{AFX_DATA_INIT(CViewPref) m_d_GreyContours = FALSE; m_d_LegendFlag = TRUE; m_d_NumContours = 19; m_d_ResetOnReload = FALSE; m_d_GridFlag = FALSE; m_d_ShowAi = FALSE; m_d_ShowAr = TRUE; m_d_PtsFlag = TRUE; m_d_MeshFlag = FALSE; m_d_SnapFlag = FALSE; m_d_Smooth = TRUE; m_d_LineIntegralPoints = 400; m_d_ShiftH = TRUE; m_d_PlotPoints = 150; m_d_ShowMask = FALSE; m_d_shownames = FALSE; //}}AFX_DATA_INIT m_d_DensityPlot=0; m_d_EditAction=0; m_d_VectorPlot=0; clist=(COLORREF *)calloc(64,sizeof(COLORREF)); int i=0; clist[i++]=dSelColor; clist[i++]=dBackColor; clist[i++]=dMeshColor; clist[i++]=dBlockColor; clist[i++]=dLineColor; clist[i++]=dGridColor; clist[i++]=dNodeColor; clist[i++]=dRegionColor; clist[i++]=dTextColor; clist[i++]=dRealFluxLineColor; clist[i++]=dImagFluxLineColor; clist[i++]=dMaskLineColor; clist[i++]=dNameColor; clist[i++]=dRealVectorColor; clist[i++]=dImagVectorColor; clist[i++]=dColor00; clist[i++]=dColor01; clist[i++]=dColor02; clist[i++]=dColor03; clist[i++]=dColor04; clist[i++]=dColor05; clist[i++]=dColor06; clist[i++]=dColor07; clist[i++]=dColor08; clist[i++]=dColor09; clist[i++]=dColor10; clist[i++]=dColor11; clist[i++]=dColor12; clist[i++]=dColor13; clist[i++]=dColor14; clist[i++]=dColor15; clist[i++]=dColor16; clist[i++]=dColor17; clist[i++]=dColor18; clist[i++]=dColor19; clist[i++]=dGrey00; clist[i++]=dGrey01; clist[i++]=dGrey02; clist[i++]=dGrey03; clist[i++]=dGrey04; clist[i++]=dGrey05; clist[i++]=dGrey06; clist[i++]=dGrey07; clist[i++]=dGrey08; clist[i++]=dGrey09; clist[i++]=dGrey10; clist[i++]=dGrey11; clist[i++]=dGrey12; clist[i++]=dGrey13; clist[i++]=dGrey14; clist[i++]=dGrey15; clist[i++]=dGrey16; clist[i++]=dGrey17; clist[i++]=dGrey18; clist[i++]=dGrey19; } CViewPref::~CViewPref() { free(clist); } void CViewPref::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CViewPref) DDX_Control(pDX, IDC_VECTORPLOT, m_d_vplotlist); DDX_Control(pDX, IDC_DENSITYPLOT, m_d_dplotlist); DDX_Control(pDX, IDC_EDITACTION, m_d_editlist); DDX_Control(pDX, IDC_COLORS, m_d_color); DDX_Check(pDX, IDC_GREY, m_d_GreyContours); DDX_Check(pDX, IDC_LEGEND, m_d_LegendFlag); DDX_Text(pDX, IDC_NCONT, m_d_NumContours); DDV_MinMaxInt(pDX, m_d_NumContours, 4, 999); DDX_Check(pDX, IDC_ONRELOAD, m_d_ResetOnReload); DDX_Check(pDX, IDC_SHOWGRID, m_d_GridFlag); DDX_Check(pDX, IDC_SHOWIMAGINARY, m_d_ShowAi); DDX_Check(pDX, IDC_SHOWREAL, m_d_ShowAr); DDX_Check(pDX, IDC_SHOWPTS, m_d_PtsFlag); DDX_Check(pDX, IDC_SHOWMESH, m_d_MeshFlag); DDX_Check(pDX, IDC_SNAPGRID, m_d_SnapFlag); DDX_Check(pDX, IDC_SMOOTHING, m_d_Smooth); DDX_Check(pDX, IDC_SHIFTH, m_d_ShiftH); DDX_Text(pDX, IDC_LIPOINTS, m_d_LineIntegralPoints); DDV_MinMaxInt(pDX, m_d_LineIntegralPoints, 10, 100000); DDX_Text(pDX, IDC_PLOTPOINTS, m_d_PlotPoints); DDV_MinMaxInt(pDX, m_d_PlotPoints, 10, 100000); DDX_Check(pDX, IDC_SHOWMASK, m_d_ShowMask); DDX_Check(pDX, IDC_SHOWNAMEZ, m_d_shownames); //}}AFX_DATA_MAP DDX_Control(pDX, IDC_NCONT, m_IDC_d_NumContours); DDX_Control(pDX, IDC_LIPOINTS, m_IDC_d_LineIntegralPoints); DDX_Control(pDX, IDC_PLOTPOINTS, m_IDC_d_PlotPoints); } BEGIN_MESSAGE_MAP(CViewPref, CDialog) //{{AFX_MSG_MAP(CViewPref) ON_BN_CLICKED(IDC_FV_MODBTN, OnModBtn) ON_BN_CLICKED(IDC_FV_RESET, OnResetColors) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// //CViewPref message handlers void CViewPref::OnModBtn() { CColorDialog dlg; COLORREF cclist[16]; int i,k; UpdateData(); i=m_d_color.GetCurSel(); for(k=0;k<16;k++) cclist[k]=RGB(190,190,190); if(i<11) for(k=0;k<11;k++) cclist[k]=clist[k]; if((i>10)&&(i<23)) for(k=11;k<23;k++) cclist[k-11]=clist[k]; if(i>22) for(k=23;k<35;k++) cclist[k-23]=clist[k]; dlg.m_cc.lpCustColors=cclist; dlg.m_cc.rgbResult=clist[i]; dlg.m_cc.Flags=dlg.m_cc.Flags | CC_FULLOPEN | CC_RGBINIT; if(dlg.DoModal()==IDOK){ clist[i]=dlg.GetColor(); } } BOOL CViewPref::OnInitDialog() { CDialog::OnInitDialog(); ScanPrefs(); m_d_color.SetCurSel(0); m_d_dplotlist.SetCurSel(m_d_DensityPlot); m_d_editlist.SetCurSel(m_d_EditAction); m_d_vplotlist.SetCurSel(m_d_VectorPlot); UpdateData(FALSE); return TRUE; } void CViewPref::OnResetColors() { if(AfxMessageBox("Reset all color preferences?",MB_OKCANCEL)==IDOK) { int i=0; clist[i++]=dSelColor; clist[i++]=dBackColor; clist[i++]=dMeshColor; clist[i++]=dBlockColor; clist[i++]=dLineColor; clist[i++]=dGridColor; clist[i++]=dNodeColor; clist[i++]=dRegionColor; clist[i++]=dTextColor; clist[i++]=dRealFluxLineColor; clist[i++]=dImagFluxLineColor; clist[i++]=dMaskLineColor; clist[i++]=dNameColor; clist[i++]=dRealVectorColor; clist[i++]=dImagVectorColor; clist[i++]=dColor00; clist[i++]=dColor01; clist[i++]=dColor02; clist[i++]=dColor03; clist[i++]=dColor04; clist[i++]=dColor05; clist[i++]=dColor06; clist[i++]=dColor07; clist[i++]=dColor08; clist[i++]=dColor09; clist[i++]=dColor10; clist[i++]=dColor11; clist[i++]=dColor12; clist[i++]=dColor13; clist[i++]=dColor14; clist[i++]=dColor15; clist[i++]=dColor16; clist[i++]=dColor17; clist[i++]=dColor18; clist[i++]=dColor19; clist[i++]=dGrey00; clist[i++]=dGrey01; clist[i++]=dGrey02; clist[i++]=dGrey03; clist[i++]=dGrey04; clist[i++]=dGrey05; clist[i++]=dGrey06; clist[i++]=dGrey07; clist[i++]=dGrey08; clist[i++]=dGrey09; clist[i++]=dGrey10; clist[i++]=dGrey11; clist[i++]=dGrey12; clist[i++]=dGrey13; clist[i++]=dGrey14; clist[i++]=dGrey15; clist[i++]=dGrey16; clist[i++]=dGrey17; clist[i++]=dGrey18; clist[i++]=dGrey19; } } BOOL CViewPref::PreTranslateMessage(MSG* pMsg) { // Pressing ENTER should reroute message to parent if( (pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_RETURN) ) { GetParent()->PostMessage(WM_KEYDOWN, VK_RETURN, 0); // Message needs no further processing return TRUE; } // Pressing ESC should reroute message to parent if( (pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_ESCAPE) ) { GetParent()->PostMessage(WM_KEYDOWN, VK_ESCAPE, 0); // Message needs no further processing return TRUE; } // Allow default handler otherwise return CDialog::PreTranslateMessage(pMsg); } char* StripKey(char *c); void CViewPref::ScanPrefs() { FILE *fp; CString fname = ((CFemmApp *)AfxGetApp())->GetExecutablePath() + "femmview.cfg"; fp=fopen(fname,"rt"); if (fp!=NULL) { BOOL flag=FALSE; char s[1024]; char q[1024]; char *v; int cr,cg,cb; // parse the file while (fgets(s,1024,fp)!=NULL) { sscanf(s,"%s",q); if( _strnicmp(q,"<LineIntegralPoints>",20)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_LineIntegralPoints); q[0]=NULL; } if( _strnicmp(q,"<ShiftH>",8)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_ShiftH); q[0]=NULL; } if( _strnicmp(q,"<SelColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); SelColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<MeshColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); MeshColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<BlockColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); BlockColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<NodeColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); NodeColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<NameColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); NameColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<BkgndColor>",12)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); BackColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<TextColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); TextColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<FluxRColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); RealFluxLineColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<FluxIColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); ImagFluxLineColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<MaskColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); MaskLineColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<VectorRColor>",14)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); RealVectorColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<VectorIColor>",14)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); ImagVectorColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<LineColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); LineColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<RegionColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); RegionColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<GridColor>",10)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); GridColor=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color00>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color00=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color01>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color01=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color02>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color02=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color03>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color03=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color04>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color04=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color05>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color05=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color06>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color06=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color07>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color07=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color08>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color08=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color09>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color09=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color10>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color10=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color11>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color11=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color12>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color12=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color13>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color13=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color14>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color14=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color15>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color15=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color16>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color16=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color17>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color17=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color18>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color18=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Color19>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Color19=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey00>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey00=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey01>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey01=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey02>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey02=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey03>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey03=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey04>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey04=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey05>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey05=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey06>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey06=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey07>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey07=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey08>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey08=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey09>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey09=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey10>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey10=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey11>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey11=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey12>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey12=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey13>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey13=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey14>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey14=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey15>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey15=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey16>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey16=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey17>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey17=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey18>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey18=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<Grey19>",8)==0) { v=StripKey(s); sscanf(v,"%i %i %i",&cr,&cg,&cb); Grey19=RGB(cr,cg,cb); q[0]=NULL; } if( _strnicmp(q,"<EditAction>",12)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_EditAction); q[0]=NULL; } if( _strnicmp(q,"<DensityPlot>",13)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_DensityPlot); q[0]=NULL; } if( _strnicmp(q,"<VectorPlot>",12)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_VectorPlot); q[0]=NULL; } if( _strnicmp(q,"<GridFlag>",10)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_GridFlag); q[0]=NULL; } if( _strnicmp(q,"<SnapFlag>",10)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_SnapFlag); q[0]=NULL; } if( _strnicmp(q,"<MeshFlag>",10)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_MeshFlag); q[0]=NULL; } if( _strnicmp(q,"<LegendFlag>",12)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_LegendFlag); q[0]=NULL; } if( _strnicmp(q,"<NumContours>",13)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_NumContours); q[0]=NULL; } if( _strnicmp(q,"<ShowAr>",8)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_ShowAr); q[0]=NULL; } if( _strnicmp(q,"<ShowAi>",8)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_ShowAi); q[0]=NULL; } if( _strnicmp(q,"<ShowMask>",10)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_ShowMask); q[0]=NULL; } if( _strnicmp(q,"<GreyContours>",14)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_GreyContours); q[0]=NULL; } if( _strnicmp(q,"<PtsFlag>",9)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_PtsFlag); q[0]=NULL; } if( _strnicmp(q,"<Smooth>",8)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_Smooth); q[0]=NULL; } if( _strnicmp(q,"<PlotPoints>",12)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_PlotPoints); q[0]=NULL; } if( _strnicmp(q,"<ResetOnReload>",15)==0) { v=StripKey(s); sscanf(v,"%i",&m_d_ResetOnReload); q[0]=NULL; } } fclose(fp); } } void WriteColor(char *cname, COLORREF c,FILE *fp); void CViewPref::WritePrefs() { UpdateData(); m_d_DensityPlot=m_d_dplotlist.GetCurSel(); m_d_EditAction=m_d_editlist.GetCurSel(); m_d_VectorPlot=m_d_vplotlist.GetCurSel(); FILE *fp; CString fname = ((CFemmApp *)AfxGetApp())->GetExecutablePath() + "femmview.cfg"; fp=fopen(fname,"wt"); if (fp!=NULL) { WriteColor("SelColor",SelColor,fp); WriteColor("BkgndColor",BackColor,fp); WriteColor("MeshColor",MeshColor,fp); WriteColor("BlockColor",BlockColor,fp); WriteColor("LineColor",LineColor,fp); WriteColor("GridColor",GridColor,fp); WriteColor("NodeColor",NodeColor,fp); WriteColor("RegionColor",RegionColor,fp); WriteColor("TextColor",TextColor,fp); WriteColor("FluxRColor",RealFluxLineColor,fp); WriteColor("FluxIColor",ImagFluxLineColor,fp); WriteColor("MaskColor", MaskLineColor,fp); WriteColor("VectorRColor", RealVectorColor,fp); WriteColor("VectorIColor", ImagVectorColor,fp); WriteColor("NameColor", NameColor,fp); WriteColor("Color00",Color00,fp); WriteColor("Color01",Color01,fp); WriteColor("Color02",Color02,fp); WriteColor("Color03",Color03,fp); WriteColor("Color04",Color04,fp); WriteColor("Color05",Color05,fp); WriteColor("Color06",Color06,fp); WriteColor("Color07",Color07,fp); WriteColor("Color08",Color08,fp); WriteColor("Color09",Color09,fp); WriteColor("Color10",Color10,fp); WriteColor("Color11",Color11,fp); WriteColor("Color12",Color12,fp); WriteColor("Color13",Color13,fp); WriteColor("Color14",Color14,fp); WriteColor("Color15",Color15,fp); WriteColor("Color16",Color16,fp); WriteColor("Color17",Color17,fp); WriteColor("Color18",Color18,fp); WriteColor("Color19",Color19,fp); WriteColor("Grey00",Grey00,fp); WriteColor("Grey01",Grey01,fp); WriteColor("Grey02",Grey02,fp); WriteColor("Grey03",Grey03,fp); WriteColor("Grey04",Grey04,fp); WriteColor("Grey05",Grey05,fp); WriteColor("Grey06",Grey06,fp); WriteColor("Grey07",Grey07,fp); WriteColor("Grey08",Grey08,fp); WriteColor("Grey09",Grey09,fp); WriteColor("Grey10",Grey10,fp); WriteColor("Grey11",Grey11,fp); WriteColor("Grey12",Grey12,fp); WriteColor("Grey13",Grey13,fp); WriteColor("Grey14",Grey14,fp); WriteColor("Grey15",Grey15,fp); WriteColor("Grey16",Grey16,fp); WriteColor("Grey17",Grey17,fp); WriteColor("Grey18",Grey18,fp); WriteColor("Grey19",Grey19,fp); fprintf(fp,"<EditAction> = %i\n",m_d_EditAction); fprintf(fp,"<DensityPlot> = %i\n",m_d_DensityPlot); fprintf(fp,"<VectorPlot> = %i\n",m_d_VectorPlot); fprintf(fp,"<GridFlag> = %i\n",m_d_GridFlag); fprintf(fp,"<SnapFlag> = %i\n",m_d_SnapFlag); fprintf(fp,"<MeshFlag> = %i\n",m_d_MeshFlag); fprintf(fp,"<LegendFlag> = %i\n",m_d_LegendFlag); fprintf(fp,"<NumContours> = %i\n",m_d_NumContours); fprintf(fp,"<ShowAr> = %i\n",m_d_ShowAr); fprintf(fp,"<ShowAi> = %i\n",m_d_ShowAi); fprintf(fp,"<ShowMask> = %i\n",m_d_ShowMask); fprintf(fp,"<GreyContours> = %i\n",m_d_GreyContours); fprintf(fp,"<PtsFlag> = %i\n",m_d_PtsFlag); fprintf(fp,"<ResetOnReload> = %i\n",m_d_ResetOnReload); fprintf(fp,"<Smooth> = %i\n",m_d_Smooth); fprintf(fp,"<PlotPoints> = %i\n",m_d_PlotPoints); fprintf(fp,"<LineIntegralPoints> = %i\n",m_d_LineIntegralPoints); fprintf(fp,"<ShiftH> = %i\n",m_d_ShiftH); fclose(fp); } }
0racles/devil.js
node_modules/can-make-rest/can-make-rest.js
var each = require("can-util/js/each/each"); var methodMapping = { item: { 'GET': 'getData', 'PUT': 'updateData', 'DELETE': 'destroyData', }, list: { 'GET': 'getListData', 'POST': 'createData' } }; function inferIdProp (url) { var wrappedInBraces = /\{(.*)\}/; var matches = url.match(wrappedInBraces); var isUniqueMatch = matches && matches.length === 2; if (isUniqueMatch) { return matches[1]; } } function getItemAndListUrls (url, idProp) { idProp = idProp || inferIdProp(url) || "id"; var itemRegex = new RegExp('\\/\\{' + idProp+"\\}.*" ); var rootIsItemUrl = itemRegex.test(url); var listUrl = rootIsItemUrl ? url.replace(itemRegex, "") : url; var itemUrl = rootIsItemUrl ? url : (url.trim() + "/{" + idProp + "}"); return {item: itemUrl, list: listUrl}; } module.exports = function(url, idProp){ var data= {}; each( getItemAndListUrls(url, idProp), function(url, type){ each(methodMapping[type], function(interfaceMethod, method){ data[interfaceMethod] = { method: method, url: url }; }); }); return data; };
skycryer/carbon-for-ibm-dotcom
packages/utilities/src/utilities/removeHtmlTagEntities/removeHtmlTagEntities.js
/** * Copyright IBM Corp. 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ const _htmlTagRegex = /<.*?>/g; const _cleanStringRegex = /\n|\s{2,}|&([a-zA-Z]+);/g; /** * Removes any html tags from a string and keeps inner text if any * * @param {string} str String to be checked for html tags * @returns {string} String with html tags stripped out * @private */ const _removeHtmlTags = str => str.replace(_htmlTagRegex, ''); /** * Cleans string by replacing multiple spaces with a single space * and removing single new lines. * * @param {string} str String to be checked * @returns {string} String with multiple spaces and single new lines removed * @private */ const _cleanString = str => str.replace(_cleanStringRegex, ' '); /** * * @param {string} str html string passed in to remove html tags and entities * @param {object} [options={}] Object with options for the conversion * @param {boolean} [options.removeEntities=true] Defines if should remove html entities * @returns {string} String removed of html tags * @example * import { removeHtmlTagEntities } from '@carbon/ibmdotcom-utilities'; * * markdownToHtml('<p>example string</p>&nbsp;<p>here</>') * // 'example string here' */ function removeHtmlTagEntities(str, { removeEntities = true } = {}) { let removedTags = _removeHtmlTags(str); removedTags = removeEntities ? _cleanString(removedTags) : removedTags; return removedTags; } export default removeHtmlTagEntities;
OpenMPDK/SMDK
lib/linux-5.18-rc3-smdk/include/trace/trace_custom_events.h
<filename>lib/linux-5.18-rc3-smdk/include/trace/trace_custom_events.h /* SPDX-License-Identifier: GPL-2.0 */ /* * This is similar to the trace_events.h file, but is to only * create custom trace events to be attached to existing tracepoints. * Where as the TRACE_EVENT() macro (from trace_events.h) will create * both the trace event and the tracepoint it will attach the event to, * TRACE_CUSTOM_EVENT() is to create only a custom version of an existing * trace event (created by TRACE_EVENT() or DEFINE_EVENT()), and will * be placed in the "custom" system. */ #include <linux/trace_events.h> /* All custom events are placed in the custom group */ #undef TRACE_SYSTEM #define TRACE_SYSTEM custom #ifndef TRACE_SYSTEM_VAR #define TRACE_SYSTEM_VAR TRACE_SYSTEM #endif /* The init stage creates the system string and enum mappings */ #include "stages/init.h" #undef TRACE_CUSTOM_EVENT #define TRACE_CUSTOM_EVENT(name, proto, args, tstruct, assign, print) \ DECLARE_CUSTOM_EVENT_CLASS(name, \ PARAMS(proto), \ PARAMS(args), \ PARAMS(tstruct), \ PARAMS(assign), \ PARAMS(print)); \ DEFINE_CUSTOM_EVENT(name, name, PARAMS(proto), PARAMS(args)); /* Stage 1 creates the structure of the recorded event layout */ #include "stages/stage1_struct_define.h" #undef DECLARE_CUSTOM_EVENT_CLASS #define DECLARE_CUSTOM_EVENT_CLASS(name, proto, args, tstruct, assign, print) \ struct trace_custom_event_raw_##name { \ struct trace_entry ent; \ tstruct \ char __data[]; \ }; \ \ static struct trace_event_class custom_event_class_##name; #undef DEFINE_CUSTOM_EVENT #define DEFINE_CUSTOM_EVENT(template, name, proto, args) \ static struct trace_event_call __used \ __attribute__((__aligned__(4))) custom_event_##name #include TRACE_INCLUDE(TRACE_INCLUDE_FILE) /* Stage 2 creates the custom class */ #include "stages/stage2_data_offsets.h" #undef DECLARE_CUSTOM_EVENT_CLASS #define DECLARE_CUSTOM_EVENT_CLASS(call, proto, args, tstruct, assign, print) \ struct trace_custom_event_data_offsets_##call { \ tstruct; \ }; #undef DEFINE_CUSTOM_EVENT #define DEFINE_CUSTOM_EVENT(template, name, proto, args) #include TRACE_INCLUDE(TRACE_INCLUDE_FILE) /* Stage 3 create the way to print the custom event */ #include "stages/stage3_trace_output.h" #undef DECLARE_CUSTOM_EVENT_CLASS #define DECLARE_CUSTOM_EVENT_CLASS(call, proto, args, tstruct, assign, print) \ static notrace enum print_line_t \ trace_custom_raw_output_##call(struct trace_iterator *iter, int flags, \ struct trace_event *trace_event) \ { \ struct trace_seq *s = &iter->seq; \ struct trace_seq __maybe_unused *p = &iter->tmp_seq; \ struct trace_custom_event_raw_##call *field; \ int ret; \ \ field = (typeof(field))iter->ent; \ \ ret = trace_raw_output_prep(iter, trace_event); \ if (ret != TRACE_TYPE_HANDLED) \ return ret; \ \ trace_event_printf(iter, print); \ \ return trace_handle_return(s); \ } \ static struct trace_event_functions trace_custom_event_type_funcs_##call = { \ .trace = trace_custom_raw_output_##call, \ }; #include TRACE_INCLUDE(TRACE_INCLUDE_FILE) /* Stage 4 creates the offset layout for the fields */ #include "stages/stage4_event_fields.h" #undef DECLARE_CUSTOM_EVENT_CLASS #define DECLARE_CUSTOM_EVENT_CLASS(call, proto, args, tstruct, func, print) \ static struct trace_event_fields trace_custom_event_fields_##call[] = { \ tstruct \ {} }; #include TRACE_INCLUDE(TRACE_INCLUDE_FILE) /* Stage 5 creates the helper function for dynamic fields */ #include "stages/stage5_get_offsets.h" #undef DECLARE_CUSTOM_EVENT_CLASS #define DECLARE_CUSTOM_EVENT_CLASS(call, proto, args, tstruct, assign, print) \ static inline notrace int trace_custom_event_get_offsets_##call( \ struct trace_custom_event_data_offsets_##call *__data_offsets, proto) \ { \ int __data_size = 0; \ int __maybe_unused __item_length; \ struct trace_custom_event_raw_##call __maybe_unused *entry; \ \ tstruct; \ \ return __data_size; \ } #include TRACE_INCLUDE(TRACE_INCLUDE_FILE) /* Stage 6 creates the probe function that records the event */ #include "stages/stage6_event_callback.h" #undef DECLARE_CUSTOM_EVENT_CLASS #define DECLARE_CUSTOM_EVENT_CLASS(call, proto, args, tstruct, assign, print) \ \ static notrace void \ trace_custom_event_raw_event_##call(void *__data, proto) \ { \ struct trace_event_file *trace_file = __data; \ struct trace_custom_event_data_offsets_##call __maybe_unused __data_offsets; \ struct trace_event_buffer fbuffer; \ struct trace_custom_event_raw_##call *entry; \ int __data_size; \ \ if (trace_trigger_soft_disabled(trace_file)) \ return; \ \ __data_size = trace_custom_event_get_offsets_##call(&__data_offsets, args); \ \ entry = trace_event_buffer_reserve(&fbuffer, trace_file, \ sizeof(*entry) + __data_size); \ \ if (!entry) \ return; \ \ tstruct \ \ { assign; } \ \ trace_event_buffer_commit(&fbuffer); \ } /* * The ftrace_test_custom_probe is compiled out, it is only here as a build time check * to make sure that if the tracepoint handling changes, the ftrace probe will * fail to compile unless it too is updated. */ #undef DEFINE_CUSTOM_EVENT #define DEFINE_CUSTOM_EVENT(template, call, proto, args) \ static inline void ftrace_test_custom_probe_##call(void) \ { \ check_trace_callback_type_##call(trace_custom_event_raw_event_##template); \ } #include TRACE_INCLUDE(TRACE_INCLUDE_FILE) /* Stage 7 creates the actual class and event structure for the custom event */ #include "stages/stage7_class_define.h" #undef DECLARE_CUSTOM_EVENT_CLASS #define DECLARE_CUSTOM_EVENT_CLASS(call, proto, args, tstruct, assign, print) \ static char custom_print_fmt_##call[] = print; \ static struct trace_event_class __used __refdata custom_event_class_##call = { \ .system = TRACE_SYSTEM_STRING, \ .fields_array = trace_custom_event_fields_##call, \ .fields = LIST_HEAD_INIT(custom_event_class_##call.fields),\ .raw_init = trace_event_raw_init, \ .probe = trace_custom_event_raw_event_##call, \ .reg = trace_event_reg, \ }; #undef DEFINE_CUSTOM_EVENT #define DEFINE_CUSTOM_EVENT(template, call, proto, args) \ \ static struct trace_event_call __used custom_event_##call = { \ .name = #call, \ .class = &custom_event_class_##template, \ .event.funcs = &trace_custom_event_type_funcs_##template, \ .print_fmt = custom_print_fmt_##template, \ .flags = TRACE_EVENT_FL_CUSTOM, \ }; \ static inline int trace_custom_event_##call##_update(struct tracepoint *tp) \ { \ if (tp->name && strcmp(tp->name, #call) == 0) { \ custom_event_##call.tp = tp; \ custom_event_##call.flags = TRACE_EVENT_FL_TRACEPOINT; \ return 1; \ } \ return 0; \ } \ static struct trace_event_call __used \ __section("_ftrace_events") *__custom_event_##call = &custom_event_##call #include TRACE_INCLUDE(TRACE_INCLUDE_FILE)
mf01/luacpp
Source/Engine/LuaTUserData.cpp
<reponame>mf01/luacpp /* MIT License Copyright (c) 2021 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include "LuaTUserData.hpp" using namespace LuaCpp::Engine; int LuaTUserData::getTypeId() { return LUA_TUSERDATA; } std::string LuaTUserData::getTypeName(LuaState &L) { return std::string(lua_typename(L, LUA_TUSERDATA)); } void LuaTUserData::PushValue(LuaState &L) { userdata = lua_newuserdata(L, size); if (metatable.size() > 0) { lua_newtable(L); for (const auto &pairs: metatable) { lua_pushcfunction(L, pairs.second); lua_setfield(L, -2, pairs.first.c_str()); } lua_setmetatable(L, -2); } _storeData(); } void LuaTUserData::PopValue(LuaState &L, int idx) { if (lua_type(L, idx) == LUA_TUSERDATA) { void * _userdata = lua_touserdata(L, idx); if (_userdata == userdata) { _retreiveData(); } else { throw std::domain_error("The value on the stack "+std::to_string(idx)+" has different pointer to the userdata buffer."); } } else { throw std::invalid_argument("The value at the stack position " + std::to_string(idx) + " is not LUA_TNUMBER"); } } std::string LuaTUserData::ToString() { return "userdata"; } void LuaTUserData::_storeData() { } void LuaTUserData::_retreiveData() { } void* LuaTUserData::getRawUserData() { return userdata; } void LuaTUserData::AddMetaFunction(std::string fname, lua_CFunction fn) { metatable[fname] = fn; }
aashishgahlawat/CompetetiveProgramming
aashishgahlawat/codeforces/B/556-B/556-B-31658893.cpp
<filename>aashishgahlawat/codeforces/B/556-B/556-B-31658893.cpp<gh_stars>0 #include <iostream> #include <bits/stdc++.h> #define endl '\n' using namespace std; int game[1002]; int counter; bool Check(){ int i=1; for(i=1;i<counter;++i){ if((game[i]-1)!=game[i-1]) break; } if(i==counter) return true;//as break -1 return false; } int main() { ios_base::sync_with_stdio(false); ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); // aashish gahlawat cin>>counter; if(counter==1) {cout<<"YES"; return 0;} for(int i=0;i<counter;i++){ cin>>game[i]; } if(Check()) {cout<<"YES"; return 0;} int temp=counter; int me=0; while(temp--){ for(int i=0;i<counter;i++){ if(i & 1){//odd case if(game[i]==0) game[i]=counter-1; else game[i]--; }else{//even case if(game[i]==counter-1) game[i]=0; else game[i]++; } ////////////////////////////// if(i>0){ if(game[i]==game[i-1]+1) me++; } ///////////////////////////// } //if(Check()) {cout<<"YES"; return 0;} ////////////////////////////////////// if(me==counter-1){ cout<<"YES"; return 0;} me=0; ///////////////////////////////////// } cout<<"NO"; return 0; }
fancheng123/wangsy-january
january-merchant/src/main/java/smile/wangsy/january/merchant/vo/ProductCategoryVo.java
<reponame>fancheng123/wangsy-january<gh_stars>100-1000 package smile.wangsy.january.merchant.vo; import org.springframework.beans.BeanUtils; import smile.wangsy.january.merchant.model.ProductCategory; import java.util.List; import java.io.Serializable; import java.util.stream.Collectors; import lombok.Data; /** * @author wangsy * @date 2018/08/31. */ @Data public class ProductCategoryVo implements Serializable { private Long id; /** * 类别名称 */ private String name; /** * 描述 */ private String description; /** * 审核状态(0:未审核,1:通过;2:不通过) */ private Integer state; public static ProductCategoryVo transModelToVo(ProductCategory model) { ProductCategoryVo vo = new ProductCategoryVo(); BeanUtils.copyProperties(model, vo); return vo; } /** * 将ModelList转换为ModelVoList * @param modelList * @return */ public static List<ProductCategoryVo> transModelListToVoList(List<ProductCategory> modelList) { List<ProductCategoryVo> voList = modelList.stream().map(e -> transModelToVo(e)).collect(Collectors.toList()); return voList; } }
pln606/https-github.com-OmegaHelix-openproject
app/models/queries/relations/filters/involved_filter.rb
#-- encoding: UTF-8 #-- copyright # OpenProject is a project management system. # Copyright (C) 2012-2017 the OpenProject Foundation (OPF) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2017 <NAME> # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See doc/COPYRIGHT.rdoc for more details. #++ module Queries module Relations module Filters ## # Filters relations by work package ID in either `from` or `to` position of a relation. # For instance: # Given relations [{ from_id: 3, to_id: 7 }, { from_id: 8, to_id: 3}] # filtering by involved=3 would yield both these relations. class InvolvedFilter < ::Queries::Relations::Filters::RelationFilter def type :integer end def self.key :involved end def where integer_values = values.map(&:to_i) case operator when "=" ["from_id IN (?) OR to_id IN (?)", integer_values, integer_values] when "!" ["from_id NOT IN (?) AND to_id NOT IN (?)", integer_values, integer_values] end end end end end end
Passer-D/GameAISDK
src/ImgProc/Comm/Utils/Log.h
/* * Tencent is pleased to support the open source community by making GameAISDK available. * This source code file is licensed under the GNU General Public License Version 3. * For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package. * Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. */ #ifndef GAME_AI_SDK_IMGPROC_COMM_UTILS_LOG_H_ #define GAME_AI_SDK_IMGPROC_COMM_UTILS_LOG_H_ #include <stdio.h> #include <string> #include "Comm/Utils/TqcCommon.h" #include "Comm/Utils/TqcLock.h" #include "Comm/Utils/TSingleton.h" class CLog : public TSingleton<CLog> { public: DECLARE_SINGLETON_CLASS(CLog); enum LogPriority { LOG_PRIORITY_ERROR = 0x1, LOG_PRIORITY_WARN = 0x2, LOG_PRIORITY_RUN = 0x4, }; CLog(); public: /*! @brief 初始化日志系??? @param[in] pszLogFileName 日志文件基础??? @param[in] eLogLevel 日志级别,可过滤日志输出 @param[in] nLogFileSize 单个日志文件大小,默认为10M @param[in] nLogRollNum 日志文件个数 @return 0 成功, -1失败 */ int init(const char *pszLogFileName, int eLogLevel = LOG_PRIORITY_ERROR | LOG_PRIORITY_WARN | LOG_PRIORITY_RUN, int nLogFileSize = 10 * 1024 * 1024, int nLogRollNum = 5); /*! @brief 输出日志 @param[in] eLogLevel 日志级别 @param[in] pszLogContent 输出日志内容 @param[in] uLogContentLen 输出日志内容长度 @return */ // int logWrite(int eLogLevel, const char* pszFormat, ...); int logWrite(int eLogLevel, const char *pszLogContent, size_t uLogContentLen); /*! @brief 关闭日志文件 */ void closeLog(); int getLogLevel(char *arg); private: /*! @brief 向日志文件输出错误级别日志内??? @param[in] pszLogContent 输出日志内容 @param[in] uLogContentLen 输出日志内容长度 */ void logError(const char *pszLogContent, size_t uLogContentLen); /*! @brief 向日志文件输出错误级别日志内??? @param[in] pszLogContent 输出日志内容 @param[in] uLogContentLen 输出日志内容长度 */ void logWarn(const char *pszLogContent, size_t uLogContentLen); /*! @brief 向日志文件输出错误级别日志内??? @param[in] pszLogContent 输出日志内容 @param[in] uLogContentLen 输出日志内容长度 */ void logRun(const char *pszLogContent, size_t uLogContentLen); /*! @brief 打开日志文件,若文件存在不清??? @param[in] pszLogFileName 日志文件路径 @return 0 成功???< 0 失败 */ int openLogFile(const char *pszLogFileName); /*! */ int openResetLogFile(const char *pszLogFileName); private: FILE *m_pfLogfile; int m_nFileSize; int m_nLogPriotify; int m_nMaxRollNum; int m_nCurRollNum; int m_nCurPosition; std::string m_strLogBaseName; CLock m_oLock; }; #endif // GAME_AI_SDK_IMGPROC_COMM_UTILS_LOG_H_
OhmPopy/MPFUI
include/suic/Skia/core/SkFontHost.h
<filename>include/suic/Skia/core/SkFontHost.h<gh_stars>10-100 /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkFontHost_DEFINED #define SkFontHost_DEFINED #include "SkTypeface.h" class SkDescriptor; class SkScalerContext; struct SkScalerContextRec; class SkStream; class SkWStream; /** \class SkFontHost This class is ported to each environment. It is responsible for bridging the gap between the (sort of) abstract class SkTypeface and the platform-specific implementation that provides access to font files. One basic task is for each create (subclass of) SkTypeface, the FontHost is responsible for assigning a uniqueID. The ID should be unique for the underlying font file/data, not unique per typeface instance. Thus it is possible/common to request a typeface for the same font more than once (e.g. asking for the same font by name several times). The FontHost may return seperate typeface instances in that case, or it may choose to use a cache and return the same instance (but calling typeface->ref(), since the caller is always responsible for calling unref() on each instance that is returned). Either way, the fontID for those instance(s) will be the same. In addition, the fontID should never be set to 0. That value is used as a sentinel to indicate no-font-id. The major aspects are: 1) Given either a name/style, return a subclass of SkTypeface that references the closest matching font available on the host system. 2) Given the data for a font (either in a stream or a file name), return a typeface that allows access to that data. 3) Each typeface instance carries a 32bit ID for its corresponding font. SkFontHost turns that ID into a stream to access the font's data. 4) Given a font ID, return a subclass of SkScalerContext, which connects a font scaler (e.g. freetype or other) to the font's data. 5) Utilites to manage the font cache (budgeting) and gamma correction */ class SK_API SkFontHost { public: /** LCDs either have their color elements arranged horizontally or vertically. When rendering subpixel glyphs we need to know which way round they are. Note, if you change this after startup, you'll need to flush the glyph cache because it'll have the wrong type of masks cached. @deprecated use SkPixelGeometry instead. */ enum LCDOrientation { kHorizontal_LCDOrientation = 0, //!< this is the default kVertical_LCDOrientation = 1 }; /** @deprecated set on Device creation. */ static void SetSubpixelOrientation(LCDOrientation orientation); /** @deprecated get from Device. */ static LCDOrientation GetSubpixelOrientation(); /** LCD color elements can vary in order. For subpixel text we need to know the order which the LCDs uses so that the color fringes are in the correct place. Note, if you change this after startup, you'll need to flush the glyph cache because it'll have the wrong type of masks cached. kNONE_LCDOrder means that the subpixel elements are not spatially separated in any usable fashion. @deprecated use SkPixelGeometry instead. */ enum LCDOrder { kRGB_LCDOrder = 0, //!< this is the default kBGR_LCDOrder = 1, kNONE_LCDOrder = 2 }; /** @deprecated set on Device creation. */ static void SetSubpixelOrder(LCDOrder order); /** @deprecated get from Device. */ static LCDOrder GetSubpixelOrder(); private: /** Return a new, closest matching typeface given either an existing family (specified by a typeface in that family) or by a familyName and a requested style. 1) If familyFace is null, use familyName. 2) If familyName is null, use data (UTF-16 to cover). 3) If all are null, return the default font that best matches style */ static SkTypeface* CreateTypeface(const SkTypeface* familyFace, const char familyName[], SkTypeface::Style style); /** Return a new typeface given the data buffer. If the data does not represent a valid font, returns null. If a typeface instance is returned, the caller is responsible for calling unref() on the typeface when they are finished with it. The returned typeface may or may not have called ref() on the stream parameter. If the typeface has not called ref(), then it may have made a copy of the releveant data. In either case, the caller is still responsible for its refcnt ownership of the stream. */ static SkTypeface* CreateTypefaceFromStream(SkStream*); /** Return a new typeface from the specified file path. If the file does not represent a valid font, this returns null. If a typeface is returned, the caller is responsible for calling unref() when it is no longer used. */ static SkTypeface* CreateTypefaceFromFile(const char path[]); static SkScalerContext* CreateScalerContext(SkTypeface* f, const SkDescriptor* desc); static SkTypeface* NextLogicalFont(SkFontID fontID, SkTypeface::Style s); /////////////////////////////////////////////////////////////////////////// friend class SkScalerContext; friend class SkTypeface; }; #endif
willfish/trade-tariff-backend
db/migrate/20130123125153_adjust_chief_decimal_columns.rb
<reponame>willfish/trade-tariff-backend Sequel.migration do up do alter_table :chief_comm do set_column_type :full_dty_adval1, BigDecimal, size: [6, 3] set_column_type :full_dty_adval2, BigDecimal, size: [6, 3] set_column_type :full_dty_spfc1, BigDecimal, size: [8, 4] set_column_type :full_dty_spfc2, BigDecimal, size: [8, 4] end end down do alter_table :chief_comm do set_column_type :full_dty_adval1, BigDecimal, size: [3, 3] set_column_type :full_dty_adval2, BigDecimal, size: [3, 3] set_column_type :full_dty_spfc1, BigDecimal, size: [7, 4] set_column_type :full_dty_spfc2, BigDecimal, size: [7, 4] end end end
whitmans-max/python-examples
Google API/Geocoding/main.py
<filename>Google API/Geocoding/main.py # # https://developers.google.com/maps/documentation/geocoding/intro # import googlemaps API_KEY = '<YOUR-API-KEY>' gmaps = googlemaps.Client(key=API_KEY) # convert address to lat,long results = gmaps.geocode('221B Baker Street, London, United Kingdom') for key in results[0].keys(): print('key:', key) print('-----') item = results[0] print('formatted_address:', item['formatted_address']) print('lat:', item['geometry']['location']['lat']) print('lng:', item['geometry']['location']['lng']) print('location:', item['geometry']['location']) for part in item['address_components']: print(part) print('---') print('address_components:', item['address_components']) print('formatted_address:', item['formatted_address']) print('geometry:', item['geometry']) print('place_id:', item['place_id']) print('types:', item['types']) print('-----------------------------------------') # convert lat,long to (nearest?) addresses result = gmaps.geocode('51.523767 -0.1585557') for item in result: for part in item['address_components']: print(part['long_name']) print('---')
NeilJustice/FileRevisor
libFileRevisorTests/UtilityComponents/FunctionCallers/Member/MetalMock/NonVoidTwoArgMemberFunctionCallerMock.h
<reponame>NeilJustice/FileRevisor #pragma once #include "libFileRevisor/UtilityComponents/FunctionCallers/Member/NonVoidTwoArgMemberFunctionCaller.h" template<typename ReturnType, typename ClassType, typename Arg1Type, typename Arg2Type> class NonVoidTwoArgMemberFunctionCallerMock : public Metal::Mock<NonVoidTwoArgMemberFunctionCaller<ReturnType, ClassType, Arg1Type, Arg2Type>> { public: using ConstMemberFunctionType = ReturnType(ClassType::*)(Arg1Type, Arg2Type) const; METALMOCK_NONVOID4_CONST(ReturnType, CallConstMemberFunction, const ClassType*, ConstMemberFunctionType, Arg1Type, Arg2Type) using NonConstMemberFunctionType = ReturnType(ClassType::*)(Arg1Type, Arg2Type); METALMOCK_NONVOID4_CONST(ReturnType, CallNonConstMemberFunction, ClassType*, NonConstMemberFunctionType, Arg1Type, Arg2Type) };
zvam1/gitlab-on-heroku
app/assets/javascripts/pipelines/utils.js
import { pickBy } from 'lodash'; import { SUPPORTED_FILTER_PARAMETERS } from './constants'; export const validateParams = params => { return pickBy(params, (val, key) => SUPPORTED_FILTER_PARAMETERS.includes(key) && val); }; export const createUniqueJobId = (stageName, jobName) => `${stageName}-${jobName}`; /** * This function takes a json payload that comes from a yml * file converted to json through `jsyaml` library. Because we * naively convert the entire yaml to json, some keys (like `includes`) * are irrelevant to rendering the graph and must be removed. We also * restructure the data to have the structure from an API response for the * pipeline data. * @param {Object} jsonData * @returns {Array} - Array of stages containing all jobs */ export const preparePipelineGraphData = jsonData => { const jsonKeys = Object.keys(jsonData); const jobNames = jsonKeys.filter(job => jsonData[job]?.stage); // Creates an object with only the valid jobs const jobs = jsonKeys.reduce((acc, val) => { if (jobNames.includes(val)) { return { ...acc, [val]: { ...jsonData[val], id: createUniqueJobId(jsonData[val].stage, val) }, }; } return { ...acc }; }, {}); // We merge both the stages from the "stages" key in the yaml and the stage associated // with each job to show the user both the stages they explicitly defined, and those // that they added under jobs. We also remove duplicates. const jobStages = jobNames.map(job => jsonData[job].stage); const userDefinedStages = jsonData?.stages ?? []; // The order is important here. We always show the stages in order they were // defined in the `stages` key first, and then stages that are under the jobs. const stages = Array.from(new Set([...userDefinedStages, ...jobStages])); const arrayOfJobsByStage = stages.map(val => { return jobNames.filter(job => { return jsonData[job].stage === val; }); }); const pipelineData = stages.map((stage, index) => { const stageJobs = arrayOfJobsByStage[index]; return { name: stage, groups: stageJobs.map(job => { return { name: job, jobs: [{ ...jsonData[job] }], id: createUniqueJobId(stage, job), }; }), }; }); return { stages: pipelineData, jobs }; }; export const generateJobNeedsDict = ({ jobs }) => { const arrOfJobNames = Object.keys(jobs); return arrOfJobNames.reduce((acc, value) => { const recursiveNeeds = jobName => { if (!jobs[jobName]?.needs) { return []; } return jobs[jobName].needs .map(job => { const { id } = jobs[job]; // If we already have the needs of a job in the accumulator, // then we use the memoized data instead of the recursive call // to save some performance. const newNeeds = acc[id] ?? recursiveNeeds(job); return [id, ...newNeeds]; }) .flat(Infinity); }; // To ensure we don't have duplicates job relationship when 2 jobs // needed by another both depends on the same jobs, we remove any // duplicates from the array. const uniqueValues = Array.from(new Set(recursiveNeeds(value))); return { ...acc, [jobs[value].id]: uniqueValues }; }, {}); };
coveo/swagger-core
modules/swagger-jaxrs/src/test/scala/resources/Resource942SubResource.java
<reponame>coveo/swagger-core<filename>modules/swagger-jaxrs/src/test/scala/resources/Resource942SubResource.java package resources; import models.Employee; import com.wordnik.swagger.annotations.*; import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.util.*; @Api(hidden = true) public class Resource942SubResource { @ApiOperation(value = "gets all employees", response = Employee.class, responseContainer = "list", tags = "Employees") @Path("") public Response getEmployeesById() { return Response.ok().build(); } }
hktr92/phaser3-rex-notes
templates/ui/roundrectanglecanvas/RoundRectangleCanvas.js
import RoundRectangleCanvas from '../../../plugins/gameobjects/canvas/roundrectangle/RoundRectangle.js'; export default RoundRectangleCanvas;
dipta007/Competitive-Programming
SPOJ/QTREE2.cpp
#include <bits/stdc++.h> using namespace std; #define READ(f) freopen(f, "r", stdin) #define WRITE(f) freopen(f, "w", stdout) #define MP(x, y) make_pair(x, y) #define PB(x) push_back(x) #define FOR(i,L,R) for (int i = (int)(L); i <= (int)(R); i++) #define ROF(i,L,R) for (int i = (int)(L); i >= (int)(R); i--) #define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++) #define ALL(p) p.begin(),p.end() #define ALLR(p) p.rbegin(),p.rend() #define SET(p) memset(p, -1, sizeof(p)) #define CLR(p) memset(p, 0, sizeof(p)) #define MEM(p, v) memset(p, v, sizeof(p)) #define getI(a) scanf("%d", &a) #define getII(a,b) scanf("%d%d", &a, &b) #define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c) #define getL(a) scanf("%lld",&a) #define getLL(a,b) scanf("%lld%lld",&a,&b) #define getLLL(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define getC(n) scanf("%c",&n) #define getF(n) scanf("%lf",&n) #define getS(n) scanf("%s",n) #define bitCheck(N,in) ((bool)(N&(1<<(in)))) #define bitOff(N,in) (N&(~(1<<(in)))) #define bitOn(N,in) (N|(1<<(in))) #define bitFlip(a,k) (a^(1<<(k))) #define bitCount(a) __builtin_popcount(a) #define bitCountLL(a) __builtin_popcountll(a) #define bitLeftMost(a) (63-__builtin_clzll((a))) #define bitRightMost(a) (__builtin_ctzll(a)) #define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end()) #define vi vector < int > #define vii vector < vector < int > > #define pii pair< int, int > #define ff first #define ss second #define ll long long #define ull unsigned long long #define sf scanf #define pf printf #define FMT(...) (sprintf(CRTBUFF, __VA_ARGS__)?CRTBUFF:0) char CRTBUFF[30000]; #ifdef dipta00 #define debug(args...) {cerr<<"Debug: "; dbg,args; cerr<<endl;} #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...); } #else #define debug(args...) /// Just strip off all debug tokens #define trace(...) ///yeeeee #endif struct debugger{ template<typename T> debugger& operator , (const T& v){ cerr<<v<<" "; return *this; } }dbg; const double EPS = 1e-9; const int INF = 0x7f7f7f7f; const double PI=acos(-1.0); // g++ -g -O2 -std=gnu++11 A.cpp // ./a.out ///****************** template ends here **************** int t, n, m; //LCA with Sparse Table struct LCA{ static const int NMAX = 30004; // Must be atleast twice the number of nodes static const int WIDTH = 20; int F[NMAX+10], L[NMAX+10], lst, DD[NMAX+10]; ll D[NMAX+10]; int idx [NMAX+10][WIDTH+4]; int id [NMAX+10][WIDTH+4]; vector<pii> *G; int power[NMAX + 4]; void pre() { int h = 2; int now = 1; power[0] = 0; for(int i=0; i<=NMAX; i++) { power[i] = now; if(i == h) { now = h; h *= 2; } } } void build(vector<pii> *G, int u){ pre(); memset(F, -1, sizeof(F)); this->G=G; D[u]=lst=0; dfs(u, -1); for(int h=1; h<=20; h++) { for(int i=0; i+(1<<h)<NMAX; i++) { int x = id[i][h]; if(x != -1) x =id[x][h]; id[i][h+1]=x; int hh = h - 1; idx[i][h]=argmin(idx[i][hh], idx[i+(1<<hh)][hh]); } } } void dfs(int u, int par){ id[u][0] = u; id[u][1] = par; idx[lst][0] = u; F[u]=L[u]=lst++; for(auto v: G[u]){ if(F[v.ff]==-1){ D[v.ff]=D[u]+v.ss; DD[v.ff] = DD[u] + 1; dfs(v.ff, u); idx[lst][0] = u; L[u]=lst++; } } } int get(int u, int v){ int x = min(F[u], F[v]), y = max(L[u], L[v]); if(x == y) return u; if(x > y) swap(x, y); int h = bitWidth(y - x); return argmin(idx[x][h], idx[y - (1<<h)][h]); } ll dist(int u, int v){ trace(u, v, D[u], D[v], get(u,v)); return D[u]+D[v]-2*D[get(u, v)]; } int distK(int u, int v){ return DD[u]+DD[v]-2*DD[get(u, v)]; } int afterKup(int u, int k) { k--; while(k != 0) { int h = power[k]; u = id[u][h]; k -= h; trace(u, h); } return u; } int kth(int u, int v, int k) { int root = get(u, v); int ud = distK(u, root); int vd = distK(v, root); int unodes = ud + 1; trace(u, v, k, ud, vd, unodes); if(k > unodes + vd) return v; if(k <= unodes) { return afterKup(u, k); } else { k -= unodes; vd -= k; vd++; return afterKup(v, vd); } } // Helper Functions int bitWidth(int x){return 31-__builtin_clz(x);} int argmin(int x, int y){return DD[x]<DD[y]?x:y;} } lca; vector < pii > adj[10004]; int main() { #ifdef dipta007 READ("in.txt"); WRITE("out.txt"); #endif // dipta007 ios_base::sync_with_stdio(0);cin.tie(0); int t; cin >> t; FOR(ci,1,t) { int n; cin >> n; FOR(i,0,n) adj[i].clear(); FOR(i, 1, n-1) { int u,v,w; cin >> u >> v >> w; adj[u].PB( MP(v, w) ); adj[v].PB( MP(u, w) ); } lca.build(adj, 1); string st; cin >> st; while(st != "DONE") { int x, y; cin >> x >> y; if(st[0] == 'D') { cout << lca.dist(x, y) << endl; } else { int k; cin >> k; cout << lca.kth(x, y, k) << endl; } cin >> st; } cout << endl; } return 0; }
phatblat/macOSPrivateFrameworks
PrivateFrameworks/SidecarCore/SidecarDisplayAgent_Interface-Protocol.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // @class NSArray, SidecarDevice, SidecarDisplayConfig; @protocol SidecarDisplayAgent_Interface - (void)preferencesChanged:(NSArray *)arg1; - (void)displayCurrentConfig:(void (^)(SidecarDisplayConfig *, NSError *))arg1; - (void)displayAgentDevices:(void (^)(SidecarDevice *, NSArray *, NSError *))arg1; - (void)displayAgentDisconnectFromDevice:(SidecarDevice *)arg1 completion:(void (^)(NSError *))arg2; - (void)displayAgentConnectToDevice:(SidecarDevice *)arg1 withConfig:(SidecarDisplayConfig *)arg2 completion:(void (^)(NSError *))arg3; @end
int128/amefuriso
gateways/weather_test.go
<gh_stars>1-10 package gateways import ( "context" "testing" "time" "github.com/go-test/deep" "github.com/golang/mock/gomock" "github.com/int128/amefuriso/domain" "github.com/int128/amefuriso/domain/testdata" "github.com/int128/amefuriso/gateways/interfaces" "github.com/int128/amefuriso/infrastructure/interfaces/mock_infrastructure" "github.com/int128/go-yahoo-weather/weather" ) func TestWeatherService_Get(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() ctx := context.Background() client := mock_infrastructure.NewMockWeatherClient(ctrl) client.EXPECT(). Get(ctx, "CLIENT_ID", weather.Request{ Coordinates: []weather.Coordinates{ {Latitude: 35.663613, Longitude: 139.732293}, {Latitude: 41.7686738, Longitude: 140.728924}, }, IntervalMinutes: 5, PastHours: 1, }). Return([]weather.Weather{ { Coordinates: weather.Coordinates{Latitude: 35.663613, Longitude: 139.73229}, Events: []weather.Event{ {Time: time.Date(2018, 12, 12, 13, 5, 0, 0, weather.Timezone)}, {Time: time.Date(2018, 12, 12, 13, 15, 0, 0, weather.Timezone), Forecast: true}, {Time: time.Date(2018, 12, 12, 13, 25, 0, 0, weather.Timezone), Forecast: true}, {Time: time.Date(2018, 12, 12, 13, 35, 0, 0, weather.Timezone), Forecast: true}, {Time: time.Date(2018, 12, 12, 13, 45, 0, 0, weather.Timezone), Forecast: true}, {Time: time.Date(2018, 12, 12, 13, 55, 0, 0, weather.Timezone), Forecast: true}, {Time: time.Date(2018, 12, 12, 14, 5, 0, 0, weather.Timezone), Forecast: true}, }, }, { Coordinates: weather.Coordinates{Latitude: 41.768674, Longitude: 140.72892}, Events: []weather.Event{ {Time: time.Date(2018, 12, 12, 13, 5, 0, 0, weather.Timezone), Rainfall: 0.35}, {Time: time.Date(2018, 12, 12, 13, 15, 0, 0, weather.Timezone), Rainfall: 0.45}, {Time: time.Date(2018, 12, 12, 13, 25, 0, 0, weather.Timezone), Rainfall: 1.15}, {Time: time.Date(2018, 12, 12, 13, 35, 0, 0, weather.Timezone), Rainfall: 0.45}, {Time: time.Date(2018, 12, 12, 13, 45, 0, 0, weather.Timezone), Rainfall: 1.85}, {Time: time.Date(2018, 12, 12, 13, 55, 0, 0, weather.Timezone), Forecast: true}, {Time: time.Date(2018, 12, 12, 14, 5, 0, 0, weather.Timezone), Forecast: true}, }, }, }, nil) service := WeatherService{Client: client} actual, err := service.Get(ctx, domain.YahooClientID("CLIENT_ID"), []domain.Location{testdata.TokyoLocation, testdata.HakodateLocation}, gateways.OneHourObservation) if err != nil { t.Fatalf("Error while service.Get: %s", err) } want := []domain.Weather{ { Location: testdata.TokyoLocation, Observations: []domain.Event{ {Time: time.Date(2018, 12, 12, 13, 5, 0, 0, weather.Timezone)}, }, Forecasts: []domain.Event{ {Time: time.Date(2018, 12, 12, 13, 15, 0, 0, weather.Timezone)}, {Time: time.Date(2018, 12, 12, 13, 25, 0, 0, weather.Timezone)}, {Time: time.Date(2018, 12, 12, 13, 35, 0, 0, weather.Timezone)}, {Time: time.Date(2018, 12, 12, 13, 45, 0, 0, weather.Timezone)}, {Time: time.Date(2018, 12, 12, 13, 55, 0, 0, weather.Timezone)}, {Time: time.Date(2018, 12, 12, 14, 5, 0, 0, weather.Timezone)}, }, }, { Location: testdata.HakodateLocation, Observations: []domain.Event{ {Time: time.Date(2018, 12, 12, 13, 5, 0, 0, weather.Timezone), Rainfall: 0.35}, {Time: time.Date(2018, 12, 12, 13, 15, 0, 0, weather.Timezone), Rainfall: 0.45}, {Time: time.Date(2018, 12, 12, 13, 25, 0, 0, weather.Timezone), Rainfall: 1.15}, {Time: time.Date(2018, 12, 12, 13, 35, 0, 0, weather.Timezone), Rainfall: 0.45}, {Time: time.Date(2018, 12, 12, 13, 45, 0, 0, weather.Timezone), Rainfall: 1.85}, }, Forecasts: []domain.Event{ {Time: time.Date(2018, 12, 12, 13, 55, 0, 0, weather.Timezone)}, {Time: time.Date(2018, 12, 12, 14, 5, 0, 0, weather.Timezone)}, }, }, } if diff := deep.Equal(want, actual); diff != nil { t.Error(diff) } }
zipated/src
chrome/android/java/src/org/chromium/chrome/browser/TtsPlatformImpl.java
<filename>chrome/android/java/src/org/chromium/chrome/browser/TtsPlatformImpl.java<gh_stars>1000+ // Copyright 2013 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. package org.chromium.chrome.browser; import android.os.AsyncTask; import android.os.Build; import android.speech.tts.TextToSpeech; import android.speech.tts.UtteranceProgressListener; import org.chromium.base.ContextUtils; import org.chromium.base.ThreadUtils; import org.chromium.base.TraceEvent; import org.chromium.base.annotations.CalledByNative; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; /** * This class is the Java counterpart to the C++ TtsPlatformImplAndroid class. * It implements the Android-native text-to-speech code to support the web * speech synthesis API. * * Threading model note: all calls from C++ must happen on the UI thread. * Callbacks from Android may happen on a different thread, so we always * use ThreadUtils.runOnUiThread when calling back to C++. */ class TtsPlatformImpl { private static class TtsVoice { private TtsVoice(String name, String language) { mName = name; mLanguage = language; } private final String mName; private final String mLanguage; } private static class PendingUtterance { private PendingUtterance(TtsPlatformImpl impl, int utteranceId, String text, String lang, float rate, float pitch, float volume) { mImpl = impl; mUtteranceId = utteranceId; mText = text; mLang = lang; mRate = rate; mPitch = pitch; mVolume = volume; } private void speak() { mImpl.speak(mUtteranceId, mText, mLang, mRate, mPitch, mVolume); } TtsPlatformImpl mImpl; int mUtteranceId; String mText; String mLang; float mRate; float mPitch; float mVolume; } private long mNativeTtsPlatformImplAndroid; protected final TextToSpeech mTextToSpeech; private boolean mInitialized; private List<TtsVoice> mVoices; private String mCurrentLanguage; private PendingUtterance mPendingUtterance; protected TtsPlatformImpl(long nativeTtsPlatformImplAndroid) { mInitialized = false; mNativeTtsPlatformImplAndroid = nativeTtsPlatformImplAndroid; mTextToSpeech = new TextToSpeech(ContextUtils.getApplicationContext(), status -> { if (status == TextToSpeech.SUCCESS) { ThreadUtils.runOnUiThread(() -> initialize()); } }); addOnUtteranceProgressListener(); } /** * Create a TtsPlatformImpl object, which is owned by TtsPlatformImplAndroid * on the C++ side. * @param nativeTtsPlatformImplAndroid The C++ object that owns us. * */ @CalledByNative private static TtsPlatformImpl create(long nativeTtsPlatformImplAndroid) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return new LollipopTtsPlatformImpl(nativeTtsPlatformImplAndroid); } else { return new TtsPlatformImpl(nativeTtsPlatformImplAndroid); } } /** * Called when our C++ counterpoint is deleted. Clear the handle to our * native C++ object, ensuring it's never called. */ @CalledByNative private void destroy() { mNativeTtsPlatformImplAndroid = 0; } /** * @return true if our TextToSpeech object is initialized and we've * finished scanning the list of voices. */ @CalledByNative private boolean isInitialized() { return mInitialized; } /** * @return the number of voices. */ @CalledByNative private int getVoiceCount() { assert mInitialized; return mVoices.size(); } /** * @return the name of the voice at a given index. */ @CalledByNative private String getVoiceName(int voiceIndex) { assert mInitialized; return mVoices.get(voiceIndex).mName; } /** * @return the language of the voice at a given index. */ @CalledByNative private String getVoiceLanguage(int voiceIndex) { assert mInitialized; return mVoices.get(voiceIndex).mLanguage; } /** * Attempt to start speaking an utterance. If it returns true, will call back on * start and end. * * @param utteranceId A unique id for this utterance so that callbacks can be tied * to a particular utterance. * @param text The text to speak. * @param lang The language code for the text (e.g., "en-US"). * @param rate The speech rate, in the units expected by Android TextToSpeech. * @param pitch The speech pitch, in the units expected by Android TextToSpeech. * @param volume The speech volume, in the units expected by Android TextToSpeech. * @return true on success. */ @CalledByNative private boolean speak(int utteranceId, String text, String lang, float rate, float pitch, float volume) { if (!mInitialized) { mPendingUtterance = new PendingUtterance(this, utteranceId, text, lang, rate, pitch, volume); return true; } if (mPendingUtterance != null) mPendingUtterance = null; if (!lang.equals(mCurrentLanguage)) { mTextToSpeech.setLanguage(new Locale(lang)); mCurrentLanguage = lang; } mTextToSpeech.setSpeechRate(rate); mTextToSpeech.setPitch(pitch); int result = callSpeak(text, volume, utteranceId); return (result == TextToSpeech.SUCCESS); } /** * Stop the current utterance. */ @CalledByNative private void stop() { if (mInitialized) mTextToSpeech.stop(); if (mPendingUtterance != null) mPendingUtterance = null; } /** * Post a task to the UI thread to send the TTS "end" event. */ protected void sendEndEventOnUiThread(final String utteranceId) { ThreadUtils.runOnUiThread(() -> { if (mNativeTtsPlatformImplAndroid != 0) { nativeOnEndEvent(mNativeTtsPlatformImplAndroid, Integer.parseInt(utteranceId)); } }); } /** * Post a task to the UI thread to send the TTS "error" event. */ protected void sendErrorEventOnUiThread(final String utteranceId) { ThreadUtils.runOnUiThread(() -> { if (mNativeTtsPlatformImplAndroid != 0) { nativeOnErrorEvent(mNativeTtsPlatformImplAndroid, Integer.parseInt(utteranceId)); } }); } /** * Post a task to the UI thread to send the TTS "start" event. */ protected void sendStartEventOnUiThread(final String utteranceId) { ThreadUtils.runOnUiThread(() -> { if (mNativeTtsPlatformImplAndroid != 0) { nativeOnStartEvent(mNativeTtsPlatformImplAndroid, Integer.parseInt(utteranceId)); } }); } /** * This is overridden by LollipopTtsPlatformImpl because the API changed. */ @SuppressWarnings("deprecation") protected void addOnUtteranceProgressListener() { mTextToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() { @Override public void onDone(final String utteranceId) { sendEndEventOnUiThread(utteranceId); } // This is deprecated in Lollipop and higher but we still need to catch it // on pre-Lollipop builds. @Override @SuppressWarnings("deprecation") public void onError(final String utteranceId) { sendErrorEventOnUiThread(utteranceId); } @Override public void onStart(final String utteranceId) { sendStartEventOnUiThread(utteranceId); } }); } /** * This is overridden by LollipopTtsPlatformImpl because the API changed. */ @SuppressWarnings("deprecation") protected int callSpeak(String text, float volume, int utteranceId) { HashMap<String, String> params = new HashMap<String, String>(); if (volume != 1.0) { params.put(TextToSpeech.Engine.KEY_PARAM_VOLUME, Double.toString(volume)); } params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, Integer.toString(utteranceId)); return mTextToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, params); } /** * Note: we enforce that this method is called on the UI thread, so * we can call nativeVoicesChanged directly. */ private void initialize() { TraceEvent.begin("TtsPlatformImpl:initialize"); new AsyncTask<Void, Void, List<TtsVoice>>() { @Override protected List<TtsVoice> doInBackground(Void... unused) { assert mNativeTtsPlatformImplAndroid != 0; try (TraceEvent te = TraceEvent.scoped("TtsPlatformImpl:initialize.async_task")) { Locale[] locales = Locale.getAvailableLocales(); final List<TtsVoice> voices = new ArrayList<>(); for (Locale locale : locales) { if (!locale.getVariant().isEmpty()) continue; try { if (mTextToSpeech.isLanguageAvailable(locale) > 0) { String name = locale.getDisplayLanguage(); if (!locale.getCountry().isEmpty()) { name += " " + locale.getDisplayCountry(); } TtsVoice voice = new TtsVoice(name, locale.toString()); voices.add(voice); } } catch (Exception e) { // Just skip the locale if it's invalid. // // We used to catch only java.util.MissingResourceException, // but we need to catch more exceptions to work around a bug // in Google TTS when we query "bn". // http://crbug.com/792856 } } return voices; } } @Override protected void onPostExecute(List<TtsVoice> voices) { mVoices = voices; mInitialized = true; nativeVoicesChanged(mNativeTtsPlatformImplAndroid); if (mPendingUtterance != null) mPendingUtterance.speak(); TraceEvent.end("TtsPlatformImpl:initialize"); } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } private native void nativeVoicesChanged(long nativeTtsPlatformImplAndroid); private native void nativeOnEndEvent(long nativeTtsPlatformImplAndroid, int utteranceId); private native void nativeOnStartEvent(long nativeTtsPlatformImplAndroid, int utteranceId); private native void nativeOnErrorEvent(long nativeTtsPlatformImplAndroid, int utteranceId); }
medja/ovs-prirocnik
src/components/plot/plot.js
import React, { Component } from 'react'; import { math, range } from 'core'; import { Surface } from 'components/graphics'; import Grid from './grid'; class Plot extends Component { static defaultProps = { fill: '#bbdefb' }; width = 1000; height = 700; padding = 20; offset = 100; componentWillMount() { this.resize(this.props); this.prepare(this.props); this.update(this.props); } componentWillReceiveProps(props) { this.resize(props); this.prepare(props); this.update(props); } resize({ height }) { if (height) { this.height = height; } } prepare(props) { const { range } = props; const [ min, max ] = range; const { selected = [ min - 1, max + 1 ] } = props; this.compile(props.func); const steps = max - min + 1; const width = this.width / steps; const height = this.height - this.padding - this.offset; this.params = { steps, min, max, width, height, range, selected }; return this.params; } generate(steps, generator) { this.params.scale = 0; const values = Array.from(range(steps), step => { const x = this.position(step); const y = this.func(x); if (y > this.params.scale) { this.params.scale = y; } return generator(step, y); }); return this.scale(values); } scale(values) { return values.map(point => { if (Array.isArray(point[0])) { return this.scale(point); } else { const [ x, y ] = point; const { height, scale } = this.params; return [ x, this.padding + height * (1 - y / scale) ] } }); } compile(func) { if (this.funcSource != func) { const compiled = math.compile(func); this.funcSource = func; this.func = (x) => compiled.eval({ x }); } } getStyle() { const { width } = this.props; let style = {}; if (width) { style.maxWidth = ('' + width).replace(/^(\d+)$/, '$1px'); } return { ...style, ...this.props.style }; } render() { const { range, className } = this.props; const surface = { width: this.width, height: this.height, style: this.getStyle(), className }; const grid = { width: this.width, height: this.height, padding: this.padding, offset: this.offset, discrete: this.discrete, range }; return ( <Surface {...surface}> { this.plot() } <Grid {...grid} /> </Surface> ); } } export default Plot;
DeepDiver1975/msgraph.go
v1.0/WorkbookChartTitleModel.go
// Code generated by msgraph-generate.go DO NOT EDIT. package msgraph // WorkbookChartTitle undocumented type WorkbookChartTitle struct { // Entity is the base model of WorkbookChartTitle Entity // Overlay undocumented Overlay *bool `json:"overlay,omitempty"` // Text undocumented Text *string `json:"text,omitempty"` // Visible undocumented Visible *bool `json:"visible,omitempty"` // Format undocumented Format *WorkbookChartTitleFormat `json:"format,omitempty"` }
PiCaQiuLory/Travel-For-Qinker
AutoSync/src/main/java/com/ss/pojo/OrderApplyExample.java
<gh_stars>0 package com.ss.pojo; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; public class OrderApplyExample implements Serializable{ /** * */ private static final long serialVersionUID = 8641579177993474910L; protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public OrderApplyExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Long> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Long> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andApplyTimeIsNull() { addCriterion("apply_time is null"); return (Criteria) this; } public Criteria andApplyTimeIsNotNull() { addCriterion("apply_time is not null"); return (Criteria) this; } public Criteria andApplyTimeEqualTo(Date value) { addCriterion("apply_time =", value, "applyTime"); return (Criteria) this; } public Criteria andApplyTimeNotEqualTo(Date value) { addCriterion("apply_time <>", value, "applyTime"); return (Criteria) this; } public Criteria andApplyTimeGreaterThan(Date value) { addCriterion("apply_time >", value, "applyTime"); return (Criteria) this; } public Criteria andApplyTimeGreaterThanOrEqualTo(Date value) { addCriterion("apply_time >=", value, "applyTime"); return (Criteria) this; } public Criteria andApplyTimeLessThan(Date value) { addCriterion("apply_time <", value, "applyTime"); return (Criteria) this; } public Criteria andApplyTimeLessThanOrEqualTo(Date value) { addCriterion("apply_time <=", value, "applyTime"); return (Criteria) this; } public Criteria andApplyTimeIn(List<Date> values) { addCriterion("apply_time in", values, "applyTime"); return (Criteria) this; } public Criteria andApplyTimeNotIn(List<Date> values) { addCriterion("apply_time not in", values, "applyTime"); return (Criteria) this; } public Criteria andApplyTimeBetween(Date value1, Date value2) { addCriterion("apply_time between", value1, value2, "applyTime"); return (Criteria) this; } public Criteria andApplyTimeNotBetween(Date value1, Date value2) { addCriterion("apply_time not between", value1, value2, "applyTime"); return (Criteria) this; } public Criteria andTotalIsNull() { addCriterion("total is null"); return (Criteria) this; } public Criteria andTotalIsNotNull() { addCriterion("total is not null"); return (Criteria) this; } public Criteria andTotalEqualTo(BigDecimal value) { addCriterion("total =", value, "total"); return (Criteria) this; } public Criteria andTotalNotEqualTo(BigDecimal value) { addCriterion("total <>", value, "total"); return (Criteria) this; } public Criteria andTotalGreaterThan(BigDecimal value) { addCriterion("total >", value, "total"); return (Criteria) this; } public Criteria andTotalGreaterThanOrEqualTo(BigDecimal value) { addCriterion("total >=", value, "total"); return (Criteria) this; } public Criteria andTotalLessThan(BigDecimal value) { addCriterion("total <", value, "total"); return (Criteria) this; } public Criteria andTotalLessThanOrEqualTo(BigDecimal value) { addCriterion("total <=", value, "total"); return (Criteria) this; } public Criteria andTotalIn(List<BigDecimal> values) { addCriterion("total in", values, "total"); return (Criteria) this; } public Criteria andTotalNotIn(List<BigDecimal> values) { addCriterion("total not in", values, "total"); return (Criteria) this; } public Criteria andTotalBetween(BigDecimal value1, BigDecimal value2) { addCriterion("total between", value1, value2, "total"); return (Criteria) this; } public Criteria andTotalNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("total not between", value1, value2, "total"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(Boolean value) { addCriterion("status =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(Boolean value) { addCriterion("status <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(Boolean value) { addCriterion("status >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(Boolean value) { addCriterion("status >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(Boolean value) { addCriterion("status <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(Boolean value) { addCriterion("status <=", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<Boolean> values) { addCriterion("status in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<Boolean> values) { addCriterion("status not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(Boolean value1, Boolean value2) { addCriterion("status between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(Boolean value1, Boolean value2) { addCriterion("status not between", value1, value2, "status"); return (Criteria) this; } public Criteria andPayTimeIsNull() { addCriterion("pay_time is null"); return (Criteria) this; } public Criteria andPayTimeIsNotNull() { addCriterion("pay_time is not null"); return (Criteria) this; } public Criteria andPayTimeEqualTo(Date value) { addCriterion("pay_time =", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeNotEqualTo(Date value) { addCriterion("pay_time <>", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeGreaterThan(Date value) { addCriterion("pay_time >", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeGreaterThanOrEqualTo(Date value) { addCriterion("pay_time >=", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeLessThan(Date value) { addCriterion("pay_time <", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeLessThanOrEqualTo(Date value) { addCriterion("pay_time <=", value, "payTime"); return (Criteria) this; } public Criteria andPayTimeIn(List<Date> values) { addCriterion("pay_time in", values, "payTime"); return (Criteria) this; } public Criteria andPayTimeNotIn(List<Date> values) { addCriterion("pay_time not in", values, "payTime"); return (Criteria) this; } public Criteria andPayTimeBetween(Date value1, Date value2) { addCriterion("pay_time between", value1, value2, "payTime"); return (Criteria) this; } public Criteria andPayTimeNotBetween(Date value1, Date value2) { addCriterion("pay_time not between", value1, value2, "payTime"); return (Criteria) this; } public Criteria andPayWayIsNull() { addCriterion("pay_way is null"); return (Criteria) this; } public Criteria andPayWayIsNotNull() { addCriterion("pay_way is not null"); return (Criteria) this; } public Criteria andPayWayEqualTo(Boolean value) { addCriterion("pay_way =", value, "payWay"); return (Criteria) this; } public Criteria andPayWayNotEqualTo(Boolean value) { addCriterion("pay_way <>", value, "payWay"); return (Criteria) this; } public Criteria andPayWayGreaterThan(Boolean value) { addCriterion("pay_way >", value, "payWay"); return (Criteria) this; } public Criteria andPayWayGreaterThanOrEqualTo(Boolean value) { addCriterion("pay_way >=", value, "payWay"); return (Criteria) this; } public Criteria andPayWayLessThan(Boolean value) { addCriterion("pay_way <", value, "payWay"); return (Criteria) this; } public Criteria andPayWayLessThanOrEqualTo(Boolean value) { addCriterion("pay_way <=", value, "payWay"); return (Criteria) this; } public Criteria andPayWayIn(List<Boolean> values) { addCriterion("pay_way in", values, "payWay"); return (Criteria) this; } public Criteria andPayWayNotIn(List<Boolean> values) { addCriterion("pay_way not in", values, "payWay"); return (Criteria) this; } public Criteria andPayWayBetween(Boolean value1, Boolean value2) { addCriterion("pay_way between", value1, value2, "payWay"); return (Criteria) this; } public Criteria andPayWayNotBetween(Boolean value1, Boolean value2) { addCriterion("pay_way not between", value1, value2, "payWay"); return (Criteria) this; } public Criteria andPayNumberIsNull() { addCriterion("pay_number is null"); return (Criteria) this; } public Criteria andPayNumberIsNotNull() { addCriterion("pay_number is not null"); return (Criteria) this; } public Criteria andPayNumberEqualTo(String value) { addCriterion("pay_number =", value, "payNumber"); return (Criteria) this; } public Criteria andPayNumberNotEqualTo(String value) { addCriterion("pay_number <>", value, "payNumber"); return (Criteria) this; } public Criteria andPayNumberGreaterThan(String value) { addCriterion("pay_number >", value, "payNumber"); return (Criteria) this; } public Criteria andPayNumberGreaterThanOrEqualTo(String value) { addCriterion("pay_number >=", value, "payNumber"); return (Criteria) this; } public Criteria andPayNumberLessThan(String value) { addCriterion("pay_number <", value, "payNumber"); return (Criteria) this; } public Criteria andPayNumberLessThanOrEqualTo(String value) { addCriterion("pay_number <=", value, "payNumber"); return (Criteria) this; } public Criteria andPayNumberLike(String value) { addCriterion("pay_number like", value, "payNumber"); return (Criteria) this; } public Criteria andPayNumberNotLike(String value) { addCriterion("pay_number not like", value, "payNumber"); return (Criteria) this; } public Criteria andPayNumberIn(List<String> values) { addCriterion("pay_number in", values, "payNumber"); return (Criteria) this; } public Criteria andPayNumberNotIn(List<String> values) { addCriterion("pay_number not in", values, "payNumber"); return (Criteria) this; } public Criteria andPayNumberBetween(String value1, String value2) { addCriterion("pay_number between", value1, value2, "payNumber"); return (Criteria) this; } public Criteria andPayNumberNotBetween(String value1, String value2) { addCriterion("pay_number not between", value1, value2, "payNumber"); return (Criteria) this; } public Criteria andItemIdIsNull() { addCriterion("item_id is null"); return (Criteria) this; } public Criteria andItemIdIsNotNull() { addCriterion("item_id is not null"); return (Criteria) this; } public Criteria andItemIdEqualTo(Integer value) { addCriterion("item_id =", value, "itemId"); return (Criteria) this; } public Criteria andItemIdNotEqualTo(Integer value) { addCriterion("item_id <>", value, "itemId"); return (Criteria) this; } public Criteria andItemIdGreaterThan(Integer value) { addCriterion("item_id >", value, "itemId"); return (Criteria) this; } public Criteria andItemIdGreaterThanOrEqualTo(Integer value) { addCriterion("item_id >=", value, "itemId"); return (Criteria) this; } public Criteria andItemIdLessThan(Integer value) { addCriterion("item_id <", value, "itemId"); return (Criteria) this; } public Criteria andItemIdLessThanOrEqualTo(Integer value) { addCriterion("item_id <=", value, "itemId"); return (Criteria) this; } public Criteria andItemIdIn(List<Integer> values) { addCriterion("item_id in", values, "itemId"); return (Criteria) this; } public Criteria andItemIdNotIn(List<Integer> values) { addCriterion("item_id not in", values, "itemId"); return (Criteria) this; } public Criteria andItemIdBetween(Integer value1, Integer value2) { addCriterion("item_id between", value1, value2, "itemId"); return (Criteria) this; } public Criteria andItemIdNotBetween(Integer value1, Integer value2) { addCriterion("item_id not between", value1, value2, "itemId"); return (Criteria) this; } public Criteria andUserIdIsNull() { addCriterion("user_id is null"); return (Criteria) this; } public Criteria andUserIdIsNotNull() { addCriterion("user_id is not null"); return (Criteria) this; } public Criteria andUserIdEqualTo(Integer value) { addCriterion("user_id =", value, "userId"); return (Criteria) this; } public Criteria andUserIdNotEqualTo(Integer value) { addCriterion("user_id <>", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThan(Integer value) { addCriterion("user_id >", value, "userId"); return (Criteria) this; } public Criteria andUserIdGreaterThanOrEqualTo(Integer value) { addCriterion("user_id >=", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThan(Integer value) { addCriterion("user_id <", value, "userId"); return (Criteria) this; } public Criteria andUserIdLessThanOrEqualTo(Integer value) { addCriterion("user_id <=", value, "userId"); return (Criteria) this; } public Criteria andUserIdIn(List<Integer> values) { addCriterion("user_id in", values, "userId"); return (Criteria) this; } public Criteria andUserIdNotIn(List<Integer> values) { addCriterion("user_id not in", values, "userId"); return (Criteria) this; } public Criteria andUserIdBetween(Integer value1, Integer value2) { addCriterion("user_id between", value1, value2, "userId"); return (Criteria) this; } public Criteria andUserIdNotBetween(Integer value1, Integer value2) { addCriterion("user_id not between", value1, value2, "userId"); return (Criteria) this; } public Criteria andAuditorIdIsNull() { addCriterion("auditor_id is null"); return (Criteria) this; } public Criteria andAuditorIdIsNotNull() { addCriterion("auditor_id is not null"); return (Criteria) this; } public Criteria andAuditorIdEqualTo(Integer value) { addCriterion("auditor_id =", value, "auditorId"); return (Criteria) this; } public Criteria andAuditorIdNotEqualTo(Integer value) { addCriterion("auditor_id <>", value, "auditorId"); return (Criteria) this; } public Criteria andAuditorIdGreaterThan(Integer value) { addCriterion("auditor_id >", value, "auditorId"); return (Criteria) this; } public Criteria andAuditorIdGreaterThanOrEqualTo(Integer value) { addCriterion("auditor_id >=", value, "auditorId"); return (Criteria) this; } public Criteria andAuditorIdLessThan(Integer value) { addCriterion("auditor_id <", value, "auditorId"); return (Criteria) this; } public Criteria andAuditorIdLessThanOrEqualTo(Integer value) { addCriterion("auditor_id <=", value, "auditorId"); return (Criteria) this; } public Criteria andAuditorIdIn(List<Integer> values) { addCriterion("auditor_id in", values, "auditorId"); return (Criteria) this; } public Criteria andAuditorIdNotIn(List<Integer> values) { addCriterion("auditor_id not in", values, "auditorId"); return (Criteria) this; } public Criteria andAuditorIdBetween(Integer value1, Integer value2) { addCriterion("auditor_id between", value1, value2, "auditorId"); return (Criteria) this; } public Criteria andAuditorIdNotBetween(Integer value1, Integer value2) { addCriterion("auditor_id not between", value1, value2, "auditorId"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
SKA-ScienceDataProcessor/rascil
rascil/workflows/shared/__init__.py
<gh_stars>1-10 from .imaging import *
surav6174/Code-With-C
Computer Lab/Lab 6 Source Code/Program02.c
/*Write a program to display the chessboard pattern.*/ /*Importing Header Files*/ #include <stdio.h> #include <conio.h> #include <stdlib.h> int main() { system("cls"); /*Clear the screen*/ printf("\t\tChessBoard\n\n"); /*An information while printing*/ /*Double Loop explained below:*/ for (int i = 0; i < 9; i++) { printf("\t\t"); /*Just make a space so that chessboard comes in middle*/ for (int j = 0; j < 9; j++) { if ((i + j) % 2 == 0) { printf("\xdb"); /*Prints white*/ } else { printf(" "); /*Prints black*/ } } printf("\n"); } getch(); /*Waits till a character is pressed*/ return 0; } /* Double loop: for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { printf("(%d,%d) ",i,j); } printf("\n"); } (0,0) (0,1) (0,2) (0,3) (0,4) (0,5) (0,6) (0,7) (0,8) (1,0) (1,1) (1,2) (1,3) (1,4) (1,5) (1,6) (1,7) (1,8) (2,0) (2,1) (2,2) (2,3) (2,4) (2,5) (2,6) (2,7) (2,8) (3,0) (3,1) (3,2) (3,3) (3,4) (3,5) (3,6) (3,7) (3,8) (4,0) (4,1) (4,2) (4,3) (4,4) (4,5) (4,6) (4,7) (4,8) (5,0) (5,1) (5,2) (5,3) (5,4) (5,5) (5,6) (5,7) (5,8) (6,0) (6,1) (6,2) (6,3) (6,4) (6,5) (6,6) (6,7) (6,8) (7,0) (7,1) (7,2) (7,3) (7,4) (7,5) (7,6) (7,7) (7,8) (8,0) (8,1) (8,2) (8,3) (8,4) (8,5) (8,6) (8,7) (8,8) */ /* In chess board white and black are in alternate order so Taking i+j%2 ==0 as white Taking i+j%2 ==1 as black Inside second for loop: if((i+j)%2==0){ printf("w "); } else{ printf("b "); } w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w b w */ /* We use \xdb for white space so changing "w" to"\xdb" abd we leave space to print blaak so "b" to " " if((i+j)%2==0){ printf("\xdb"); } else{ printf(" "); } █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ */
1337programming/leviathan
nfc/src/DOOM/neo/swf/SWF_Main.cpp
/* =========================================================================== Doom 3 BFG Edition GPL Source Code Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code"). Doom 3 BFG Edition Source Code 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. Doom 3 BFG Edition Source Code 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 Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #pragma hdrstop #include "../idlib/precompiled.h" #include "../renderer/image.h" #pragma warning(disable: 4355) // 'this' : used in base member initializer list idCVar swf_loadBinary( "swf_loadBinary", "1", CVAR_INTEGER, "used to set whether to load binary swf from generated" ); int idSWF::mouseX = -1; int idSWF::mouseY = -1; bool idSWF::isMouseInClientArea = false; extern idCVar in_useJoystick; /* =================== idSWF::idSWF =================== */ idSWF::idSWF( const char * filename_, idSoundWorld * soundWorld_ ) { atlasMaterial = NULL; swfScale = 1.0f; scaleToVirtual.Set( 1.0f, 1.0f ); random.SetSeed( Sys_Milliseconds() ); guiSolid = declManager->FindMaterial( "guiSolid" ); guiCursor_arrow = declManager->FindMaterial( "ui/assets/guicursor_arrow" ); guiCursor_hand = declManager->FindMaterial( "ui/assets/guicursor_hand" ); white = declManager->FindMaterial( "_white" ); tooltipButtonImage.Append( keyButtonImages_t( "<JOY1>", "guis/assets/hud/controller/xb360/a", "guis/assets/hud/controller/ps3/cross", 37, 37, 0 ) ); tooltipButtonImage.Append( keyButtonImages_t( "<JOY2>", "guis/assets/hud/controller/xb360/b", "guis/assets/hud/controller/ps3/circle", 37, 37, 0 ) ); tooltipButtonImage.Append( keyButtonImages_t( "<JOY3>", "guis/assets/hud/controller/xb360/x", "guis/assets/hud/controller/ps3/square", 37, 37, 0 ) ); tooltipButtonImage.Append( keyButtonImages_t( "<JOY4>", "guis/assets/hud/controller/xb360/y", "guis/assets/hud/controller/ps3/triangle", 37, 37, 0 ) ); tooltipButtonImage.Append( keyButtonImages_t( "<JOY_TRIGGER2>", "guis/assets/hud/controller/xb360/rt", "guis/assets/hud/controller/ps3/r2", 64, 52, 0 ) ); tooltipButtonImage.Append( keyButtonImages_t( "<JOY_TRIGGER1>", "guis/assets/hud/controller/xb360/lt", "guis/assets/hud/controller/ps3/l2", 64, 52, 0 ) ); tooltipButtonImage.Append( keyButtonImages_t( "<JOY5>", "guis/assets/hud/controller/xb360/lb", "guis/assets/hud/controller/ps3/l1", 52, 32, 0 ) ); tooltipButtonImage.Append( keyButtonImages_t( "<JOY6>", "guis/assets/hud/controller/xb360/rb", "guis/assets/hud/controller/ps3/r1", 52, 32, 0 ) ); tooltipButtonImage.Append( keyButtonImages_t( "<MOUSE1>", "guis/assets/hud/controller/mouse1", "", 64, 52, 0 ) ); tooltipButtonImage.Append( keyButtonImages_t( "<MOUSE2>", "guis/assets/hud/controller/mouse2", "", 64, 52, 0 ) ); tooltipButtonImage.Append( keyButtonImages_t( "<MOUSE3>", "guis/assets/hud/controller/mouse3", "", 64, 52, 0 ) ); for ( int index = 0; index < tooltipButtonImage.Num(); index++ ) { if ( ( tooltipButtonImage[index].xbImage != NULL ) && ( tooltipButtonImage[index].xbImage[0] != '\0' ) ) { declManager->FindMaterial( tooltipButtonImage[index].xbImage ); } if ( ( tooltipButtonImage[index].psImage != NULL ) && ( tooltipButtonImage[index].psImage[0] != '\0' ) ) { declManager->FindMaterial( tooltipButtonImage[index].psImage ); } } frameWidth = 0; frameHeight = 0; frameRate = 0; lastRenderTime = 0; isActive = false; inhibitControl = false; useInhibtControl = true; crop = false; blackbars = false; paused = false; hasHitObject = false; useMouse = true; mouseEnabled = false; renderBorder = 0; mouseObject = NULL; hoverObject = NULL; soundWorld = NULL; forceNonPCPlatform = false; if ( idStr::Cmpn( filename_, "swf/", 4 ) != 0 ) { // if it doesn't already have swf/ in front of it, add it filename = "swf/"; filename += filename_; } else { filename = filename_; } filename.ToLower(); filename.BackSlashesToSlashes(); filename.SetFileExtension( ".swf" ); timestamp = fileSystem->GetTimestamp( filename ); mainsprite = new (TAG_SWF) idSWFSprite( this ); mainspriteInstance = NULL; idStr binaryFileName = "generated/"; binaryFileName += filename; binaryFileName.SetFileExtension( ".bswf" ); if ( swf_loadBinary.GetBool() ) { ID_TIME_T sourceTime = fileSystem->GetTimestamp( filename ); if ( !LoadBinary( binaryFileName, sourceTime ) ) { if ( LoadSWF( filename ) ) { WriteBinary( binaryFileName ); } } } else { LoadSWF( filename ); } idStr atlasFileName = binaryFileName; atlasFileName.SetFileExtension( ".tga" ); atlasMaterial = declManager->FindMaterial( atlasFileName ); globals = idSWFScriptObject::Alloc(); globals->Set( "_global", globals ); globals->Set( "Object", &scriptFunction_Object ); mainspriteInstance = spriteInstanceAllocator.Alloc(); mainspriteInstance->Init( mainsprite, NULL, 0 ); shortcutKeys = idSWFScriptObject::Alloc(); scriptFunction_shortcutKeys_clear.Bind( this ); scriptFunction_shortcutKeys_clear.Call( shortcutKeys, idSWFParmList() ); globals->Set( "shortcutKeys", shortcutKeys ); globals->Set( "deactivate", scriptFunction_deactivate.Bind( this ) ); globals->Set( "inhibitControl", scriptFunction_inhibitControl.Bind( this ) ); globals->Set( "useInhibit", scriptFunction_useInhibit.Bind( this ) ); globals->Set( "precacheSound", scriptFunction_precacheSound.Bind( this ) ); globals->Set( "playSound", scriptFunction_playSound.Bind( this ) ); globals->Set( "stopSounds",scriptFunction_stopSounds.Bind( this ) ); globals->Set( "getPlatform", scriptFunction_getPlatform.Bind( this ) ); globals->Set( "getTruePlatform", scriptFunction_getTruePlatform.Bind( this ) ); globals->Set( "getLocalString", scriptFunction_getLocalString.Bind( this ) ); globals->Set( "swapPS3Buttons", scriptFunction_swapPS3Buttons.Bind( this ) ); globals->Set( "_root", mainspriteInstance->scriptObject ); globals->Set( "strReplace", scriptFunction_strReplace.Bind( this ) ); globals->Set( "getCVarInteger", scriptFunction_getCVarInteger.Bind( this ) ); globals->Set( "setCVarInteger", scriptFunction_setCVarInteger.Bind( this ) ); globals->Set( "acos", scriptFunction_acos.Bind( this ) ); globals->Set( "cos", scriptFunction_cos.Bind( this ) ); globals->Set( "sin", scriptFunction_sin.Bind( this ) ); globals->Set( "round", scriptFunction_round.Bind( this ) ); globals->Set( "pow", scriptFunction_pow.Bind( this ) ); globals->Set( "sqrt", scriptFunction_sqrt.Bind( this ) ); globals->Set( "abs", scriptFunction_abs.Bind( this ) ); globals->Set( "rand", scriptFunction_rand.Bind( this ) ); globals->Set( "floor", scriptFunction_floor.Bind( this ) ); globals->Set( "ceil", scriptFunction_ceil.Bind( this ) ); globals->Set( "toUpper", scriptFunction_toUpper.Bind( this ) ); globals->SetNative( "platform", swfScriptVar_platform.Bind( &scriptFunction_getPlatform ) ); globals->SetNative( "blackbars", swfScriptVar_blackbars.Bind( this ) ); globals->SetNative( "cropToHeight", swfScriptVar_crop.Bind( this ) ); globals->SetNative( "cropToFit", swfScriptVar_crop.Bind( this ) ); globals->SetNative( "crop", swfScriptVar_crop.Bind( this ) ); // Do this to touch any external references (like sounds) // But disable script warnings because many globals won't have been created yet extern idCVar swf_debug; int debug = swf_debug.GetInteger(); swf_debug.SetInteger( 0 ); mainspriteInstance->Run(); mainspriteInstance->RunActions(); mainspriteInstance->RunTo( 0 ); swf_debug.SetInteger( debug ); if ( mouseX == -1 ) { mouseX = ( frameWidth / 2 ); } if ( mouseY == -1 ) { mouseY = ( frameHeight / 2 ); } soundWorld = soundWorld_; } /* =================== idSWF::~idSWF =================== */ idSWF::~idSWF() { spriteInstanceAllocator.Free( mainspriteInstance ); delete mainsprite; for ( int i = 0 ; i < dictionary.Num() ; i++ ) { if ( dictionary[i].sprite ) { delete dictionary[i].sprite; dictionary[i].sprite = NULL; } if ( dictionary[i].shape ) { delete dictionary[i].shape; dictionary[i].shape = NULL; } if ( dictionary[i].font ) { delete dictionary[i].font; dictionary[i].font = NULL; } if ( dictionary[i].text ) { delete dictionary[i].text; dictionary[i].text = NULL; } if ( dictionary[i].edittext ) { delete dictionary[i].edittext; dictionary[i].edittext = NULL; } } globals->Clear(); tooltipButtonImage.Clear(); globals->Release(); shortcutKeys->Clear(); shortcutKeys->Release(); } /* =================== idSWF::Activate when a SWF is deactivated, it rewinds the timeline back to the start =================== */ void idSWF::Activate( bool b ) { if ( !isActive && b ) { inhibitControl = false; lastRenderTime = Sys_Milliseconds(); mainspriteInstance->FreeDisplayList(); mainspriteInstance->Play(); mainspriteInstance->Run(); mainspriteInstance->RunActions(); } isActive = b; } /* =================== idSWF::InhibitControl =================== */ bool idSWF::InhibitControl() { if ( !IsLoaded() || !IsActive() ) { return false; } return ( inhibitControl && useInhibtControl ); } /* =================== idSWF::PlaySound =================== */ int idSWF::PlaySound( const char * sound, int channel, bool blocking ) { if ( !IsActive() ) { return -1; } if ( soundWorld != NULL ) { return soundWorld->PlayShaderDirectly( sound, channel ); } else { idLib::Warning( "No playing sound world on soundSystem in swf play sound!" ); return -1; } } /* =================== idSWF::PlaySound =================== */ void idSWF::StopSound( int channel ) { if ( soundWorld != NULL ) { soundWorld->PlayShaderDirectly( NULL, channel ); } else { idLib::Warning( "No playing sound world on soundSystem in swf play sound!" ); } } /* =================== idSWF::idSWFScriptFunction_inhibitControl::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_inhibitControl::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { pThis->inhibitControl = parms[0].ToBool(); return idSWFScriptVar(); } /* =================== idSWF::idSWFScriptFunction_inhibitControl::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_useInhibit::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { pThis->useInhibtControl = parms[0].ToBool(); return idSWFScriptVar(); } /* =================== idSWF::idSWFScriptFunction_deactivate::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_deactivate::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { pThis->Activate( false ); return idSWFScriptVar(); } /* =================== idSWF::idSWFScriptFunction_precacheSound::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_precacheSound::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { const idSoundShader * soundShader = declManager->FindSound( parms[0].ToString(), true ); return soundShader->GetName(); } /* =================== idSWF::idSWFScriptFunction_playSound::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_playSound::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { int channel = SCHANNEL_ANY; // specific channel passed in if ( parms.Num() > 1 ) { channel = parms[1].ToInteger(); } pThis->PlaySound( parms[0].ToString(), channel ); return idSWFScriptVar(); } /* =================== idSWF::idSWFScriptFunction_stopSounds::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_stopSounds::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { int channel = SCHANNEL_ANY; if ( parms.Num() == 1 ) { channel = parms[0].ToInteger(); } pThis->StopSound( channel ); return idSWFScriptVar(); } /* ======================== idSWFScriptFunction_GetPlatform::Call ======================== */ idSWFScriptVar idSWF::idSWFScriptFunction_getPlatform::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { return pThis->GetPlatform(); } /* ======================== idSWFScriptFunction_GetPlatform::Call ======================== */ idSWFScriptVar idSWF::idSWFScriptFunction_getTruePlatform::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { return 2; } /* ======================== idSWFScriptFunction_GetPlatform::Call ======================== */ idSWFScriptVar idSWF::idSWFScriptFunction_strReplace::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() != 3 ) { return ""; } idStr str = parms[0].ToString(); idStr repString = parms[1].ToString(); idStr val = parms[2].ToString(); str.Replace( repString, val ); return str; } /* ======================== idSWFScriptFunction_GetPlatform::Call ======================== */ idSWFScriptVar idSWF::idSWFScriptFunction_getLocalString::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() == 0 ) { return idSWFScriptVar(); } idStr val = idLocalization::GetString( parms[0].ToString() ); return val; } /* ======================== idSWF::UseCircleForAccept ======================== */ bool idSWF::UseCircleForAccept() { return false; } /* ======================== idSWF::GetPlatform ======================== */ int idSWF::GetPlatform() { if ( in_useJoystick.GetBool() || forceNonPCPlatform ) { forceNonPCPlatform = false; return 0; } return 2; } /* ======================== idSWFScriptFunction_swapPS3Buttons::Call ======================== */ idSWFScriptVar idSWF::idSWFScriptFunction_swapPS3Buttons::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { return pThis->UseCircleForAccept(); } /* ======================== idSWFScriptFunction_getCVarInteger::Call ======================== */ idSWFScriptVar idSWF::idSWFScriptFunction_getCVarInteger::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { return cvarSystem->GetCVarInteger( parms[0].ToString() ); } /* ======================== idSWFScriptFunction_setCVarInteger::Call ======================== */ idSWFScriptVar idSWF::idSWFScriptFunction_setCVarInteger::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { cvarSystem->SetCVarInteger( parms[0].ToString(), parms[1].ToInteger() ); return idSWFScriptVar(); } /* =================== idSWF::idSWFScriptFunction_acos::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_acos::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() != 1 ) { return idSWFScriptVar(); } return idMath::ACos( parms[0].ToFloat() ); } /* =================== idSWF::idSWFScriptFunction_cos::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_cos::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() != 1 ) { return idSWFScriptVar(); } return idMath::Cos( parms[0].ToFloat() ); } /* =================== idSWF::idSWFScriptFunction_sin::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_sin::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() != 1 ) { return idSWFScriptVar(); } return ( idMath::Sin( parms[0].ToFloat() ) ); } /* =================== idSWF::idSWFScriptFunction_round::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_round::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() != 1 ) { return idSWFScriptVar(); } int value = idMath::Ftoi( parms[0].ToFloat() + 0.5f ); return value; } /* =================== idSWF::idSWFScriptFunction_pow::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_pow::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() != 2 ) { return idSWFScriptVar(); } float value = parms[0].ToFloat(); float power = parms[1].ToFloat(); return ( idMath::Pow( value, power ) ); } /* =================== idSWF::idSWFScriptFunction_pow::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_sqrt::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() != 1 ) { return idSWFScriptVar(); } float value = parms[0].ToFloat(); return ( idMath::Sqrt( value ) ); } /* =================== idSWF::idSWFScriptFunction_abs::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_abs::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() != 1 ) { return idSWFScriptVar(); } float value = idMath::Fabs( parms[0].ToFloat() ); return value; } /* =================== idSWF::idSWFScriptFunction_rand::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_rand::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { float min = 0.0f; float max = 1.0f; switch ( parms.Num() ) { case 0: break; case 1: max = parms[0].ToFloat(); break; default: min = parms[0].ToFloat(); max = parms[1].ToFloat(); break; } return min + pThis->GetRandom().RandomFloat() * ( max - min ); } /* ======================== idSWFScriptFunction_floor::Call ======================== */ idSWFScriptVar idSWF::idSWFScriptFunction_floor::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() != 1 || !parms[0].IsNumeric() ) { idLib::Warning( "Invalid parameters specified for floor" ); return idSWFScriptVar(); } float num = parms[0].ToFloat(); return idSWFScriptVar( idMath::Floor( num ) ); } /* ======================== idSWFScriptFunction_ceil::Call ======================== */ idSWFScriptVar idSWF::idSWFScriptFunction_ceil::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() != 1 || !parms[0].IsNumeric() ) { idLib::Warning( "Invalid parameters specified for ceil" ); return idSWFScriptVar(); } float num = parms[0].ToFloat(); return idSWFScriptVar( idMath::Ceil( num ) ); } /* ======================== idSWFScriptFunction_toUpper::Call ======================== */ idSWFScriptVar idSWF::idSWFScriptFunction_toUpper::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { if ( parms.Num() != 1 || !parms[0].IsString() ) { idLib::Warning( "Invalid parameters specified for toUpper" ); return idSWFScriptVar(); } idStr val = idLocalization::GetString( parms[0].ToString() ); val.ToUpper(); return val; } /* =================== idSWF::idSWFScriptFunction_shortcutKeys_clear::Call =================== */ idSWFScriptVar idSWF::idSWFScriptFunction_shortcutKeys_clear::Call( idSWFScriptObject * thisObject, const idSWFParmList & parms ) { idSWFScriptObject * object = pThis->shortcutKeys; object->Clear(); object->Set( "clear", this ); object->Set( "JOY1", "ENTER" ); object->Set( "JOY2", "BACKSPACE" ); object->Set( "JOY3", "START" ); object->Set( "JOY5", "LB" ); object->Set( "JOY6", "RB" ); object->Set( "JOY9", "START" ); object->Set( "JOY10", "BACKSPACE" ); object->Set( "JOY_DPAD_UP", "UP" ); object->Set( "JOY_DPAD_DOWN", "DOWN" ); object->Set( "JOY_DPAD_LEFT", "LEFT" ); object->Set( "JOY_DPAD_RIGHT", "RIGHT" ); object->Set( "JOY_STICK1_UP", "STICK1_UP" ); object->Set( "JOY_STICK1_DOWN", "STICK1_DOWN" ); object->Set( "JOY_STICK1_LEFT", "STICK1_LEFT" ); object->Set( "JOY_STICK1_RIGHT", "STICK1_RIGHT" ); object->Set( "JOY_STICK2_UP", "STICK2_UP" ); object->Set( "JOY_STICK2_DOWN", "STICK2_DOWN" ); object->Set( "JOY_STICK2_LEFT", "STICK2_LEFT" ); object->Set( "JOY_STICK2_RIGHT", "STICK2_RIGHT" ); object->Set( "KP_ENTER", "ENTER" ); object->Set( "MWHEELDOWN", "MWHEEL_DOWN" ); object->Set( "MWHEELUP", "MWHEEL_UP" ); object->Set( "K_TAB", "TAB" ); // FIXME: I'm an RTARD and didn't realize the keys all have "ARROW" after them object->Set( "LEFTARROW", "LEFT" ); object->Set( "RIGHTARROW", "RIGHT" ); object->Set( "UPARROW", "UP" ); object->Set( "DOWNARROW", "DOWN" ); return idSWFScriptVar(); } idSWFScriptVar idSWF::idSWFScriptNativeVar_blackbars::Get( idSWFScriptObject * object ) { return pThis->blackbars; } void idSWF::idSWFScriptNativeVar_blackbars::Set( idSWFScriptObject * object, const idSWFScriptVar & value ) { pThis->blackbars = value.ToBool(); } idSWFScriptVar idSWF::idSWFScriptNativeVar_crop::Get( idSWFScriptObject * object ) { return pThis->crop; } void idSWF::idSWFScriptNativeVar_crop::Set( idSWFScriptObject * object, const idSWFScriptVar & value ) { pThis->crop = value.ToBool(); }
olsonbrandon/react-native
ReactAndroid/src/main/java/com/facebook/react/devsupport/interfaces/DevBundleDownloadListener.java
<reponame>olsonbrandon/react-native /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.react.devsupport.interfaces; import javax.annotation.Nullable; public interface DevBundleDownloadListener { void onSuccess(); void onProgress(@Nullable String status, @Nullable Integer done, @Nullable Integer total); void onFailure(Exception cause); }
apulis/apulisedge
cloud/pkg/domain/node/types.go
<reponame>apulis/apulisedge // Copyright 2020 Apulis Technology Inc. All rights reserved. package node import ( _ "fmt" ) // node status const ( StatusOnline string = "Online" StatusOffline string = "Offline" StatusNotInstalled string = "NotInstalled" StatusInstalling string = "Installing" StatusDeleting string = "Deleting" ) // node roles const ( EdgeRoleKey string = "node-role.kubernetes.io/edge" AgentRoleKey string = "node-role.kubernetes.io/agent" EdgeRole string = "edge" AgentRole string = "agent" ) const ( TransferCountEach int = 10 ) var CSVSavePath string = "/tmp/apulisedge/upload/nodeBatch" // node types var TypesOfNode = []string{"Raspberrypi 4B", "Atlas 500", "Generic"}
fergy/aplit_linux-5
drivers/net/wireless/realtek/rtlwifi/rtl8723com/main.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright(c) 2009-2014 Realtek Corporation.*/ #include "../wifi.h" #include <linux/module.h> MODULE_AUTHOR("Realtek WlanFAE <<EMAIL>>"); MODULE_AUTHOR("<NAME> <<EMAIL>>"); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Realtek RTL8723AE/RTL8723BE 802.11n PCI wireless common routines");
glvnian/go-atlassian-1
pkg/infra/models/admin_scim_group.go
<reponame>glvnian/go-atlassian-1 package models type SCIMGroupPathScheme struct { Schemas []string `json:"schemas,omitempty"` Operations []*SCIMGroupOperationScheme `json:"Operations,omitempty"` } type SCIMGroupOperationScheme struct { Op string `json:"op,omitempty"` Path string `json:"path,omitempty"` Value []*SCIMGroupOperationValueScheme `json:"value,omitempty"` } type SCIMGroupOperationValueScheme struct { Value string `json:"value,omitempty"` Display string `json:"display,omitempty"` } type ScimGroupPageScheme struct { Schemas []string `json:"schemas,omitempty"` TotalResults int `json:"totalResults,omitempty"` StartIndex int `json:"startIndex,omitempty"` ItemsPerPage int `json:"itemsPerPage,omitempty"` Resources []*ScimGroupScheme `json:"Resources,omitempty"` } type ScimGroupScheme struct { Schemas []string `json:"schemas,omitempty"` ID string `json:"id,omitempty"` ExternalID string `json:"externalId,omitempty"` DisplayName string `json:"displayName,omitempty"` Members []*ScimGroupMemberScheme `json:"members,omitempty"` Meta *ScimMetadata `json:"meta,omitempty"` } type ScimGroupMemberScheme struct { Type string `json:"type,omitempty"` Value string `json:"value,omitempty"` Display string `json:"display,omitempty"` Ref string `json:"$ref,omitempty"` } type ScimMetadata struct { ResourceType string `json:"resourceType,omitempty"` Location string `json:"location,omitempty"` LastModified string `json:"lastModified,omitempty"` Created string `json:"created,omitempty"` }
ID2R/ID2R-API
api-common/src/main/java/dev/id2r/api/common/placeholder/replacer/CharsReplacer.java
package dev.id2r.api.common.placeholder.replacer; import dev.id2r.api.common.placeholder.Placeholder; import java.util.function.Function; public class CharsReplacer implements Replacer { // https://github.com/PlaceholderAPI/PlaceholderAPI/blob/master/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java @Override public String apply(String text, Function<String, Placeholder> lookup) { final char[] chars = text.toCharArray(); final StringBuilder builder = new StringBuilder(); final StringBuilder identifier = new StringBuilder(); final StringBuilder parameter = new StringBuilder(); for (int i = 0; i < chars.length; i++) { char l = chars[i]; if (l == '&' && ++i < chars.length) { final char color = chars[i]; if ("0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(i) > -1) builder.append('\u00A7').append(color); else builder.append(l).append(color); continue; } else if (l == '%') { boolean detect = false; boolean hadSpace = false; boolean hasClosure = false; while (++i < chars.length) { char n = chars[i]; if (n == '%') { hasClosure = true; break; } if (n == ' ' && !detect) { hadSpace = true; break; } if (n != '_') { if (!detect) identifier.append(n); else parameter.append(n); continue; } detect = true; } if (!hasClosure) { builder.append("%").append(identifier); if (detect) { builder.append('_').append(parameter); } if (hadSpace) { builder.append(' '); } } else { final Placeholder placeholder = lookup.apply(identifier.toString()); if (placeholder != null) { builder.append(placeholder.onRequest(parameter.toString())); } else { builder.append("%").append(identifier).append("_").append(parameter).append("%"); } } identifier.setLength(0); parameter.setLength(0); continue; } builder.append(l); } return builder.toString(); } }
11Zero/DemoBCG
BCG/BCGPDragFrameImpl.cpp
//******************************************************************************* // COPYRIGHT NOTES // --------------- // This is a part of BCGControlBar Library Professional Edition // Copyright (C) 1998-2014 BCGSoft Ltd. // All rights reserved. // // This source code can be used, distributed or modified // only under terms and conditions // of the accompanying license agreement. //******************************************************************************* // // BCGPDragFrameImpl.cpp: implementation of the CBCGPDragFrameImpl class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "bcgcbpro.h" #include "BCGPDragFrameImpl.h" #include "BCGPTabbedControlBar.h" #include "BCGPMiniFrameWnd.h" #include "BCGPDockManager.h" #include "BCGGlobals.h" #include "BCGPGlobalUtils.h" #include "BCGPMultiMiniFrameWnd.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif class CBCGPDummyDockingControlBar : public CBCGPDockingControlBar { virtual void DoPaint(CDC* /*pDC*/) {} protected: afx_msg BOOL OnEraseBkgnd(CDC* /*pDC*/) {return FALSE;} DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(CBCGPDummyDockingControlBar, CBCGPDockingControlBar) ON_WM_ERASEBKGND() END_MESSAGE_MAP() static UINT BCGP_DUMMY_WND_ID = (UINT) -2; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CBCGPDragFrameImpl::CBCGPDragFrameImpl() { m_rectDrag.SetRectEmpty (); m_rectExpectedDocked.SetRectEmpty (); m_ptHot.x = m_ptHot.y = 0; m_nOldThikness = globalData.m_nDragFrameThiknessFloat; m_pDraggedWnd = NULL; m_pDockManager = NULL; m_pTargetBar = NULL; m_nInsertedTabID = -1; m_bDockToTab = FALSE; m_pFinalTargetBar = NULL; m_bDragStarted = FALSE; m_bFrameTabDrawn = FALSE; m_pOldTargetBar = NULL; m_pWndDummy = NULL; } CBCGPDragFrameImpl::~CBCGPDragFrameImpl() { if (m_pWndDummy != NULL) { m_pWndDummy->DestroyWindow (); delete m_pWndDummy; } } //--------------------------------------------------------------------------------------// void CBCGPDragFrameImpl::Init (CWnd* pDraggedWnd) { ASSERT_VALID (pDraggedWnd); m_pDraggedWnd = pDraggedWnd; CWnd* pDockSite = NULL; if (m_pDraggedWnd->IsKindOf (RUNTIME_CLASS (CBCGPMiniFrameWnd))) { CBCGPMiniFrameWnd* pMiniFrame = DYNAMIC_DOWNCAST (CBCGPMiniFrameWnd, m_pDraggedWnd); pDockSite = pMiniFrame->GetParent (); } else if (m_pDraggedWnd->IsKindOf (RUNTIME_CLASS (CBCGPControlBar))) { CBCGPControlBar* pBar = DYNAMIC_DOWNCAST (CBCGPControlBar, m_pDraggedWnd); ASSERT_VALID (pBar); CBCGPMiniFrameWnd* pParentMiniFrame = pBar->GetParentMiniFrame (); if (pParentMiniFrame != NULL) { pDockSite = pParentMiniFrame->GetParent (); } else { pDockSite = pBar->GetDockSite (); } } m_pDockManager = globalUtils.GetDockManager (pDockSite); if (globalUtils.m_bDialogApp) { return; } ASSERT(m_pDockManager != NULL); } //--------------------------------------------------------------------------------------// void CBCGPDragFrameImpl::MoveDragFrame (BOOL bForceMove) { ASSERT_VALID (m_pDraggedWnd); m_pFinalTargetBar = NULL; if (m_pDraggedWnd == NULL || m_pDockManager == NULL) { return; } if (m_pWndDummy == NULL) { m_pWndDummy = new CBCGPDummyDockingControlBar; m_pWndDummy->CreateEx (0, _T (""), BCGCBProGetTopLevelFrame (m_pDraggedWnd), CRect (0, 0, 0, 0), FALSE, BCGP_DUMMY_WND_ID, WS_CHILD); } CSize szSencitivity = CBCGPDockingControlBar::GetDragSencitivity (); CPoint ptMouse; GetCursorPos (&ptMouse); CPoint ptOffset = ptMouse - m_ptHot; if (abs (ptOffset.x) < szSencitivity.cx && abs (ptOffset.y) < szSencitivity.cy && m_rectDrag.IsRectEmpty () && !bForceMove) { return; } m_bDragStarted = TRUE; m_pDockManager->LockUpdate (TRUE); CRect rectOld = m_rectExpectedDocked.IsRectEmpty () ? m_rectDrag : m_rectExpectedDocked; BOOL bFirstTime = FALSE; if (m_rectDrag.IsRectEmpty ()) { if (m_pDraggedWnd->IsKindOf (RUNTIME_CLASS (CBCGPMiniFrameWnd))) { m_pDraggedWnd->GetWindowRect (m_rectDrag); } else if (m_pDraggedWnd->IsKindOf (RUNTIME_CLASS (CBCGPControlBar))) { CBCGPControlBar* pBar = DYNAMIC_DOWNCAST (CBCGPControlBar, m_pDraggedWnd); ASSERT_VALID (pBar); m_pDraggedWnd->GetWindowRect (m_rectDrag); // if the bar is docked then the floating rect has to be set to recent floating rect if (pBar->GetParentMiniFrame () == NULL) { m_rectDrag.right = m_rectDrag.left + pBar->m_recentDockInfo.m_rectRecentFloatingRect.Width (); m_rectDrag.bottom = m_rectDrag.top + pBar->m_recentDockInfo.m_rectRecentFloatingRect.Height (); } if (!m_rectDrag.PtInRect (m_ptHot)) { int nOffset = m_rectDrag.left - m_ptHot.x; m_rectDrag.OffsetRect (-nOffset - 5, 0); // offset of mouse pointer // from the drag rect bound } } bFirstTime = TRUE; } BOOL bDrawTab = FALSE; CBCGPDockingControlBar* pOldTargetBar = m_pTargetBar; CRect rectExpected; rectExpected.SetRectEmpty (); CBCGPSmartDockingManager* pSDManager = NULL; BOOL bSDockingIsOn = FALSE; if (m_pDockManager != NULL && (pSDManager = m_pDockManager->GetSDManagerPermanent()) != NULL && pSDManager->IsStarted()) { bSDockingIsOn = TRUE; } m_pDockManager->CalcExpectedDockedRect (m_pDraggedWnd, ptMouse, rectExpected, bDrawTab, &m_pTargetBar); if (pOldTargetBar != NULL && m_nInsertedTabID != -1 && (pOldTargetBar != m_pTargetBar || !bDrawTab)) { RemoveTabPreDocking (pOldTargetBar); bFirstTime = TRUE; } BOOL bCanBeAttached = TRUE; if (m_pDraggedWnd->IsKindOf (RUNTIME_CLASS (CBCGPMiniFrameWnd))) { } else if (m_pDraggedWnd->IsKindOf (RUNTIME_CLASS (CBCGPControlBar))) { CBCGPControlBar* pBar = DYNAMIC_DOWNCAST (CBCGPControlBar, m_pDraggedWnd); bCanBeAttached = pBar->CanBeAttached (); } if (m_pTargetBar != NULL && bCanBeAttached) { CBCGPBaseTabbedBar* pTabbedBar = DYNAMIC_DOWNCAST (CBCGPBaseTabbedBar, m_pTargetBar); if (pTabbedBar != NULL && bDrawTab && (pTabbedBar->GetVisibleTabsNum () > 1 && pTabbedBar->IsHideSingleTab () || pTabbedBar->GetVisibleTabsNum () > 0 && !pTabbedBar->IsHideSingleTab ())) { PlaceTabPreDocking (pTabbedBar, bFirstTime); return; } else if (bDrawTab) { if (m_nInsertedTabID != -1) { return; } if (!bFirstTime) { EndDrawDragFrame (FALSE); } DrawFrameTab (m_pTargetBar, FALSE); m_nInsertedTabID = 1; return; } } m_rectDrag.OffsetRect (ptOffset); m_ptHot = ptMouse; m_rectExpectedDocked = rectExpected; int nNewThickness = m_rectExpectedDocked.IsRectEmpty ()? globalData.m_nDragFrameThiknessFloat : globalData.m_nDragFrameThiknessDock; CRect rectDocked; if (m_rectExpectedDocked.IsRectEmpty ()) { if (!m_rectDrag.PtInRect (ptMouse)) { CPoint ptMiddleRect (m_rectDrag.TopLeft ().x + m_rectDrag.Width () / 2, m_rectDrag.top + 5); CPoint ptOffset = ptMouse - ptMiddleRect; m_rectDrag.OffsetRect (ptOffset); } rectDocked = m_rectDrag; } else { rectDocked = m_rectExpectedDocked; } if (!bSDockingIsOn || !m_rectExpectedDocked.IsRectEmpty ()) { DrawDragFrame (rectOld, rectDocked, bFirstTime, nNewThickness, m_nOldThikness); m_nOldThikness = nNewThickness; } } //--------------------------------------------------------------------------------------// void CBCGPDragFrameImpl::DrawFrameTab (CBCGPDockingControlBar* pTargetBar, BOOL bErase) { CRect rectWnd; pTargetBar->GetWindowRect (rectWnd); CBCGPSmartDockingManager* pSDManager = NULL; BOOL bSDockingIsOn = FALSE; if (m_pDockManager != NULL && (pSDManager = m_pDockManager->GetSDManagerPermanent()) != NULL && pSDManager->IsStarted()) { bSDockingIsOn = TRUE; } int nThikness = globalData.m_nDragFrameThiknessDock; CRect rectSmallTab = rectWnd; // to be changed to tab height if (CBCGPTabbedControlBar::m_bTabsAlwaysTop) { rectWnd.top += globalData.GetTextHeight (); rectSmallTab.bottom = rectSmallTab.top + globalData.GetTextHeight (); rectSmallTab.left += 10; rectSmallTab.right = rectSmallTab.left + 40; } else { rectWnd.bottom -= globalData.GetTextHeight (); rectSmallTab.top = rectSmallTab.bottom - globalData.GetTextHeight (); rectSmallTab.left += 10; rectSmallTab.right = rectSmallTab.left + 40; } if (rectSmallTab.right >= rectWnd.right) { rectSmallTab.right = rectWnd.right - nThikness - 4; } CRect rectEmpty; rectEmpty.SetRectEmpty (); CRect rectLine; if (CBCGPTabbedControlBar::m_bTabsAlwaysTop) { rectLine.SetRect (rectSmallTab.left + nThikness, rectSmallTab.bottom - nThikness, rectSmallTab.right - nThikness, rectSmallTab.bottom + nThikness); } else { rectLine.SetRect (rectSmallTab.left + nThikness, rectSmallTab.top - nThikness, rectSmallTab.right - nThikness, rectSmallTab.top + nThikness); } if (bErase) { if (bSDockingIsOn) { pSDManager->HidePlace (); } else { DrawDragFrame (rectEmpty, rectSmallTab, FALSE, nThikness, nThikness); DrawDragFrame (rectEmpty, rectWnd, FALSE, nThikness, nThikness); DrawDragFrame (rectEmpty, rectLine, FALSE, nThikness, nThikness); m_bFrameTabDrawn = FALSE; } } else { if (bSDockingIsOn) { pSDManager->ShowTabbedPlaceAt (&rectWnd, 10, rectSmallTab.Width(), rectSmallTab.Height()); } else { DrawDragFrame (rectEmpty, rectSmallTab, TRUE, nThikness, nThikness); DrawDragFrame (rectEmpty, rectWnd, TRUE, nThikness, nThikness); DrawDragFrame (rectEmpty, rectLine, TRUE, nThikness, nThikness); m_bFrameTabDrawn = TRUE; } } } //--------------------------------------------------------------------------------------// void CBCGPDragFrameImpl::EndDrawDragFrame (BOOL bClearInternalRects) { if (m_pDockManager == NULL) { return; } BOOL bSDockingIsOn = FALSE; CBCGPSmartDockingManager* pSDManager = NULL; if ((pSDManager = m_pDockManager->GetSDManagerPermanent()) != NULL && pSDManager->IsStarted()) { bSDockingIsOn = TRUE; pSDManager->HidePlace (); } CRect rectEmpty; rectEmpty.SetRectEmpty (); CRect rectDocked = m_rectExpectedDocked.IsRectEmpty () ? m_rectDrag : m_rectExpectedDocked; // do not draw the final frame (meaning - clear) if it was not drawn because of tab if (m_nInsertedTabID == -1) { if (!bSDockingIsOn) { DrawDragFrame (rectEmpty, rectDocked, 0, m_nOldThikness); } } else { m_bDockToTab = TRUE; } if (bClearInternalRects) { RemoveTabPreDocking (); m_rectExpectedDocked.SetRectEmpty (); m_rectDrag.SetRectEmpty (); m_pFinalTargetBar = m_pTargetBar; m_pTargetBar = NULL; } m_bDragStarted = FALSE; ASSERT (m_pDockManager != NULL); if (!bSDockingIsOn) { m_pDockManager->LockUpdate (FALSE); } } //--------------------------------------------------------------------------------------// void CBCGPDragFrameImpl::DrawDragFrame (LPCRECT lpRectOld, LPCRECT lpRectNew, BOOL bFirstTime, int nNewThickness, int nOldThikness) { CWindowDC dc (m_pDraggedWnd->GetDesktopWindow ()); CSize szNewThickness (nNewThickness, nNewThickness); CSize szOldThickness (nOldThikness, nOldThikness); CBCGPSmartDockingManager* pSDManager = NULL; if (m_pDockManager != NULL && (pSDManager = m_pDockManager->GetSDManagerPermanent()) != NULL && pSDManager->IsStarted()) { pSDManager->ShowPlaceAt (lpRectNew); } else { if (bFirstTime) { dc.DrawDragRect (lpRectNew, szNewThickness, NULL, szOldThickness); } else { dc.DrawDragRect (lpRectNew, szNewThickness, lpRectOld, szOldThickness); } } } //****************************************************************************** void CBCGPDragFrameImpl::PlaceTabPreDocking (CBCGPBaseTabbedBar* pTabbedBar, BOOL bFirstTime) { if (m_nInsertedTabID != -1) { return; } if (!bFirstTime) { EndDrawDragFrame (FALSE); } CString strLabel; if (m_pDraggedWnd->IsKindOf (RUNTIME_CLASS (CBCGPMultiMiniFrameWnd))) { CBCGPMultiMiniFrameWnd* pMultiMiniFrame = DYNAMIC_DOWNCAST (CBCGPMultiMiniFrameWnd, m_pDraggedWnd); if (pMultiMiniFrame != NULL) { CWnd* pBar = pMultiMiniFrame->GetFirstVisibleBar (); ASSERT_VALID (pBar); if (pBar != NULL) { pBar->GetWindowText (strLabel); } } } else { m_pDraggedWnd->GetWindowText (strLabel); } if (m_pWndDummy == NULL) { m_pWndDummy = new CBCGPDummyDockingControlBar; m_pWndDummy->CreateEx (0, _T (""), BCGCBProGetTopLevelFrame (m_pDraggedWnd), CRect (0, 0, 0, 0), FALSE, BCGP_DUMMY_WND_ID, WS_CHILD); } pTabbedBar->GetUnderlinedWindow ()->AddTab (m_pWndDummy, strLabel); CBCGPSmartDockingManager* pSDManager = NULL; if ((pSDManager = m_pDockManager->GetSDManagerPermanent()) != NULL && pSDManager->IsStarted()) { m_pDraggedWnd->ShowWindow (SW_HIDE); } m_nInsertedTabID = pTabbedBar->GetUnderlinedWindow ()->GetTabFromHwnd (*m_pWndDummy); m_pOldTargetBar = pTabbedBar; } //****************************************************************************** void CBCGPDragFrameImpl::PlaceTabPreDocking (CWnd* pCBarToPlaceOn) { CBCGPBaseTabbedBar* pTabbedBar = DYNAMIC_DOWNCAST (CBCGPBaseTabbedBar, pCBarToPlaceOn); if (pTabbedBar != NULL && (pTabbedBar->GetVisibleTabsNum () > 1 && pTabbedBar->IsHideSingleTab () || pTabbedBar->GetVisibleTabsNum () > 0 && !pTabbedBar->IsHideSingleTab ())) { m_pTargetBar = pTabbedBar; PlaceTabPreDocking (pTabbedBar, TRUE); return; } else if (m_nInsertedTabID == -1) { CBCGPDockingControlBar* pDockingControlBar = DYNAMIC_DOWNCAST (CBCGPDockingControlBar, pCBarToPlaceOn); if (pDockingControlBar != NULL) { DrawFrameTab (pDockingControlBar, FALSE); m_pTargetBar = pDockingControlBar; m_pOldTargetBar = pDockingControlBar; m_nInsertedTabID = 1; } } } //****************************************************************************** void CBCGPDragFrameImpl::RemoveTabPreDocking (CBCGPDockingControlBar* pOldTargetBar) { if (pOldTargetBar == NULL) { pOldTargetBar = m_pOldTargetBar; } if (pOldTargetBar != NULL && m_nInsertedTabID != -1) { CBCGPBaseTabbedBar* pOldTabbedBar = DYNAMIC_DOWNCAST (CBCGPBaseTabbedBar, pOldTargetBar); if (pOldTabbedBar != NULL && !m_bFrameTabDrawn && m_pWndDummy != NULL && m_pWndDummy->GetSafeHwnd () != NULL) { CBCGPSmartDockingManager* pSDManager = NULL; BOOL bSDockingIsOn = FALSE; if (m_pDockManager != NULL && (pSDManager = m_pDockManager->GetSDManagerPermanent()) != NULL && pSDManager->IsStarted()) { bSDockingIsOn = TRUE; } m_pWndDummy->ShowWindow (SW_HIDE); if (!bSDockingIsOn) { m_pDockManager->LockUpdate (FALSE); } CWnd* pWnd = pOldTabbedBar->GetUnderlinedWindow ()->GetTabWnd (m_nInsertedTabID); if (pWnd == m_pWndDummy) { pOldTabbedBar->GetUnderlinedWindow ()->RemoveTab (m_nInsertedTabID); } if (!bSDockingIsOn) { m_pDockManager->LockUpdate (TRUE); } } else { DrawFrameTab (pOldTargetBar, TRUE); } CBCGPSmartDockingManager* pSDManager = NULL; if ((pSDManager = m_pDockManager->GetSDManagerPermanent()) != NULL && pSDManager->IsStarted()) { m_pDraggedWnd->ShowWindow (SW_SHOW); } } m_nInsertedTabID = -1; m_pOldTargetBar = NULL; } //****************************************************************************** void CBCGPDragFrameImpl::ResetState () { m_ptHot = CPoint (-1, -1); m_rectDrag.SetRectEmpty (); m_rectExpectedDocked.SetRectEmpty (); m_pFinalTargetBar = NULL; m_pOldTargetBar = NULL; m_bDockToTab = FALSE; m_bDragStarted = FALSE; m_nInsertedTabID = -1; }
CommandPost/FinalCutProFrameworks
Headers/Frameworks/LunaKit/LKFeetFramesTimecode-Protocol.h
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Mar 11 2021 20:53:35). // // Copyright (C) 1997-2019 <NAME>. // @protocol LKFeetFramesTimecode - (void)subtractFeet:(long long)arg1 frames:(long long)arg2 quarterFrames:(long long)arg3; - (void)addFeet:(long long)arg1 frames:(long long)arg2 quarterFrames:(long long)arg3; - (void)setFFQuarterFrames:(long long)arg1; - (void)setFFFrames:(long long)arg1; - (void)setFFFeet:(long long)arg1; - (void)getFFFeet:(long long *)arg1 frames:(long long *)arg2 quarterFrames:(long long *)arg3; @end
JasonPollman/jp-utils
test/Protolib.object.max.js
<reponame>JasonPollman/jp-utils (function () { 'use strict'; var expect; if(typeof window === 'object' && window.expect) { expect = window.expect; } else { expect = require('chai').expect; } describe('Protolib.object.max', function () { before(function () { if(typeof window !== 'object' && !Object._) new (require('../'))('_'); }); it('It should return the maximum value in an object or array', function () { expect([1, 4, 7, 5, 99, 1, 2]._.max()).to.equal(99); expect(['a', 'e', 'i', 'q', 'b', 'z']._.max()).to.equal('z'); expect([1, 'a', 4, 'r', 999]._.max()).to.equal(999); expect({ a: 43, b: 123, c: 0 }._.max()).to.equal(123); var data = [ { name: 'foo', value: 1 }, { name: 'bar', value: 2 }, { name: 'baz', value: 3 } ]; var max = data._.max(function (item) { return item.value; }); expect(max).to.eql({ name: 'baz', value: 3 }); data = [ { name: 'foo', value: 2 }, { name: 'bar', value: 3 }, { name: 'baz', value: 1 } ]; max = data._.max(function (item) { return item.value; }); expect(max).to.eql({ name: 'bar', value: 3 }); data = [ { name: 'foo', value: 'a' }, { name: 'bar', value: 'd' }, { name: 'baz', value: 'x' }, { name: 'hello', value: 'z' }, { name: 'world', value: 'b' } ]; max = data._.max(function (item) { return item.value; }); expect(max).to.eql({ name: 'hello', value: 'z' }); data = [ { name: 'foo', value: [1, 2, 3, 4] }, { name: 'bar', value: [1, 2, 3, 4] }, { name: 'baz', value: [1, 2, 3, 4] }, { name: 'hello', value: [1, 2, 3, 4] }, { name: 'world', value: [1, 2, 3, 4] } ]; max = data._.max(function (item) { return item._.max(); }); expect(max).to.eql({ name: 'world', value: [1, 2, 3, 4] }); data = [ { name: 'foo', value: [1, 2, 3, 4] }, { name: 'bar', value: [5, 6, 7, 8] }, { name: 'baz', value: [9, 10, 11, 12] }, { name: 'hello', value: [13, 14, 15, 16] }, { name: 'world', value: [17, 18, 19, 20] } ]; max = data._.max(function (item) { return item._.max(); }); expect(max).to.eql({ name: 'world', value: [17, 18, 19, 20] }); data = [ { name: 'foo', value: 'a' } ]; max = data._.max(function (item) { return item.value; }); expect(max).to.eql({ name: 'foo', value: 'a' }); data = []; max = data._.max(function (item) { return item.value; }); expect(max).to.eql(undefined); }); it('It should simply return the object if not an array or object', function () { expect((5)._.max()).to.equal(5); expect(('string')._.max()).to.equal('string'); expect((true)._.max()).to.equal(true); }); }); }());