repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
bowen0701/python-algorithms-data-structures
lc0678_valid_parenthesis_string.py
<reponame>bowen0701/python-algorithms-data-structures """Leetcode 678. Valid Parenthesis String Medium URL: https://leetcode.com/problems/valid-parenthesis-string/ Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: - Any left parenthesis '(' must have a corresponding right parenthesis ')'. - Any right parenthesis ')' must have a corresponding left parenthesis '('. - Left parenthesis '(' must go before the corresponding right parenthesis ')'. - '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. - An empty string is also valid. Example 1: Input: "()" Output: True Example 2: Input: "(*)" Output: True Example 3: Input: "(*))" Output: True Note: The string size will be in the range [1, 100]. """ class SolutionBruteForce(object): def _enumerate(self, s): """Enumerate s by replacing '*' by '(', '', & ')'.""" s_set = set() queue = [s] while queue: for i in range(len(queue)): si = list(queue.pop()) if si.count('*'): for j, c in enumerate(si): if c == '*': for r in ['(', 'a', ')']: si[j] = r if not si.count('*'): s_set.add(''.join(si)) else: queue.append(''.join(si)) else: s_set.add(''.join(si)) return list(s_set) def _is_valid(self, s): """Check s is valid with parentheses.""" stack = [] for c in s: if c == '(': stack.append('(') elif c == ')': if not stack: return False stack.pop() return not stack def checkValidString(self, s): """ :type s: str :rtype: bool Note: Time Limit Exceeded. Time complexity: O(3^k), where k is the number of '*'s. Space complexity: O(3^k). """ # Edge case. if len(s) == 1: return s == '*' # Enumerate all strings with '*' replaced by, '(', '', ')'. s_list = self._enumerate(s) # Iterate through list to check if there is one valid. for si in s_list: if self._is_valid(si): return True return False class SolutionMinMaxCloseCount(object): def checkValidString(self, s): """ :type s: str :rtype: bool Time complexity: O(n). Space complexity: O(1). """ if len(s) == 1: return s == '*' # Iterate through s to collect expected min/max number of '('. # - max_ncloses treats each '*' as '(', should never be negative. # - min_ncloses treats each '*' as ')'; treat it as '' if < 0. min_ncloses = max_ncloses = 0 for c in s: if c == '(': max_ncloses += 1 min_ncloses += 1 elif c == ')': max_ncloses -= 1 min_ncloses = max(min_ncloses - 1, 0) else: max_ncloses += 1 min_ncloses = max(min_ncloses - 1, 0) if max_ncloses < 0: return False # If min_ncloses > 0, there are not enough ')'. return min_ncloses == 0 def main(): # Output: True s = "()" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) # Output: True s = "(*)" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) # Output: True s = "(*))" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) # Output: False s = "*((" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) # Output: False s = "**((" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) # Output: False s = "()(()(*(())()*)(*)))()))*)((()(*(((()())()))()()*)((*)))()))(*)(()()(((()*()()((()))((*((*)()" print(SolutionBruteForce().checkValidString(s)) print(SolutionMinMaxCloseCount().checkValidString(s)) if __name__ == '__main__': main()
viticm/web-pap
server/World/WorldData/User.inl
<gh_stars>1-10 #ifndef __USER_INL__ #define __USER_INL__ #include "Config.h" // 取得玩家的 UserID ID_t USER::GetUserID() const { return m_UserID; } // 设置玩家的 UserID VOID USER::SetUserID( ID_t id ) { m_UserID = id; } // 取得玩家状态 UINT USER::UserStatus() const { return m_UserStatus; }; // 设置玩家状态 VOID USER::SetUserStatus( UINT uStatus ) { if( uStatus > US_NONE && uStatus < US_SIZE ) { m_UserStatus = uStatus; } else { Assert( FALSE && "uStatus Exception!" ); } } // 取得完整玩家数据 FULLUSERDATA* USER::GetFullUserData() const { return m_pFullUserData; } // 设置完整玩家数据 VOID USER::SetFullUserData( FULLUSERDATA* pData ) { m_pFullUserData = pData; } // 取得玩家的 ServerID ID_t USER::GetServerID() const { if( GetSceneID()<0 ) return INVALID_ID ; return g_Config.SceneID2ServerID(GetSceneID()) ; } // 取得玩家 PlayerID PlayerID_t USER::GetPlayerID() const { return m_PlayerID; } // 设置玩家 PlayerID VOID USER::SetPlayerID( PlayerID_t pid ) { m_PlayerID = pid; } // 取得玩家 GUID GUID_t USER::GetGUID() const { return m_SimpleData.m_GUID; } // 设置玩家 GUID VOID USER::SetGUID( GUID_t guid ) { m_SimpleData.m_GUID = guid; } // 取得玩家 SceneID SceneID_t USER::GetSceneID() const { return m_SceneID; } // 设置玩家 SceneID VOID USER::SetSceneID( SceneID_t SceneID ) { m_SceneID = SceneID; } // 取得玩家 SceneID SceneID_t USER::GetOldSceneID() const { return m_OldSceneID; } // 设置玩家 SceneID VOID USER::SetOldSceneID( SceneID_t SceneID ) { m_OldSceneID = SceneID; } // 得到玩家常用数据 const USER_SIMPLE_DATA* USER::GetUserSimpleData() const { return &m_SimpleData; } // 取得玩家名字 const CHAR* USER::GetName() const { return m_SimpleData.m_Name; } // 设置玩家名字 VOID USER::SetName( const CHAR* szName ) { Assert(szName); strncpy( m_SimpleData.m_Name, szName, sizeof(m_SimpleData.m_Name)-1 ); } // 取得账户名字 const CHAR* USER::GetAccount() const { return m_SimpleData.m_Account; } // 设置账户名字 VOID USER::SetAccount( const CHAR* szName ) { Assert(szName); strncpy( m_SimpleData.m_Account, szName, sizeof(m_SimpleData.m_Account)-1 ); } // 取得官网GUID inline GUID_t USER::GetAccountGUID() const { return m_SimpleData.m_AccountGUID; } // 设置官网GUID inline VOID USER::SetAccountGUID( UINT uAccountGUID ) { m_SimpleData.m_AccountGUID = uAccountGUID; } // 取得玩家性别 UINT USER::GetSex() const { return m_SimpleData.m_uSex; } // 设置玩家性别 VOID USER::SetSex( UINT uSex ) { m_SimpleData.m_uSex = uSex; } // 取得玩家的门派号 INT USER::GetMenpai() const { return m_SimpleData.m_uMenPai; } // 设置玩家的门派号 VOID USER::SetMenpai(INT nMenpai) { m_SimpleData.m_uMenPai = nMenpai; } // 得到玩家等级 INT USER::GetLevel() const { return m_SimpleData.m_nLevel; } // 设置玩家等级 VOID USER::SetLevel(INT nLevel) { m_SimpleData.m_nLevel = nLevel; } // 得到玩家的头像 INT USER::GetPortrait() const { return m_SimpleData.m_nPortrait; } // 设置玩家头像 VOID USER::SetPortrait(INT nPortrait) { m_SimpleData.m_nPortrait = nPortrait; } // 得到脸部模型 UCHAR USER::GetFaceModel() const { return m_SimpleData.m_uFaceMeshID; } // 设置脸部模型 VOID USER::SetFaceModel(UCHAR uFaceMeshID) { m_SimpleData.m_uFaceMeshID = uFaceMeshID; } // 得到头发模型 UCHAR USER::GetHairModel() const { return m_SimpleData.m_uHairMeshID; } // 设置头发模型 VOID USER::SetHairModel(UCHAR uHairMeshID) { m_SimpleData.m_uHairMeshID = uHairMeshID; } // 得到发色 UINT USER::GetHairColor() const { return m_SimpleData.m_uHairColor; } // 设置发色 VOID USER::SetHairColor(UINT uHairColor) { m_SimpleData.m_uHairColor = uHairColor; } // 取得玩家的队伍号 TeamID_t USER::GetTeamID() const { return m_TeamID; } // 设置玩家队伍号 VOID USER::SetTeamID( TeamID_t tid ) { m_TeamID = tid; } // 取得玩家的称号 const CHAR* USER::GetTitle() const { return m_SimpleData.m_szTitle; } // 设置玩家的称号 VOID USER::SetTitle(const CHAR* szTitle) { Assert(szTitle); strncpy( m_SimpleData.m_szTitle, szTitle, MAX_CHARACTER_TITLE-1 ); } // 得到玩家帮会 ID GuildID_t USER::GetGuildID() const { return m_SimpleData.m_GuildID; } // 设置玩家帮会 ID VOID USER::SetGuildID(GuildID_t gid) { m_SimpleData.m_GuildID = gid; } // 得到玩家创建的聊天频道号 ChannelID_t USER::GetChannelID() const { return m_ChannelID; } // 设置玩家创建的聊天频道号 VOID USER::SetChannelID( ChannelID_t cid ) { m_ChannelID = cid; } // 得到用户验证码 UINT USER::GetKey() const { return m_uKey; } // 设置用户验证码 VOID USER::SetKey( UINT uKey ) { m_uKey = uKey; } // 清除帮会数据 VOID USER::CleanUpGuildData() { m_SimpleData.m_GuildID = INVALID_ID; m_GuildData.CleanUp(); } // 清除玩家关系数据 VOID USER::CleanUpRelationData() { m_RelationData.CleanUp(); } // 取得玩家的心情 const CHAR* USER::GetMood() const { return m_RelationData.m_szMood; } // 保存心情 VOID USER::SetMood( const CHAR* szMood ) { Assert( szMood ); strncpy( m_RelationData.m_szMood, szMood, MOOD_DATA_SIZE-1 ); } // 保存设置 VOID USER::SetSettings(USHORT uSettings) { m_RelationData.m_Flag.m_wFlags = uSettings; } // 是否拒绝被加为好友 BOOL USER::IsCannotAddFriend() { return m_RelationData.m_Flag.isSetBit(GSF_CANNOT_ADD_FRIEND); } // 是否拒绝收发邮件 BOOL USER::IsCannotRecvMail() { return m_RelationData.m_Flag.isSetBit(GSF_CANNOT_RECV_MAIL); } // 是否拒绝陌生人的邮件 BOOL USER::IsCannotRecvStrangerMail() { return m_RelationData.m_Flag.isSetBit(GSF_CANNOT_RECV_STRANGER_MAIL); } // 是否拒绝组队申请 BOOL USER::IsRefuseTeamInvite() { return m_RelationData.m_Flag.isSetBit(GSF_REFUSE_TEAM_INVITE); } #endif // __USER_INL__
D-Wolter/JavaScript-Udemy
cursoJava/4 - fundamentos/39NUmber/cuidado_c_numeros.js
<filename>cursoJava/4 - fundamentos/39NUmber/cuidado_c_numeros.js console.log(7 / 0)//7 dividido por zero retorna Infinity console.log('10.6' / 2)// tipagem fraca permite usar string se ela for numerica de equacoes console.log('3' + 2)//32 cuidado a string com mais cocatena console.log('3' - 2)//1 console.log('Show' * 2)//NaN console.log(0.1 + 0.7)//0.7999999999999999 console.log((10.353).toFixed(2))//10.35 console.log((10).toString())//converte em string
malayap47/dummy
lib/commonAPI/coreapi/ext/platform/android/src/com/motorolasolutions/rho/notification/led/LedFactory.java
package com.motorolasolutions.rho.notification.led; import com.rho.notification.led.ILed; import com.rho.notification.led.ILedFactory; import com.rho.notification.led.ILedSingleton; public class LedFactory implements ILedFactory { private LedSingleton singleton; public LedFactory() { LedRhoListener.registerListener(this); } @Override public ILedSingleton getApiSingleton() { if(singleton == null) singleton = new LedSingleton(); return singleton; } @Override public ILed getApiObject(String id) { return singleton.getLed(id); } public void onPause() { if(singleton != null) { singleton.onPause(); } } public void onStop() { if(singleton != null) { singleton.onStop(); } } public void onDestroy() { if(singleton != null) { singleton.onDestroy(); } } }
Vitupero/elections-webui
js/app.js
<reponame>Vitupero/elections-webui import React from 'react'; import ReactDOM from 'react-dom'; import { Router, hashHistory } from 'react-router'; import '../sass/app.scss'; import TopBar from './components/TopBar'; import routes from './routes'; ReactDOM.render( <div> <TopBar /> <div style={{ marginTop: "65px" }}> <Router history={hashHistory} routes={routes} /> </div> </div>, document.getElementById('root') );
yeehanchung/evergreen
src/icons/generated/TextHighlightIcon.js
import React, { memo, forwardRef } from 'react' import Icon from '../src/Icon' const svgPaths16 = [ 'M9 10H2V6h7V4H1c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h8v-2zm4 3h-1V3h1c.55 0 1-.45 1-1s-.45-1-1-1h-1c-.37 0-.7.11-1 .28-.3-.17-.63-.28-1-.28H9c-.55 0-1 .45-1 1s.45 1 1 1h1v10H9c-.55 0-1 .45-1 1s.45 1 1 1h1c.37 0 .7-.11 1-.28.3.17.63.28 1 .28h1c.55 0 1-.45 1-1s-.45-1-1-1zm2-9h-2v2h1v4h-1v2h2c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1z' ] const svgPaths20 = [ 'M16 17c-.55 0-1-.45-1-1V4c0-.55.45-1 1-1s1-.45 1-1-.45-1-1-1c-.77 0-1.47.3-2 .78-.53-.48-1.23-.78-2-.78-.55 0-1 .45-1 1s.45 1 1 1 1 .45 1 1v12c0 .55-.45 1-1 1s-1 .45-1 1 .45 1 1 1c.77 0 1.47-.3 2-.78.53.48 1.23.78 2 .78.55 0 1-.45 1-1s-.45-1-1-1zm-4-4H2V7h10V5H1c-.55 0-1 .45-1 1v8c0 .55.45 1 1 1h11v-2zm7-8h-3v2h2v6h-2v2h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1z' ] export const TextHighlightIcon = memo( forwardRef(function TextHighlightIcon(props, ref) { return <Icon svgPaths16={svgPaths16} svgPaths20={svgPaths20} ref={ref} name="text-highlight" {...props} /> }) )
phatblat/macOSPrivateFrameworks
PrivateFrameworks/PhotosFormats/PFSlowMotionUtilities.h
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "NSObject.h" @interface PFSlowMotionUtilities : NSObject { } + (CDStruct_e83c9415)adjustTimeRange:(CDStruct_e83c9415)arg1 forNewStartTime:(CDStruct_1b6d18a9)arg2 endTime:(CDStruct_1b6d18a9)arg3; + (struct OpaqueAVCFAudioMix *)_createAVCFAudioMixForScaledComposition:(struct OpaqueAVCFAsset *)arg1 timeRangeMapper:(id)arg2 allocator:(struct __CFAllocator *)arg3; + (id)audioMixForScaledComposition:(id)arg1 timeRangeMapper:(id)arg2; + (CDStruct_e83c9415)_timeRangeFromTime:(float)arg1 toTime:(float)arg2; + (struct OpaqueAVCFAudioMixInputParameters *)_createInputParametersForSlowMotionRegionsInTrack:(struct OpaqueAVCFAssetTrack *)arg1 timeRangeMapper:(id)arg2 volume:(float)arg3 allocator:(struct __CFAllocator *)arg4; + (id)_setVolume:(float)arg1 forSlowMotionRegionsInTrack:(id)arg2 timeRangeMapper:(id)arg3; + (id)exportPresetForAsset:(id)arg1 preferredPreset:(id)arg2; + (void)configureExportSession:(id)arg1 forcePreciseConversion:(BOOL)arg2; + (double)_scaleWithinComposition:(id)arg1 compositionCF:(struct OpaqueAVCFAsset *)arg2 fromCursor:(double)arg3 timeStep:(double)arg4 rate:(float)arg5 timeRangeMapper:(id)arg6; + (BOOL)_scaleComposition:(id)arg1 compositionCF:(struct OpaqueAVCFAsset *)arg2 baseDuration:(double)arg3 slowMotionRate:(float)arg4 slowMotionRegions:(id)arg5 forExport:(BOOL)arg6 outTimeRangeMapper:(id *)arg7; + (id)timeRangeMapperForSourceDuration:(double)arg1 slowMotionRate:(float)arg2 slowMotionTimeRange:(CDStruct_e83c9415)arg3 forExport:(BOOL)arg4; + (id)_slowMotionRegionsFromSlowMotionTimeRange:(CDStruct_e83c9415)arg1; + (void)_applyPreferredTransformFromAsset:(struct OpaqueAVCFAsset *)arg1 toComposition:(struct OpaqueAVCFAsset *)arg2; + (struct OpaqueAVCFAsset *)_createScaledAVCFCompositionForAsset:(struct OpaqueAVCFAsset *)arg1 slowMotionRate:(float)arg2 slowMotionTimeRange:(CDStruct_e83c9415)arg3 forExport:(BOOL)arg4 allocator:(struct __CFAllocator *)arg5 outTimeRangeMapper:(id *)arg6 outError:(struct __CFError **)arg7; + (BOOL)scaleAVCFAsset:(struct OpaqueAVCFAsset *)arg1 slowMotionRate:(float)arg2 slowMotionTimeRange:(CDStruct_e83c9415)arg3 forExport:(BOOL)arg4 allocator:(struct __CFAllocator *)arg5 outComposition:(struct OpaqueAVCFAsset **)arg6 outAudioMix:(struct OpaqueAVCFAudioMix **)arg7 outError:(struct __CFError **)arg8; + (id)_scaledCompositionForAsset:(id)arg1 slowMotionRate:(float)arg2 slowMotionTimeRange:(CDStruct_e83c9415)arg3 forExport:(BOOL)arg4 outTimeRangeMapper:(id *)arg5; + (BOOL)_isValidSlowMotionTimeRange:(CDStruct_e83c9415)arg1; + (BOOL)_isValidSlowMotionRate:(float)arg1; + (id)assetFromVideoAsset:(id)arg1 slowMotionRate:(float)arg2 slowMotionTimeRange:(CDStruct_e83c9415)arg3 forExport:(BOOL)arg4 outAudioMix:(id *)arg5 outTimeRangeMapper:(id *)arg6; + (id)slowMotionSourceAssetPropertyKeys; + (int)preferredTimeScale; + (id)sharedConfiguration; @end
freechw/JN5169-for-xiaomi-wireless-switch
sdk/JN-SW-4170/Tools/Eclipse_plugins/Source/com.jennic.zps.configeditor/src/com/jennic/ZPSConfiguration/NodePowerDescriptor.java
/** * (C) Jennic Ltd * * $Id: NodePowerDescriptor.java 78102 2016-03-24 15:35:29Z nxp29741 $ */ package com.jennic.ZPSConfiguration; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Node Power Descriptor</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link com.jennic.ZPSConfiguration.NodePowerDescriptor#isConstantPower <em>Constant Power</em>}</li> * <li>{@link com.jennic.ZPSConfiguration.NodePowerDescriptor#isRechargeableBattery <em>Rechargeable Battery</em>}</li> * <li>{@link com.jennic.ZPSConfiguration.NodePowerDescriptor#isDisposableBattery <em>Disposable Battery</em>}</li> * <li>{@link com.jennic.ZPSConfiguration.NodePowerDescriptor#getDefaultPowerSource <em>Default Power Source</em>}</li> * <li>{@link com.jennic.ZPSConfiguration.NodePowerDescriptor#getDefaultPowerMode <em>Default Power Mode</em>}</li> * </ul> * </p> * * @see com.jennic.ZPSConfiguration.ZPSConfigurationPackage#getNodePowerDescriptor() * @model * @generated */ public interface NodePowerDescriptor extends EObject { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String copyright = "(C) NXP B.V"; /** * Returns the value of the '<em><b>Constant Power</b></em>' attribute. * The default value is <code>"true"</code>. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Constant Power</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Constant Power</em>' attribute. * @see #setConstantPower(boolean) * @see com.jennic.ZPSConfiguration.ZPSConfigurationPackage#getNodePowerDescriptor_ConstantPower() * @model default="true" required="true" * @generated */ boolean isConstantPower(); /** * Sets the value of the '{@link com.jennic.ZPSConfiguration.NodePowerDescriptor#isConstantPower <em>Constant Power</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Constant Power</em>' attribute. * @see #isConstantPower() * @generated */ void setConstantPower(boolean value); /** * Returns the value of the '<em><b>Rechargeable Battery</b></em>' attribute. * The default value is <code>"false"</code>. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Rechargeable Battery</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Rechargeable Battery</em>' attribute. * @see #setRechargeableBattery(boolean) * @see com.jennic.ZPSConfiguration.ZPSConfigurationPackage#getNodePowerDescriptor_RechargeableBattery() * @model default="false" required="true" * @generated */ boolean isRechargeableBattery(); /** * Sets the value of the '{@link com.jennic.ZPSConfiguration.NodePowerDescriptor#isRechargeableBattery <em>Rechargeable Battery</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Rechargeable Battery</em>' attribute. * @see #isRechargeableBattery() * @generated */ void setRechargeableBattery(boolean value); /** * Returns the value of the '<em><b>Disposable Battery</b></em>' attribute. * The default value is <code>"false"</code>. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Disposable Battery</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Disposable Battery</em>' attribute. * @see #setDisposableBattery(boolean) * @see com.jennic.ZPSConfiguration.ZPSConfigurationPackage#getNodePowerDescriptor_DisposableBattery() * @model default="false" required="true" * @generated */ boolean isDisposableBattery(); /** * Sets the value of the '{@link com.jennic.ZPSConfiguration.NodePowerDescriptor#isDisposableBattery <em>Disposable Battery</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Disposable Battery</em>' attribute. * @see #isDisposableBattery() * @generated */ void setDisposableBattery(boolean value); /** * Returns the value of the '<em><b>Default Power Source</b></em>' attribute. * The default value is <code>"Constant Power"</code>. * The literals are from the enumeration {@link com.jennic.ZPSConfiguration.PowerSources}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Default Power Source</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Default Power Source</em>' attribute. * @see com.jennic.ZPSConfiguration.PowerSources * @see #setDefaultPowerSource(PowerSources) * @see com.jennic.ZPSConfiguration.ZPSConfigurationPackage#getNodePowerDescriptor_DefaultPowerSource() * @model default="Constant Power" required="true" * @generated */ PowerSources getDefaultPowerSource(); /** * Sets the value of the '{@link com.jennic.ZPSConfiguration.NodePowerDescriptor#getDefaultPowerSource <em>Default Power Source</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Default Power Source</em>' attribute. * @see com.jennic.ZPSConfiguration.PowerSources * @see #getDefaultPowerSource() * @generated */ void setDefaultPowerSource(PowerSources value); /** * Returns the value of the '<em><b>Default Power Mode</b></em>' attribute. * The default value is <code>"Synchronised with RxOnWhenIdle"</code>. * The literals are from the enumeration {@link com.jennic.ZPSConfiguration.PowerModes}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Default Power Mode</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Default Power Mode</em>' attribute. * @see com.jennic.ZPSConfiguration.PowerModes * @see #setDefaultPowerMode(PowerModes) * @see com.jennic.ZPSConfiguration.ZPSConfigurationPackage#getNodePowerDescriptor_DefaultPowerMode() * @model default="Synchronised with RxOnWhenIdle" required="true" * @generated */ PowerModes getDefaultPowerMode(); /** * Sets the value of the '{@link com.jennic.ZPSConfiguration.NodePowerDescriptor#getDefaultPowerMode <em>Default Power Mode</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Default Power Mode</em>' attribute. * @see com.jennic.ZPSConfiguration.PowerModes * @see #getDefaultPowerMode() * @generated */ void setDefaultPowerMode(PowerModes value); } // NodePowerDescriptor
jepetolee/CRYPTONALYTICS
calcul/percent.py
<filename>calcul/percent.py from numba import jit, njit @jit def cal_varience_percent(x): return [-100 + 100 * float(x[i + 1] / x[i]) for i in range(len(x) - 1)] @jit def varience_percent(a,b): return [-100 + 100 * float(b / a)]
tvdg45/shopping-cart
src/main/java/views/Show_Shopping_Cart_Items_Update.java
<filename>src/main/java/views/Show_Shopping_Cart_Items_Update.java //Author: <NAME> package views; import java.util.ArrayList; import utilities.Find_and_replace; public class Show_Shopping_Cart_Items_Update { public static int shopping_cart_total_quantity; public static ArrayList<String> receipts; public static ArrayList<ArrayList<String>> items_sold; public static String add_item_error_message() { String output = ""; output += "problem adding item"; return output; } public static String item_added_message() { String output = ""; output += "item added"; return output; } public static String change_item_error_message() { String output = ""; output += "problem changing item"; return output; } public static String item_changed_message() { String output = ""; if (shopping_cart_total_quantity > 0) { output += "updated - still has items"; } else { output += "updated - shopping cart empty"; } return output; } public static String show_receipts() { String output = ""; ArrayList find = new ArrayList<>(); ArrayList replace = new ArrayList<>(); find.add("<script"); find.add("<style"); find.add("\""); find.add("'"); find.add("<br />"); find.add("<br>"); find.add("<div>"); find.add("</div>"); replace.add("&lt;script"); replace.add("&lt;style"); replace.add("&quot;"); replace.add("&apos;"); replace.add(" "); replace.add(""); replace.add(""); replace.add(""); output += "["; for (int i = 0; i < receipts.size(); i++) { output += "{\"receipt\": \"" + Find_and_replace.find_and_replace( find, replace, receipts.get(i).replaceAll("[\r\n]+", " ").replaceAll("<", "&lt;").replaceAll(">", "&gt;")) + "\"}, "; } output += "{}]"; return output; } public static String show_items_sold() { String output = ""; ArrayList find = new ArrayList<>(); ArrayList replace = new ArrayList<>(); find.add("<script"); find.add("<style"); find.add("\""); find.add("'"); find.add("<br />"); find.add("<br>"); find.add("<div>"); find.add("</div>"); replace.add("&lt;script"); replace.add("&lt;style"); replace.add("&quot;"); replace.add("&apos;"); replace.add(" "); replace.add(""); replace.add(""); replace.add(""); output += "["; for (int i = 0; i < items_sold.get(0).size(); i++) { output += "{\"item\": \"" + Find_and_replace.find_and_replace( find, replace, items_sold.get(0).get(i).replaceAll("[\r\n]+", " ").replaceAll("<", "&lt;").replaceAll(">", "&gt;")) + "\", \"thumbnail\": \"" + Find_and_replace.find_and_replace( find, replace, items_sold.get(1).get(i).replaceAll("[\r\n]+", " ").replaceAll("<", "&lt;").replaceAll(">", "&gt;")) + "\", \"category\": \"" + Find_and_replace.find_and_replace( find, replace, items_sold.get(2).get(i).replaceAll("[\r\n]+", " ").replaceAll("<", "&lt;").replaceAll(">", "&gt;")) + "\", \"description\": \"" + Find_and_replace.find_and_replace( find, replace, items_sold.get(3).get(i).replaceAll("[\r\n]+", " ")) + "\", \"total_price\": \"" + Find_and_replace.find_and_replace( find, replace, items_sold.get(4).get(i).replaceAll("[\r\n]+", " ").replaceAll("<", "&lt;").replaceAll(">", "&gt;")) + "\", \"receipt_id\": \"" + Find_and_replace.find_and_replace( find, replace, items_sold.get(5).get(i).replaceAll("[\r\n]+", " ").replaceAll("<", "&lt;").replaceAll(">", "&gt;")) + "\"}, "; } output += "{}]"; return output; } }
JGPnet/net.jgp.labs.spark
src/main/java/net/jgp/labs/spark/l090_metadata/l100_join_metadata/AddAuthorsAndBooksMetadataApp.java
package net.jgp.labs.spark.l090_metadata.l100_join_metadata; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.types.StructField; import net.jgp.labs.spark.x.utils.DataframeUtils; import net.jgp.labs.spark.x.utils.FieldUtils; public class AddAuthorsAndBooksMetadataApp { public static void main(String[] args) { AddAuthorsAndBooksMetadataApp app = new AddAuthorsAndBooksMetadataApp(); app.start(); } private void start() { SparkSession spark = SparkSession.builder() .appName("Authors and Books metadata") .master("local[*]").getOrCreate(); String filename = "data/authors.csv"; Dataset<Row> authorsDf = spark.read() .format("csv") .option("inferSchema", true) .option("header", true) .load(filename); authorsDf = DataframeUtils.addMetadata(authorsDf, "x-source", filename); filename = "data/books.csv"; Dataset<Row> booksDf = spark.read() .format("csv") .option("inferSchema", true) .option("header", true) .load(filename); booksDf = DataframeUtils.addMetadata(booksDf, "x-source", filename); Dataset<Row> libraryDf = authorsDf.join(booksDf, authorsDf.col("id") .equalTo(booksDf.col("authorId")), "full_outer"); libraryDf.show(); libraryDf.printSchema(); System.out.println("Output of joining metadata"); System.out.println("--------------------------"); for (StructField field : libraryDf.schema().fields()) { System.out.println(FieldUtils.explain(field)); } } }
zhangtongrui/limax_5.16
java/limax/src/limax/pkix/LmkBundleUtils.java
<filename>java/limax/src/limax/pkix/LmkBundleUtils.java<gh_stars>0 package limax.pkix; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; import java.net.Socket; import java.nio.file.Files; import java.nio.file.Path; import java.security.KeyFactory; import java.security.Principal; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.KeySpec; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPrivateKeySpec; import java.util.Arrays; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509ExtendedKeyManager; import javax.net.ssl.X509TrustManager; import limax.codec.CodecException; import limax.codec.MarshalException; import limax.codec.Octets; import limax.endpoint.LmkBundle; import limax.util.Pair; import limax.util.SecurityUtils; import limax.util.SecurityUtils.PublicKeyAlgorithm; public class LmkBundleUtils { private LmkBundleUtils() { } private static Octets passphrase2Octets(char[] passphrase) { byte[] key = new byte[passphrase.length]; for (int i = 0; i < key.length; i++) key[i] = (byte) passphrase[i]; return Octets.wrap(key); } private static byte[] toDERs(Certificate[] chain) throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); for (Certificate c : chain) os.write(c.getEncoded()); return os.toByteArray(); } private static class LmkBundle_ extends LmkBundle { private LmkBundle_(Path path, char[] passphrase) throws CodecException, MarshalException, IOException { super(Octets.wrap(Files.readAllBytes(path)), passphrase2Octets(passphrase)); } private LmkBundle_(PrivateKey privateKey, byte[] chain) { if (!(privateKey instanceof RSAPrivateKey)) throw new UnsupportedOperationException("RSA only"); if (privateKey instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey k0 = (RSAPrivateCrtKey) privateKey; this.chain = Octets.wrap(chain); this.p = k0.getPrimeP(); this.q = k0.getPrimeQ(); this.exp1 = k0.getPrimeExponentP(); this.exp2 = k0.getPrimeExponentQ(); this.coef = k0.getCrtCoefficient(); } else { RSAPrivateKey k1 = (RSAPrivateKey) privateKey; this.chain = Octets.wrap(chain); this.n = k1.getModulus(); this.d = k1.getPrivateExponent(); } } private Pair<PrivateKey, Certificate[]> extract() throws Exception { Certificate[] certs = CertificateFactory.getInstance("X.509") .generateCertificates(new ByteArrayInputStream(chain.array(), 0, chain.size())) .toArray(new Certificate[0]); BigInteger e = ((RSAPublicKey) certs[0].getPublicKey()).getPublicExponent(); KeySpec keySpec; if (coef == null) keySpec = new RSAPrivateKeySpec(n, d); else { if (n == null) n = p.multiply(q); if (d == null) d = e.modInverse(p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE))); keySpec = new RSAPrivateCrtKeySpec(n, e, d, p, q, exp1, exp2, coef); } return new Pair<>(KeyFactory.getInstance("RSA").generatePrivate(keySpec), certs); } } static void save(Path path, byte[] privateKeyBytes, byte[] certificateChainBytes, char[] passphrase) throws Exception { Files.write(path, new LmkBundle_(PublicKeyAlgorithm.loadPrivateKey(new String(privateKeyBytes), passphrase), toDERs(SecurityUtils.sortCertificateChain(CertificateFactory.getInstance("X.509") .generateCertificates(new ByteArrayInputStream(certificateChainBytes)) .toArray(new Certificate[0])))).save(passphrase2Octets(passphrase)).getBytes(), KeyContainer.options); } static Pair<PrivateKey, Certificate[]> extract(Path path, char[] passphrase) throws Exception { return new LmkBundle_(path, passphrase).extract(); } public static LmkBundle createInstance(PrivateKey privateKey, Certificate[] chain) throws Exception { return new LmkBundle_(privateKey, toDERs(chain)); } public static LmkBundle load(Path path, char[] passphrase) throws CodecException, MarshalException, IOException { return new LmkBundle_(path, passphrase); } public static void renew(Path path, char[] passphrase) throws Exception { Pair<PrivateKey, Certificate[]> pair = LmkBundleUtils.extract(path, passphrase); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(new KeyManager[] { new X509ExtendedKeyManager() { @Override public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) { return "none"; } @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { return "none"; } @Override public X509Certificate[] getCertificateChain(String alias) { return Arrays.stream(pair.getValue()).toArray(X509Certificate[]::new); } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { return new String[] { "none" }; } @Override public PrivateKey getPrivateKey(String alias) { return pair.getKey(); } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { return new String[] { "none" }; } } }, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }, null); Files.write(path, new LmkRequest(null, null) .createContext(SecurityUtils.extractOcspURI((X509Certificate) pair.getValue()[0]).getHost()) .fetch(sslContext).save(passphrase2Octets(passphrase)).getBytes()); } }
saikumar-chilukuri/Actyv-Bootcamp
BootCamp/03-Logger/controllers/index.js
const log = require("log4js").getLogger("index"); indexlog = function(req, res) { log.debug("This is in the first log module"); res.send("I am in first log"); }; secondlog = function(req, res) { log.debug("This is the second log module"); res.send("I am in second log"); }; errorlog = function(req, res) { log.error("This is the error log module"); res.error("I am in error log"); }; module.exports = { indexlog, secondlog, errorlog };
fasterthanlime/ooc-legacy
legacy-src/org/ooc/parsers/StaticBlockParser.java
<reponame>fasterthanlime/ooc-legacy package org.ooc.parsers; import java.io.IOException; import org.ooc.errors.SourceContext; import org.ooc.nodes.others.StaticBlock; import org.ubi.FileLocation; import org.ubi.SourceReader; /** * Static block parser. * * @author <NAME> */ public class StaticBlockParser implements Parser { public boolean parse(final SourceContext context) throws IOException { SourceReader reader = context.reader; FileLocation location = reader.getLocation(); if(reader.matches("static", true) && reader.hasWhitespace(true) && reader.matches("{", true)) { context.open(new StaticBlock(location)); return true; } return false; } }
lechium/iPhoneOS_12.1.1_Headers
System/Library/PrivateFrameworks/AvatarKit.framework/AVTPreset.h
<filename>System/Library/PrivateFrameworks/AvatarKit.framework/AVTPreset.h /* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:50:38 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/AvatarKit.framework/AvatarKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <AvatarKit/AvatarKit-Structs.h> @class NSString, NSArray, NSDictionary, UIImage; @interface AVTPreset : NSObject { long long _category; NSString* _identifier; NSArray* _assets; NSString* _variant; float _intensity; BOOL _mirrored; NSArray* _rigs; NSArray* _params; NSArray* _dependencies; NSDictionary* _tags; NSDictionary* _specializationSettings; } @property (nonatomic,readonly) long long category; @property (nonatomic,readonly) NSString * identifier; @property (nonatomic,readonly) NSString * displayableName; @property (nonatomic,readonly) NSString * localizedName; @property (nonatomic,readonly) UIImage * thumbnail; @property (nonatomic,readonly) BOOL hasComponent; @property (nonatomic,readonly) NSDictionary * tags; //@synthesize tags=_tags - In the implementation block @property (readonly) NSDictionary * specializationSettings; //@synthesize specializationSettings=_specializationSettings - In the implementation block +(id)findPresetWithIdentifier:(id)arg1 inPresets:(id)arg2 ; +(void)registerVariantNamed:(id)arg1 forComponentType:(long long)arg2 ; +(void)loadPresets; +(id)_colorPresetsForCategory:(long long)arg1 palette:(id)arg2 ; +(void)enumerateComponentType:(long long)arg1 variantDependencies:(/*^block*/id)arg2 ; +(id)availablePresetsForCategory:(long long)arg1 ; +(id)presetWithCategory:(long long)arg1 identifier:(id)arg2 ; +(id)colorPresetsForCategory:(long long)arg1 ; +(id)secondaryColorPresetsForCategory:(long long)arg1 ; -(BOOL)hasComponent; -(NSString *)displayableName; -(float)intensity; -(id)assets; -(UIImage*)maskImage; -(NSDictionary *)tags; -(NSDictionary *)specializationSettings; -(void)rebuildSpecializationSettings; -(id)componentPaths; -(BOOL)hasOverride; -(void)enumerateOverrides:(/*^block*/id)arg1 ; -(void)enumerateVariantDependencies:(/*^block*/id)arg1 ; -(void)applyPresetOnAvatar:(id)arg1 ; -(id)cacheWithRenderer:(id)arg1 ; -(id)colorPresets; -(id)init; -(NSString *)identifier; -(id)description; -(NSString *)localizedName; -(id)cache; -(long long)category; -(UIImage *)thumbnail; @end
zwxbest/Demo
demo/src/main/java/com/tuowazi/demo/list/linked/node/Node.java
package com.tuowazi.demo.list.linked.node; /** * User:zhangweixiao * Description: */ public class Node<T> { private T obj; private Node next = null; public Node(T obj) { this.setObj(obj); } public Node<T> getNext() { return next; } public void setNext(Node next) { this.next = next; } public T getObj() { return obj; } public void setObj(T obj) { this.obj = obj; } }
yantarou/midonet
midonet-cluster/src/main/java/org/midonet/cluster/rest_api/conversion/TraceRequestDataConverter.java
/* * Copyright 2015 Midokura SARL * * 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.midonet.cluster.rest_api.conversion; import org.midonet.cluster.rest_api.models.TraceRequest; import static org.midonet.cluster.rest_api.conversion.ConditionDataConverter.makeCondition; public class TraceRequestDataConverter { public static org.midonet.cluster.data.TraceRequest toData(TraceRequest tr) { org.midonet.midolman.rules.Condition c = makeCondition(tr.condition); return new org.midonet.cluster.data.TraceRequest() .setId(tr.id) .setName(tr.name) .setDeviceType(tr.deviceType) .setDeviceId(tr.deviceId) .setCondition(c) .setCreationTimestampMs(tr.creationTimestampMs) .setLimit(tr.limit); } }
tekliner/postgres
vendor/github.com/openshift/origin/pkg/build/builder/sti.go
package builder import ( "bytes" "context" "errors" "fmt" "net/url" "os" "os/exec" "path/filepath" "strings" "time" s2iapi "github.com/openshift/source-to-image/pkg/api" "github.com/openshift/source-to-image/pkg/api/describe" "github.com/openshift/source-to-image/pkg/api/validation" s2ibuild "github.com/openshift/source-to-image/pkg/build" s2i "github.com/openshift/source-to-image/pkg/build/strategies" "github.com/openshift/source-to-image/pkg/docker" s2igit "github.com/openshift/source-to-image/pkg/scm/git" s2iutil "github.com/openshift/source-to-image/pkg/util" buildapiv1 "github.com/openshift/api/build/v1" buildclientv1 "github.com/openshift/client-go/build/clientset/versioned/typed/build/v1" "github.com/openshift/origin/pkg/build/builder/cmd/dockercfg" "github.com/openshift/origin/pkg/build/builder/timing" builderutil "github.com/openshift/origin/pkg/build/builder/util" "github.com/openshift/origin/pkg/build/controller/strategy" buildutil "github.com/openshift/origin/pkg/build/util" "github.com/openshift/origin/pkg/git" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // builderFactory is the internal interface to decouple S2I-specific code from Origin builder code type builderFactory interface { // Create S2I Builder based on S2I configuration Builder(config *s2iapi.Config, overrides s2ibuild.Overrides) (s2ibuild.Builder, s2iapi.BuildInfo, error) } // validator is the interval interface to decouple S2I-specific code from Origin builder code type validator interface { // Perform validation of S2I configuration, returns slice of validation errors ValidateConfig(config *s2iapi.Config) []validation.Error } // runtimeBuilderFactory is the default implementation of stiBuilderFactory type runtimeBuilderFactory struct{} // Builder delegates execution to S2I-specific code func (_ runtimeBuilderFactory) Builder(config *s2iapi.Config, overrides s2ibuild.Overrides) (s2ibuild.Builder, s2iapi.BuildInfo, error) { client, err := docker.NewEngineAPIClient(config.DockerConfig) if err != nil { return nil, s2iapi.BuildInfo{}, err } builder, buildInfo, err := s2i.Strategy(client, config, overrides) return builder, buildInfo, err } // runtimeConfigValidator is the default implementation of stiConfigValidator type runtimeConfigValidator struct{} // ValidateConfig delegates execution to S2I-specific code func (_ runtimeConfigValidator) ValidateConfig(config *s2iapi.Config) []validation.Error { return validation.ValidateConfig(config) } // S2IBuilder performs an STI build given the build object type S2IBuilder struct { builder builderFactory validator validator dockerClient DockerClient dockerSocket string build *buildapiv1.Build client buildclientv1.BuildInterface cgLimits *s2iapi.CGroupLimits } // NewS2IBuilder creates a new STIBuilder instance func NewS2IBuilder(dockerClient DockerClient, dockerSocket string, buildsClient buildclientv1.BuildInterface, build *buildapiv1.Build, cgLimits *s2iapi.CGroupLimits) *S2IBuilder { // delegate to internal implementation passing default implementation of builderFactory and validator return newS2IBuilder(dockerClient, dockerSocket, buildsClient, build, runtimeBuilderFactory{}, runtimeConfigValidator{}, cgLimits) } // newS2IBuilder is the internal factory function to create STIBuilder based on parameters. Used for testing. func newS2IBuilder(dockerClient DockerClient, dockerSocket string, buildsClient buildclientv1.BuildInterface, build *buildapiv1.Build, builder builderFactory, validator validator, cgLimits *s2iapi.CGroupLimits) *S2IBuilder { // just create instance return &S2IBuilder{ builder: builder, validator: validator, dockerClient: dockerClient, dockerSocket: dockerSocket, build: build, client: buildsClient, cgLimits: cgLimits, } } // injectConfigMaps creates an s2i `VolumeSpec` from each provided `ConfigMapBuildSource` func injectConfigMaps(configMaps []buildapiv1.ConfigMapBuildSource) []s2iapi.VolumeSpec { vols := make([]s2iapi.VolumeSpec, len(configMaps)) for i, c := range configMaps { vols[i] = makeVolumeSpec(configMapSource(c), strategy.ConfigMapBuildSourceBaseMountPath) } return vols } // injectSecrets creates an s2i `VolumeSpec` from each provided `SecretBuildSource` func injectSecrets(secrets []buildapiv1.SecretBuildSource) []s2iapi.VolumeSpec { vols := make([]s2iapi.VolumeSpec, len(secrets)) for i, s := range secrets { vols[i] = makeVolumeSpec(secretSource(s), strategy.SecretBuildSourceBaseMountPath) } return vols } func makeVolumeSpec(src localObjectBuildSource, mountPath string) s2iapi.VolumeSpec { glog.V(3).Infof("Injecting build source %q into a build into %q", src.LocalObjectRef().Name, filepath.Clean(src.DestinationPath())) return s2iapi.VolumeSpec{ Source: filepath.Join(mountPath, src.LocalObjectRef().Name), Destination: src.DestinationPath(), Keep: !src.IsSecret(), } } // Build executes S2I build based on configured builder, S2I builder factory // and S2I config validator func (s *S2IBuilder) Build() error { var err error ctx := timing.NewContext(context.Background()) defer func() { s.build.Status.Stages = timing.AppendStageAndStepInfo(s.build.Status.Stages, timing.GetStages(ctx)) HandleBuildStatusUpdate(s.build, s.client, nil) }() if s.build.Spec.Strategy.SourceStrategy == nil { return errors.New("the source to image builder must be used with the source strategy") } var push bool // if there is no output target, set one up so the docker build logic // (which requires a tag) will still work, but we won't push it at the end. if s.build.Spec.Output.To == nil || len(s.build.Spec.Output.To.Name) == 0 { s.build.Status.OutputDockerImageReference = s.build.Name } else { push = true } pushTag := s.build.Status.OutputDockerImageReference sourceInfo, err := readSourceInfo() if err != nil { return fmt.Errorf("error reading git source info: %v", err) } var s2iSourceInfo *s2igit.SourceInfo if sourceInfo != nil { s2iSourceInfo = toS2ISourceInfo(sourceInfo) } injections := s2iapi.VolumeList{} injections = append(injections, injectSecrets(s.build.Spec.Source.Secrets)...) injections = append(injections, injectConfigMaps(s.build.Spec.Source.ConfigMaps)...) buildTag := randomBuildTag(s.build.Namespace, s.build.Name) scriptDownloadProxyConfig, err := scriptProxyConfig(s.build) if err != nil { return err } if scriptDownloadProxyConfig != nil { glog.V(0).Infof("Using HTTP proxy %v and HTTPS proxy %v for script download", buildutil.SafeForLoggingURL(scriptDownloadProxyConfig.HTTPProxy), buildutil.SafeForLoggingURL(scriptDownloadProxyConfig.HTTPSProxy), ) } var incremental bool if s.build.Spec.Strategy.SourceStrategy.Incremental != nil { incremental = *s.build.Spec.Strategy.SourceStrategy.Incremental } srcDir := buildutil.InputContentPath contextDir := "" if len(s.build.Spec.Source.ContextDir) != 0 { contextDir = filepath.Clean(s.build.Spec.Source.ContextDir) if contextDir == "." || contextDir == "/" { contextDir = "" } } networkMode, resolvConfHostPath, err := getContainerNetworkConfig() if err != nil { return err } config := &s2iapi.Config{ // Save some processing time by not cleaning up (the container will go away anyway) PreserveWorkingDir: true, WorkingDir: "/tmp", DockerConfig: &s2iapi.DockerConfig{Endpoint: s.dockerSocket}, DockerCfgPath: os.Getenv(dockercfg.PullAuthType), LabelNamespace: builderutil.DefaultDockerLabelNamespace, ScriptsURL: s.build.Spec.Strategy.SourceStrategy.Scripts, BuilderImage: s.build.Spec.Strategy.SourceStrategy.From.Name, Incremental: incremental, IncrementalFromTag: pushTag, Environment: buildEnvVars(s.build, sourceInfo), Labels: s2iBuildLabels(s.build, sourceInfo), DockerNetworkMode: s2iapi.DockerNetworkMode(networkMode), Source: &s2igit.URL{URL: url.URL{Path: srcDir}, Type: s2igit.URLTypeLocal}, ContextDir: contextDir, SourceInfo: s2iSourceInfo, ForceCopy: true, Injections: injections, Tag: buildTag, CGroupLimits: s.cgLimits, ScriptDownloadProxyConfig: scriptDownloadProxyConfig, BlockOnBuild: true, } if len(resolvConfHostPath) != 0 { cmd := exec.Command("chcon", "system_u:object_r:svirt_sandbox_file_t:s0", "/etc/resolv.conf") err := cmd.Run() if err != nil { return fmt.Errorf("unable to set permissions on /etc/resolv.conf: %v", err) } config.BuildVolumes = []string{fmt.Sprintf("%s:/etc/resolv.conf", resolvConfHostPath)} } if s.build.Spec.Strategy.SourceStrategy.ForcePull { glog.V(4).Infof("With force pull true, setting policies to %s", s2iapi.PullAlways) config.BuilderPullPolicy = s2iapi.PullAlways } else { glog.V(4).Infof("With force pull false, setting policies to %s", s2iapi.PullIfNotPresent) config.BuilderPullPolicy = s2iapi.PullIfNotPresent } config.PreviousImagePullPolicy = s2iapi.PullAlways allowedUIDs := os.Getenv(builderutil.AllowedUIDs) glog.V(4).Infof("The value of %s is [%s]", builderutil.AllowedUIDs, allowedUIDs) if len(allowedUIDs) > 0 { err = config.AllowedUIDs.Set(allowedUIDs) if err != nil { return err } } dropCaps := os.Getenv(builderutil.DropCapabilities) glog.V(4).Infof("The value of %s is [%s]", builderutil.DropCapabilities, dropCaps) if len(dropCaps) > 0 { config.DropCapabilities = strings.Split(dropCaps, ",") } // If DockerCfgPath is provided in buildapiv1.Config, then attempt to read the // dockercfg file and get the authentication for pulling the builder image. t, _ := dockercfg.NewHelper().GetDockerAuth(config.BuilderImage, dockercfg.PullAuthType) config.PullAuthentication = s2iapi.AuthConfig{Username: t.Username, Password: <PASSWORD>, Email: t.Email, ServerAddress: t.ServerAddress} t, _ = dockercfg.NewHelper().GetDockerAuth(pushTag, dockercfg.PushAuthType) config.IncrementalAuthentication = s2iapi.AuthConfig{Username: t.Username, Password: <PASSWORD>, Email: t.Email, ServerAddress: t.ServerAddress} if errs := s.validator.ValidateConfig(config); len(errs) != 0 { var buffer bytes.Buffer for _, ve := range errs { buffer.WriteString(ve.Error()) buffer.WriteString(", ") } return errors.New(buffer.String()) } client, err := docker.NewEngineAPIClient(config.DockerConfig) if err != nil { return err } if glog.Is(4) { redactedConfig := SafeForLoggingS2IConfig(config) glog.V(4).Infof("Creating a new S2I builder with config: %#v\n", describe.Config(client, redactedConfig)) } builder, buildInfo, err := s.builder.Builder(config, s2ibuild.Overrides{Downloader: nil}) if err != nil { s.build.Status.Phase = buildapiv1.BuildPhaseFailed s.build.Status.Reason, s.build.Status.Message = convertS2IFailureType( buildInfo.FailureReason.Reason, buildInfo.FailureReason.Message, ) HandleBuildStatusUpdate(s.build, s.client, nil) return err } glog.V(4).Infof("Starting S2I build from %s/%s BuildConfig ...", s.build.Namespace, s.build.Name) startTime := metav1.Now() result, err := builder.Build(config) for _, stage := range result.BuildInfo.Stages { for _, step := range stage.Steps { timing.RecordNewStep(ctx, buildapiv1.StageName(stage.Name), buildapiv1.StepName(step.Name), metav1.NewTime(step.StartTime), metav1.NewTime(step.StartTime.Add(time.Duration(step.DurationMilliseconds)*time.Millisecond))) } } if err != nil { s.build.Status.Phase = buildapiv1.BuildPhaseFailed s.build.Status.Reason, s.build.Status.Message = convertS2IFailureType( result.BuildInfo.FailureReason.Reason, result.BuildInfo.FailureReason.Message, ) HandleBuildStatusUpdate(s.build, s.client, nil) return err } cName := containerName("s2i", s.build.Name, s.build.Namespace, "post-commit") err = execPostCommitHook(ctx, s.dockerClient, s.build.Spec.PostCommit, buildTag, cName) if err != nil { s.build.Status.Phase = buildapiv1.BuildPhaseFailed s.build.Status.Reason = buildapiv1.StatusReasonPostCommitHookFailed s.build.Status.Message = builderutil.StatusMessagePostCommitHookFailed HandleBuildStatusUpdate(s.build, s.client, nil) return err } if push { if err = tagImage(s.dockerClient, buildTag, pushTag); err != nil { return err } } if err = removeImage(s.dockerClient, buildTag); err != nil { glog.V(0).Infof("warning: Failed to remove temporary build tag %v: %v", buildTag, err) } if push { // Get the Docker push authentication pushAuthConfig, authPresent := dockercfg.NewHelper().GetDockerAuth( pushTag, dockercfg.PushAuthType, ) if authPresent { glog.V(3).Infof("Using provided push secret for pushing %s image", pushTag) } else { glog.V(3).Infof("No push secret provided") } glog.V(0).Infof("\nPushing image %s ...", pushTag) startTime = metav1.Now() digest, err := pushImage(s.dockerClient, pushTag, pushAuthConfig) timing.RecordNewStep(ctx, buildapiv1.StagePushImage, buildapiv1.StepPushImage, startTime, metav1.Now()) if err != nil { s.build.Status.Phase = buildapiv1.BuildPhaseFailed s.build.Status.Reason = buildapiv1.StatusReasonPushImageToRegistryFailed s.build.Status.Message = builderutil.StatusMessagePushImageToRegistryFailed HandleBuildStatusUpdate(s.build, s.client, nil) return reportPushFailure(err, authPresent, pushAuthConfig) } if len(digest) > 0 { s.build.Status.Output.To = &buildapiv1.BuildStatusOutputTo{ ImageDigest: digest, } HandleBuildStatusUpdate(s.build, s.client, nil) } glog.V(0).Infof("Push successful") } return nil } // buildEnvVars returns a map with build metadata to be inserted into Docker // images produced by build. It transforms the output from buildInfo into the // input format expected by s2iapi.Config.Environment. // Note that using a map has at least two downsides: // 1. The order of metadata KeyValue pairs is lost; // 2. In case of repeated Keys, the last Value takes precedence right here, // instead of deferring what to do with repeated environment variables to the // Docker runtime. func buildEnvVars(build *buildapiv1.Build, sourceInfo *git.SourceInfo) s2iapi.EnvironmentList { bi := buildInfo(build, sourceInfo) envVars := &s2iapi.EnvironmentList{} for _, item := range bi { envVars.Set(fmt.Sprintf("%s=%s", item.Key, item.Value)) } return *envVars } // s2iBuildLabels returns a slice of KeyValue pairs in a format that appendLabel can // consume. func s2iBuildLabels(build *buildapiv1.Build, sourceInfo *git.SourceInfo) map[string]string { labels := map[string]string{} if sourceInfo == nil { sourceInfo = &git.SourceInfo{} } if len(build.Spec.Source.ContextDir) > 0 { sourceInfo.ContextDir = build.Spec.Source.ContextDir } labels = s2iutil.GenerateLabelsFromSourceInfo(labels, toS2ISourceInfo(sourceInfo), builderutil.DefaultDockerLabelNamespace) if build != nil && build.Spec.Source.Git != nil && build.Spec.Source.Git.Ref != "" { // override the io.openshift.build.commit.ref label to match what we // were originally told to check out, as well as the // OPENSHIFT_BUILD_REFERENCE environment variable. This can sometimes // differ from git's view (see PotentialPRRetryAsFetch for details). labels[builderutil.DefaultDockerLabelNamespace+"build.commit.ref"] = build.Spec.Source.Git.Ref } // override autogenerated labels for _, lbl := range build.Spec.Output.ImageLabels { labels[lbl.Name] = lbl.Value } return labels } // scriptProxyConfig determines a proxy configuration for downloading // scripts from a URL. For now, it uses environment variables passed in // the strategy's environment. There is no preference given to either lowercase // or uppercase form of the variable. func scriptProxyConfig(build *buildapiv1.Build) (*s2iapi.ProxyConfig, error) { httpProxy := "" httpsProxy := "" for _, env := range build.Spec.Strategy.SourceStrategy.Env { switch env.Name { case "HTTP_PROXY", "http_proxy": httpProxy = env.Value case "HTTPS_PROXY", "https_proxy": httpsProxy = env.Value } } if len(httpProxy) == 0 && len(httpsProxy) == 0 { return nil, nil } config := &s2iapi.ProxyConfig{} if len(httpProxy) > 0 { proxyURL, err := buildutil.ParseProxyURL(httpProxy) if err != nil { return nil, err } config.HTTPProxy = proxyURL } if len(httpsProxy) > 0 { proxyURL, err := buildutil.ParseProxyURL(httpsProxy) if err != nil { return nil, err } config.HTTPSProxy = proxyURL } return config, nil } // copyToVolumeList copies the artifacts set in the build config to the // VolumeList struct in the s2iapi.Config func copyToVolumeList(artifactsMapping []buildapiv1.ImageSourcePath) (volumeList s2iapi.VolumeList) { for _, mappedPath := range artifactsMapping { volumeList = append(volumeList, s2iapi.VolumeSpec{ Source: mappedPath.SourcePath, Destination: mappedPath.DestinationDir, }) } return } func convertS2IFailureType(reason s2iapi.StepFailureReason, message s2iapi.StepFailureMessage) (buildapiv1.StatusReason, string) { return buildapiv1.StatusReason(reason), string(message) }
codelynx/sdl_ios
SmartDeviceLink/public/SDLAppHMIType.h
<filename>SmartDeviceLink/public/SDLAppHMIType.h // SDLAppHMIType.h // #import "SDLEnum.h" /** * Enumeration listing possible app hmi types. * * @since SDL 2.0 */ typedef SDLEnum SDLAppHMIType NS_TYPED_ENUM; /** * The App will have default rights. */ extern SDLAppHMIType const SDLAppHMITypeDefault; /** * Communication type of App */ extern SDLAppHMIType const SDLAppHMITypeCommunication; /** * App dealing with Media */ extern SDLAppHMIType const SDLAppHMITypeMedia; /** * Messaging App */ extern SDLAppHMIType const SDLAppHMITypeMessaging; /** * Navigation App */ extern SDLAppHMIType const SDLAppHMITypeNavigation; /** * Information App */ extern SDLAppHMIType const SDLAppHMITypeInformation; /** * App dealing with social media */ extern SDLAppHMIType const SDLAppHMITypeSocial; /** * App dealing with Mobile Projection applications */ extern SDLAppHMIType const SDLAppHMITypeProjection; /** * App designed for use in the background */ extern SDLAppHMIType const SDLAppHMITypeBackgroundProcess; /** * App only for Testing purposes */ extern SDLAppHMIType const SDLAppHMITypeTesting; /** * System App */ extern SDLAppHMIType const SDLAppHMITypeSystem; /** * Remote control */ extern SDLAppHMIType const SDLAppHMITypeRemoteControl; /** * WebEngine Projection mode * * @since 7.0 */ extern SDLAppHMIType const SDLAppHMITypeWebView;
VictorAdad/sigi-api-adad
app/models/Usuario/Usuario.java
<gh_stars>0 package models; import java.util.Objects; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.ManyToMany; import javax.persistence.Column; import javax.persistence.JoinTable; import javax.persistence.JoinColumn; import play.data.validation.Constraints; @Entity public class Usuario extends BaseModel { @Constraints.Required(groups = SaveStep.class) @Column(columnDefinition="Varchar2(100 Char)") public String nombre; @Constraints.Required(groups = SaveStep.class) @Column(columnDefinition="Varchar2(100 Char)") public String paterno; @Column(columnDefinition="Varchar2(100 Char)") public String materno; @Column(columnDefinition="Varchar2(12 Char)") public String contrasenia; @Constraints.Required(groups = SaveStep.class) @Column(columnDefinition="Varchar2(20 Char)") public String username; @Constraints.Required(groups = SaveStep.class) @Column(columnDefinition="Varchar2(20 Char)") public String numContacto; @Constraints.Required(groups = SaveStep.class) @Column(columnDefinition="Varchar2(40 Char)") public String email; @Column(columnDefinition="Varchar2(30 Char)") public String numGafete; @Column(columnDefinition="Varchar2(50 Char)") public String cargo; @Column(columnDefinition="NUMBER(1,0) default 0") public boolean inhabilitar; @Constraints.Required(groups = SaveStep.class) @ManyToOne public Sexo sexo; @ManyToOne public Distrito distrito; @ManyToOne public Fiscalia fiscalia; @ManyToOne public Agencia agencia; @ManyToOne public Subdireccion subdireccion; @ManyToOne public Base base; @ManyToOne public Municipio municipio; @Constraints.Required(groups = SaveStep.class) @ManyToOne public Turno turno; @ManyToMany @JoinTable(name="UsuarioRol", joinColumns=@JoinColumn(name="usuario",referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name="rol", referencedColumnName="id")) public List<Rol> roles; @Override public int hashCode() { int hash = 3; hash = 232 * hash + Objects.hashCode(this.nombre); hash = 232 * hash + Objects.hashCode(this.paterno); hash = 232 * hash + Objects.hashCode(this.materno); hash = 232 * hash + Objects.hashCode(this.contrasenia); hash = 232 * hash + Objects.hashCode(this.username); hash = 232 * hash + Objects.hashCode(this.numContacto); hash = 232 * hash + Objects.hashCode(this.turno); hash = 232 * hash + Objects.hashCode(this.email); hash = 232 * hash + Objects.hashCode(this.numGafete); hash = 232 * hash + Objects.hashCode(this.cargo); hash = 232 * hash + Objects.hashCode(this.inhabilitar); hash = 232 * hash + Objects.hashCode(this.sexo); hash = 232 * hash + Objects.hashCode(this.distrito); hash = 232 * hash + Objects.hashCode(this.fiscalia); hash = 232 * hash + Objects.hashCode(this.agencia); hash = 232 * hash + Objects.hashCode(this.subdireccion); hash = 232 * hash + Objects.hashCode(this.base); hash = 232 * hash + Objects.hashCode(this.municipio); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Usuario other = (Usuario) obj; return ( !Objects.equals(this.nombre, other.nombre) || !Objects.equals(this.paterno, other.paterno) || !Objects.equals(this.materno, other.materno) || !Objects.equals(this.contrasenia, other.contrasenia) || !Objects.equals(this.username, other.username) || !Objects.equals(this.numContacto, other.numContacto) || !Objects.equals(this.turno, other.turno) || !Objects.equals(this.email, other.email) || !Objects.equals(this.numGafete, other.numGafete) || !Objects.equals(this.cargo, other.cargo) || !Objects.equals(this.inhabilitar, other.inhabilitar) || !Objects.equals(this.sexo, other.sexo) || !Objects.equals(this.distrito, other.distrito) || !Objects.equals(this.fiscalia, other.fiscalia) || !Objects.equals(this.agencia, other.agencia) || !Objects.equals(this.subdireccion, other.subdireccion) || !Objects.equals(this.base, other.base) || !Objects.equals(this.municipio, other.municipio) ) ? false : true; } }
BIBSYSDEV/nva-commons
core/src/main/java/nva/commons/core/attempt/ConsumerWithException.java
<gh_stars>0 package nva.commons.core.attempt; @FunctionalInterface public interface ConsumerWithException<T, E extends Exception> { void consume(T t) throws E; }
ycj123/Research-Project
proFL-plugin-2.0.3/groovy/util/CliBuilder$_expandArgumentFile_closure3_closure4.java
<filename>proFL-plugin-2.0.3/groovy/util/CliBuilder$_expandArgumentFile_closure3_closure4.java // // Decompiled by Procyon v0.5.36 // package groovy.util; import org.codehaus.groovy.runtime.callsite.CallSiteArray; import groovy.lang.MetaClass; import org.codehaus.groovy.runtime.callsite.CallSite; import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; import groovy.lang.GroovyObject; import java.lang.ref.SoftReference; import org.codehaus.groovy.reflection.ClassInfo; import groovy.lang.Reference; import org.codehaus.groovy.runtime.GeneratedClosure; import groovy.lang.Closure; class CliBuilder$_expandArgumentFile_closure3_closure4 extends Closure implements GeneratedClosure { private Reference<Object> args; private Reference<Object> charAsInt; private static final /* synthetic */ Integer $const$0; private static final /* synthetic */ Integer $const$1; private static /* synthetic */ SoftReference $callSiteArray; private static /* synthetic */ Class $class$java$lang$Object; private static /* synthetic */ Class $class$java$io$StreamTokenizer; public CliBuilder$_expandArgumentFile_closure3_closure4(final Object _outerInstance, final Object _thisObject, final Reference<Object> args, final Reference<Object> charAsInt) { final Reference args2 = new Reference((T)args); final Reference charAsInt2 = new Reference((T)charAsInt); $getCallSiteArray(); super(_outerInstance, _thisObject); this.args = args2.get(); this.charAsInt = charAsInt2.get(); } public Object doCall(final Object it) { final CallSite[] $getCallSiteArray = $getCallSiteArray(); $getCallSiteArray[0].callCurrent(this); $getCallSiteArray[1].callCurrent(this, $getCallSiteArray[2].call(this.charAsInt.get(), " "), CliBuilder$_expandArgumentFile_closure3_closure4.$const$0); $getCallSiteArray[3].callCurrent(this, CliBuilder$_expandArgumentFile_closure3_closure4.$const$1, $getCallSiteArray[4].call(this.charAsInt.get(), " ")); $getCallSiteArray[5].callCurrent(this, $getCallSiteArray[6].call(this.charAsInt.get(), "#")); $getCallSiteArray[7].callCurrent(this, $getCallSiteArray[8].call(this.charAsInt.get(), "\"")); $getCallSiteArray[9].callCurrent(this, $getCallSiteArray[10].call(this.charAsInt.get(), "'")); while (ScriptBytecodeAdapter.compareNotEqual($getCallSiteArray[11].callCurrent(this), $getCallSiteArray[12].callGetProperty($get$$class$java$io$StreamTokenizer()))) { $getCallSiteArray[13].call(this.args.get(), $getCallSiteArray[14].callGroovyObjectGetProperty(this)); } return null; } public Object getArgs() { $getCallSiteArray(); return this.args.get(); } public Object getCharAsInt() { $getCallSiteArray(); return this.charAsInt.get(); } public Object doCall() { return $getCallSiteArray()[15].callCurrent(this, ScriptBytecodeAdapter.createPojoWrapper(null, $get$$class$java$lang$Object())); } static { $const$1 = 0; $const$0 = 255; } private static /* synthetic */ CallSiteArray $createCallSiteArray() { final String[] names = new String[16]; $createCallSiteArray_1(names); return new CallSiteArray($get$$class$groovy$util$CliBuilder$_expandArgumentFile_closure3_closure4(), names); } private static /* synthetic */ CallSite[] $getCallSiteArray() { CallSiteArray $createCallSiteArray; if (CliBuilder$_expandArgumentFile_closure3_closure4.$callSiteArray == null || ($createCallSiteArray = CliBuilder$_expandArgumentFile_closure3_closure4.$callSiteArray.get()) == null) { $createCallSiteArray = $createCallSiteArray(); CliBuilder$_expandArgumentFile_closure3_closure4.$callSiteArray = new SoftReference($createCallSiteArray); } return $createCallSiteArray.array; } private static /* synthetic */ Class $get$$class$java$lang$Object() { Class $class$java$lang$Object; if (($class$java$lang$Object = CliBuilder$_expandArgumentFile_closure3_closure4.$class$java$lang$Object) == null) { $class$java$lang$Object = (CliBuilder$_expandArgumentFile_closure3_closure4.$class$java$lang$Object = class$("java.lang.Object")); } return $class$java$lang$Object; } private static /* synthetic */ Class $get$$class$java$io$StreamTokenizer() { Class $class$java$io$StreamTokenizer; if (($class$java$io$StreamTokenizer = CliBuilder$_expandArgumentFile_closure3_closure4.$class$java$io$StreamTokenizer) == null) { $class$java$io$StreamTokenizer = (CliBuilder$_expandArgumentFile_closure3_closure4.$class$java$io$StreamTokenizer = class$("java.io.StreamTokenizer")); } return $class$java$io$StreamTokenizer; } static /* synthetic */ Class class$(final String className) { try { return Class.forName(className); } catch (ClassNotFoundException ex) { throw new NoClassDefFoundError(ex.getMessage()); } } }
sentinel-hub/requests-builder
src/components/common/Output/OutputResponses.js
import React from 'react'; import store from '../../../store'; import requestSlice from '../../../store/request'; import { OUTPUT_FORMATS } from '../../../utils/const/const'; import { connect } from 'react-redux'; const generateResponses = (responses, mode) => { const handleIdentifierChange = (e) => { store.dispatch( requestSlice.actions.setResponse({ idx: parseInt(e.target.name), identifier: e.target.value }), ); }; const handleImageFormatChange = (e) => { store.dispatch( requestSlice.actions.setResponse({ idx: parseInt(e.target.name), format: e.target.value }), ); }; const handleDeleteResponse = (e) => { store.dispatch(requestSlice.actions.deleteResponse(parseInt(e.target.getAttribute('name')))); }; if (mode === 'WMS') { return ( <div className="flex w-full flex-col mb-2"> <label className="form__label">Image Format</label> <select onChange={handleImageFormatChange} value={responses[0].format} name={responses[0].idx} className="form__input mb-2" > {OUTPUT_FORMATS.map((format) => ( <option key={format.name} value={format.value}> {format.name} </option> ))} </select> </div> ); } return responses.map((resp, idx) => ( <div className="response" key={resp.idx}> <label htmlFor={`image-format-${idx}`} className="form__label"> Image Format </label> <select id={`image-format-${idx}`} onChange={handleImageFormatChange} value={resp.format} name={resp.idx} className="form__input mb-2" > {OUTPUT_FORMATS.map((format) => ( <option key={format.name} value={format.value}> {format.name} </option> ))} </select> <label htmlFor={`identifier-${idx}`} className="form__label"> Identifier </label> <input id={`identifier-${idx}`} value={resp.identifier} onChange={handleIdentifierChange} name={resp.idx} type="text" className="form__input mb-2" autoComplete="off" /> {resp.idx !== 0 ? ( <button name={resp.idx} className="secondary-button secondary-button--cancel w-fit mb-2" onClick={handleDeleteResponse} > Remove Response </button> ) : null} {responses.length - 1 !== idx ? <hr className="mt-1"></hr> : null} </div> )); }; const OutputResponses = ({ responses, mode }) => { const handleAddResponse = () => { store.dispatch(requestSlice.actions.addResponse()); }; return ( <> {generateResponses(responses, mode)} {mode !== 'WMS' ? ( <button className="secondary-button w-fit" onClick={handleAddResponse}> Add Response </button> ) : null} </> ); }; const mapStateToProps = (state) => ({ responses: state.request.responses, mode: state.request.mode, }); export default connect(mapStateToProps)(OutputResponses);
xyzshen/WeBASE-Front
src/main/java/com/webank/webase/front/base/config/RabbitMQConfig.java
/* * Copyright 2014-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webank.webase.front.base.config; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.rabbit.connection.ConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitAdmin; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * init mq instance, add config in spring configuration * ********mq config******* * spring: * ... * rabbitmq: * host: 127.0.0.1 * port: 5672 * username: youraccount * password: <PASSWORD> * virtual-host: yourvirtualhost * publisher-confirm: true * ssl: * enabled: false * ... * ************************* * @author marsli */ @Slf4j @Configuration public class RabbitMQConfig { /** * 新建yml中rabbitmq-queue默认的队列 * @param connectionFactory spring的yml中rabbitmq项配置 * @return */ @Bean(name = "rabbitAdmin") public RabbitAdmin initRabbitAdmin(ConnectionFactory connectionFactory) { RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory); return rabbitAdmin; } /** * 用于发送消息到队列 * 传输的message消息体在Message实体类中使用jackson进行序列化 * @param rabbitAdmin * @return */ @Bean(name = "rabbitTemplate") public RabbitTemplate getRabbitTemplate(RabbitAdmin rabbitAdmin) { RabbitTemplate rabbitTemplate = rabbitAdmin.getRabbitTemplate(); return rabbitTemplate; } }
xctrln/algs
BigO/c4.go
<gh_stars>0 package BigO func find(array []int, x int) int { pos := -1 for _, i := range array { if array[i] == x { pos = i break } } return pos }
shanghailzj123/irishub
modules/guardian/keeper/querier_test.go
package keeper_test import ( "testing" "github.com/stretchr/testify/suite" abci "github.com/tendermint/tendermint/abci/types" "github.com/irisnet/irishub/modules/guardian/keeper" "github.com/irisnet/irishub/modules/guardian/types" ) func TestQuerierSuite(t *testing.T) { suite.Run(t, new(KeeperTestSuite)) } func (suite *KeeperTestSuite) TestNewQuerier() { req := abci.RequestQuery{ Path: "", Data: []byte{}, } querier := keeper.NewQuerier(suite.keeper, suite.cdc) res, err := querier(suite.ctx, []string{"other"}, req) suite.Error(err) suite.Nil(res) // test querySupers res, err = querier(suite.ctx, []string{types.QuerySupers}, abci.RequestQuery{}) suite.NoError(err) var supers []types.Super e := suite.cdc.UnmarshalJSON(res, &supers) suite.NoError(e) for i, val := range supers { equal := val.Equal(types.DefaultGenesisState().Supers[i]) suite.True(equal) } }
billy1380/blogwt
src/main/java/com/willshex/blogwt/server/service/search/ISearch.java
// // ISearch.java // blogwt // // Created by <NAME> (billy1380) on 25 Jul 2016. // Copyright © 2016 WillShex Limited. All rights reserved. // package com.willshex.blogwt.server.service.search; import java.util.Collection; import java.util.List; import com.willshex.blogwt.shared.api.SortDirectionType; /** * @author <NAME> (billy1380) * */ public interface ISearch<T> extends IIndex<T> { List<T> search (String query, Integer start, Integer count, String sortBy, SortDirectionType direction); String search (Collection<T> resultHolder, String query, String next, Integer count, String sortBy, SortDirectionType direction); /* (non-Javadoc) * * @see com.willshex.blogwt.server.service.search.ITenancy#isShared() */ @Override default boolean isShared () { return false; } }
linminglu/Fgame
game/rank/handler/init.go
<reponame>linminglu/Fgame<gh_stars>0 package handler import ( "fgame/fgame/common/codec" uipb "fgame/fgame/common/codec/pb/ui" gamecodec "fgame/fgame/game/codec" ) func init() { gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_FORCE_GET_TYPE), (*uipb.CSRankForceGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_FORCE_GET_TYPE), (*uipb.SCRankForceGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_MOUNT_GET_TYPE), (*uipb.CSRankMountGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_MOUNT_GET_TYPE), (*uipb.SCRankMountGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_WING_GET_TYPE), (*uipb.CSRankWingGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_WING_GET_TYPE), (*uipb.SCRankWingGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_BODYSHIELD_GET_TYPE), (*uipb.CSRankBodyShieldGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_BODYSHIELD_GET_TYPE), (*uipb.SCRankBodyShieldGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_WEAPON_GET_TYPE), (*uipb.CSRankWeaponGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_WEAPON_GET_TYPE), (*uipb.SCRankWeaponGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_GANG_GET_TYPE), (*uipb.CSRankGangGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_GANG_GET_TYPE), (*uipb.SCRankGangGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_MY_GET_TYPE), (*uipb.CSRankMyGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_MY_GET_TYPE), (*uipb.SCRankMyGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_SHENFA_GET_TYPE), (*uipb.CSRankShenFaGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_SHENFA_GET_TYPE), (*uipb.SCRankShenFaGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_LINGYU_GET_TYPE), (*uipb.CSRankLingYuGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_LINGYU_GET_TYPE), (*uipb.SCRankLingYuGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_FEATHER_GET_TYPE), (*uipb.CSRankFeatherGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_FEATHER_GET_TYPE), (*uipb.SCRankFeatherGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_SHIELD_GET_TYPE), (*uipb.CSRankShieldGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_SHIELD_GET_TYPE), (*uipb.SCRankShieldGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_ANQI_GET_TYPE), (*uipb.CSRankAnQiGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_ANQI_GET_TYPE), (*uipb.SCRankAnQiGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_FABAO_GET_TYPE), (*uipb.CSRankFaBaoGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_FABAO_GET_TYPE), (*uipb.SCRankFaBaoGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_XIANTI_GET_TYPE), (*uipb.CSRankXianTiGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_XIANTI_GET_TYPE), (*uipb.SCRankXianTiGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_SHIHUNFAN_GET_TYPE), (*uipb.CSRankShiHunFanGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_SHIHUNFAN_GET_TYPE), (*uipb.SCRankShiHunFanGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_TIANMOTI_GET_TYPE), (*uipb.CSRankTianMoTiGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_TIANMOTI_GET_TYPE), (*uipb.SCRankTianMoTiGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_LINGTONG_LEVEL_GET_TYPE), (*uipb.CSRankLingTongLevelGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_LINGTONG_LEVEL_GET_TYPE), (*uipb.SCRankLingTongLevelGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_LINGTONGDEV_GET_TYPE), (*uipb.CSRankLingTongDevGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_LINGTONGDEV_GET_TYPE), (*uipb.SCRankLingTongDevGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_CS_RANK_FEI_SHENG_GET_TYPE), (*uipb.CSRankFeiShengGet)(nil)) gamecodec.RegisterMsg(codec.MessageType(uipb.MessageType_SC_RANK_FEI_SHENG_GET_TYPE), (*uipb.SCRankFeiShengGet)(nil)) }
Animofree/HospitalInformationSystem
src/com/cjj/dao/baseinfo/ViptypeMapper.java
package com.cjj.dao.baseinfo; import java.util.List; import com.cjj.po.Viptype; public interface ViptypeMapper { List<Viptype> findAll(); }
victory1355/LinuxAPI
io_operation/test/3th/find_tree.c
<filename>io_operation/test/3th/find_tree.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <errno.h> #define MAX_PATH 512 void print_file_info(char *pathname) { struct stat filestat; if (stat(pathname, &filestat) == -1) { printf("cannot access the file %s", pathname); return; } printf("%s %8ld\n", pathname, filestat.st_size); if ((filestat.st_mode & S_IFMT) == S_IFDIR) { dir_order(pathname); } } void dir_order(char *pathname) { DIR *dfd; char name[MAX_PATH]; struct dirent *dp; if ((dfd = opendir(pathname)) == NULL) { printf("dir_order: can't open %s\n %s", pathname,strerror(errno)); return; } while ((dp = readdir(dfd)) != NULL) { //过滤当前目录和上一级的目录信息 if (strncmp(dp->d_name, ".", 1) == 0) continue; if (strlen(pathname) + strlen(dp->d_name) + 2 > sizeof(name)) { printf("dir_order: name %s %s too long\n", pathname, dp->d_name); } else { memset(name, 0, sizeof(name)); sprintf(name, "%s/%s", pathname, dp->d_name); print_file_info(name); } } closedir(dfd); } int main(int argc, char *argv[]) { if (argc == 1) { dir_order("."); } else { dir_order(argv[1]); } return 0; }
all-of-us/research
api/src/test/java/org/pmiops/workbench/conceptset/ConceptSetServiceTest.java
package org.pmiops.workbench.conceptset; import static com.google.common.truth.Truth.assertThat; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.pmiops.workbench.FakeClockConfiguration; import org.pmiops.workbench.cdr.ConceptBigQueryService; import org.pmiops.workbench.cohortbuilder.CohortBuilderService; import org.pmiops.workbench.cohortbuilder.mapper.CohortBuilderMapper; import org.pmiops.workbench.conceptset.mapper.ConceptSetMapper; import org.pmiops.workbench.conceptset.mapper.ConceptSetMapperImpl; import org.pmiops.workbench.db.dao.WorkspaceDao; import org.pmiops.workbench.db.model.DbConceptSet; import org.pmiops.workbench.db.model.DbConceptSetConceptId; import org.pmiops.workbench.db.model.DbWorkspace; import org.pmiops.workbench.model.Domain; import org.pmiops.workbench.utils.mappers.CommonMappers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.test.annotation.DirtiesContext; @DataJpaTest @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) public class ConceptSetServiceTest { @Autowired WorkspaceDao workspaceDao; @Autowired ConceptSetService conceptSetService; @Autowired ConceptSetMapper conceptSetMapper; @TestConfiguration @Import({FakeClockConfiguration.class, ConceptSetService.class, ConceptSetMapperImpl.class}) @MockBean({ CommonMappers.class, CohortBuilderMapper.class, ConceptBigQueryService.class, CohortBuilderService.class }) static class Configuration {} @Test public void testCloneConceptSetWithNoCdrVersionChange() { DbWorkspace mockDbWorkspace = mockWorkspace(); DbConceptSet fromConceptSet = mockConceptSet(); DbConceptSet copiedConceptSet = conceptSetService.cloneConceptSetAndConceptIds(fromConceptSet, mockDbWorkspace); assertThat(copiedConceptSet).isNotNull(); assertThat(copiedConceptSet.getConceptSetConceptIds().size()).isEqualTo(5); assertThat(copiedConceptSet.getWorkspaceId()).isEqualTo(mockDbWorkspace.getWorkspaceId()); assertThat(copiedConceptSet).isNotNull(); } private DbConceptSet mockConceptSet() { DbConceptSetConceptId dbConceptSetConceptId1 = DbConceptSetConceptId.builder().addConceptId(1L).addStandard(true).build(); DbConceptSetConceptId dbConceptSetConceptId2 = DbConceptSetConceptId.builder().addConceptId(2L).addStandard(true).build(); DbConceptSetConceptId dbConceptSetConceptId3 = DbConceptSetConceptId.builder().addConceptId(3L).addStandard(true).build(); DbConceptSetConceptId dbConceptSetConceptId4 = DbConceptSetConceptId.builder().addConceptId(4L).addStandard(true).build(); DbConceptSetConceptId dbConceptSetConceptId5 = DbConceptSetConceptId.builder().addConceptId(5L).addStandard(true).build(); Set<DbConceptSetConceptId> dbConceptSetConceptIds = Stream.of( dbConceptSetConceptId1, dbConceptSetConceptId2, dbConceptSetConceptId3, dbConceptSetConceptId4, dbConceptSetConceptId5) .collect(Collectors.toCollection(HashSet::new)); DbConceptSet conceptSet = new DbConceptSet(); conceptSet.setConceptSetConceptIds(dbConceptSetConceptIds); conceptSet.setConceptSetId(1); conceptSet.setName("Mock Concept Set"); conceptSet.setDomainEnum(Domain.CONDITION); return conceptSet; } private DbWorkspace mockWorkspace() { DbWorkspace workspace = new DbWorkspace(); workspace.setName("Target DbWorkspace"); workspace.setWorkspaceId(2); workspace = workspaceDao.save(workspace); return workspace; } }
lechium/tvOS130Headers
System/Library/PrivateFrameworks/AppStoreDaemon.framework/Support/appstored/XDCDeviceManager.h
/* * This header is generated by classdump-dyld 1.0 * on Tuesday, November 5, 2019 at 2:38:48 AM Mountain Standard Time * Operating System: Version 13.0 (Build 17J586) * Image Source: /System/Library/PrivateFrameworks/AppStoreDaemon.framework/Support/appstored * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ @protocol OS_dispatch_queue; @class NSMutableDictionary, NSObject, XDCDevice; @interface XDCDeviceManager : NSObject { NSMutableDictionary* _devices; NSObject*<OS_dispatch_queue> _dispatchQueue; } @property (readonly) XDCDevice * activePairedDevice; +(id)sharedInstance; -(id)init; -(id)deviceForPairingID:(id)arg1 ; -(XDCDevice *)activePairedDevice; -(id)deviceForDestinationID:(id)arg1 ; -(id)deviceForFromID:(id)arg1 usingService:(id)arg2 ; -(void)updateDevicesWithArray:(id)arg1 ; @end
mniak/alkanoid
cmd/http/routes_test.go
package main import ( "bytes" "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" "github.com/brianvoe/gofakeit/v6" "github.com/golang/mock/gomock" "github.com/mniak/Alkanoid/app" "github.com/mniak/Alkanoid/internal/mocks" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestCreateAccount(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() var requestObj app.CreateAccountRequest var responseObj app.CreateAccountResponse gofakeit.Struct(&requestObj) gofakeit.Struct(&responseObj) a := mocks.NewMockApplication(ctrl) a.EXPECT(). CreateAccount(requestObj). Return(responseObj, nil) router := setupRouter(a) w := httptest.NewRecorder() reqBytes, err := json.Marshal(requestObj) require.NoError(t, err) req, _ := http.NewRequest("POST", "/accounts", bytes.NewReader(reqBytes)) router.ServeHTTP(w, req) assert.Equal(t, 201, w.Code) var parsedResponse app.CreateAccountResponse require.NoError(t, json.Unmarshal(w.Body.Bytes(), &parsedResponse)) require.Equal(t, responseObj, parsedResponse) } func TestGetAccount(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() var requestObj app.GetAccountRequest var responseObj app.GetAccountResponse gofakeit.Struct(&requestObj) gofakeit.Struct(&responseObj) a := mocks.NewMockApplication(ctrl) a.EXPECT(). GetAccount(requestObj). Return(responseObj, nil) router := setupRouter(a) w := httptest.NewRecorder() req, _ := http.NewRequest("GET", fmt.Sprintf("/accounts/%d", requestObj.AccountID), nil) router.ServeHTTP(w, req) assert.Equal(t, 200, w.Code) var parsedResponse app.GetAccountResponse require.NoError(t, json.Unmarshal(w.Body.Bytes(), &parsedResponse)) require.Equal(t, responseObj, parsedResponse) } func TestCreateTransaction(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() var requestObj app.CreateTransactionRequest var responseObj app.CreateTransactionResponse gofakeit.Struct(&requestObj) gofakeit.Struct(&responseObj) a := mocks.NewMockApplication(ctrl) a.EXPECT(). CreateTransaction(requestObj). Return(responseObj, nil) router := setupRouter(a) w := httptest.NewRecorder() reqBytes, err := json.Marshal(requestObj) require.NoError(t, err) req, _ := http.NewRequest("POST", "/transactions", bytes.NewReader(reqBytes)) router.ServeHTTP(w, req) assert.Equal(t, 201, w.Code) var parsedResponse app.CreateTransactionResponse require.NoError(t, json.Unmarshal(w.Body.Bytes(), &parsedResponse)) require.Equal(t, responseObj, parsedResponse) }
gaoht/house
java/classes/android/support/transition/az.java
<filename>java/classes/android/support/transition/az.java package android.support.transition; import android.view.View; import java.util.Map; public abstract class az extends ae { private static final String[] a = { "android:visibilityPropagation:visibility", "android:visibilityPropagation:center" }; private static int a(ag paramag, int paramInt) { if (paramag == null) { return -1; } paramag = (int[])paramag.a.get("android:visibilityPropagation:center"); if (paramag == null) { return -1; } return paramag[paramInt]; } public void captureValues(ag paramag) { View localView = paramag.b; Integer localInteger = (Integer)paramag.a.get("android:visibility:visibility"); Object localObject = localInteger; if (localInteger == null) { localObject = Integer.valueOf(localView.getVisibility()); } paramag.a.put("android:visibilityPropagation:visibility", localObject); localObject = new int[2]; localView.getLocationOnScreen((int[])localObject); localObject[0] += Math.round(localView.getTranslationX()); localObject[0] += localView.getWidth() / 2; localObject[1] += Math.round(localView.getTranslationY()); int i = localObject[1]; localObject[1] = (localView.getHeight() / 2 + i); paramag.a.put("android:visibilityPropagation:center", localObject); } public String[] getPropagationProperties() { return a; } public int getViewVisibility(ag paramag) { if (paramag == null) { return 8; } paramag = (Integer)paramag.a.get("android:visibilityPropagation:visibility"); if (paramag == null) { return 8; } return paramag.intValue(); } public int getViewX(ag paramag) { return a(paramag, 0); } public int getViewY(ag paramag) { return a(paramag, 1); } } /* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/android/support/transition/az.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
digi-embedded/android_platform_system_bt
bta/include/bta_gatt_api.h
<reponame>digi-embedded/android_platform_system_bt<gh_stars>0 /****************************************************************************** * * Copyright (C) 2003-2013 Broadcom Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ /****************************************************************************** * * This is the public interface file for BTA GATT. * ******************************************************************************/ #ifndef BTA_GATT_API_H #define BTA_GATT_API_H #include "bta_api.h" #include "gatt_api.h" #include "osi/include/list.h" #include <base/callback_forward.h> #include <vector> using std::vector; #ifndef BTA_GATT_DEBUG #define BTA_GATT_DEBUG false #endif /***************************************************************************** * Constants and data types ****************************************************************************/ /************************** * Common Definitions **************************/ /* GATT ID */ typedef struct { tBT_UUID uuid; /* uuid of the attribute */ uint8_t inst_id; /* instance ID */ } __attribute__((packed)) tBTA_GATT_ID; /* Success code and error codes */ #define BTA_GATT_OK GATT_SUCCESS #define BTA_GATT_INVALID_HANDLE GATT_INVALID_HANDLE /* 0x0001 */ #define BTA_GATT_READ_NOT_PERMIT GATT_READ_NOT_PERMIT /* 0x0002 */ #define BTA_GATT_WRITE_NOT_PERMIT GATT_WRITE_NOT_PERMIT /* 0x0003 */ #define BTA_GATT_INVALID_PDU GATT_INVALID_PDU /* 0x0004 */ #define BTA_GATT_INSUF_AUTHENTICATION GATT_INSUF_AUTHENTICATION /* 0x0005 */ #define BTA_GATT_REQ_NOT_SUPPORTED GATT_REQ_NOT_SUPPORTED /* 0x0006 */ #define BTA_GATT_INVALID_OFFSET GATT_INVALID_OFFSET /* 0x0007 */ #define BTA_GATT_INSUF_AUTHORIZATION GATT_INSUF_AUTHORIZATION /* 0x0008 */ #define BTA_GATT_PREPARE_Q_FULL GATT_PREPARE_Q_FULL /* 0x0009 */ #define BTA_GATT_NOT_FOUND GATT_NOT_FOUND /* 0x000a */ #define BTA_GATT_NOT_LONG GATT_NOT_LONG /* 0x000b */ #define BTA_GATT_INSUF_KEY_SIZE GATT_INSUF_KEY_SIZE /* 0x000c */ #define BTA_GATT_INVALID_ATTR_LEN GATT_INVALID_ATTR_LEN /* 0x000d */ #define BTA_GATT_ERR_UNLIKELY GATT_ERR_UNLIKELY /* 0x000e */ #define BTA_GATT_INSUF_ENCRYPTION GATT_INSUF_ENCRYPTION /* 0x000f */ #define BTA_GATT_UNSUPPORT_GRP_TYPE GATT_UNSUPPORT_GRP_TYPE /* 0x0010 */ #define BTA_GATT_INSUF_RESOURCE GATT_INSUF_RESOURCE /* 0x0011 */ #define BTA_GATT_NO_RESOURCES GATT_NO_RESOURCES /* 0x80 */ #define BTA_GATT_INTERNAL_ERROR GATT_INTERNAL_ERROR /* 0x81 */ #define BTA_GATT_WRONG_STATE GATT_WRONG_STATE /* 0x82 */ #define BTA_GATT_DB_FULL GATT_DB_FULL /* 0x83 */ #define BTA_GATT_BUSY GATT_BUSY /* 0x84 */ #define BTA_GATT_ERROR GATT_ERROR /* 0x85 */ #define BTA_GATT_CMD_STARTED GATT_CMD_STARTED /* 0x86 */ #define BTA_GATT_ILLEGAL_PARAMETER GATT_ILLEGAL_PARAMETER /* 0x87 */ #define BTA_GATT_PENDING GATT_PENDING /* 0x88 */ #define BTA_GATT_AUTH_FAIL GATT_AUTH_FAIL /* 0x89 */ #define BTA_GATT_MORE GATT_MORE /* 0x8a */ #define BTA_GATT_INVALID_CFG GATT_INVALID_CFG /* 0x8b */ #define BTA_GATT_SERVICE_STARTED GATT_SERVICE_STARTED /* 0x8c */ #define BTA_GATT_ENCRYPED_MITM GATT_ENCRYPED_MITM /* GATT_SUCCESS */ #define BTA_GATT_ENCRYPED_NO_MITM GATT_ENCRYPED_NO_MITM /* 0x8d */ #define BTA_GATT_NOT_ENCRYPTED GATT_NOT_ENCRYPTED /* 0x8e */ #define BTA_GATT_CONGESTED GATT_CONGESTED /* 0x8f */ #define BTA_GATT_DUP_REG 0x90 /* 0x90 */ #define BTA_GATT_ALREADY_OPEN 0x91 /* 0x91 */ #define BTA_GATT_CANCEL 0x92 /* 0x92 */ /* 0xE0 ~ 0xFC reserved for future use */ #define BTA_GATT_CCC_CFG_ERR \ GATT_CCC_CFG_ERR /* 0xFD Client Characteristic Configuration Descriptor \ Improperly Configured */ #define BTA_GATT_PRC_IN_PROGRESS \ GATT_PRC_IN_PROGRESS /* 0xFE Procedure Already in progress */ #define BTA_GATT_OUT_OF_RANGE \ GATT_OUT_OF_RANGE /* 0xFFAttribute value out of range */ typedef uint8_t tBTA_GATT_STATUS; #define BTA_GATT_INVALID_CONN_ID GATT_INVALID_CONN_ID /* Client callback function events */ #define BTA_GATTC_DEREG_EVT 1 /* GATT client deregistered event */ #define BTA_GATTC_OPEN_EVT 2 /* GATTC open request status event */ #define BTA_GATTC_CLOSE_EVT 5 /* GATTC close request status event */ #define BTA_GATTC_SEARCH_CMPL_EVT 6 /* GATT discovery complete event */ #define BTA_GATTC_SEARCH_RES_EVT 7 /* GATT discovery result event */ #define BTA_GATTC_NOTIF_EVT 10 /* GATT attribute notification event */ #define BTA_GATTC_EXEC_EVT 12 /* execute write complete event */ #define BTA_GATTC_ACL_EVT 13 /* ACL up event */ #define BTA_GATTC_CANCEL_OPEN_EVT 14 /* cancel open event */ #define BTA_GATTC_SRVC_CHG_EVT 15 /* service change event */ #define BTA_GATTC_ENC_CMPL_CB_EVT 17 /* encryption complete callback event */ #define BTA_GATTC_CFG_MTU_EVT 18 /* configure MTU complete event */ #define BTA_GATTC_CONGEST_EVT 24 /* Congestion event */ #define BTA_GATTC_PHY_UPDATE_EVT 25 /* PHY change event */ #define BTA_GATTC_CONN_UPDATE_EVT 26 /* Connection parameters update event */ typedef uint8_t tBTA_GATTC_EVT; typedef tGATT_IF tBTA_GATTC_IF; typedef struct { uint16_t unit; /* as UUIUD defined by SIG */ uint16_t descr; /* as UUID as defined by SIG */ tGATT_FORMAT format; int8_t exp; uint8_t name_spc; /* The name space of the description */ } tBTA_GATT_CHAR_PRES; #define BTA_GATT_CLT_CONFIG_NONE GATT_CLT_CONFIG_NONE /* 0x0000 */ #define BTA_GATT_CLT_CONFIG_NOTIFICATION \ GATT_CLT_CONFIG_NOTIFICATION /* 0x0001 */ #define BTA_GATT_CLT_CONFIG_INDICATION GATT_CLT_CONFIG_INDICATION /* 0x0002 */ typedef uint16_t tBTA_GATT_CLT_CHAR_CONFIG; /* characteristic descriptor: server configuration value */ #define BTA_GATT_SVR_CONFIG_NONE GATT_SVR_CONFIG_NONE /* 0x0000 */ #define BTA_GATT_SVR_CONFIG_BROADCAST GATT_SVR_CONFIG_BROADCAST /* 0x0001 */ typedef uint16_t tBTA_GATT_SVR_CHAR_CONFIG; /* Characteristic Aggregate Format attribute value */ #define BTA_GATT_AGGR_HANDLE_NUM_MAX 10 typedef struct { uint8_t num_handle; uint16_t handle_list[BTA_GATT_AGGR_HANDLE_NUM_MAX]; } tBTA_GATT_CHAR_AGGRE; typedef tGATT_VALID_RANGE tBTA_GATT_VALID_RANGE; typedef struct { uint16_t len; uint8_t* p_value; } tBTA_GATT_UNFMT; #define BTA_GATT_MAX_ATTR_LEN GATT_MAX_ATTR_LEN #define BTA_GATTC_TYPE_WRITE GATT_WRITE #define BTA_GATTC_TYPE_WRITE_NO_RSP GATT_WRITE_NO_RSP typedef uint8_t tBTA_GATTC_WRITE_TYPE; #define BTA_GATT_CONN_UNKNOWN 0 #define BTA_GATT_CONN_L2C_FAILURE \ GATT_CONN_L2C_FAILURE /* general l2cap resource failure */ #define BTA_GATT_CONN_TIMEOUT GATT_CONN_TIMEOUT /* 0x08 connection timeout */ #define BTA_GATT_CONN_TERMINATE_PEER_USER \ GATT_CONN_TERMINATE_PEER_USER /* 0x13 connection terminate by peer user */ #define BTA_GATT_CONN_TERMINATE_LOCAL_HOST \ GATT_CONN_TERMINATE_LOCAL_HOST /* 0x16 connectionterminated by local host */ #define BTA_GATT_CONN_FAIL_ESTABLISH \ GATT_CONN_FAIL_ESTABLISH /* 0x03E connection fail to establish */ #define BTA_GATT_CONN_LMP_TIMEOUT \ GATT_CONN_LMP_TIMEOUT /* 0x22 connection fail for LMP response tout */ #define BTA_GATT_CONN_CANCEL \ GATT_CONN_CANCEL /* 0x0100 L2CAP connection cancelled */ #define BTA_GATT_CONN_NONE 0x0101 /* 0x0101 no connection to cancel */ typedef uint16_t tBTA_GATT_REASON; #define BTA_GATTC_MULTI_MAX GATT_MAX_READ_MULTI_HANDLES typedef struct { uint8_t num_attr; uint16_t handles[BTA_GATTC_MULTI_MAX]; } tBTA_GATTC_MULTI; #define BTA_GATT_AUTH_REQ_NONE GATT_AUTH_REQ_NONE #define BTA_GATT_AUTH_REQ_NO_MITM \ GATT_AUTH_REQ_NO_MITM /* unauthenticated encryption */ #define BTA_GATT_AUTH_REQ_MITM \ GATT_AUTH_REQ_MITM /* authenticated encryption \ */ #define BTA_GATT_AUTH_REQ_SIGNED_NO_MITM GATT_AUTH_REQ_SIGNED_NO_MITM #define BTA_GATT_AUTH_REQ_SIGNED_MITM GATT_AUTH_REQ_SIGNED_MITM typedef tGATT_AUTH_REQ tBTA_GATT_AUTH_REQ; enum { BTA_GATTC_ATTR_TYPE_INCL_SRVC, BTA_GATTC_ATTR_TYPE_CHAR, BTA_GATTC_ATTR_TYPE_CHAR_DESCR, BTA_GATTC_ATTR_TYPE_SRVC }; typedef uint8_t tBTA_GATTC_ATTR_TYPE; typedef struct { tBT_UUID uuid; uint16_t s_handle; uint16_t e_handle; /* used for service only */ uint8_t attr_type; uint8_t id; uint8_t prop; /* used when attribute type is characteristic */ bool is_primary; /* used when attribute type is service */ uint16_t incl_srvc_handle; /* used when attribute type is included service */ } tBTA_GATTC_NV_ATTR; /* callback data structure */ typedef struct { tBTA_GATT_STATUS status; tBTA_GATTC_IF client_if; tBT_UUID app_uuid; } tBTA_GATTC_REG; typedef struct { uint16_t conn_id; tBTA_GATT_STATUS status; uint16_t handle; uint16_t len; uint8_t value[BTA_GATT_MAX_ATTR_LEN]; } tBTA_GATTC_READ; typedef struct { uint16_t conn_id; tBTA_GATT_STATUS status; uint16_t handle; } tBTA_GATTC_WRITE; typedef struct { uint16_t conn_id; tBTA_GATT_STATUS status; } tBTA_GATTC_EXEC_CMPL; typedef struct { uint16_t conn_id; tBTA_GATT_STATUS status; } tBTA_GATTC_SEARCH_CMPL; typedef struct { uint16_t conn_id; tBTA_GATT_ID service_uuid; } tBTA_GATTC_SRVC_RES; typedef struct { uint16_t conn_id; tBTA_GATT_STATUS status; uint16_t mtu; } tBTA_GATTC_CFG_MTU; typedef struct { tBTA_GATT_STATUS status; uint16_t conn_id; tBTA_GATTC_IF client_if; BD_ADDR remote_bda; tBTA_TRANSPORT transport; uint16_t mtu; } tBTA_GATTC_OPEN; typedef struct { tBTA_GATT_STATUS status; uint16_t conn_id; tBTA_GATTC_IF client_if; BD_ADDR remote_bda; tBTA_GATT_REASON reason; /* disconnect reason code, not useful when connect event is reported */ } tBTA_GATTC_CLOSE; typedef struct { uint16_t conn_id; BD_ADDR bda; uint16_t handle; uint16_t len; uint8_t value[BTA_GATT_MAX_ATTR_LEN]; bool is_notify; } tBTA_GATTC_NOTIFY; typedef struct { uint16_t conn_id; bool congested; /* congestion indicator */ } tBTA_GATTC_CONGEST; typedef struct { tBTA_GATT_STATUS status; tBTA_GATTC_IF client_if; uint16_t conn_id; BD_ADDR remote_bda; } tBTA_GATTC_OPEN_CLOSE; typedef struct { tBTA_GATTC_IF client_if; BD_ADDR remote_bda; } tBTA_GATTC_ENC_CMPL_CB; typedef struct { tBTA_GATTC_IF server_if; uint16_t conn_id; uint8_t tx_phy; uint8_t rx_phy; tBTA_GATT_STATUS status; } tBTA_GATTC_PHY_UPDATE; typedef struct { tBTA_GATTC_IF server_if; uint16_t conn_id; uint16_t interval; uint16_t latency; uint16_t timeout; tBTA_GATT_STATUS status; } tBTA_GATTC_CONN_UPDATE; typedef union { tBTA_GATT_STATUS status; tBTA_GATTC_SEARCH_CMPL search_cmpl; /* discovery complete */ tBTA_GATTC_SRVC_RES srvc_res; /* discovery result */ tBTA_GATTC_REG reg_oper; /* registration data */ tBTA_GATTC_OPEN open; tBTA_GATTC_CLOSE close; tBTA_GATTC_READ read; /* read attribute/descriptor data */ tBTA_GATTC_WRITE write; /* write complete data */ tBTA_GATTC_EXEC_CMPL exec_cmpl; /* execute complete */ tBTA_GATTC_NOTIFY notify; /* notification/indication event data */ tBTA_GATTC_ENC_CMPL_CB enc_cmpl; BD_ADDR remote_bda; /* service change event */ tBTA_GATTC_CFG_MTU cfg_mtu; /* configure MTU operation */ tBTA_GATTC_CONGEST congest; tBTA_GATTC_PHY_UPDATE phy_update; tBTA_GATTC_CONN_UPDATE conn_update; } tBTA_GATTC; /* GATTC enable callback function */ typedef void(tBTA_GATTC_ENB_CBACK)(tBTA_GATT_STATUS status); /* Client callback function */ typedef void(tBTA_GATTC_CBACK)(tBTA_GATTC_EVT event, tBTA_GATTC* p_data); /* GATT Server Data Structure */ /* Server callback function events */ #define BTA_GATTS_REG_EVT 0 #define BTA_GATTS_READ_CHARACTERISTIC_EVT \ GATTS_REQ_TYPE_READ_CHARACTERISTIC /* 1 */ #define BTA_GATTS_READ_DESCRIPTOR_EVT GATTS_REQ_TYPE_READ_DESCRIPTOR /* 2 */ #define BTA_GATTS_WRITE_CHARACTERISTIC_EVT \ GATTS_REQ_TYPE_WRITE_CHARACTERISTIC /* 3 */ #define BTA_GATTS_WRITE_DESCRIPTOR_EVT GATTS_REQ_TYPE_WRITE_DESCRIPTOR /* 4 */ #define BTA_GATTS_EXEC_WRITE_EVT GATTS_REQ_TYPE_WRITE_EXEC /* 5 */ #define BTA_GATTS_MTU_EVT GATTS_REQ_TYPE_MTU /* 6 */ #define BTA_GATTS_CONF_EVT GATTS_REQ_TYPE_CONF /* 7 */ #define BTA_GATTS_DEREG_EVT 8 #define BTA_GATTS_DELELTE_EVT 11 #define BTA_GATTS_STOP_EVT 13 #define BTA_GATTS_CONNECT_EVT 14 #define BTA_GATTS_DISCONNECT_EVT 15 #define BTA_GATTS_OPEN_EVT 16 #define BTA_GATTS_CANCEL_OPEN_EVT 17 #define BTA_GATTS_CLOSE_EVT 18 #define BTA_GATTS_CONGEST_EVT 20 #define BTA_GATTS_PHY_UPDATE_EVT 21 #define BTA_GATTS_CONN_UPDATE_EVT 22 typedef uint8_t tBTA_GATTS_EVT; typedef tGATT_IF tBTA_GATTS_IF; /* Attribute permissions */ #define BTA_GATT_PERM_READ GATT_PERM_READ /* bit 0 - 0x0001 */ #define BTA_GATT_PERM_READ_ENCRYPTED \ GATT_PERM_READ_ENCRYPTED /* bit 1 - 0x0002 */ #define BTA_GATT_PERM_READ_ENC_MITM \ GATT_PERM_READ_ENC_MITM /* bit 2 - 0x0004 */ #define BTA_GATT_PERM_WRITE GATT_PERM_WRITE /* bit 4 - 0x0010 */ #define BTA_GATT_PERM_WRITE_ENCRYPTED \ GATT_PERM_WRITE_ENCRYPTED /* bit 5 - 0x0020 */ #define BTA_GATT_PERM_WRITE_ENC_MITM \ GATT_PERM_WRITE_ENC_MITM /* bit 6 - 0x0040 */ #define BTA_GATT_PERM_WRITE_SIGNED \ GATT_PERM_WRITE_SIGNED /* bit 7 - 0x0080 \ */ #define BTA_GATT_PERM_WRITE_SIGNED_MITM \ GATT_PERM_WRITE_SIGNED_MITM /* bit 8 - 0x0100 */ typedef uint16_t tBTA_GATT_PERM; #define BTA_GATTS_INVALID_APP 0xff #define BTA_GATTS_INVALID_IF 0 /* definition of characteristic properties */ #define BTA_GATT_CHAR_PROP_BIT_BROADCAST \ GATT_CHAR_PROP_BIT_BROADCAST /* 0x01 \ */ #define BTA_GATT_CHAR_PROP_BIT_READ GATT_CHAR_PROP_BIT_READ /* 0x02 */ #define BTA_GATT_CHAR_PROP_BIT_WRITE_NR GATT_CHAR_PROP_BIT_WRITE_NR /* 0x04 */ #define BTA_GATT_CHAR_PROP_BIT_WRITE GATT_CHAR_PROP_BIT_WRITE /* 0x08 */ #define BTA_GATT_CHAR_PROP_BIT_NOTIFY GATT_CHAR_PROP_BIT_NOTIFY /* 0x10 */ #define BTA_GATT_CHAR_PROP_BIT_INDICATE GATT_CHAR_PROP_BIT_INDICATE /* 0x20 */ #define BTA_GATT_CHAR_PROP_BIT_AUTH GATT_CHAR_PROP_BIT_AUTH /* 0x40 */ #define BTA_GATT_CHAR_PROP_BIT_EXT_PROP GATT_CHAR_PROP_BIT_EXT_PROP /* 0x80 */ typedef uint8_t tBTA_GATT_CHAR_PROP; #ifndef BTA_GATTC_CHAR_DESCR_MAX #define BTA_GATTC_CHAR_DESCR_MAX 7 #endif /*********************** NV callback Data Definitions ********************** */ typedef struct { tBT_UUID app_uuid128; tBT_UUID svc_uuid; uint16_t svc_inst; uint16_t s_handle; uint16_t e_handle; bool is_primary; /* primary service or secondary */ } tBTA_GATTS_HNDL_RANGE; #define BTA_GATTS_SRV_CHG_CMD_ADD_CLIENT GATTS_SRV_CHG_CMD_ADD_CLIENT #define BTA_GATTS_SRV_CHG_CMD_UPDATE_CLIENT GATTS_SRV_CHG_CMD_UPDATE_CLIENT #define BTA_GATTS_SRV_CHG_CMD_REMOVE_CLIENT GATTS_SRV_CHG_CMD_REMOVE_CLIENT #define BTA_GATTS_SRV_CHG_CMD_READ_NUM_CLENTS GATTS_SRV_CHG_CMD_READ_NUM_CLENTS #define BTA_GATTS_SRV_CHG_CMD_READ_CLENT GATTS_SRV_CHG_CMD_READ_CLENT typedef tGATTS_SRV_CHG_CMD tBTA_GATTS_SRV_CHG_CMD; typedef tGATTS_SRV_CHG tBTA_GATTS_SRV_CHG; typedef tGATTS_SRV_CHG_REQ tBTA_GATTS_SRV_CHG_REQ; typedef tGATTS_SRV_CHG_RSP tBTA_GATTS_SRV_CHG_RSP; #define BTA_GATT_TRANSPORT_LE GATT_TRANSPORT_LE #define BTA_GATT_TRANSPORT_BR_EDR GATT_TRANSPORT_BR_EDR #define BTA_GATT_TRANSPORT_LE_BR_EDR GATT_TRANSPORT_LE_BR_EDR typedef uint8_t tBTA_GATT_TRANSPORT; /* attribute value */ typedef tGATT_VALUE tBTA_GATT_VALUE; /* attribute response data */ typedef tGATTS_RSP tBTA_GATTS_RSP; /* attribute request data from the client */ #define BTA_GATT_PREP_WRITE_CANCEL 0x00 #define BTA_GATT_PREP_WRITE_EXEC 0x01 typedef tGATT_EXEC_FLAG tBTA_GATT_EXEC_FLAG; /* read request always based on UUID */ typedef tGATT_READ_REQ tTA_GBATT_READ_REQ; /* write request data */ typedef tGATT_WRITE_REQ tBTA_GATT_WRITE_REQ; /* callback data for server access request from client */ typedef tGATTS_DATA tBTA_GATTS_REQ_DATA; typedef struct { tBTA_GATT_STATUS status; BD_ADDR remote_bda; uint32_t trans_id; uint16_t conn_id; tBTA_GATTS_REQ_DATA* p_data; } tBTA_GATTS_REQ; typedef struct { tBTA_GATTS_IF server_if; tBTA_GATT_STATUS status; tBT_UUID uuid; } tBTA_GATTS_REG_OPER; typedef struct { tBTA_GATTS_IF server_if; uint16_t service_id; uint16_t svc_instance; bool is_primary; tBTA_GATT_STATUS status; tBT_UUID uuid; } tBTA_GATTS_CREATE; typedef struct { tBTA_GATTS_IF server_if; uint16_t service_id; tBTA_GATT_STATUS status; } tBTA_GATTS_SRVC_OPER; typedef struct { tBTA_GATTS_IF server_if; BD_ADDR remote_bda; uint16_t conn_id; tBTA_GATT_REASON reason; /* report disconnect reason */ tBTA_GATT_TRANSPORT transport; } tBTA_GATTS_CONN; typedef struct { uint16_t conn_id; bool congested; /* report channel congestion indicator */ } tBTA_GATTS_CONGEST; typedef struct { uint16_t conn_id; /* connection ID */ tBTA_GATT_STATUS status; /* notification/indication status */ } tBTA_GATTS_CONF; typedef struct { tBTA_GATTS_IF server_if; uint16_t conn_id; uint8_t tx_phy; uint8_t rx_phy; tBTA_GATT_STATUS status; } tBTA_GATTS_PHY_UPDATE; typedef struct { tBTA_GATTS_IF server_if; uint16_t conn_id; uint16_t interval; uint16_t latency; uint16_t timeout; tBTA_GATT_STATUS status; } tBTA_GATTS_CONN_UPDATE; /* GATTS callback data */ typedef union { tBTA_GATTS_REG_OPER reg_oper; tBTA_GATTS_CREATE create; tBTA_GATTS_SRVC_OPER srvc_oper; tBTA_GATT_STATUS status; /* BTA_GATTS_LISTEN_EVT */ tBTA_GATTS_REQ req_data; tBTA_GATTS_CONN conn; /* BTA_GATTS_CONN_EVT */ tBTA_GATTS_CONGEST congest; /* BTA_GATTS_CONGEST_EVT callback data */ tBTA_GATTS_CONF confirm; /* BTA_GATTS_CONF_EVT callback data */ tBTA_GATTS_PHY_UPDATE phy_update; /* BTA_GATTS_PHY_UPDATE_EVT callback data */ tBTA_GATTS_CONN_UPDATE conn_update; /* BTA_GATTS_CONN_UPDATE_EVT callback data */ } tBTA_GATTS; /* GATTS enable callback function */ typedef void(tBTA_GATTS_ENB_CBACK)(tBTA_GATT_STATUS status); /* Server callback function */ typedef void(tBTA_GATTS_CBACK)(tBTA_GATTS_EVT event, tBTA_GATTS* p_data); typedef struct { tBT_UUID uuid; bool is_primary; uint16_t handle; uint16_t s_handle; uint16_t e_handle; list_t* characteristics; /* list of tBTA_GATTC_CHARACTERISTIC */ list_t* included_svc; /* list of tBTA_GATTC_INCLUDED_SVC */ } __attribute__((packed, aligned(alignof(tBT_UUID)))) tBTA_GATTC_SERVICE; typedef struct { tBT_UUID uuid; uint16_t handle; tBTA_GATT_CHAR_PROP properties; tBTA_GATTC_SERVICE* service; /* owning service*/ list_t* descriptors; /* list of tBTA_GATTC_DESCRIPTOR */ } __attribute__((packed, aligned(alignof(tBT_UUID)))) tBTA_GATTC_CHARACTERISTIC; typedef struct { tBT_UUID uuid; uint16_t handle; tBTA_GATTC_CHARACTERISTIC* characteristic; /* owning characteristic */ } __attribute__((packed)) tBTA_GATTC_DESCRIPTOR; typedef struct { tBT_UUID uuid; uint16_t handle; tBTA_GATTC_SERVICE* owning_service; /* owning service*/ tBTA_GATTC_SERVICE* included_service; } __attribute__((packed)) tBTA_GATTC_INCLUDED_SVC; /***************************************************************************** * External Function Declarations ****************************************************************************/ /************************** * Client Functions **************************/ /******************************************************************************* * * Function BTA_GATTC_Disable * * Description This function is called to disable the GATTC module * * Parameters None. * * Returns None * ******************************************************************************/ extern void BTA_GATTC_Disable(void); using BtaAppRegisterCallback = base::Callback<void(uint8_t /* app_id */, uint8_t /* status */)>; /** * This function is called to register application callbacks with BTA GATTC *module. * p_client_cb - pointer to the application callback function. **/ extern void BTA_GATTC_AppRegister(tBTA_GATTC_CBACK* p_client_cb, BtaAppRegisterCallback cb); /******************************************************************************* * * Function BTA_GATTC_AppDeregister * * Description This function is called to deregister an application * from BTA GATTC module. * * Parameters client_if - client interface identifier. * * Returns None * ******************************************************************************/ extern void BTA_GATTC_AppDeregister(tBTA_GATTC_IF client_if); /******************************************************************************* * * Function BTA_GATTC_Open * * Description Open a direct connection or add a background auto connection * bd address * * Parameters client_if: server interface. * remote_bda: remote device BD address. * is_direct: direct connection or background auto connection * initiating_phys: LE PHY to use, optional * ******************************************************************************/ extern void BTA_GATTC_Open(tBTA_GATTC_IF client_if, BD_ADDR remote_bda, bool is_direct, tBTA_GATT_TRANSPORT transport, bool opportunistic); extern void BTA_GATTC_Open(tBTA_GATTC_IF client_if, BD_ADDR remote_bda, bool is_direct, tBTA_GATT_TRANSPORT transport, bool opportunistic, uint8_t initiating_phys); /******************************************************************************* * * Function BTA_GATTC_CancelOpen * * Description Open a direct connection or add a background auto connection * bd address * * Parameters client_if: server interface. * remote_bda: remote device BD address. * is_direct: direct connection or background auto connection * * Returns void * ******************************************************************************/ extern void BTA_GATTC_CancelOpen(tBTA_GATTC_IF client_if, BD_ADDR remote_bda, bool is_direct); /******************************************************************************* * * Function BTA_GATTC_Close * * Description Close a connection to a GATT server. * * Parameters conn_id: connectino ID to be closed. * * Returns void * ******************************************************************************/ extern void BTA_GATTC_Close(uint16_t conn_id); /******************************************************************************* * * Function BTA_GATTC_ServiceSearchRequest * * Description This function is called to request a GATT service discovery * on a GATT server. This function report service search result * by a callback event, and followed by a service search * complete event. * * Parameters conn_id: connection ID. * p_srvc_uuid: a UUID of the service application is interested * in. If Null, discover for all services. * * Returns None * ******************************************************************************/ extern void BTA_GATTC_ServiceSearchRequest(uint16_t conn_id, tBT_UUID* p_srvc_uuid); /** * This function is called to send "Find service by UUID" request. Used only for * PTS tests. */ extern void BTA_GATTC_DiscoverServiceByUuid(uint16_t conn_id, tBT_UUID* p_srvc_uuid); /******************************************************************************* * * Function BTA_GATTC_GetServices * * Description This function is called to find the services on the given * server. * * Parameters conn_id: connection ID which identify the server. * * Returns returns list_t of tBTA_GATTC_SERVICE or NULL. * ******************************************************************************/ extern const list_t* BTA_GATTC_GetServices(uint16_t conn_id); /******************************************************************************* * * Function BTA_GATTC_GetCharacteristic * * Description This function is called to find the characteristic on the * given server. * * Parameters conn_id: connection ID which identify the server. * handle: characteristic handle * * Returns returns pointer to tBTA_GATTC_CHARACTERISTIC or NULL. * ******************************************************************************/ extern const tBTA_GATTC_CHARACTERISTIC* BTA_GATTC_GetCharacteristic( uint16_t conn_id, uint16_t handle); /******************************************************************************* * * Function BTA_GATTC_GetDescriptor * * Description This function is called to find the characteristic on the * given server. * * Parameters conn_id: connection ID which identify the server. * handle: descriptor handle * * Returns returns pointer to tBTA_GATTC_DESCRIPTOR or NULL. * ******************************************************************************/ extern const tBTA_GATTC_DESCRIPTOR* BTA_GATTC_GetDescriptor(uint16_t conn_id, uint16_t handle); /******************************************************************************* * * Function BTA_GATTC_GetGattDb * * Description This function is called to get gatt db. * * Parameters conn_id: connection ID which identify the server. * db: output parameter which will contain gatt db copy. * Caller is responsible for freeing it. * count: number of elements in db. * ******************************************************************************/ extern void BTA_GATTC_GetGattDb(uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, btgatt_db_element_t** db, int* count); typedef void (*GATT_READ_OP_CB)(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, uint16_t len, uint8_t* value, void* data); typedef void (*GATT_WRITE_OP_CB)(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, void* data); /******************************************************************************* * * Function BTA_GATTC_ReadCharacteristic * * Description This function is called to read a characteristics value * * Parameters conn_id - connectino ID. * handle - characteritic handle to read. * * Returns None * ******************************************************************************/ void BTA_GATTC_ReadCharacteristic(uint16_t conn_id, uint16_t handle, tBTA_GATT_AUTH_REQ auth_req, GATT_READ_OP_CB callback, void* cb_data); /** * This function is called to read a value of characteristic with uuid equal to * |uuid| */ void BTA_GATTC_ReadUsingCharUuid(uint16_t conn_id, tBT_UUID uuid, uint16_t s_handle, uint16_t e_handle, tBTA_GATT_AUTH_REQ auth_req, GATT_READ_OP_CB callback, void* cb_data); /******************************************************************************* * * Function BTA_GATTC_ReadCharDescr * * Description This function is called to read a descriptor value. * * Parameters conn_id - connection ID. * handle - descriptor handle to read. * * Returns None * ******************************************************************************/ void BTA_GATTC_ReadCharDescr(uint16_t conn_id, uint16_t handle, tBTA_GATT_AUTH_REQ auth_req, GATT_READ_OP_CB callback, void* cb_data); /******************************************************************************* * * Function BTA_GATTC_WriteCharValue * * Description This function is called to write characteristic value. * * Parameters conn_id - connection ID. * handle - characteristic handle to write. * write_type - type of write. * value - the value to be written. * * Returns None * ******************************************************************************/ void BTA_GATTC_WriteCharValue(uint16_t conn_id, uint16_t handle, tBTA_GATTC_WRITE_TYPE write_type, vector<uint8_t> value, tBTA_GATT_AUTH_REQ auth_req, GATT_WRITE_OP_CB callback, void* cb_data); /******************************************************************************* * * Function BTA_GATTC_WriteCharDescr * * Description This function is called to write descriptor value. * * Parameters conn_id - connection ID * handle - descriptor handle to write. * value - the value to be written. * * Returns None * ******************************************************************************/ void BTA_GATTC_WriteCharDescr(uint16_t conn_id, uint16_t handle, vector<uint8_t> value, tBTA_GATT_AUTH_REQ auth_req, GATT_WRITE_OP_CB callback, void* cb_data); /******************************************************************************* * * Function BTA_GATTC_SendIndConfirm * * Description This function is called to send handle value confirmation. * * Parameters conn_id - connection ID. * handle - characteristic handle to confirm. * * Returns None * ******************************************************************************/ extern void BTA_GATTC_SendIndConfirm(uint16_t conn_id, uint16_t handle); /******************************************************************************* * * Function BTA_GATTC_RegisterForNotifications * * Description This function is called to register for notification of a * service. * * Parameters client_if - client interface. * remote_bda - target GATT server. * handle - GATT characteristic handle. * * Returns OK if registration succeed, otherwise failed. * ******************************************************************************/ extern tBTA_GATT_STATUS BTA_GATTC_RegisterForNotifications( tBTA_GATTC_IF client_if, const BD_ADDR remote_bda, uint16_t handle); /******************************************************************************* * * Function BTA_GATTC_DeregisterForNotifications * * Description This function is called to de-register for notification of a * service. * * Parameters client_if - client interface. * remote_bda - target GATT server. * handle - GATT characteristic handle. * * Returns OK if deregistration succeed, otherwise failed. * ******************************************************************************/ extern tBTA_GATT_STATUS BTA_GATTC_DeregisterForNotifications( tBTA_GATTC_IF client_if, const BD_ADDR remote_bda, uint16_t handle); /******************************************************************************* * * Function BTA_GATTC_PrepareWrite * * Description This function is called to prepare write a characteristic * value. * * Parameters conn_id - connection ID. * handle - GATT characteritic handle. * offset - offset of the write value. * value - the value to be written. * * Returns None * ******************************************************************************/ extern void BTA_GATTC_PrepareWrite(uint16_t conn_id, uint16_t handle, uint16_t offset, vector<uint8_t> value, tBTA_GATT_AUTH_REQ auth_req, GATT_WRITE_OP_CB callback, void* cb_data); /******************************************************************************* * * Function BTA_GATTC_ExecuteWrite * * Description This function is called to execute write a prepare write * sequence. * * Parameters conn_id - connection ID. * is_execute - execute or cancel. * * Returns None * ******************************************************************************/ extern void BTA_GATTC_ExecuteWrite(uint16_t conn_id, bool is_execute); /******************************************************************************* * * Function BTA_GATTC_ReadMultiple * * Description This function is called to read multiple characteristic or * characteristic descriptors. * * Parameters conn_id - connectino ID. * p_read_multi - read multiple parameters. * * Returns None * ******************************************************************************/ extern void BTA_GATTC_ReadMultiple(uint16_t conn_id, tBTA_GATTC_MULTI* p_read_multi, tBTA_GATT_AUTH_REQ auth_req); /******************************************************************************* * * Function BTA_GATTC_Refresh * * Description Refresh the server cache of the remote device * * Parameters remote_bda: remote device BD address. * * Returns void * ******************************************************************************/ extern void BTA_GATTC_Refresh(const bt_bdaddr_t& remote_bda); /******************************************************************************* * * Function BTA_GATTC_ConfigureMTU * * Description Configure the MTU size in the GATT channel. This can be done * only once per connection. * * Parameters conn_id: connection ID. * mtu: desired MTU size to use. * * Returns void * ******************************************************************************/ extern void BTA_GATTC_ConfigureMTU(uint16_t conn_id, uint16_t mtu); /******************************************************************************* * BTA GATT Server API ******************************************************************************/ /******************************************************************************* * * Function BTA_GATTS_Init * * Description This function is called to initalize GATTS module * * Parameters None * * Returns None * ******************************************************************************/ extern void BTA_GATTS_Init(); /******************************************************************************* * * Function BTA_GATTS_Disable * * Description This function is called to disable GATTS module * * Parameters None. * * Returns None * ******************************************************************************/ extern void BTA_GATTS_Disable(void); /******************************************************************************* * * Function BTA_GATTS_AppRegister * * Description This function is called to register application callbacks * with BTA GATTS module. * * Parameters p_app_uuid - applicaiton UUID * p_cback - pointer to the application callback function. * * Returns None * ******************************************************************************/ extern void BTA_GATTS_AppRegister(tBT_UUID* p_app_uuid, tBTA_GATTS_CBACK* p_cback); /******************************************************************************* * * Function BTA_GATTS_AppDeregister * * Description De-register with BTA GATT Server. * * Parameters server_if: server interface * * Returns void * ******************************************************************************/ extern void BTA_GATTS_AppDeregister(tBTA_GATTS_IF server_if); /******************************************************************************* * * Function BTA_GATTS_AddService * * Description Add the given |service| and all included elements to the * GATT database. a |BTA_GATTS_ADD_SRVC_EVT| is triggered to * report the status and attribute handles. * * Parameters server_if: server interface. * service: pointer to vector describing service. * * Returns Returns |BTA_GATT_OK| on success or |BTA_GATT_ERROR| if the * service cannot be added. * ******************************************************************************/ extern uint16_t BTA_GATTS_AddService(tBTA_GATTS_IF server_if, vector<btgatt_db_element_t>& service); /******************************************************************************* * * Function BTA_GATTS_DeleteService * * Description This function is called to delete a service. When this is * done, a callback event BTA_GATTS_DELETE_EVT is report with * the status. * * Parameters service_id: service_id to be deleted. * * Returns returns none. * ******************************************************************************/ extern void BTA_GATTS_DeleteService(uint16_t service_id); /******************************************************************************* * * Function BTA_GATTS_StopService * * Description This function is called to stop a service. * * Parameters service_id - service to be topped. * * Returns None * ******************************************************************************/ extern void BTA_GATTS_StopService(uint16_t service_id); /******************************************************************************* * * Function BTA_GATTS_HandleValueIndication * * Description This function is called to read a characteristics * descriptor. * * Parameters conn_id - connection identifier. * attr_id - attribute ID to indicate. * value - data to indicate. * need_confirm - if this indication expects a confirmation or * not. * * Returns None * ******************************************************************************/ extern void BTA_GATTS_HandleValueIndication(uint16_t conn_id, uint16_t attr_id, vector<uint8_t> value, bool need_confirm); /******************************************************************************* * * Function BTA_GATTS_SendRsp * * Description This function is called to send a response to a request. * * Parameters conn_id - connection identifier. * trans_id - transaction ID. * status - response status * p_msg - response data. * * Returns None * ******************************************************************************/ extern void BTA_GATTS_SendRsp(uint16_t conn_id, uint32_t trans_id, tBTA_GATT_STATUS status, tBTA_GATTS_RSP* p_msg); /******************************************************************************* * * Function BTA_GATTS_Open * * Description Open a direct open connection or add a background auto * connection bd address * * Parameters server_if: server interface. * remote_bda: remote device BD address. * is_direct: direct connection or background auto connection * * Returns void * ******************************************************************************/ extern void BTA_GATTS_Open(tBTA_GATTS_IF server_if, BD_ADDR remote_bda, bool is_direct, tBTA_GATT_TRANSPORT transport); /******************************************************************************* * * Function BTA_GATTS_CancelOpen * * Description Cancel a direct open connection or remove a background auto * connection bd address * * Parameters server_if: server interface. * remote_bda: remote device BD address. * is_direct: direct connection or background auto connection * * Returns void * ******************************************************************************/ extern void BTA_GATTS_CancelOpen(tBTA_GATTS_IF server_if, BD_ADDR remote_bda, bool is_direct); /******************************************************************************* * * Function BTA_GATTS_Close * * Description Close a connection a remote device. * * Parameters conn_id: connectino ID to be closed. * * Returns void * ******************************************************************************/ extern void BTA_GATTS_Close(uint16_t conn_id); #endif /* BTA_GATT_API_H */
huanghongxun/ACM
vijos/NOIP/2013/match.cpp
#include <cstdio> #include <cstdio> #include <cstring> #define N 100005 typedef long long ll; int global_count; int num = 0; void merge(int ar[],int low,int mid,int high) { int* b = new int[high + 1]; for (int i = low;i <= high;++i) { b[i] = ar[i]; } int i = low,j = mid + 1,k = low; while (i <= mid&&j <= high) { if (b[i] <= b[j]) { ar[k++] = b[i++]; } else { ar[k++] = b[j++]; global_count += mid - i + 1; } } while (i <= mid) { ar[k++] = b[i++]; } while (j <= high){ ar[k++] = b[j++]; } delete []b; } void merge_sort(int ar[],int low,int high) { if (low < high) { int mid = low + (high - low)/2; merge_sort(ar,low,mid); merge_sort(ar,mid + 1,high); merge(ar,low,mid,high); } } int main() { int n; int a[N], b[N], c[N]; int i; scanf("%d", &n); for(i=0;i<n;i++) scanf("%d",&a[i]); for(i=0;i<n;i++) scanf("%d",&b[i]); global_count = 0; merge_sort(a,0,n-1); merge_sort(b,0,n-1); printf("%d",global_count); return 0; }
yumuzi234/e8vm
pl/codegen/vtable.go
<gh_stars>0 package codegen import "fmt" type vtable struct { // interface name: pkg.interface i string // struct name:pkg.structName // sName can used for reflection s string // entries will be sorted by func names entries []*FuncSym } func newVtable(i, s string) *vtable { return &vtable{ i: i, s: s, entries: make([]*FuncSym, 0), } } func (t *vtable) String() string { return fmt.Sprintf("<vTable %s %s>", t.i, t.s) } func (t *vtable) RegSizeAlign() bool { return true } func (t *vtable) Size() int32 { return regSize * 2 } func (t *vtable) fill(fs []*FuncSym) { t.entries = append(t.entries, fs...) } type vtablePool struct { pkg string vtables []*vtable } func newVtablePool(pkg string) *vtablePool { return &vtablePool{ pkg: pkg, vtables: make([]*vtable, 0), } } func (p *vtablePool) addTable(i, s string) Ref { t := newVtable(i, s) p.vtables = append(p.vtables, t) return t }
bianapis/sd-customer-workbench-v2.0
src/main/java/org/bian/dto/BQBrowsingRetrieveInputModelBrowsingInstanceAnalysis.java
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; /** * BQBrowsingRetrieveInputModelBrowsingInstanceAnalysis */ public class BQBrowsingRetrieveInputModelBrowsingInstanceAnalysis { private String browsingInstanceAnalysisReference = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the control record instance analysis view * @return browsingInstanceAnalysisReference **/ public String getBrowsingInstanceAnalysisReference() { return browsingInstanceAnalysisReference; } public void setBrowsingInstanceAnalysisReference(String browsingInstanceAnalysisReference) { this.browsingInstanceAnalysisReference = browsingInstanceAnalysisReference; } }
admariner/gtin-cloud
src/websiteVendors.js
<gh_stars>10-100 import got from 'got' import cheerio from 'cheerio' import gtinPath from './gtinPath' import rua from 'random-useragent' import scrapeIt from 'scrape-it' import storeTasks from './storeTasks' const debug = require('debug')('gtin-cloud') const scriptReg = /<(script|style)\b[^<]*(?:(?!<\/(script|style)>)<[^<]*)*<\/(script|style)>/gi const getGoogleProductId = async (gtin) => { try { const url = `https://www.google.com/search?tbm=shop&tbs=vw:l,new:1&q=${gtin}` const rst = await got.get(url, { headers: { 'User-Agent': rua.getRandom(ua => ua.browserName === 'Firefox'), 'Accept': 'text/html', 'Accept-Language': 'en-US' } }) const re = /<a[^>]+href="\/shopping\/product\/([^"]+)+"[^>]*>/g const bd = rst.body.replace(scriptReg, '') const m = re.exec(bd) if (m[1] && m[1].indexOf('?') > 0) { return m[1] } // console.log(bd) debug(bd) return null } catch(e) { // console.log(e) debug(JSON.stringify(e, null, 2)) return null } } const scrapeGoogleShopping = async (shopUrl) => { try { // we want the biggest image possible, otherwise add '/specs' to url // to get product Nutritions, Brand, etc.. const url = `https://www.google.com/shopping/product/${shopUrl}` const rst = await got.get(url, { headers: { 'User-Agent': rua.getRandom(ua => ua.browserName === 'Firefox'), 'Accept': 'text/html', 'Accept-Language': 'en-US' } }) // remove script and style tags to help cheerio const bd = rst.body.replace(scriptReg, '') const $ = cheerio.load(bd) const opts = { name: 'title', description: { selector: 'meta[name="description"]', attr: 'content' }, image_url: { selector: '.main-image img', attr: 'src' } } const obj = scrapeIt.scrapeHTML($, opts) obj.url = url obj.name = obj.name.replace('| Google Shopping', '').trim() // try a different query if (!obj.image_url) { const img = $('#pp-altimg-init-main > img') // console.log(img.html()) obj.image_url = img.attr('src') } return obj } catch(e) { // console.log(e) debug(JSON.stringify(e, null, 2)) return null } } const convertGtinToAsin = async (gtin) => { try { // TODO: fix this const url = `https://some.service.that.convert.gtin.to.asin/${gtin}` const rst = await got.get(url, { headers: { 'User-Agent': rua.getRandom(ua => ua.browserName === 'Firefox'), 'Accept': 'text/html', 'Accept-Language': 'en-US' } }) return rst.body } catch(e) { // console.log(e) debug(JSON.stringify(e, null, 2)) return null } } const scrapeAmazon = async (asin) => { try { // we want the biggest image possible, otherwise add '/specs' to url // to get product Nutritions, Brand, etc.. const url = `https://www.amazon.com/dp/${asin}` const rst = await got.get(url, { headers: { 'User-Agent': rua.getRandom(ua => ua.browserName === 'Firefox'), 'Accept': 'text/html', 'Accept-Language': 'en-US' } }) const $ = cheerio.load(rst.body) const opts = { title: '#productTitle', sale_price: 'tr#priceblock_ourprice_row td.a-span12 span#priceblock_ourprice', sale_price_desc: 'tr#priceblock_ourprice_row span.a-size-small.a-color-price', deal_price: 'span#priceblock_dealprice', seller_price: { selector: 'div#toggleBuyBox span.a-color-price', convert: x => { if (x.charAt(0) === '$') { return x.slice(1); } return x; } }, mrpp: 'div#price span.a-text-strike', savings: 'tr#regularprice_savings td.a-span12.a-color-price.a-size-base', brand: 'div#bylineInfo_feature_div a#bylineInfo', vat: 'tr#vatMessage', availiability: 'div#availability', vnv: 'div#vnv-container', features: { listItem: 'div#feature-bullets ul li', name: 'features', data: { feature: 'span.a-list-item' } }, images: { listItem: 'div#imageBlock div#altImages ul li', name: 'altImages', data: { url: { selector: 'img', attr: 'src', convert: x => x.replace(/_[S][A-Z][0-9][0-9]_./g, '') } } }, brand_url: { selector: 'div#bylineInfo_feature_div a#bylineInfo', attr: 'href' }, image_url: { selector: 'img#landingImage', attr: 'src' } } const obj = scrapeIt.scrapeHTML($, opts) obj.url = url obj.asin = asin return obj } catch(e) { // console.log(e) debug(JSON.stringify(e, null, 2)) return null } } class Handlers { static async amazonRequest(gtin, storeData = false, imageUrl = null) { try { const asin = await convertGtinToAsin(gtin) let obj = null if (asin && asin.length > 0) { obj = await scrapeAmazon(asin) obj.gtin = gtin obj.gtin_path = gtinPath(gtin) obj._ts = (new Date()).toISOString() obj.image = imageUrl || obj.image_url if (storeData) { // stash the data and image const rsp = storeTasks(gtin, obj.image, 'image', obj, 'amazonweb') if (rsp.tasks) { await Promise.all(rsp.tasks) } } } else { return `${gtin} not found` } debug(`completed ${gtin}`) return obj } catch (e) { debug(JSON.stringify(e, null, 2)) return { error: 'request error' } } } static async googleshoppingRequest(gtin, storeData = false, imageUrl = null) { try { // convert gtin to asin const shopUrl = await getGoogleProductId(gtin) let obj = null if (shopUrl && shopUrl.length > 0) { obj = await scrapeGoogleShopping(shopUrl) obj.gtin = gtin obj.gtin_path = gtinPath(gtin) obj._ts = (new Date()).toISOString() obj.image = imageUrl || obj.image_url if (storeData) { // stash the data and image const rsp = storeTasks(gtin, obj.image, 'image', obj, 'googleshopping') if (rsp.tasks) { await Promise.all(rsp.tasks) } } } else { return `${gtin} not found with url https://www.google.com/shopping/product/${shopUrl}` } debug(`completed ${gtin}`) return obj } catch (e) { debug(JSON.stringify(e, null, 2)) return { error: 'request error' } } } } export default Handlers
evandojunior/urbem3.0
src/Urbem/RecursosHumanosBundle/Resources/public/javascripts/estagio/estagiario.js
<reponame>evandojunior/urbem3.0<gh_stars>0 (function() { 'use strict'; var populateSelect = function (select, data, prop) { var firstOption = select.find('option:first-child'); select.empty().append(firstOption); $.each(data, function (index, item) { var option = $('<option>', {value: item[prop.value], text: item[prop.text]}); select.append(option); }); $('select').material_select(); }; var calculaBolsa = function () { if ($('#estagiario_estagio_estagiarioEstagioBolsa_0_vlBolsa').val() > 0){ var faltas = $('#estagiario_estagio_estagiarioEstagioBolsa_0_faltas').val(); if(((faltas) > 0) && (faltas <= 30)) { var valorBolsaAtual = $('#estagiario_estagio_estagiarioEstagioBolsa_0_vlBolsa').val(); $('#novoValorBolsa').val((valorBolsaAtual - ((valorBolsaAtual / 30) * faltas).toFixed(2)).formatMoney('2','.',',')); $('#novoValor').css("display", "block"); }else{ $('#novoValor').css("display", "none"); $('#novoValorBolsa').val('0'); } } } $('#estagiario_estagio_estagiarioEstagioBolsa_0_faltas') .parent('div') .append('<div id="novoValor" style="display:none">' + '<label class="control-label label-rh required active" for="novoValorBolsa">Novo Valor da Bolsa</label>' + '<input type="text" name="novoValorBolsa" id="novoValorBolsa" class="white input-rh browser-default"/>' + '</div>'); $('#estagiario_estagio_cgmInstituicaoEnsino').on('change', function () { var selectedOption = $(this).find('option:selected'), selectTarget = $('#estagiario_estagio_codGrau'); $.ajax({ url: '/recursos-humanos/estagio/estagiario/consultar-grau', method: 'POST', data: { instituicao_ensino: selectedOption.val() }, dataType: 'json', success: function (data) { populateSelect(selectTarget, data, {value: 'cod_grau', text: 'descricao'}); } }); }); $('#estagiario_estagio_codGrau').on('change', function() { var selectedOptionGrau = $(this).find('option:selected'), selectedOptionInstituicao = $('select#estagiario_estagio_cgmInstituicaoEnsino option:selected'), selectTarget = $('#estagiario_estagio_codCurso'); $.ajax({ url: '/recursos-humanos/estagio/estagiario/consultar-curso', method: 'POST', data: { grau: selectedOptionGrau.val(), instituicao_ensino: selectedOptionInstituicao.val() }, dataType: 'json', success: function (data) { populateSelect(selectTarget, data, {value: 'cod_curso', text: 'nom_curso'}); } }); }); $("input[id^='estagiario_estagio_vinculoEstagio']").on('change', function () { }) $('#estagiario_estagio_cgmEstagiario').on('change', function() { var selectedOption = $(this).find('option:selected'); $.ajax({ url: '/recursos-humanos/estagio/estagiario/consultar-cgm', method: 'POST', data: { cgm: selectedOption.val() }, dataType: 'json', success: function (data) { $("#estagiario_estagio_rg").val(data['rg']); $("#estagiario_estagio_cpf").val(data['cpf']); $("#estagiario_estagio_endereco").val(data['endereco']); $("#estagiario_estagio_telefoneFixo").val(data['telefone']); $("#estagiario_estagio_telefoneCelular").val(data['celular']); } }) }); $('#estagiario_estagio_codEntitidadeIntermediadora').on('change', function() { var selectedOption = $(this).find('option:selected'), selectTarget = $("#estagiario_estagio_cgmInstituicaoEnsino"); $.ajax({ url: '/recursos-humanos/estagio/entidade-intermediadora/consultar-instituicoes', method: 'POST', data: { entidade_intermediadora: selectedOption.val() }, dataType: 'json', success: function (data) { populateSelect(selectTarget, data, {value: 'id', text: 'cgm'}); } }) }); $('#estagiario_estagio_codCurso').on('change', function() { var selectedOption = $(this).find('option:selected'); $.ajax({ url: '/recursos-humanos/estagio/estagiario/consultar-curso-valor', method: 'POST', data: { cgm: selectedOption.val() }, dataType: 'json', success: function (data) { $("#estagiario_estagio_estagiarioEstagioBolsa_0_vlBolsa").val(data['vl_bolsa']); $("#estagiario_estagio_estagiarioEstagioBolsa_0_faltas").val('0'); } }) }); $( "#estagiario_estagio_estagiarioEstagioBolsa_0_faltas" ).bind( "keyup", function() { calculaBolsa(); }); $( "#estagiario_estagio_estagiarioEstagioBolsa_0_vlBolsa" ).bind( "keyup", function() { calculaBolsa(); }); $( "#estagiario_estagio_codOrgao" ).on( "change", function() { var orgao = $(this).find('option:selected').val(); var classificacao = $('#estagiario_estagio_classificacao'); var arrClassificacao = classificacao.val().split('.'); arrClassificacao[0] = orgao; if(orgao == ''){ arrClassificacao[0] = '0'; } classificacao.val(arrClassificacao.join('.')); }); $( "#estagiario_estagio_codGrade" ).on( "change", function() { var selectedOption = $(this).find('option:selected'); $.ajax({ url: '/recursos-humanos/estagio/estagiario/consultar-grade', method: 'POST', data: { grade: selectedOption.val() }, dataType: 'json', success: function (data) { if(selectedOption.val() == ''){ $('#mostraGrade').html(''); return; } var table = $('<table/>', { }); var theader = $('<thead/>').appendTo(table); var title = $('<tr/>', {}).appendTo(theader); $('<th/>').html('Dia').appendTo(title); $('<th/>').html('Horário de Entrada').appendTo(title); $('<th/>').html('Horário de Saída').appendTo(title); $('<th/>').html('Horário de Entrada2').appendTo(title); $('<th/>').html('Horário de Saída2').appendTo(title); var tbody = $('<tbody/>').appendTo(table); for (var i = 0; i < data.length; i++) { var row = $('<tr/>', {}).appendTo(tbody); $('<td/>').html(data[i].nom_dia).appendTo(row); $('<td/>').html(data[i].hora_entrada).appendTo(row); $('<td/>').html(data[i].hora_saida).appendTo(row); $('<td/>').html(data[i].hora_entrada_2).appendTo(row); $('<td/>').html(data[i].hora_saida_2).appendTo(row); } $('#mostraGrade').html(table); } }) }); $("input[name='estagiario_estagio[vinculoEstagio]'").on('change', function () { if ($(this).val() == "e") { $('#codEntitidadeIntermediadoraContainer').removeClass('hide'); $('select').material_select(); } else if ($(this).val() == "i") { $('#codEntitidadeIntermediadoraContainer').addClass('hide'); } }); $('select').material_select(); }());
juanfelipe82193/opensap
sapui5-sdk-1.74.0/test-resources/sap/suite/ui/commons/demokit/sample/ImageEditorCircleCrop/ImageEditorContainer.controller.js
sap.ui.define([ "sap/ui/core/mvc/Controller", "sap/m/library", "sap/suite/ui/commons/library", "sap/m/Dialog", "sap/m/Button", "sap/suite/ui/commons/imageeditor/ImageEditor" ], function (Controller, MLibrary, SuiteLibrary, Dialog, Button, ImageEditor) { "use strict"; var ButtonType = MLibrary.ButtonType, ImageEditorMode = SuiteLibrary.ImageEditorMode; var oPageController = Controller.extend("sap.suite.ui.commons.sample.ImageEditorCircleCrop.ImageEditorContainer", { onPress: function () { if (!this.oDialog) { var that = this; this._oImageEditor = new ImageEditor({ src: sap.ui.require.toUrl("sap/m/sample/") + "../../images/demo/nature/ALotOfElephants.jpg", scaleCropArea: true }); this.oDialog = new Dialog({ title: 'Circual cropping', contentWidth: "700px", contentHeight: "500px", verticalScrolling: false, content: [ this._oImageEditor ], beginButton: new Button({ text: 'Apply crop', type: ButtonType.Emphasized, press: function () { var oResultImage = that.getView().byId("croppedImage"); that._oImageEditor.applyVisibleCrop(); oResultImage.setSrc(that._oImageEditor.getImagePngDataURL()); this.oDialog.close(); }.bind(this) }), endButton: new Button({ text: 'Close', press: function () { this.oDialog.close(); }.bind(this) }), afterOpen: function() { that._oImageEditor.zoomToFit(); that._oImageEditor.setMode(ImageEditorMode.CropEllipse); that._oImageEditor.setCropAreaByRatio(1, 1); } }); } this.oDialog.open(); } }); return oPageController; });
sillywalk/grazz
tests/binutils-2.30/src/ld/testsuite/ld-x86-64/copyreloc-lib.c
<gh_stars>1-10 int a_glob = 2;
gwh111/UITemplateApp
UITemplateApp/Pods/bench_ios/bench_ios/bench/CC_Foundation/CC_Foundation.h
// // CC_Foundation.h // testbenchios // // Created by gwh on 2019/7/29. // Copyright © 2019 gwh. All rights reserved. // //#ifndef CC_Foundation_h //#define CC_Foundation_h #import <Foundation/Foundation.h> #import "CC_CoreFoundation.h" #import "CC_Money.h" #import "CC_Model.h" #import "CC_CoreTimer.h" #import "CC_CoreThread.h" #import "CC_Lib+NSString.h" #import "CC_Lib+NSArray.h" #import "CC_Lib+NSDictionary.h" #import "CC_Lib+NSObject.h" #import "CC_Lib+NSDate.h" #import "CC_Lib+NSData.h" //#endif /* CC_Foundation_h */
daileyet/webpage-keeper
src/main/java/com/openthinks/others/webpages/transfer/BatchHtmlPageTransfer.java
package com.openthinks.others.webpages.transfer; import java.io.File; import com.gargoylesoftware.htmlunit.html.HtmlPage; /** * add common folder for common resource * * @author <EMAIL> * */ public class BatchHtmlPageTransfer extends HtmlPageTransfer { public static final String COMMON_RESOURCE_DIR = "common"; private File commonDir = null; private BatchHtmlPageTransfer(HtmlPage htmlPage, File keepDir) { super(htmlPage, keepDir); this.commonDir = new File(keepDir.getParentFile(), COMMON_RESOURCE_DIR); } public static BatchHtmlPageTransfer create(HtmlPage htmlPage, File keepDir) { return new BatchHtmlPageTransfer(htmlPage, keepDir); } @Override public File getJsKeepDir() { return new File(commonDir, RESOURCE_SCRIPT_DIR); } @Override public String getJsPath() { return "../common/" + RESOURCE_SCRIPT_DIR; } @Override public File getCssKeepDir() { return new File(commonDir, RESOURCE_STYLE_DIR); } @Override public String getCssPath() { return "../common/" + RESOURCE_STYLE_DIR; } }
myflytop/ruoyi-cms
ruoyi-cms/cms-blog/blog-admin/src/main/java/com/ruoyi/cms/system/service/ICmsCatService.java
<filename>ruoyi-cms/cms-blog/blog-admin/src/main/java/com/ruoyi/cms/system/service/ICmsCatService.java package com.ruoyi.cms.system.service; import com.ruoyi.cms.system.model.po.CmsCat; import com.ruoyi.cms.system.model.vo.CatCountVo; import com.ruoyi.common.core.domain.Ztree; import org.apache.ibatis.annotations.Param; import java.util.List; public interface ICmsCatService { /** * 添加类目 * @param cmsCat * @return */ int insertCmsCat(CmsCat cmsCat); /** * 批量添加类目 * @param cmsCats * @return */ int insertCmsCats(List<CmsCat> cmsCats); /** * 修改类目 * @param cmsCat * @return */ int updateCmsCat(CmsCat cmsCat); /** * 删除单个类目导航 * @param catId * @return */ int deleteCmsCatById(Long catId); /** * 获取列表 * @param cmsCat * @return */ List<CmsCat> listCmsCatByCat(CmsCat cmsCat); /** * 获取没有隐藏的列表 * @return */ List<CmsCat> listCmsCat(); /** * 获取没有隐藏的列表 带文章统计 * @param cmsCat * @return */ List<CatCountVo> listCatCountVoByCat(CmsCat cmsCat); /** * 获取没有隐藏的列表 带文章统计 * @return */ List<CatCountVo> listCatCountVo(); /** * 获取一条类目 所有字段 * @param catId * @return */ CmsCat getCmsCatById(Long catId); /** * 获取目录树 * @param b 1目录 0非目录 * @return */ List<Ztree> catTreeData(Byte b); /** * 获取类目子列表 所有字段 * @param parentId * @return */ List<CmsCat> listCmsCatByParentId(Long parentId); /** * 获取类目名 * @param catId * @return */ String getCatNameById(Long catId); /** * 统计是否存在子节点的 * @param parentId * @return */ int countCatByParentId(Long parentId); /** * 验证同类目下类目名唯一 * @param cmsCat * @return */ String checkCatNameUnique(CmsCat cmsCat); /** * 验证路径 * @param cmsCat * @return */ String checkCatUrlUnique( CmsCat cmsCat); /** * 统计关联文章 * @param catId * @return */ int countArticleByCatId(Long catId); /** * 获取类目列表通过文章id * 文章关联类目 * @param articleId * @return */ List<CmsCat> listCmsCatByArticleTagId(Long articleId); int updateTagVisible(Long catId, Byte visible); }
halfbaked/gapic-generator-java
test/integration/goldens/iam/com/google/iam/v1/package-info.java
<reponame>halfbaked/gapic-generator-java<filename>test/integration/goldens/iam/com/google/iam/v1/package-info.java /* * Copyright 2021 Google LLC * * 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://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. */ /** * The interfaces provided are listed below, along with usage samples. * * <p>======================= IAMPolicyClient ======================= * * <p>Service Description: ## API Overview * * <p>Manages Identity and Access Management (IAM) policies. * * <p>Any implementation of an API that offers access control features implements the * google.iam.v1.IAMPolicy interface. * * <p>## Data model * * <p>Access control is applied when a principal (user or service account), takes some action on a * resource exposed by a service. Resources, identified by URI-like names, are the unit of access * control specification. Service implementations can choose the granularity of access control and * the supported permissions for their resources. For example one database service may allow access * control to be specified only at the Table level, whereas another might allow access control to * also be specified at the Column level. * * <p>## Policy Structure * * <p>See google.iam.v1.Policy * * <p>This is intentionally not a CRUD style API because access control policies are created and * deleted implicitly with the resources to which they are attached. * * <p>Sample for IAMPolicyClient: * * <pre>{@code * try (IAMPolicyClient iAMPolicyClient = IAMPolicyClient.create()) { * SetIamPolicyRequest request = * SetIamPolicyRequest.newBuilder() * .setResource("resource-341064690") * .setPolicy(Policy.newBuilder().build()) * .build(); * Policy response = iAMPolicyClient.setIamPolicy(request); * } * }</pre> */ @Generated("by gapic-generator-java") package com.google.iam.v1; import javax.annotation.Generated;
josephhyatt/learn_co
orm-mapping-to-table-lab-v-000/config/environment.rb
require 'bundler' Bundler.require require_relative '../lib/student' DB = {:conn => SQLite3::Database.new("db/students.db")}
talsewell/cerberus
tests/suite/constraints/assignment_in_constant_expression.c
int global_1 = 0; int global_2 = sizeof (global_1++); int global_3 = global_1++; int main (void) { return global_3; }
chs6558/chs6558.github.io
node_modules/styled-icons/boxicons-solid/Server/Server.esm.js
<filename>node_modules/styled-icons/boxicons-solid/Server/Server.esm.js export * from '@styled-icons/boxicons-solid/Server';
alexstrive/Ifmo-Works
Algorithms/Work 4/taskB.cpp
<reponame>alexstrive/Ifmo-Works #include <fstream> #include <vector> using namespace std; struct Node { int key, left, right; }; // Особый порядок прохода дерева // В результате получаем условно остортировнаный по неубыванию массив ключей void inorderTreeWalk(vector<Node> &tree, vector<int> &keys, int root) { // Выход, если узла не существует if (root == -1) { return; } // Спуск влево inorderTreeWalk(tree, keys, tree[root].left); keys.push_back(tree[root].key); // Спуск вправо inorderTreeWalk(tree, keys, tree[root].right); } // Проверка массива на отсортированность по неубыванию bool isSorted(vector<int> &keys) { for (int i = 0; i < keys.size() - 1; i++) { if (keys[i] >= keys[i + 1]) { return false; } } return true; } // Является ли массив двоичным деревом поиска bool isBST(vector<Node> &tree) { vector<int> keys; inorderTreeWalk(tree, keys, 0); return isSorted(keys); } int main() { ifstream input("check.in"); int numberNodes; vector<Node> tree; input >> numberNodes; for (int i = 0; i < numberNodes; i++) { int key, left, right; input >> key >> left >> right; // Уменьшаем на единицу индексы левого и правого дочернего узла // Чтобы использовать их в дальнейшем tree.push_back({key, left - 1, right - 1}); } ofstream output("check.out"); output << (numberNodes == 0 || isBST(tree) ? "YES" : "NO"); return EXIT_SUCCESS; }
IllyasvielEin/Robocup3dInstaller
SimSpark/spark/lib/kerosin/textureserver/textureserver_c.cpp
<reponame>IllyasvielEin/Robocup3dInstaller<gh_stars>0 #include "textureserver.h" using namespace boost; using namespace kerosin; using namespace zeitgeist; void CLASS(TextureServer)::DefineClass() { DEFINE_BASECLASS(zeitgeist/Leaf); }
julianladisch/stripes-testing
cypress/support/utils/dateTools.js
<gh_stars>0 const padWithZero = value => String(value).padStart(2, '0'); export default { padWithZero, getCurrentDate: () => { const currentDate = new Date(); return `${padWithZero(currentDate.getMonth() + 1)}/${padWithZero(currentDate.getDate())}/${currentDate.getFullYear()}`; }, getPreviousDayDate: () => { const currentDate = new Date(); return `${padWithZero(currentDate.getMonth() + 1)}/${padWithZero(currentDate.getDate() - 1)}/${currentDate.getFullYear()}`; }, getPreviousFiscalYearCode: () => { return 'FY' + (new Date().getFullYear() - 1).toString(); }, getCurrentFiscalYearCode: () => { return 'FY' + (new Date().getFullYear()).toString(); }, getRandomFiscalYearCode: (min, max) => { // returns random 4 digit code for the Fiscal Year return 'FY' + Math.floor((Math.random() * (Math.floor(max) - Math.ceil(min)) + Math.ceil(min))).toString(); }, getDateRanges: (rangesCount = 1, isInDifferentYears = false) => { const resultRanges = []; const currentDate = new Date(); const rangeLength = 7; for (let i = 0; i < rangesCount; i++) { const specialRange = { startDay: new Date(currentDate), endDay: new Date(currentDate) }; specialRange.startDay.setDate(currentDate.getDate() - ((i + 1) * rangeLength) + 1); specialRange.endDay.setDate(currentDate.getDate() - i * rangeLength); resultRanges.push(specialRange); if (isInDifferentYears) { currentDate.setFullYear(currentDate.getFullYear() - 1); } } return resultRanges; }, parseDateFromFilename(dateString) { const dateFormat = /\d{4}-\d{2}-\d{2}T\d{2}_\d{2}_\d{2}\+\d{2}_\d{2}/gm; const date = dateString.match(dateFormat)[0]; return Date.parse(date.replaceAll('_', ':')); }, verifyDate(actualDate, timeInterval = 60000) { expect(actualDate).to.be.greaterThan(Date.now() - timeInterval); expect(actualDate).to.be.lessThan(Date.now() + timeInterval); }, // Formats date as YYYY-MM-DD getFormattedDate({ date }) { return `${date.getFullYear()}-${padWithZero(date.getMonth() + 1)}-${padWithZero(date.getDate())}`; }, clearPaddingZero(initialString) { return initialString.replaceAll(/0([1-9])\//g, '$1/'); } };
assessorgeneral/ConQAT
org.conqat.engine.cpp/src/org/conqat/engine/cpp/dependency/IDependencyInjector.java
/*-------------------------------------------------------------------------+ | | | Copyright 2005-2011 the ConQAT Project | | | | Licensed under the Apache License, Version 2.0 (the "License"); | | you may not use this file except in compliance with the License. | | You may obtain a copy of the License at | | | | http://www.apache.org/licenses/LICENSE-2.0 | | | | Unless required by applicable law or agreed to in writing, software | | distributed under the License is distributed on an "AS IS" BASIS, | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | | See the License for the specific language governing permissions and | | limitations under the License. | +-------------------------------------------------------------------------*/ package org.conqat.engine.cpp.dependency; import org.conqat.engine.sourcecode.resource.ITokenElement; import org.conqat.lib.commons.collections.PairList; /** * Interface for injecting additional dependencies based on parsing information. * The idea is to map identifiers (potential method calls) to unique strings, * i.e. matching read/write functions must be mapped to the same string by the * methods of this interface. * * @author $Author: hummelb $ * @version $Rev: 41240 $ * @ConQAT.Rating YELLOW Hash: B81C487C9556EAA725BEC8EE75A9BBA8 */ public interface IDependencyInjector { /** * Returns a unique identifier for a source call (or null if this is not a * source call). */ String asNormalizedSourceCall(String text, ITokenElement element); /** * Returns a unique identifier for a target call (or null if this is not a * target call). */ String asNormalizedTargetCall(String text, ITokenElement element); /** * Returns a dependency target for the given identifier text. Returns null * if no direct dependency can be determined. * * @return pairs of uniform path (target element) and message describing the * dependency. The element described by the uniform path is not * required to exist and may be artificial. */ PairList<String, String> getDirectDependencyTarget(String text, ITokenElement element); /** Returns the type of dependency created. */ String getType(); }
daniel-perry/rt
reference_implementation/cs6620-prog6/Time.cc
<reponame>daniel-perry/rt #include "Time.h" #include <sys/time.h> #include <errno.h> #ifdef __linux #include <time.h> #endif #include <stdexcept> static struct timeval start_time; static bool initialized = false; void Time::initialize() { initialized=true; if(gettimeofday(&start_time, 0) != 0) throw std::runtime_error(std::string("gettimeofday failed: ") +strerror(errno)); } double Time::currentSeconds() { if(!initialized) initialized = true; struct timeval now_time; if(gettimeofday(&now_time, 0) != 0) throw std::runtime_error(std::string("gettimeofday failed: ") +strerror(errno)); return (now_time.tv_sec-start_time.tv_sec)+(now_time.tv_usec-start_time.tv_usec)*1.e-6; }
DataAgg/DAFramework
commons/src/main/java/com/dataagg/util/WMap.java
package com.dataagg.util; import org.nutz.lang.util.NutMap; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by watano on 2017/3/4. */ public class WMap extends NutMap { private static final long serialVersionUID = -852470603991540244L; public WMap() { super(); } public WMap(Map<String, Object> data) { super(data); } public String string(String key) { return this.getAs(key, String.class); } public String[] strings(String key) { List<String> strings = new ArrayList<>(); for (Object v : this.getArray(key, Object.class)) { strings.add(v.toString()); } return strings.toArray(new String[]{}); } public String[] stringsNoDuplicate(String key) { Set<String> strings = new LinkedHashSet<>(); for (Object v : this.getArray(key, Object.class)) { strings.add(v.toString()); } return strings.toArray(new String[]{}); } public WMap map(String key) { return this.getAs(key, WMap.class); } public List<?> list(String key) { return this.getAs(key, List.class); } public void addAll(WMap data2) { for (String key : data2.keySet()) { addX(key, data2.get(key)); } } @SuppressWarnings({ "unchecked", "rawtypes" }) public void addX(String key, Object value) { if (value == null) { return; } Object currValue = get(key); if (currValue == null) { put(key, value); } else if (currValue instanceof Map && value instanceof Map) { WMap obj = map(key); Map vObj = (Map) value; for (Object k : vObj.keySet()) { obj.addX(k.toString(), vObj.get(k)); } put(key, obj); } else if (currValue instanceof List) { List<Object> lst = getList(key, Object.class); if (value instanceof List) { lst.addAll((List) value); } else if (value instanceof Object[]) { for(Object o:(Object[])value){ lst.add(o); } } else { lst.add(value); } put(key, lst); } else if (value instanceof List) { ((List<Object>) value).add(currValue); put(key, value); } else if (value instanceof Object[]) { List<Object> all = new ArrayList<>(); all.add(currValue); for(Object o:(Object[])value){ all.add(o); } put(key, all); } else { put(key, value); } } public static <T> Set<T> convert(List<T> lst) { Set<T> set = new LinkedHashSet<>(); if (lst != null) { for (T o : lst) { if (!set.contains(o)) { set.add(o); } } } return set; } @SafeVarargs public static <T> Set<T> convert(T... lst) { Set<T> set = new LinkedHashSet<>(); if (lst != null) { for (T o : lst) { if (!set.contains(o)) { set.add(o); } } } return set; } }
bobbrow/cpp-docs
docs/atl/codesnippet/CPP/com-map-macros_7.h
<filename>docs/atl/codesnippet/CPP/com-map-macros_7.h BEGIN_COM_MAP(COuter4) COM_INTERFACE_ENTRY_AUTOAGGREGATE_BLIND(m_punkAutoAggB, CLSID_CAutoAggB) END_COM_MAP()
LineGames/Leggiero
Engine/Modules/Font/Common/PriorityFontSet.h
<gh_stars>10-100 //////////////////////////////////////////////////////////////////////////////// // Common/PriorityFontSet.h (Leggiero/Modules - Font) // // Prioritized Fonts Set //////////////////////////////////////////////////////////////////////////////// #ifndef __LM_FONT__COMMON__PRIORITY_FONT_SET_H #define __LM_FONT__COMMON__PRIORITY_FONT_SET_H // Standard Library #include <iterator> #include <memory> #include <vector> #include <utility> // Leggiero.Basic #include <Basic/LeggieroBasic.h> // Leggiero.Font #include "FontTypes.h" #include "IFontSet.h" #include "SingleFontSet.h" namespace Leggiero { namespace Font { // Forward Declarations class IFontFace; // Font Set with Priority class PriorityFontSet : public IFontSet { protected: struct _IteratorTypeSpecializerGeneralTag { }; struct _IteratorTypeSpecializerFontFaceTag { }; template <typename IteratorContentsT> struct _IteratorTypeSpecializer { public: using ValueCategory = _IteratorTypeSpecializerGeneralTag; }; template <typename InputIterator> PriorityFontSet(InputIterator first, InputIterator last, _IteratorTypeSpecializerGeneralTag) : m_baseSets(first, last) { } template <typename InputIterator> PriorityFontSet(InputIterator first, InputIterator last, _IteratorTypeSpecializerFontFaceTag) { for (InputIterator currentIter = first; currentIter != last; ++currentIter) { m_baseSets.push_back(std::make_shared<SingleFontSet>(*currentIter)); } } public: PriorityFontSet(std::shared_ptr<IFontSet> baseSet); PriorityFontSet(std::shared_ptr<IFontFace> baseFace); PriorityFontSet(std::initializer_list<std::shared_ptr<IFontSet> > initializer); PriorityFontSet(std::initializer_list<std::shared_ptr<IFontFace> > initializer); template <typename InputIterator> PriorityFontSet(InputIterator first, InputIterator last) : PriorityFontSet(first, last, _IteratorTypeSpecializer<typename std::iterator_traits<InputIterator>::value_type >::ValueCategory()) { } virtual ~PriorityFontSet() { } private: PriorityFontSet() = delete; public: // Get a real font to render a given glyph virtual EffectiveFontResult GetEffectiveFont(GlyphCodePointType glyph, GlyphStyleType style = GlyphStyleType::kNone) const override; protected: std::vector<std::shared_ptr<IFontSet> > m_baseSets; }; // Template specializations template <> struct PriorityFontSet::_IteratorTypeSpecializer<std::shared_ptr<IFontFace> > { public: using ValueCategory = PriorityFontSet::_IteratorTypeSpecializerFontFaceTag; }; template <> struct PriorityFontSet::_IteratorTypeSpecializer<const std::shared_ptr<IFontFace> > { public: using ValueCategory = PriorityFontSet::_IteratorTypeSpecializerFontFaceTag; }; } } #endif
gogoods/x
redis/redis_test.go
package redis import ( "log" "testing" "time" ) func Test(t *testing.T) { r, err := New("192.168.1.211:6379", "99101691", 10, 100, time.Minute, 4) if err != nil { log.Panic(err.Error()) } conn := r.GetConn() defer conn.Close() vals := []int{1, 2, 3} reply, err := conn.Do("RPUSH", "key", vals) log.Println(reply, err) }
tcard/jackcess
src/main/java/com/healthmarketscience/jackcess/impl/query/CrossTabQueryImpl.java
<filename>src/main/java/com/healthmarketscience/jackcess/impl/query/CrossTabQueryImpl.java<gh_stars>100-1000 /* Copyright (c) 2008 Health Market Science, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.healthmarketscience.jackcess.impl.query; import java.util.List; import static com.healthmarketscience.jackcess.impl.query.QueryFormat.*; import com.healthmarketscience.jackcess.query.CrossTabQuery; /** * Concrete Query subclass which represents a crosstab/pivot query, e.g.: * {@code TRANSFORM <expr> SELECT <query> PIVOT <expr>} * * @author <NAME> */ public class CrossTabQueryImpl extends BaseSelectQueryImpl implements CrossTabQuery { public CrossTabQueryImpl(String name, List<Row> rows, int objectId, int objectFlag) { super(name, rows, objectId, objectFlag, Type.CROSS_TAB); } protected Row getTransformRow() { return getUniqueRow( filterRowsByNotFlag(super.getColumnRows(), (short)(CROSSTAB_PIVOT_FLAG | CROSSTAB_NORMAL_FLAG))); } @Override protected List<Row> getColumnRows() { return filterRowsByFlag(super.getColumnRows(), CROSSTAB_NORMAL_FLAG); } @Override protected List<Row> getGroupByRows() { return filterRowsByFlag(super.getGroupByRows(), CROSSTAB_NORMAL_FLAG); } protected Row getPivotRow() { return getUniqueRow(filterRowsByFlag(super.getColumnRows(), CROSSTAB_PIVOT_FLAG)); } @Override public String getTransformExpression() { Row row = getTransformRow(); if(row.expression == null) { return null; } // note column expression are always quoted appropriately StringBuilder builder = new StringBuilder(row.expression); return toAlias(builder, row.name1).toString(); } @Override public String getPivotExpression() { return getPivotRow().expression; } @Override protected void toSQLString(StringBuilder builder) { String transformExpr = getTransformExpression(); if(transformExpr != null) { builder.append("TRANSFORM ").append(transformExpr).append(NEWLINE); } toSQLSelectString(builder, true); builder.append(NEWLINE).append("PIVOT ") .append(getPivotExpression()); } }
p-ranav/walnut.v1
tests/test_parser_call_expression.hpp
#pragma once #include <catch.hpp> #include <lexer.hpp> #include <parser.hpp> #include <environment.hpp> #include <iostream> #include <string> #include <clocale> namespace walnut { TEST_CASE("The parser can parse the call 'myfunction();'", "[parser]") { setlocale(LC_ALL, ""); EnvironmentPtr environment = std::make_shared<Environment>(); String filename = ""; String buffer = "myfunction();"; Lexer lexer(filename, buffer); lexer.Tokenize(); Parser parser(lexer.tokens, buffer); parser.ParseProgram(); REQUIRE(parser.statements.size() == 1); REQUIRE(parser.statements[0]->type == Node::Type::CALL_EXPRESSION); REQUIRE(parser.statements[0]->ToString() == "myfunction()"); CallExpressionNodePtr call = std::dynamic_pointer_cast<CallExpressionNode>(parser.statements[0]); REQUIRE(call != nullptr); REQUIRE(call->arguments->elements.size() == 0); } TEST_CASE("The parser can parse the identity function 'myfunction(a);'", "[parser]") { setlocale(LC_ALL, ""); EnvironmentPtr environment = std::make_shared<Environment>(); String filename = ""; String buffer = "myfunction(a);"; Lexer lexer(filename, buffer); lexer.Tokenize(); Parser parser(lexer.tokens, buffer); parser.ParseProgram(); REQUIRE(parser.statements.size() == 1); REQUIRE(parser.statements[0]->type == Node::Type::CALL_EXPRESSION); REQUIRE(parser.statements[0]->ToString() == "myfunction(a)"); CallExpressionNodePtr call = std::dynamic_pointer_cast<CallExpressionNode>(parser.statements[0]); REQUIRE(call != nullptr); REQUIRE(call->arguments->elements.size() == 1); REQUIRE(call->arguments->elements[0]->type == NodeType::IDENTIFIER); } TEST_CASE("The parser can parse the identity function 'myfunction(a = 1, b = 2);'", "[parser]") { setlocale(LC_ALL, ""); EnvironmentPtr environment = std::make_shared<Environment>(); String filename = ""; String buffer = "myfunction(a = 1, b = 2);"; Lexer lexer(filename, buffer); lexer.Tokenize(); Parser parser(lexer.tokens, buffer); parser.ParseProgram(); REQUIRE(parser.statements.size() == 1); REQUIRE(parser.statements[0]->type == Node::Type::CALL_EXPRESSION); REQUIRE(parser.statements[0]->ToString() == "myfunction(a = 1, b = 2)"); CallExpressionNodePtr call = std::dynamic_pointer_cast<CallExpressionNode>(parser.statements[0]); REQUIRE(call != nullptr); REQUIRE(call->arguments->elements.size() == 2); REQUIRE(call->arguments->elements[0]->type == NodeType::KEY_VALUE_ARGUMENT); REQUIRE(call->arguments->elements[0]->type == NodeType::KEY_VALUE_ARGUMENT); } TEST_CASE("The parser can parse the identity function 'myfunction(a, b);'", "[parser]") { setlocale(LC_ALL, ""); EnvironmentPtr environment = std::make_shared<Environment>(); String filename = ""; String buffer = "myfunction(a, b);"; Lexer lexer(filename, buffer); lexer.Tokenize(); Parser parser(lexer.tokens, buffer); parser.ParseProgram(); REQUIRE(parser.statements.size() == 1); REQUIRE(parser.statements[0]->type == Node::Type::CALL_EXPRESSION); REQUIRE(parser.statements[0]->ToString() == "myfunction(a, b)"); CallExpressionNodePtr call = std::dynamic_pointer_cast<CallExpressionNode>(parser.statements[0]); REQUIRE(call != nullptr); REQUIRE(call->arguments->elements.size() == 2); REQUIRE(call->arguments->elements[0]->type == NodeType::IDENTIFIER); REQUIRE(call->arguments->elements[1]->type == NodeType::IDENTIFIER); } TEST_CASE("The parser can parse the identity function 'myfunction(a, b, c = 1, d = 'w');'", "[parser]") { setlocale(LC_ALL, ""); EnvironmentPtr environment = std::make_shared<Environment>(); String filename = ""; String buffer = "myfunction(a, b, c = 1, d = 'w');"; Lexer lexer(filename, buffer); lexer.Tokenize(); Parser parser(lexer.tokens, buffer); parser.ParseProgram(); REQUIRE(parser.statements.size() == 1); REQUIRE(parser.statements[0]->type == Node::Type::CALL_EXPRESSION); REQUIRE(parser.statements[0]->ToString() == "myfunction(a, b, c = 1, d = 'w')"); CallExpressionNodePtr call = std::dynamic_pointer_cast<CallExpressionNode>(parser.statements[0]); REQUIRE(call != nullptr); REQUIRE(call->arguments->elements.size() == 4); REQUIRE(call->arguments->elements[0]->type == NodeType::IDENTIFIER); REQUIRE(call->arguments->elements[1]->type == NodeType::IDENTIFIER); REQUIRE(call->arguments->elements[2]->type == NodeType::KEY_VALUE_ARGUMENT); REQUIRE(call->arguments->elements[3]->type == NodeType::KEY_VALUE_ARGUMENT); } } // namespace walnut
sakusimu/mh4g-skillsimu
test/unit/40_deco/30_assembler.js
<reponame>sakusimu/mh4g-skillsimu<gh_stars>1-10 'use strict'; var assert = require('power-assert'), Assembler = require('../../../lib/deco/assembler.js'); describe('40_deco/30_assembler', function () { it('require', function () { assert(typeof Assembler === 'function', 'is function'); }); it('new', function () { var a = new Assembler(); assert(typeof a === 'object', 'is object'); assert(typeof a.initialize === 'function', 'has initialie()'); }); });
zamannoor/DIQL
tests/parallel/map.scala
<filename>tests/parallel/map.scala import edu.uta.diql._ import scala.io.Source import scala.collection.parallel.ParIterable object Test { def main ( args: Array[String] ) { println("Number of cores: "+Runtime.getRuntime().availableProcessors()) var t: Long = System.currentTimeMillis() val a = (1 to args(0).toInt).toList println("**** construct sequential: "+(System.currentTimeMillis()-t)/1000.0+" secs") t = System.currentTimeMillis() a.map(_+1) println("**** sequential: "+(System.currentTimeMillis()-t)/1000.0+" secs") t = System.currentTimeMillis() val c = (1 to args(0).toInt).toList.par println("**** construct parallel: "+(System.currentTimeMillis()-t)/1000.0+" secs") explain(true) t = System.currentTimeMillis() q(""" select v+1 from v <- c """) println("**** parallel: "+(System.currentTimeMillis()-t)/1000.0+" secs") } }
xmidt-org/carousel
pkg/carousel/mocks_test.go
<gh_stars>0 package carousel import ( "github.com/stretchr/testify/mock" "github.com/xmidt-org/carousel/pkg/model" "github.com/xmidt-org/carousel/pkg/runner" ) type MockController struct { mock.Mock } func (m *MockController) SelectWorkspace(workspace string) error { args := m.Called(workspace) return args.Error(0) } func (m *MockController) CreateApply(target model.ClusterState, step model.Step) runner.Runnable { args := m.Called(target, step) return args.Get(0).(runner.Runnable) } func (m *MockController) GetCluster() (model.Cluster, error) { args := m.Called() return args.Get(0).(model.Cluster), args.Error(1) } func (m *MockController) TaintResources(resources []string) error { args := m.Called(resources) return args.Error(0) } func (m *MockController) TaintHost(hostname string) error { args := m.Called(hostname) return args.Error(0) } type MockRunner struct { mock.Mock } func (m *MockRunner) Output() ([]byte, error) { args := m.Called() if data := args.Get(0); data != nil { return args.Get(0).([]byte), args.Error(1) } return nil, args.Error(1) } func (m *MockRunner) String() string { args := m.Called() return args.String(0) }
jonkjenn/ChessTour
chess24.cpp
<filename>chess24.cpp #include "chess24.h" #include <QtNetwork> #include <QObject> #include <QJsonDocument> #include <optional> #include <iostream> #include "disknetworkcookiejar.h" const QString Chess24::loginurl = "https://chess24.com/en/login"; /// /// \brief Chess24::Chess24 /// \param parent /// \param qnam /// /// Fasilitates interactions with the Chess24 website /// Chess24::Chess24(QObject *parent,QNetworkAccessManager &qnam):LoginManager(parent),qnam(qnam) { } void Chess24::onTryLogin(QString username, QString password) { //Load the login page so we can get the CSRF code to perform login QNetworkReply *reply = qnam.get(QNetworkRequest(Chess24::loginurl)); connect(reply,&QNetworkReply::finished,[this,reply,username,password](){httpFinished(reply,username,password); }); //connect(&qnam,&QNetworkAccessManager::sslErrors,this,&Chess24::sslErrors); } void Chess24::onCheckLoggedIn(UserData::LoginSource source) { downloadUserData(source); } void Chess24::httpFinished(QNetworkReply *reply, QString username, QString password) { QByteArray data = reply->readAll(); QString txt{data}; std::optional<QString> csrf = getCSRF(txt); if(!csrf){ UserData ud; ud.result = false; emit loginResult(ud); return; } QUrlQuery qu; qu.addQueryItem("LoginForm[emailOrUsername]",username); qu.addQueryItem("LoginForm[password]",password); qu.addQueryItem("csrf",csrf.value()); qu.addQueryItem("LoginForm[rememberMe]","0"); qu.addQueryItem("LoginForm[rememberMe]","1"); qu.addQueryItem("yt1","Login"); QNetworkRequest req(QUrl("https://chess24.com/en/login")); req.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded"); req.setRawHeader(QByteArray("origin"),QByteArray("https://chess24.com")); req.setRawHeader(QByteArray("Referer"),QByteArray("https://chess24.com/en/login")); req.setRawHeader("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"); qDebug() << username << " "<< password << " " << csrf.value(); //Send login post QNetworkReply * rep = qnam.post(req,qu.query(QUrl::FullyEncoded).toUtf8()); connect(rep,&QNetworkReply::finished,[this,rep](){ //Check if logged in by using this api call downloadUserData(UserData::LoginSource::USERPASS); rep->deleteLater(); }); connect(rep,&QNetworkReply::redirected,this,&Chess24::redirected); connect(rep,static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),this,&Chess24::gotError); } void Chess24::downloadUserData(UserData::LoginSource source){ QNetworkRequest req(QUrl("https://chess24.com/api/web/UserAPI/getUserData")); QNetworkReply *urep = qnam.get(req); connect(urep,&QNetworkReply::finished,[this,urep,source]{ QByteArray data = urep->readAll(); qDebug() << data; UserData udat = getUserData(data); udat.loginSource = source; if(udat.loginSource == UserData::LoginSource::USERPASS){ DiskNetworkCookieJar *jar = static_cast<DiskNetworkCookieJar*>(qnam.cookieJar()); jar->saveCookieJar(); } emit loginResult(udat); urep->deleteLater(); }); } UserData Chess24::getUserData(const QByteArray &data){ UserData d; QJsonDocument jdoc(QJsonDocument::fromJson(data)); QJsonDocument ujdoc(QJsonDocument::fromJson((jdoc.object())["data"].toObject()["userData"].toObject()["value"].toString().toUtf8())); QJsonObject userdata = ujdoc.object(); QJsonObject user = userdata["user"].toObject(); d.authToken = user["authToken"].toString(); d.country = user["country"].toString(); d.name = user["name"].toString(); d.permalink = user["permalink"].toString(); d.uuid = user["uuid"].toString(); QJsonObject level = userdata["level"].toObject(); d.isRegistered = level["isRegistered"].toBool(); d.isPremium = level["isPremium"].toBool(); d.result = true; return d; } void Chess24::redirected(const QUrl &url) { std::cout << url.toString().toStdString() << std::endl; } void Chess24::gotError(QNetworkReply::NetworkError error) { qDebug() << error; } void Chess24::sslErrors(QNetworkReply *reply, const QList<QSslError> &errors) { for(auto e:errors){ qDebug() << e.errorString(); } } /// /// \brief Chess24::getCSRF /// \param source Source code of the login page /// \return /// /// /// Typical <input value="xxxxxxxxxxxxxx" name="csrf"/> /// /// std::optional<QString> Chess24::getCSRF(QString source){ int csrfidx = source.indexOf("csrf"); //The name attribute that says "csrf", is after the value attribute with the csrf code if(csrfidx<0){ return {}; } //Find the start of the code int start1 = source.lastIndexOf("value=",csrfidx-source.length()); if(csrfidx<0){ return {}; } //Add number of letters in value=" int start = start1 + 7; //Find the end quote int end = source.indexOf("\"",start); if(csrfidx<0){ return {}; } return source.mid(start,end-start); }
chromium/chromium
services/audio/output_device_mixer_impl.h
<filename>services/audio/output_device_mixer_impl.h<gh_stars>1000+ // Copyright 2021 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. #ifndef SERVICES_AUDIO_OUTPUT_DEVICE_MIXER_IMPL_H_ #define SERVICES_AUDIO_OUTPUT_DEVICE_MIXER_IMPL_H_ #include <memory> #include <set> #include <string> #include "base/callback.h" #include "base/check.h" #include "base/containers/unique_ptr_adapters.h" #include "base/dcheck_is_on.h" #include "base/synchronization/lock.h" #include "base/timer/timer.h" #include "media/audio/audio_io.h" #include "media/base/audio_parameters.h" #include "media/base/reentrancy_checker.h" #include "services/audio/mixing_graph.h" #include "services/audio/output_device_mixer.h" namespace audio { class MixingGraph; // OutputDeviceMixerImpl manages the rendering of all output streams created by // MakeMixableStream(). It has two rendering modes: if there // are not listeners attached, each active output stream is rendered // independently. If the mixer has listeners and at least one of the managed // streams there is playing, all output streams are mixed by // |mixing_graph_| and the result is played by |mixing_graph_output_stream_|. // After mixing started, the mixed playback will stop only when the last // listener is gone; this means the mixed playback will continue even when there // are no managed streams playing. That is done because the listeners do not // like when the reference signal stops and then starts again: it can cause // reference signal delay jumps. TODO(olka): add metrics for how often/how long // we may have listeners forsing such silent mixed playback. class OutputDeviceMixerImpl final : public OutputDeviceMixer { public: using ErrorType = media::AudioOutputStream::AudioSourceCallback::ErrorType; static constexpr base::TimeDelta kSwitchToUnmixedPlaybackDelay = base::Seconds(1); static constexpr double kDefaultVolume = 1.0; // |device_id| is the id of the device to manage the playback for (expected to // be a valid physical output device id); |output_params| are the parameters // of the audio mix the mixer will be playing in case there are listeners // attached (otherwise, each output stream is played independently using its // individual parameters); |create_mixing_graph_callback| is used to create // a mixing graph object which will combine individual audio streams into a // mixed signal; |create_stream_callback| is used to create physical output // streams to be used for audio rendering. OutputDeviceMixerImpl( const std::string& device_id, const media::AudioParameters& output_params, MixingGraph::CreateCallback create_mixing_graph_callback, CreateStreamCallback create_stream_callback); OutputDeviceMixerImpl(const OutputDeviceMixerImpl&) = delete; OutputDeviceMixerImpl& operator=(const OutputDeviceMixerImpl&) = delete; ~OutputDeviceMixerImpl() final; // Creates an output stream managed by |this|. media::AudioOutputStream* MakeMixableStream( const media::AudioParameters& params, base::OnceCallback<void()> on_device_change_callback) final; void ProcessDeviceChange() final; // ReferenceOutput implementation. // Starts listening to the mixed audio stream. void StartListening(Listener* listener) final; // Stops listening to the mixed audio stream. void StopListening(Listener* listener) final; private: class MixTrack; class MixableOutputStream; class MixingStats; struct StreamAutoClose { void operator()(media::AudioOutputStream* stream) { if (!stream) return; stream->Close(); stream = nullptr; } }; // Do not change: used for UMA reporting, matches // AudioOutputDeviceMixerMixedPlaybackStatus from enums.xml. enum class MixingError { kNone = 0, kOpenFailed, kPlaybackFailed, kMaxValue = kPlaybackFailed }; using MixTracks = std::set<std::unique_ptr<MixTrack>, base::UniquePtrComparator>; using ActiveTracks = std::set<MixTrack*>; using Listeners = std::set<Listener*>; // Operations delegated by MixableOutputStream. void StartStream(MixTrack* mix_track, media::AudioOutputStream::AudioSourceCallback* callback); void StopStream(MixTrack* mix_track); void CloseStream(MixTrack* mix_track); // Helper to create physical audio streams. media::AudioOutputStream* CreateAndOpenDeviceStream( const media::AudioParameters& params); // Delivers audio to listeners; provided as a callback to MixingGraph. void BroadcastToListeners(const media::AudioBus& audio_bus, base::TimeDelta delay); // Processes |mixing_output_stream_| rendering errors; provided as a callback // to MixingGraph. void OnMixingGraphError(ErrorType error); // Helpers to manage audio playback. bool HasListeners() const; void StartMixingGraphPlayback(); void StopMixingGraphPlayback(MixingError mixing_error); void SwitchToUnmixedPlaybackTimerHelper(); static const char* ErrorToString(MixingError error); SEQUENCE_CHECKER(owning_sequence_); // Callback to create physical audio streams. const CreateStreamCallback create_stream_callback_; // Streams managed by the mixer. MixTracks mix_tracks_ GUARDED_BY_CONTEXT(owning_sequence_); // Active tracks rendering audio. ActiveTracks active_tracks_ GUARDED_BY_CONTEXT(owning_sequence_); // Listeners receiving the reference output (mixed playback). Playback is // mixed if and only if there is at least one listener. mutable base::Lock listener_lock_; Listeners listeners_ GUARDED_BY(listener_lock_); // Audio parameters for mixed playback. const media::AudioParameters mixing_graph_output_params_; // Provides the audio mix combined of |active_members_| audio to // |mixing_output_stream_| for playback. const std::unique_ptr<MixingGraph> mixing_graph_ GUARDED_BY_CONTEXT(owning_sequence_); // Stream to render the audio mix. Non-null if and only if the playback is // being mixed at the moment. std::unique_ptr<media::AudioOutputStream, StreamAutoClose> mixing_graph_output_stream_ GUARDED_BY_CONTEXT(owning_sequence_); // Delays switching to unmixed playback in case a new listener is coming // soon (within kSwitchToIndependentPlaybackDelay). base::OneShotTimer switch_to_unmixed_playback_delay_timer_ GUARDED_BY_CONTEXT(owning_sequence_); // Non-null when the playback is being mixed. Collects mixing statistics. // Logs them upon the destruction when mixing stops. std::unique_ptr<MixingStats> mixing_stats_; #if DCHECK_IS_ON() bool device_changed_ = false; #endif // A mixable stream operation cannot be invoked within a context of another // such operation. In practice it means that AudioOutputStream created by the // mixer cannot be stopped/closed synchronously from AudioSourceCallback // provided to it on AudioOutputStream::Start(). REENTRANCY_CHECKER(reentrancy_checker_); // Supplies weak pointers to |this| for MixableOutputStream instances. base::WeakPtrFactory<OutputDeviceMixerImpl> weak_factory_{this}; }; } // namespace audio #endif // SERVICES_AUDIO_OUTPUT_DEVICE_MIXER_IMPL_H_
qussarah/declare
j2k/testData/fileOrElement/for/forThroughListIndices.java
<filename>j2k/testData/fileOrElement/for/forThroughListIndices.java import java.util.List; import java.util.ArrayList; class C{ void foo1(List<String> list) { for (int i = 0; i < list.size(); i++) { list.set(i, "a"); } } void foo2(ArrayList<String> list) { for (int i = 0; i < list.size(); i++) { list.set(i, "a"); } } }
cmsis-packs/cmsis-5
CMSIS/Documentation/NN/html/search/enumvalues_0.js
var searchData= [ ['arm_5fsigmoid',['ARM_SIGMOID',['../arm__nnfunctions_8h.html#a7f41aa78cd9a0552fae9b348ee4831a0a49b307e029715fbaa6f3101c806b8c54',1,'arm_nnfunctions.h']]], ['arm_5ftanh',['ARM_TANH',['../arm__nnfunctions_8h.html#a7f41aa78cd9a0552fae9b348ee4831a0ac24e4db95c986f16c10dca71a4b4e1c5',1,'arm_nnfunctions.h']]] ];
benety/mongo
jstests/replsets/prepare_failover_rollback_commit.js
/** * This tests that preparing a transaction successfully will update the lastWriteOpTime on * secondaries so that the corresponding commitTransaction oplog entry has a correct prevOpTime. * The test exercises a failover right after a prepare, so that we have to commit the transaction * while talking to a node that was in secondary state when it was prepared. We commit that * transaction, then roll back that commit entry, the success of which depends on the prevOpTime * being set properly. * * @tags: [ * uses_prepare_transaction, * uses_transactions, * ] */ (function() { "use strict"; load("jstests/replsets/libs/rollback_test.js"); load("jstests/core/txns/libs/prepare_helpers.js"); const dbName = "test"; const collName = "prepare_failover_rollback_commit"; const rollbackTest = new RollbackTest(collName); let primary = rollbackTest.getPrimary(); const testDB = primary.getDB(dbName); const testColl = testDB.getCollection(collName); // First create the collection for all. assert.commandWorked(testColl.insert({"a": "baseDoc"})); const session = primary.startSession(); const sessionDB = session.getDatabase(dbName); const sessionColl = sessionDB.getCollection(collName); session.startTransaction(); assert.commandWorked(sessionColl.insert({"b": "transactionDoc"})); // Prepare a transaction. This will be replicated to the secondary. const prepareTimestamp = PrepareHelpers.prepareTransaction(session); // Do a failover first, without rolling back any of the data from this test. We want the // current secondary to become primary and inherit the prepared transaction. rollbackTest.transitionToRollbackOperations(); rollbackTest.transitionToSyncSourceOperationsBeforeRollback(); rollbackTest.transitionToSyncSourceOperationsDuringRollback(); rollbackTest.transitionToSteadyStateOperations({skipDataConsistencyChecks: true}); // Now set up a rollback scenario for that new primary. rollbackTest.transitionToRollbackOperations(); // Create a proxy session to reuse the session state of the old primary. primary = rollbackTest.getPrimary(); const newSession1 = new _DelegatingDriverSession(primary, session); // Commit the transaction on this primary. We expect the commit to roll back. assert.commandWorked(PrepareHelpers.commitTransaction(newSession1, prepareTimestamp)); rollbackTest.transitionToSyncSourceOperationsBeforeRollback(); rollbackTest.transitionToSyncSourceOperationsDuringRollback(); rollbackTest.transitionToSteadyStateOperations({skipDataConsistencyChecks: true}); // Create a proxy session to reuse the session state of the old primary. primary = rollbackTest.getPrimary(); const newSession2 = new _DelegatingDriverSession(primary, session); // Commit the transaction for all to conclude the test. assert.commandWorked(PrepareHelpers.commitTransaction(newSession2, prepareTimestamp)); rollbackTest.stop(); })();
GuildOfWeavers/AirAssembly
bin/lib/registers/StaticRegister.js
<reponame>GuildOfWeavers/AirAssembly<gh_stars>10-100 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // CLASS DEFINITION // ================================================================================================ class StaticRegister { } exports.StaticRegister = StaticRegister; //# sourceMappingURL=StaticRegister.js.map
chreden/trview
trview.app/Windows/TriggersWindow.h
<filename>trview.app/Windows/TriggersWindow.h /// @file TriggersWindow.h /// @brief Used to show and filter the triggers in the level. #pragma once #include <trview.ui/Listbox.h> #include <trview.app/Elements/Item.h> #include <trview.app/Elements/ITrigger.h> #include "ITriggersWindow.h" #include "CollapsiblePanel.h" #include <trview.common/Windows/IClipboard.h> #include <trview.app/UI/IBubble.h> namespace trview { namespace ui { class Checkbox; class Dropdown; } class TriggersWindow final : public ITriggersWindow, public CollapsiblePanel { public: struct Names { static const std::string add_to_route_button; static const std::string filter_dropdown; static const std::string stats_listbox; static const std::string sync_trigger_checkbox; static const std::string track_room_checkbox; static const std::string triggers_listbox; static const std::string trigger_commands_listbox; }; explicit TriggersWindow(const graphics::IDeviceWindow::Source& device_window_source, const ui::render::IRenderer::Source& renderer_source, const ui::IInput::Source& input_source, const Window& parent, const std::shared_ptr<IClipboard>& clipboard, const IBubble::Source& bubble_source); virtual ~TriggersWindow() = default; virtual void render(bool vsync) override; virtual void set_triggers(const std::vector<std::weak_ptr<ITrigger>>& triggers) override; virtual void update_triggers(const std::vector<std::weak_ptr<ITrigger>>& triggers) override; virtual void clear_selected_trigger() override; virtual void set_current_room(uint32_t room) override; virtual void set_selected_trigger(const std::weak_ptr<ITrigger>& trigger) override; virtual void set_items(const std::vector<Item>& items) override; virtual std::weak_ptr<ITrigger> selected_trigger() const override; virtual void update(float delta) override; protected: virtual void update_layout() override; private: void populate_triggers(const std::vector<std::weak_ptr<ITrigger>>& triggers); std::unique_ptr<ui::Control> create_left_panel(); std::unique_ptr<ui::Control> create_right_panel(); void set_track_room(bool value); void set_sync_trigger(bool value); void load_trigger_details(const ITrigger& trigger); void apply_filters(); ui::Control* _controls; ui::Checkbox* _track_room_checkbox; ui::Listbox* _triggers_list; ui::Listbox* _stats_list; ui::Listbox* _command_list; ui::Dropdown* _command_filter; std::vector<Item> _all_items; std::vector<std::weak_ptr<ITrigger>> _all_triggers; /// Whether the trigger window is tracking the current room. bool _track_room{ false }; /// The current room number selected for tracking. uint32_t _current_room{ 0u }; /// Whether the room tracking filter has been applied. bool _filter_applied{ false }; bool _sync_trigger{ true }; std::weak_ptr<ITrigger> _selected_trigger; std::vector<TriggerCommandType> _selected_commands; std::shared_ptr<IClipboard> _clipboard; std::unique_ptr<IBubble> _bubble; }; }
Verteiron/JContainers
JContainers/src/autorelease_queue.h
#pragma once #include <atomic> namespace collections { class object_registry; class autorelease_queue { std::thread _thread; bshared_mutex& _mutex; object_registry& _registry; typedef std::lock_guard<decltype(_mutex)> lock; typedef unsigned int time_point; //typedef chrono::time_point<chrono::system_clock> time_point; typedef std::vector<std::pair<HandleT, time_point> > queue; queue _queue; time_point _timeNow; std::atomic_int_fast8_t _state; enum queue_state : unsigned char { state_none = 0x0, state_run = 0x1, state_paused = 0x2, }; public: void u_clear() { u_stop(); _queue.clear(); } template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & _timeNow; ar & _queue; } explicit autorelease_queue(object_registry& registry, bshared_mutex &mt) : _thread() , _timeNow(0) , _state(state_none) , _mutex(mt) , _registry(registry) { start(); } void push(HandleT handle) { write_lock g(_mutex); _queue.push_back(std::make_pair(handle, _timeNow)); } void start() { if ((_state & state_run) == 0) { _state = state_run; write_lock g(_mutex); _thread = std::thread(&autorelease_queue::run, std::ref(*this)); } } size_t count() { read_lock hg(_mutex); return u_count(); } size_t u_count() const { return _queue.size(); } void setPaused(bool paused) { _state |= state_paused; } void stop() { u_stop(); } void u_stop() { _state = state_none; if (_thread.joinable()) { _thread.join(); } } ~autorelease_queue() { stop(); } private: void cycleIncr() { if (_timeNow < (std::numeric_limits<time_point>::max)()) { ++_timeNow; } else { _timeNow = 0; } } time_point lifetimeDiff(time_point time) const { if (_timeNow >= time) { return _timeNow - time; } else { return ((std::numeric_limits<time_point>::max)() - time) + _timeNow; } } public: enum { obj_lifetime = 10, // seconds tick_duration = 2, // seconds sleep_duration_millis = 100, // milliseconds }; enum { tick_duration_millis = 1000 * tick_duration, obj_lifeInTicks = obj_lifetime / tick_duration, // ticks }; private: static void run(autorelease_queue &self) { using namespace std; chrono::milliseconds sleepTime(sleep_duration_millis); vector<HandleT> toRelease; uint32 millisecondCounter = 0; // plain & dumb counter while (true) { unsigned char state = self._state; if ((state & state_run) == 0) { break; } std::this_thread::sleep_for(sleepTime); millisecondCounter += sleep_duration_millis; if (millisecondCounter >= tick_duration_millis) { millisecondCounter = 0; if ((state & state_paused) == 0) { write_lock g(self._mutex); self._queue.erase( remove_if(self._queue.begin(), self._queue.end(), [&](const queue::value_type& val) { auto diff = self.lifetimeDiff(val.second); bool release = diff >= obj_lifeInTicks; if (release) toRelease.push_back(val.first); return release; }), self._queue.end()); self.cycleIncr(); } for(auto& val : toRelease) { auto obj = self._registry.getObject(val); if (obj) { bool deleted = obj->_deleteOrRelease(nullptr); //printf("handle %u %s\n", val, (deleted ? "deleted" : "released")); } } toRelease.clear(); } } printf("autorelease_queue finish\n"); } }; }
CalderaWP/cf-pantheon-upstream
web/wp-content/plugins/caldera-forms/assets/js/api/stores.js
<filename>web/wp-content/plugins/caldera-forms/assets/js/api/stores.js /** * A factory for a form state containers * * Can be used constructed with CFAPI() or other data. Designed to provide data to our VueJS entry viewer, but is framework agnostic. * * @since 1.50 * * @param formId The ID of the form * @param allFields All fields of this form * @param listFields The fields of this form with "Show In Entry List" checked * * @returns {{state: {formId: *, allFields: *, listFields: *}, setFormId: setFormId, setAllFields: setAllFields, setListFields: setListFields, getAllFields: getAllFields}} * * @constructor */ function CFFormStoreFactory( formId, allFields, listFields ){ return { state: { formId: formId, allFields: allFields, listFields: listFields }, setFormId: function(newValue) { this.state.formId = newValue }, setAllFields: function(newValue) { this.state.allFields = newValue }, setListFields: function(newValue) { this.state.listFields = newValue }, getAllFields: function () { return this.state.allFields; } }; } /** * A factory for creating a state container for a paginated collection of entries * * Can be used constructed with CFAPI() or other data. Designed to provide data to our VueJS entry viewer, but is framework agnostic. * * @since 1.50 * * @param formId The ID of form entries are from * @param entries The entry collection * * @returns {{state: {formId: *, entries: *, total: number, totalPages: number}, setEntries: setEntries, setTotal: setTotal, setTotalPages: setTotalPages, getTotalPages: getTotalPages, getEntry: getEntry, getFieldFromEntry: getFieldFromEntry}} * * @constructor */ function CFEntriesStoreFactory( formId, entries ){ return { state: { formId: formId, entries: entries, total: 0, totalPages: 0, page: 0 }, setEntries: function (entries) { this.state.entries = entries; }, setTotal: function( total ){ this.state.total = total; }, getTotal: function(){ return this.state.total; }, setTotalPages: function( totalPages ){ this.state.totalPages = totalPages; }, getTotalPages: function(){ return this.state.totalPages; }, setPage: function( page ){ this.state.page = page; }, getPage: function(){ return this.state.page; }, getEntry :function( id ){ if( 'object' == typeof this.state.entries[id] ){ return this.state.entries[id]; } return false; }, getFieldFromEntry: function( entry, fieldId ){ if( 'object' == typeof entry.fields[fieldId ]) { return entry.fields[fieldId]; } return false; } } }
toilatester/sample-automation-frameworks-across-languages
python/Core/Base/BaseTest.py
<filename>python/Core/Base/BaseTest.py import os import unittest import traceback import threading from Core.Config.DriverFactory import DriverFactory from Config import YAML_CONFIG from GUI.POM.LoginPage.LoginPage import LoginPage from GUI.POM.RegisterPage.RegisterPage import RegisterPage from GUI.POM.CreateBotPage.CreateBotPage import CreateBotPage from GUI.POM.Dashboard.DashboardPage import DashboardPage from Utils.DataGenerateUtils import DataGenerateUtils from Core.Exceptions.TestContextException import TestContextException class RepeatedTest(object): def __init__(self, repeated_number: int = 0, parallel=False, thread_count=4, is_continue=True): self.__repeated_number = 1 if repeated_number == 0 else repeated_number self.__parallel = parallel self.__thread_count = thread_count self.__is_continue = is_continue self.__result = [] def __call__(self, test_func): def wrapped_test(*args): test_class = args[0] setup_method = getattr(test_class, "repeated_setup") teardown_method = getattr(test_class, "repeated_teardown") if self.__parallel: self.__invoke_test_parallel(setup_method, teardown_method, test_func, *args) else: self.__invoke_test_single_thread(setup_method, teardown_method, test_func, *args) return wrapped_test def __invoke_test_parallel(self, setup_method, teardown_method, test_func, *args): list_thread = [] for i in range(0, self.__repeated_number, 1): thread_name = "Repeated Test " + str( i) list_thread.append(threading.Thread(target=self.__invoke_test, name=thread_name, args=(i, setup_method, teardown_method, test_func, *args))) count = int(self.__repeated_number / self.__thread_count) for index in range(0, count, 1): for t in list_thread[self.__thread_count * index: (self.__thread_count * index) + self.__thread_count]: t.start() for t in list_thread[self.__thread_count * index: (self.__thread_count * index) + self.__thread_count]: t.join() if len(self.__result) > 0: msg = "\n".join(self.__result) raise AssertionError("\n" + msg) def __invoke_test_single_thread(self, setup_method, teardown_method, test_func, *args): for i in range(0, self.__repeated_number, 1): self.__invoke_test(i, setup_method, teardown_method, test_func, *args) if len(self.__result) > 0: msg = "\n".join(self.__result) raise AssertionError("\n" + msg) def __invoke_test(self, i, setup_method, teardown_method, test_func, *args): try: print("Run cycle {}".format(i + 1)) self.__invoke_hook_method(setup_method) test_func(*args) self.__invoke_hook_method(teardown_method) except (TestContextException, Exception) as e: tb = (traceback.format_tb(e.__traceback__)) print(tb) self.__result.append("Test Run {}: \n".format(i) + "\n".join(tb)) def __invoke_hook_method(self, func): try: func() except (TestContextException, Exception) as e: if not self.__is_continue: raise TestContextException(e) class BaseTest(unittest.TestCase): API_PAY_LOAD = [] GUI_SCREEN_SHOT = [] def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) self.__api_test = os.environ.get('api', False) self.TEST_CLASS = self self.__login = LoginPage() self.__register = RegisterPage() self.__dashboard = DashboardPage() self.__create_bot = CreateBotPage() self.__data = DataGenerateUtils() def setUp(self): self.API_PAY_LOAD = [] if not self.is_api_test: DriverFactory.create_driver() def repeated_setup(self): pass def repeated_teardown(self): pass def tearDown(self): if not self.is_api_test: DriverFactory.dispose_driver() @property def is_api_test(self): return self.__api_test @is_api_test.setter def is_api_test(self, is_api_test): self.__api_test = is_api_test def sign_in_for_ui_test(self, username=None, email=None, password=<PASSWORD>, bot_name=None, faq_url=None, is_debugging=False): try: if not is_debugging: # Generate data email = email or self.__data.create_email() username = username or self.__data.create_name() password = password or <PASSWORD>() bot_name = bot_name or self.__data.create_uuid_number() invalid_faq = faq_url or YAML_CONFIG.get("stub_invalid_faq_url") self.__register.open_register_page() self.__register.login_with_new_account(username, email, password) self.__create_bot.wait_for_create_page() self.__create_bot.create_bot_with_data(bot_name, invalid_faq) else: email = email or YAML_CONFIG.get("email_for_debugging") password = password or YAML_CONFIG.get("pass_for_debugging") self.__login.login_with_account(email, password) self.__dashboard.wait_for_dashboard_page() except Exception as e: raise TestContextException(e) @staticmethod def assert_container(func, expected, actual): return lambda: func(expected, actual)
hue715/BaiduPCS-Go-1
pcsutil/checksum/checksum.go
// Package checksum 校验本地文件包 package checksum import ( "crypto/md5" "github.com/Erope/BaiduPCS-Go/pcsutil/cachepool" "github.com/Erope/BaiduPCS-Go/pcsutil/converter" "hash/crc32" "io" "os" ) const ( // DefaultBufSize 默认的bufSize DefaultBufSize = int(256 * converter.KB) ) const ( // CHECKSUM_MD5 获取文件的 md5 值 CHECKSUM_MD5 int = 1 << iota // CHECKSUM_SLICE_MD5 获取文件前 sliceSize 切片的 md5 值 CHECKSUM_SLICE_MD5 // CHECKSUM_CRC32 获取文件的 crc32 值 CHECKSUM_CRC32 ) type ( // LocalFileMeta 本地文件元信息 LocalFileMeta struct { Path string `json:"path"` // 本地路径 Length int64 `json:"length"` // 文件大小 SliceMD5 []byte `json:"slicemd5"` // 文件前 requiredSliceLen (256KB) 切片的 md5 值 MD5 []byte `json:"md5"` // 文件的 md5 CRC32 uint32 `json:"crc32"` // 文件的 crc32 ModTime int64 `json:"modtime"` // 修改日期 } // LocalFileChecksum 校验本地文件 LocalFileChecksum struct { LocalFileMeta bufSize int sliceSize int buf []byte file *os.File // 文件 } ) func NewLocalFileChecksum(localPath string, sliceSize int) *LocalFileChecksum { return NewLocalFileChecksumWithBufSize(localPath, DefaultBufSize, sliceSize) } func NewLocalFileChecksumWithBufSize(localPath string, bufSize, sliceSize int) *LocalFileChecksum { return &LocalFileChecksum{ LocalFileMeta: LocalFileMeta{ Path: localPath, }, bufSize: bufSize, sliceSize: sliceSize, } } // OpenPath 检查文件状态并获取文件的大小 (Length) func (lfc *LocalFileChecksum) OpenPath() error { if lfc.file != nil { lfc.file.Close() } var err error lfc.file, err = os.Open(lfc.Path) if err != nil { return err } info, err := lfc.file.Stat() if err != nil { return err } lfc.Length = info.Size() lfc.ModTime = info.ModTime().Unix() return nil } // GetFile 获取文件 func (lfc *LocalFileChecksum) GetFile() *os.File { return lfc.file } // Close 关闭文件 func (lfc *LocalFileChecksum) Close() error { if lfc.file == nil { return ErrFileIsNil } return lfc.file.Close() } func (lfc *LocalFileChecksum) initBuf() { if lfc.buf == nil { lfc.buf = cachepool.RawMallocByteSlice(lfc.bufSize) } } func (lfc *LocalFileChecksum) writeChecksum(data []byte, wus ...*ChecksumWriteUnit) (err error) { doneCount := 0 for _, wu := range wus { _, err := wu.Write(data) switch err { case ErrChecksumWriteStop: doneCount++ continue case nil: default: return err } } if doneCount == len(wus) { return ErrChecksumWriteAllStop } return nil } func (lfc *LocalFileChecksum) repeatRead(wus ...*ChecksumWriteUnit) (err error) { if lfc.file == nil { return ErrFileIsNil } lfc.initBuf() defer func() { _, err = lfc.file.Seek(0, os.SEEK_SET) // 恢复文件指针 if err != nil { return } }() // 读文件 var ( n int ) read: for { n, err = lfc.file.Read(lfc.buf) switch err { case io.EOF: err = lfc.writeChecksum(lfc.buf[:n], wus...) break read case nil: err = lfc.writeChecksum(lfc.buf[:n], wus...) default: return } } switch err { case ErrChecksumWriteAllStop: // 全部结束 err = nil } return } func (lfc *LocalFileChecksum) createChecksumWriteUnit(cw ChecksumWriter, isAll, isSlice bool, getSumFunc func(sliceSum interface{}, sum interface{})) (wu *ChecksumWriteUnit, deferFunc func(err error)) { wu = &ChecksumWriteUnit{ ChecksumWriter: cw, End: lfc.LocalFileMeta.Length, OnlySliceSum: !isAll, } if isSlice { wu.SliceEnd = int64(lfc.sliceSize) } return wu, func(err error) { if err != nil { return } getSumFunc(wu.SliceSum, wu.Sum) } } // Sum 计算文件摘要值 func (lfc *LocalFileChecksum) Sum(checkSumFlag int) (err error) { lfc.fix() wus := make([]*ChecksumWriteUnit, 0, 2) if (checkSumFlag & (CHECKSUM_MD5 | CHECKSUM_SLICE_MD5)) != 0 { md5w := md5.New() wu, d := lfc.createChecksumWriteUnit( NewHashChecksumWriter(md5w), (checkSumFlag&CHECKSUM_MD5) != 0, (checkSumFlag&CHECKSUM_SLICE_MD5) != 0, func(sliceSum interface{}, sum interface{}) { if sliceSum != nil { lfc.SliceMD5 = sliceSum.([]byte) } if sum != nil { lfc.MD5 = sum.([]byte) } }, ) wus = append(wus, wu) defer d(err) } if (checkSumFlag & CHECKSUM_CRC32) != 0 { crc32w := crc32.NewIEEE() wu, d := lfc.createChecksumWriteUnit( NewHash32ChecksumWriter(crc32w), true, false, func(sliceSum interface{}, sum interface{}) { if sum != nil { lfc.CRC32 = sum.(uint32) } }, ) wus = append(wus, wu) defer d(err) } err = lfc.repeatRead(wus...) return } func (lfc *LocalFileChecksum) fix() { if lfc.sliceSize <= 0 { lfc.sliceSize = DefaultBufSize } if lfc.bufSize < DefaultBufSize { lfc.bufSize = DefaultBufSize } }
devjsc/ledger-1
libs/vectorise/tests/memory/shared_array_tests.cpp
<gh_stars>1-10 //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "core/random/lcg.hpp" #include "vectorise/memory/shared_array.hpp" #include <gtest/gtest.h> using namespace fetch::memory; using data_type = uint64_t; using array_type = SharedArray<data_type>; class TestClass : public ::testing::TestWithParam<int> { }; TEST_P(TestClass, basic_Test) { static fetch::random::LinearCongruentialGenerator lcg1, lcg2; lcg1.Reset(); lcg2.Reset(); std::size_t N = lcg1() % 100000; lcg2(); array_type array(N), other; for (std::size_t i = 0; i < N; ++i) { array[i] = lcg1(); } for (std::size_t i = 0; i < N; ++i) { EXPECT_EQ(array[i], lcg2()) << "1: memory doesn't store what it is supposed to"; } other = array; lcg2.Reset(); lcg2(); for (std::size_t i = 0; i < N; ++i) { EXPECT_EQ(other[i], lcg2()) << "2: memory doesn't store what it is supposed to"; } array_type yao(other); lcg2.Reset(); lcg2(); for (std::size_t i = 0; i < N; ++i) { EXPECT_EQ(yao[i], lcg2()) << "3: memory doesn't store what it is supposed to"; } // array = array; /* if(array.reference_count() != 3) { std::cout << "expected array to be referenced exactly 3 times"; std::cout << "but is referenced " << array.reference_count() << std::endl; } if(testing::total_shared_objects != 1) { std::cout << "expected exactly 1 object but " << testing::total_shared_objects; std::cout << "found" << std::endl; } */ lcg1.Seed(lcg1()); lcg2.Seed(lcg2()); } INSTANTIATE_TEST_CASE_P(Basic_test, TestClass, ::testing::Range(0, 100), );
MrManiak/Squad-SDK
Cpp/SDK/InputCapture_parameters.h
#pragma once // Name: S, Version: b #include "../SDK.h" #ifdef _MSC_VER #pragma pack(push, 0x01) #endif /*!!HELPER_DEF!!*/ /*!!DEFINE!!*/ namespace UFT { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function InputCapture.InputCapture_C.OnMouseMove struct UInputCapture_C_OnMouseMove_Params { struct FGeometry MyGeometry; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor) struct FPointerEvent MouseEvent; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) struct FEventReply ReturnValue; // (Parm, OutParm, ReturnParm) }; // Function InputCapture.InputCapture_C.OnKeyDown struct UInputCapture_C_OnKeyDown_Params { struct FGeometry MyGeometry; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor) struct FKeyEvent InKeyEvent; // (BlueprintVisible, BlueprintReadOnly, Parm) struct FEventReply ReturnValue; // (Parm, OutParm, ReturnParm) }; // Function InputCapture.InputCapture_C.OnMouseWheel struct UInputCapture_C_OnMouseWheel_Params { struct FGeometry MyGeometry; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor) struct FPointerEvent MouseEvent; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) struct FEventReply ReturnValue; // (Parm, OutParm, ReturnParm) }; // Function InputCapture.InputCapture_C.OnMouseButtonDown struct UInputCapture_C_OnMouseButtonDown_Params { struct FGeometry MyGeometry; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor) struct FPointerEvent MouseEvent; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) struct FEventReply ReturnValue; // (Parm, OutParm, ReturnParm) }; // Function InputCapture.InputCapture_C.EndInputCapture struct UInputCapture_C_EndInputCapture_Params { }; // Function InputCapture.InputCapture_C.BeginInputCapture struct UInputCapture_C_BeginInputCapture_Params { }; // Function InputCapture.InputCapture_C.OnInput__DelegateSignature struct UInputCapture_C_OnInput__DelegateSignature_Params { struct FKey InputKey; // (BlueprintVisible, BlueprintReadOnly, Parm, HasGetValueTypeHash) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
lgxkdream/algorithm-problems
src/io/github/lgxkdream/test/unit10/SumOfMutatedArrayClosestToTarget.java
<gh_stars>0 package io.github.lgxkdream.test.unit10; import java.util.Arrays; /** * @author <NAME> * @version 1.0.0 * @title 1300. 转变数组后最接近目标值的数组和 * @description * @since 2020-06-14 10:47 */ public class SumOfMutatedArrayClosestToTarget { public static void main(String[] args) { /** * 输出:3 * 解释:当选择 value 为 3 时,数组会变成 [3, 3, 3],和为 9 ,这是最接近 target 的方案。 */ System.out.println(findBestValue(new int[]{4, 9, 3}, 10)); /** * 输出:5 */ System.out.println(findBestValue(new int[]{2, 3, 5}, 10)); /** * 输出:11361 */ System.out.println(findBestValue(new int[]{60864, 25176, 27249, 21296, 20204}, 56803)); } /** * 数组的和 arr[0]+...+arr[i−1]+x∗(n−i) * * @param arr * @param target * @return */ public static int findBestValue(int[] arr, int target) { int len = arr.length; Arrays.sort(arr); int sum = 0; for (int i = 0; i < len; i++) { int avg = (target - sum) / (len - i); if (arr[i] > avg) { double temp = (double) (target - sum) / (len - i); if (temp - avg > 0.5) { return avg + 1; } else { return avg; } } sum += arr[i]; } return arr[len - 1]; } }
lechium/tvOS144Headers
Applications/Podcasts/MTTVDeleteTableViewCell.h
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import <UIKit/UITableViewCell.h> @interface MTTVDeleteTableViewCell : UITableViewCell { } - (void)updateColors; // IMP=0x00000001000f3e80 - (void)didUpdateFocusInContext:(id)arg1 withAnimationCoordinator:(id)arg2; // IMP=0x00000001000f3da8 - (void)setSelected:(_Bool)arg1 animated:(_Bool)arg2; // IMP=0x00000001000f3d58 - (void)setHighlighted:(_Bool)arg1 animated:(_Bool)arg2; // IMP=0x00000001000f3d08 - (id)initWithStyle:(long long)arg1 reuseIdentifier:(id)arg2; // IMP=0x00000001000f3c18 @end
jasonoctaviano/RPM
dev/freemodbus-v1.5.0/demo/LINUX/demo.c
<gh_stars>0 /* * FreeModbus Libary: Linux Demo Application * Copyright (C) 2006 <NAME> <<EMAIL>> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * File: $Id: demo.c,v 1.2 2006/10/12 08:12:06 wolti Exp $ */ /* ----------------------- Standard includes --------------------------------*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <pthread.h> #include <signal.h> /* ----------------------- Modbus includes ----------------------------------*/ #include "mb.h" #include "mbport.h" /* ----------------------- Defines ------------------------------------------*/ #define PROG "freemodbus" #define REG_INPUT_START 1000 #define REG_INPUT_NREGS 4 #define REG_HOLDING_START 2000 #define REG_HOLDING_NREGS 130 /* ----------------------- Static variables ---------------------------------*/ static USHORT usRegInputStart = REG_INPUT_START; static USHORT usRegInputBuf[REG_INPUT_NREGS]; static USHORT usRegHoldingStart = REG_HOLDING_START; static USHORT usRegHoldingBuf[REG_HOLDING_NREGS]; static enum ThreadState { STOPPED, RUNNING, SHUTDOWN } ePollThreadState; static pthread_mutex_t xLock = PTHREAD_MUTEX_INITIALIZER; static BOOL bDoExit; /* ----------------------- Static functions ---------------------------------*/ static BOOL bCreatePollingThread( void ); static enum ThreadState eGetPollingThreadState( void ); static void vSetPollingThreadState( enum ThreadState eNewState ); static void *pvPollingThread( void *pvParameter ); /* ----------------------- Start implementation -----------------------------*/ BOOL bSetSignal( int iSignalNr, void ( *pSigHandler ) ( int ) ) { BOOL bResult; struct sigaction xNewSig, xOldSig; xNewSig.sa_handler = pSigHandler; sigemptyset( &xNewSig.sa_mask ); xNewSig.sa_flags = 0; if( sigaction( iSignalNr, &xNewSig, &xOldSig ) != 0 ) { bResult = FALSE; } else { bResult = TRUE; } return bResult; } void vSigShutdown( int xSigNr ) { switch ( xSigNr ) { case SIGQUIT: case SIGINT: case SIGTERM: vSetPollingThreadState( SHUTDOWN ); bDoExit = TRUE; } } int main( int argc, char *argv[] ) { int iExitCode; CHAR cCh; const UCHAR ucSlaveID[] = { 0xAA, 0xBB, 0xCC }; if( !bSetSignal( SIGQUIT, vSigShutdown ) || !bSetSignal( SIGINT, vSigShutdown ) || !bSetSignal( SIGTERM, vSigShutdown ) ) { fprintf( stderr, "%s: can't install signal handlers: %s!\n", PROG, strerror( errno ) ); iExitCode = EXIT_FAILURE; } else if( eMBInit( MB_RTU, 0x0A, 0, 38400, MB_PAR_EVEN ) != MB_ENOERR ) { fprintf( stderr, "%s: can't initialize modbus stack!\n", PROG ); iExitCode = EXIT_FAILURE; } else if( eMBSetSlaveID( 0x34, TRUE, ucSlaveID, 3 ) != MB_ENOERR ) { fprintf( stderr, "%s: can't set slave id!\n", PROG ); iExitCode = EXIT_FAILURE; } else { vSetPollingThreadState( STOPPED ); /* CLI interface. */ printf( "Type 'q' for quit or 'h' for help!\n" ); bDoExit = FALSE; do { printf( "> " ); cCh = getchar( ); switch ( cCh ) { case 'q': bDoExit = TRUE; break; case 'd': vSetPollingThreadState( SHUTDOWN ); break; case 'e': if( bCreatePollingThread( ) != TRUE ) { printf( "Can't start protocol stack! Already running?\n" ); } break; case 's': switch ( eGetPollingThreadState( ) ) { case RUNNING: printf( "Protocol stack is running.\n" ); break; case STOPPED: printf( "Protocol stack is stopped.\n" ); break; case SHUTDOWN: printf( "Protocol stack is shuting down.\n" ); break; } break; case 'h': printf( "FreeModbus demo application help:\n" ); printf( " 'd' ... disable protocol stack.\n" ); printf( " 'e' ... enabled the protocol stack.\n" ); printf( " 's' ... show current status.\n" ); printf( " 'q' ... quit application.\n" ); printf( " 'h' ... this information.\n" ); printf( "\n" ); printf( "Copyright 2006 <NAME> <<EMAIL>>\n" ); break; default: if( !bDoExit && ( cCh != '\n' ) ) { printf( "illegal command '%c'!\n", cCh ); } break; } /* eat up everything untill return character. */ while( !bDoExit && ( cCh != '\n' ) ) { cCh = getchar( ); } } while( !bDoExit ); /* Release hardware resources. */ ( void )eMBClose( ); iExitCode = EXIT_SUCCESS; } return iExitCode; } BOOL bCreatePollingThread( void ) { BOOL bResult; pthread_t xThread; if( eGetPollingThreadState( ) == STOPPED ) { if( pthread_create( &xThread, NULL, pvPollingThread, NULL ) != 0 ) { bResult = FALSE; } else { bResult = TRUE; } } else { bResult = FALSE; } return bResult; } void * pvPollingThread( void *pvParameter ) { vSetPollingThreadState( RUNNING ); if( eMBEnable( ) == MB_ENOERR ) { do { if( eMBPoll( ) != MB_ENOERR ) break; usRegInputBuf[0] = ( USHORT ) rand( ); } while( eGetPollingThreadState( ) != SHUTDOWN ); } ( void )eMBDisable( ); vSetPollingThreadState( STOPPED ); return 0; } enum ThreadState eGetPollingThreadState( ) { enum ThreadState eCurState; ( void )pthread_mutex_lock( &xLock ); eCurState = ePollThreadState; ( void )pthread_mutex_unlock( &xLock ); return eCurState; } void vSetPollingThreadState( enum ThreadState eNewState ) { ( void )pthread_mutex_lock( &xLock ); ePollThreadState = eNewState; ( void )pthread_mutex_unlock( &xLock ); } eMBErrorCode eMBRegInputCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNRegs ) { eMBErrorCode eStatus = MB_ENOERR; int iRegIndex; if( ( usAddress >= REG_INPUT_START ) && ( usAddress + usNRegs <= REG_INPUT_START + REG_INPUT_NREGS ) ) { iRegIndex = ( int )( usAddress - usRegInputStart ); while( usNRegs > 0 ) { *pucRegBuffer++ = ( unsigned char )( usRegInputBuf[iRegIndex] >> 8 ); *pucRegBuffer++ = ( unsigned char )( usRegInputBuf[iRegIndex] & 0xFF ); iRegIndex++; usNRegs--; } } else { eStatus = MB_ENOREG; } return eStatus; } eMBErrorCode eMBRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNRegs, eMBRegisterMode eMode ) { eMBErrorCode eStatus = MB_ENOERR; int iRegIndex; if( ( usAddress >= REG_HOLDING_START ) && ( usAddress + usNRegs <= REG_HOLDING_START + REG_HOLDING_NREGS ) ) { iRegIndex = ( int )( usAddress - usRegHoldingStart ); switch ( eMode ) { /* Pass current register values to the protocol stack. */ case MB_REG_READ: while( usNRegs > 0 ) { *pucRegBuffer++ = ( UCHAR ) ( usRegHoldingBuf[iRegIndex] >> 8 ); *pucRegBuffer++ = ( UCHAR ) ( usRegHoldingBuf[iRegIndex] & 0xFF ); iRegIndex++; usNRegs--; } break; /* Update current register values with new values from the * protocol stack. */ case MB_REG_WRITE: while( usNRegs > 0 ) { usRegHoldingBuf[iRegIndex] = *pucRegBuffer++ << 8; usRegHoldingBuf[iRegIndex] |= *pucRegBuffer++; iRegIndex++; usNRegs--; } } } else { eStatus = MB_ENOREG; } return eStatus; } eMBErrorCode eMBRegCoilsCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNCoils, eMBRegisterMode eMode ) { return MB_ENOREG; } eMBErrorCode eMBRegDiscreteCB( UCHAR * pucRegBuffer, USHORT usAddress, USHORT usNDiscrete ) { return MB_ENOREG; }
LakshyAAAgrawal/streamblocks-graalvm
language/src/main/java/ch/epfl/vlsc/truffle/cal/nodes/expression/literals/FunctionLiteralNode.java
<gh_stars>10-100 package ch.epfl.vlsc.truffle.cal.nodes.expression.literals; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.frame.VirtualFrame; import ch.epfl.vlsc.truffle.cal.CALLanguage; import ch.epfl.vlsc.truffle.cal.nodes.CALExpressionNode; import ch.epfl.vlsc.truffle.cal.runtime.CALFunction; public final class FunctionLiteralNode extends CALExpressionNode { /** * The name of the function. */ private final String functionName; @CompilerDirectives.CompilationFinal private CALFunction cachedFunction; public FunctionLiteralNode(String functionName) { this.functionName = functionName; } public String getFunctionName() { return functionName; } @Override public CALFunction executeGeneric(VirtualFrame frame) { if (cachedFunction == null) { /* We are about to change a @CompilationFinal field. */ CompilerDirectives.transferToInterpreterAndInvalidate(); /* First execution of the node: lookup the function in the function registry. */ cachedFunction = lookupContextReference(CALLanguage.class).get().getFunctionRegistry().lookup(functionName, true); } return cachedFunction; } }
vnerozin/cimlib
platforms/portable/frm_math/frm_ema_s16.c
<reponame>vnerozin/cimlib<filename>platforms/portable/frm_math/frm_ema_s16.c /******************************************************************************* * Copyright (c) 2017 <NAME> * * This library is free software; you can redistribute it and/or modify it * under the terms of the MIT license. See LICENSE.md for details. ******************************************************************************/ /* ----------------------------------------------------------------------------- * Includes * ---------------------------------------------------------------------------*/ #include <string.h> #include "cimlib.h" /* Library header */ /* ----------------------------------------------------------------------------- * Exported functions * ---------------------------------------------------------------------------*/ /******************************************************************************* * This function perform EMA (Exponential Moving Average) of vector, * frame based, 16 bit signed. Use 'CIMLIB_EMA_TIME_2_ALPHA_S16' macro * to convert EMA time constant into alpha. * * @param[in,out] pX Pointer to input/output vector, 16 bit signed. * @param[in] len Vector length. * @param[in] acc Accumulator (previous EMA), 16 bit signed. * @param[in] alpha Alpha, [0..1.0], 16 bit signed. * @param[in] radix Radix. * * @return New EMA (accumulator), 16 bit signed. ******************************************************************************/ int16_t frm_ema_s16(int16_t *pX, int len, int16_t acc, int16_t alpha, int radix) { int n; int32_t tmp; int16_t rnd = 0; /* For correct rounding add half of radix */ if (radix != 0) { rnd = (1 << (radix - 1)); } /* EMA */ for (n = 0; n < len; n++) { tmp = (int32_t)alpha * (pX[n] - acc); acc += (int16_t)((tmp + rnd) >> radix); pX[n] = acc; } return acc; } #if (CIMLIB_BUILD_TEST == 1) /* Simplify macroses for fixed radix */ #define RADIX (12) #define CONST(X) CIMLIB_CONST_S16(X, RADIX) #define EMA_TIME_2_ALPHA(TIME, FREQS) \ CIMLIB_EMA_TIME_2_ALPHA_S16(TIME, FREQS, RADIX) /******************************************************************************* * This function tests 'frm_ema_s16' function. Returns 'true' if validation * is successfully done, 'false' - otherwise. ******************************************************************************/ bool test_frm_ema_s16(void) { int16_t z[4]; static int16_t alpha = EMA_TIME_2_ALPHA(1.0, 20.0); static int16_t res[4] = { CONST(9.4995117188E-01), CONST(9.0234375000E-01), CONST(8.5717773438E-01), CONST(8.1420898438E-01) }; bool flOk = true; /* Reset output vector */ (void)memset(z, 0, 4 * sizeof(int16_t)); /* Call 'sc_ema_s16' function */ (void)frm_ema_s16(z, 4, CONST(1.0), alpha, RADIX); /* Check the correctness of the result */ TEST_LIBS_CHECK_RES_REAL(z, res, 4, flOk); return flOk; } #endif /* (CIMLIB_BUILD_TEST == 1) */
naoki-iwami/ermaster-b
src/org/insightech/er/db/impl/sqlserver/SqlServerDDLCreator.java
package org.insightech.er.db.impl.sqlserver; import org.insightech.er.db.impl.db2.tablespace.DB2TablespaceProperties; import org.insightech.er.editor.model.ERDiagram; import org.insightech.er.editor.model.dbexport.ddl.DDLCreator; import org.insightech.er.editor.model.diagram_contents.element.node.table.column.NormalColumn; import org.insightech.er.editor.model.diagram_contents.not_element.sequence.Sequence; import org.insightech.er.editor.model.diagram_contents.not_element.tablespace.Tablespace; import org.insightech.er.util.Check; public class SqlServerDDLCreator extends DDLCreator { public SqlServerDDLCreator(ERDiagram diagram, boolean semicolon) { super(diagram, semicolon); } /** * {@inheritDoc} */ @Override protected String getColulmnDDL(NormalColumn normalColumn) { StringBuilder ddl = new StringBuilder(); ddl.append(super.getColulmnDDL(normalColumn)); if (normalColumn.isAutoIncrement()) { ddl.append(" IDENTITY "); Sequence sequence = normalColumn.getAutoIncrementSetting(); if (sequence.getIncrement() != null || sequence.getStart() != null) { ddl.append("("); if (sequence.getStart() != null) { ddl.append(sequence.getStart()); } else { ddl.append("1"); } if (sequence.getIncrement() != null) { ddl.append(", "); ddl.append(sequence.getIncrement()); } ddl.append(")"); } } return ddl.toString(); } @Override protected String getDDL(Tablespace tablespace) { DB2TablespaceProperties tablespaceProperties = (DB2TablespaceProperties) tablespace .getProperties(this.environment, this.getDiagram()); StringBuilder ddl = new StringBuilder(); ddl.append("CREATE "); if (!Check.isEmpty(tablespaceProperties.getType())) { ddl.append(tablespaceProperties.getType()); ddl.append(" "); } ddl.append("TABLESPACE "); ddl.append(filter(tablespace.getName())); ddl.append("\r\n"); if (!Check.isEmpty(tablespaceProperties.getPageSize())) { ddl.append(" PAGESIZE "); ddl.append(tablespaceProperties.getPageSize()); ddl.append("\r\n"); } ddl.append(" MANAGED BY "); ddl.append(tablespaceProperties.getManagedBy()); ddl.append(" USING("); ddl.append(tablespaceProperties.getContainer()); ddl.append(")\r\n"); if (!Check.isEmpty(tablespaceProperties.getExtentSize())) { ddl.append(" EXTENTSIZE "); ddl.append(tablespaceProperties.getExtentSize()); ddl.append("\r\n"); } if (!Check.isEmpty(tablespaceProperties.getPrefetchSize())) { ddl.append(" PREFETCHSIZE "); ddl.append(tablespaceProperties.getPrefetchSize()); ddl.append("\r\n"); } if (!Check.isEmpty(tablespaceProperties.getBufferPoolName())) { ddl.append(" BUFFERPOOL "); ddl.append(tablespaceProperties.getBufferPoolName()); ddl.append("\r\n"); } if (this.semicolon) { ddl.append(";"); } return ddl.toString(); } }
woodkri/ec
org.schema/src/main/java/org/schema/RadioStation.java
<filename>org.schema/src/main/java/org/schema/RadioStation.java package org.schema; /** * Schema.org/RadioStation * A radio station. * * @author schema.org * @class RadioStation * @module org.schema * @extends LocalBusiness */ public class RadioStation extends LocalBusiness { /** * Constructor, automatically sets @context and @type. * * @constructor */ public RadioStation() { context = "http://schema.org/"; type = "RadioStation"; } }
nomadsinteractive/ark
platform/darwin/platform/log.h
<reponame>nomadsinteractive/ark #ifndef ARK_PLATFORMS_ANDROID_PLATFORM_LOG_H_ #define ARK_PLATFORMS_ANDROID_PLATFORM_LOG_H_ #define LOGD(...) #define LOGE(...) #endif
cirquit/random-code
C/Systempraktikum/Aufgaben03/Multithreading/ThreadsExample2.c
<filename>C/Systempraktikum/Aufgaben03/Multithreading/ThreadsExample2.c #define _BSD_SOURCE // for usleep - has to be the first thing to declare #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <semaphore.h> /* This is our thread function. It is like main(), but for a thread*/ void *threadFunc(void *arg) { char *str; int i = 0; str=(char*)arg; while(i < 15 ) { usleep(1); printf("threadFunc says: %s\n",str); ++i; } return NULL; } int main(void) { pthread_t pth; // this is our thread identifier int i = 0; pthread_create(&pth,NULL,threadFunc,"foo"); while(i < 10) { usleep(1); printf("main is running...\n"); ++i; } printf("main waiting for thread to terminate...\n"); pthread_join(pth,NULL); return 0; }
lechium/tvOS124Headers
System/Library/Frameworks/ContactsUI.framework/CNPropertyGroupItemDelegate.h
<reponame>lechium/tvOS124Headers<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.0 * on Saturday, August 24, 2019 at 9:45:13 PM Mountain Standard Time * Operating System: Version 12.4 (Build 16M568) * Image Source: /System/Library/Frameworks/ContactsUI.framework/ContactsUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ @protocol CNPropertyGroupItemDelegate <NSObject> @optional -(void)propertyItem:(id)arg1 willChangeValue:(id)arg2; -(id)storeForPropertyItem:(id)arg1; @end
daniol/angular-line-awesome
projects/angular-line-awesome/icons/build/-lab-uikit.icon.js
export const labUikit = { name: 'lab-uikit', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path d="M22.2 6.7l-4.3 2.5 5.1 2.9v7.8L16 24l-7-4.1v-5.5L5 12v10.5L16 29l11-6.5v-13zm-2-1.2L16 3l-4.2 2.5L16 8z"/></svg>` };
357758509/vuemusic
src/router/index.js
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const routes = [ { path: '', redirect: '/index' }, { name: 'index', path: '/index', component: () => import('@/pages/index/index') // 懒加载引入方式 }, { name: 'detail', path: '/detail', component: () => import('@/pages/detail/detail') } ] export default new Router({ routes: routes, // 使用<keep-alive>,scrollBehavior才能生效。 scrollBehavior(to, from, savedPosition) { if (savedPosition) { return savedPosition } else { return { x: 0, y: 0 } } } })
lechium/iOS1351Headers
usr/libexec/CarPlay/CARHomeKitServiceTypes.h
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @interface CARHomeKitServiceTypes : NSObject { } + (id)serviceNameForType:(id)arg1; // IMP=0x00000001000972e8 + (id)serviceNameByType; // IMP=0x0000000100097210 + (id)serviceTypeByName; // IMP=0x0000000100097134 @end
mypetrobot/lfmwk
src/commands/powerambient.js
<filename>src/commands/powerambient.js const Command = require('../handler/Command') const BotEmbed = require('../classes/BotEmbed') const { stringify } = require('querystring') const fetch = require('node-fetch') const capitalize = (s) => { if (typeof s !== 'string') return '' return s.charAt(0).toUpperCase() + s.slice(1) } function sleep(ms){ return new Promise(resolve=>{ setTimeout(resolve,ms) }) } class PowerAmbientCommand extends Command { constructor() { super({ name: 'powerambient', usage: ['powerambient'], aliases: ['pa'], hidden: true }) } async run(client, message, args) { if((message.author.id==client.ownerID)||(message.author.id=="<PASSWORD>")||(message.author.id=="<PASSWORD>")||(message.author.id=="<PASSWORD>")||(message.author.id=="<PASSWORD>")||(message.author.id=="<PASSWORD>")||(message.author.id=="5<PASSWORD>")||(message.author.id=="<PASSWORD>")){ const council=[ 'mypetrobot', 'moth', 'Jess', 'ea_n', 'Horizons', 'Mr_Chris', 'Ivana__1902', 'vapor' ] let word0=[ 'Imagine', 'Picture', 'Embrace', 'Discover', 'Explore', 'Immerse yourself in', 'Inhale', 'Feel the', 'Experience', 'Delve into', 'Worship', 'Kneel before', 'Become enlighted by', 'Pray at the altar of', 'Meditate upon', 'Travel to worlds of', 'Become one with', 'Swear allegiance to', 'Obey', 'Bow before', 'Invoke', 'Call forth', 'Summon', 'Plunge deeper into' ] let word1=[ 'transcendent', 'frozen', 'ambient', 'powerful', 'deep', 'lush', 'expansive', 'dynamic', 'barren', 'icy', 'swollen', 'swelling', 'haunting', 'foggy', 'dizzying', 'contemplative', 'rumbling', 'dense', 'ghostly', 'elusive', 'glassy', 'crystalline', 'chilling', 'ethereal', 'massive', 'rich', 'patient', 'fractured', 'meditative', 'resonant', 'cinematic', 'hypnotic', 'mysterious', 'spacious', 'cavernous', 'chilling', 'extraterrestrial', 'terrestrial', 'empyrean', 'divine', 'mesmerizing', 'ancient', 'digital', 'supernatural', 'arcane', 'forbidden', 'spiritual', 'sparkling', 'glittering', 'hazy', 'mutant', 'shadowy', 'blurry', 'dark', 'rippling', 'billowing', 'enchanted', 'meaty', 'heavy', 'ornate', 'yawning', 'chasmal', 'sunken', 'vast', 'boundless', 'immense', 'impenetrable', 'cabalistic', 'unknowable', 'abstruse', 'hidden', 'hallowed', 'consecrated', 'unworldly', 'intense', 'alien', 'violent', 'restful', 'distant', 'gargantuan', 'distorted', 'crackling', 'thunderous', 'active', 'warped', 'dusty', 'aqueous' ] let word2=[ 'sound', 'drone', 'power', 'aural', 'aural', 'sonic', 'sonic', 'timbral', 'timbral', 'tonal', 'tonal', 'auditory', 'auditory', 'cosmic', 'cryptic', 'enigmatic', 'layered', 'haunted', 'temporal', 'acoustic', 'mystic', 'static', 'auricular', 'infinite', 'electroacoustic', 'radiant', 'metallic', 'choral', 'acoustoelectric', 'eternal', 'metaphysical', 'spectral', 'phantasmal', 'holy', 'intergalactic', 'apocalyptic', 'acoustical', 'seismic', 'paradoxical', 'geometric' ] let word3=[ 'space', 'spaces', 'ambience', 'drones', 'tones', 'washes', 'swells', 'dynamics', 'layers', 'fever dreams', 'voices', 'timbres', 'textures', 'patterns', 'landscapes', 'moods', 'gravity', 'motion', 'expanses', 'soundscapes', 'presence', 'energy', 'rituals', 'undercurrents', 'drama', 'colors', 'manipulation', 'shifts', 'noise', 'density', 'weight', 'atmosphere', 'volume', 'hum', 'vibrations', 'tonality', 'reverberation', 'pulses', 'shimmer', 'motifs', 'haze', 'forms', 'themes', 'bursts', 'crescendos', 'surges', 'ripples', 'echoes', 'harmony', 'silence', 'tranquility', 'figures', 'arrangements', 'hymns', 'cacophony', 'discord', 'suffocation', 'spaciousness', 'feedback', 'thunderclaps', 'intensity', 'lushness', 'realms', 'anomalies', 'aberrations' ] let word4=[ 'blended with', 'paired with', 'and', 'layered with', 'mixed with', 'as well as', 'combined with', 'punctuated by', 'enhanced by', 'running parallel to', 'tiptoeing beside', 'skittering beside', 'enveloped in', 'surrounded by', 'wrapped in', 'engulfed in', 'wrapped around', 'mingling with', 'accompanied by', 'contrasted by', 'swimming in', 'embracing', 'echoing out from', 'dividing', 'swallowing up', 'exhaling', 'beckoning' ] if (args.length === 0) { await message.react('🌩') let totalmsg=125 let msgnumber = Math.floor(Math.random() * totalmsg) let msg="" switch (msgnumber) { case 0: msg="> Where ambient is apt to wash over you, power ambient demands you pay attention to its constant shifts in mood and intensity." msg+="\n- `<NAME>` *(Fact Magazine)*" break case 1: msg="> Played at low volumes it can be quite soothing, but by and large ambient's relaxing qualities don't apply here. This music is altogether harsher and meatier, rough with grit and teeming with motion, even as it keeps much of the space and stillness of ambient music at its heart." msg+="\n- `<NAME>` *(Fact Magazine)*" break case 2: msg="> Perhaps you could call it \"power ambient\" - there is force to the music, some of it has certain gravity, but it is not meant to be overpowering." msg+="\n- `<NAME>` *(DJ & Blogger)*" break case 3: msg="> Many of 2014's best \"power ambient\" LPs lay at the intersection of noise, dance music and ambient." msg+="\n- `<NAME>` *(Fact Magazine)*" break case 4: msg="> The tones are shimmering, but possibly only from the stream of tears that they evoke." msg+="\n- `<NAME>` *(Blogger)*" break case 5: msg="> ...shouldered on sustained tones and crackled ozone drones that hit the listener squarely in solar plexus..." msg+="\n- `<NAME>` *(Blogger)*" break case 6: msg="> Powerful drone-ambient pieces ... all developed methodically and patiently as mysterious, otherworldly rituals." msg+="\n- `<NAME>` *(Blogger)*" break case 7: msg="> The sonic textures sound timeless, even static, but patiently more colors and shades are revealed and morph into powerful, dense walls of sounds." msg+="\n- `<NAME>` *(Blogger)*" break case 8: msg="> ...contemplative and minimalist ambient soundscapes, each with its own subtle, dramatic dynamics." msg+="\n- `<NAME>` *(Blogger)*" break case 9: msg="> The result is smudged without being indistinct, its filigree detail adding density to its ominous weight rather than detracting from it." msg+="\n- `<NAME>` *(Fact Magazine)*" break case 10: msg="> Although \"power ambient\" seems like an oxymoron, it's a useful catchall term for music you could very loosely group with ambient, but that also shares characteristics with extreme styles and dance music, drawing on doom, drone, noise, dub, industrial and techno." msg+="\n- `<NAME>` *(Fact Magazine)*" break case 11: msg="> ...temporal manipulation with dense layers of percussion, monumental drones and lashes of noise pitted against a vast expanse of empty space." msg+="\n- `<NAME>` *(Fact Magazine)*" break case 12: msg="> ...each piece a riot of abrasive textures, crushing dynamics and thunderous bass." msg+="\n- `<NAME>` *(Fact Magazine)*" break case 13: msg="> ...skitter across moods, with nostalgia provided by viscous synths and wan melodies, while deep bass rumbles and sheets of white noise rise that dissolve as rapidly as they rise inject the atmosphere with intense drama." msg+="\n- `<NAME>` *(Fact Magazine)*" break case 14: msg="https://www.last.fm/tag/power+ambient" break case 15: msg="https://open.spotify.com/album/0QqlIeJRDX0ZeSpiHPLWxY?si=ngNB81oARvuD1Nrm_-YOkw" break default: let rannumber = Math.floor(Math.random() * 3) switch (rannumber) { case 0: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word2[Math.floor(Math.random() * word2.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break case 1: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word2[Math.floor(Math.random() * word2.length)]+" "+word3[Math.floor(Math.random() * word3.length)]+" "+word4[Math.floor(Math.random() * word4.length)]+" "+word1[Math.floor(Math.random() * word1.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break case 2: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break } msg="**"+word0[Math.floor(Math.random() * word0.length)]+" "+msg+".**" } await message.channel.send(msg) }else{ await message.react('🌌') let validartists=[ { name:'<NAME>', relic:'\🍭 Staff of Heckfire', relicatk: 8, relicdef: 0, relicintel: 0, relicfire: 2, relicearth: 0, relicair: 0, relicwater: 0, atk: .6, def: .1, intel: .3, fire: .75, earth: .1, air: .15, water: 0 },{ name:'<NAME>', relic:'\🥀 Thorns of Self-Exorcism', relicatk: 5, relicdef: 0, relicintel: 0, relicfire: 0, relicearth: 5, relicair: 0, relicwater: 0, atk: .4, def: .3, intel: .3, fire: .1, earth: .9, air: 0, water: 0 },{ name:'<NAME>', relic:'\📔 Tome of Alien Mathematics', relicatk: 0, relicdef: 0, relicintel: 10, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .2, def: 0, intel: .8, fire: .15, earth: 0, air: .85, water: 0 },{ name:'<NAME>', relic:'\⛸ Boots of Frostwalking', relicatk: 0, relicdef: 0, relicintel: 0, relicfire: 0, relicearth: 5, relicair: 0, relicwater: 5, atk: .7, def: .2, intel: .1, fire: 0, earth: 0, air: 0, water: 1 },{ name:'Motion Sickness of Time Travel', relic:'\💊 Transtemporal Dramamine', relicatk: 0, relicdef: 5, relicintel: 5, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .3, def: .3, intel: .4, fire: .25, earth: .25, air: .25, water: .25 },{ name:'<NAME>', relic:'\🏹 Bow Forged of Layered Roots', relicatk: 10, relicdef: 0, relicintel: 0, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .2, def: .5, intel: .3, fire: 0, earth: .9, air: .1, water: 0 },{ name:'<NAME>', relic:'\✝ The Crux Conspiro', relicatk: 0, relicdef: 8, relicintel: 2, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .5, def: .2, intel: .3, fire: .2, earth: .55, air: .1, water: .15 },{ name:'<NAME>', relic:'\📜 Scroll of the Common Tongue', relicatk: 0, relicdef: 0, relicintel: 10, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .3, def: .4, intel: .3, fire: .1, earth: .8, air: 0, water: .1 },{ name:'<NAME>', relic:'\🍺 Enchanted Ale of Tumbling', relicatk: 5, relicdef: 5, relicintel: 0, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .6, def: .3, intel: .1, fire: .1, earth: .5, air: .2, water: .2 },{ name:'<NAME>', relic:'\🏊 The Diver\'s Lung', relicatk: 0, relicdef: 0, relicintel: 0, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 10, atk: .7, def: .1, intel: .2, fire: 0, earth: 0, air: .15, water: .85 },{ name:'<NAME>', relic:'\⏱ The Hypnotist\'s Pocketwatch', relicatk: 0, relicdef: 2, relicintel: 8, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .5, def: .4, intel: .1, fire: .1, earth: .1, air: .5, water: .3 },{ name:'<NAME>', relic:'\📐 Implements of Far-Eastern Geometry', relicatk: 0, relicdef: 0, relicintel: 10, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .3, def: .4, intel: .3, fire: .2, earth: .8, air: 0, water: 0 },{ name:'<NAME>', relic:'\💍 Ring of Paradoxical Silence', relicatk: 0, relicdef: 5, relicintel: 5, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .2, def: .6, intel: .2, fire: .25, earth: .25, air: .25, water: .25 },{ name:'Ø', relic:'\🥄 Null Rod', relicatk: 6, relicdef: 0, relicintel: 4, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .7, def: .1, intel: .2, fire: .25, earth: .25, air: .25, water: .25 },{ name:'<NAME>', relic:'\💿 Shard of the Forgotten Format', relicatk: 5, relicdef: 0, relicintel: 5, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .8, def: .2, intel: 0, fire: .25, earth: .25, air: .25, water: .25 },{ name:'<NAME>', relic:'\🥁 Goblin War Drums', relicatk: 10, relicdef: 0, relicintel: 0, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .5, def: .5, intel: 0, fire: .5, earth: .5, air: 0, water: 0 },{ name:'Fennesz', relic:'\🌓 Static Orb', relicatk: 0, relicdef: 0, relicintel: 5, relicfire: 0, relicearth: 0, relicair: 5, relicwater: 0, atk: .1, def: .2, intel: .7, fire: .15, earth: .05, air: .75, water: .05 },{ name:'<NAME>', relic:'\🦉 The Drone Wizard\'s Familiar', relicatk: 0, relicdef: 0, relicintel: 7, relicfire: 0, relicearth: 0, relicair: 3, relicwater: 0, atk: .1, def: .7, intel: .2, fire: .6, earth: .2, air: .2, water: 0 },{ name:'<NAME>', relic:'\🔔 The Court Jester\'s Bell', relicatk: 5, relicdef: 0, relicintel: 5, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .7, def: .2, intel: .1, fire: .6, earth: .2, air: .2, water: 0 },{ name:'<NAME>', relic:'\☁ Nimbostratus Apparatus', relicatk: 0, relicdef: 0, relicintel: 0, relicfire: 0, relicearth: 0, relicair: 10, relicwater: 0, atk: .1, def: .4, intel: .5, fire: 0, earth: 0, air: 1, water: 0 },{ name:'<NAME>', relic:'\🎻 Strings of Infinite Sustain', relicatk: 0, relicdef: 0, relicintel: 5, relicfire: 0, relicearth: 0, relicair: 5, relicwater: 0, atk: .4, def: .5, intel: .1, fire: 0, earth: .8, air: 0, water: .2 },{ name:'<NAME>', relic:'\🧭 Elven Compass', relicatk: 0, relicdef: 0, relicintel: 5, relicfire: 0, relicearth: 5, relicair: 0, relicwater: 0, atk: .2, def: .2, intel: .6, fire: 0, earth: .5, air: .5, water: 0 },{ name:'<NAME>', relic:'\🧽 Kerchief of Maximum Absorption', relicatk: 0, relicdef: 7, relicintel: 0, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 3, atk: .4, def: .4, intel: 0, fire: 0, earth: .3, air: .7, water: 0 },{ name:'<NAME>', relic:'\🌫️ Wings of Deterioration', relicatk: 6, relicdef: 0, relicintel: 4, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .6, def: 0, intel: .4, fire: .7, earth: 0, air: .15, water: .15 },{ name:'Sjellos', relic:'\🔮 Power Core of Unearthly Vibrations', relicatk: 0, relicdef: 7, relicintel: 3, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .6, def: 0, intel: .4, fire: 0, earth: .45, air: .1, water: .45 },{ name:'<NAME>', relic:'\🌊 Wave of Nonexistent Perfection', relicatk: 0, relicdef: 0, relicintel: 5, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 5, atk: 0, def: .25, intel: .75, fire: 0, earth: 0, air: .4, water: .6 },{ name:'<NAME>', relic:'\🚩 Rose-Coloured Banner of Resonance', relicatk: 0, relicdef: 6, relicintel:4, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .1, def: .7, intel: .2, fire: 0, earth: .2, air: .4, water: .4 },{ name:'<NAME>', relic:'\🦋 Cocoon of Artificial Transformation', relicatk: 0, relicdef: 9, relicintel:1, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .3, def: .5, intel: .2, fire: 0, earth: .4, air: .2, water: .4 },{ name:'Lumisokea', relic:'\⚖️ Balance of Reticence and Impulse', relicatk: 0, relicdef: 2, relicintel:8, relicfire: 0, relicearth: 0, relicair: 0, relicwater: 0, atk: .3, def: .2, intel: .5, fire: .2, earth: .7, air: .0, water: .1 } ] let leveltitles=[ 'Neophyte', 'Novice', 'Apprentice', 'Journeyman', 'Expert', 'Adept', 'Master', 'Grandmaster', 'Elder', 'Legendary' ] let wizards=[ 'Wizard', 'Mage', 'Clairvoyant', 'Conjurer', 'Diviner', 'Enchanter', 'Medium', 'Necromancer', 'Occultist', 'Seer', 'Shaman', 'Sorcerer', 'Alchemist', 'Scholar', 'Healer', 'Mystic', 'Arcanist', 'Spellcaster', 'Timelord', 'Archmage', 'Druid', 'Haruspex', 'Channeller', 'Psychic', 'Soothsayer', 'Prophet', 'Telepathist', 'Oracle', 'Harbinger', 'Theurgist', 'Elementalist', 'Abjurer', 'Apparitionist', 'Animist', 'Augurer', 'Chronomancer', 'Cryptomancer', 'Diabolist', 'Dowser', 'Empath', 'Evoker', 'Maledict', 'Mesmerist', 'Oneiromancer', 'Runecaster', 'Ritualist', 'Scryer' ] if((args[0].toLowerCase()=='gospel')||(args[0].toLowerCase()=='g')){ await message.react('📜') let num=0 let msg="" let rannumber = Math.floor(Math.random() * 3) switch (rannumber) { case 0: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word2[Math.floor(Math.random() * word2.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break case 1: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word2[Math.floor(Math.random() * word2.length)]+" "+word3[Math.floor(Math.random() * word3.length)]+" "+word4[Math.floor(Math.random() * word4.length)]+" "+word1[Math.floor(Math.random() * word1.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break case 2: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break } let qname=validartists[Math.floor(Math.random() * validartists.length)].name.split(' ') msg="*\""+word0[Math.floor(Math.random() * word0.length)]+" "+msg+".\" ("+qname[qname.length-1]+" "+(Math.floor(Math.random() * 39)+1)+":"+(Math.floor(Math.random() * 49)+1)+")*" if(args.length>1){ let chosenartist=parseInt(args[1])-1 if((chosenartist<0)||(chosenartist>validartists.length-1)){ await message.channel.send(msg) return }else{ switch (rannumber) { case 0: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word2[Math.floor(Math.random() * word2.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break case 1: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word2[Math.floor(Math.random() * word2.length)]+" "+word3[Math.floor(Math.random() * word3.length)]+" "+word4[Math.floor(Math.random() * word4.length)]+" "+word1[Math.floor(Math.random() * word1.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break case 2: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break } qname=validartists[chosenartist].name.split(' ') msg="*\""+word0[Math.floor(Math.random() * word0.length)]+" "+msg+".\" ("+qname[qname.length-1]+" "+(Math.floor(Math.random() * 39)+1)+":"+(Math.floor(Math.random() * 49)+1)+")*" const allcrowns = await client.models.crowns.findAll({ where: { guildID: message.guild.id, artistName: validartists[chosenartist].name } }) let relicowner="no one" if (allcrowns.length > 0) { //await message.reply('**'+ message.guild.members.cache.get(allcrowns[0].userID).user.username+'** has the crown for **' + artistName+'** with **'+ allcrowns[0].artistPlays + "** plays.") relicowner= message.guild.members.cache.get(allcrowns[0].userID).user.username } let relicplays="" try{ relicplays+=" with "+allcrowns[0].artistPlays+" plays" }catch{ } const description = "**Relic:** \n" + "`"+validartists[chosenartist].relic+"` \n*(Currently possessed by "+relicowner+relicplays+")*\n\n" + "**Elemental Alignment:**\n" + '`\🌲 '+`${parseInt(validartists[chosenartist].earth*100)}`+'% | \💧 '+`${parseInt(validartists[chosenartist].water*100)}`+'% | \💨 '+`${parseInt(validartists[chosenartist].air*100)}`+'% | \🔥 '+`${parseInt(validartists[chosenartist].fire*100)}`+'%`' const embed = new BotEmbed(message) .setTitle(`The Gospel of ${validartists[chosenartist].name}`) .setDescription(description+'\n\n'+msg) await message.channel.send(embed) } }else{ const description = validartists //.map(x => `**${x.name}:** `+'`\🌲 '+`${parseInt(x.earth*100)}`+'% | \💧 '+`${parseInt(x.water*100)}`+'% | \💨 '+`${parseInt(x.air*100)}`+'% | \🔥 '+`${parseInt(x.fire*100)}`+'%`') .map(x => `${++num}. **${x.name}** `) .join('\n') const embed = new BotEmbed(message) .setTitle(`The Gospel`) .setDescription(description+'\n\n'+msg) await message.channel.send(embed) } }else{ let spellicons=[ '✨', //sparkles '☄', //comet '⚡', //zap '🔥', //fire '💥', //boom '💫', //dizzy '☠', //skullcrossbones '❄', //snowflake '💨', //dash '🌀', //cyclone '☢️', //radioactive '💠', //diamond shape '💢', //anger '💮' //white flower ] let levelxp=[] for(let z=0;z<=100;z++){ //levelxp.push(Math.floor(((4 * (Math.pow(z, 2.5)))/5)/6)) levelxp.push(Math.floor(.3 * Math.pow(z, 2.2))) } levelxp[2]=1 const { bans, users, crowns } = client.models let checkuser = message.mentions.members.first() const user = await users.findOne({ where: { userID: checkuser.id } }) let xp=0 let mostplays=0 let affinity="None" let inventory=[] let elements={fire:0,earth:0,air:0,water:0} let stats={atk:0,def:0,intel:0} let books=0 for(let i=0;i<validartists.length;i++){ const allcrowns = await client.models.crowns.findAll({ where: { guildID: message.guild.id, artistName: validartists[i].name } }) if (allcrowns.length > 0) { if( message.guild.members.cache.get(allcrowns[0].userID).user.username==checkuser.user.username){ //console.log('found crown for '+validartists[i]+' - '+user) let statmsg="" if(validartists[i].relicatk>0){ statmsg+='+'+validartists[i].relicatk+' ATK ' } if(validartists[i].relicdef>0){ statmsg+='+'+validartists[i].relicdef+' DEF ' } if(validartists[i].relicintel>0){ statmsg+='+'+validartists[i].relicintel+' INT ' } + '> **Elemental Alignment:**\n> `\🌲 '+elements.earth+' | \💧 '+elements.water+' | \💨 '+elements.air+' | \🔥 '+elements.fire+"`\n" if(validartists[i].relicfire>0){ statmsg+='+'+validartists[i].relicfire+' \🔥 ' } if(validartists[i].relicearth>0){ statmsg+='+'+validartists[i].relicearth+' \🌲 ' } if(validartists[i].relicwater>0){ statmsg+='+'+validartists[i].relicwater+' \💧 ' } if(validartists[i].relicair>0){ statmsg+='+'+validartists[i].relicair+' \💨 ' } statmsg=statmsg.trim() inventory.push(validartists[i].relic+' ('+statmsg+')') stats.atk+=(validartists[i].relicatk*10) stats.def+=(validartists[i].relicdef*10) stats.intel+=(validartists[i].relicintel*10) elements.fire+=(validartists[i].relicfire*10) elements.earth+=(validartists[i].relicearth*10) elements.water+=(validartists[i].relicwater*10) elements.air+=(validartists[i].relicair*10) } } //console.log('Checking '+validartists[i]+' for '+user.username) try{ let checker=user.username }catch{ await message.react('❌') await message.reply("I can't find this user. Is "+checkuser+" logged into me?") return } const params = stringify({ method: 'artist.getinfo', artist: validartists[i].name, api_key: client.apikey, format: 'json', user: user.username }) const data = await fetch(`${client.url}${params}`).then(r => r.json()) //console.log(data.artist.stats.userplaycount) if(parseInt(data.artist.stats.userplaycount)>parseInt(mostplays)){ mostplays=data.artist.stats.userplaycount affinity=validartists[i].name } xp+=parseInt(data.artist.stats.userplaycount) if(data.artist.stats.userplaycount>=30){ books=books+1 //console.log("read" + validartists[i].name + ": "+data.artist.stats.userplaycount) } elements.fire+=(validartists[i].fire*parseInt(data.artist.stats.userplaycount)) elements.earth+=(validartists[i].earth*parseInt(data.artist.stats.userplaycount)) elements.water+=(validartists[i].water*parseInt(data.artist.stats.userplaycount)) elements.air+=(validartists[i].air*parseInt(data.artist.stats.userplaycount)) stats.atk+=(validartists[i].atk*parseInt(data.artist.stats.userplaycount)) stats.def+=(validartists[i].def*parseInt(data.artist.stats.userplaycount)) stats.intel+=(validartists[i].intel*parseInt(data.artist.stats.userplaycount)) //console.log('XP: '+xp) await sleep(100) } let gospelbonus=1+((books/validartists.length)/2) //console.log(gospelbonus + " : " + parseInt((gospelbonus-1)*100)+"%") elements.fire=Math.round((elements.fire/10)*gospelbonus) elements.earth=Math.round((elements.earth/10)*gospelbonus) elements.water=Math.round((elements.water/10)*gospelbonus) elements.air=Math.round((elements.air/10)*gospelbonus) stats.atk=Math.round((stats.atk/10)*gospelbonus) stats.def=Math.round((stats.def/10)*gospelbonus) stats.intel=Math.round((stats.intel/10)*gospelbonus) let curlev=0 for (let z=1;z<levelxp.length;z++){ if(xp>=levelxp[z]){ curlev=z } } //curlev=1 /* let bonusxp=0 let lvlcount=curlev for (let z=xp;z>0;z--){ //let tmpxp=xp-levelxp[z] if(z>=levelxp[lvlcount]){ bonusxp=bonusxp+(lvlcount/100) }else{ console.log(lvlcount+" - "+bonusxp) lvlcount=lvlcount-1 } } xp+=Math.round(bonusxp) for (let z=1;z<levelxp.length;z++){ if(xp>=levelxp[z]){ curlev=z } } */ let titlerate=Math.floor(curlev/10)-1 let yourtitle="" if(titlerate<0){ titlerate=0 if(curlev==0){ curlev=1 yourtitle="Uninitiated" }else{ yourtitle="Tenderfoot" } }else{ if(titlerate>9){titlerate=9} yourtitle=leveltitles[titlerate] } let rating="" if (Math.random()>.5){ rating=yourtitle+" "+capitalize(word1[Math.floor(Math.random() * word1.length)])+" "+capitalize(word2[Math.floor(Math.random() * word2.length)])+" "+wizards[Math.floor(Math.random() * wizards.length)] }else{ rating=yourtitle+" "+wizards[Math.floor(Math.random() * wizards.length)]+" of "+capitalize(word1[Math.floor(Math.random() * word1.length)])+" "+capitalize(word3[Math.floor(Math.random() * word3.length)]) } let totalhp=Math.ceil((curlev/100)*200) if(totalhp<=0){totalhp=1} let curspell="N/A" const params = stringify({ method: 'user.getrecenttracks', limit: totalhp, api_key: client.apikey, format: 'json', user: user.username }) const data = await fetch(`${client.url}${params}`).then(r => r.json()) let currenthp=0 let currentmp=0 let curdate=Math.floor(new Date() / 1000) //console.log("CURRENT DATE: "+curdate) for(let z=0;z<data.recenttracks.track.length;z++){ for(let i=0;i<validartists.length;i++){ if(data.recenttracks.track[z].artist["#text"]==validartists[i].name){ if(curspell=="N/A"){ curspell=data.recenttracks.track[z].name } currentmp=currentmp+1 let hpadd=0 try{ hpadd=1+(Math.ceil((10000-(parseInt(curdate)-parseInt(data.recenttracks.track[z].date.uts)))/1000)) }catch{ hpadd=10 } if(hpadd<=1){hpadd=1} currenthp=currenthp+hpadd //console.log('found '+validartists[i]+' at '+z+' - CURHP: '+currenthp) } } } totalhp=Math.ceil(totalhp*gospelbonus) totalhp=totalhp-1 if(totalhp<=0){totalhp=1} let totalmana=Math.ceil((totalhp*1.33)*gospelbonus) let currentmana=totalmana-Math.ceil(currentmp*1.33) if(currentmana<=0){currentmana=0} if(currentmana>=totalmana){currentmana=totalmana} let hpmult=1+((curlev/10)*(curlev/100)) //console.log('HP Multipler: '+hpmult+" ("+Math.ceil(currenthp*hpmult)+")") currenthp=Math.ceil((currenthp*hpmult)*gospelbonus) if(currenthp<=1){currenthp=1} if(currenthp>=totalhp){currenthp=totalhp} //console.log('HP: '+currenthp+'/'+totalhp) //console.log('LEVEL: '+curlev) //console.log('Affinity: '+affinity +'('+mostplays+')') //console.log('XP Needed: '+(levelxp[curlev+1]-xp)) let description = '**' let iscouncil=false for(let c=0;c<council.length;c++){ if(checkuser.user.username==council[c]){ iscouncil=true } } if(iscouncil){ description +=('`🙏` Elder Councilmember '+checkuser.user.username).toUpperCase() }else{ description +=checkuser.user.username.toUpperCase() } description +='**\n*The '+rating+'*\n\n' + '> **Level:** '+curlev if(curlev!=100){ description += (' *('+(levelxp[curlev+1]-xp)+' XP needed to level up)*') } description +='\n' + '> **HP:** '+currenthp+'/'+totalhp+' ' + '| **MP:** '+currentmana+'/'+totalmana+' ' + '| **Total XP:** '+xp+'\n' + '> **ATK:** '+stats.atk+' ' + '| **DEF:** '+stats.def+' ' + '| **INT:** '+stats.intel+'\n' + '> **Elemental Alignment:**\n> `\🌲 '+elements.earth+' | \💧 '+elements.water+' | \💨 '+elements.air+' | \🔥 '+elements.fire+"`\n" + '> **Gospels Read:** `📚 '+books+'/'+validartists.length+'` (+'+parseInt((gospelbonus-1)*100)+'% scholar bonus)\n' + '> **Allegiance:** '+affinity if(affinity!="None"){ description += ' *('+mostplays+' plays)*' } if(inventory.length>0){ description += '\n> **Inventory:**\n`' + inventory.join('\n') + '`' } if(curspell!="N/A"){ description += '\n\n '+spellicons[Math.floor(Math.random() * spellicons.length)]+' **'+checkuser.user.username+' recently cast a level '+curlev+' "'+curspell+'" spell.**' } let rannumber = Math.floor(Math.random() * 3) let msg="" switch (rannumber) { case 0: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word2[Math.floor(Math.random() * word2.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break case 1: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word2[Math.floor(Math.random() * word2.length)]+" "+word3[Math.floor(Math.random() * word3.length)]+" "+word4[Math.floor(Math.random() * word4.length)]+" "+word1[Math.floor(Math.random() * word1.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break case 2: msg=word1[Math.floor(Math.random() * word1.length)]+" "+word3[Math.floor(Math.random() * word3.length)] break } let qname=validartists[Math.floor(Math.random() * validartists.length)].name.split(' ') msg="*\""+word0[Math.floor(Math.random() * word0.length)]+" "+msg+".\" ("+qname[qname.length-1]+" "+(Math.floor(Math.random() * 39)+1)+":"+(Math.floor(Math.random() * 49)+1)+")*" description +='\n\n'+msg+'\n' //+ `\n\n${user.user.username} has **${crowns.length}** crowns in ${message.guild.name}.` const embed = new BotEmbed(message) .setTitle(`Power Ambience of ${checkuser.user.username}`) .setDescription(description) .setThumbnail(checkuser.user.avatarURL) await message.channel.send(embed) } } } } } module.exports = PowerAmbientCommand
newcommerdontblame/ionlib
src/sdk/hl2_csgo/game/client/swarm/c_asw_pickup_equipment.cpp
<reponame>newcommerdontblame/ionlib<filename>src/sdk/hl2_csgo/game/client/swarm/c_asw_pickup_equipment.cpp #include "cbase.h" #include "c_asw_pickup_equipment.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //--------- // Medkit //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Medkit, DT_ASW_Pickup_Weapon_Medkit, CASW_Pickup_Weapon_Medkit ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Medkit::C_ASW_Pickup_Weapon_Medkit() { } //--------- // Sentry Gun Case //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Sentry, DT_ASW_Pickup_Weapon_Sentry, CASW_Pickup_Weapon_Sentry ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Sentry::C_ASW_Pickup_Weapon_Sentry() { } //--------- // Flamer Sentry Gun Case //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Sentry_Flamer, DT_ASW_Pickup_Weapon_Sentry_Flamer, CASW_Pickup_Weapon_Sentry_Flamer ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Sentry_Flamer::C_ASW_Pickup_Weapon_Sentry_Flamer() { } //--------- // Cannon Sentry Gun Case //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Sentry_Cannon, DT_ASW_Pickup_Weapon_Sentry_Cannon, CASW_Pickup_Weapon_Sentry_Cannon ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Sentry_Cannon::C_ASW_Pickup_Weapon_Sentry_Cannon() { } //--------- // Freeze Sentry Gun Case //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Sentry_Freeze, DT_ASW_Pickup_Weapon_Sentry_Freeze, CASW_Pickup_Weapon_Sentry_Freeze ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Sentry_Freeze::C_ASW_Pickup_Weapon_Sentry_Freeze() { } //--------- // Tesla Sentry Gun Case //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Tesla_Trap, DT_ASW_Pickup_Weapon_Tesla_Trap, CASW_Pickup_Weapon_Tesla_Trap ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Tesla_Trap::C_ASW_Pickup_Weapon_Tesla_Trap() { } //--------- // Ammo Bag //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Ammo_Bag, DT_ASW_Pickup_Weapon_Ammo_Bag, CASW_Pickup_Weapon_Ammo_Bag ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Ammo_Bag::C_ASW_Pickup_Weapon_Ammo_Bag() { } //--------- // Ammo Satchel //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Ammo_Satchel, DT_ASW_Pickup_Weapon_Ammo_Satchel, CASW_Pickup_Weapon_Ammo_Satchel ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Ammo_Satchel::C_ASW_Pickup_Weapon_Ammo_Satchel() { } //--------- // Medical Satchel //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Medical_Satchel, DT_ASW_Pickup_Weapon_Medical_Satchel, CASW_Pickup_Weapon_Medical_Satchel ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Medical_Satchel::C_ASW_Pickup_Weapon_Medical_Satchel() { } //--------- // Stim //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Stim, DT_ASW_Pickup_Weapon_Stim, CASW_Pickup_Weapon_Stim ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Stim::C_ASW_Pickup_Weapon_Stim() { } //--------- // Flares //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Flares, DT_ASW_Pickup_Weapon_Flares, CASW_Pickup_Weapon_Flares ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Flares::C_ASW_Pickup_Weapon_Flares() { } //--------- // Mines //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Mines, DT_ASW_Pickup_Weapon_Mines, CASW_Pickup_Weapon_Mines ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Mines::C_ASW_Pickup_Weapon_Mines() { } //--------- // T75 //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_T75, DT_ASW_Pickup_Weapon_T75, CASW_Pickup_Weapon_T75 ) END_RECV_TABLE() C_ASW_Pickup_Weapon_T75::C_ASW_Pickup_Weapon_T75() { } //--------- // Heal Grenade //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Heal_Grenade, DT_ASW_Pickup_Weapon_Heal_Grenade, CASW_Pickup_Weapon_Heal_Grenade ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Heal_Grenade::C_ASW_Pickup_Weapon_Heal_Grenade() { } //--------- // Buff Grenade //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Buff_Grenade, DT_ASW_Pickup_Weapon_Buff_Grenade, CASW_Pickup_Weapon_Buff_Grenade ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Buff_Grenade::C_ASW_Pickup_Weapon_Buff_Grenade() { } //--------- // Hornet Barrage //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Hornet_Barrage, DT_ASW_Pickup_Hornet_Barrage, CASW_Pickup_Hornet_Barrage ) END_RECV_TABLE() C_ASW_Pickup_Hornet_Barrage::C_ASW_Pickup_Hornet_Barrage() { } //--------- // Flashlight //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Flashlight, DT_ASW_Pickup_Weapon_Flashlight, CASW_Pickup_Weapon_Flashlight ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Flashlight::C_ASW_Pickup_Weapon_Flashlight() { } //--------- // Welder //--------- IMPLEMENT_CLIENTCLASS_DT( C_ASW_Pickup_Weapon_Welder, DT_ASW_Pickup_Weapon_Welder, CASW_Pickup_Weapon_Welder ) END_RECV_TABLE() C_ASW_Pickup_Weapon_Welder::C_ASW_Pickup_Weapon_Welder() { }
dbstein/ipde
ipde/annular/stokes.py
<reponame>dbstein/ipde import numpy as np from ..utilities import fast_dot, concat, fast_LU_solve, mfft, mifft, fourier_multiply import scipy as sp import scipy.linalg from personal_utilities.scipy_gmres import right_gmres def scalar_laplacian(CO, AAG, RAG, uh): R01 = CO.R01 R12 = CO.R12 D01 = CO.D01 D12 = CO.D12 ks = AAG.ks psi1 = RAG.psi1 ipsi1 = RAG.inv_psi1 ipsi2 = RAG.inv_psi2 uh_t = R01.dot(uh*ks*1j) uh_tt = R12.dot(fourier_multiply(uh_t, ipsi1)*ks*1j) uh_rr = D12.dot(fourier_multiply(D01.dot(uh), psi1)) luh = fourier_multiply(uh_rr+uh_tt, ipsi2) return luh class AnnularStokesSolver(object): """ Spectrally accurate Stokes solver on annular domain Solves -mu Lu + grad p = f in the annulus described by the Annular Geometry AG div u = 0 Subject to the boundary condition: u(ri) = ig (boundary condition at the inner radius) u(ro) = og (boundary condition at the outer radius) Note that this solver solves the problem in (r, t) coordinates And not in (u, v) coordinates The forces, and boundary conditions, must be given in this manner """ def __init__(self, AAG, mu): self.AAG = AAG self.mu = mu M = AAG.M ns = AAG.ns n = AAG.n self.M = M self.ns = ns self.n = n self.NU = self.M*self.ns self.NP = (self.M-1)*self.ns self.NB = 2*self.NU + self.NP self.u_small_shape = (self.M, self.ns) self.u_shape = (self.M, self.n) self.p_small_shape = (self.M-1, self.ns) self.p_shape = (self.M-1, self.n) self._construct() self.APPLY = scipy.sparse.linalg.LinearOperator((self.NB, self.NB), dtype=complex, matvec=self._apply) self.PREC = scipy.sparse.linalg.LinearOperator((self.NB, self.NB), dtype=complex, matvec=self._preconditioner) def _construct(self): AAG = self.AAG CO = AAG.CO apsi0 = AAG.approx_psi0 apsi1 = AAG.approx_psi1 aipsi1 = AAG.approx_inv_psi1 aipsi2 = AAG.approx_inv_psi2 ks = AAG.ks D01 = CO.D01 D12 = CO.D12 R01 = CO.R01 R12 = CO.R12 R02 = CO.R02 ibcd = CO.ibc_dirichlet obcd = CO.obc_dirichlet VI1 = CO.VI1 ns = self.ns M = self.M self._KLUS = [] for i in range(ns): K = np.zeros((3*M-1, 3*M-1), dtype=complex) LL = fast_dot(aipsi2, fast_dot(D12, fast_dot(apsi1, D01))) - \ fast_dot(np.ones(M-2)*ks[i]**2, fast_dot(R12, fast_dot(aipsi1, R01))) # ur things K[ 0*M + 0 : 0*M + M-2 , 0*M : 1*M ] = -LL + fast_dot(aipsi2**2, R02) K[ 0*M + 0 : 0*M + M-2 , 1*M : 2*M ] = fast_dot(2*aipsi2**2, fast_dot(R02, 1j*ks[i]*np.ones(M)) ) K[ 0*M + 0 : 0*M + M-2 , 0*M : 2*M ] *= self.mu K[ 0*M + 0 : 0*M + M-2 , 2*M : ] = D12 K[ 0*M + M-2 : 0*M + M-1 , 0*M : 1*M ] = ibcd K[ 0*M + M-1 : 0*M + M , 0*M : 1*M ] = obcd # ut things K[ 1*M + 0 : 1*M + M-2 , 0*M : 1*M ] = -fast_dot(2*aipsi2**2, fast_dot(R02, 1j*ks[i]*np.ones(M)) ) K[ 1*M + 0 : 1*M + M-2 , 1*M : 2*M ] = -LL + fast_dot(aipsi2**2, R02) K[ 1*M + 0 : 1*M + M-2 , 0*M : 2*M ] *= self.mu K[ 1*M + 0 : 1*M + M-2 , 2*M : ] = fast_dot(aipsi2, fast_dot(R12, 1j*ks[i]*np.ones(M-1))) K[ 1*M + M-2 : 1*M + M-1 , 1*M : 2*M ] = ibcd K[ 1*M + M-1 : 1*M + M , 1*M : 2*M ] = obcd # div u things K[ 2*M + 0 : 2*M + M-1 , 0*M : 1*M ] = fast_dot(aipsi1, fast_dot(D01, apsi0)) K[ 2*M + 0 : 2*M + M-1 , 1*M : 2*M ] = fast_dot(aipsi1, fast_dot(R01, 1j*ks[i]*np.ones(M))) # fix the pressure nullspace if i == 0: K[2*M:, 2*M:] += VI1[0] self._KLUS.append(sp.linalg.lu_factor(K)) def _preconditioner(self, ffh): M = self.M frh, fth, fph = self._extract_stokes(ffh, withcopy=True) for i in range(self.ns): vec = concat(frh[:,i], fth[:,i], fph[:,i]) vec = fast_LU_solve(self._KLUS[i], vec) frh[:,i] = vec[0*M:1*M] fth[:,i] = vec[1*M:2*M] fph[:,i] = vec[2*M:] return concat(frh, fth, fph) def _extract_stokes(self, fh, withcopy=False): frh = fh[0*self.NU:1*self.NU ].reshape(self.u_small_shape) fth = fh[1*self.NU:2*self.NU ].reshape(self.u_small_shape) fph = fh[2*self.NU:2*self.NU+self.NP ].reshape(self.p_small_shape) if withcopy: frh = frh.copy() fth = fth.copy() fph = fph.copy() return frh, fth, fph def _apply(self, uuh): AAG = self.AAG RAG = self.RAG CO = self.AAG.CO ibcd = CO.ibc_dirichlet obcd = CO.obc_dirichlet D01 = CO.D01 D12 = CO.D12 R01 = CO.R01 R12 = CO.R12 R02 = CO.R02 VI1 = CO.VI1 ks = AAG.ks psi0 = RAG.psi0 psi1 = RAG.psi1 ipsi1 = RAG.inv_psi1 ipsi2 = RAG.inv_psi2 DR_psi2 = RAG.DR_psi2 ipsi_DR_ipsi_DT_psi2 = RAG.ipsi_DR_ipsi_DT_psi2 ipsi_DT_ipsi_DR_psi2 = RAG.ipsi_DT_ipsi_DR_psi2 # a lot of room for optimization in this function! urh, uth, ph = self._extract_stokes(uuh) # compute scalar laplacian lap_urh = scalar_laplacian(CO, AAG, RAG, urh) lap_uth = scalar_laplacian(CO, AAG, RAG, uth) # ur equation t1 = fourier_multiply(R02.dot(uth*1j*ks), 2*DR_psi2*ipsi2**2) t2 = fourier_multiply(R02.dot(urh), DR_psi2**2*ipsi2**2) t3 = fourier_multiply(R02.dot(uth), ipsi_DR_ipsi_DT_psi2) t4 = D12.dot(ph) frh = self.mu*(-lap_urh + t1 + t2 + t3) + t4 # ut equation t1 = fourier_multiply(R02.dot(urh*1j*ks), 2*DR_psi2*ipsi2**2) t2 = fourier_multiply(R02.dot(uth), DR_psi2**2*ipsi2**2) t3 = fourier_multiply(R02.dot(urh), ipsi_DT_ipsi_DR_psi2) t4 = fourier_multiply(R12.dot(ph*1j*ks), ipsi2) fth = self.mu*(-lap_uth - t1 + t2 - t3) + t4 # div u equation fph = fourier_multiply(D01.dot(fourier_multiply(urh, psi0)) + R01.dot(uth*1j*ks), ipsi1) # add BCS frh_full = concat( frh, ibcd.dot(urh), obcd.dot(urh) ) fth_full = concat( fth, ibcd.dot(uth), obcd.dot(uth) ) # fph output fph[:,0] += VI1.dot(ph)[0,0] # this is the mean of the pressure! # get mean of the pressure return concat( frh_full, fth_full, fph ) def solve(self, RAG, fr, ft, irg, itg, org, otg, verbose=False, **kwargs): self.RAG = RAG R02 = self.AAG.CO.R02 P10 = self.AAG.CO.P10 ffr = concat(R02.dot(fr), irg, org) fft = concat(R02.dot(ft), itg, otg) ffrh = mfft(ffr.reshape(self.u_shape)) ffth = mfft(fft.reshape(self.u_shape)) ffph = np.zeros(self.NP, dtype=complex) ffh = concat(ffrh, ffth, ffph) out = right_gmres(self.APPLY, ffh, M=self.PREC, verbose=verbose, **kwargs) res = out[0] if verbose: print('GMRES took:', len(out[2]), 'iterations.') urh, uth, ph = self._extract_stokes(res) ur = mifft(urh).real ut = mifft(uth).real p = P10.dot(mifft(ph).real) return ur, ut, p
iamzken/aliyun-openapi-cpp-sdk
gpdb/src/model/AddBuDBInstanceRelationRequest.cc
<filename>gpdb/src/model/AddBuDBInstanceRelationRequest.cc<gh_stars>10-100 /* * Copyright 2009-2017 Alibaba Cloud 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. */ #include <alibabacloud/gpdb/model/AddBuDBInstanceRelationRequest.h> using AlibabaCloud::Gpdb::Model::AddBuDBInstanceRelationRequest; AddBuDBInstanceRelationRequest::AddBuDBInstanceRelationRequest() : RpcServiceRequest("gpdb", "2016-05-03", "AddBuDBInstanceRelation") { setMethod(HttpRequest::Method::Post); } AddBuDBInstanceRelationRequest::~AddBuDBInstanceRelationRequest() {} std::string AddBuDBInstanceRelationRequest::getAccessKeyId()const { return accessKeyId_; } void AddBuDBInstanceRelationRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::string AddBuDBInstanceRelationRequest::getDBInstanceId()const { return dBInstanceId_; } void AddBuDBInstanceRelationRequest::setDBInstanceId(const std::string& dBInstanceId) { dBInstanceId_ = dBInstanceId; setParameter("DBInstanceId", dBInstanceId); } long AddBuDBInstanceRelationRequest::getOwnerId()const { return ownerId_; } void AddBuDBInstanceRelationRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); } std::string AddBuDBInstanceRelationRequest::getBusinessUnit()const { return businessUnit_; } void AddBuDBInstanceRelationRequest::setBusinessUnit(const std::string& businessUnit) { businessUnit_ = businessUnit; setParameter("BusinessUnit", businessUnit); }
reels-research/iOS-Private-Frameworks
AccessibilityUtilities.framework/AXSwitchRecipe.h
<filename>AccessibilityUtilities.framework/AXSwitchRecipe.h /* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/AccessibilityUtilities.framework/AccessibilityUtilities */ @interface AXSwitchRecipe : NSObject { NSArray * _mappings; NSString * _menuIconIdentifier; NSString * _name; double _timeout; NSString * _unlocalizedName; NSUUID * _uuid; } @property (nonatomic, retain) NSArray *mappings; @property (nonatomic, copy) NSString *menuIconIdentifier; @property (nonatomic, copy) NSString *name; @property (nonatomic, readonly) bool shouldContinueScanning; @property (nonatomic) double timeout; @property (nonatomic, retain) NSString *unlocalizedName; @property (nonatomic, retain) NSUUID *uuid; + (id)recipeWithDictionaryRepresentation:(id)arg1; - (void).cxx_destruct; - (id)description; - (id)dictionaryRepresentation; - (id)init; - (id)mappings; - (id)menuIconIdentifier; - (id)name; - (void)setMappings:(id)arg1; - (void)setMenuIconIdentifier:(id)arg1; - (void)setName:(id)arg1; - (void)setTimeout:(double)arg1; - (void)setUnlocalizedName:(id)arg1; - (void)setUuid:(id)arg1; - (bool)shouldContinueScanning; - (double)timeout; - (id)unlocalizedName; - (id)uuid; @end
edalex-yinzi/openEQUELLA
Source/Plugins/Core/com.equella.serverbase/src/com/tle/core/dao/helpers/DMLPartitioner.java
<reponame>edalex-yinzi/openEQUELLA /* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0, (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tle.core.dao.helpers; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.ScrollableResults; import org.hibernate.Session; import org.springframework.orm.hibernate5.HibernateCallback; /** * Partition up the set of query and execute a DML statement over each partition. This helps to * prevent locking problems, especially when whole tables start getting locked. */ @SuppressWarnings("nls") public abstract class DMLPartitioner implements HibernateCallback { private static final int MAX_BATCH_SIZE = 500; private final String tableName; private final String idColumn; public DMLPartitioner(String tableName, String idColumn) { this.tableName = tableName; this.idColumn = idColumn; } @Override public final Object doInHibernate(Session session) throws HibernateException { return withSession(session); } public final int withSession(Session session) { final String idFinderHql = buildIdFinderHql(); final String dmlHql = buildDmlHql(); int total = 0; long startId = -1; long endId = -1; while (true) { // Find the next start and end ID startId = endId + 1; Query idFinder = session.createQuery(idFinderHql); idFinder.setMaxResults(MAX_BATCH_SIZE); idFinder.setParameter("startId", startId); setWhereParams(idFinder); ScrollableResults sr = idFinder.scroll(); try { if (sr.last()) { endId = sr.getLong(0); } else { // Nothing more to process return total; } } finally { sr.close(); } // Process rows in our ID range Query dml = session.createQuery(dmlHql); dml.setParameter("startId", startId); dml.setParameter("endId", endId); setWhereParams(dml); setDmlParams(dml); total += dml.executeUpdate(); } } private String buildIdFinderHql() { StringBuilder s = new StringBuilder(); s.append("SELECT ").append(idColumn).append(" FROM ").append(tableName); s.append(" ").append(getWhereClause()); s.append(" AND ").append(idColumn).append(" >= :startId"); s.append(" ORDER BY ").append(idColumn).append(" ASC"); return s.toString(); } private String buildDmlHql() { StringBuilder s = new StringBuilder(); s.append(getDmlStart()); s.append(" ").append(getWhereClause()); s.append(" AND (").append(idColumn).append(" >= :startId"); s.append(" AND ").append(idColumn).append(" <= :endId)"); return s.toString(); } public abstract String getWhereClause(); public abstract void setWhereParams(Query q); public abstract String getDmlStart(); public abstract void setDmlParams(Query q); }
itYangJie/leetcode
src/com/ityang/leetcode/Subject299.java
package com.ityang.leetcode; import java.util.HashMap; import java.util.Map; public class Subject299 { public static void main(String[] args) { // TODO Auto-generated method stub getHint("1123", "0111"); } public static String getHint(String secret, String guess) { int bulls = 0, cows = 0; Map<Integer, Integer> secretMap = new HashMap<>(); Map<Integer, Integer> guessMap = new HashMap<>(); for (int i = 0; i < secret.length(); i++) { if (secret.charAt(i) == guess.charAt(i)) bulls++; if (secretMap.containsKey(secret.charAt(i) - '0')) secretMap.put(secret.charAt(i) - '0', secretMap.get(secret.charAt(i) - '0') + 1); else secretMap.put(secret.charAt(i) - '0', 1); if (guessMap.containsKey(guess.charAt(i) - '0')) guessMap.put(guess.charAt(i) - '0', guessMap.get(guess.charAt(i) - '0') + 1); else guessMap.put(guess.charAt(i) - '0', 1); } for (int i = 0; i <= 9; i++) { if(secretMap.containsKey(i) && guessMap.containsKey(i)) cows += Math.min(secretMap.get(i), guessMap.get(i)); } cows = cows-bulls; return bulls+"A"+cows+"B"; } }
anirudha4/react-template
app/themes/colors.js
/** * This file contains the application's colors. * * Define color here instead of duplicating them throughout the components. * That allows to change them more easily later on. */ const primary = '#DF5E5E'; const text = '#212529'; const textLight = '#999'; const secondary = '#FDD2BF'; const success = '#28a745'; const error = '#dc3545'; const border = '#e8e8e8'; const shadow = 'rgba(0,0,0,0.04)'; const overlay = 'rgba(0,0,0,0.3)'; const colors = { transparent: 'rgba(0,0,0,0)', // Example colors: text, primary, secondary, success, error, textLight, border, shadow, overlay, theme: { lightMode: { primary, secondary }, darkMode: { primary: secondary, secondary: primary } } }; module.exports = colors;
UnicornsIncluded/Givhub
server/database/index.js
const mongoose = require('mongoose') mongoose.Promise = global.Promise mongoose.set('useCreateIndex', true) mongoose.set('useFindAndModify', false) const options = { useNewUrlParser: true, useUnifiedTopology: true } const database = mongoose .connect(process.env.DATABASE_URL, options) .then(() => console.log('Connected to database.')) .catch(err => console.error('Error connecting to database:', err.message)) module.exports = database
pasgra/spimosim
lib/modules/HelpTextGenerator/ResearchGroupShort.js
'use strict'; spimosimCore.modules.add('HelpTextGenerator', { name: 'research group short', files: [ 'lib/modules/HelpTextGenerator/ResearchGroupShort.js' ], depends: [], version: '1.0', author: '<NAME>', description: 'A help text generator for a short text.', date: '2020-03-26' }, function (iconUrl) { return '<h2>Instructions</h2>' + '<p>' + ' On this website you can play with several interesting models studied by' + ' our group.' + ' Use the arrows next to the model name to switch between models.' + '<p>' + '' + '<p>' + ' In the left section you can change parameters of the model and' + ' the network and more. Click' + ' <ul>' + ' <li><img class="inline-symbol" src="' + iconUrl + '/restart.svg"> to restart the simulation or</li>' + ' <li><img class="inline-symbol" src="' + iconUrl + '/settings.svg"> for more options.</li>' + ' </ul>' + '<p>' + '' + '<p>' + ' In the middle section you can see the state of the model.' + '</p>' + '' + '<p>' + ' In the right section you see plots that visualize and analyze the' + ' simulated data. Click <img class="inline-symbol" src="' + iconUrl + '/tools.svg">' + ' to download CSV files and more.' + '</p>'; });
lifenstein/fez-frontend
src/modules/SharedComponents/PublicationCitation/components/citations/partials/EditorsCitationView.test.js
import EditorsCitationView from './EditorsCitationView'; function setup(testProps = {}) { const props = { classes: {}, ...testProps, publication: testProps.publication || {}, }; return getElement(EditorsCitationView, props); } describe('EditorsCitationView test ', () => { it('should render component with no contributors', () => { const wrapper = setup(); expect(toJson(wrapper)).toMatchSnapshot(); }); it('should render component with one contributor', () => { const testObject = { fez_record_search_key_contributor: [ { rek_contributor_id: null, rek_contributor_pid: 'UQ:678742', rek_contributor: 'Pedroso, <NAME>', rek_contributor_order: 1, }, ], }; const wrapper = setup({ publication: testObject }); expect(toJson(wrapper)).toMatchSnapshot(); }); it('should render component with two contributors', () => { const testObject = { fez_record_search_key_contributor: [ { rek_contributor_id: null, rek_contributor_pid: 'UQ:678742', rek_contributor: 'Pedroso, <NAME>', rek_contributor_order: 1, }, { rek_contributor_id: null, rek_contributor_pid: 'UQ:678742', rek_contributor: '<NAME>', rek_contributor_order: 2, }, ], }; const wrapper = setup({ publication: testObject }); expect(toJson(wrapper)).toMatchSnapshot(); }); it('should render component with three contributors', () => { const testObject = { fez_record_search_key_contributor: [ { rek_contributor_id: null, rek_contributor_pid: 'UQ:678742', rek_contributor: 'Pedroso, <NAME>', rek_contributor_order: 1, }, { rek_contributor_id: null, rek_contributor_pid: 'UQ:678742', rek_contributor: '<NAME>', rek_contributor_order: 2, }, { rek_contributor_id: null, rek_contributor_pid: 'UQ:678742', rek_contributor: '<NAME>', rek_contributor_order: 3, }, ], }; const wrapper = setup({ publication: testObject }); expect(toJson(wrapper)).toMatchSnapshot(); }); });