identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/qhapaq-49/pokeai/blob/master/pokeai/ai/battle_status.py
Github Open Source
Open Source
MIT
2,021
pokeai
qhapaq-49
Python
Code
569
2,465
""" バトルの状態を表すオブジェクト あるプレイヤーから見た状態を管理する """ import json import re from typing import Dict, Set, Optional, Tuple from pokeai.sim.party_generator import Party def parse_hp_condition(hp_condition: str) -> Tuple[int, int, str]: """ HPと状態異常を表す文字列のパース :param hp_condition: '50/200' (現在HP=50, 最大HP=200, 状態異常なし) or '50/200 psn' (状態異常の時) :return: 現在HP, 最大HP, 状態異常('', 'psn'(毒), 'tox'(猛毒), 'par', 'brn', 'slp', 'frz', 'fnt'(瀕死)) """ if hp_condition == '0 fnt': # 瀕死の時は0という表示になっている # 便宜上最大HP100として返している return 0, 100, 'fnt' m = re.match('^(\\d+)/(\\d+)(?: (psn|tox|par|brn|slp|frz|fnt)|)?$', hp_condition) assert m is not None, f"HP_CONDITION '{hp_condition}' cannot be parsed." # m[3]は状態異常がないときNoneとなる return int(m[1]), int(m[2]), m[3] or '' def _parse_details(details: str) -> Tuple[str, int, str]: """ ポケモンの情報をパース :param details: 種族名・レベル・性別情報 例:'Ninetales, L50, M' :return: """ # 例外的な種族名 'Nidoran-F', 'Porygon2', 'Mr. Mime', "Farfetch'd" m = re.match('^([A-Za-z-]+|Porygon2|Mr\\. Mime|Farfetch\'d), L(\\d+)(?:, (M|F|N))?$', details) assert m is not None, f"DETAILS '{details}' cannot be parsed." # 性別不明だとm[3]はNone return m[1], int(m[2]), m[3] or 'N' class ActivePokeStatus: """ 場に出ているポケモンの状態 """ RANK_INITIAL = {'atk': 0, 'def': 0, 'spa': 0, 'spd': 0, 'spe': 0, 'accuracy': 0, 'evasion': 0} RANK_MAX = 6 RANK_MIN = -6 RANK_ZERO = 0 pokemon: str # |switch|POKEMON|DETAILS|HP STATUSにおけるPOKEMON部分。例:'p1a: Ninetales' species: str # 種族 例:'Ninetales' level: int gender: str hp_current: int hp_max: int status: str # 状態異常 (異常がない時は'') ranks: Dict[str, int] volatile_statuses: Set[str] # 状態変化 def __init__(self, pokemon: str, species: str, level: int, gender: str, hp_current: int, hp_max: int, status: str): """ 場に出た直後のポケモンを生成する :param pokemon: :param species: :param hp_current: :param hp_max: :param status: """ self.pokemon = pokemon self.species = species self.level = level self.gender = gender self.hp_current = hp_current self.hp_max = hp_max self.status = status self.ranks = ActivePokeStatus.RANK_INITIAL.copy() self.volatile_statuses = set() def rank_boost(self, stat: str, amount: int): self._rank_set_clip(stat, self.ranks[stat] + amount) def rank_unboost(self, stat: str, amount: int): self._rank_set_clip(stat, self.ranks[stat] - amount) def rank_setboost(self, stat: str, amount: int): self._rank_set_clip(stat, amount) def _rank_set_clip(self, stat: str, value: int): assert stat in self.ranks self.ranks[stat] = min(max(value, ActivePokeStatus.RANK_MIN), ActivePokeStatus.RANK_MAX) def rank_clearallboost(self): for stat in self.ranks.keys(): self.ranks[stat] = ActivePokeStatus.RANK_ZERO @property def hp_ratio(self) -> float: return self.hp_current / self.hp_max class SideStatus: """ 一方のプレイヤーの状態 """ active: Optional[ActivePokeStatus] reserve_pokes: Dict[str, ActivePokeStatus] # 控えのポケモンの交代直前の状態(瀕死状態のポケモンも含む) side_statuses: Set[str] # プレイヤーの場の状態 total_pokes: int # 全手持ちポケモン数 remaining_pokes: int # 残っているポケモン数 def __init__(self): """ バトル開始時の状態を生成する """ self.active = None self.reserve_pokes = {} self.side_statuses = set() self.total_pokes = 0 self.remaining_pokes = 0 def switch(self, active: ActivePokeStatus): """ ポケモンを交換、またはゲームの最初に繰り出す :param active: :return: """ if self.active is not None: self.reserve_pokes[self.active.species] = self.active self.active = active if active.species in self.reserve_pokes: del self.reserve_pokes[active.species] def get_mean_hp_ratio(self) -> float: """ 控えを含めたポケモンごとの現在HP/最大HPを計算し、全ポケモンの平均を返す :return: """ assert self.total_pokes > 0 assert self.active is not None # まだ登場していないポケモンはhp_ratio==1.0とみなす ratio_sum = self.active.hp_ratio + sum(p.hp_ratio for p in self.reserve_pokes.values()) + ( self.total_pokes - 1 - len(self.reserve_pokes)) return ratio_sum / self.total_pokes def get_alive_ratio(self) -> float: """ 生きているポケモン数/全ポケモン数を計算する :return: """ assert self.total_pokes > 0 return self.remaining_pokes / self.total_pokes class BattleStatus: WEATHER_NONE = 'none' turn: int # ターン番号(最初が0) side_friend: str # 自分側のside ('p1' or 'p2') side_opponent: str # 相手側のside ('p1' or 'p2') side_party: Party # 自分側のパーティ weather: str # 天候(なしの時はWEATHER_NONE='none') side_statuses: Dict[str, SideStatus] # key: 'p1' or 'p2' def __init__(self, side_friend: str, side_party: Party): assert side_friend in ['p1', 'p2'] self.side_friend = side_friend self.side_opponent = {'p1': 'p2', 'p2': 'p1'}[side_friend] self.side_party = side_party self.turn = 0 self.weather = BattleStatus.WEATHER_NONE self.side_statuses = {'p1': SideStatus(), 'p2': SideStatus()} def switch(self, pokemon: str, details: str, hp_condition: str): side = pokemon[:2] species, level, gender = _parse_details(details) hp_current, hp_max, status = parse_hp_condition(hp_condition) poke = ActivePokeStatus(pokemon, species, level, gender, hp_current, hp_max, status) self.side_statuses[side].switch(poke) def get_side(self, pokemon: str) -> SideStatus: return self.side_statuses[pokemon[:2]] def json_dumps(self) -> str: def default(obj): if isinstance(obj, set): return list(obj) else: return obj.__dict__ return json.dumps(self, default=default)
32,512
https://github.com/Ilyoung-3pm/prepare-a-case/blob/master/tests/pact/case-service/update-case.test.pact.js
Github Open Source
Open Source
MIT
2,021
prepare-a-case
Ilyoung-3pm
JavaScript
Code
160
484
/* global describe, it, expect */ const { pactWith } = require('jest-pact') const { Matchers } = require('@pact-foundation/pact') const { update } = require('../../../server/services/utils/request') const { validateSchema } = require('../../testUtils/schemaValidation') const pactResponseMock = require('./update-case.test.pact.json') const schema = require('../../../schemas/put-case.schema.json') pactWith({ consumer: 'prepare-a-case', provider: 'court-case-service' }, provider => { describe('PUT /court/{courtCode}/case/{caseNo}', () => { const mockRequestData = pactResponseMock.request.jsonBody const mockResponseData = pactResponseMock.response.jsonBody const apiUrl = pactResponseMock.request.path it('should validate the JSON schema against the provided request sample data', () => { validateSchema(mockRequestData, schema) }) it('should validate the JSON schema against the provided response sample data', () => { validateSchema(mockResponseData, schema) }) it('updates and returns a specific case', async () => { await provider.addInteraction({ state: 'a case exists with the given case number', uponReceiving: 'a request to update a specific case', withRequest: { method: pactResponseMock.request.method, path: apiUrl, headers: pactResponseMock.request.headers, body: mockRequestData }, willRespondWith: { status: 201, headers: pactResponseMock.response.headers, body: Matchers.like(mockResponseData) } }) const response = await update(`${provider.mockService.baseUrl}${apiUrl}`, mockResponseData) expect(response.data).toEqual(mockResponseData) return response }) }) })
26,926
https://github.com/pengbin8/endiciaApi/blob/master/TSI.Utils.Shipping.Endicia/TSI.Utils.Shipping.Endicia/LabelRequestResponse.cs
Github Open Source
Open Source
Apache-2.0
2,016
endiciaApi
pengbin8
C#
Code
388
2,222
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using TSI.Utils.Shipping.Endicia.Enums; using TSI.Utils.Shipping.Endicia.Interfaces; namespace TSI.Utils.Shipping.Endicia { internal class LabelRequestResponse : ILabelRequestResponse { public int CostCenter { get { return JustDecompileGenerated_get_CostCenter(); } set { JustDecompileGenerated_set_CostCenter(value); } } private int JustDecompileGenerated_CostCenter_k__BackingField; public int JustDecompileGenerated_get_CostCenter() { return this.JustDecompileGenerated_CostCenter_k__BackingField; } public void JustDecompileGenerated_set_CostCenter(int value) { this.JustDecompileGenerated_CostCenter_k__BackingField = value; } public List<ILabel> CustomForms { get { return JustDecompileGenerated_get_CustomForms(); } set { JustDecompileGenerated_set_CustomForms(value); } } private List<ILabel> JustDecompileGenerated_CustomForms_k__BackingField; public List<ILabel> JustDecompileGenerated_get_CustomForms() { return this.JustDecompileGenerated_CustomForms_k__BackingField; } public void JustDecompileGenerated_set_CustomForms(List<ILabel> value) { this.JustDecompileGenerated_CustomForms_k__BackingField = value; } public string CustomNumber { get { return JustDecompileGenerated_get_CustomNumber(); } set { JustDecompileGenerated_set_CustomNumber(value); } } private string JustDecompileGenerated_CustomNumber_k__BackingField; public string JustDecompileGenerated_get_CustomNumber() { return this.JustDecompileGenerated_CustomNumber_k__BackingField; } public void JustDecompileGenerated_set_CustomNumber(string value) { this.JustDecompileGenerated_CustomNumber_k__BackingField = value; } public string ErrorMessage { get { return JustDecompileGenerated_get_ErrorMessage(); } set { JustDecompileGenerated_set_ErrorMessage(value); } } private string JustDecompileGenerated_ErrorMessage_k__BackingField; public string JustDecompileGenerated_get_ErrorMessage() { return this.JustDecompileGenerated_ErrorMessage_k__BackingField; } public void JustDecompileGenerated_set_ErrorMessage(string value) { this.JustDecompileGenerated_ErrorMessage_k__BackingField = value; } public decimal FinalPostage { get { return JustDecompileGenerated_get_FinalPostage(); } set { JustDecompileGenerated_set_FinalPostage(value); } } private decimal JustDecompileGenerated_FinalPostage_k__BackingField; public decimal JustDecompileGenerated_get_FinalPostage() { return this.JustDecompileGenerated_FinalPostage_k__BackingField; } public void JustDecompileGenerated_set_FinalPostage(decimal value) { this.JustDecompileGenerated_FinalPostage_k__BackingField = value; } public List<ILabel> Labels { get { return JustDecompileGenerated_get_Labels(); } set { JustDecompileGenerated_set_Labels(value); } } private List<ILabel> JustDecompileGenerated_Labels_k__BackingField; public List<ILabel> JustDecompileGenerated_get_Labels() { return this.JustDecompileGenerated_Labels_k__BackingField; } public void JustDecompileGenerated_set_Labels(List<ILabel> value) { this.JustDecompileGenerated_Labels_k__BackingField = value; } public string PostmarkDate { get { return JustDecompileGenerated_get_PostmarkDate(); } set { JustDecompileGenerated_set_PostmarkDate(value); } } private string JustDecompileGenerated_PostmarkDate_k__BackingField; public string JustDecompileGenerated_get_PostmarkDate() { return this.JustDecompileGenerated_PostmarkDate_k__BackingField; } public void JustDecompileGenerated_set_PostmarkDate(string value) { this.JustDecompileGenerated_PostmarkDate_k__BackingField = value; } public string ReferenceId { get { return JustDecompileGenerated_get_ReferenceId(); } set { JustDecompileGenerated_set_ReferenceId(value); } } private string JustDecompileGenerated_ReferenceId_k__BackingField; public string JustDecompileGenerated_get_ReferenceId() { return this.JustDecompileGenerated_ReferenceId_k__BackingField; } public void JustDecompileGenerated_set_ReferenceId(string value) { this.JustDecompileGenerated_ReferenceId_k__BackingField = value; } public TransactionResultEnum Status { get { return JustDecompileGenerated_get_Status(); } set { JustDecompileGenerated_set_Status(value); } } private TransactionResultEnum JustDecompileGenerated_Status_k__BackingField; public TransactionResultEnum JustDecompileGenerated_get_Status() { return this.JustDecompileGenerated_Status_k__BackingField; } public void JustDecompileGenerated_set_Status(TransactionResultEnum value) { this.JustDecompileGenerated_Status_k__BackingField = value; } public string TrackingNumber { get { return JustDecompileGenerated_get_TrackingNumber(); } set { JustDecompileGenerated_set_TrackingNumber(value); } } private string JustDecompileGenerated_TrackingNumber_k__BackingField; public string JustDecompileGenerated_get_TrackingNumber() { return this.JustDecompileGenerated_TrackingNumber_k__BackingField; } public void JustDecompileGenerated_set_TrackingNumber(string value) { this.JustDecompileGenerated_TrackingNumber_k__BackingField = value; } public int TransactionId { get { return JustDecompileGenerated_get_TransactionId(); } set { JustDecompileGenerated_set_TransactionId(value); } } private int JustDecompileGenerated_TransactionId_k__BackingField; public int JustDecompileGenerated_get_TransactionId() { return this.JustDecompileGenerated_TransactionId_k__BackingField; } public void JustDecompileGenerated_set_TransactionId(int value) { this.JustDecompileGenerated_TransactionId_k__BackingField = value; } public LabelRequestResponse() { } } }
45,087
https://github.com/SnipeDragon/darkspace/blob/master/DarkSpace/GadgetELF.cpp
Github Open Source
Open Source
MIT
2,016
darkspace
SnipeDragon
C++
Code
422
1,342
/* GadgetELF.cpp (c)2000 Palestar Inc, Richard Lyle */ #include "Debug/Assert.h" #include "GadgetELF.h" #include "GameContext.h" #include "resource.h" //---------------------------------------------------------------------------- const int ELF_UPDATE_RATE = TICKS_PER_SECOND * 5; //! what is the max energy that can be leeched per tick from a single target... const int MAX_ENERGY_LEECH = 50; //---------------------------------------------------------------------------- IMPLEMENT_ABSTRACT_FACTORY( GadgetELF, NounGadget ); REGISTER_FACTORY_KEY( GadgetELF, 4368350708589970753LL ); BEGIN_ABSTRACT_PROPERTY_LIST( GadgetELF, NounGadget ); END_PROPERTY_LIST(); GadgetELF::GadgetELF() { m_nUpdateAffected = key() % ELF_UPDATE_RATE; } //---------------------------------------------------------------------------- bool GadgetELF::read( const InStream & input ) { if (! NounGadget::read( input ) ) return false; m_nUpdateAffected = key() % ELF_UPDATE_RATE; return true; } //---------------------------------------------------------------------------- void GadgetELF::render( RenderContext &context, const Matrix33 & frame, const Vector3 & position ) { if ( active() ) { Scene * pUseEffect = useEffect(); if ( pUseEffect != NULL ) pUseEffect->render( context, frame, position ); } } //---------------------------------------------------------------------------- void GadgetELF::release() { NounGadget::release(); m_Affect.release(); } //---------------------------------------------------------------------------- NounGadget::Type GadgetELF::type() const { return WEAPON; } dword GadgetELF::hotkey() const { return 'V'; } bool GadgetELF::usable( Noun * pTarget, bool shift ) const { if ( active() ) return true; if (! NounGadget::usable( pTarget, shift ) ) return false; if ( WidgetCast<NounShip>( parent() ) && ((NounShip *)parent())->testFlags( NounShip::FLAG_CLOAKED|NounShip::FLAG_IN_SAFE_ZONE ) ) return false; // weapons are disabled if ( destroyed() ) return false; return true; } bool GadgetELF::useActive() const { return active(); } void GadgetELF::use( dword when, Noun * pTarget, bool shift) { if ( active() ) NounGadget::use( when, pTarget, shift ); // set the device active setFlags( FLAG_ACTIVE, !active() ); message( CharString().format( "<color;ffffff>Tactical: %s %s.", name(), active() ? "Active" : "Inactive" ) ); } int GadgetELF::useEnergy( dword nTick, int energy ) { if ( active() ) { Vector3 myPosition( worldPosition() ); m_nUpdateAffected++; if ( m_nUpdateAffected >= ELF_UPDATE_RATE ) { m_nUpdateAffected -= ELF_UPDATE_RATE; m_Affect.release(); // update list of ship list Array< GameContext::NounCollision > nouns; if ( context()->proximityCheck( worldPosition(), range(), nouns, CLASS_KEY(NounShip) ) ) { for(int i=0;i<nouns.size();i++) { NounShip * pAffect = (NounShip *)nouns[i].pNoun; if ( pAffect != NULL && pAffect != parentBody() ) m_Affect.push( pAffect ); } } } // drain energy from the affected ships... based on range for(int i=0;i<m_Affect.size();i++) { NounShip * pAffect = m_Affect[ i ]; float fDistance = (pAffect->worldPosition() - myPosition).magnitude(); if ( fDistance < range() ) { int leech = damageRatioInv() * ((fDistance * pAffect->energy()) / range()); if ( leech > MAX_ENERGY_LEECH ) leech = MAX_ENERGY_LEECH; pAffect->setEnergy( pAffect->energy() - leech ); energy += leech; } } } return energy; } bool GadgetELF::updateLogic() { NounShip * pShip = WidgetCast<NounShip>( parent() ); if (! pShip ) return false; if (! useActive() ) pShip->useGadget( this, NULL, false ); return true; } //---------------------------------------------------------------------------- //EOF
44,310
https://github.com/KeepPositive/Tad-OS/blob/master/build_scripts/base/binutils.sh
Github Open Source
Open Source
MIT
null
Tad-OS
KeepPositive
Shell
Code
93
292
#! /bin/bash PACKAGE="binutils" VERSION=$1 FOLD_NAME="$PACKAGE-$VERSION" BUILD_DIR="/$FOLD_NAME/build" if [ -z "$CORES" ]; then CORES='4' fi tar xvf "$PACKAGE_DIR/$FOLD_NAME.tar.bz2" pushd "$FOLD_NAME" # Verify some things using expect expect -c "spawn ls" # Apply this patch patch -Np1 -i "$PACKAGE_DIR/binutils-2.26-upstream_fixes-3.patch" popd mkdir "$BUILD_DIR" pushd "$BUILD_DIR" # Configure the source ../configure --prefix=/usr \ --enable-shared \ --disable-werror # Build using the configured sources make -j "$CORES" tooldir=/usr # Install the built package if [ "$INSTALL_SOURCES" -eq 1 ] then make tooldir=/usr install fi # Exit the build dir popd # Remove the source code directory rm -rf "$FOLD_NAME"
2,894
https://github.com/pnancke/intellij-git-tag-statusbar/blob/master/settings.gradle
Github Open Source
Open Source
MIT
2,020
intellij-git-tag-statusbar
pnancke
Gradle
Code
3
23
rootProject.name = 'git-tag-for-intellij-status-bar'
1,439
https://github.com/mattboschetti/kingdom-key/blob/master/src/test/java/com/github/mattboschetti/kingdom/scores/model/GameTest.java
Github Open Source
Open Source
Unlicense, LicenseRef-scancode-warranty-disclaimer
2,020
kingdom-key
mattboschetti
Java
Code
69
283
package com.github.mattboschetti.kingdom.scores.model; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; public class GameTest { @Test public void testAddScore() { Game game = new Game(); game.addScore(1, createScore(100, 10)); List<Score> highScores = game.getHighScores(1); assertNotNull(highScores); assertEquals(1, highScores.size()); assertEquals(10, highScores.get(0).getScore()); assertEquals(100, highScores.get(0).getUser().getId()); } @Test public void gettingHighScoresForNonExistentScoreShouldReturnEmptyList() { Game game = new Game(); List<Score> highScores = game.getHighScores(1); assertNotNull(highScores); assertTrue(highScores.isEmpty()); } private Score createScore(int userId, int score) { return new Score(score, new User(userId)); } }
43,415
https://github.com/philsometimes/innerfish-3d/blob/master/src/views/Info.js
Github Open Source
Open Source
MIT
null
innerfish-3d
philsometimes
JavaScript
Code
361
1,315
import React, {useContext} from 'react'; import ReactHtmlParser from 'react-html-parser'; import {Box, Flex, Image, Text, Heading, Link} from 'rebass'; import Markdown from 'markdown-to-jsx' import { useTheme } from 'emotion-theming' import { DataContext, IdContext, SetIdContext, DarkContext, BackerContext} from '../Context' const Info = ({attribution}) => { const theme = useTheme() const data = useContext(DataContext) const setId = useContext(SetIdContext) const id = useContext(IdContext) const dark = useContext(DarkContext) const backer = useContext(BackerContext) const specimen = data.find(datum => datum.uid === id) const LinkCatcher= props =>{ return( <Link sx={{ color:'sea', fontWeight:'bold', cursor: 'pointer', ':hover':{ color:'sky', } }} onClick={()=> {setId(props.href.replace('#',''))}}>{props.children}</Link> ) } return( <Box sx={{px:'5vmin', py:'4vmin', bg: backer===1 ? dark ? 'light85' : 'dark85' : 'transparent', height:'fit-content',width:'fit-content', maxWidth:'30vw', pointerEvents:'all',alignSelf:'flex-end', transition:'background-color 0.4s'}}> {specimen.scientific && <Heading sx={{ fontSize:'medium', fontStyle:'italic', lineHeight:'1.1', mb: '1vmin', color: (backer===0 && dark) ? 'light' : (backer===0 && !dark) ? 'dark' : dark ? 'dark' : 'light', opacity: backer !== 2 ? 1 : 0, transition:'opacity 0.4s' // textShadow: `0.1vmin 0.1vmin 0.3vmin ${theme.colors.dark50}`, }}>{specimen.scientific}</Heading> } {specimen.scientific && specimen.common && <Heading sx={{ fontSize:'small', mb: '0.6vmin', color: (backer===0 && dark) ? 'light' : (backer===0 && !dark) ? 'dark' : dark ? 'dark' : 'light', opacity: backer !== 2 ? 1 : 0, transition:'opacity 0.4s' // textShadow: `0.1vmin 0.1vmin 0.3vmin ${theme.colors.dark50}`, }}>{specimen.common}</Heading> } {!specimen.scientific && specimen.common && <Heading sx={{ fontSize:'medium', lineHeight:'1.1', mb: '1vmin', color: (backer===0 && dark) ? 'light' : (backer===0 && !dark) ? 'dark' : dark ? 'dark' : 'light', opacity: backer !== 2 ? 1 : 0, transition:'opacity 0.4s' // textShadow: `0.1vmin 0.1vmin 0.3vmin ${theme.colors.dark50}`, }}>{specimen.common}</Heading> } {attribution && <Link href={specimen.url} target='_blank' sx={{ fontFamily:'body', fontWeight:'bold', textTransform:'uppercase', letterSpacing:'0.1vmin', textDecoration:'none', fontSize:'miniscule', lineHeight:'1.1', color: (backer===0 && dark) ? 'ochre' : (backer===0 && !dark) ? 'amber' : dark ? 'amber' : 'ochre', opacity: backer !== 2 ? 1 : 0, transition:'opacity 0.4s', ':hover':{ color: dark ? 'amber' : 'marigold', } }}>{attribution}</Link> } {/*<Text sx={{ fontFamily:'body', fontSize:'teensy', lineHeight:'1.65', mt: '2vmin', color: dark ? 'light' : 'dark', }}>{ReactHtmlParser(specimen.caption)}</Text>*/} <Text sx={{ fontFamily:'body', fontSize:'teensy', lineHeight:'1.65', mt: '2vmin', color: (backer===0 && dark) ? 'light' : (backer===0 && !dark) ? 'dark' : dark ? 'dark' : 'light', opacity: backer !== 2 ? 1 : 0, transition:'opacity 0.4s', }}> <Markdown options={{overrides:{a:{component:LinkCatcher}}}}> {specimen.caption} </Markdown> </Text> </Box> ) } export default Info
24,038
https://github.com/flushentitypacket/concepts/blob/master/problems/largest-rectangle.js
Github Open Source
Open Source
MIT
null
concepts
flushentitypacket
JavaScript
Code
75
178
// https://www.hackerrank.com/challenges/largest-rectangle/problem const myRectangles = [1,2,3,4,5] const largestRectangle = (h) => { let largest = 0 h.forEach((height, index) => { let i = index let j = index while (i > 0 && h[i - 1] >= height) { i-- } while (j < h.length - 1 && h[j + 1] >= height) { j++ } const width = j - i + 1 largest = Math.max(largest, width * height) }) return largest } console.log(largestRectangle(myRectangles))
9,201
https://github.com/SpacePassport/unity-algorand-sdk/blob/master/Runtime/CareBoo.AlgoSdk/Serialization/AlgoApiKeyAttribute.cs
Github Open Source
Open Source
MIT
2,022
unity-algorand-sdk
SpacePassport
C#
Code
67
201
using System; using System.Diagnostics; namespace AlgoSdk { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = true, AllowMultiple = false)] [Conditional("UNITY_EDITOR")] public sealed class AlgoApiField : Attribute { readonly string jsonKeyName; readonly string msgPackKeyName; readonly bool readOnly; public AlgoApiField(string jsonKeyName, string msgPackKeyName, bool readOnly = false) { this.jsonKeyName = jsonKeyName; this.msgPackKeyName = msgPackKeyName; } public string JsonKeyName => jsonKeyName; public string MessagePackKeyName => msgPackKeyName; public bool ReadOnly => readOnly; } }
25,519
https://github.com/Next-Gen-UI/Code-Dynamics/blob/master/Leetcode/0546. Remove Boxes/0546.cpp
Github Open Source
Open Source
MIT
null
Code-Dynamics
Next-Gen-UI
C++
Code
130
374
class Solution { public: int removeBoxes(vector<int>& boxes) { const int n = boxes.size(); // dp[i][j][k] := max score of boxes[i..j] if k boxes eqaul to boxes[j] dp.resize(n, vector<vector<int>>(n, vector<int>(n))); return removeBoxes(boxes, 0, n - 1, 0); } private: vector<vector<vector<int>>> dp; int removeBoxes(const vector<int>& boxes, int i, int j, int k) { if (i > j) return 0; if (dp[i][j][k]) return dp[i][j][k]; int r = j; int sameBoxes = k + 1; while (r > 0 && boxes[r - 1] == boxes[r]) { --r; ++sameBoxes; } dp[i][j][k] = removeBoxes(boxes, i, r - 1, 0) + sameBoxes * sameBoxes; for (int p = i; p < r; ++p) if (boxes[p] == boxes[r]) dp[i][j][k] = max(dp[i][j][k], removeBoxes(boxes, i, p, sameBoxes) + removeBoxes(boxes, p + 1, r - 1, 0)); return dp[i][j][k]; } };
3,362
https://github.com/wmyfelix/genshin-gacha-kit/blob/master/ggacha/throwable.py
Github Open Source
Open Source
MIT
2,021
genshin-gacha-kit
wmyfelix
Python
Code
75
547
class GenshinBaseException(Exception): """原神祈愿卡池抽取记录处理程序所抛出的异常的基类。""" def __init__(self, *args): super(GenshinBaseException, self).__init__(*args) class CollectingError(GenshinBaseException): """获取祈愿卡池抽取记录时触发的错误。""" def __init__(self, *args): super(CollectingError, self).__init__(*args) class MergingException(GenshinBaseException): """合并异常。""" def __init__(self, *args): super(MergingException, self).__init__(*args) class MultiRegionError(MergingException): """不允许合并两段不同地区的抽卡记录""" def __init__(self, region1, region2): super(MultiRegionError, self).__init__( self.__doc__ + ':%s %s' % (region1, region2) ) class MultiLanguageError(MergingException): """不允许合并两段不同语言文字记载的抽卡记录""" def __init__(self, lang1, lang2): super(MultiLanguageError, self).__init__( '{tip}:{lang_a} 与 {lang_b}'.format( tip=self.__doc__, lang_a=lang1, lang_b=lang2, ), ) class MultiUIDError(MergingException): """不允许合并两段不同UID的抽卡记录""" def __init__(self, uid1, uid2): super(MultiUIDError, self).__init__( '{tip}:{uid_a} 与 {uid_b}'.format( tip=self.__doc__, uid_a=uid1, uid_b=uid2, ), )
25,178
https://github.com/minrk/xeus-cling/blob/master/src/xholder_cling.cpp
Github Open Source
Open Source
BSD-3-Clause
2,019
xeus-cling
minrk
C++
Code
161
635
/*************************************************************************** * Copyright (c) 2016, Johan Mabille, Loic Gouarin and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #include "xholder_cling.hpp" #include "xpreamble.hpp" #include <algorithm> namespace xcpp { /*********************************** * xholder_preamble implementation * ***********************************/ xholder_preamble::xholder_preamble() : p_holder(nullptr) { } xholder_preamble::xholder_preamble(xpreamble* holder) : p_holder(holder) { } xholder_preamble::~xholder_preamble() { delete p_holder; } xholder_preamble::xholder_preamble(const xholder_preamble& rhs) : p_holder(rhs.p_holder ? rhs.p_holder->clone() : nullptr) { } xholder_preamble::xholder_preamble(xholder_preamble&& rhs) : p_holder(rhs.p_holder) { rhs.p_holder = nullptr; } xholder_preamble& xholder_preamble::operator=(const xholder_preamble& rhs) { xholder_preamble tmp(rhs); swap(tmp); return *this; } xholder_preamble& xholder_preamble::operator=(xholder_preamble&& rhs) { xholder_preamble tmp(std::move(rhs)); swap(tmp); return *this; } xholder_preamble& xholder_preamble::operator=(xpreamble* holder) { delete p_holder; p_holder = holder; return *this; } void xholder_preamble::apply(const std::string& s, xeus::xjson& kernel_res) { if (p_holder != nullptr) { p_holder->apply(s, kernel_res); } } bool xholder_preamble::is_match(const std::string& s) const { if (p_holder != nullptr) { return p_holder->is_match(s); } return false; } }
28,825
https://github.com/IvanJL/2021_python_selenium/blob/master/module_05/test_sauce_class_login.py
Github Open Source
Open Source
Unlicense
null
2021_python_selenium
IvanJL
Python
Code
91
319
from module_05.sauce_fun_lib.TestBase import TestBase import pytest from selenium.common.exceptions import TimeoutException from selenium.webdriver.remote.webdriver import WebDriver from module_05.sauce_fun_lib.inventory import get_inventory from module_05.sauce_fun_lib.login import login, get_login_error class TestLogin(TestBase): _ERROR_MSG = 'Epic sadface: Username and password do not match any user in this service' def test_login(self): self.driver: WebDriver login(self.wait, 'standard_user', 'secret_sauce') items = get_inventory(self.wait) assert len(items) > 0, 'Inventory should be loaded' def test_invalid_login(self): login(self.wait, 'standard_user', 'invalid_secret') error_msg = get_login_error(self.wait) assert error_msg is not None, 'Error message should be displayed for invalid login' assert error_msg == TestBase._ERROR_MSG, f'Error message should be {TestBase._ERROR_MSG}' with pytest.raises(TimeoutException): get_inventory(self.wait)
13,309
https://github.com/nasa/cumulus/blob/master/packages/integration-tests/bin/cli.js
Github Open Source
Open Source
LicenseRef-scancode-warranty-disclaimer, Apache-2.0, LicenseRef-scancode-unknown-license-reference
2,023
cumulus
nasa
JavaScript
Code
203
550
#!/usr/bin/env node 'use strict'; const program = require('commander'); const pckg = require('../package.json'); const testRunner = require('..'); program.version(pckg.version); /** * Verify that the given param is not null. Write out an error if null. * * @param {Object} paramConfig - param name and value {name: value:} * @returns {boolean} true if param is not null */ function verifyRequiredParameter(paramConfig) { if (paramConfig.value === null) { console.log(`Error: ${paramConfig.name} is a required parameter.`); return false; } return true; } /** * Verify required parameters are present * * @param {list<Object>} requiredParams - params in the form {name: 'x' value: 'y'} * @returns {boolean} - true if all params are not null */ function verifyWorkflowParameters(requiredParams) { return requiredParams.map(verifyRequiredParameter).includes(false) === false; } program .usage('TYPE COMMAND [options]') .option('-s, --stack-name <stackName>', 'AWS Cloud Formation stack name', null) .option('-b, --bucket-name <bucketName>', 'AWS S3 internal bucket name', null) .option('-w, --workflow <workflow>', 'Workflow name', null) .option('-i, --input-file <inputFile>', 'Workflow input JSON file', null); program .command('workflow') .description('Execute a workflow and determine if the workflow completes successfully') .action(() => { if (verifyWorkflowParameters([{ name: 'stack-name', value: program.stackName }, { name: 'bucket-name', value: program.bucketName }, { name: 'workflow', value: program.workflow }, { name: 'input-file', value: program.inputFile }])) { testRunner.testWorkflow( program.stackName, program.bucketName, program.workflow, program.inputFile ); } }); program .parse(process.argv);
15,745
https://github.com/luchotess/nestjs-auth/blob/master/src/resources/users/users.controller.ts
Github Open Source
Open Source
MIT
null
nestjs-auth
luchotess
TypeScript
Code
83
288
import { Controller, Request, Post, UseGuards, Res, Get } from '@nestjs/common'; import { JwtAuthGuard } from 'src/core/auth/guards/jwt-auth.guard'; import { UsersService } from 'src/resources/users/users.service'; import { Response } from 'express'; import { BaseController } from '../../core/base.controller'; @Controller('users') @UseGuards(JwtAuthGuard) export class UsersController extends BaseController { constructor (private _UsersService: UsersService) { super(_UsersService) } @Post() async createUser (@Request() req, @Res() res: Response) { if (!req.body.role) { req.body.role = 'admin'; } return res.status(201).json(await this._UsersService.create(req.body)); } @Get('clients') async getUserProjects(@Request() req, @Res() res: Response) { return res.json(await this._UsersService.getUserClients(req.user.id)); } }
24,898
https://github.com/zadr/WWDCDownloader/blob/master/WWDCDownloader/WWDCURLRequest.h
Github Open Source
Open Source
Apache-2.0
2,023
WWDCDownloader
zadr
Objective-C
Code
78
254
// // WWDCURLRequest.h // WWDCDownloader // // Created by zach on 6/14/13. // @class WWDCURLRequest; @class WWDCURLResponse; typedef void (^WWDCRequestCompletionBlock)(WWDCURLRequest *request, WWDCURLResponse *response, NSError *error); @interface WWDCURLRequest : NSOperation + (instancetype) requestWithRemoteAddress:(NSString *) remoteAddress savePath:(NSString *) localPath; @property (nonatomic, copy) WWDCRequestCompletionBlock successBlock; @property (nonatomic, copy) WWDCRequestCompletionBlock failureBlock; @end @interface WWDCURLResponse : NSObject @property (nonatomic, copy, readonly) NSString *remoteAddress; @property (nonatomic, copy, readonly) NSString *localPath; @property (nonatomic, readonly) NSInteger statusCode; @end @interface NSOperationQueue (Additions) + (NSOperationQueue *) wwdc_requestQueue; @end
5,042
https://github.com/Pandinosaurus/legate.pandas/blob/master/test.py
Github Open Source
Open Source
Apache-2.0
2,021
legate.pandas
Pandinosaurus
Python
Code
1,532
5,182
#!/usr/bin/env python # Copyright 2021 NVIDIA 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. # from __future__ import print_function import argparse import datetime import glob import json import multiprocessing import os import platform import subprocess import sys # Find physical core count of the machine. if platform.system() == "Linux": lines = subprocess.check_output(["lscpu", "--parse=core"]) physical_cores = len( set( line for line in lines.decode("utf-8").strip().split("\n") if not line.startswith("#") ) ) elif platform.system() == "Darwin": physical_cores = int( subprocess.check_output(["sysctl", "-n", "hw.physicalcpu"]) ) else: raise Exception("Unknown platform: %s" % platform.system()) # Choose a reasonable number of application cores given the # available physical cores. app_cores = max(physical_cores - 2, 1) # some test programs have additional command line arguments test_flags = {} # some tests are currently disabled disabled_tests = [] red = "\033[1;31m" green = "\033[1;32m" clear = "\033[0m" FNULL = open(os.devnull, "w") def find_tests_to_run(pattern): # draw tests from these directories legate_tests = [] if pattern is None: legate_tests.extend(glob.glob("tests/pandas/*.py")) legate_tests.extend(glob.glob("tests/interop/*.py")) legate_tests.extend(glob.glob("tests/io/*.py")) else: to_test = set( (glob.glob(pattern) if os.path.isfile(pattern) else []) + glob.glob(pattern + "*.py") + glob.glob(pattern + "/*.py") ) legate_tests.extend(to_test) # filter out disabled tests legate_tests = sorted( filter(lambda test: test not in disabled_tests, legate_tests) ) return legate_tests def load_json_config(filename): try: with open(filename, "r") as f: return json.load(f) except IOError: return None def cmd(command, env=None, cwd=None, stdout=None, stderr=None, show=True): if show: print(" ".join(command)) return subprocess.check_call( command, env=env, cwd=cwd, stdout=stdout, stderr=stderr ) def build_legate(root_dir, env, threads): cmd( [os.path.join(root_dir, "install.py"), "-j", str(threads)], env=env, cwd=root_dir, ) def run_test( test_file, driver, flags, test_flags, env, root_dir, suppress_stdout, verbose, ): test_path = os.path.join(root_dir, test_file) try: # Supress stdout for now, still want to see stderr cmd( [driver, test_path, "--test"] + flags + test_flags, env=env, cwd=root_dir, stdout=FNULL if not verbose or suppress_stdout else sys.stderr, stderr=FNULL if not verbose else sys.stderr, show=verbose, ) return True, test_file except (OSError, subprocess.CalledProcessError): return False, test_file def report_result(test_name, result): (passed, test_file) = result if passed: print("[%sPASS%s] (%s) %s" % (green, clear, test_name, test_file)) return 1 else: print("[%sFAIL%s] (%s) %s" % (red, clear, test_name, test_file)) return 0 def compute_thread_pool_size_for_gpu_tests(pynvml, gpus_per_test): # TODO: We need to make this configurable MEMORY_BUDGET = 6 << 30 gpu_count = pynvml.nvmlDeviceGetCount() parallelism_per_gpu = 16 for idx in range(gpu_count): info = pynvml.nvmlDeviceGetMemoryInfo( pynvml.nvmlDeviceGetHandleByIndex(idx) ) parallelism_per_gpu = min( parallelism_per_gpu, info.free // MEMORY_BUDGET ) return ( parallelism_per_gpu * (gpu_count // gpus_per_test), parallelism_per_gpu, ) def run_all_tests_legate( test_name, legate_tests, root_dir, flags, env, threads, nodes, suppress_stdout, verbose, num_procs, num_util_procs, ): legate_pandas_dir = os.path.dirname(os.path.realpath(__file__)) legate_config = os.path.join(legate_pandas_dir, ".legate.core.json") legate_dir = None if "LEGATE_DIR" in os.environ: legate_dir = os.environ["LEGATE_DIR"] elif legate_dir is None: legate_dir = load_json_config(legate_config) if legate_dir is None or not os.path.exists(legate_dir): raise Exception("You need to provide a Legate Core installation") legate_dir = os.path.realpath(legate_dir) driver = os.path.join(os.path.join(legate_dir, "bin"), "legate") if test_name == "GPU": try: import pynvml pynvml.nvmlInit() except ModuleNotFoundError: pynvml = None total_pass = 0 flags += ["--no-replicate"] flags += ["--util", str(num_util_procs)] if threads == 1 or (test_name == "GPU" and pynvml is None): for test_file in legate_tests: result = run_test( test_file, driver, flags, test_flags.get(test_file, []), env, root_dir, suppress_stdout, verbose, ) total_pass += report_result(test_name, result) else: if verbose: print( "Warning: outputs from test runs will be jumbled when " "parallel testing is enabled. Please run with '-j 1' " "for a cleaner output" ) # Turn off the core pinning so that the tests can run concurrently env["REALM_SYNTHETIC_CORE_MAP"] = "" if threads is None: if test_name == "CPU": threads = multiprocessing.cpu_count() // num_procs else: threads, parallelism = compute_thread_pool_size_for_gpu_tests( pynvml, num_procs ) elif test_name == "GPU": gpu_count = pynvml.nvmlDeviceGetCount() parallelism = threads * num_procs // gpu_count pool = multiprocessing.Pool(threads) results = [] for idx, test_file in enumerate(legate_tests): results.append( pool.apply_async( run_test, ( test_file, driver, flags + ( [ "-cuda:skipgpus", str( ((idx % threads) // parallelism) * num_procs ), ] if test_name == "GPU" else [] ), test_flags.get(test_file, []), env, root_dir, suppress_stdout, verbose, ), ) ) pool.close() result_set = set(results) while True: completed = set() for result in result_set: if result.ready(): total_pass += report_result(test_name, result.get()) completed.add(result) result_set -= completed if len(result_set) == 0: break print( "%24s: Passed %4d of %4d tests (%5.1f%%)" % ( "%s" % test_name, total_pass, len(legate_tests), float(100 * total_pass) / len(legate_tests), ) ) if test_name == "GPU": if pynvml is not None: pynvml.nvmlShutdown() return total_pass def option_enabled(option, options, var_prefix="", default=True): if options is not None: return option in options option_var = "%s%s" % (var_prefix, option.upper()) if option_var in os.environ: return os.environ[option_var] == "1" return default class Stage(object): __slots__ = ["name", "begin_time"] def __init__(self, name): self.name = name def __enter__(self): self.begin_time = datetime.datetime.now() print() print("#" * 60) print("### Entering Stage: %s" % self.name) print("#" * 60) print() sys.stdout.flush() def __exit__(self, exc_type, exc_val, exc_tb): end_time = datetime.datetime.now() print() print("#" * 60) print("### Exiting Stage: %s" % self.name) print("### * Exception Type: %s" % exc_type) print("### * Elapsed Time: %s" % (end_time - self.begin_time)) print("#" * 60) print() sys.stdout.flush() def report_mode( debug, use_gasnet, use_cuda, use_spy, use_gcov, use_cmake, ): print() print("#" * 60) print("### Test Suite Configuration") print("###") print("### Debug: %s" % debug) print("###") print("### Build Flags:") print("### * GASNet: %s" % use_gasnet) print("### * CUDA: %s" % use_cuda) print("### * Spy: %s" % use_spy) print("### * Gcov: %s" % use_gcov) print("### * CMake: %s" % use_cmake) print("#" * 60) print() sys.stdout.flush() def run_tests( debug=True, use_features=None, thread_count=None, node_count=0, utils=2, cpus=4, gpus=1, only_pattern=None, root_dir=None, suppress_stdout=False, verbose=False, ): if root_dir is None: root_dir = os.path.dirname(os.path.realpath(__file__)) # Determine which features to build with. def feature_enabled(feature, default=True): return option_enabled(feature, use_features, "USE_", default) use_gasnet = feature_enabled("gasnet", False) use_cuda = feature_enabled("cuda", False) use_spy = feature_enabled("spy", False) use_gcov = feature_enabled("gcov", False) use_cmake = feature_enabled("cmake", False) gcov_flags = " -ftest-coverage -fprofile-arcs" report_mode( debug, use_gasnet, use_cuda, use_spy, use_gcov, use_cmake, ) # Normalize the test environment. env = dict( list(os.environ.items()) + [ ("LEGATE_TEST", "1"), ("DEBUG", "1" if debug else "0"), ("USE_GASNET", "1" if use_gasnet else "0"), ("USE_CUDA", "1" if use_cuda else "0"), ("USE_PYTHON", "1"), # Always need python for Legate ("USE_SPY", "1" if use_spy else "0"), ] + ( # Gcov doesn't get a USE_GCOV flag, but instead stuff the GCC # options for Gcov on to the compile and link flags. [ ( "CC_FLAGS", ( os.environ["CC_FLAGS"] + gcov_flags if "CC_FLAGS" in os.environ else gcov_flags ), ), ( "LD_FLAGS", ( os.environ["LD_FLAGS"] + gcov_flags if "LD_FLAGS" in os.environ else gcov_flags ), ), ] if use_gcov else [] ) ) legate_tests = find_tests_to_run(only_pattern) # Build Legate in the right environment # with Stage('build'): # build_legate(root_dir, env, thread_count) total_pass, total_count = 0, 0 # Now run the tests if not use_cuda: with Stage("CPU tests"): count = run_all_tests_legate( "CPU", legate_tests, root_dir, ["--cpus", str(cpus)], env, thread_count, node_count, suppress_stdout, verbose, cpus, utils, ) total_pass += count total_count += len(legate_tests) else: with Stage("GPU tests"): count = run_all_tests_legate( "GPU", legate_tests, root_dir, ["--gpus", str(gpus), "-lg:window", "4096"], env, thread_count, node_count, suppress_stdout, verbose, gpus, utils, ) total_pass += count total_count += len(legate_tests) print(" " + "~" * 54) print( "%24s: Passed %4d of %4d tests (%5.1f%%)" % ( "total", total_pass, total_count, (float(100 * total_pass) / total_count), ) ) return not (total_count == total_pass) # behaves enough like a normal list for ArgumentParser's needs, except for # the __contains__ method, which accepts a list of values and checks each # one for membership class MultipleChoiceList(object): def __init__(self, *args): self.list = list(args) def __contains__(self, x): if type(x) is list: for v in x: if v not in self.list: return False return True else: return x in self.list def __iter__(self): return self.list.__iter__() class ExtendAction(argparse.Action): def __init__(self, **kwargs): super(ExtendAction, self).__init__(**kwargs) def __call__(self, parser, namespace, values, option_string=None): items = getattr(namespace, self.dest, None) items = items[:] if items else [] if type(values) is list: items.extend(values) else: items.append(values) setattr(namespace, self.dest, items) def driver(): parser = argparse.ArgumentParser(description="Legate test suite") # Build options: parser.add_argument( "--debug", dest="debug", action="store_true", default=os.environ["DEBUG"] == "1" if "DEBUG" in os.environ else True, help="Build Legate in debug mode (also via DEBUG).", ) parser.add_argument( "--no-debug", dest="debug", action="store_false", help="Disable debug mode (equivalent to DEBUG=0).", ) parser.add_argument( "--use", dest="use_features", action=ExtendAction, choices=MultipleChoiceList("gasnet", "cuda", "spy", "gcov", "cmake"), type=lambda s: s.split(","), default=None, help="Build Legate with features (also via USE_*).", ) parser.add_argument( "--nodes", dest="node_count", nargs="?", type=int, default=0, help="Number of nodes used to run the tests (will always be launched " "using mpirun, even with 1 node).", ) parser.add_argument( "--util", dest="utils", nargs="?", type=int, default=2, help="Number of utility processors used to run the tests.", ) parser.add_argument( "--cpus", dest="cpus", nargs="?", type=int, default=4, help="Number of CPUs per node used to run the tests.", ) parser.add_argument( "--gpus", dest="gpus", nargs="?", type=int, default=1, help="Number of GPUs per node used to run the tests.", ) parser.add_argument( "-C", "--directory", dest="root_dir", metavar="DIR", action="store", required=False, help="Legate root directory.", ) parser.add_argument( "-j", dest="thread_count", nargs="?", type=int, help="Number threads used to compile.", ) parser.add_argument( "--only", dest="only_pattern", type=str, required=False, default=None, help="Glob pattern selecting test cases to run.", ) parser.add_argument( "--suppress_stdout", dest="suppress_stdout", action="store_true", required=False, default=False, help="Suppress stdout in verbose mode", ) parser.add_argument( "-v", "--verbose", dest="verbose", action="store_true", required=False, default=False, help="Print more debugging information.", ) args = parser.parse_args() sys.exit(run_tests(**vars(args))) if __name__ == "__main__": driver()
2,928
https://github.com/liuguangqiang/CookieBar/blob/master/app/src/main/java/com/liuguangqiang/cookie/sample/MainActivity.java
Github Open Source
Open Source
Apache-2.0
2,022
CookieBar
liuguangqiang
Java
Code
167
916
package com.liuguangqiang.cookie.sample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.liuguangqiang.cookie.CookieBar; import com.liuguangqiang.cookie.OnActionClickListener; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnTop = (Button) findViewById(R.id.btn_top); btnTop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new CookieBar.Builder(MainActivity.this) .setTitle(R.string.cookie_title) .setMessage(R.string.cookie_message) .show(); } }); Button btnBottom = (Button) findViewById(R.id.btn_bottom); btnBottom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new CookieBar .Builder(MainActivity.this) .setTitle(R.string.cookie_title) .setIcon(R.mipmap.ic_launcher) .setMessage(R.string.cookie_message) .setLayoutGravity(Gravity.BOTTOM) .setAction(R.string.cookie_action, new OnActionClickListener() { @Override public void onClick() { Toast.makeText(getApplicationContext(), "点击后,我更帅了!", Toast.LENGTH_LONG).show(); } }) .show(); } }); Button btnTopWithIcon = (Button) findViewById(R.id.btn_top_with_icon); btnTopWithIcon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new CookieBar.Builder(MainActivity.this) .setMessage(R.string.cookie_message) .setDuration(10000) .setActionWithIcon(R.mipmap.ic_action_close, new OnActionClickListener() { @Override public void onClick() { Toast.makeText(getApplicationContext(), "点击后,我更帅了!", Toast.LENGTH_LONG).show(); } }) .show(); } }); Button btnCustom = (Button) findViewById(R.id.btn_custom); btnCustom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new CookieBar.Builder(MainActivity.this) .setTitle(R.string.cookie_title) .setMessage(R.string.cookie_message) .setDuration(3000) .setBackgroundColor(R.color.colorPrimary) .setActionColor(android.R.color.white) .setTitleColor(R.color.colorAccent) .setAction(R.string.cookie_action, new OnActionClickListener() { @Override public void onClick() { Toast.makeText(getApplicationContext(), "点击后,我更帅了!", Toast.LENGTH_LONG).show(); } }) .show(); } }); } }
46,847
https://github.com/karta0898098/iam/blob/master/pkg/db/connection.go
Github Open Source
Open Source
MIT
2,023
iam
karta0898098
Go
Code
164
485
package db import ( "gorm.io/gorm" "github.com/karta0898098/iam/pkg/db/conn" ) type RWConfig struct { Read conn.Database `mapstructure:"read"` Write conn.Database `mapstructure:"write"` } type Connection interface { ReadDB() *gorm.DB WriteDB() *gorm.DB } type RWConnection struct { readDB *gorm.DB writeDB *gorm.DB } func (conn *RWConnection) ReadDB() *gorm.DB { return conn.readDB } func (conn *RWConnection) WriteDB() *gorm.DB { return conn.writeDB } func NewRWConnection(config RWConfig) (Connection, error) { var ( c Connection ) readDB, err := conn.SetupDatabase(&config.Read) if err != nil { return c, err } writeDB, err := conn.SetupDatabase(&config.Write) if err != nil { return c, err } return &RWConnection{ readDB: readDB, writeDB: writeDB, }, nil } type Config struct { Conn conn.Database `mapstructure:"conn"` } type connection struct { db *gorm.DB } func (c *connection) ReadDB() *gorm.DB { return c.db } func (c *connection) WriteDB() *gorm.DB { return c.db } func NewConnection(config Config) (Connection, error) { var ( c Connection ) db, err := conn.SetupDatabase(&config.Conn) if err != nil { return c, err } return &connection{ db: db, }, nil }
29,287
https://github.com/InstantBusinessNetwork/IBN/blob/master/Source/Server/Business/WidgetEngine/GoogleGadgetRequestHandler.cs
Github Open Source
Open Source
MIT
2,021
IBN
InstantBusinessNetwork
C#
Code
145
498
using System; using System.Collections.Generic; using System.Text; using Mediachase.Ibn.Core.Business; using Mediachase.Ibn.Data; namespace Mediachase.IBN.Business.WidgetEngine { /// <summary> /// Represents google gadget request handler. /// </summary> public class GoogleGadgetRequestHandler : BusinessObjectRequestHandler { #region Const #endregion #region Fields #endregion #region .Ctor /// <summary> /// Initializes a new instance of the <see cref="CustomizationItemArgumentRequestHandler"/> class. /// </summary> public GoogleGadgetRequestHandler() { } #endregion #region Properties #endregion #region Methods #region CreateEntityObject /// <summary> /// Creates the entity object. /// </summary> /// <param name="metaClassName">Name of the meta class.</param> /// <param name="primaryKeyId">The primary key id.</param> /// <returns></returns> protected override EntityObject CreateEntityObject(string metaClassName, PrimaryKeyId? primaryKeyId) { if (metaClassName == GoogleGadgetEntity.ClassName) { GoogleGadgetEntity retVal = new GoogleGadgetEntity(); retVal.PrimaryKeyId = primaryKeyId; return retVal; } return base.CreateEntityObject(metaClassName, primaryKeyId); } #endregion #region Load protected override void Load(BusinessContext context) { // solve problem if item was load in LocalDiskEntityObjectPlugin if (context.Response == null) { base.Load(context); } } #endregion #endregion } }
11,823
https://github.com/birkin/annex_receipts/blob/master/NameConverter.py
Github Open Source
Open Source
MIT
null
annex_receipts
birkin
Python
Code
357
1,042
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ Part of LAS-to-Josiah code. Convert names. """ import datetime, logging, os, pprint, string, sys log = logging.getLogger(__name__) ## add project parent-directory to sys.path parent_working_dir = os.path.abspath( os.path.join(os.getcwd(), os.pardir) ) sys.path.append( parent_working_dir ) from annex_eod_project import FileHandler class NameConverter( object ): def makeTrueOrigToArchiveOrigDictionary(self, inputList, timeStamp): log.debug( 'starting makeTrueOrigToArchiveOrigDictionary()' ) builtDict = {} for fileName in inputList: key = fileName # import string # underscorePosition = string.find(fileName, "_") underscorePosition = str.find(fileName, "_") rootSlice = fileName[:underscorePosition] value = "ORIG_" + rootSlice + "_" + timeStamp + ".dat" builtDict[key] = value return builtDict def makeArchiveOrigToArchiveParsedDictionary(self, inputDictionary, timeStamp): builtDict = {} for fileName in inputDictionary.values(): # the value in the incoming dictionary becomes the key in this built dictionary key = fileName rootSlice = fileName[5:10] value = "PARSED_" + rootSlice + "_" + timeStamp + ".dat" builtDict[key] = value return builtDict def convertInputToOriginal(self, inputFileName): if(inputFileName[:4] == "ORIG"): root = inputFileName[5:10] month = inputFileName[16:18] day = inputFileName[19:21] returnValue = root + "_" + month + day + ".txt" elif(inputFileName[:4] == "PARS"): root = inputFileName[7:12] month = inputFileName[18:20] day = inputFileName[21:23] returnValue = root + "_" + month + day + ".txt" else: returnValue = inputFileName return returnValue def prepareFinalDestinationDictionary(self, archive_original_to_archive_parsed_dictionary, destination_directory): """ Takes most recently used dictionary (with references to empty files removed) and creates the new dictionary for copying the parsed files to their final destination. Also checks for pre-existing files, and if found, appends a suffix to the file name to prevent overwriting. Called by Controller.py """ built_dct = {} for filename in archive_original_to_archive_parsed_dictionary.values(): key = filename # destinationFileName in inputDictionary becomes sourceFileName in outputDictionary root = filename[7:12].lower() ( year_str, month_str, day_str, hour_str, minute_str ) = self.make_datetime_strings( filename ) new_filename = '{rt}{yr}{mo}{dy}T{hr}{mn}'.format( rt=root, yr=year_str, mo=month_str, dy=day_str, hr=hour_str, mn=minute_str ) built_dct[key] = new_filename log.debug( 'built_dct, ```{0}```'.format( pprint.pformat(built_dct) ) ) return built_dct def make_datetime_strings( self, filename ): """ Extracts timestamp info from filename. Called by prepareFinalDestinationDictionary() """ year_str = filename[13:17] month_str = filename[18:20] day_str = filename[21:23] hour_str = filename[24:26] minute_str = filename[27:29] data_tpl = ( year_str, month_str, day_str, hour_str, minute_str ) log.debug( 'data_tpl, ```{0}```'.format( pprint.pformat(data_tpl) ) ) return data_tpl ## end class NameConverter()
44,015
https://github.com/kancve/mr4c/blob/master/java/src/java/com/google/mr4c/nativec/jna/JnaDataFileSource.java
Github Open Source
Open Source
Apache-2.0
2,020
mr4c
kancve
Java
Code
1,052
3,621
/** * Copyright 2014 Google Inc. 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. */ package com.google.mr4c.nativec.jna; import com.ochafik.lang.jnaerator.runtime.NativeSize; import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; import com.google.mr4c.nativec.ExternalDataFileSource; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.MR4CDataSourceReadPtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.MR4CDataSourceSkipPtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.MR4CGetDataSourceBytesPtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.MR4CGetDataSourceSizePtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.MR4CReleaseDataSourcePtr; import com.google.mr4c.nativec.jna.lib.Mr4cLibrary.CExternalDataFileSourcePtr; import com.google.mr4c.nativec.jna.lib.CExternalDataSourceCallbacksStruct; import com.google.mr4c.sources.AbstractDataFileSource; import com.google.mr4c.sources.BytesDataFileSource; import com.google.mr4c.sources.DataFileSource; import com.google.mr4c.util.MR4CLogging; import com.google.mr4c.util.ByteBufferInputStream; import com.sun.jna.Memory; import com.sun.jna.Pointer; import java.io.InputStream; import java.io.IOException; import java.io.PushbackInputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Arrays; import org.apache.hadoop.fs.BlockLocation; import org.slf4j.Logger; public class JnaDataFileSource implements ExternalDataFileSource { protected static final Logger s_log = MR4CLogging.getLogger(JnaDataFileSource.class); static Mr4cLibrary s_lib = Mr4cLibrary.INSTANCE; private DataFileSource m_src; private CExternalDataSourceCallbacksStruct m_callbacks; private DisposableMemory m_memory; private ByteBuffer m_buf; private long m_size = -1; private PushbackInputStream m_stream; private ReadableByteChannel m_chan; private boolean m_eof; private CExternalDataFileSourcePtr m_nativeSrc; /*package*/ JnaDataFileSource(DataFileSource src) { m_src = src; m_callbacks = new CExternalDataSourceCallbacksStruct(); buildBytesCallback(); buildSizeCallback(); buildReadCallback(); buildSkipCallback(); buildReleaseCallback(); m_nativeSrc = s_lib.CExternalDataFileSource_newDataFileSource(m_callbacks); JnaUtils.protectSource(m_src, this); } /*package*/ JnaDataFileSource(CExternalDataFileSourcePtr nativeSrc) { m_nativeSrc = nativeSrc; m_src = new SimpleSource(); } public DataFileSource getSource() { return m_src; } private void buildBytesCallback() { m_callbacks.getBytesCallback = new MR4CGetDataSourceBytesPtr() { public Pointer apply() { return doGetBytes(); } }; } private void buildSizeCallback() { m_callbacks.getSizeCallback = new MR4CGetDataSourceSizePtr() { public byte apply(NativeSizeByReference size) { return doGetSize(size); } }; } private void buildReadCallback() { m_callbacks.readCallback = new MR4CDataSourceReadPtr() { public byte apply(Pointer bufPtr, NativeSize num, NativeSizeByReference read) { return doRead(bufPtr, num, read); } }; } private void buildSkipCallback() { m_callbacks.skipCallback = new MR4CDataSourceSkipPtr() { public byte apply(NativeSize num, NativeSizeByReference skipped) { return doSkip(num, skipped); } }; } private void buildReleaseCallback() { m_callbacks.releaseCallback = new MR4CReleaseDataSourcePtr() { public void apply() { doRelease(); } }; } private void initSizeIfNecessary() throws IOException { if ( m_size!=-1 ) { return; } m_size = m_src.getFileSize(); if ( m_size==-1 ) { initBuffer(); } } private void initBufferIfNecessary() throws IOException { if ( m_buf!=null ) { return; } initBuffer(); } private void initBuffer() throws IOException { m_size = m_src.getFileSize(); if ( m_size==-1 ) { initBufferFromBytes(); } else { initBufferFromChannel(); } } private void initBufferFromBytes() throws IOException { byte[] bytes = m_src.getFileBytes(); m_memory = new DisposableMemory(bytes.length); m_buf = m_memory.getByteBuffer(0,bytes.length); m_buf.put(bytes); m_size = bytes.length; } private void initBufferFromChannel() throws IOException { m_memory = new DisposableMemory(m_size); InputStream stream = null; ReadableByteChannel chan = null; try { stream = m_src.getFileInputStream(); chan = Channels.newChannel(stream); m_buf = m_memory.getByteBuffer(0,m_size); int read = chan.read(m_buf); if ( read!=m_size ) { throw new IllegalStateException(String.format("Expected %s bytes, read %s bytes", m_size, read)); } } finally { if ( chan!=null ) { chan.close(); } else if ( stream!=null ) { stream.close(); } } } private void initStreamIfNecessary() throws IOException { if ( m_stream!=null ) { return; } m_stream = new PushbackInputStream(m_src.getFileInputStream()); m_chan = Channels.newChannel(m_stream); m_eof = false; } private synchronized Pointer doGetBytes() { try { initBufferIfNecessary(); return m_memory; } catch ( Exception e ) { s_log.error("Error accessing " + m_src.getDescription(), e); return null; } } private synchronized byte doGetSize(NativeSizeByReference size) { try { initSizeIfNecessary(); size.setValue(new NativeSize(m_size)); return 1; } catch ( Exception e ) { s_log.error("Error accessing " + m_src.getDescription(), e); return 0; } } private synchronized byte doRead(Pointer bufPtr, NativeSize num, NativeSizeByReference read) { try { initStreamIfNecessary(); if ( m_eof ) { read.setValue(new NativeSize(0)); return 1; } int size = num.intValue(); ByteBuffer buf = bufPtr.getByteBuffer(0, size); int numRead = m_chan.read(buf); if ( numRead<=0 ) { // reached EOF m_eof=true; numRead=0; } read.setValue(new NativeSize(numRead)); return 1; } catch ( Exception e ) { s_log.error("Error accessing " + m_src.getDescription(), e); return 0; } } private synchronized byte doSkip(NativeSize num, NativeSizeByReference skipped) { try { initStreamIfNecessary(); if ( m_eof ) { skipped.setValue(new NativeSize(0)); return 1; } long size = num.longValue(); long numSkipped = m_stream.skip(size); // InputStream just keeps skipping at EOF // Need to check if there are any bytes, or it could skip forever int next = m_stream.read(); if ( next==-1 ) { m_eof = true; } else { m_stream.unread(next); } skipped.setValue(new NativeSize(numSkipped)); return 1; } catch ( Exception e ) { s_log.error("Error accessing " + m_src.getDescription(), e); return 0; } } private synchronized void doRelease() { releaseMemory(); releaseStream(); m_src.release(); } private void releaseMemory() { if ( m_memory!=null ) { s_log.info("Freeing {} byte file [{}]" , m_size, m_src.getDescription()); m_memory.publicDispose(); } m_buf = null; m_memory = null; } private void releaseStream() { if ( m_chan==null ) { return; } s_log.info("Closing stream for file [{}]" , m_src.getDescription()); try { m_chan.close(); m_chan=null; m_stream=null; m_eof=false; } catch (IOException ioe) { s_log.warn("Error closing stream for " + m_src.getDescription(), ioe); } } /*package*/ CExternalDataFileSourcePtr getNativeSource() { return m_nativeSrc; } /*package*/ static CExternalDataFileSourcePtr toNative(ExternalDataFileSource src) { JnaDataFileSource jnaSrc = (JnaDataFileSource) src; return jnaSrc==null ? null : jnaSrc.getNativeSource(); } /*package*/ static JnaDataFileSource fromNative(CExternalDataFileSourcePtr nativeSrc) { return nativeSrc==null ? null : new JnaDataFileSource(nativeSrc); } // NOTE: JNA normally won't free the native memory until the Memory finalizer runs. // Its pretty easy for the GC to go a very long time without that happening. // This class exposes the protected dispose method. private static class DisposableMemory extends Memory { DisposableMemory(long length) { super(length); } public void publicDispose() { dispose(); } } // This class allows delaying asking for bytes from the native source private class SimpleSource extends AbstractDataFileSource { private DataFileSource m_delegate; public InputStream getFileInputStream() throws IOException { long size = getFileSize(); Pointer ptr = getPointer(); ByteBuffer buf = ptr.getByteBuffer(0, size); return new ByteBufferInputStream(buf); } public synchronized long getFileSize() throws IOException { return m_delegate==null ? getSizeHelper() : m_delegate.getFileSize(); } public synchronized byte[] getFileBytes() throws IOException { ensureSource(); return m_delegate.getFileBytes(); } public synchronized void getFileBytes(ByteBuffer buf) throws IOException { ensureSource(); m_delegate.getFileBytes(buf); } public synchronized void release() { if ( m_delegate!=null ) { m_delegate.release(); m_delegate=null; } } public String getDescription() { return "Simple JNA source wrapper"; } private void ensureSource() { if ( m_delegate!=null ) { return; } long size = getSizeHelper(); Pointer ptr = getPointer(); byte[] bytes = ptr.getByteArray(0, (int)size); m_delegate = new BytesDataFileSource(bytes); } private long getSizeHelper() { return s_lib.CExternalDataFileSource_getSize(m_nativeSrc).intValue(); } private Pointer getPointer() { return s_lib.CExternalDataFileSource_getBytes(m_nativeSrc); } } }
15,440
https://github.com/ZhangLei012/Nachos/blob/master/nachos_dianti/nachos-3.4/code/machine/elevator.h
Github Open Source
Open Source
Apache-2.0
2,020
Nachos
ZhangLei012
C
Code
728
1,515
// elevator.h // Data structures to emulate a bank of elevators. // // There are two interfaces -- one for the threads controlling // the elevators, and one for threads representing elevator // passengers. The only communication between these two // groups is via the elevator device. The elevator device // interface has both regular calls from the rider/controller // threads to the device, as well as "callbacks" (interrupts) // from the device to the riders/controllers when events occur. // // DO NOT CHANGE -- part of the machine emulation // // Copyright (c) 1992-1996 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #ifndef ELEVATOR_H #define ELEVATOR_H #include "copyright.h" #include "utility.h" #include "list.h" // which direction the elevator or rider is going enum Direction { Down, Up, Neither}; // elevator events that require signalling rider (on DoorsOpened) // or controllers (on ButtonPressed or ElevatorArrived) enum ElevatorEvent { NoEvent, DoorsOpened, UpButtonPressed, DownButtonPressed, FloorButtonPressed, ElevatorArrived}; const int MaxRiders = 4; // carrying capacity of each elevator const int DelayPerFloor = 100; // how long does an elevator take // to move between floors? class ElevatorInfo; class PendingElevatorEvent; typedef List ListOfEvents; // The following class defines a bank of elevators class ElevatorBank { public: ElevatorBank(int numElvtrs, int numFlrs, VoidFunctionPtr riders, int ridersArg, VoidFunctionPtr controllers, int controllersArg); // Initialize the elevator hardware, // use "riders" and "controllers" to // notify the rider/controller threads // that an event occurred they should // be interested in (such as, elevator // arrives, doors open, etc) ~ElevatorBank(); // deallocate the elevator hardware // Controller interface to elevator hardware void OpenDoors(int elevator);// Open the elevator doors; elevator // must not be in motion! void CloseDoors(int elevator);// Close the elevator doors. void MoveTo(int goingToFloor, int elevator); // Set the elevator into motion. // Elevator doors must be closed. // If elevator is already in motion, // this causes the elevator to stop // at a new floor (eg, if a rider // presses a new floor while the // elevator is moving) int WhereIsElevator(int elevator); // return the current position of // the elevator (which floor its on) void MarkDirection(int elevator, Direction dir); // change the display to show riders // where this elevator is headed ElevatorEvent getNextControllerEvent(int *floor, int *elevator) { return getNextEvent(controllerEvents, floor, elevator); } // when the elevator device calls back, // this will tell you what event(s) // (relevant to controller threads) // triggered the callback. // Rider interface to elevator control panel; roughly in // the order that they are called by a rider. void PressButton(int onFloor, Direction goingTo); // Press button outside elevator to // indicate where rider wants to go Direction getDirection(int elevator); // return the indicated direction // (set by MarkDirection()) of this // elevator bool EnterElevator(int onFloor, int elevator); // Step onto the elevator; elevator must have // < MaxRiders people on it currently // Returns false if doors have closed (might // have happened between when riders got // OpenDoors event and when they decided // to step onto the elevator). void PressFloor(int goingToFloor, int onElevator); // Press button inside elevator to // indicate where rider wants to go; // thread must be on the elevator bool ExitElevator(int onFloor, int elevator); // Step off the elevator. Returns false if // doors have closed. ElevatorEvent getNextRiderEvent(int *floor, int *elevator) { return getNextEvent(riderEvents, floor, elevator); } // when the elevator device calls back, // this will tell you what event(s) // (relevant to rider threads) // triggered the callback. void HandleInterrupt(); private: int numElevators; // how many elevators in this bank? int numFloors; // how many floors in this building? VoidFunctionPtr handlerRiders, handlerControllers; int argRiders, argControllers; // CallBackObj *callRiders; // call when an event occurs that // riders would be interested in // CallBackObj *callControllers; // call when an event occurs that // elevator controller threads // would be interested in ListOfEvents *riderEvents; // pending events relevant to riders ListOfEvents *controllerEvents;// pending events relevant to controllers ElevatorInfo **elevators; // array of per-elevator state void PostEvent(ListOfEvents *list, ElevatorEvent event, int floor, int elevator, bool inHandler); // an event occurred that requires // a callback ElevatorEvent getNextEvent(ListOfEvents *list, int *floor, int *elevator); // pull next event off the pending list // of events, return NoEvent if list is // empty }; #endif // ELEVATOR_H
1,095
https://github.com/aropixel/sylius-admin-media-plugin/blob/master/tests/Behat/Page/Admin/Product/CreateSimpleProductWithImagesPage.php
Github Open Source
Open Source
MIT
2,021
sylius-admin-media-plugin
aropixel
PHP
Code
577
2,319
<?php declare( strict_types=1 ); namespace Tests\Aropixel\SyliusAdminMediaPlugin\Behat\Page\Admin\Product; use Behat\Mink\Element\NodeElement; use Behat\Mink\Session; use Sylius\Behat\Page\Admin\Product\CreateSimpleProductPage; use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface; use Symfony\Component\Routing\RouterInterface; use Webmozart\Assert\Assert; class CreateSimpleProductWithImagesPage extends CreateSimpleProductPage { private const PARAM_ENTITIES_CROPS = "aropixel_sylius_admin_media.entities_crops"; private const PARAM_DEFAULT_CROPS = "aropixel_sylius_admin_media.default_crops"; private const PARAM_LIIP_FILTERS = "liip_imagine.filter_sets"; /** * @var ParameterBagInterface */ private $params; public function __construct( Session $session, $minkParameters, RouterInterface $router, string $routeName, ParameterBagInterface $params ) { parent::__construct( $session, $minkParameters, $router, $routeName ); $this->params = $params; } public function isSpinnerVisible() { $spinner = $this->getElement('spinner'); return $spinner->isVisible(); } public function waitForAjaxUpload() { $this->getDocument()->waitFor(10000, function () { return $this->isSpinnerHidden(); }); } private function isSpinnerHidden() { $spinner = $this->getElement('spinner'); return !$spinner->isVisible(); } public function isImagePreviewVisible($path) { $this->waitForAjaxUpload(); $imageForm = $this->getLastImageElement(); $imageNode = $imageForm->find('css', '.crop-hover img'); $imgUrl = $imageNode->getAttribute('src'); $this->getDocument()->waitFor( 10000, function () use ( $imgUrl, $path ) { return (strpos($imgUrl, $path) !== false); } ); //Assert::true(strpos($imgUrl, $path) !== false); return $this->isImageLinkBroken( $imgUrl ); } private function getLastImageElement(): NodeElement { $images = $this->getElement('images'); $items = $images->findAll('css', 'div[data-form-collection="item"]'); Assert::notEmpty($items); return end($items); } /** * @param string|null $imgUrl * * @return bool */ private function isImageLinkBroken( ?string $imgUrl ): bool { $baseUrl = $this->getParameter( 'base_url' ); $this->getSession()->visit( $baseUrl . '/' . $imgUrl ); $pageText = $this->getDocument()->getText(); $this->getSession()->back(); // si le 404 n'a pas été trouvé, retourne true return ( strpos( $pageText, '404 Not Found' ) === false ); } public function addImageItem() { $this->clickTabIfItsNotActive('media'); $filesPath = $this->getParameter('files_path'); $this->getDocument()->clickLink('Add'); $imageForm = $this->getLastImageElement(); } private function clickTabIfItsNotActive(string $tabName): void { $attributesTab = $this->getElement('tab', ['%name%' => $tabName]); if (!$attributesTab->hasClass('active')) { $attributesTab->click(); } } public function getDefaultCrops() { $defaultsCrops = $this->params->get(self::PARAM_DEFAULT_CROPS); return $defaultsCrops; } public function getProductImageCrops() { $entitiesCrops = $this->params->get(self::PARAM_ENTITIES_CROPS); $productImageCrops = $entitiesCrops['Sylius\Component\Core\Model\ProductImage']; return $productImageCrops; } public function getTypeOptions() { $typeInput = $this->getTypeInput(); return $typeInput->getText(); } private function getTypeInput() { $imageForm = $this->getLastImageElement(); return $imageForm->find('css', '.js-admin-media-type'); } public function selectImageType($type) { $this->waitForAjaxUpload(); $typeInput = $this->getTypeInput(); $typeInput->selectOption($type); } public function isCroppingFree() { $cropStyles = $this->cropImage(); $widthBeforeDrag = $this->buildArrayFromStyleString( $cropStyles['before'] )['width']; $widthAfterDrag = $this->buildArrayFromStyleString( $cropStyles['after'] )['width']; return ($widthBeforeDrag === $widthAfterDrag); } public function isCroppingSquare() { $cropStyles = $this->cropImage(); $widthBeforeDrag = $this->buildArrayFromStyleString( $cropStyles['before'] )['width']; $heightBeforeDrag = $this->buildArrayFromStyleString( $cropStyles['before'] )['height']; // check that the crop tool before resize it is square Assert::true($widthBeforeDrag === $heightBeforeDrag); $widthAfterDrag = $this->buildArrayFromStyleString( $cropStyles['after'] )['width']; $heightAfterDrag = $this->buildArrayFromStyleString( $cropStyles['after'] )['height']; // check that the crop tool after resize it is square return $widthAfterDrag === $heightAfterDrag; } private function buildArrayFromStyleString(string $style) { $dictionary = []; if (empty($style)) { return $dictionary; } foreach (explode(';', rtrim($style, ';, ')) as $css) { $parts = explode(':', $css); $dictionary[trim($parts[0])] = trim($parts[1]); } return $dictionary; } protected function getDefinedElements(): array { return array_merge(parent::getDefinedElements(), [ 'spinner' => '.spinner-container', ]); } private function getCropModal() { $imageForm = $this->getLastImageElement(); $triggerCropModal = $imageForm->find( 'css', '.js-crop' ); $triggerCropModal->click(); $cropModal = $imageForm->find( 'css', '.artgris-media-crop-modal' ); $this->getDocument()->waitFor( 10000, function () use ( $cropModal ) { return $cropModal->isVisible(); } ); return $cropModal; } /** * @return array */ private function cropImage(): array { $this->waitForAjaxUpload(); $cropModal = $this->getCropModal(); $this->getDocument()->waitFor( 10000, function () use ( $cropModal ){ return ( ! is_null( $cropModal->find( 'css', '.point-nw' ) ) ); } ); // find the crop box which contain the width and height $cropperBoxInitialStyle = $cropModal->find( 'css', '.cropper-crop-box' )->getAttribute( 'style' ); $pointNWCropDrag = $cropModal->find( 'css', '.point-nw' ); $pointWCropDrag = $cropModal->find( 'css', '.point-w' ); $pointNWCropDrag->dragTo( $pointWCropDrag ); $cropperBoxResizedStyle = $cropModal->find( 'css', '.cropper-crop-box' )->getAttribute( 'style' ); return [ 'before' => $cropperBoxInitialStyle, 'after' => $cropperBoxResizedStyle ]; } public function applyCrop() { $imageForm = $this->getLastImageElement(); $saveCrop = $imageForm->find('css', '.js-save'); $saveCrop->click(); $this->getDocument()->waitFor( 10000, function () use ( $imageForm ){ $modalBackground = $imageForm->find('css', '.js-modal-background'); return (!$modalBackground->isVisible()); } ); } }
29,018
https://github.com/SomeAspy/SCP-079/blob/master/internals/APIs.js
Github Open Source
Open Source
MIT
null
SCP-079
SomeAspy
JavaScript
Code
38
106
// Copyright (c) 2022 Aiden Baker // // This software is released under the MIT License. // https://opensource.org/licenses/MIT import { fetch } from 'undici'; export async function getNeko(type) { return fetch(`https://nekos.life/api/v2/img/${type}`) .then((res) => res.json()) .then((json) => json.url); }
28,024
https://github.com/hikalkan/samples/blob/master/ddd-layers/2/test/Acme.Crm.EntityFrameworkCore.Tests/EntityFrameworkCore/CrmEntityFrameworkCoreTestBase.cs
Github Open Source
Open Source
MIT
2,022
samples
hikalkan
C#
Code
14
59
using Volo.Abp; namespace Acme.Crm.EntityFrameworkCore { public abstract class CrmEntityFrameworkCoreTestBase : CrmTestBase<CrmEntityFrameworkCoreTestModule> { } }
7,986
https://github.com/SCP766/ProjectConsus/blob/master/ProjectConsus/Monitoring/Monitoring_Main.xaml.vb
Github Open Source
Open Source
MIT
null
ProjectConsus
SCP766
Visual Basic
Code
154
487
Imports System.ComponentModel Imports System.Data Imports ProjectConsus.CSQL Public Class Monitoring_Main Implements INotifyPropertyChanged Private dtMonitoredEmployees As New DataTable Private ParamName As New List(Of String) Private ParamValue As New List(Of Object) Public ReadOnly Property DvMonitoredEmployees Get Return dtMonitoredEmployees.DefaultView End Get End Property Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged Private Sub RaiseEventPropertyChanged(propertyname As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyname)) End Sub Public Sub New() InitializeComponent() Me.DataContext = Me GetEmployeeMonitoringList() End Sub Private Sub GetEmployeeMonitoringList() With ParamName .Clear() .Add("@EmployeeID") End With With ParamValue .Clear() .Add(AppDock.Emp.MyEmployeeID) End With dtMonitoredEmployees = ReadData(ParamName, ParamValue, "sp_Monitoring_GetList") RaiseEventPropertyChanged("DvMonitoredEmployees") End Sub Private Sub ChangeSchedule(sender As Object, e As RoutedEventArgs) Dim obj As Object = TryCast((CType(sender, FrameworkElement)).DataContext, Object) Dim ChangeSchedule As New Monitoring_ChangeSchedule(obj(0), obj(1), obj(2)) Dim res As Nullable(Of Boolean) = ChangeSchedule.ShowDialog If res Then GetEmployeeMonitoringList() End If End Sub Private Sub TitleBar_MouseDown(sender As Object, e As MouseButtonEventArgs) If e.LeftButton = MouseButtonState.Pressed Then DragMove() End If End Sub Private Sub WindowClose() Me.Close() End Sub End Class
46,837
https://github.com/khandy21yo/aplus/blob/master/CMC030/gl/source/gl_spec_reversebatch.bas
Github Open Source
Open Source
MIT
2,018
aplus
khandy21yo
Visual Basic
Code
562
1,594
1 %TITLE "Special Reversal Function" %SBTTL "GL_SPEC_REVERSEBATCH" %IDENT "V3.6a Calico" ! ! COPYRIGHT (C) 1989 BY ! ! Computer Management Center, Inc. ! Idaho Falls, Idaho. ! ! This software is furnished under a license and may be used and ! copied only in accordance with terms of such license and with ! the inclusion of the above copyright notice. This software or ! any other copies thereof may not be provided or otherwise made ! available to any other person. No title to and ownership of ! the software is hereby transferred. ! ! The information in this software is subject to change without ! notice and should not be construed as a commitment by ! Computer Management Center, Inc. ! ! CMC assumes no responsibility for the use or reliability of ! its software on equipment which is not supported by CMC. ! !++ ! Abstract:HELP ! .b ! .lm +5 ! This program is used to reverse the amounts in one ! entire post to the general ledger. ! It manually digs into the period file and changes ! the amounts there. Requires a RESYNC afterwards. ! NOTE: Does not use any CMC functions so that the ! size is as small as possible so KERMIT will not take ! too long. ! .lm -5 ! ! Index: ! ! Option: ! ! ! Compile: ! ! $ BAS GL_SOURCE:GL_SPEC_REVERSEBATCH/LINE ! $ LINK/EXECUTABLE=GL_EXE: GL_SPEC_REVERSEBATCH, FUNC_LIB:CMCLINK/OPTION ! $ DELETE GL_SPEC_REVERSEBATCH.OBJ;* ! ! Author: ! ! 01/10/89 - Kevin Handy ! ! Modification history: ! ! 03/30/93 - Kevin Handy ! Clean up (Check) ! ! 04/15/95 - Kevin Handy ! (V3.6) ! Update to V3.6 coding standards ! ! 08/19/98 - Kevin Handy ! (V3.6a Calico) ! Update to V3.6a coding standards !-- %PAGE OPTION SIZE = (INTEGER LONG, REAL GFLOAT) ! ! Include files ! %INCLUDE "FUNC_INCLUDE:FUNCTION.HB" MAP (SCOPE) SCOPE_STRUCT SCOPE %INCLUDE "SOURCE:[GL.OPEN]GL_YYYY_PP.HB" MAP (GL_YYYY_PP) GL_YYYY_PP_CDD GL_YYYY_PP 100 LINPUT "GL Period to reverse (YYYY_PP)"; YYYY_PP$ IF INSTR(1%, YYYY_PP$, "_") = 0% THEN PRINT "Missing underscore!" GOTO 32767 END IF LINPUT "Batch number to reverse (000000)"; BATCH_NO$ BATCH_NO$ = BATCH_NO$ + SPACE$(6% - LEN(BATCH_NO$)) 110 !====================================================================== ! GL_YYYY_PP file (open read/write) !====================================================================== GL_YYYY_PP.CH% = 10% GL_YYYY_PP.DEV$ = "" GL_YYYY_PP.NAME$ = GL_YYYY_PP.DEV$ + "GL_" + YYYY_PP$ + ".LED" WHEN ERROR IN OPEN GL_YYYY_PP.NAME$ FOR INPUT AS FILE GL_YYYY_PP.CH%, & ORGANIZATION INDEXED FIXED, & MAP GL_YYYY_PP, & PRIMARY KEY & ( & GL_YYYY_PP::ACCT, & GL_YYYY_PP::TRANDAT & ) DUPLICATES, & ALTERNATE KEY & ( & GL_YYYY_PP::SUBACC, & GL_YYYY_PP::OPERATION, & GL_YYYY_PP::ACCT & ) DUPLICATES CHANGES, & ALTERNATE KEY & ( & GL_YYYY_PP::XREFNO, & GL_YYYY_PP::ACCT & ) DUPLICATES CHANGES, & ALTERNATE KEY & ( & GL_YYYY_PP::CKNO, & GL_YYYY_PP::ACCT & ) DUPLICATES CHANGES, & ALTERNATE KEY & GL_YYYY_PP::BTHNUM & DUPLICATES CHANGES, & ACCESS MODIFY, ALLOW NONE USE PRINT "Unable to open period file" CONTINUE 32767 END WHEN 200 ! ! Search for first item with that batch number ! WHEN ERROR IN FIND #GL_YYYY_PP.CH%, KEY #4% EQ BATCH_NO$ USE PRINT "No such batch!" CONTINUE 32767 END WHEN 250 ! ! Process one record ! WHEN ERROR IN GET #GL_YYYY_PP.CH% USE CONTINUE 300 IF ERR = 11% CONTINUE HelpError END WHEN 260 IF GL_YYYY_PP::BTHNUM == BATCH_NO$ THEN GL_YYYY_PP::AMOUNT = -GL_YYYY_PP::AMOUNT UPDATE #GL_YYYY_PP.CH% PRINT "."; GOTO 250 END IF 300 ! ! Done ! CLOSE #GL_YYYY_PP.CH% GOTO 32767 HelpError: PRINT "ERROR"; ERR; " AT LINE"; ERL; 32767 END
28,443
https://github.com/CmdrMoozy/pwm/blob/master/src/tests/crypto/padding.rs
Github Open Source
Open Source
Apache-2.0
2,018
pwm
CmdrMoozy
Rust
Code
141
342
// Copyright 2015 Axel Rasmussen // // 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. use crate::crypto::padding::*; use crate::tests::random_secret; use bdrck::crypto::secret::Secret; #[test] fn test_padding_round_trip() { crate::init().unwrap(); let mut data = random_secret(123); let original_data = data.try_clone().unwrap(); pad(&mut data).unwrap(); assert!(data.len() > original_data.len()); unpad(&mut data).unwrap(); unsafe { assert_eq!(original_data.as_slice(), data.as_slice()); } } #[test] fn test_unpadding_invalid_size() { crate::init().unwrap(); let mut data = Secret::new(); assert!(unpad(&mut data).is_err()); }
8,812
https://github.com/Panda-Programming-Language/Panda/blob/master/panda-framework/src/main/java/panda/interpreter/parser/expression/ExpressionSubparser.java
Github Open Source
Open Source
Apache-2.0
2,019
Panda
Panda-Programming-Language
Java
Code
290
622
/* * Copyright (c) 2021 dzikoysk * * 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 panda.interpreter.parser.expression; import org.jetbrains.annotations.NotNull; import panda.interpreter.parser.Context; import panda.interpreter.parser.Parser; /** * Subparsers is extension parser used by the {@link ExpressionSubparser} */ public interface ExpressionSubparser extends Parser, Comparable<ExpressionSubparser> { /** * Creates worker of the current subparser * * @return the worker instance * @param context the context to use by the worker */ ExpressionSubparserWorker createWorker(Context<?> context); /** * Get minimal required length of source to use the subparser. * Used by {@link ExpressionParser} to improve performance. * * @return the minimal required length of source */ default int minimalRequiredLengthOfSource() { return 1; } /** * Get type of the subparser * * @return type of subparser * * @see ExpressionSubparserType */ default ExpressionSubparserType type() { return ExpressionSubparserType.MODERATE; } /** * Get category of the subparser * * @return the category * * @see ExpressionCategory */ default ExpressionCategory category() { return ExpressionCategory.DEFAULT; } /** * Get priority of the subparser. Subparsers are called ascending. * * @return the priority, by default 1.0 */ default double priority() { return 1.0; } @Override default int compareTo(@NotNull ExpressionSubparser to) { int result = Integer.compare(type().getPriority(), to.type().getPriority()); if (result != 0) { return result; } return Double.compare(priority(), to.priority()); } }
22,082
https://github.com/whampson/gta3-cargen-editor/blob/master/Gta3CarGenEditor/Models/SaveDataFileAndroid.cs
Github Open Source
Open Source
MIT
2,021
gta3-cargen-editor
whampson
C#
Code
191
903
using System.IO; using System.Text; namespace WHampson.Gta3CarGenEditor.Models { /// <summary> /// Represents a Grand Theft Auto III save data file for the Android mobile platform. /// </summary> public class SaveDataFileAndroid : SaveDataFile { private const int SizeOfSimpleVars = 0xB0; public SaveDataFileAndroid() : base(GamePlatform.Android) { m_simpleVars.Data = new byte[SizeOfSimpleVars]; } protected override long DeserializeObject(Stream stream) { long start = stream.Position; using (BinaryReader r = new BinaryReader(stream, Encoding.Default, true)) { ReadBigDataBlock(stream, m_simpleVars, m_scripts); ReadBigDataBlock(stream, m_playerPeds); ReadBigDataBlock(stream, m_garages); ReadBigDataBlock(stream, m_vehicles); ReadBigDataBlock(stream, m_objects); ReadBigDataBlock(stream, m_pathFind); ReadBigDataBlock(stream, m_cranes); ReadBigDataBlock(stream, m_pickups); ReadBigDataBlock(stream, m_phoneInfo); ReadBigDataBlock(stream, m_restarts); ReadBigDataBlock(stream, m_radar); ReadBigDataBlock(stream, m_zones); ReadBigDataBlock(stream, m_gangs); ReadBigDataBlock(stream, m_carGenerators); ReadBigDataBlock(stream, m_particles); ReadBigDataBlock(stream, m_audioScriptObjects); ReadBigDataBlock(stream, m_playerInfo); ReadBigDataBlock(stream, m_stats); ReadBigDataBlock(stream, m_streaming); ReadBigDataBlock(stream, m_pedTypes); ReadPadding(stream); r.ReadInt32(); // Checksum (ignored) } DeserializeDataBlocks(); return stream.Position - start; } protected override long SerializeObject(Stream stream) { SerializeDataBlocks(); long start = stream.Position; using (BinaryWriter w = new BinaryWriter(stream, Encoding.Default, true)) { WriteBigDataBlock(stream, m_simpleVars, m_scripts); WriteBigDataBlock(stream, m_playerPeds); WriteBigDataBlock(stream, m_garages); WriteBigDataBlock(stream, m_vehicles); WriteBigDataBlock(stream, m_objects); WriteBigDataBlock(stream, m_pathFind); WriteBigDataBlock(stream, m_cranes); WriteBigDataBlock(stream, m_pickups); WriteBigDataBlock(stream, m_phoneInfo); WriteBigDataBlock(stream, m_restarts); WriteBigDataBlock(stream, m_radar); WriteBigDataBlock(stream, m_zones); WriteBigDataBlock(stream, m_gangs); WriteBigDataBlock(stream, m_carGenerators); WriteBigDataBlock(stream, m_particles); WriteBigDataBlock(stream, m_audioScriptObjects); WriteBigDataBlock(stream, m_playerInfo); WriteBigDataBlock(stream, m_stats); WriteBigDataBlock(stream, m_streaming); WriteBigDataBlock(stream, m_pedTypes); WritePadding(stream); w.Write(GetChecksum(stream)); } return stream.Position - start; } } }
12,843
https://github.com/wahoostik/chatroom/blob/master/src/components/Chatroom/styles.scss
Github Open Source
Open Source
MIT
null
chatroom
wahoostik
SCSS
Code
24
88
@use 'src/styles/vars' as v; .chatroom { width: 90%; margin: 0 auto; max-width: 600px; height: 100vh; background-color: v.$color-alt; display: flex; flex-direction: column; justify-content: space-between; }
10,166
https://github.com/WillBishop/Tweaks-for-Reddit/blob/master/shared/In-App Purchases/TFRProduct.swift
Github Open Source
Open Source
MIT
null
Tweaks-for-Reddit
WillBishop
Swift
Code
37
89
// // TFRProduct.swift // Tweaks for Reddit // // Created by Michael Rippe on 5/21/21. // Copyright © 2021 Michael Rippe. All rights reserved. // import Foundation enum TFRProduct: String, CaseIterable { case liveCommentPreviews = "livecommentpreview" }
14,476
https://github.com/yacon/koala-framework/blob/master/Kwf/Test/ResultLogger.php
Github Open Source
Open Source
BSD-2-Clause
2,019
koala-framework
yacon
PHP
Code
40
126
<?php class Kwf_Test_ResultLogger extends PHPUnit_TextUI_ResultPrinter { protected $_log = ''; public function __construct($verbose = FALSE) { parent::__construct(); } protected function writeProgress($progress) { //empty } public function write($buffer) { $this->_log .= $buffer; } public function getContent() { return $this->_log; } }
13,163
https://github.com/frauber84/mario64missingstars/blob/master/80405000-behav_cmd_12_flexible_collision.s
Github Open Source
Open Source
MIT
null
mario64missingstars
frauber84
GAS
Code
490
1,101
; the collision distance wasn't inplemented in the version used in this hack ;# Behavior command 12 ;12 00 00 [00] [xx xx xx xx] ; | \-->segmented address for beggining of collision pointer list ; \--> 1 = process collision distance. 0 = specify it manually by '0e 43' .ORG 0x80400100 ADDIU SP, SP, 0xFFE0 SW RA, 0x0014 (SP) LUI T6, 0x8036 LW T6, 0x1164 (T6) # Pointer to current behavior command LW S0, 0x0000 (T6) ANDI S0, S0, 0x00FF # get arg byte. LW A0, 0x0004 (T6) # A0 = segmented base address for ROM pointer list ADDIU T7, R0, 0x0001 # initializes for { i = 1; i < 100; i++ } loop ADDIU AT, R0, 0x0100 Loop: # to discover what Model ID the object is using SLL T8, T7, 0x2 # i * 4 LUI T4, 0x8033 LW T4, 0xDDC4 (T4) # T4 = Pointer to beggining of Graphic Pointer list (generated from 0x22 command values) ADDU T6, T4, T8 # T6 = T4 + (i * 4) LW T4, 0x0000 (T6) # T4 = value from T6 LUI T9, 0x8036 LW T9, 0x1160 (T9) # Pointer for RAM Object LW T9, 0x0014 (T9) # Load value from 0x14 = Graphic Pointer BEQ T4, T9, LoadCollision # if ( Obj->0x14 == Graphic Pointer List->(i*4) ) NOP BNE T7, AT, Loop ADDIU T7, T7, 0x0001 # i++; BEQ R0, R0, End NOP LoadCollision: SLL T9, T7, 0x1 # i * 2 ADDU T8, T8, T9 # T8 = (i * 4) + (i *2) JAL 0x80277F50 # segmented_to_virtual (convert A0 [already set] into RAM pointer) SW T8, 0x001C (SP) # store T8 in stack because the function above uses it LW T8, 0x001C (SP) # restore ADDU T6, V0, T8 # V0 = virtual memory value of A0. Adds (i * 4 + i * 2) to get the right collision pointer. LW A0, 0x0000 (T6) # A0 = load segmented collision pointer and convert it JAL 0x80277F50 SW T6, 0x001C (SP) # store LUI T8, 0x8036 LW T8, 0x1160 (T8) # Get RAM obect pointer again SW V0, 0x0218 (T8) # store final virtual memory collision pointer into offset 0x218. LW T6, 0x001C (SP) # restore pointer to collision LW A3, 0x0004 (T6) # read collision distance LUI T9, 0xFFFF ORI T9, T9, 0x0000 AND A3, A3, T9 # clear 4 last bytes SRL A3, A3, 0x16 # >> 16 BEQ A3, R0, End # if arg3 == 0 skip (default value will be loaded); NOP BEQ S0, R0, End # if process_bytes == 0 skip; NOP LoadCollisionDistance: MTC1 A3, F4 NOP CVT.S.W f6, f4 # convert signed int to float SWC1 F6, 0x0194 (T8) # store float into obj->0x194 End: LUI T9, 0x8036 LW T9, 0x1164 (T9) ADDIU T0, T9, 0x0008 # current behavior position + 8 LUI AT, 0x8036 SW T0, 0x1164 (AT) LW RA, 0x0014 (SP) JR RA ADDIU SP, SP, 0x0020
8,090
https://github.com/Gundlack-C-C/vdd-prio/blob/master/vdd-prio/src/app/prio/table/table.component.ts
Github Open Source
Open Source
MIT
null
vdd-prio
Gundlack-C-C
TypeScript
Code
103
320
import { Component, Input, OnInit } from '@angular/core'; import { Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-table-prio', templateUrl: './table.component.html', styleUrls: ['./table.component.css'] }) export class TableComponent implements OnInit { @Input() data: { heading: string[] | undefined, rows: string[][] } = { heading: [], rows: [] } @Output() dataChangedEvent= new EventEmitter<any>(); get heading(): string[] { return this.data ? (this.data.heading ? this.data.heading : []) : []; } get rows(): string[][] { return this.data ? this.data.rows : [] } constructor() { } ngOnInit() { } valueChanged(event: any, row: number, col: number) { if(event && event.target) { var val = event.target.value; this.data.rows[row][col]=val; console.log(event.currentTarget.value); this.dataChangedEvent.emit(this.data) } } }
10,682
https://github.com/devhl-labs/CocApi/blob/master/src/CocApi/Model/ClanWarAttack.cs
Github Open Source
Open Source
MIT
2,020
CocApi
devhl-labs
C#
Code
526
1,619
/* * Clash of Clans API * * Check out <a href=\"https://developer.clashofclans.com/#/getting-started\" target=\"_parent\">Getting Started</a> for instructions and links to other resources. Clash of Clans API uses <a href=\"https://jwt.io/\" target=\"_blank\">JSON Web Tokens</a> for authorizing the requests. Tokens are created by developers on <a href=\"https://developer.clashofclans.com/#/account\" target=\"_parent\">My Account</a> page and must be passed in every API request in Authorization HTTP header using Bearer authentication scheme. Correct Authorization header looks like this: \"Authorization: Bearer API_TOKEN\". * * The version of the OpenAPI document: v1 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = CocApi.Client.OpenAPIDateConverter; namespace CocApi.Model { /// <summary> /// ClanWarAttack /// </summary> [DataContract(Name = "ClanWarAttack")] public partial class ClanWarAttack : IEquatable<ClanWarAttack>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ClanWarAttack" /> class. /// </summary> /// <param name="order">order.</param> /// <param name="attackerTag">attackerTag.</param> /// <param name="defenderTag">defenderTag.</param> /// <param name="stars">stars.</param> /// <param name="destructionPercentage">destructionPercentage.</param> public ClanWarAttack(int order, string attackerTag, string defenderTag, int stars, int destructionPercentage) { Order = order; AttackerTag = attackerTag; DefenderTag = defenderTag; Stars = stars; DestructionPercentage = destructionPercentage; } /// <summary> /// Gets or Sets Order /// </summary> [DataMember(Name = "order", EmitDefaultValue = false)] public int Order { get; private set; } /// <summary> /// Gets or Sets AttackerTag /// </summary> [DataMember(Name = "attackerTag", EmitDefaultValue = false)] public string AttackerTag { get; private set; } /// <summary> /// Gets or Sets DefenderTag /// </summary> [DataMember(Name = "defenderTag", EmitDefaultValue = false)] public string DefenderTag { get; private set; } /// <summary> /// Gets or Sets Stars /// </summary> [DataMember(Name = "stars", EmitDefaultValue = false)] public int Stars { get; private set; } /// <summary> /// Gets or Sets DestructionPercentage /// </summary> [DataMember(Name = "destructionPercentage", EmitDefaultValue = false)] public int DestructionPercentage { get; private set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ClanWarAttack {\n"); sb.Append(" Order: ").Append(Order).Append('\n'); sb.Append(" AttackerTag: ").Append(AttackerTag).Append('\n'); sb.Append(" DefenderTag: ").Append(DefenderTag).Append('\n'); sb.Append(" Stars: ").Append(Stars).Append('\n'); sb.Append(" DestructionPercentage: ").Append(DestructionPercentage).Append('\n'); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson(Newtonsoft.Json.JsonSerializerSettings? jsonSerializerSettings = null) { return Newtonsoft.Json.JsonConvert.SerializeObject(this, jsonSerializerSettings ?? CocApi.Client.ClientUtils.JsonSerializerSettings); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object? input) { return Equals(input as ClanWarAttack); } /// <summary> /// Returns true if ClanWarAttack instances are equal /// </summary> /// <param name="input">Instance of ClanWarAttack to be compared</param> /// <returns>Boolean</returns> public bool Equals(ClanWarAttack? input) { if (input == null) return false; return ( Order == input.Order || Order.Equals(input.Order) ) && ( AttackerTag == input.AttackerTag || (AttackerTag != null && AttackerTag.Equals(input.AttackerTag)) ) && ( DefenderTag == input.DefenderTag || (DefenderTag != null && DefenderTag.Equals(input.DefenderTag)) ) && ( Stars == input.Stars || Stars.Equals(input.Stars) ) && ( DestructionPercentage == input.DestructionPercentage || DestructionPercentage.Equals(input.DestructionPercentage) ); } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
612
https://github.com/kette-io/nft-asset-registry-backend/blob/master/test/cryptofunctions.test.js
Github Open Source
Open Source
MIT
2,019
nft-asset-registry-backend
kette-io
JavaScript
Code
70
242
const expect = require('chai').expect; const cryptoFunctions = require('../modules/cryptoFunctions'); describe("cryptoFunctions", () => { it('[sign] -> should sign a message', () => { const key = cryptoFunctions.generateNewKey(); const messageToSign = { action: "register", assetType: "bike", uniqueId: "1337" } const signedMessage = cryptoFunctions.sign(JSON.stringify(messageToSign), key.privateKey); expect(signedMessage).not.to.be.null; }) it('[toPrivateKeyBuffer] -> recreate private key buffer from string', () => { const key = cryptoFunctions.generateNewKey(); const privateKeyBufferFromString = cryptoFunctions.toPrivateKeyBuffer(key.privateKeyString); expect(key.privateKey, "keys are not the same").to.be.deep.equal(privateKeyBufferFromString) }) })
50,307
https://github.com/successmarket/oroinc-platform/blob/master/src/Oro/Bundle/EntityBundle/Form/EntityField/Handler/EntityApiBaseHandler.php
Github Open Source
Open Source
MIT
2,020
oroinc-platform
successmarket
PHP
Code
222
777
<?php namespace Oro\Bundle\EntityBundle\Form\EntityField\Handler; use Doctrine\Bundle\DoctrineBundle\Registry; use Oro\Bundle\EntityBundle\Form\EntityField\Handler\Processor\EntityApiHandlerProcessor; use Symfony\Component\Form\FormInterface; use Symfony\Component\PropertyAccess\PropertyAccess; /** * Used to pre-process entity and submit form data */ class EntityApiBaseHandler { /** @var Registry */ protected $registry; /** @var EntityApiHandlerProcessor */ protected $processor; /** * @param Registry $registry * @param EntityApiHandlerProcessor $processor */ public function __construct( Registry $registry, EntityApiHandlerProcessor $processor ) { $this->registry = $registry; $this->processor = $processor; } /** * Process form * * @param $entity * @param FormInterface $form * @param array $data * @param string $method * * @return array changset */ public function process($entity, FormInterface $form, $data, $method) { $this->processor->preProcess($entity); $form->setData($entity); if (in_array($method, ['POST', 'PUT', 'PATCH'], true)) { $form->submit($data, 'PATCH' !== $method); if ($form->isValid()) { $this->processor->beforeProcess($entity); $this->onSuccess($entity); $changeSet = $this->initChangeSet($entity, $data); $changeSet = $this->updateChangeSet($changeSet, $this->processor->afterProcess($entity)); return $changeSet; } else { $this->processor->invalidateProcess($entity); } } return []; } /** * @param $entity * * @return array */ protected function initChangeSet($entity, $data) { $accessor = PropertyAccess::createPropertyAccessor(); $response = [ 'fields' => $data ]; if ($accessor->isReadable($entity, 'updatedAt')) { $response['fields']['updatedAt'] = $accessor->getValue($entity, 'updatedAt'); } return $response; } /** * @param $changeSet * @param $update * * @return array */ protected function updateChangeSet($changeSet, $update) { if (is_array($update)) { $result = array_replace_recursive($changeSet, $update); } else { $result = $changeSet; } return $result; } /** * "Success" form handler * * @param $entity */ protected function onSuccess($entity) { $this->registry->getManager()->persist($entity); $this->registry->getManager()->flush(); } }
765
https://github.com/JasonWyx/ktwgEngine/blob/master/source/ktwgEngine/sat.cpp
Github Open Source
Open Source
MIT
null
ktwgEngine
JasonWyx
C++
Code
1,035
2,839
#include "sat.h" bool SAT::CheckFaceSeparation(FaceQuery& outA, FaceQuery& outB, const Transform& transformA, const Transform& transformB, const Vec3& extentsA, const Vec3& extentsB, const Matrix3& rotMatA, const Matrix3& rotMatB, const Matrix3& transform, const Matrix3& absoluteTransform) { Vec3 t = MultiplyT(rotMatA, transformB.GetPosition() - transformA.GetPosition()); float s = 0.0f; float tmo = Dot(absoluteTransform.GetColumn(0), extentsB); // Check x axis of Box A, normal to face is also the x axis s = abs(t.x_) - (extentsA.x_ + Dot(absoluteTransform.GetColumn(0), extentsB)); if (CheckSeparation(outA, s, rotMatA.GetRow(0), 0)) return false; tmo = Dot(absoluteTransform.GetColumn(1), extentsB); // Check y axis of Box A, normal to face is also the y axis s = abs(t.y_) - (extentsA.y_ + Dot(absoluteTransform.GetColumn(1), extentsB)); if (CheckSeparation(outA, s, rotMatA.GetRow(1), 1)) return false; tmo = Dot(absoluteTransform.GetColumn(2), extentsB); // Check z axis of Box A, normal to face is also the z axis s = abs(t.z_) - (extentsA.z_ + Dot(absoluteTransform.GetColumn(2), extentsB)); if (CheckSeparation(outA, s, rotMatA.GetRow(2), 2)) return false; // Check x axis of Box B, normal to face is also the x axis s = abs(Dot(t, transform.GetRow(0))) - (extentsB.x_ + Dot(absoluteTransform.GetRow(0), extentsA)); if (CheckSeparation(outB, s, rotMatB.GetRow(0), 3)) return false; // Check y axis of Box B, normal to face is also the y axis s = abs(Dot(t, transform.GetRow(1))) - (extentsB.y_ + Dot(absoluteTransform.GetRow(1), extentsA)); if (CheckSeparation(outB, s, rotMatB.GetRow(1), 4)) return false; // Check z axis of Box B, normal to face is also the z axis s = abs(Dot(t, transform.GetRow(2))) - (extentsB.z_ + Dot(absoluteTransform.GetRow(2), extentsA)); if (CheckSeparation(outB, s, rotMatB.GetRow(2), 5)) return false; // Pass all face axis test return true; } bool SAT::CheckEdgeSeparation(EdgeQuery& out, const Transform& transformA, const Transform& transformB, const Vec3& extentsA, const Vec3& extentsB, const Matrix3& rotMatA, const Matrix3& rotMatB, const Matrix3& transform, const Matrix3& absoluteTransform) { // Compute vector t from center A to center B in A's space Vec3 t = MultiplyT(rotMatA, transformB.GetPosition() - transformA.GetPosition()); float s = 0.0f; // In A's space, A's local axis is (1, 0, 0), (0, 1, 0) and (0, 0, 1) // In A's space, B's axis is (A^T * B)'s row 0, row 1 and row 2 ( row major ) // Edge case : Cross A.x & B.x // l = Cross(A.x, B.x) = (1, 0, 0) x | (A^T * B).row(0) | = (0, -m[0][2], m[0][1]) // | A^T * B | = absoluteTransform // s = Dot(t, l) - Dot(extentA, l) - Dot(absTransform * extentB, l) Vec3 l = Vec3{ 0.0f, -transform.m_[0][2], transform.m_[0][1] }; Vec3 absL = Absolute(l); float projA = Dot(extentsA, absL); float projB = Dot(extentsB, absL); s = abs(Dot(t, l)) - (projA + projB); if (CheckSeparation(out, s, l, 6)) return false; // Edge case : Cross A.x & B.y // l = Cross(A.x, B.y) = (1, 0, 0) x | (A^T * B).row(1) | = (0, -m[1][2], m[1][1]) l = Vec3{ 0.0f, -transform.m_[1][2], transform.m_[1][1] }; absL = Absolute(l); projA = Dot(extentsA, absL); projB = Dot(extentsB, absL); s = abs(Dot(t, l)) - (projA + projB); if (CheckSeparation(out, s, l, 7)) return false; // Edge case : Cross A.x & B.z // l = Cross(A.x, B.z) = (1, 0, 0) x | (A^T * B).row(2) | = (0, -m[2][2], m[2][1]) l = Vec3{ 0.0f, -transform.m_[2][2], transform.m_[2][1] }; absL = Absolute(l); projA = Dot(extentsA, absL); projB = Dot(extentsB, absL); s = abs(Dot(t, l)) - (projA + projB); if (CheckSeparation(out, s, l, 8)) return false; // Edge case : Cross A.y & B.x // l = Cross(A.y, B.x) = (0, 1, 0) x | (A^T * B).row(0) | = (m[0][2], 0, -m[0][0]) l = Vec3{ transform.m_[0][2], 0.0f, -transform.m_[0][0] }; absL = Absolute(l); projA = Dot(extentsA, absL); projB = Dot(extentsB, absL); s = abs(Dot(t, l)) - (projA + projB); if (CheckSeparation(out, s, l, 9)) return false; // Edge case : Cross A.y & B.y // l = Cross(A.y, B.y) = (0, 1, 0) x | (A^T * B).row(1) | = (m[1][2], 0, -m[1][0]) l = Vec3{ transform.m_[1][2], 0.0f, -transform.m_[1][0] }; absL = Absolute(l); projA = Dot(extentsA, absL); projB = Dot(extentsB, absL); s = abs(Dot(t, l)) - (projA + projB); if (CheckSeparation(out, s, l, 10)) return false; // Edge case : Cross A.y & B.z // l = Cross(A.y, B.z) = (0, 1, 0) x | (A^T * B).row(2) | = (m[2][2], 0, -Column[2][0]) l = Vec3{ transform.m_[2][2], 0.0f, -transform.m_[2][0] }; absL = Absolute(l); projA = Dot(extentsA, absL); projB = Dot(extentsB, absL); s = abs(Dot(t, l)) - (projA + projB); if (CheckSeparation(out, s, l, 11)) return false; // Edge case : Cross A.z & B.x // l = Cross(A.z, B.x) = (0, 0, 1) x | (A^T * B).row(0) | = (-m[0][1], Column[0][0], 0.0f) l = Vec3{ -transform.m_[0][1], transform.m_[0][0], 0.0f }; absL = Absolute(l); projA = Dot(extentsA, absL); projB = Dot(extentsB, absL); s = abs(Dot(t, l)) - (projA + projB); if (CheckSeparation(out, s, l, 12)) return false; // Edge case : Cross A.z & B.y // l = Cross(A.z, B.x) = (0, 0, 1) x | (A^T * B).row(1) | = (-m[1][1], m[1][0], 0.0f) l = Vec3{ -transform.m_[1][1], transform.m_[1][0], 0.0f }; absL = Absolute(l); projA = Dot(extentsA, absL); projB = Dot(extentsB, absL); s = abs(Dot(t, l)) - (projA + projB); if (CheckSeparation(out, s, l, 13)) return false; // Edge case : Cross A.z & B.z // l = Cross(A.z, B.x) = (0, 0, 1) x | (A^T * B).row(2) | = (-m[2][1], Column[2][0], 0.0f) l = Vec3{ -transform.m_[2][1], transform.m_[2][0], 0.0f }; absL = Absolute(l); projA = Dot(extentsA, absL); projB = Dot(extentsB, absL); s = abs(Dot(t, l)) - (projA + projB); if (CheckSeparation(out, s, l, 14)) return false; return true; } bool SAT::CheckSeparation(FaceQuery& out, float separation, const Vec3& normal, unsigned index) { // If separation distance is more than 0, means SAT detect that the convex shapes are not colliding if (separation > 0.0f) return true; // Update the separation distance to get the Minimum Translation Vector if (separation > out.maxSeparation_) { out.maxSeparation_ = separation; out.normal_ = normal; out.index_ = index; } return false; } bool SAT::CheckSeparation(EdgeQuery& out, float separation, const Vec3& normal, unsigned index) { // If separation distance is more than 0, means SAT detect that the convex shapes are not colliding if (separation > 0.0f) return true; // Update the separation distance to get the Minimum Translation Vector if (separation > out.maxSeparation_) { out.maxSeparation_ = separation; out.normal_ = normal; out.index_ = index; } return false; }
15,110
https://github.com/diogoalves/chat/blob/master/frontend/src/components/Input.js
Github Open Source
Open Source
MIT
null
chat
diogoalves
JavaScript
Code
147
440
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { withStyles } from '@material-ui/core/styles'; import Paper from '@material-ui/core/Paper'; import TextField from '@material-ui/core/TextField'; import actions from '../actions'; const styles = theme => ({ root: { ...theme.mixins.gutters(), paddingTop: theme.spacing.unit * 2, paddingBottom: theme.spacing.unit * 2, position: 'absolute', bottom: 0, width: '100%' } }); class Input extends Component { state = { value: '' }; handleChange = event => { this.setState({ value: event.target.value }); }; handleSubmit = event => { event.preventDefault(); const { user } = this.props; const value = this.state.value.trim(); if (value) { this.props.dispatch(actions.addMsg({ author: user, content: value })); } this.setState(() => ({ value: '' })); }; render() { return ( <Paper className={this.props.classes.root} elevation={1}> <form onSubmit={this.handleSubmit}> <TextField autoFocus placeholder="Write a message here" fullWidth margin="normal" value={this.state.value} onChange={this.handleChange} /> </form> </Paper> ); } } const mapStateToProps = state => ({ user: state.user }); export default connect(mapStateToProps)(withStyles(styles)(Input));
34,710
https://github.com/zgjslc/Film-Recovery-master1/blob/master/utils/tv_losses.py
Github Open Source
Open Source
Apache-2.0
2,022
Film-Recovery-master1
zgjslc
Python
Code
47
285
import torch import torch.nn as nn from torch.autograd import Variable class TVLoss(nn.Module): def __init__(self,TVLoss_weight=0.2): super(TVLoss,self).__init__() self.TVLoss_weight = TVLoss_weight def forward(self,x): batch_size = x.size()[0] h_x = x.size()[2] w_x = x.size()[3] count_h = self._tensor_size(x[:,:,1:,:]) count_w = self._tensor_size(x[:,:,:,1:]) h_tv = torch.pow((x[:,:,1:,:]-x[:,:,:h_x-1,:]),2).sum() w_tv = torch.pow((x[:,:,:,1:]-x[:,:,:,:w_x-1]),2).sum() return self.TVLoss_weight*2*(h_tv/count_h+w_tv/count_w)/batch_size def _tensor_size(self,t): return t.size()[1]*t.size()[2]*t.size()[3]
40,375
https://github.com/MuhammadArifMahendra/projek_uts/blob/master/system/app/Http/Controllers/HomeController.php
Github Open Source
Open Source
MIT
2,020
projek_uts
MuhammadArifMahendra
PHP
Code
23
89
<?php namespace App\Http\Controllers; class HomeController extends Controller{ function Showtemplate(){ return view('template.base'); } function Showblog(){ return view('template.blog'); } function Showadmin(){ return view('template.Admin.admin'); } }
47,649
https://github.com/nkemjikaobi/capital-ticketing/blob/master/app/Http/Controllers/FootBallController.php
Github Open Source
Open Source
MIT
2,021
capital-ticketing
nkemjikaobi
PHP
Code
432
1,683
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\FootBallTicket; use App\Models\FootBallPay; use Illuminate\Support\Facades\DB; class FootBallController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function buy_tickets_football(){ //Get FootBall Tickets $tickets = FootBallTicket::paginate(6); return view("dashboard.football.buy_tickets_football",compact('tickets')); } public function buy_tickets_football_fixture($id){ $fixture_details = FootBallTicket::findorfail($id); if($fixture_details->time_left < 1){ return redirect('/buy_tickets/football')->with('error', 'Error: The Ticket has expired'); } return view('dashboard.football.buy_tickets_football_fixture',compact('fixture_details')); } public function buy_tickets_football_pay(Request $request){ $email = auth()->user()->email; FootBallPay::create([ 'home_team' => request('home_team'), 'away_team' => request('away_team'), 'purchase_number' => request('purchase_number'), 'ticket_price' => request('ticket_price'), 'tickets_available' => request('tickets_available'), 'expected_profit' => request('expected_profit'), 'country' => request('country'), 'competition' => request('competition'), 'fixture_date' => request('fixture_date'), 'fixture_time' => request('fixture_time'), 'time_left' => request('time_left'), 'email' => $email ]); $ticket_id = request('ticket_id'); $pay = FootBallPay::where('email', '=', $email)->orderBy('id', 'DESC')->take(1)->get(); return view("dashboard.football.buy_tickets_football_pay",compact('pay','ticket_id')); } public function buy_tickets_football_pay_process(Request $request){ //Check that balance is sufficient if(request('final_pay') <= auth()->user()->portfolio->balance ){ //Check that purchase number does not exceed number of tickets available if(request('purchase_number') <= request('tickets_available')){ //Update the transaction status and final pay $football_pay = DB::table('foot_ball_pays') ->where('email', '=', auth()->user()->email) ->orderBy('id', 'DESC') ->take(1) ->update([ 'final_pay' => request('final_pay'), 'transaction_status' => 1, 'tickets_available' => request('tickets_available') - request('purchase_number'), 'roi' => request('final_pay') ]); if($football_pay){ //Update user balance $portfolio = DB::table('portfolios') ->where('user_id', '=', auth()->user()->id) ->update([ 'balance' => auth()->user()->portfolio->balance - request('final_pay') ]); if($portfolio){ //Update Tickets Available $ticket = DB::table('foot_ball_tickets') ->where('id' , '=', request('ticket_id')) ->update([ 'tickets_available' => request('tickets_available') - request('purchase_number') ]); if($ticket){ //Delete redundant rows from FootBall Pays table DB::table('foot_ball_pays') ->where('transaction_status', '=', 0) ->delete(); } } return redirect("/view_tickets")->with('success','Tickets bought successfully'); } else{ return redirect("/view_tickets")->with('error','An error occurred..Try again later'); } } } else{ return redirect("/view_tickets")->with('error','Insufficient Funds'); } } public function calculate_football_roi(){ //Get all tickets that are active $tickets = DB::table('foot_ball_pays') ->where('transaction_status', '=', 1) ->get(); //Initialize arrays $id = []; $profit = []; $roi = []; $amount_paid = []; //Get each of the array fields foreach ($tickets as $ticket){ $id[] = $ticket->id; $profit[] = $ticket->expected_profit; $roi[] = $ticket->roi; $amount_paid[] = $ticket->final_pay; } //Convert profits to percentage $profit_percentage = []; for($i = 0; $i < count($tickets); $i++){ $profit_percentage[] = $profit[$i] / 100; } //Calculate the increment $max_increment = []; for($i = 0; $i < count($tickets); $i++){ $max_increment[] = $profit_percentage[$i] * $amount_paid[$i]; } //Calculate the maximum amount it gets to $max_amount = []; for($i = 0; $i < count($tickets); $i++){ $max_amount[] = $max_increment[$i] + $amount_paid[$i]; } //Get the random roi increments $new_roi = []; for($i = 0; $i < count($tickets); $i++){ $new_roi[] = (rand(1, 100)/100) + $roi[$i]; } //Do the increments accordingly for($i = 0; $i < count($tickets); $i++){ //Actually update the database with the new roi DB::table('foot_ball_pays') ->where('id', '=', $id[$i]) ->update([ 'roi' => $new_roi[$i] ]); } } }
2,892
https://github.com/thaodv/bank-wallet-ios/blob/master/BankWallet/BankWallet/Theme/TransactionsFilterTheme.swift
Github Open Source
Open Source
MIT
null
bank-wallet-ios
thaodv
Swift
Code
77
199
import UIKit class TransactionsFilterTheme { static let cornerRadius: CGFloat = 14 static let borderColor = UIColor.cryptoYellow static let borderWidth:CGFloat = 1 static let nameFont = UIFont.cryptoCaption2 static let nameVerticalMargin: CGFloat = 8 static let nameHorizontalMargin: CGFloat = 24 static let nameMinWidth: CGFloat = 87 static let spacing: CGFloat = 8 static let deselectedNameColor = UIColor.cryptoYellow static let selectedNameColor = UIColor.black static let deselectedBackgroundColor = UIColor.clear static let selectedBackgroundColor = UIColor.cryptoYellow static let filterHeaderHeight: CGFloat = 44 }
46,335
https://github.com/CuBoulder/d8_composer_base/blob/master/web/modules/contrib/purge/tests/src/Unit/Logger/LoggerChannelPartTest.php
Github Open Source
Open Source
MIT, GPL-2.0-only
2,019
d8_composer_base
CuBoulder
PHP
Code
618
2,274
<?php namespace Drupal\Tests\purge\Unit\Logger; use Drupal\Core\Logger\RfcLogLevel; use Drupal\purge\Logger\LoggerChannelPart; use Drupal\Tests\UnitTestCase; /** * @coversDefaultClass \Drupal\purge\Logger\LoggerChannelPart * @group purge */ class LoggerChannelPartTest extends UnitTestCase { /** * The mocked logger channel. * * @var \PHPUnit_Framework_MockObject_MockObject|\Psr\Log\LoggerInterface */ protected $loggerChannelPurge; /** * {@inheritdoc} */ protected function setUp() { $this->loggerChannelPurge = $this->getMock('\Psr\Log\LoggerInterface'); } /** * Helper to all severity methods. */ private function helperForSeverityMethods($id, array $grants, $output, $severity) { $occurrence = is_null($output) ? $this->never() : $this->once(); $this->loggerChannelPurge ->expects($occurrence) ->method('log') ->with( $this->stringContains($severity), $this->stringContains('@purge_channel_part: @replaceme'), $this->callback(function ($subject) use ($id, $output) { return ($subject['@purge_channel_part'] === $id) && ($subject['@replaceme'] === $output); }) ); $part = new LoggerChannelPart($this->loggerChannelPurge, $id, $grants); $part->$severity('@replaceme', ['@replaceme' => $output]); } /** * @covers ::__construct */ public function testInstance() { $part = new LoggerChannelPart($this->loggerChannelPurge, 'id', []); $this->assertInstanceOf('\Psr\Log\LoggerInterface', $part); } /** * @covers ::getGrants * * @dataProvider providerTestGetGrants() */ public function testGetGrants(array $grants) { $part = new LoggerChannelPart($this->loggerChannelPurge, 'id', $grants); $this->assertEquals(count($grants), count($part->getGrants())); $this->assertEquals($grants, $part->getGrants()); foreach ($part->getGrants() as $k => $v) { $this->assertTrue(is_int($k)); $this->assertTrue(is_int($v)); } } /** * Provides test data for testGetGrants(). */ public function providerTestGetGrants() { return [ [[]], [[RfcLogLevel::EMERGENCY]], [[RfcLogLevel::ALERT]], [[RfcLogLevel::CRITICAL]], [[RfcLogLevel::ERROR]], [[RfcLogLevel::WARNING]], [[RfcLogLevel::NOTICE]], [[RfcLogLevel::INFO]], [[RfcLogLevel::INFO, RfcLogLevel::DEBUG]], [[RfcLogLevel::DEBUG]], ]; } /** * @covers ::emergency * * @dataProvider providerTestEmergency() */ public function testEmergency($id, array $grants, $output) { $this->helperForSeverityMethods($id, $grants, $output, 'emergency'); } /** * Provides test data for testEmergency(). */ public function providerTestEmergency() { return [ ['good', [RfcLogLevel::EMERGENCY], 'bazinga!'], ['bad', [-1], NULL], ]; } /** * @covers ::alert * * @dataProvider providerTestAlert() */ public function testAlert($id, array $grants, $output) { $this->helperForSeverityMethods($id, $grants, $output, 'alert'); } /** * Provides test data for testAlert(). */ public function providerTestAlert() { return [ ['good', [RfcLogLevel::ALERT], 'bazinga!'], ['bad', [-1], NULL], ]; } /** * @covers ::critical * * @dataProvider providerTestCritical() */ public function testCritical($id, array $grants, $output) { $this->helperForSeverityMethods($id, $grants, $output, 'critical'); } /** * Provides test data for testCritical(). */ public function providerTestCritical() { return [ ['good', [RfcLogLevel::CRITICAL], 'bazinga!'], ['bad', [-1], NULL], ]; } /** * @covers ::error * * @dataProvider providerTestError() */ public function testError($id, array $grants, $output) { $this->helperForSeverityMethods($id, $grants, $output, 'error'); } /** * Provides test data for testError(). */ public function providerTestError() { return [ ['good', [RfcLogLevel::ERROR], 'bazinga!'], ['bad', [-1], NULL], ]; } /** * @covers ::warning * * @dataProvider providerTestWarning() */ public function testWarning($id, array $grants, $output) { $this->helperForSeverityMethods($id, $grants, $output, 'warning'); } /** * Provides test data for testWarning(). */ public function providerTestWarning() { return [ ['good', [RfcLogLevel::WARNING], 'bazinga!'], ['bad', [-1], NULL], ]; } /** * @covers ::notice * * @dataProvider providerTestNotice() */ public function testNotice($id, array $grants, $output) { $this->helperForSeverityMethods($id, $grants, $output, 'notice'); } /** * Provides test data for testNotice(). */ public function providerTestNotice() { return [ ['good', [RfcLogLevel::NOTICE], 'bazinga!'], ['bad', [-1], NULL], ]; } /** * @covers ::info * * @dataProvider providerTestInfo() */ public function testInfo($id, array $grants, $output) { $this->helperForSeverityMethods($id, $grants, $output, 'info'); } /** * Provides test data for testInfo(). */ public function providerTestInfo() { return [ ['good', [RfcLogLevel::INFO], 'bazinga!'], ['bad', [-1], NULL], ]; } /** * @covers ::debug * * @dataProvider providerTestDebug() */ public function testDebug($id, array $grants, $output) { $this->helperForSeverityMethods($id, $grants, $output, 'debug'); } /** * Provides test data for testDebug(). */ public function providerTestDebug() { return [ ['good', [RfcLogLevel::DEBUG], 'bazinga!'], ['bad', [-1], NULL], ]; } /** * @covers ::log * * @dataProvider providerTestLog() */ public function testLog($id, $level, $message, $output) { $this->loggerChannelPurge ->expects($this->once()) ->method('log') ->with( $this->stringContains($level), $this->stringContains('@purge_channel_part: ' . $message), $this->callback(function ($subject) use ($id, $output) { return ($subject['@purge_channel_part'] === $id) && ($subject['@replaceme'] === $output); }) ); $part = new LoggerChannelPart($this->loggerChannelPurge, $id); $part->log($level, $message, ['@replaceme' => $output]); } /** * Provides test data for testLog(). */ public function providerTestLog() { return [ ['id1', 'level1', 'message @placeholder', ['@placeholder' => 'foo']], ['id2', 'level2', 'message @placeholder', ['@placeholder' => 'bar']], ['id3', 'level3', 'message @placeholder', ['@placeholder' => 'baz']], ]; } }
41,803
https://github.com/AgustinJimenez/kingbull_web/blob/master/Modules/Reservas/Resources/views/admin/horarios/partials/index/modal-alert.blade.php
Github Open Source
Open Source
RSA-MD
null
kingbull_web
AgustinJimenez
PHP
Code
71
380
<div class="modal fade modal-danger" id="modal-alert" tabindex="-1" role="dialog" aria-labelledby="delete-confirmation-title" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">×</span> <span class="sr-only">Close</span> </button> <h4 class="modal-title text-center"> AVISO </h4> </div> <div class="modal-body text-center" id="modal-alert-body"> </div> <div class="modal-footer text-center"> <form action="{{ route('admin.reservas.horario.destroy', [0]) }}" method="POST" accept-charset="utf-8" id="form-eliminar"> <input name="_method" type="hidden" value="DELETE"> {!! csrf_field() !!} <button type="submit" class="btn btn-danger" data-dismiss="modal" id="button-eliminar"><span class="glyphicon glyphicon-trash"></span>ELIMINAR</button> <button type="button" class="btn btn-danger" data-dismiss="modal">CERRAR</button> </form> </div> </div> </div> </div>
20,863
https://github.com/Nfreewind/stromx/blob/master/stromx/runtime/impl/OutputNode.h
Github Open Source
Open Source
Apache-2.0
2,018
stromx
Nfreewind
C++
Code
212
524
/* * Copyright 2011 Matthias Fuchs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef STROMX_RUNTIME_IMPL_OUTPUTNODE_H #define STROMX_RUNTIME_IMPL_OUTPUTNODE_H #include <boost/thread/locks.hpp> #include <boost/thread/mutex.hpp> #include <set> namespace stromx { namespace runtime { class Operator; class DataContainer; namespace impl { class InputNode; class OutputNode { public: OutputNode(Operator* const op, const unsigned int outputId); unsigned int outputId() const { return m_outputId; } Operator* op() const { return m_operator; } DataContainer getOutputData(); void addConnectedInput(InputNode* const input); void removeConnectedInput(InputNode* const input); const std::set<InputNode*> & connectedInputs() const { return m_connectedInputs; } /** * Resets the counter which tracks how many inputs have received the data * of the output node. */ void reset(); private: typedef boost::lock_guard<boost::mutex> lock_t; Operator* m_operator; unsigned int m_outputId; std::set<InputNode*> m_connectedInputs; unsigned int m_servedInputs; boost::mutex m_mutex; }; } } } #endif // STROMX_RUNTIME_IMPL_OUTPUTNODE_H
41,040
https://github.com/laboratorybox/hither2/blob/master/examples/expensive_calculation.py
Github Open Source
Open Source
Apache-2.0
2,021
hither2
laboratorybox
Python
Code
37
120
# expensive_calculation.py import hither2 as hi import time as time @hi.function( 'expensive_calculation', '0.1.0', image=hi.RemoteDockerImage('docker://jsoules/simplescipy:latest'), modules=['simplejson'], ) def expensive_calculation(x): # Simulate an expensive computation by just sleeping for # x seconds and then return 42 time.sleep(x) return 42
2,924
https://github.com/zhuochu/mand-mobile-rn/blob/master/samples/src/screen/business/captcha/index.js
Github Open Source
Open Source
Apache-2.0
2,021
mand-mobile-rn
zhuochu
JavaScript
Code
36
104
import React from 'react' import Container from '../../../components/container' import CaptchaDemo from '../../../../demo/captcha/base.demo' export class CaptchaScreen extends React.Component { static navigationOptions = { title: 'Captcha', } render() { return ( <Container> <CaptchaDemo /> </Container> ) } }
9,901
https://github.com/code-refs/bach/blob/master/test.projects/test/java/test/projects/StreamingEventsTests.java
Github Open Source
Open Source
MIT
2,021
bach
code-refs
Java
Code
90
353
package test.projects; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertLinesMatch; import com.github.sormuras.bach.Bach; import com.github.sormuras.bach.Logbook; import com.github.sormuras.bach.Options; import java.nio.file.Path; import org.junit.jupiter.api.Test; class StreamingEventsTests { @Test void build() { var name = "StreamingEvents"; var root = Path.of("test.projects", name); var bach = Bach.of( Logbook.ofErrorPrinter(), Options.of() .with("--chroot", root.toString()) .with("--verbose", "true") .with("--limit-tool", "javac", "jar", "test", "junit") .with("--workflow", "build")); assertEquals(0, bach.run(), bach.logbook().toString()); assertLinesMatch( """ >> BACH'S INITIALIZATION >> Work on project StreamingEvents 0 >> INFO + BUILD >> Ran 2 tests in .+ Build end. Bach run took .+ Logbook written to .+ """ .lines(), bach.logbook().lines()); } }
47,941
https://github.com/ttracx/OpenTuring/blob/master/turing/test/Examples/Introduction to Programming in Turing/Ch20/DrawParabola.t
Github Open Source
Open Source
MIT
2,022
OpenTuring
ttracx
Perl
Code
383
726
% The "DrawParabola" program % Plots a graph of y = x ** 2 % for values of x from 0 to 14 % Number of points to be plotted is 100 setscreen ("graphics") procedure minmax (list : array 1 .. * of real, listlength : int, var listmin, listmax, listrange : real) % Find the minimum, maximum and range of the list listmin := list (1) listmax := list (1) for i : 2 .. listlength listmin := min (listmin, list (i)) listmax := max (listmax, list (i)) end for listrange := listmax - listmin end minmax procedure graphplot (x, y : array 1 .. * of real, pointcount : int, title : string) % Label graph at top of window locate (1, 1) put title % Layout plotting area const plotleft := 0 const plotlow := 0 const plotright := maxx const plothigh := maxy - 10 drawbox (plotleft, plotlow, plotright, plothigh, 1) var xmin, xmax, xrange : real var ymin, ymax, yrange : real minmax (x, pointcount, xmin, xmax, xrange) minmax (y, pointcount, ymin, ymax, yrange) const xscale := (plotright - plotleft) / xrange const yscale := (plothigh - plotlow) / yrange % Draw axes if in plotting area if ymin <= 0 and ymax > 0 then % Plot x-axis const yzero := round ( - ymin * yscale) + plotlow drawline (plotleft, yzero, plotright, yzero, 2) end if if xmin <= 0 and xmax > 0 then % Plot y-axis const xzero := round ( - xmin * xscale) + plotleft drawline (xzero, plotlow, xzero, plothigh, 2) end if % Plot graph for i : 1 .. pointcount const xplot := round ( (x (i) - xmin) * xscale) + plotleft const yplot := round ( (y (i) - ymin) * yscale) + plotlow drawdot (xplot, yplot, 3) end for end graphplot const pointcount := 100 var x, y : array 1 .. pointcount of real const xleft := 0.0 const xright := 14.0 const xdifference := (xright - xleft) / (pointcount - 1) % Compute corresponding values of x and y for i : 1 .. pointcount x (i) := xleft + (i - 1) * xdifference y (i) := x (i) ** 2 end for graphplot (x, y, pointcount, "Graph of y = x ** 2")
6,514
https://github.com/610yilingliu/wheels/blob/master/py_wheels/visualization.py
Github Open Source
Open Source
MIT
null
wheels
610yilingliu
Python
Code
822
2,114
import os import time import math import sys import time import numpy as np import matplotlib.pyplot as plt import scipy.io def de_project(np_arr): """ project numpy array from [-1, 1] to [0, 255] for visualization """ item = (np_arr +1)*255 / 2 return item.astype(np.int32, copy=True) def time_helper(seperator = '_', to_sec = False): """ return a string like 2020_09_11_22_43_00 (if to_sec is True) or 2020_09_11_22_43 (if to_sec is False) """ localtime = time.asctime(time.localtime(time.time())) if to_sec: return time.strftime("%Y" + seperator + "%m" + seperator + "%d" + seperator + "%H" + seperator + "%M" + seperator + "%S", time.localtime()) return time.strftime("%Y" + seperator + "%m" + seperator + "%d" + seperator + "%H" + seperator + "%M", time.localtime()) def show_imgs(np_arr, dest_path, specific_sep = None, specific_suf = None, show_num = None, show = False): """ :type np_arr: numpy array contains images :type dest_path: String, destination folder to export images :type specific_sep: String, seperator inside output file name. like 2020_01_01_01_01.png or 202001010101.png :type specific_suf: String, if you specific a suffix like a, the filename will be 2020_01_02_01_01_a.png :type show_num: int. How many number of pictures will be shown in the plot """ make_dir(dest_path) if show_num is None: data_size = np_arr.shape[0] else: data_size = min(show_num, np_arr.shape[0]) plot_size = int(math.sqrt(data_size)) l = plot_size if l == 0: print('empty numpy array') return h = data_size // l if data_size % l == 0 else (data_size // l) + 1 plt.figure(figsize=(8, 8)) for i in range(data_size): p = plt.subplot(h, l, i + 1) p.axis('off') # HWC to CHW new = np_arr[i].transpose((1, 2, 0)) plt.imshow(new) f = plt.gcf() if show: plt.show() plt.draw() if specific_suf and specific_sep: fname = time_helper(specific_sep) + specific_sep + specific_suf elif specific_sep: fname = time_helper(specific_sep) elif specific_suf: fname = time_helper() + '_' + specific_suf else: fname = time_helper() name = dest_path + '/' + fname + '.png' f.savefig(name) try: f.savefig(name) except: print('The file name you defined is ' + name + ', please make sure that there are no system-rejected symbol in file name.\n') print('Program terminated...') exit(0) plt.close() ## Export system output to a log file class Logger(object): def __init__(self, filename='dcgan.log', stream=sys.stdout): self.terminal = stream self.log = open(filename, 'a') def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): pass def loss_graph(losses, dest_path, name): make_dir(dest_path) fig, ax = plt.subplots() losses = np.array(losses) plt.plot(losses.T[0], label='Discriminator', alpha=0.5) plt.plot(losses.T[1], label='Generator', alpha=0.5) plt.title("Training Losses") plt.legend() f = plt.gcf() plt.draw() f.savefig(dest_path + '/' + name) plt.close() def pic_to_npz(path, outname, target_folder = None): """ :type path: String, folder that stores pictures :type outname: String, name of the output .npz file. Remember you do not have to input '.npz' suffix. :type target_folder: root path of the """ if not os.path.exists(path): print(path + ' not exists') return x = [] files = os.listdir(path) for f in files: img = cv2.imread(path + '/' + f) img= cv2.cvtColor(img,cv2.COLOR_BGR2RGB) img = img.transpose((2,0,1)) x.append(img) if target_folder is None: np.savez(outname, train = x) else: make_dir(target_folder) np.savez(target_folder + '/' + outname, train = x) def mat_tonpz(mat_file, outname, target_folder = None): """ :type mat_file: String, path of a .mat file :type outname: String, name of the output(not the whole path name) :type target_folder: String, name of the folder to export .npz file ### Explain: After you read `.mat` file with scipy, the data that stores in your memory is a dictionary. For dataset that Yuliya is using, the dictionary has two keys with data: 'X' and 'y' (You can view the datatype by add some break points in your ide(not Jupyter Notebook!)), and enter debug mode to run. The data we export is numpy in 'X', which are images we want. One thing you have to be careful in .mat file is that the first three keys in that file are not data, these keys are listed in set invalid in the following code, you need to skip it """ data = scipy.io.loadmat(mat_file) invalid = ('__header__', '__version__', '__globals__') for key in data: if key in invalid: continue ## Only store X data train_data = data[key] ## Original data is in HWCN style (height, width, channel, images). TF GPU version calculates NCHW faster, but matplotlib.pyplot and TF CPU version requires NHWC. ## Transpose it into NCHW for tf, and we will do NHWC for plotting in visualize_tools.show_image() ## The reason why GPU prefers NCHW format explained here(in Chinese, use Google translate if you cannot read it): ## https://blog.csdn.net/weixin_37801695/article/details/86614566 train_data = train_data.transpose((3, 2, 0, 1)) if target_folder is None: np.savez(outname, train = train_data) else: make_dir(target_folder) np.savez(target_folder + '/' + outname, train = train_data) break def make_dir(path): """ :type path: String. Only separator '/' is supported This is a helper function to build an directory. os.mkdir does not allow you to create floder like `./abc/def`, you must create `./abc` first and create `./abc/def` inside it """ path = path.split('/') cur = './' for i in range(len(path)): if path[i] == '' or path[i] == '.': continue cur = cur + '/' + path[i] if not os.path.exists(cur): try: os.mkdir(cur) except: print('Something Strange happend while creating directory ' + cur + '\n') return
48,238
https://github.com/xinwuyun/cattery/blob/master/node_modules/speech-rule-engine/js/rule_engine/speech_rule_engine.js
Github Open Source
Open Source
MIT
null
cattery
xinwuyun
JavaScript
Code
1,404
5,010
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.storeFactory = exports.SpeechRuleEngine = void 0; const auditory_description_1 = require("../audio/auditory_description"); const debugger_1 = require("../common/debugger"); const DomUtil = require("../common/dom_util"); const engine_1 = require("../common/engine"); const EngineConst = require("../common/engine_const"); const xpath_util_1 = require("../common/xpath_util"); const SpeechRules = require("../speech_rules/speech_rules"); const SpeechRuleStores = require("../speech_rules/speech_rule_stores"); const braille_store_1 = require("./braille_store"); const dynamic_cstr_1 = require("./dynamic_cstr"); const grammar_1 = require("./grammar"); const math_store_1 = require("./math_store"); const speech_rule_1 = require("./speech_rule"); const trie_1 = require("../indexing/trie"); class SpeechRuleEngine { constructor() { this.trie = null; this.evaluators_ = {}; this.trie = new trie_1.Trie(); } static getInstance() { SpeechRuleEngine.instance = SpeechRuleEngine.instance || new SpeechRuleEngine(); return SpeechRuleEngine.instance; } static debugSpeechRule(rule, node) { const prec = rule.precondition; const queryResult = rule.context.applyQuery(node, prec.query); debugger_1.Debugger.getInstance().output(prec.query, queryResult ? queryResult.toString() : queryResult); prec.constraints.forEach((cstr) => debugger_1.Debugger.getInstance().output(cstr, rule.context.applyConstraint(node, cstr))); } static debugNamedSpeechRule(name, node) { const rules = SpeechRuleEngine.getInstance().trie.collectRules(); const allRules = rules.filter((rule) => rule.name == name); for (let i = 0, rule; (rule = allRules[i]); i++) { debugger_1.Debugger.getInstance().output('Rule', name, 'DynamicCstr:', rule.dynamicCstr.toString(), 'number', i); SpeechRuleEngine.debugSpeechRule(rule, node); } } static updateEvaluator(node) { let parent = node; while (parent && !parent.evaluate) { parent = parent.parentNode; } if (parent.evaluate) { xpath_util_1.xpath.currentDocument = parent; } } evaluateNode(node) { if (engine_1.default.getInstance().mode === EngineConst.Mode.HTTP) { SpeechRuleEngine.updateEvaluator(node); } const timeIn = new Date().getTime(); let result = []; try { result = this.evaluateNode_(node); } catch (err) { console.error('Something went wrong computing speech.'); debugger_1.Debugger.getInstance().output(err); } const timeOut = new Date().getTime(); debugger_1.Debugger.getInstance().output('Time:', timeOut - timeIn); return result; } toString() { const allRules = this.trie.collectRules(); return allRules.map((rule) => rule.toString()).join('\n'); } runInSetting(settings, callback) { const engine = engine_1.default.getInstance(); const save = {}; for (const key in settings) { save[key] = engine[key]; engine[key] = settings[key]; } engine.setDynamicCstr(); const result = callback(); for (const key in save) { engine[key] = save[key]; } engine.setDynamicCstr(); return result; } addStore(set) { const store = storeFactory(set); if (store.kind !== 'abstract') { store.getSpeechRules().forEach((x) => this.trie.addRule(x)); } this.addEvaluator(store); } processGrammar(context, node, grammar) { const assignment = {}; for (const key in grammar) { const value = grammar[key]; assignment[key] = typeof value === 'string' ? context.constructString(node, value) : value; } grammar_1.Grammar.getInstance().pushState(assignment); } addEvaluator(store) { const fun = store.evaluateDefault.bind(store); const loc = this.evaluators_[store.locale]; if (loc) { loc[store.modality] = fun; return; } const mod = {}; mod[store.modality] = fun; this.evaluators_[store.locale] = mod; } getEvaluator(locale, modality) { const loc = this.evaluators_[locale] || this.evaluators_[dynamic_cstr_1.DynamicCstr.DEFAULT_VALUES[dynamic_cstr_1.Axis.LOCALE]]; return loc[modality] || loc[dynamic_cstr_1.DynamicCstr.DEFAULT_VALUES[dynamic_cstr_1.Axis.MODALITY]]; } enumerate(opt_info) { return this.trie.enumerate(opt_info); } evaluateNode_(node) { if (!node) { return []; } this.updateConstraint_(); return this.evaluateTree_(node); } evaluateTree_(node) { const engine = engine_1.default.getInstance(); let result; debugger_1.Debugger.getInstance().output(engine.mode !== EngineConst.Mode.HTTP ? node.toString() : node); grammar_1.Grammar.getInstance().setAttribute(node); const rule = this.lookupRule(node, engine.dynamicCstr); if (!rule) { if (engine.strict) { return []; } result = this.getEvaluator(engine.locale, engine.modality)(node); if (node.attributes) { this.addPersonality_(result, {}, false, node); } return result; } debugger_1.Debugger.getInstance().generateOutput(() => [ 'Apply Rule:', rule.name, rule.dynamicCstr.toString(), (engine.mode !== EngineConst.Mode.HTTP ? node : node).toString() ]); const context = rule.context; const components = rule.action.components; result = []; for (let i = 0, component; (component = components[i]); i++) { let descrs = []; const content = component.content || ''; const attributes = component.attributes || {}; let multi = false; if (component.grammar) { this.processGrammar(context, node, component.grammar); } let saveEngine = null; if (attributes.engine) { saveEngine = engine_1.default.getInstance().dynamicCstr.getComponents(); const features = grammar_1.Grammar.parseInput(attributes.engine); engine_1.default.getInstance().setDynamicCstr(features); } switch (component.type) { case speech_rule_1.ActionType.NODE: { const selected = context.applyQuery(node, content); if (selected) { descrs = this.evaluateTree_(selected); } } break; case speech_rule_1.ActionType.MULTI: { multi = true; const selects = context.applySelector(node, content); if (selects.length > 0) { descrs = this.evaluateNodeList_(context, selects, attributes['sepFunc'], context.constructString(node, attributes['separator']), attributes['ctxtFunc'], context.constructString(node, attributes['context'])); } } break; case speech_rule_1.ActionType.TEXT: { const xpath = attributes['span']; const attrs = {}; if (xpath) { const nodes = (0, xpath_util_1.evalXPath)(xpath, node); if (nodes.length) { attrs.extid = nodes[0].getAttribute('extid'); } } const str = context.constructString(node, content); if (str) { if (Array.isArray(str)) { descrs = str.map(function (span) { return auditory_description_1.AuditoryDescription.create({ text: span.speech, attributes: span.attributes }, { adjust: true }); }); } else { descrs = [ auditory_description_1.AuditoryDescription.create({ text: str, attributes: attrs }, { adjust: true }) ]; } } } break; case speech_rule_1.ActionType.PERSONALITY: default: descrs = [auditory_description_1.AuditoryDescription.create({ text: content })]; } if (descrs[0] && !multi) { if (attributes['context']) { descrs[0]['context'] = context.constructString(node, attributes['context']) + (descrs[0]['context'] || ''); } if (attributes['annotation']) { descrs[0]['annotation'] = attributes['annotation']; } } this.addLayout(descrs, attributes, multi); if (component.grammar) { grammar_1.Grammar.getInstance().popState(); } result = result.concat(this.addPersonality_(descrs, attributes, multi, node)); if (saveEngine) { engine_1.default.getInstance().setDynamicCstr(saveEngine); } } return result; } evaluateNodeList_(context, nodes, sepFunc, sepStr, ctxtFunc, ctxtStr) { if (!nodes.length) { return []; } const sep = sepStr || ''; const cont = ctxtStr || ''; const cFunc = context.contextFunctions.lookup(ctxtFunc); const ctxtClosure = cFunc ? cFunc(nodes, cont) : function () { return cont; }; const sFunc = context.contextFunctions.lookup(sepFunc); const sepClosure = sFunc ? sFunc(nodes, sep) : function () { return [ auditory_description_1.AuditoryDescription.create({ text: sep }, { translate: true }) ]; }; let result = []; for (let i = 0, node; (node = nodes[i]); i++) { const descrs = this.evaluateTree_(node); if (descrs.length > 0) { descrs[0]['context'] = ctxtClosure() + (descrs[0]['context'] || ''); result = result.concat(descrs); if (i < nodes.length - 1) { const text = sepClosure(); result = result.concat(text); } } } return result; } addLayout(descrs, props, _multi) { const layout = props.layout; if (!layout) { return; } if (layout.match(/^begin/)) { descrs.unshift(new auditory_description_1.AuditoryDescription({ text: '', layout: layout })); return; } if (layout.match(/^end/)) { descrs.push(new auditory_description_1.AuditoryDescription({ text: '', layout: layout })); return; } descrs.unshift(new auditory_description_1.AuditoryDescription({ text: '', layout: `begin${layout}` })); descrs.push(new auditory_description_1.AuditoryDescription({ text: '', layout: `end${layout}` })); } addPersonality_(descrs, props, multi, node) { const personality = {}; let pause = null; for (const key of EngineConst.personalityPropList) { const value = props[key]; if (typeof value === 'undefined') { continue; } const numeral = parseFloat(value); const realValue = isNaN(numeral) ? value.charAt(0) === '"' ? value.slice(1, -1) : value : numeral; if (key === EngineConst.personalityProps.PAUSE) { pause = realValue; } else { personality[key] = realValue; } } for (let i = 0, descr; (descr = descrs[i]); i++) { this.addRelativePersonality_(descr, personality); this.addExternalAttributes_(descr, node); } if (multi && descrs.length) { delete descrs[descrs.length - 1].personality[EngineConst.personalityProps.JOIN]; } if (pause && descrs.length) { const last = descrs[descrs.length - 1]; if (last.text || Object.keys(last.personality).length) { descrs.push(auditory_description_1.AuditoryDescription.create({ text: '', personality: { pause: pause } })); } else { last.personality[EngineConst.personalityProps.PAUSE] = pause; } } return descrs; } addExternalAttributes_(descr, node) { if (node.hasAttributes()) { const attrs = node.attributes; for (let i = attrs.length - 1; i >= 0; i--) { const key = attrs[i].name; if (!descr.attributes[key] && key.match(/^ext/)) { descr.attributes[key] = attrs[i].value; } } } } addRelativePersonality_(descr, personality) { if (!descr['personality']) { descr['personality'] = personality; return descr; } const descrPersonality = descr['personality']; for (const p in personality) { if (descrPersonality[p] && typeof descrPersonality[p] == 'number' && typeof personality[p] == 'number') { descrPersonality[p] = descrPersonality[p] + personality[p]; } else if (!descrPersonality[p]) { descrPersonality[p] = personality[p]; } } return descr; } updateConstraint_() { const dynamic = engine_1.default.getInstance().dynamicCstr; const strict = engine_1.default.getInstance().strict; const trie = this.trie; const props = {}; let locale = dynamic.getValue(dynamic_cstr_1.Axis.LOCALE); let modality = dynamic.getValue(dynamic_cstr_1.Axis.MODALITY); let domain = dynamic.getValue(dynamic_cstr_1.Axis.DOMAIN); if (!trie.hasSubtrie([locale, modality, domain])) { domain = dynamic_cstr_1.DynamicCstr.DEFAULT_VALUES[dynamic_cstr_1.Axis.DOMAIN]; if (!trie.hasSubtrie([locale, modality, domain])) { modality = dynamic_cstr_1.DynamicCstr.DEFAULT_VALUES[dynamic_cstr_1.Axis.MODALITY]; if (!trie.hasSubtrie([locale, modality, domain])) { locale = dynamic_cstr_1.DynamicCstr.DEFAULT_VALUES[dynamic_cstr_1.Axis.LOCALE]; } } } props[dynamic_cstr_1.Axis.LOCALE] = [locale]; props[dynamic_cstr_1.Axis.MODALITY] = [ modality !== 'summary' ? modality : dynamic_cstr_1.DynamicCstr.DEFAULT_VALUES[dynamic_cstr_1.Axis.MODALITY] ]; props[dynamic_cstr_1.Axis.DOMAIN] = [ modality !== 'speech' ? dynamic_cstr_1.DynamicCstr.DEFAULT_VALUES[dynamic_cstr_1.Axis.DOMAIN] : domain ]; const order = dynamic.getOrder(); for (let i = 0, axis; (axis = order[i]); i++) { if (!props[axis]) { const value = dynamic.getValue(axis); const valueSet = this.makeSet_(value, dynamic.preference); const def = dynamic_cstr_1.DynamicCstr.DEFAULT_VALUES[axis]; if (!strict && value !== def) { valueSet.push(def); } props[axis] = valueSet; } } dynamic.updateProperties(props); } makeSet_(value, preferences) { if (!preferences || !Object.keys(preferences).length) { return [value]; } return value.split(':'); } lookupRule(node, dynamic) { if (!node || (node.nodeType !== DomUtil.NodeType.ELEMENT_NODE && node.nodeType !== DomUtil.NodeType.TEXT_NODE)) { return null; } const matchingRules = this.lookupRules(node, dynamic); return matchingRules.length > 0 ? this.pickMostConstraint_(dynamic, matchingRules) : null; } lookupRules(node, dynamic) { return this.trie.lookupRules(node, dynamic.allProperties()); } pickMostConstraint_(_dynamic, rules) { const comparator = engine_1.default.getInstance().comparator; rules.sort(function (r1, r2) { return (comparator.compare(r1.dynamicCstr, r2.dynamicCstr) || r2.precondition.priority - r1.precondition.priority || r2.precondition.constraints.length - r1.precondition.constraints.length || r2.precondition.rank - r1.precondition.rank); }); debugger_1.Debugger.getInstance().generateOutput((() => { return rules.map((x) => x.name + '(' + x.dynamicCstr.toString() + ')'); }).bind(this)); return rules[0]; } } exports.SpeechRuleEngine = SpeechRuleEngine; const stores = new Map(); function getStore(modality) { if (modality === 'braille') { return new braille_store_1.BrailleStore(); } return new math_store_1.MathStore(); } function storeFactory(set) { const name = `${set.locale}.${set.modality}.${set.domain}`; if (set.kind === 'actions') { const store = stores.get(name); store.parse(set); return store; } SpeechRuleStores.init(); if (set && !set.functions) { set.functions = SpeechRules.getStore(set.locale, set.modality, set.domain); } const store = getStore(set.modality); stores.set(name, store); if (set.inherits) { store.inherits = stores.get(`${set.inherits}.${set.modality}.${set.domain}`); } store.parse(set); store.initialize(); return store; } exports.storeFactory = storeFactory; engine_1.default.nodeEvaluator = SpeechRuleEngine.getInstance().evaluateNode.bind(SpeechRuleEngine.getInstance());
33,972
https://github.com/szhengye/Biz-SIP-Cloud/blob/master/common/src/main/java/com/bizmda/bizsip/message/fixedlength/FixedLengthConfig.java
Github Open Source
Open Source
Apache-2.0
2,021
Biz-SIP-Cloud
szhengye
Java
Code
97
395
package com.bizmda.bizsip.message.fixedlength; import com.bizmda.bizsip.common.BizException; import com.bizmda.bizsip.message.fieldfunction.FieldFunction; import lombok.Data; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author 史正烨 */ @Data public class FixedLengthConfig { private String name; private int length; private List<FieldFunction> packFunctions; private List<FieldFunction> unpackFunctions; public FixedLengthConfig(Map<String,Object> map) throws BizException { this.name = (String)map.get("name"); this.length = (int)map.get("length"); List<Map<String,Object>> mapList = (List<Map<String,Object>>)map.get("pack-functions"); this.packFunctions = new ArrayList<>(); if (mapList != null) { for(Map<String,Object> functionMap:mapList) { FieldFunction fieldFunction = new FieldFunction(functionMap); this.packFunctions.add(fieldFunction); } } mapList = (List<Map<String,Object>>)map.get("unpack-functions"); this.unpackFunctions = new ArrayList<>(); if (mapList != null) { for(Map<String,Object> functionMap:mapList) { FieldFunction fieldFunction = new FieldFunction(functionMap); this.unpackFunctions.add(fieldFunction); } } } }
7,067
https://github.com/cornelinux/privacyIDEA-ADFSProvider/blob/master/privacyIDEAADFSProvider/config.cs
Github Open Source
Open Source
MIT
null
privacyIDEA-ADFSProvider
cornelinux
C#
Code
345
1,325
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System.Xml.Serialization; // // This source code was auto-generated by xsd, Version=4.6.1055.0. // namespace privacyIDEAADFSProvider { /// <remarks/> [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] public partial class ADFSserver { private string urlField; private string realmField; private string sslField; private string adminuserField; private string adminpwField; private ADFSinterface[] interfaceField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] public string url { get { return this.urlField; } set { this.urlField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] public string realm { get { return this.realmField; } set { this.realmField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] public string ssl { get { return this.sslField; } set { this.sslField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] public string adminuser { get { return this.adminuserField; } set { this.adminuserField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] public string adminpw { get { return this.adminpwField; } set { this.adminpwField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("interface", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] public ADFSinterface[] @interface { get { return this.interfaceField; } set { this.interfaceField = value; } } } /// <remarks/> [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class ADFSinterface { private string errormessageField; private string wellcomemessageField; private string lICDField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] public string errormessage { get { return this.errormessageField; } set { this.errormessageField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)] public string wellcomemessage { get { return this.wellcomemessageField; } set { this.wellcomemessageField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public string LICD { get { return this.lICDField; } set { this.lICDField = value; } } } /// <remarks/> [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] [System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)] public partial class NewDataSet { private ADFSserver[] itemsField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("server")] public ADFSserver[] Items { get { return this.itemsField; } set { this.itemsField = value; } } } }
23,068
https://github.com/isabella232/lsp-client/blob/master/src/lsp-conversion.ts
Github Open Source
Open Source
MIT
2,020
lsp-client
isabella232
TypeScript
Code
410
1,244
import * as sourcegraph from 'sourcegraph' import { TextDocumentPositionParams, WorkspaceFolder } from 'vscode-languageserver-protocol' import { Diagnostic, DiagnosticSeverity, Hover, Location, MarkupContent, Position, Range, } from 'vscode-languageserver-types' export const convertProviderParams = ( { textDocument, position }: { textDocument: sourcegraph.TextDocument; position: sourcegraph.Position }, { clientToServerURI }: { clientToServerURI: (u: URL) => URL } ): TextDocumentPositionParams => ({ textDocument: { uri: clientToServerURI(new URL(textDocument.uri)).href, }, position: { line: position.line, character: position.character, }, }) export const convertPosition = (sourcegraph: typeof import('sourcegraph'), position: Position): sourcegraph.Position => new sourcegraph.Position(position.line, position.character) export const convertRange = (sourcegraph: typeof import('sourcegraph'), range: Range): sourcegraph.Range => new sourcegraph.Range(convertPosition(sourcegraph, range.start), convertPosition(sourcegraph, range.end)) export function convertHover(sourcegraph: typeof import('sourcegraph'), hover: Hover | null): sourcegraph.Hover | null { if (!hover) { return null } const contents = Array.isArray(hover.contents) ? hover.contents : [hover.contents] return { range: hover.range && convertRange(sourcegraph, hover.range), contents: { kind: sourcegraph.MarkupKind.Markdown, value: contents .map(content => { if (MarkupContent.is(content)) { // Assume it's markdown. To be correct, markdown would need to be escaped for non-markdown kinds. return content.value } if (typeof content === 'string') { return content } if (!content.value) { return '' } return '```' + content.language + '\n' + content.value + '\n```' }) .filter(str => !!str.trim()) .join('\n\n---\n\n'), }, } } export const convertLocation = ( sourcegraph: typeof import('sourcegraph'), location: Location ): sourcegraph.Location => ({ uri: new sourcegraph.URI(location.uri), range: convertRange(sourcegraph, location.range), }) export function convertLocations( sourcegraph: typeof import('sourcegraph'), locationOrLocations: Location | Location[] | null ): sourcegraph.Location[] | null { if (!locationOrLocations) { return null } const locations = Array.isArray(locationOrLocations) ? locationOrLocations : [locationOrLocations] return locations.map(location => convertLocation(sourcegraph, location)) } const DIAGNOSTIC_COLORS: Readonly<Record<DiagnosticSeverity, string>> = { [DiagnosticSeverity.Error]: 'var(--danger, #dc3545)', [DiagnosticSeverity.Information]: 'var(--info, #17a2b8)', [DiagnosticSeverity.Warning]: 'var(--success, #ffc107)', [DiagnosticSeverity.Hint]: 'var(--secondary, #6c757d)', } export const convertDiagnosticToDecoration = ( sourcegraph: typeof import('sourcegraph'), diagnostic: Diagnostic ): sourcegraph.TextDocumentDecoration => ({ after: { color: DIAGNOSTIC_COLORS[diagnostic.severity ?? DiagnosticSeverity.Hint], contentText: diagnostic.message, }, range: convertRange(sourcegraph, diagnostic.range), }) export const toLSPWorkspaceFolder = ({ clientToServerURI }: { clientToServerURI: (u: URL) => URL }) => ( root: sourcegraph.WorkspaceRoot ): WorkspaceFolder => { const serverUri = clientToServerURI(new URL(root.uri.toString())) return { uri: serverUri.href, name: new URL(serverUri.href).pathname.split('/').pop()!, } } /** * Rewrites all `uri` properties in an object, recursively */ export function rewriteUris(obj: any, transform: (uri: URL) => URL): void { // Scalar if (typeof obj !== 'object' || obj === null) { return } // Arrays if (Array.isArray(obj)) { for (const element of obj) { rewriteUris(element, transform) } return } // Object if ('uri' in obj) { obj.uri = transform(new URL(obj.uri)).href } for (const key of Object.keys(obj)) { rewriteUris(obj[key], transform) } }
43,269
https://github.com/raiyanla/compute-runtime/blob/master/opencl/source/helpers/memory_properties_flags_helpers.cpp
Github Open Source
Open Source
MIT
2,020
compute-runtime
raiyanla
C++
Code
31
112
/* * Copyright (C) 2019-2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "opencl/source/helpers/memory_properties_flags_helpers_base.inl" namespace NEO { void MemoryPropertiesFlagsParser::addExtraMemoryPropertiesFlags(MemoryPropertiesFlags &propertiesFlag, cl_mem_flags flags, cl_mem_flags_intel flagsIntel) { } } // namespace NEO
5,492
https://github.com/nschonni/spec-prod/blob/master/test/validate-links.test.ts
Github Open Source
Open Source
MIT
2,022
spec-prod
nschonni
TypeScript
Code
57
131
import main from "../src/validate-links.js"; import { Outputs } from "./index.test.js"; export default async function validateLinks(outputs: Outputs) { const { links: shouldValidate = false } = outputs?.prepare?.validate || {}; if (shouldValidate === false) { return; } const { dest = process.cwd() + ".common", file = "index.html" } = outputs?.build?.w3c || {}; return await main({ dest, file }); }
23,552
https://github.com/pf92/x-chain-protocols/blob/master/contracts/Protocol1.sol
Github Open Source
Open Source
MIT
2,021
x-chain-protocols
pf92
Solidity
Code
828
1,991
pragma solidity ^0.5.13; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "solidity-rlp/contracts/RLPReader.sol"; import "./TxInclusionVerifier.sol"; contract Protocol1 is ERC20 { using RLPReader for RLPReader.RLPItem; using RLPReader for bytes; struct ClaimData { address burnContract; // the contract which has burnt the tokens on the other blockchian address recipient; address claimContract; uint value; // the value to create on this chain bool isBurnValid; // indicates whether the burning of tokens has taken place (didn't abort, e.g., due to require statement) } TxInclusionVerifier txInclusionVerifier; mapping(bytes32 => bool) claimedTransactions; uint chainIdentifier; mapping(address => bool) participatingTokenContracts; // addresses of the token contracts living on other blockchains uint TRANSFER_FEE = 10; // 1/10 of the transfer amount uint8 constant REQUIRED_TX_CONFIRMATIONS = 10; // number of blocks that have to follow the block containing a tx to consider it confirmed uint constant FAIR_CLAIM_PERIOD = 20; // Number of blocks that must follow the block containing the burn tx. // Posting a claim within this period results in transferring the fees to the burner. // If the claim is posted after this period, the client submitting the claim gets the fees. constructor(address[] memory tokenContracts, address txInclVerifier, uint initialSupply) public { for (uint i = 0; i < tokenContracts.length; i++) { participatingTokenContracts[tokenContracts[i]] = true; } txInclusionVerifier = TxInclusionVerifier(txInclVerifier); _mint(msg.sender, initialSupply); } // For simplicity, use this function to register further token contracts. // This has obvious security implications as any one is able to change this address -> do not use it in production. function registerTokenContract(address tokenContract) public { require(tokenContract != address(0), "contract address must not be zero address"); participatingTokenContracts[tokenContract] = true; } function burn(address recipient, address claimContract, uint value) public { require(recipient != address(0), "recipient address must not be zero address"); require(participatingTokenContracts[claimContract] == true, "claim contract address is not registered"); require(balanceOf(msg.sender) >= value, 'sender has not enough tokens'); _burn(msg.sender, value); emit Burn(recipient, claimContract, value); } function claim( bytes memory rlpHeader, // rlp-encoded header of the block containing burn tx along with its receipt bytes memory rlpEncodedTx, // rlp-encoded burn tx bytes memory rlpEncodedReceipt, // rlp-encoded receipt of burn tx ('burn receipt) bytes memory rlpMerkleProofTx, // rlp-encoded Merkle proof of Membership for burn tx (later passed to relay) bytes memory rlpMerkleProofReceipt, // rlp-encoded Merkle proof of Membership for burn receipt (later passed to relay) bytes memory path // the path from the root node down to the burn tx/receipt in the corresponding Merkle tries (tx, receipt). // path is the same for both tx and its receipt. ) public { ClaimData memory c = extractClaim(rlpEncodedTx, rlpEncodedReceipt); bytes32 txHash = keccak256(rlpEncodedTx); // check pre-conditions require(claimedTransactions[txHash] == false, "tokens have already been claimed"); require(participatingTokenContracts[c.burnContract] == true, "burn contract address is not registered"); require(c.claimContract == address(this), "this contract has not been specified as destination token contract"); require(c.isBurnValid == true, "burn transaction was not successful (e.g., require statement was violated)"); // verify inclusion of burn transaction uint txExists = txInclusionVerifier.verifyTransaction(0, rlpHeader, REQUIRED_TX_CONFIRMATIONS, rlpEncodedTx, path, rlpMerkleProofTx); require(txExists == 0, "burn transaction does not exist or has not enough confirmations"); // verify inclusion of receipt uint receiptExists = txInclusionVerifier.verifyReceipt(0, rlpHeader, REQUIRED_TX_CONFIRMATIONS, rlpEncodedReceipt, path, rlpMerkleProofReceipt); require(receiptExists == 0, "burn receipt does not exist or has not enough confirmations"); uint fee = calculateFee(c.value, TRANSFER_FEE); uint remainingValue = c.value - fee; address feeRecipient = c.recipient; if (msg.sender != c.recipient && txInclusionVerifier.isBlockConfirmed(0, keccak256(rlpHeader), FAIR_CLAIM_PERIOD)) { // other client wants to claim fees // fair claim period has elapsed -> fees go to msg.sender feeRecipient = msg.sender; } // mint fees to feeRecipient _mint(feeRecipient, fee); // mint remaining value to recipient _mint(c.recipient, remainingValue); claimedTransactions[txHash] = true; // IMPORTANT: prevent this tx from being used for further claims emit Claim(txHash, c.burnContract, c.recipient, feeRecipient, remainingValue, fee); } function extractClaim(bytes memory rlpTransaction, bytes memory rlpReceipt) private pure returns (ClaimData memory) { ClaimData memory c; // parse transaction RLPReader.RLPItem[] memory transaction = rlpTransaction.toRlpItem().toList(); c.burnContract = transaction[3].toAddress(); // parse receipt RLPReader.RLPItem[] memory receipt = rlpReceipt.toRlpItem().toList(); c.isBurnValid = receipt[0].toBoolean(); // read logs RLPReader.RLPItem[] memory logs = receipt[3].toList(); RLPReader.RLPItem[] memory burnEventTuple = logs[1].toList(); // logs[0] contains the transfer event emitted by the ECR20 method _burn // logs[1] contains the burn event emitted by the method burn (this contract) RLPReader.RLPItem[] memory burnEventTopics = burnEventTuple[1].toList(); // topics contain all indexed event fields // read value and recipient from burn event c.recipient = address(burnEventTopics[1].toUint()); // indices of indexed fields start at 1 (0 is reserved for the hash of the event signature) c.claimContract = address(burnEventTopics[2].toUint()); c.value = burnEventTopics[3].toUint(); return c; } /** * @dev Divides amount by divisor and returns the integer result. If the remainder is greater than 0, * the result is incremented by 1 (rounded up). */ function calculateFee(uint amount, uint divisor) private pure returns (uint) { uint result = amount / divisor; uint remainder = amount % divisor; if (remainder > 0) { // round towards next integer return result + 1; } else { return result; } } event Burn(address indexed recipient, address indexed claimContract, uint indexed value); event Claim( bytes32 indexed burnTxHash, address indexed burnContract, address indexed recipient, address feeRecipient, uint value, uint fee ); }
13,634
https://github.com/NeoTim/hiphop-php-docker/blob/master/src/hiphop-php/hphp/compiler/util/jump_table.cpp
Github Open Source
Open Source
PHP-3.01, Zend-2.0, LicenseRef-scancode-unknown-license-reference
2,017
hiphop-php-docker
NeoTim
C++
Code
277
883
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include <compiler/util/jump_table.h> #include <compiler/analysis/analysis_result.h> #include <compiler/option.h> #include <util/util.h> namespace HPHP { /////////////////////////////////////////////////////////////////////////////// JumpTable::JumpTable(CodeGenerator &cg, const vector<const char*> &keys, bool caseInsensitive, bool hasPrehash, bool useString, bool quiet /* = false */) : m_cg(cg), m_subIter(0), m_quiet(quiet) { if (keys.empty()) { m_size = 0; m_iter = m_table.end(); return; } int tableSize = m_size = Util::roundUpToPowerOfTwo(keys.size() * 2); CodeGenerator::BuildJumpTable(keys, m_table, tableSize, caseInsensitive); m_iter = m_table.begin(); if (!quiet) { if (hasPrehash) { m_cg_printf("if (hash < 0) "); } else { m_cg_printf("int64 "); } if (useString) { m_cg_printf("hash = s->hash();\n"); } else { m_cg_printf("hash = hash_string(s);\n"); } m_cg.printStartOfJumpTable(tableSize); if (ready()) { m_cg_indentBegin("case %d:\n", m_iter->first); } } } void JumpTable::next() { assert(ready()); m_subIter++; if (m_subIter >= m_iter->second.size()) { m_subIter = 0; ++m_iter; if (!m_quiet) { m_cg_indentEnd(" break;\n"); if (m_iter == m_table.end()) { m_cg_printf("default:\n"); m_cg_printf(" break;\n"); m_cg_indentEnd("}\n"); } else { m_cg_indentBegin("case %d:\n", m_iter->first); } } } } int JumpTable::current() const { return m_iter->first; } bool JumpTable::last() const { assert(ready()); return m_subIter + 1 == m_iter->second.size(); } bool JumpTable::ready() const { return m_iter != m_table.end(); } const char *JumpTable::key() const { return m_iter->second.at(m_subIter); } /////////////////////////////////////////////////////////////////////////////// }
22,284
https://github.com/alialfredji/fia/blob/master/src/index.js
Github Open Source
Open Source
MIT
2,020
fia
alialfredji
JavaScript
Code
241
553
/** * Browser Entry Point * ------------------- * * This code runs in the browser only and you can count on that. * */ import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { Router } from 'react-router-dom' import { LocaleProvider } from '@forrestjs/feature-locale/client' // project specific modules import * as serviceWorker from './serviceWorker' import App from './App' import { createState } from './app.state' import './locale' import './index.css' /** * It's likely that the server will provide the production `initialState`` * via the global variable. * * Here you can provide some static state for development pourpose. * Anyway, it's best if you set it up as `defaultState` in each reducer */ const initialState = window.SERVER_DATA || {} // createMemoryHistory | createHashHistory | createBrowserHistory const history = require('history').createBrowserHistory() // eslint-disable-next-line const Root = ({ store, history, ...props }) => ( <Router history={history}> <Provider store={store}> <LocaleProvider> <App {...props} /> </LocaleProvider> </Provider> </Router> ) const boot = props => { const renderApp = () => { const root = <Root {...props} /> const target = document.querySelector('#root') ReactDOM.render(root, target) } if (module.hot) { module.hot.accept(renderApp) } renderApp() } createState(initialState, history) .then(boot) // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA // serviceWorker.unregister(); .then(() => process.env.NODE_ENV === 'production' ? serviceWorker.register() : serviceWorker.unregister() ) .catch(err => console.error(err))
49,260
https://github.com/controversial/luk.ke/blob/master/src/styles/dimensions.sass
Github Open Source
Open Source
MIT
2,021
luk.ke
controversial
Sass
Code
6
27
$menu-width: 380px $nav-height: 80px $mobile-nav-height: 60px
14,779
https://github.com/CodeMySky/KDD99/blob/master/kdd.r
Github Open Source
Open Source
MIT
null
KDD99
CodeMySky
R
Code
29
663
data = read.table("kddcup.data_10_percent", sep="," , col.names=c("duration","protocol_type","service","flag","src_bytes","dst_bytes","land", "wrong_fragment","urgent","hot","num_failed_logins","logged_in","num_compromised", "root_shell","su_attempted","num_root","num_file_creations","num_shells","num_access_files", "num_outbound_cmds","is_host_login","is_guest_login","count","srv_count","serror_rate", "srv_serror_rate","rerror_rate","srv_rerror_rate","same_srv_rate","diff_srv_rate", "srv_diff_host_rate","dst_host_count","dst_host_srv_count","dst_host_same_srv_rate", "dst_host_diff_srv_rate","dst_host_same_src_port_rate","dst_host_srv_diff_host_rate", "dst_host_serror_rate","dst_host_srv_serror_rate","dst_host_rerror_rate","dst_host_srv_rerror_rate","label"), colClasses=c(label="character",protocol_type="factor", service="factor")) data[1,'label'] == "normal."; label_distribution = table(data$label); as.data.frame(label_distribution) library(rpart) fit <- rpart(label ~ duration+protocol_type+service+flag+src_bytes+dst_bytes+land+wrong_fragment+urgent+hot+num_failed_logins+logged_in+num_compromised+root_shell+su_attempted+num_root+num_file_creations+num_shells+num_access_files+num_outbound_cmds+is_host_login+is_guest_login+count+srv_count+serror_rate+srv_serror_rate+rerror_rate+srv_rerror_rate+same_srv_rate+diff_srv_rate+srv_diff_host_rate+dst_host_count+dst_host_srv_count+dst_host_same_srv_rate+dst_host_diff_srv_rate+dst_host_same_src_port_rate+dst_host_srv_diff_host_rate+dst_host_serror_rate+dst_host_srv_serror_rate+dst_host_rerror_rate+dst_host_srv_rerror_rate,method="class", data=data)
50,726
https://github.com/Yusuf007R/urlShortener/blob/master/frontend/src/services/getDataAPI/index.js
Github Open Source
Open Source
WTFPL
null
urlShortener
Yusuf007R
JavaScript
Code
94
236
import handleError from "../../utils/handleError"; import request from "../../utils/request"; const getShortLinks = async (params) => { try { const result = await request({ method: "get", url: "/getshortlinks", params: { page: params.page || 1, limit: params.limit || 10, }, }); if (result.status === 200) { return result.data; } } catch (error) { return handleError(error.response); } }; const getUserData = async () => { try { const result = await request({ method: "get", url: "/getuserdata", }); if (result.status === 200) { return result.data; } } catch (error) { return handleError(error.response); } }; export { getShortLinks, getUserData };
20,692
https://github.com/subanzafar/graphenee/blob/master/gx/gx-flow/src/main/java/io/graphenee/vaadin/flow/security/GxSecurityGroupListView.java
Github Open Source
Open Source
Apache-2.0
2,021
graphenee
subanzafar
Java
Code
69
317
package io.graphenee.vaadin.flow.security; import com.vaadin.flow.component.HasComponents; import com.vaadin.flow.router.AfterNavigationEvent; import org.springframework.beans.factory.annotation.Autowired; import io.graphenee.core.model.bean.GxNamespaceBean; import io.graphenee.vaadin.flow.base.GxSecuredView; import io.graphenee.vaadin.flow.base.GxVerticalLayoutView; @GxSecuredView(GxSecurityGroupListView.VIEW_NAME) public class GxSecurityGroupListView extends GxVerticalLayoutView { private static final long serialVersionUID = 1L; public static final String VIEW_NAME = "security-groups"; @Autowired GxSecurityGroupList list; @Autowired(required = false) GxNamespaceBean namespace; @Override protected void decorateLayout(HasComponents rootLayout) { rootLayout.add(list); } @Override public void afterNavigation(AfterNavigationEvent event) { list.initializeWithNamespace(namespace); } @Override protected String getCaption() { return "Security Groups"; } }
16,398
https://github.com/Raiffeisen-DGTL/ViennaUI/blob/master/workspaces/deprecated-icons/src/IceCream/IceCream.tsx
Github Open Source
Open Source
MIT
2,022
ViennaUI
Raiffeisen-DGTL
TypeScript
Code
155
536
import React, { SVGAttributes } from 'react'; export interface IceCreamProps extends SVGAttributes<SVGElement> { [key: string]: any; size?: 'xs' | 's' | 'm' | 'l' | 'xl' | number; color?: string; } const sizes = { xs: 12, s: 16, m: 20, l: 24, xl: 32 }; export const IceCream: React.FC<IceCreamProps> = (props): JSX.Element => { const { color = 'currentColor', size = 'm', ...attrs } = props; const d = sizes[size] || size; return ( <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width={d} height={d} fill={color} {...attrs}> <defs /> <path d='M8.753 17.66l-5.04 5.04-1.415-1.414 5.033-5.032-.661-.654a3.31 3.31 0 010-4.68l7-7a3.31 3.31 0 014.68 0l2.73 2.73a3.31 3.31 0 010 4.68l-7 7a3.31 3.31 0 01-2.34.97 3.33 3.33 0 01-2.34-1l-.647-.64zM16 5a1.33 1.33 0 00-.93.38l-7 7a1.32 1.32 0 000 1.86l2.73 2.73a1.32 1.32 0 001.86 0l7-7a1.32 1.32 0 000-1.86l-2.73-2.77A1.33 1.33 0 0016 5zm-3.707 4.292l2.998-2.998 1.414 1.414-2.998 2.998-1.414-1.414z' /> </svg> ); }; IceCream.defaultProps = { size: 'm', color: 'currentColor', }; IceCream.displayName = 'IceCream'; export default IceCream;
29,664
https://github.com/japaric/syscall.rs/blob/master/src/lib.rs
Github Open Source
Open Source
Apache-2.0, MIT
2,022
syscall.rs
japaric
Rust
Code
328
1,118
// Copyright 2014 The syscall.rs Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Raw system calls for Rust. //! //! NOTE: Only these architectures have been ported to the stable (as of 1.59) `asm!` macro //! //! - aarch64 //! - riscv64 //! - x86_64 //! //! All the other architectures use the deprecated `llvm_asm!` macro which has already been removed. //! To use this crate with those architectures you'll need to use an older nightly like //! `nightly-2022-01-14` // Reference http://man7.org/linux/man-pages/man2/syscall.2.html #![allow(deprecated)] // llvm_asm! #![deny(warnings)] #![no_std] #![cfg_attr(any( target_arch = "arm", target_arch = "mips", target_arch = "mips64", target_arch = "powerpc", target_arch = "powerpc64", target_arch = "sparc64", target_arch = "x86" ), feature(llvm_asm))] #[cfg(test)] extern crate std; pub use platform::*; pub mod macros; #[cfg(all(any(target_os = "linux", target_os = "android"), target_arch = "aarch64"))] #[path="platform/linux-aarch64/mod.rs"] pub mod platform; #[cfg(all(any(target_os = "linux", target_os = "android"), target_arch = "arm"))] #[path="platform/linux-armeabi/mod.rs"] pub mod platform; #[cfg(all(any(target_os = "linux", target_os = "android"), target_arch = "mips"))] #[path="platform/linux-mips/mod.rs"] pub mod platform; #[cfg(all(any(target_os = "linux", target_os = "android"), target_arch = "mips64"))] #[path="platform/linux-mips64/mod.rs"] pub mod platform; #[cfg(all(any(target_os = "linux", target_os = "android"), target_arch = "powerpc"))] #[path="platform/linux-powerpc/mod.rs"] pub mod platform; #[cfg(all(any(target_os = "linux", target_os = "android"), target_arch = "powerpc64"))] #[path="platform/linux-powerpc64/mod.rs"] pub mod platform; #[cfg(all(any(target_os = "linux", target_os = "android"), target_arch = "riscv64"))] #[path="platform/linux-riscv64/mod.rs"] pub mod platform; #[cfg(all(any(target_os = "linux", target_os = "android"), target_arch = "sparc64"))] #[path="platform/linux-sparc64/mod.rs"] pub mod platform; #[cfg(all(any(target_os = "linux", target_os = "android"), target_arch = "x86"))] #[path="platform/linux-x86/mod.rs"] pub mod platform; #[cfg(all(any(target_os = "linux", target_os = "android"), target_arch = "x86_64"))] #[path="platform/linux-x86_64/mod.rs"] pub mod platform; #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))] #[path="platform/freebsd-x86_64/mod.rs"] pub mod platform; #[cfg(all(target_os = "macos", target_arch = "x86_64"))] #[path="platform/macos-x86_64/mod.rs"] pub mod platform; #[cfg(all(target_os = "macos", target_arch = "aarch64"))] #[path="platform/macos-aarch64/mod.rs"] pub mod platform;
14,111
https://github.com/AstR0x/bonch-lab/blob/master/client/src/features/auth/constants.ts
Github Open Source
Open Source
MIT
2,021
bonch-lab
AstR0x
TypeScript
Code
12
28
/** * Соль для шифрования пароля */ export const SALT = 'bonch-lab';
36,799
https://github.com/apache/incubator-taverna-server/blob/master/taverna-server-webapp/src/main/java/org/apache/taverna/server/master/worker/VelocityCompletionNotifier.java
Github Open Source
Open Source
Apache-2.0
2,021
incubator-taverna-server
apache
Java
Code
379
1,079
package org.apache.taverna.server.master.worker; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.StringWriter; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.springframework.beans.factory.annotation.Required; import org.apache.taverna.server.master.common.version.Version; import org.apache.taverna.server.master.exceptions.NoListenerException; import org.apache.taverna.server.master.interfaces.Listener; import org.apache.taverna.server.master.interfaces.UriBuilderFactory; public class VelocityCompletionNotifier implements CompletionNotifier { private String subject; private VelocityEngine engine; private Template template; private String name; private String templateName; private UriBuilderFactory ubf; @Override public String getName() { return name; } /** * @param subject * The subject of the notification email. */ @Required public void setSubject(String subject) { this.subject = subject; } /** * @param engine * The configured Apache Velocity engine. */ @Required public void setVelocityEngine(VelocityEngine engine) { this.engine = engine; } /** * @param uriBuilderFactory * The configured URI builder factory. */ @Required public void setUriBuilderFactory(UriBuilderFactory uriBuilderFactory) { this.ubf = uriBuilderFactory; } /** * @param name * The name of the template. */ @Required public void setName(String name) { this.name = name; this.templateName = getClass().getName() + "_" + name + ".vtmpl"; } private Template getTemplate() { if (template == null) synchronized(this) { if (template == null) template = engine.getTemplate(templateName); } return template; } @Override public String makeCompletionMessage(String name, RemoteRunDelegate run, int code) { VelocityContext ctxt = new VelocityContext(); ctxt.put("id", name); ctxt.put("uriBuilder", ubf.getRunUriBuilder(run)); ctxt.put("name", run.getName()); ctxt.put("creationTime", run.getCreationTimestamp()); ctxt.put("startTime", run.getStartTimestamp()); ctxt.put("finishTime", run.getFinishTimestamp()); ctxt.put("expiryTime", run.getExpiry()); ctxt.put("serverVersion", Version.JAVA); for (Listener l : run.getListeners()) if (l.getName().equals("io")) { for (String p : l.listProperties()) try { ctxt.put("prop_" + p, l.getProperty(p)); } catch (NoListenerException e) { // Ignore... } break; } StringWriter sw = new StringWriter(); getTemplate().merge(ctxt, sw); return sw.toString(); } @Override public String makeMessageSubject(String name, RemoteRunDelegate run, int code) { return subject; } }
45,094
https://github.com/itstack-naive-chat/itstack-naive-chat-server/blob/master/itstack-naive-chat-server-ddd/src/main/java/org/itstack/naive/chat/infrastructure/dao/IUserDao.java
Github Open Source
Open Source
Apache-2.0
2,021
itstack-naive-chat-server
itstack-naive-chat
Java
Code
48
251
package org.itstack.naive.chat.infrastructure.dao; import org.apache.ibatis.annotations.Mapper; import org.itstack.naive.chat.domain.inet.model.ChannelUserReq; import org.itstack.naive.chat.infrastructure.po.User; import java.util.List; /** * 博 客:http://bugstack.cn * 公众号:bugstack虫洞栈 | 沉淀、分享、成长,让自己和他人都能有所收获! * create by 小傅哥 on @2020 */ @Mapper public interface IUserDao { String queryUserPassword(String userId); User queryUserById(String userId); List<User> queryFuzzyUserList(String userId, String searchKey); Long queryChannelUserCount(ChannelUserReq req); List<User> queryChannelUserList(ChannelUserReq req); }
11,430
https://github.com/Miky91/Herolve/blob/master/HeRolve/web/php/inc/modelo/edificios.php
Github Open Source
Open Source
MIT
null
Herolve
Miky91
PHP
Code
171
771
<?php class Edificio{ public $id; public $clase_edificio; public $clase_recurso; public $valormadera; public $valorpiedra; public $valormetal; public $valorcomida; public $valorrubies; public $descripcion; public $nombre; public $exponente; public $cantidad; public function __construct (/*$id, $clase_edificio, $clase_recurso,$valormadera , $valorpiedra, $valormetal, $valorcomida, $valorrubies, $descripcion, $nombre, $exponenten, $cantidad*/){ /*$this->id = $id; $this->clase_edificio = $clase_edificio; $this->clase_recurso = $clase_recurso; $this->valormadera = $valormadera; $this->valorpiedra = $valorpiedra; $this->valormetal = $valormetal; $this->valorcomida = $valorcomida; $this->valoreubies = $valorrubies; $this->descripcion = $descripcion; $this->nombre = $nombre; $this->exponenten = $exponenten; $this->cantidad = $cantidad;*/ } public function setId($id){ $this->id=$id; } public function setClaseEdificio($clase_edificio){ $this->clase_edificio = $clase_edificio; } public function setClaseRecurso($clase_recurso){ $this->clase_recurso = $clase_recurso; } public function setValor($valor){ $this->valor = $valor; } public function setDescripcion($descripcion){ $this->descripcion = $descripcion; } public function setNombre($nombre){ $this->nombre = $nombre; } public function setCantidad ($cantidad){ $this->cantidad = $cantidad; } public function getId(){ return $this->id; } public function getClaseEdificio(){ return $this->clase_edificio; } public function getClaseRecurso(){ return $this->clase_recurso; } public function getValor(){ return $this->valor; } public function getDescripcion(){ return $this->descripcion; } public function getNombre(){ return $this->nombre; } public function getCantidad (){ return $this->cantidad; } }
16,424
https://github.com/Helmut-Ortmann/Enterprise-Architect-VBScript-Library/blob/master/Projects/Hotellio Scripts/Project Browser Group/Link to Domain Model.vbs
Github Open Source
Open Source
BSD-2-Clause
2,016
Enterprise-Architect-VBScript-Library
Helmut-Ortmann
VBScript
Code
1,533
3,858
option explicit !INC Local Scripts.EAConstants-VBScript ' ' Script Name: Link to Domain Model ' Author: Geert Bellekens ' Purpose: Link elements with classes in the domain model based on their name. ' Date: 15/11/2015 ' sub main 'let the user select the domain model package dim response response = Msgbox ("Please select the domain model package", vbOKCancel+vbQuestion, "Selecte domain model") if response = vbOK then dim domainModelPackage as EA.Package set domainModelPackage = selectPackage() if not domainModelPackage is nothing then Repository.CreateOutputTab "Link to Domain Model" Repository.ClearOutput "Link to Domain Model" Repository.EnsureOutputVisible "Link to Domain Model" 'link selected elements to the domain model elements linkSelectionToDomainModel(domainModelPackage) 'tell the user we are done Repository.WriteOutput "Link to Domain Model", "Finished!", 0 end if end if end sub 'this is the actual call to the main function main function linkSelectionToDomainModel(domainModelPackage) 'first get the pattern from all the classes in the domain model dim dictionary Set dictionary = CreateObject("Scripting.Dictionary") 'create domain model dictionary 'tell the user what we are doing Repository.WriteOutput "Link to Domain Model", "Creating domain model dictionary", 0 addToClassDictionary domainModelPackage.PackageGUID, dictionary 'tell the user what we are doing Repository.WriteOutput "Link to Domain Model", "Interpreting dictionary", 0 ' and prepare the regex object dim pattern 'create the pattern based on the names in the dictionary pattern = createRegexPattern(dictionary) Dim regExp Set regExp = CreateObject("VBScript.RegExp") regExp.Global = True regExp.IgnoreCase = False regExp.Pattern = pattern ' Get the type of element selected in the Project Browser dim treeSelectedType treeSelectedType = Repository.GetTreeSelectedItemType() ' Either process the selected Element, or process all elements in the selected package select case treeSelectedType case otElement ' Code for when an element is selected dim selectedElements as EA.Collection set selectedElements = Repository.GetTreeSelectedElements() 'link the selected elements with the linkDomainClassesWithElements dictionary,regExp,selectedElements case otPackage ' Code for when a package is selected dim selectedPackage as EA.Package set selectedpackage = Repository.GetTreeSelectedObject() 'link use domain classes with the elements in the selected package linkDomainClassesWithElementsInPackage dictionary, regExp,selectedPackage case else ' Error message Session.Prompt "You have to select Elements or a Package", promptOK end select end function 'this function will get all elements in the given package and subpackages recursively and link them to the domain classes function linkDomainClassesWithElementsInPackage(dictionary,regExp,selectedPackage) dim packageList set packageList = getPackageTree(selectedPackage) dim packageIDString packageIDString = makePackageIDString(packageList) dim getElementsSQL getElementsSQL = "select o.Object_ID from t_object o where o.Package_ID in (" & packageIDString & ")" dim usecases set usecases = getElementsFromQuery(getElementsSQL) linkDomainClassesWithElements dictionary,regExp,usecases end function function linkDomainClassesWithElements(dictionary,regExp,elements) dim element as EA.Element 'loop de elements for each element in elements 'tell the user what we are doing Repository.WriteOutput "Link to Domain Model", "Linking element: " & element.Name, 0 'first remove all automatic traces removeAllAutomaticTraces element 'match based on notes and linked document dim elementText 'get full text (name +notes + linked document + scenario names + scenario notes) elementText = element.Name elementText = elementText & vbNewLine & Repository.GetFormatFromField("TXT",element.Notes) elementText = elementText & vbNewLine & getLinkedDocumentContent(element, "TXT") elementText = elementText & vbNewLine & getTextFromScenarios(element) dim matches set matches = regExp.Execute(elementText) 'for each match create a «trace» link with the element linkMatchesWithelement matches, element, dictionary 'link based on text in scenariosteps dim scenario as EA.Scenario 'get all dependencies left dim dependencies set dependencies = getDependencies(element) 'loop scenarios for each scenario in element.Scenarios dim scenarioStep as EA.ScenarioStep for each scenarioStep in scenario.Steps 'first remove any additional terms in the uses field scenarioStep.Uses = removeAddionalUses(dependencies, scenarioStep.Uses) set matches = regExp.Execute(scenarioStep.Name) dim classesToMatch set classesToMatch = getClassesToMatchDictionary(matches, dictionary) dim classToMatch as EA.Element for each classToMatch in classesToMatch.Items if not instr(scenarioStep.Uses,classToMatch.Name) > 0 then scenarioStep.Uses = scenarioStep.Uses & " " & classToMatch.Name end if 'create the dependency between the use case and the domain model class linkElementsWithAutomaticTrace element, classToMatch next 'save scenario step scenarioStep.Update scenario.Update next next next end function function linkMatchesWithelement(matches, element, dictionary) dim classesToMatch 'get the classes to match Set classesToMatch = getClassesToMatchDictionary(matches,dictionary) dim classToMatch as EA.Element 'actually link the classes for each classToMatch in classesToMatch.Items linkElementsWithAutomaticTrace element, classToMatch next end function 'get the text from the scenarios name and notes function getTextFromScenarios(element) dim scenario as EA.Scenario dim scenarioText scenarioText = "" for each scenario in element.Scenarios scenarioText = scenarioText & vbNewLine & scenario.Name scenarioText = scenarioText & vbNewLine & Repository.GetFormatFromField("TXT",scenario.Notes) next getTextFromScenarios = scenarioText end function function removeAddionalUses(dependencies, uses) dim dependency dim filteredUses filteredUses = "" if len(uses) > 0 then for each dependency in dependencies.Keys if Instr(uses,dependency) > 0 then if len(filteredUses) > 0 then filteredUses = filteredUses & " " & dependency else filteredUses = dependency end if end if next end if removeAddionalUses = filteredUses end function 'returns a dictionary of elements with the name as key and the element as value. function getDependencies(element) dim getDependencySQL getDependencySQL = "select dep.Object_ID from ( t_object dep " & _ " inner join t_connector con on con.End_Object_ID = dep.Object_ID) " & _ " where con.Connector_Type = 'Dependency' " & _ " and con.Start_Object_ID = " & element.ElementID set getDependencies = getElementDictionaryFromQuery(getDependencySQL) end function function removeAllAutomaticTraces(element) dim i dim connector as EA.Connector 'remove all the traces to domain model classes for i = element.Connectors.Count -1 to 0 step -1 set connector = element.Connectors.GetAt(i) if connector.Alias = "automatic" and connector.Stereotype = "trace" then element.Connectors.DeleteAt i,false end if next end function function getClassesToMatchDictionary(matches, allClassesDictionary) dim match dim classesToMatch dim className Set classesToMatch = CreateObject("Scripting.Dictionary") 'create list of elements to link For each match in matches if not allClassesDictionary.Exists(match.Value) then 'strip the last 's' className = left(match.Value, len(match.Value) -1) else className = match.Value end if if not classesToMatch.Exists(className) then classesToMatch.Add className, allClassesDictionary(className) end if next set getClassesToMatchDictionary = classesToMatch end function 'Create a «trace» relation between source and target with "automatic" as alias function linkElementsWithAutomaticTrace(sourceElement, targetElement) dim linkExists linkExists = false 'first make sure there isn't already a trace relation between the two dim existingConnector as EA.Connector 'make sure we are using the up-to-date connectors collection sourceElement.Connectors.Refresh for each existingConnector in sourceElement.Connectors if existingConnector.SupplierID = targetElement.ElementID _ and existingConnector.Stereotype = "trace" then linkExists = true exit for end if next if not linkExists then 'tell the user what we are doing Repository.WriteOutput "Link to Domain Model", "Adding trace between " &sourceElement.Name & " and " & targetElement.Name, 0 dim trace as EA.Connector set trace = sourceElement.Connectors.AddNew("","trace") trace.Alias = "automatic" trace.SupplierID = targetElement.ElementID trace.Update end if end function function addToClassDictionary(PackageGUID, dictionary) dim package as EA.Package set package = Repository.GetPackageByGuid(PackageGUID) 'get the classes in the dictionary (recursively addClassesToDictionary package, dictionary end function function addClassesToDictionary(package, dictionary) dim classElement as EA.Element dim subpackage as EA.Package 'process owned elements for each classElement in package.Elements if classElement.Type = "Class" AND len(classElement.Name) > 0 AND not dictionary.Exists(classElement.Name) then dictionary.Add classElement.Name, classElement end if next 'process subpackages for each subpackage in package.Packages addClassesToDictionary subpackage, dictionary next end function 'Create a reges pattern like this "\b(name1|name2|name3)\b" based on the function createRegexPattern(dictionary) Dim patternString dim className 'add begin patternString = "\b(" dim addPipe addPipe = FALSE for each className in dictionary.Keys if addPipe then patternString = patternString & "|" else addPipe = True end if patternString = patternString & className next 'add end patternString = patternString & ")s?\b" 'return pattern createRegexPattern = patternString end function 'returns an ArrayList of the given package and all its subpackages recursively function getPackageTree(package) dim packageList set packageList = CreateObject("System.Collections.ArrayList") addPackagesToList package, packageList set getPackageTree = packageList end function 'make an id string out of the package ID of the given packages function makePackageIDString(packages) dim package as EA.Package dim idString idString = "" dim addComma addComma = false for each package in packages if addComma then idString = idString & "," else addComma = true end if idString = idString & package.PackageID next 'if there are no packages then we return "0" if packages.Count = 0 then idString = "0" end if 'return idString makePackageIDString = idString end function 'returns an ArrayList with the elements accordin tot he ObjectID's in the given query function getElementsFromQuery(sqlQuery) dim elements set elements = Repository.GetElementSet(sqlQuery,2) dim result set result = CreateObject("System.Collections.ArrayList") dim element for each element in elements result.Add Element next set getElementsFromQuery = result end function 'returns a dictionary of all elements in the query with their name as key, and the element as value. 'for elements with the same name only one will be returned function getElementDictionaryFromQuery(sqlQuery) dim elements set elements = Repository.GetElementSet(sqlQuery,2) dim result set result = CreateObject("Scripting.Dictionary") dim element for each element in elements if not result.Exists(element.Name) then result.Add element.Name, element end if next set getElementDictionaryFromQuery = result end function 'gets the content of the linked document in the given format (TXT, RTF or EA) function getLinkedDocumentContent(element, format) dim linkedDocumentRTF dim linkedDocumentEA dim linkedDocumentPlainText linkedDocumentRTF = element.GetLinkedDocument() if format = "RTF" then getLinkedDocumentContent = linkedDocumentRTF else linkedDocumentEA = Repository.GetFieldFromFormat("RTF",linkedDocumentRTF) if format = "EA" then getLinkedDocumentContent = linkedDocumentEA else linkedDocumentPlainText = Repository.GetFormatFromField("TXT",linkedDocumentEA) getLinkedDocumentContent = linkedDocumentPlainText end if end if end function 'let the user select a package function selectPackage() dim documentPackageElementID documentPackageElementID = Repository.InvokeConstructPicker("IncludedTypes=Package") if documentPackageElementID > 0 then dim packageElement as EA.Element set packageElement = Repository.GetElementByID(documentPackageElementID) dim package as EA.Package set package = Repository.GetPackageByGuid(packageElement.ElementGUID) else set package = nothing end if set selectPackage = package end function 'add the given package and all subPackges to the list (recursively function addPackagesToList(package, packageList) dim subPackage as EA.Package 'add the package itself packageList.Add package 'add subpackages for each subPackage in package.Packages addPackagesToList subPackage, packageList next end function
10,250
https://github.com/taiyakikatsuto/waniwani/blob/master/backend/resources/views/ranking.blade.php
Github Open Source
Open Source
MIT
null
waniwani
taiyakikatsuto
PHP
Code
279
1,614
@extends('layouts.app') @section('content') @include('elements.navigation') @include('elements.header') <!-- Main Content --> <div class="container"> <div class="row"> <div class="col-lg-8 col-md-10 mx-auto"> <div class="card-header"> <h2>本日のスゴウデ</h2> </div> <table class="table table-bordered table-hover"> <thead class="thead-light"> <tr> <th class="text-nowrap">順位</th> <th class="text-nowrap">名前</th> <th class="text-nowrap">とくてん</th> <th class="text-nowrap">かまれた数</th> <th class="text-nowrap">あそんだ場所</th> <th class="text-nowrap">写真</th> </tr> </thead> <tbody> <tr> <td>1位</td> <td>ワニ子</td> <td>154点</td> <td>0回</td> <td>東京都</td> <td><i class="far fa-image"></i></td> </tr> @if($rankings_today->count()) @php $i = 2; @endphp @foreach ($rankings_today as $ranking_today) <tr> <td>{{$i}}位</td> <td>{{ $ranking_today->user->name }}</td> <td>{{ $ranking_today->point }}点</td> <td>{{ $ranking_today->bitten }}回</td> <td>{{ config('consts.pref')[$ranking_today->user->pref] }}</td> <td> @isset($ranking_today->file_name) @if ($ranking_today->file_name !== '#') <a href="{{ asset('storage/img/' . $ranking_today->file_name) }}" data-toggle="modal" data-target="#testModal"> <i class="far fa-image"></i> </a> <div class="d-none"> <img src="{{ asset('storage/img/' . $ranking_today->file_name) }}" id="imageresource"> </div> @endif @endisset </td> </tr> @php $i++; @endphp @endforeach @endif </tbody> </table> </div> </div> <div class="row"> <div class="col-lg-8 col-md-10 mx-auto"> <div class="card-header"> <h2>歴代のスゴウデ</h2> </div> <table class="table table-bordered table-hover"> <thead class="thead-light"> <tr> <th class="text-nowrap">順位</th> <th class="text-nowrap">名前</th> <th class="text-nowrap">とくてん</th> <th class="text-nowrap">かまれた数</th> <th class="text-nowrap">あそんだ場所</th> <th class="text-nowrap">写真</th> </tr> </thead> <tbody> <tr> <td>1位</td> <td>ワニ子</td> <td>154点</td> <td>0回</td> <td>東京都</td> <td><i class="far fa-image"></i></td> </tr> @if($rankings_all->count()) @php $i = 2; @endphp @foreach ($rankings_all as $ranking_all) <tr> <td>{{$i}}位</td> <td>{{ $ranking_all->user->name }}</td> <td>{{ $ranking_all->point }}点</td> <td>{{ $ranking_all->bitten }}回</td> <td>{{ config('consts.pref')[$ranking_today->user->pref] }}</td> @php $i++; $img = '<img src="' . "{{ asset('storage/img/' . $ranking_today->file_name) }}" . '">'; @endphp <td> @isset($ranking_today->file_name) @if ($ranking_today->file_name !== '#') <a href="{{ asset('storage/img/' . $ranking_today->file_name) }}" data-toggle="modal" data-target="#testModal" data-img="{{ $img }}"> <i class="far fa-image"></i> </a> @endif @endisset </td> </tr> @endforeach @endif </tbody> </table> </div> </div> </div> <div class="modal fade" id="testModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4><div class="modal-title" id="myModalLabel">そのときの写真</div></h4> <p class="notice_date">test</p> </div> <div class="modal-body"> <div class="w-auto"> <img id="imagepreview" class="img-fluid img-rounded" src="{{ asset('storage/img/' . $ranking_today->file_name) }}"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-info" data-dismiss="modal">閉じる</button> </div> </div> </div> </div> @include('elements.footer') @endsection
3,997
https://github.com/London-Trading-Institute/gatsby-business-starter/blob/master/src/components/Services/Services.js
Github Open Source
Open Source
MIT
null
gatsby-business-starter
London-Trading-Institute
JavaScript
Code
73
381
import React from 'react' import {ServicesContainer, ServicesLabel, ServicesCard, ServicesTitle, ServicesDescription, ServiceTypeContainer, ServiceTypeIndex, ServiceType} from './Services.elements'; const Services = () => { return ( <ServicesContainer> <ServicesLabel> -- services </ServicesLabel> <ServicesCard> <ServicesTitle> We shape the life of tomorrow </ServicesTitle> <ServicesDescription> <ServiceTypeContainer> <ServiceTypeIndex>01/</ServiceTypeIndex> <ServiceType>architecture</ServiceType> </ServiceTypeContainer> <ServiceTypeContainer> <ServiceTypeIndex>02/</ServiceTypeIndex> <ServiceType>landscape design</ServiceType> </ServiceTypeContainer> <ServiceTypeContainer> <ServiceTypeIndex>03/</ServiceTypeIndex> <ServiceType>pavement design</ServiceType> </ServiceTypeContainer> <ServiceTypeContainer> <ServiceTypeIndex>04/</ServiceTypeIndex> <ServiceType>interior</ServiceType> </ServiceTypeContainer> <ServiceTypeContainer> <ServiceTypeIndex>05/</ServiceTypeIndex> <ServiceType>graphic design</ServiceType> </ServiceTypeContainer> <ServiceTypeContainer> <ServiceTypeIndex>06/</ServiceTypeIndex> <ServiceType>exterior</ServiceType> </ServiceTypeContainer> </ServicesDescription> </ServicesCard> </ServicesContainer> ) } export default Services
25,293
https://github.com/wuyafei/featherbed/blob/master/featherbed-core/src/main/scala/featherbed/support/package.scala
Github Open Source
Open Source
MIT, LicenseRef-scancode-warranty-disclaimer, Apache-2.0
2,016
featherbed
wuyafei
Scala
Code
136
332
package featherbed import shapeless.labelled.FieldType import shapeless._, labelled.field import scala.annotation.implicitNotFound import scala.language.higherKinds package object support { @implicitNotFound("""In order to decode a request to ${A}, it must be known that a decoder exists to ${A} from all the content types that you Accept, which is currently ${ContentTypes}. You may have forgotten to specify Accept types with the `accept[T <: Coproduct]` method, or you may be missing Decoder instances for some content types. """) sealed trait DecodeAll[A, ContentTypes <: Coproduct] { val instances: List[content.Decoder.Aux[_, A]] } object DecodeAll { implicit def cnil[A] : DecodeAll[A, CNil] = new DecodeAll[A, CNil] { val instances = Nil } implicit def ccons[H, A, T <: Coproduct](implicit headInstance: content.Decoder.Aux[H, A], tailInstances: DecodeAll[A, T]) : DecodeAll[A, H :+: T] = new DecodeAll[A, H :+: T] { val instances = headInstance :: tailInstances.instances } } }
10,800
https://github.com/wezm/f0-discovery/blob/master/src/examples/timeit.rs
Github Open Source
Open Source
Apache-2.0, MIT
null
f0-discovery
wezm
Rust
Code
117
315
// Auto-generated. Do not modify this file! Instead modify examples/timeit.rs //! Timing sections of code //! //! ``` rust,no_run //! #![no_main] //! #![no_std] //! //! #[macro_use] //! extern crate f3; //! //! use f3::timeit::FREQUENCY; //! use f3::{delay, timeit}; //! //! macro_rules! timeit { //! ($e:expr) => { //! let bias = timeit::timeit(|| {}); //! let ticks = timeit::timeit(|| $e) - bias; //! iprintln!("{} took {} ticks ({} s)", //! stringify!($e), //! ticks, //! ticks as f32 / FREQUENCY as f32); //! } //! } //! //! #[export_name = "main"] //! pub extern "C" fn main() -> ! { //! timeit!(delay::ms(1_000)); //! timeit!(iprintln!("Hello, world!")); //! timeit!(iprintln!("{}", 42)); //! timeit!(iprintln!("{}", core::f32::consts::PI)); //! //! loop {} //! } //! ```
41,755
https://github.com/jeffhammond/foMPI/blob/master/Makefile
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, BSD-3-Clause-Open-MPI
2,015
foMPI
jeffhammond
Makefile
Code
319
1,762
include Makefile.inc FOMPIOPTS= -DXPMEM -DNA -DNDEBUG LIBS=-Lmpitypes/install/lib -lmpitypes -ldmapp -Llibtopodisc -ltopodisc INC=-Impitypes/install/include -Ilibtopodisc CCFLAGS+=$(FOMPIOPTS) $(INC) FCFLAGS+=$(FOMPIOPTS) $(INC) CXXFLAGS+=$(FOMPIOPTS) $(INC) OBJS = \ fompi_fortran.o \ fompi_helper.o \ fompi_op.o \ fompi_overloaded.o \ fompi_win_allocate.o \ fompi_win_attr.o \ fompi_win_create.o \ fompi_win_dynamic_create.o \ fompi_win_fence.o \ fompi_win_free.o \ fompi_win_group.o \ fompi_win_lock.o \ fompi_win_name.o \ fompi_win_pscw.o \ fompi_win_rma.o \ module_fompi.o \ fompi_comm.o \ fompi_req.o \ fompi_notif.o \ fompi_seg.o \ fompi_notif_uq.o \ fompi_notif_xpmem.o EXE = \ c_test \ fortran_test_f77 \ fortran_test_f90 # some general rules all: fompi-na.ar $(EXE) clean: rm -f *.o fompi_op.c fompi-na.ar $(EXE) recursive-clean: clean make -C mpitypes clean rm -f mpitypes/install/lib/libmpitypes.a make -C libtopodisc clean distclean: clean rm -rf mpitypes make -C libtopodisc clean # libtopodisc.a is actual not a real dependency, but is here to ensure it is build fompi-na.ar: $(OBJS) libtopodisc/libtopodisc.a ar -r fompi-na.ar $(OBJS) ranlib fompi-na.ar c_test: c_test.o fompi-na.ar ${CC} ${CCFLAGS} ${LDFLAGS} -o $@ c_test.o fompi-na.ar ${LIBS} fortran_test_f77: fortran_test_f77.o fompi-na.ar ${FC} ${FCFLAGS} ${LDFLAGS} -o $@ fortran_test_f77.o fompi-na.ar ${LIBS} fortran_test_f90: fortran_test_f90.o fompi-na.ar ${FC} ${FCFLAGS} ${LDFLAGS} -o $@ fortran_test_f90.o fompi-na.ar ${LIBS} fompi_fortran.o: fompi.h fompi_helper.o: fompi_helper.c fompi.h fompi_op.o: fompi_op.c fompi.h fompi_op.c: fompi_op.c.m4 m4 fompi_op.c.m4 > fompi_op.c fompi_overloaded.o: fompi_overloaded.c fompi.h libtopodisc/libtopodisc.h fompi_win_allocate.o: fompi_win_allocate.c fompi.h fompi_win_attr.o: fompi_win_attr.c fompi.h fompi_win_create.o: fompi_win_create.c fompi.h fompi_win_dynamic_create.o: fompi_win_dynamic_create.c fompi.h fompi_win_fence.o: fompi_win_fence.c fompi.h fompi_win_free.o: fompi_win_free.c fompi.h fompi_win_group.o: fompi_win_group.c fompi.h fompi_win_lock.o: fompi_win_lock.c fompi.h fompi_win_name.o: fompi_win_name.c fompi.h fompi_win_pscw.o: fompi_win_pscw.c fompi.h fompi_win_rma.o: fompi_win_rma.c fompi.h mpitypes/install/include/mpitypes.h mpitypes/install/lib/libmpitypes.a fompi_comm.o: fompi_comm.c fompi.h fompi_req.o: fompi_req.c fompi.h fompi_notif.o: fompi_notif.c fompi.h fompi_notif_uq.o: fompi_notif_uq.c fompi_notif_uq.h fompi.h fompi_notif_xpmem.o: fompi_notif_xpmem.c fompi.h fompi_seg.o: fompi_seg.c fompi.h fompi.h: fompi_internal.h fompi.mod module_fompi.o: module_fompi.f90 $(FC) $(FCFLAGS) $(INC) -c $< # target to build mpitypes with a separate compiler mpitypes: mpitypes/install/include/mpitypes.h mpitypes/install/lib/libmpitypes.a mpitypes/install/include/mpitypes.h mpitypes/install/lib/libmpitypes.a: mpitypes.tar.bz2 tar xfj mpitypes.tar.bz2 find mpitypes/configure.ac -type f -print0 | xargs -0 sed -i 's/mpicc/$(cc)/g' cd mpitypes ; \ ./prepare ; \ ./configure --prefix=$(CURDIR)/mpitypes/install make -C mpitypes make -C mpitypes install cp mpitypes/mpitypes-config.h mpitypes/install/include cp mpitypes/src/dataloop/dataloop_create.h mpitypes/install/include # target to build mpitypes with a separate compiler libtopodisc: libtopodisc/libtopodisc.a libtopodisc/libtopodisc.a: libtopodisc/findcliques.c libtopodisc/findcliques.h libtopodisc/meshmap2d.c libtopodisc/libtopodisc.c make -C libtopodisc
28,446
https://github.com/Wicklets/Paper.js-Toolbox/blob/master/app/assets/config/wickeditor_manifest.js
Github Open Source
Open Source
MIT
2,018
Paper.js-Toolbox
Wicklets
JavaScript
Code
8
33
//= link_directory ../javascripts/wickeditor .js //= link_directory ../stylesheets/wickeditor .css
26,647
https://github.com/res-system/Boot-Camp/blob/master/src/mvc_skeleton/src/main/java/com/res_system/mvc_skeleton/model/top/TopForm.java
Github Open Source
Open Source
Apache-2.0
2,020
Boot-Camp
res-system
Java
Code
57
154
package com.res_system.mvc_skeleton.model.top; import com.res_system.commons.mvc.model.form.Param; public class TopForm { //---------------------------------------------- properies [private]. @Param private String code; @Param private String name; //-- setter / getter. --// public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
15,143
https://github.com/sleepyyyybear/thi-trac-nghiem/blob/master/ThiTracNghiem/frmSinhVien.cs
Github Open Source
Open Source
MIT
null
thi-trac-nghiem
sleepyyyybear
C#
Code
934
3,592
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using ThiTracNghiem.CMD; using ThiTracNghiem.DTO; namespace ThiTracNghiem { public partial class frmSinhVien : Form { private Stack<Command> _commands; private DataTable lop; public frmSinhVien() { InitializeComponent(); } private void frmSinhVien_Load(object sender, EventArgs e) { _commands = new Stack<Command>(); if (DBAccess.nhom == "Truong") { btnThem.Enabled = false; btnXoa.Enabled = false; comboBox2.Enabled = false; textBox2.Enabled = false; textBox3.Enabled = false; textBox4.Enabled = false; dateTimePicker1.Enabled = false; tableLayoutPanel2.Visible = true; LoadChiNhanhToCombo(); comboBox1.Text = DBAccess.chiNhanh; } btnReload.PerformClick(); dateTimePicker1.CustomFormat = "dd-MM-yyyy"; } private void LoadChiNhanhToCombo() { foreach (Connection cnn in DBAccess.CnnList) { if (cnn.Name != "Trường") comboBox1.Items.Add(cnn.Name); } comboBox1.SelectedIndex = 0; } private void AddLopToCombo() { lop = DBAccess.ExecuteQuery("SP_LayLopDonGian"); if (lop == null) { MessageBox.Show("Lỗi CDSL! Không thể lấy danh sách các lớp"); return; } else if (lop.Rows.Count == 0) { MessageBox.Show("Trong CSDL không có lớp nào. Vui lòng nhập thêm lớp trước khi nhập sinh viên."); return; } comboBox2.Items.Clear(); foreach (DataRow s in lop.Rows) { comboBox2.Items.Add(s[1]); } comboBox2.SelectedIndex = 0; } private void btnThem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { textBox1.Text = ""; textBox2.Text = ""; textBox3.Text = ""; textBox4.Text = ""; comboBox2.Text = ""; dateTimePicker1.Value = DateTime.Today; textBox1.Enabled = true; textBox3.Enabled = true; textBox4.Enabled = true; comboBox2.Enabled = true; dateTimePicker1.Enabled = true; comboBox2.SelectedIndex = 0; textBox2.Enabled = true; comboBox2.Enabled = true; btnLuu.Enabled = true; btnHuyBo.Enabled = true; } private int Execute(string _operator, DSinhVien _operand, DSinhVien oldstate) { Command command = new SinhVienCommand(_operator, _operand, oldstate); int code = command.Execute(); _commands.Push(command); btnUndo.Enabled = true; return code; } private void btnXoa_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { btnXoa.Enabled = false; DataRow red = gridView1.GetFocusedDataRow(); DSinhVien KHTrongBang = new DSinhVien { MaSV = red["Mã sinh viên"].ToString(), Ho = red["Họ"].ToString(), Ten = red["Tên"].ToString(), NgaySinh = DateTime.Parse(red["Ngày sinh"].ToString()), DiaChi = red["Địa chỉ"].ToString(), MaLop = lop.Select(string.Format("tenlop ='{0}'", red["Tên lớp"].ToString()))[0][0].ToString() }; int code = Execute("delete", KHTrongBang, null); if (code == 0) { //MessageBox.Show("Xoá sinh viên thành công"); btnReload.PerformClick(); } else MessageBox.Show("Xoá sinh viên thất bại."); } private void btnLuu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { btnLuu.Enabled = false; int noError = 0; string errors = "Nội dung bạn nhập có 1 số lỗi sau. Vui lòng sửa trước khi lưu."; if (textBox1.Text.Trim() == "") { //MessageBox.Show("Mã sinh viên không được bỏ trống"); errors += "\r\n+ Mã sinh viên bị bỏ trống"; noError++; } if (textBox2.Text.Trim() == "") { //MessageBox.Show("Họ không được bỏ trống"); errors += "\r\n+ Họ bị bỏ trống"; noError++; } if (textBox3.Text.Trim() == "") { //MessageBox.Show("Tên không được bỏ trống"); errors += "\r\n+ Tên bị bỏ trống"; noError++; } if (comboBox2.Text.Trim() == "") { //MessageBox.Show("Tên lớp không được bỏ trống. Vui lòng nhập thêm lớp hoặc kiểm tra lại CSDL"); errors += "\r\n+ Tên lớp không được bỏ trống.\r\nVui lòng nhập thêm lớp hoặc kiểm tra lại CSDL"; noError++; } if (dateTimePicker1.Value.Date > DateTime.Today.AddYears(18)) { ///MessageBox.Show("Chỉ được đăng ký lịch thi sau thời điểm hiện tại"); errors += "\r\n+ Ngày sinh không hợp lệ"; noError++; } if (noError > 0) { MessageBox.Show(errors); btnLuu.Enabled = true; return; } if (textBox1.Enabled) { DSinhVien KHTrongForm = new DSinhVien { MaSV = textBox1.Text.Trim().ToUpper(), Ho = textBox2.Text.Trim().ToUpper(), Ten = textBox3.Text.Trim().ToUpper(), NgaySinh = dateTimePicker1.Value, DiaChi = textBox4.Text.Trim(), MaLop = lop.Select(string.Format("tenlop ='{0}'", comboBox2.Text.Trim()))[0][0].ToString() }; int code = Execute("insert", KHTrongForm, null); if (code == 0) { btnReload.PerformClick(); //MessageBox.Show("Tạo sinh viên thành công"); } else { MessageBox.Show("Tạo sinh viên thất bại"); } textBox1.Enabled = false; } else { DataRow red = gridView1.GetFocusedDataRow(); DSinhVien KHTrongBang = new DSinhVien { MaSV = red["Mã sinh viên"].ToString(), Ho = red["Họ"].ToString(), Ten = red["Tên"].ToString(), NgaySinh = DateTime.Parse(red["Ngày sinh"].ToString()), DiaChi = red["Địa chỉ"].ToString(), MaLop = lop.Select(string.Format("tenlop ='{0}'", red["Tên lớp"].ToString()))[0][0].ToString() }; DSinhVien KHTrongForm = new DSinhVien { MaSV = textBox1.Text.Trim().ToUpper(), Ho = textBox2.Text.Trim().ToUpper(), Ten = textBox3.Text.Trim().ToUpper(), NgaySinh = dateTimePicker1.Value, DiaChi = textBox4.Text.Trim(), MaLop = lop.Select(string.Format("tenlop ='{0}'", comboBox2.Text.Trim()))[0][0].ToString() }; int code = Execute("update", KHTrongForm, KHTrongBang); if (code == 0) { btnReload.PerformClick(); //MessageBox.Show("Lưu sinh viên thành công"); } else { MessageBox.Show("Lưu sinh viên thất bại"); } } btnLuu.Enabled = true; } private void btnReload_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { DataTable lop = DBAccess.ExecuteQuery("SP_LaySinhVien"); gridControl1.DataSource = lop; if (gridView1.RowCount == 0) { textBox2.Enabled = false; textBox3.Enabled = false; textBox4.Enabled = false; comboBox2.Enabled = false; dateTimePicker1.Enabled = false; if (DBAccess.nhom != "Truong") btnXoa.Enabled = false; } else { FocusedRowChanged(); if (DBAccess.nhom != "Truong") btnXoa.Enabled = true; textBox2.Enabled = true; textBox3.Enabled = true; textBox4.Enabled = true; comboBox2.Enabled = true; dateTimePicker1.Enabled = true; } textBox1.Enabled = false; btnHuyBo.Enabled = false; btnLuu.Enabled = false; AddLopToCombo(); FocusedRowChanged(); } private void btnUndo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { if (_commands.Count > 0) { Command command = _commands.Pop(); int code = command.UnExecute(); if (code == 0) { btnReload.PerformClick(); //MessageBox.Show("Phục hồi thành công"); } else MessageBox.Show("Phục hồi thất bại."); if (_commands.Count == 0) btnUndo.Enabled = false; } } private void btnHuyBo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { if (gridView1.RowCount == 0) { textBox2.Enabled = false; textBox3.Enabled = false; textBox4.Enabled = false; comboBox2.Enabled = false; dateTimePicker1.Enabled = false; } else { textBox1.Text = gridView1.GetFocusedRowCellValue("Mã sinh viên").ToString(); textBox2.Text = gridView1.GetFocusedRowCellValue("Họ").ToString(); textBox3.Text = gridView1.GetFocusedRowCellValue("Tên").ToString(); textBox4.Text = gridView1.GetFocusedRowCellValue("Địa chỉ").ToString(); comboBox2.Text = gridView1.GetFocusedRowCellValue("Tên lớp").ToString(); dateTimePicker1.Value = DateTime.Parse(gridView1.GetFocusedRowCellValue("Ngày sinh").ToString()); } textBox1.Enabled = false; btnHuyBo.Enabled = false; btnLuu.Enabled = false; } private void FocusedRowChanged() { if (gridView1.RowCount > 0) { DataRow red = gridView1.GetFocusedDataRow(); textBox1.Text = red["Mã sinh viên"].ToString(); textBox2.Text = red["Họ"].ToString(); textBox3.Text = red["Tên"].ToString(); textBox4.Text = red["Địa chỉ"].ToString(); comboBox2.Text = red["Tên lớp"].ToString(); dateTimePicker1.Value = DateTime.Parse(red["Ngày sinh"].ToString()); } btnLuu.Enabled = false; btnHuyBo.Enabled = false; } private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e) { FocusedRowChanged(); textBox1.Enabled = false; } private void textBox1_TextChanged(object sender, EventArgs e) { btnLuu.Enabled = true; btnHuyBo.Enabled = true; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { Connection cnn = DBAccess.CnnList[comboBox1.SelectedIndex]; DBAccess.dataSource = cnn.DataSource; DBAccess.initCatalog = cnn.InitCatalog; btnReload.PerformClick(); } } }
6,454
https://github.com/dbones-labs/eventual/blob/master/src/Eventual/Infrastructure/BrokerStrategies/BrokerAttribute.cs
Github Open Source
Open Source
Apache-2.0
null
eventual
dbones-labs
C#
Code
34
83
namespace Eventual.Infrastructure.BrokerStrategies { using System; public class ConsumeAttribute : Attribute { public SourceType? From { get; set; } } public class PublishAttribute : Attribute { public DestinationType? To { get; set; } } }
37,263
https://github.com/lazercorn/phoneVerifier/blob/master/app/src/main/java/net/devaction/phoneverifier/model/util/AllDataInTableDeleter.java
Github Open Source
Open Source
Apache-2.0
2,017
phoneVerifier
lazercorn
Java
Code
31
110
package net.devaction.phoneverifier.model.util; import android.content.Context; import android.database.sqlite.SQLiteDatabase; /** * @author Víctor Gil */ public class AllDataInTableDeleter{ public static void delete(Context context, String tableName){ SQLiteDatabase database = DatabaseProvider.provideWritableDatabase(context); database.delete(tableName, null, null); } }
18,807
https://github.com/BernardoGrigiastro/IBE-Editor/blob/master/guapi/api/src/main/java/com/github/franckyi/guapi/api/node/builder/generic/GenericVBoxBuilder.java
Github Open Source
Open Source
MIT
2,021
IBE-Editor
BernardoGrigiastro
Java
Code
15
81
package com.github.franckyi.guapi.api.node.builder.generic; import com.github.franckyi.guapi.api.node.VBox; public interface GenericVBoxBuilder<N extends VBox> extends VBox, GenericBoxBuilder<N>, GenericVerticalParentBuilder<N> { }
34,327
https://github.com/dnnsoftware/Dnn.Platform/blob/master/DNN Platform/Library/Entities/Modules/Prompt/AddModule.cs
Github Open Source
Open Source
LicenseRef-scancode-free-unknown, MIT
2,023
Dnn.Platform
dnnsoftware
C#
Code
461
1,694
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Modules.Prompt { using System; using System.Collections.Generic; using System.Linq; using System.Net; using DotNetNuke.Abstractions.Portals; using DotNetNuke.Abstractions.Prompt; using DotNetNuke.Abstractions.Users; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Modules.Definitions; using DotNetNuke.Entities.Tabs; using DotNetNuke.Instrumentation; using DotNetNuke.Prompt; using DotNetNuke.Security.Permissions; using DotNetNuke.Services.Localization; /// <summary>This is a (Prompt) Console Command. You should not reference this class directly. It is to be used solely through Prompt.</summary> [ConsoleCommand("add-module", Constants.CommandCategoryKeys.Modules, "Prompt_AddModule_Description")] public class AddModule : ConsoleCommand { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(AddModule)); /// <inheritdoc/> public override string LocalResourceFile => Constants.DefaultPromptResourceFile; [ConsoleCommandParameter("name", "Prompt_AddModule_FlagModuleName", true)] public string ModuleName { get; set; } [ConsoleCommandParameter("pageid", "Prompt_AddModule_FlagPageId", true)] public int PageId { get; set; } // the page on which to add the module [ConsoleCommandParameter("pane", "Prompt_AddModule_FlagPane", "ContentPane")] public string Pane { get; set; } [ConsoleCommandParameter("title", "Prompt_AddModule_FlagModuleTitle")] public string ModuleTitle { get; set; } // title for the new module. defaults to friendly name /// <inheritdoc/> public override void Initialize(string[] args, IPortalSettings portalSettings, IUserInfo userInfo, int activeTabId) { base.Initialize(args, portalSettings, userInfo, activeTabId); this.ParseParameters(this); } /// <inheritdoc/> public override IConsoleResultModel Run() { try { var desktopModule = DesktopModuleController.GetDesktopModuleByModuleName(this.ModuleName, this.PortalId); if (desktopModule == null) { return new ConsoleErrorResultModel(string.Format(this.LocalizeString("Prompt_DesktopModuleNotFound"), this.ModuleName)); } var message = default(KeyValuePair<HttpStatusCode, string>); var page = TabController.Instance.GetTab(this.PageId, this.PortalSettings.PortalId); if (page == null) { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.NotFound, string.Format(Localization.GetString("Prompt_PageNotFound", this.LocalResourceFile), this.PageId)); return null; } if (!TabPermissionController.CanManagePage(page)) { message = new KeyValuePair<HttpStatusCode, string>(HttpStatusCode.NotFound, Localization.GetString("Prompt_InsufficientPermissions", this.LocalResourceFile)); return null; } var moduleList = new List<ModuleInfo>(); foreach (var objModuleDefinition in ModuleDefinitionController.GetModuleDefinitionsByDesktopModuleID(desktopModule.DesktopModuleID).Values) { var objModule = new ModuleInfo(); objModule.Initialize(this.PortalSettings.PortalId); objModule.PortalID = this.PortalSettings.PortalId; objModule.TabID = this.PageId; objModule.ModuleOrder = 0; objModule.ModuleTitle = string.IsNullOrEmpty(this.ModuleTitle) ? objModuleDefinition.FriendlyName : this.ModuleTitle; objModule.PaneName = this.Pane; objModule.ModuleDefID = objModuleDefinition.ModuleDefID; if (objModuleDefinition.DefaultCacheTime > 0) { objModule.CacheTime = objModuleDefinition.DefaultCacheTime; if (this.PortalSettings.DefaultModuleId > Null.NullInteger && this.PortalSettings.DefaultTabId > Null.NullInteger) { var defaultModule = ModuleController.Instance.GetModule( this.PortalSettings.DefaultModuleId, this.PortalSettings.DefaultTabId, true); if (defaultModule != null) { objModule.CacheTime = defaultModule.CacheTime; } } } ModuleController.Instance.InitialModulePermission(objModule, objModule.TabID, 0); if (this.PortalSettings.ContentLocalizationEnabled) { var defaultLocale = LocaleController.Instance.GetDefaultLocale(this.PortalSettings.PortalId); // check whether original tab is exists, if true then set culture code to default language, // otherwise set culture code to current. objModule.CultureCode = TabController.Instance.GetTabByCulture(objModule.TabID, this.PortalSettings.PortalId, defaultLocale) != null ? defaultLocale.Code : this.PortalSettings.CultureCode; } else { objModule.CultureCode = Null.NullString; } objModule.AllTabs = false; objModule.Alignment = null; ModuleController.Instance.AddModule(objModule); moduleList.Add(objModule); // Set position so future additions to page can operate correctly var position = ModuleController.Instance.GetTabModule(objModule.TabModuleID).ModuleOrder + 1; } if (moduleList == null) { return new ConsoleErrorResultModel(message.Value); } if (moduleList.Count == 0) { return new ConsoleErrorResultModel(this.LocalizeString("Prompt_NoModulesAdded")); } var modules = moduleList.Select(newModule => ModuleController.Instance.GetTabModule(newModule.TabModuleID)).ToList(); return new ConsoleResultModel(string.Format(this.LocalizeString("Prompt_ModuleAdded"), modules.Count, moduleList.Count == 1 ? string.Empty : "s")) { Data = modules, Records = modules.Count }; } catch (Exception ex) { Logger.Error(ex); return new ConsoleErrorResultModel(this.LocalizeString("Prompt_AddModuleError")); } } } }
40,166
https://github.com/HeadpatServices/Nucleus/blob/master/nucleus-core/src/main/java/io/github/nucleuspowered/nucleus/modules/teleport/commands/TeleportAskAllHereCommand.java
Github Open Source
Open Source
MIT
null
Nucleus
HeadpatServices
Java
Code
181
941
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.teleport.commands; import com.google.common.collect.Lists; import io.github.nucleuspowered.nucleus.modules.teleport.TeleportPermissions; import io.github.nucleuspowered.nucleus.modules.teleport.events.RequestEvent; import io.github.nucleuspowered.nucleus.modules.teleport.services.PlayerTeleporterService; import io.github.nucleuspowered.nucleus.scaffold.command.ICommandContext; import io.github.nucleuspowered.nucleus.scaffold.command.ICommandExecutor; import io.github.nucleuspowered.nucleus.scaffold.command.ICommandResult; import io.github.nucleuspowered.nucleus.scaffold.command.annotation.Command; import io.github.nucleuspowered.nucleus.scaffold.command.annotation.EssentialsEquivalent; import io.github.nucleuspowered.nucleus.services.INucleusServiceCollection; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.args.CommandElement; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.entity.living.player.User; import org.spongepowered.api.util.annotation.NonnullByDefault; import java.util.List; import java.util.stream.Collectors; @NonnullByDefault @EssentialsEquivalent({"tpaall"}) @Command(aliases = {"tpaall", "tpaskall"}, basePermission = TeleportPermissions.BASE_TPAALL, commandDescriptionKey = "tpaall") public class TeleportAskAllHereCommand implements ICommandExecutor<Player> { @Override public CommandElement[] parameters(INucleusServiceCollection serviceCollection) { return new CommandElement[] { GenericArguments.flags().flag("f").buildWith(GenericArguments.none()) }; } @Override public ICommandResult execute(ICommandContext<? extends Player> context) throws CommandException { List<Player> cancelled = Lists.newArrayList(); PlayerTeleporterService playerTeleporterService = context .getServiceCollection() .getServiceUnchecked(PlayerTeleporterService.class); for (Player x : Sponge.getServer().getOnlinePlayers()) { if (context.is(x)) { continue; } // Before we do all this, check the event. RequestEvent.PlayerToCause event = new RequestEvent.PlayerToCause(Sponge.getCauseStackManager().getCurrentCause(), x); if (Sponge.getEventManager().post(event)) { cancelled.add(x); continue; } playerTeleporterService.requestTeleport( context.getIfPlayer(), x, 0, 0, x, context.getIfPlayer(), !context.getOne("f", Boolean.class).orElse(false), false, true, p -> {}, "command.tpahere.question" ); } context.sendMessage("command.tpaall.success"); if (!cancelled.isEmpty()) { context.sendMessage("command.tpall.cancelled", cancelled.stream().map(User::getName).collect(Collectors.joining(", "))); } return context.successResult(); } }
22,428
https://github.com/TrustedBSD/sebsd/blob/master/gnu/usr.bin/binutils/gdb/kvm-fbsd-i386.h
Github Open Source
Open Source
Naumen, Condor-1.1, MS-PL
2,019
sebsd
TrustedBSD
C
Code
552
1,501
/* Kernel core dump functions below target vector, for GDB on FreeBSD/i386. Copyright 1986, 1987, 1989, 1991, 1992, 1993, 1994, 1995 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ __FBSDID("$FreeBSD: src/gnu/usr.bin/binutils/gdb/kvm-fbsd-i386.h,v 1.1 2004/06/11 16:09:38 obrien Exp $"); #include <machine/frame.h> static CORE_ADDR ksym_maxuseraddr (void) { static CORE_ADDR maxuseraddr; struct minimal_symbol *sym; if (maxuseraddr == 0) { sym = lookup_minimal_symbol ("PTmap", NULL, NULL); if (sym == NULL) { maxuseraddr = VM_MAXUSER_ADDRESS; } else { maxuseraddr = SYMBOL_VALUE_ADDRESS (sym); } } return maxuseraddr; } /* Symbol names of kernel entry points. Use special frames. */ #define KSYM_TRAP "calltrap" #define KSYM_INTR "Xintr" #define KSYM_FASTINTR "Xfastintr" #define KSYM_OLDSYSCALL "Xlcall_syscall" #define KSYM_SYSCALL "Xint0x80_syscall" /* The following is FreeBSD-specific hackery to decode special frames and elide the assembly-language stub. This could be made faster by defining a frame_type field in the machine-dependent frame information, but we don't think that's too important right now. */ enum frametype { tf_normal, tf_trap, tf_interrupt, tf_syscall }; CORE_ADDR fbsd_kern_frame_saved_pc (struct frame_info *fi) { struct minimal_symbol *sym; CORE_ADDR this_saved_pc; enum frametype frametype; this_saved_pc = read_memory_integer (fi->frame + 4, 4); sym = lookup_minimal_symbol_by_pc (this_saved_pc); frametype = tf_normal; if (sym != NULL) { if (strcmp (SYMBOL_NAME (sym), KSYM_TRAP) == 0) frametype = tf_trap; else if (strncmp (SYMBOL_NAME (sym), KSYM_INTR, strlen (KSYM_INTR)) == 0 || strncmp (SYMBOL_NAME(sym), KSYM_FASTINTR, strlen (KSYM_FASTINTR)) == 0) frametype = tf_interrupt; else if (strcmp (SYMBOL_NAME (sym), KSYM_SYSCALL) == 0 || strcmp (SYMBOL_NAME (sym), KSYM_OLDSYSCALL) == 0) frametype = tf_syscall; } switch (frametype) { case tf_normal: return (this_saved_pc); #define oEIP offsetof (struct trapframe, tf_eip) case tf_trap: return (read_memory_integer (fi->frame + 8 + oEIP, 4)); case tf_interrupt: return (read_memory_integer (fi->frame + 12 + oEIP, 4)); case tf_syscall: return (read_memory_integer (fi->frame + 8 + oEIP, 4)); #undef oEIP } } static void fetch_kcore_registers (struct pcb *pcb) { int i; int noreg; /* Get the register values out of the sys pcb and store them where `read_register' will find them. */ /* * XXX many registers aren't available. * XXX for the non-core case, the registers are stale - they are for * the last context switch to the debugger. * XXX gcc's register numbers aren't all #defined in tm-i386.h. */ noreg = 0; for (i = 0; i < 3; ++i) /* eax,ecx,edx */ supply_register (i, (char *)&noreg); supply_register (3, (char *) &pcb->pcb_ebx); supply_register (SP_REGNUM, (char *) &pcb->pcb_esp); supply_register (FP_REGNUM, (char *) &pcb->pcb_ebp); supply_register (6, (char *) &pcb->pcb_esi); supply_register (7, (char *) &pcb->pcb_edi); supply_register (PC_REGNUM, (char *) &pcb->pcb_eip); for (i = 9; i < 14; ++i) /* eflags, cs, ss, ds, es, fs */ supply_register (i, (char *) &noreg); supply_register (15, (char *) &pcb->pcb_gs); /* XXX 80387 registers? */ }
18,123
https://github.com/exced/AI-inference-engine/blob/master/public/inferEngine/ruleEngine.js
Github Open Source
Open Source
Apache-2.0
2,017
AI-inference-engine
exced
JavaScript
Code
242
611
function RuleEngine(rules) { this.rules = rules; } /** * assert condition == triggerOn * @param {Object} fact * @param {Array} facts */ function condition(fact, facts) { return fact.condition(facts) == fact.triggerOn; } /** * do actions * @param {Object} fact * @param {Array} facts */ function actions(fact, facts) { return fact.actions(facts); } /** * prioritize */ function prioritize(rules) { var res = []; for (var i = 0; i < rules.length; i++) { var pack = rules.filter(function (rule) { return rule.priority == i; }); if (pack.length >= 1) { res.push(pack); } } return res; } /** * select applicable non marked rules */ RuleEngine.prototype.selectRules = function (facts, rules) { var selected = []; for (var i = 0; i < rules.length; i++) { var rule = rules[i]; if (!rule.marked) { if (!rule.conditions(facts)) { rule.marked = true; } else { selected.push(rule); } } } return selected; } RuleEngine.prototype.markRulesFalse = function () { this.rules.map((r) => r.marked = false); } /** * any non marked rule */ RuleEngine.prototype.someNotMarked = function (rules) { return rules.some((r) => !r.marked) } /** * infer new rules. Forward chaining * @param {Object} facts */ RuleEngine.prototype.infer = function (facts) { this.markRulesFalse(); var flow; var selectedRules; var rule; /* prioritize rules */ var rulesByPriority = prioritize(this.rules); for (var i = 0; i < rulesByPriority.length; i++) { while (this.someNotMarked(rulesByPriority[i])) { selectedRules = this.selectRules(facts, rulesByPriority[i]); if (selectedRules.length > 0) { rule = selectedRules[0]; facts = rule.actions(facts); rule.marked = true; } } } return flow; }
49,940
https://github.com/athanclark/purescript-pure-css/blob/master/src/PureCSS/Grids.purs
Github Open Source
Open Source
BSD-3-Clause
null
purescript-pure-css
athanclark
PureScript
Code
163
337
-- | Follows the [Pure.css Grids](https://purecss.io/grids/) documentation. module PureCSS.Grids where import PureCSS.Types (ClassName) import Prelude (class Show, show, (<>)) pureGrid :: ClassName pureGrid = "pure-g" -- | The `.pure-u` class pureUnitAuto :: ClassName pureUnitAuto = "pure-u" -- | The `.pure-u-1` class pureUnitWhole :: ClassName pureUnitWhole = pureUnitAuto <> "-1" -- | Assumes the user knows that Pure.css only works in 5ths and 24ths based grids: -- | see [Pure.css Grid Docs](https://purecss.io/grids/) for details. pureUnit :: Int -> Int -> ClassName pureUnit x y = pureUnitAuto <> "-" <> show x <> "-" <> show y data ScreenSize = SM | MD | LG | XL instance showScreenSize :: Show ScreenSize where show x = case x of SM -> "sm" MD -> "md" LG -> "lg" XL -> "xl" -- | Responsive units pureUnitResp :: ScreenSize -> Int -> Int -> ClassName pureUnitResp r x y = pureUnitAuto <> "-" <> show r <> "-" <> show x <> "-" <> show y
48,317
https://github.com/helen-v/momentum-ui/blob/master/web-components/src/components/modal/Modal.stories.ts
Github Open Source
Open Source
MIT
null
momentum-ui
helen-v
TypeScript
Code
172
507
import "@/components/modal/Modal"; import { withA11y } from "@storybook/addon-a11y"; import { boolean, text, withKnobs } from "@storybook/addon-knobs"; import { html } from "lit-element"; export default { title: "Modal", component: "md-modal", decorators: [withKnobs, withA11y], parameters: { a11y: { element: "md-modal" } } }; const content = html` <p> This pattern may seem inefficient, since the same style sheet is reproduced in a each instance of an element. However, the browser can deduplicate multiple instances of the same style sheet, so the cost of parsing the style sheet is only paid once. </p> `; export const Modal = () => { const show = boolean("show", false); const headerLabel = text("headerLabel", "Test header text"); const headerMessage = text("message", "Test message in header"); const closeBtnName = text("closeBtnName", "Save"); const showCloseButton = boolean("showCloseButton", true); const backdropClickExit = boolean("OutsideClick", false); const hideFooter = boolean("hideFooter", false); const hideHeader = boolean("hideHeader", false); return html` <md-modal size="default" .show=${show} headerLabel="${headerLabel}" headerMessage="${headerMessage}" closeBtnName="${closeBtnName}" .showCloseButton="${showCloseButton}" .backdropClickExit="${backdropClickExit}" ?hideFooter=${hideFooter} ?hideHeader=${hideHeader} > <div slot="header"> <span>Test slot header</span> </div> ${content} <div slot="footer"> <span>Test slot footer</span> </div> </md-modal> `; };
17,972
https://github.com/iltempe/osmosi/blob/master/sumo/tools/sumolib/scenario/scenarios/basic_net.py
Github Open Source
Open Source
MIT
null
osmosi
iltempe
Python
Code
306
932
""" @file basic_net.py @author Daniel Krajzewicz @date 2014-09-01 @version $Id$ SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ Copyright (C) 2012-2017 DLR (http://www.dlr.de/) and contributors This file is part of SUMO. SUMO is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. @date 2014-09-01 """ from __future__ import absolute_import from __future__ import print_function from . import * import os import math import sumolib.net.generator.grid as netGenerator import sumolib.net.generator.demand as demandGenerator from sumolib.net.generator.network import * class Scenario_BasicNet(Scenario): NAME = "BasicNet" THIS_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), NAME) TLS_FILE = os.path.join(THIS_DIR, "tls.add.xml") NET_FILE = os.path.join(THIS_DIR, "network_%s.net.xml") def __init__(self, rot, withDefaultDemand=True): Scenario.__init__(self, self.NAME) self.NET_FILE = self.NET_FILE % rot self.netName = self.fullPath(self.NET_FILE) self.demandName = self.fullPath("routes.rou.xml") # network if fileNeedsRebuild(self.netName, "netconvert"): print("Network in '%s' needs to be rebuild" % self.netName) defaultEdge = Edge(numLanes=1, maxSpeed=13.89) defaultEdge.addSplit(50, 1) defaultEdge.lanes = [Lane(dirs="rs"), Lane(dirs="l")] netGen = netGenerator.grid(5, 5, None, defaultEdge) m = rot / 3.14 for y in range(1, 6): for x in range(1, 6): sr = math.sin(rot * y / 2. * x / 2.) cr = math.cos(rot * x / 2. * y / 2.) # * abs(3-x)/3. netGen._nodes[ "%s/%s" % (x, y)].x = netGen._nodes["%s/%s" % (x, y)].x + sr * m * 250 # * abs(3-y)/3. netGen._nodes[ "%s/%s" % (x, y)].y = netGen._nodes["%s/%s" % (x, y)].y + cr * m * 250 # not nice, the network name should be given/returned netGen.build(self.netName) # demand if withDefaultDemand: print("Demand in '%s' needs to be rebuild" % self.demandName) self.demand = demandGenerator.Demand() # why isn't it possible to get a network and return all possible # routes or whatever - to ease the process self.demand.addStream(demandGenerator.Stream( None, 0, 3600, 1000, "6/1_to_5/1", "1/1_to_0/1", {"hdv": .2, "passenger": .8})) if fileNeedsRebuild(self.demandName, "duarouter"): self.demand.build(0, 3600, self.netName, self.demandName)
1,547
https://github.com/simrat39/brawlhalla_api.dart/blob/master/lib/models/ranking_model.freezed.dart
Github Open Source
Open Source
MIT
null
brawlhalla_api.dart
simrat39
Dart
Code
1,181
4,185
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'ranking_model.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more informations: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); RankingModel _$RankingModelFromJson(Map<String, dynamic> json) { return _RankingModel.fromJson(json); } /// @nodoc class _$RankingModelTearOff { const _$RankingModelTearOff(); _RankingModel call( {required int rank, required String name, required int brawlhalla_id, required int best_legend, required int best_legend_games, required int best_legend_wins, required int rating, required String tier, required int games, required int wins, required String region, required int peak_rating}) { return _RankingModel( rank: rank, name: name, brawlhalla_id: brawlhalla_id, best_legend: best_legend, best_legend_games: best_legend_games, best_legend_wins: best_legend_wins, rating: rating, tier: tier, games: games, wins: wins, region: region, peak_rating: peak_rating, ); } RankingModel fromJson(Map<String, Object?> json) { return RankingModel.fromJson(json); } } /// @nodoc const $RankingModel = _$RankingModelTearOff(); /// @nodoc mixin _$RankingModel { int get rank => throw _privateConstructorUsedError; String get name => throw _privateConstructorUsedError; int get brawlhalla_id => throw _privateConstructorUsedError; int get best_legend => throw _privateConstructorUsedError; int get best_legend_games => throw _privateConstructorUsedError; int get best_legend_wins => throw _privateConstructorUsedError; int get rating => throw _privateConstructorUsedError; String get tier => throw _privateConstructorUsedError; int get games => throw _privateConstructorUsedError; int get wins => throw _privateConstructorUsedError; String get region => throw _privateConstructorUsedError; int get peak_rating => throw _privateConstructorUsedError; Map<String, dynamic> toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) $RankingModelCopyWith<RankingModel> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $RankingModelCopyWith<$Res> { factory $RankingModelCopyWith( RankingModel value, $Res Function(RankingModel) then) = _$RankingModelCopyWithImpl<$Res>; $Res call( {int rank, String name, int brawlhalla_id, int best_legend, int best_legend_games, int best_legend_wins, int rating, String tier, int games, int wins, String region, int peak_rating}); } /// @nodoc class _$RankingModelCopyWithImpl<$Res> implements $RankingModelCopyWith<$Res> { _$RankingModelCopyWithImpl(this._value, this._then); final RankingModel _value; // ignore: unused_field final $Res Function(RankingModel) _then; @override $Res call({ Object? rank = freezed, Object? name = freezed, Object? brawlhalla_id = freezed, Object? best_legend = freezed, Object? best_legend_games = freezed, Object? best_legend_wins = freezed, Object? rating = freezed, Object? tier = freezed, Object? games = freezed, Object? wins = freezed, Object? region = freezed, Object? peak_rating = freezed, }) { return _then(_value.copyWith( rank: rank == freezed ? _value.rank : rank // ignore: cast_nullable_to_non_nullable as int, name: name == freezed ? _value.name : name // ignore: cast_nullable_to_non_nullable as String, brawlhalla_id: brawlhalla_id == freezed ? _value.brawlhalla_id : brawlhalla_id // ignore: cast_nullable_to_non_nullable as int, best_legend: best_legend == freezed ? _value.best_legend : best_legend // ignore: cast_nullable_to_non_nullable as int, best_legend_games: best_legend_games == freezed ? _value.best_legend_games : best_legend_games // ignore: cast_nullable_to_non_nullable as int, best_legend_wins: best_legend_wins == freezed ? _value.best_legend_wins : best_legend_wins // ignore: cast_nullable_to_non_nullable as int, rating: rating == freezed ? _value.rating : rating // ignore: cast_nullable_to_non_nullable as int, tier: tier == freezed ? _value.tier : tier // ignore: cast_nullable_to_non_nullable as String, games: games == freezed ? _value.games : games // ignore: cast_nullable_to_non_nullable as int, wins: wins == freezed ? _value.wins : wins // ignore: cast_nullable_to_non_nullable as int, region: region == freezed ? _value.region : region // ignore: cast_nullable_to_non_nullable as String, peak_rating: peak_rating == freezed ? _value.peak_rating : peak_rating // ignore: cast_nullable_to_non_nullable as int, )); } } /// @nodoc abstract class _$RankingModelCopyWith<$Res> implements $RankingModelCopyWith<$Res> { factory _$RankingModelCopyWith( _RankingModel value, $Res Function(_RankingModel) then) = __$RankingModelCopyWithImpl<$Res>; @override $Res call( {int rank, String name, int brawlhalla_id, int best_legend, int best_legend_games, int best_legend_wins, int rating, String tier, int games, int wins, String region, int peak_rating}); } /// @nodoc class __$RankingModelCopyWithImpl<$Res> extends _$RankingModelCopyWithImpl<$Res> implements _$RankingModelCopyWith<$Res> { __$RankingModelCopyWithImpl( _RankingModel _value, $Res Function(_RankingModel) _then) : super(_value, (v) => _then(v as _RankingModel)); @override _RankingModel get _value => super._value as _RankingModel; @override $Res call({ Object? rank = freezed, Object? name = freezed, Object? brawlhalla_id = freezed, Object? best_legend = freezed, Object? best_legend_games = freezed, Object? best_legend_wins = freezed, Object? rating = freezed, Object? tier = freezed, Object? games = freezed, Object? wins = freezed, Object? region = freezed, Object? peak_rating = freezed, }) { return _then(_RankingModel( rank: rank == freezed ? _value.rank : rank // ignore: cast_nullable_to_non_nullable as int, name: name == freezed ? _value.name : name // ignore: cast_nullable_to_non_nullable as String, brawlhalla_id: brawlhalla_id == freezed ? _value.brawlhalla_id : brawlhalla_id // ignore: cast_nullable_to_non_nullable as int, best_legend: best_legend == freezed ? _value.best_legend : best_legend // ignore: cast_nullable_to_non_nullable as int, best_legend_games: best_legend_games == freezed ? _value.best_legend_games : best_legend_games // ignore: cast_nullable_to_non_nullable as int, best_legend_wins: best_legend_wins == freezed ? _value.best_legend_wins : best_legend_wins // ignore: cast_nullable_to_non_nullable as int, rating: rating == freezed ? _value.rating : rating // ignore: cast_nullable_to_non_nullable as int, tier: tier == freezed ? _value.tier : tier // ignore: cast_nullable_to_non_nullable as String, games: games == freezed ? _value.games : games // ignore: cast_nullable_to_non_nullable as int, wins: wins == freezed ? _value.wins : wins // ignore: cast_nullable_to_non_nullable as int, region: region == freezed ? _value.region : region // ignore: cast_nullable_to_non_nullable as String, peak_rating: peak_rating == freezed ? _value.peak_rating : peak_rating // ignore: cast_nullable_to_non_nullable as int, )); } } /// @nodoc @JsonSerializable() class _$_RankingModel implements _RankingModel { const _$_RankingModel( {required this.rank, required this.name, required this.brawlhalla_id, required this.best_legend, required this.best_legend_games, required this.best_legend_wins, required this.rating, required this.tier, required this.games, required this.wins, required this.region, required this.peak_rating}); factory _$_RankingModel.fromJson(Map<String, dynamic> json) => _$$_RankingModelFromJson(json); @override final int rank; @override final String name; @override final int brawlhalla_id; @override final int best_legend; @override final int best_legend_games; @override final int best_legend_wins; @override final int rating; @override final String tier; @override final int games; @override final int wins; @override final String region; @override final int peak_rating; @override String toString() { return 'RankingModel(rank: $rank, name: $name, brawlhalla_id: $brawlhalla_id, best_legend: $best_legend, best_legend_games: $best_legend_games, best_legend_wins: $best_legend_wins, rating: $rating, tier: $tier, games: $games, wins: $wins, region: $region, peak_rating: $peak_rating)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _RankingModel && const DeepCollectionEquality().equals(other.rank, rank) && const DeepCollectionEquality().equals(other.name, name) && const DeepCollectionEquality() .equals(other.brawlhalla_id, brawlhalla_id) && const DeepCollectionEquality() .equals(other.best_legend, best_legend) && const DeepCollectionEquality() .equals(other.best_legend_games, best_legend_games) && const DeepCollectionEquality() .equals(other.best_legend_wins, best_legend_wins) && const DeepCollectionEquality().equals(other.rating, rating) && const DeepCollectionEquality().equals(other.tier, tier) && const DeepCollectionEquality().equals(other.games, games) && const DeepCollectionEquality().equals(other.wins, wins) && const DeepCollectionEquality().equals(other.region, region) && const DeepCollectionEquality() .equals(other.peak_rating, peak_rating)); } @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(rank), const DeepCollectionEquality().hash(name), const DeepCollectionEquality().hash(brawlhalla_id), const DeepCollectionEquality().hash(best_legend), const DeepCollectionEquality().hash(best_legend_games), const DeepCollectionEquality().hash(best_legend_wins), const DeepCollectionEquality().hash(rating), const DeepCollectionEquality().hash(tier), const DeepCollectionEquality().hash(games), const DeepCollectionEquality().hash(wins), const DeepCollectionEquality().hash(region), const DeepCollectionEquality().hash(peak_rating)); @JsonKey(ignore: true) @override _$RankingModelCopyWith<_RankingModel> get copyWith => __$RankingModelCopyWithImpl<_RankingModel>(this, _$identity); @override Map<String, dynamic> toJson() { return _$$_RankingModelToJson(this); } } abstract class _RankingModel implements RankingModel { const factory _RankingModel( {required int rank, required String name, required int brawlhalla_id, required int best_legend, required int best_legend_games, required int best_legend_wins, required int rating, required String tier, required int games, required int wins, required String region, required int peak_rating}) = _$_RankingModel; factory _RankingModel.fromJson(Map<String, dynamic> json) = _$_RankingModel.fromJson; @override int get rank; @override String get name; @override int get brawlhalla_id; @override int get best_legend; @override int get best_legend_games; @override int get best_legend_wins; @override int get rating; @override String get tier; @override int get games; @override int get wins; @override String get region; @override int get peak_rating; @override @JsonKey(ignore: true) _$RankingModelCopyWith<_RankingModel> get copyWith => throw _privateConstructorUsedError; }
44,508
https://github.com/Masses/hoplite/blob/master/hoplite-core/src/main/kotlin/com/sksamuel/hoplite/KeyMapper.kt
Github Open Source
Open Source
Apache-2.0
null
hoplite
Masses
Kotlin
Code
194
421
package com.sksamuel.hoplite import kotlin.reflect.KParameter /** * A [ParameterMapper] that will transform any snake case field names * into their camel case equivalent. * * For example, snake_case_pilsen will become camelCasePilsen. * * This key mapper won't affect other camel case fields, so by using * this you can mix and match camel and snake case fields. */ object SnakeCaseParamMapper : ParameterMapper { override fun map(param: KParameter): String { return (param.name ?: "<anon>").fold("") { acc, char -> when { char.isUpperCase() && acc.isEmpty() -> char.toLowerCase().toString() char.isUpperCase() -> acc + "_" + char.toLowerCase() else -> acc + char } } } } /** * A [ParameterMapper] that will transform any dash case field names * into their camel case equivalent. * * For example, dash-case-pilsen will become camelCasePilsen. * * This key mapper won't affect other camel case fields, so by using * this you can mix and match camel and dash case fields. */ object KebabCaseParamMapper : ParameterMapper { override fun map(param: KParameter): String { return (param.name ?: "<anon>").fold("") { acc, char -> when { char.isUpperCase() && acc.isEmpty() -> char.toLowerCase().toString() char.isUpperCase() -> acc + "-" + char.toLowerCase() else -> acc + char } } } }
44,725
https://github.com/annakristinkaufmann/nexus/blob/master/delta/service/src/test/scala/ch/epfl/bluebrain/nexus/delta/service/database/PostgresServiceDependencySpec.scala
Github Open Source
Open Source
Apache-2.0
2,022
nexus
annakristinkaufmann
Scala
Code
66
417
package ch.epfl.bluebrain.nexus.delta.service.database import ch.epfl.bluebrain.nexus.delta.kernel.Secret import ch.epfl.bluebrain.nexus.delta.sdk.model.ComponentDescription.ServiceDescription import ch.epfl.bluebrain.nexus.delta.sdk.model.Name import ch.epfl.bluebrain.nexus.delta.sourcing.config.PostgresConfig import ch.epfl.bluebrain.nexus.testkit.IOValues import ch.epfl.bluebrain.nexus.testkit.postgres.PostgresDocker import ch.epfl.bluebrain.nexus.testkit.postgres.PostgresDocker._ import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpecLike class PostgresServiceDependencySpec extends AnyWordSpecLike with Matchers with PostgresDocker with IOValues { lazy val config: PostgresConfig = PostgresConfig( hostConfig.host, hostConfig.port, "postgres", PostgresUser, Secret(PostgresPassword), s"jdbc:postgresql://${hostConfig.host}:${hostConfig.port}/postgres?stringtype=unspecified", tablesAutocreate = true ) "PostgresServiceDependency" should { "fetch its service name and version" in { new PostgresServiceDependency(config).serviceDescription.accepted shouldEqual ServiceDescription(Name.unsafe("postgres"), "12.2") } } }
14,146
https://github.com/sunshl/incubator-weex/blob/master/weex_core/Source/include/JavaScriptCore/runtime/WeakGCMap.h
Github Open Source
Open Source
Apache-2.0
2,018
incubator-weex
sunshl
C
Code
304
755
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #pragma once #include "Weak.h" #include <wtf/HashMap.h> namespace JSC { // A HashMap with Weak<JSCell> values, which automatically removes values once they're garbage collected. template<typename KeyArg, typename ValueArg, typename HashArg = typename DefaultHash<KeyArg>::Hash, typename KeyTraitsArg = HashTraits<KeyArg>> class WeakGCMap { WTF_MAKE_FAST_ALLOCATED; typedef Weak<ValueArg> ValueType; typedef HashMap<KeyArg, ValueType, HashArg, KeyTraitsArg> HashMapType; public: typedef typename HashMapType::KeyType KeyType; typedef typename HashMapType::AddResult AddResult; typedef typename HashMapType::iterator iterator; typedef typename HashMapType::const_iterator const_iterator; explicit WeakGCMap(VM&); ~WeakGCMap(); ValueArg* get(const KeyType& key) const { return m_map.get(key); } AddResult set(const KeyType& key, ValueType value) { return m_map.set(key, WTFMove(value)); } bool remove(const KeyType& key) { return m_map.remove(key); } void clear() { m_map.clear(); } bool isEmpty() const { const_iterator it = m_map.begin(); const_iterator end = m_map.end(); while (it != end) { if (it->value) return true; } return false; } inline iterator find(const KeyType& key); inline const_iterator find(const KeyType& key) const; template<typename Functor> void forEach(Functor functor) { for (auto& pair : m_map) { if (pair.value) functor(pair.key, pair.value.get()); } } inline bool contains(const KeyType& key) const; void pruneStaleEntries(); private: HashMapType m_map; VM& m_vm; }; } // namespace JSC
22,298
https://github.com/mabuonomo/flysystem/blob/master/stub/FileOverwritingAdapterStub.php
Github Open Source
Open Source
MIT
2,019
flysystem
mabuonomo
PHP
Code
181
581
<?php namespace League\Flysystem\Stub; use League\Flysystem\Adapter\CanOverwriteFiles; use League\Flysystem\AdapterInterface; use League\Flysystem\Config; /** * @codeCoverageIgnore */ class FileOverwritingAdapterStub implements AdapterInterface, CanOverwriteFiles { public $writtenPath = ''; public $writtenContents = ''; public function write($path, $contents, Config $config) { $this->writtenPath = $path; $this->writtenContents = $contents; return true; } public function writeStream($path, $resource, Config $config) { $this->writtenPath = $path; $this->writtenContents = stream_get_contents($resource); return true; } public function update($path, $contents, Config $config) { } public function updateStream($path, $resource, Config $config) { } public function rename($path, $newpath) { } public function copy($path, $newpath) { } public function delete($path) { } public function deleteDir($dirname) { } public function createDir($dirname, Config $config) { } public function setVisibility($path, $visibility) { } public function has($path) { } public function read($path) { } public function readStream($path) { } public function listContents($directory = '', $recursive = false) { } public function getMetadata($path) { } public function getSize($path) { } public function getMimetype($path) { } public function getTimestamp($path) { } public function getVisibility($path) { } public function setPathPrefix($prefix) { } public function getPathPrefix() { } public function applyPathPrefix($path) { } public function removePathPrefix($path) { } }
35,323
https://github.com/bbhunter/TLS-Attacker/blob/master/TLS-Core/src/test/java/de/rub/nds/tlsattacker/core/state/TlsContextTest.java
Github Open Source
Open Source
Apache-2.0
2,023
TLS-Attacker
bbhunter
Java
Code
465
3,000
/* * TLS-Attacker - A Modular Penetration Testing Framework for TLS * * Copyright 2014-2023 Ruhr University Bochum, Paderborn University, Technology Innovation Institute, and Hackmanit GmbH * * Licensed under Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0.txt */ package de.rub.nds.tlsattacker.core.state; import static org.junit.jupiter.api.Assertions.*; import de.rub.nds.modifiablevariable.util.ArrayConverter; import de.rub.nds.tlsattacker.core.config.Config; import de.rub.nds.tlsattacker.core.connection.OutboundConnection; import de.rub.nds.tlsattacker.core.constants.CipherSuite; import de.rub.nds.tlsattacker.core.constants.ExtensionType; import de.rub.nds.tlsattacker.core.constants.MaxFragmentLength; import de.rub.nds.tlsattacker.core.constants.ProtocolVersion; import de.rub.nds.tlsattacker.core.layer.LayerStack; import de.rub.nds.tlsattacker.core.layer.context.TlsContext; import de.rub.nds.tlsattacker.core.layer.impl.RecordLayer; import de.rub.nds.tlsattacker.core.record.cipher.CipherState; import de.rub.nds.tlsattacker.core.record.cipher.RecordAEADCipher; import de.rub.nds.tlsattacker.core.record.cipher.cryptohelper.KeySet; import de.rub.nds.tlsattacker.transport.ConnectionEndType; import java.security.Security; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.test.TestRandomData; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class TlsContextTest { private Config config; private TlsContext tlsContext; private KeySet testKeySet; @BeforeAll public static void setUpClass() { Security.addProvider(new BouncyCastleProvider()); } @BeforeEach public void setUp() { config = Config.createConfig(); tlsContext = new TlsContext(config); tlsContext.getChooser(); testKeySet = new KeySet(); testKeySet.setClientWriteKey( ArrayConverter.hexStringToByteArray( "65B7DA726864D4184D75A549BF5C06AB20867846AF4434CC")); testKeySet.setClientWriteMacSecret(new byte[0]); testKeySet.setClientWriteIv( ArrayConverter.hexStringToByteArray("11223344556677889900AABB")); testKeySet.setServerWriteIv(new byte[12]); testKeySet.setServerWriteKey(new byte[16]); testKeySet.setServerWriteMacSecret(new byte[0]); } private void activateEncryptionInContext() { tlsContext.getContext().setConnection(new OutboundConnection()); tlsContext.setTalkingConnectionEndType(ConnectionEndType.SERVER); tlsContext.setSelectedCipherSuite(CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256); tlsContext.setSelectedProtocolVersion(ProtocolVersion.TLS12); tlsContext.setRandom(new TestRandomData(ArrayConverter.hexStringToByteArray("FFEEDDCC"))); tlsContext .getContext() .setLayerStack( new LayerStack(tlsContext.getContext(), new RecordLayer(tlsContext))); tlsContext .getRecordLayer() .updateEncryptionCipher( new RecordAEADCipher( tlsContext, new CipherState( tlsContext.getChooser().getSelectedProtocolVersion(), tlsContext.getChooser().getSelectedCipherSuite(), testKeySet, tlsContext.isExtensionNegotiated( ExtensionType.ENCRYPT_THEN_MAC)))); } /** Test of getOutboundMaxRecordDataSize method, of class TlsContext. */ @Test public void testGetOutboundMaxRecordDataSizeEncryptionInactiveNoExtensions() { final Integer result = tlsContext.getOutboundMaxRecordDataSize(); assertEquals(config.getDefaultMaxRecordData(), (int) result); assertNull(tlsContext.getOutboundRecordSizeLimit()); assertFalse(config.isAddRecordSizeLimitExtension()); assertNull(tlsContext.getMaxFragmentLength()); } @Test public void testGetOutboundMaxRecordDataSizeEncryptionActiveNoExtensions() { activateEncryptionInContext(); final Integer result = tlsContext.getOutboundMaxRecordDataSize(); assertEquals(config.getDefaultMaxRecordData(), (int) result); assertNull(tlsContext.getOutboundRecordSizeLimit()); assertFalse(config.isAddRecordSizeLimitExtension()); assertNull(tlsContext.getMaxFragmentLength()); } @Test public void testGetOutboundMaxRecordDataSizeEncryptionInactiveMaxFragmentLength() { tlsContext.setMaxFragmentLength(MaxFragmentLength.TWO_11); final Integer result = tlsContext.getOutboundMaxRecordDataSize(); assertEquals(result, MaxFragmentLength.getIntegerRepresentation(MaxFragmentLength.TWO_11)); assertNull(tlsContext.getOutboundRecordSizeLimit()); assertFalse(config.isAddRecordSizeLimitExtension()); } @Test public void testGetOutboundMaxRecordDataSizeEncryptionActiveMaxFragmentLength() { activateEncryptionInContext(); tlsContext.setMaxFragmentLength(MaxFragmentLength.TWO_11); final Integer result = tlsContext.getOutboundMaxRecordDataSize(); assertEquals(result, MaxFragmentLength.getIntegerRepresentation(MaxFragmentLength.TWO_11)); assertNull(tlsContext.getOutboundRecordSizeLimit()); assertFalse(config.isAddRecordSizeLimitExtension()); } @Test public void testGetOutboundMaxRecordDataSizeRecordSizeLimitTLS12() { activateEncryptionInContext(); tlsContext.setSelectedProtocolVersion(ProtocolVersion.TLS12); tlsContext.setOutboundRecordSizeLimit(1337); final Integer result = tlsContext.getOutboundMaxRecordDataSize(); assertEquals(1337, (int) result); assertEquals(1337, (int) tlsContext.getOutboundRecordSizeLimit()); assertFalse(config.isAddRecordSizeLimitExtension()); } @Test public void testGetOutboundMaxRecordDataSizeRecordSizeLimitTLS13() { activateEncryptionInContext(); tlsContext.setSelectedProtocolVersion(ProtocolVersion.TLS13); config.setDefaultAdditionalPadding(42); tlsContext.setOutboundRecordSizeLimit(1337); final Integer result = tlsContext.getOutboundMaxRecordDataSize(); assertEquals((1337 - 1 - 42), (int) result); assertEquals(1337, (int) tlsContext.getOutboundRecordSizeLimit()); assertFalse(config.isAddRecordSizeLimitExtension()); } @Test public void testGetOutboundMaxRecordDataSizeRecordSizeLimitInvalidConfig() { activateEncryptionInContext(); tlsContext.setSelectedProtocolVersion(ProtocolVersion.TLS13); config.setDefaultAdditionalPadding(42); tlsContext.setOutboundRecordSizeLimit(42); final Integer result = tlsContext.getOutboundMaxRecordDataSize(); assertEquals(0, (int) result); assertEquals(42, (int) tlsContext.getOutboundRecordSizeLimit()); assertFalse(config.isAddRecordSizeLimitExtension()); } /** Test of getOutboundMaxRecordDataSize method, of class TlsContext. */ @Test public void testGetInboundMaxRecordDataSizeEncryptionInactiveNoExtensions() { final Integer result = tlsContext.getInboundMaxRecordDataSize(); assertEquals(config.getDefaultMaxRecordData(), (int) result); assertNull(tlsContext.getOutboundRecordSizeLimit()); assertFalse(config.isAddRecordSizeLimitExtension()); assertNull(tlsContext.getMaxFragmentLength()); } @Test public void testGetInboundMaxRecordDataSizeEncryptionActiveNoExtensions() { activateEncryptionInContext(); final Integer result = tlsContext.getInboundMaxRecordDataSize(); assertEquals(config.getDefaultMaxRecordData(), (int) result); assertNull(tlsContext.getOutboundRecordSizeLimit()); assertFalse(config.isAddRecordSizeLimitExtension()); assertNull(tlsContext.getMaxFragmentLength()); } @Test public void testGetInboundMaxRecordDataSizeEncryptionInactiveMaxFragmentLength() { tlsContext.setMaxFragmentLength(MaxFragmentLength.TWO_11); final Integer result = tlsContext.getInboundMaxRecordDataSize(); assertEquals(result, MaxFragmentLength.getIntegerRepresentation(MaxFragmentLength.TWO_11)); assertNull(tlsContext.getOutboundRecordSizeLimit()); assertFalse(config.isAddRecordSizeLimitExtension()); } @Test public void testGetInboundMaxRecordDataSizeEncryptionActiveMaxFragmentLength() { activateEncryptionInContext(); tlsContext.setMaxFragmentLength(MaxFragmentLength.TWO_11); final Integer result = tlsContext.getInboundMaxRecordDataSize(); assertEquals(result, MaxFragmentLength.getIntegerRepresentation(MaxFragmentLength.TWO_11)); assertNull(tlsContext.getOutboundRecordSizeLimit()); assertFalse(config.isAddRecordSizeLimitExtension()); } @Test public void testGetInboundMaxRecordDataSizeRecordSizeLimitTLS12() { activateEncryptionInContext(); tlsContext.setSelectedProtocolVersion(ProtocolVersion.TLS12); config.setAddRecordSizeLimitExtension(Boolean.TRUE); config.setInboundRecordSizeLimit(123); final Integer result = tlsContext.getInboundMaxRecordDataSize(); assertEquals(123, (int) result); assertNull(tlsContext.getOutboundRecordSizeLimit()); assertTrue(config.isAddRecordSizeLimitExtension()); assertEquals(123, (int) config.getInboundRecordSizeLimit()); } @Test public void testGetInboundMaxRecordDataSizeRecordSizeLimitTLS13() { activateEncryptionInContext(); tlsContext.setSelectedProtocolVersion(ProtocolVersion.TLS13); config.setDefaultAdditionalPadding(42); config.setAddRecordSizeLimitExtension(Boolean.TRUE); config.setInboundRecordSizeLimit(123); final Integer result = tlsContext.getInboundMaxRecordDataSize(); assertEquals((123 - 1 - 42), (int) result); assertNull(tlsContext.getOutboundRecordSizeLimit()); assertTrue(config.isAddRecordSizeLimitExtension()); assertEquals(123, (int) config.getInboundRecordSizeLimit()); } @Test public void testGetInboundMaxRecordDataSizeRecordSizeLimitInvalidConfig() { activateEncryptionInContext(); tlsContext.setSelectedProtocolVersion(ProtocolVersion.TLS13); config.setDefaultAdditionalPadding(123); config.setAddRecordSizeLimitExtension(Boolean.TRUE); config.setInboundRecordSizeLimit(123); final Integer result = tlsContext.getInboundMaxRecordDataSize(); assertEquals(0, (int) result); assertNull(tlsContext.getOutboundRecordSizeLimit()); assertEquals(123, (int) config.getInboundRecordSizeLimit()); } }
602
https://github.com/jiujieblue/yuanResume/blob/master/src/App.vue
Github Open Source
Open Source
MIT
2,017
yuanResume
jiujieblue
Vue
Code
335
1,381
<template> <div class="app"> <div class="app-right"> <div class="app-right-box"> <ul class="clearfix"> <li :class="{active : !route}"> <a href="#"> <i class="icon-user-tie"></i> </a> <span>关于个人</span> </li> <li :class="{active : route == 'Professional'}"> <a href="#Professional"> <i class="icon-hammer"></i> </a> <span>专业技能</span> </li> <li :class="{active : route == 'Mywork'}"> <a href="#Mywork"> <i class="icon-stack"></i> </a> <span>我的作品</span> </li> <li :class="{active : route == 'contact'}"> <a href="#contact"> <i class="icon-envelop"></i> </a> <span>联系方式</span> </li> <!-- <li :class="{active : route == 'Interest'}"> <a href="#Interest"> <i class="icon-heart"></i> <span>兴趣爱好</span> </a> </li> --> </ul> </div> </div> <transition name="fade"> <router-view v-show="show"></router-view> </transition> </div> </template> <script> export default { data () { return { show: true, route: '' } }, mounted () { $('.app-right-box ul li').hover( function(e){ var $tar = $(e.target) if(e.target.nodeName == 'SPAN'){ return false } if(e.target.nodeName != 'LI'){ $tar = $tar.parents('li') } $tar.children('span').fadeIn(200) }, function(e){ if(e.target.nodeName == 'SPAN'){ return false } var $tar = $(e.target) if(e.target.nodeName != 'LI'){ $tar = $tar.parents('li') } $tar.children('span').fadeOut() } ) }, methods : { _spanShow (e) { console.log(e.target) var $tar = $(e.target) if(e.target.nodeName != 'LI'){ $tar = $tar.parents('li') } $tar.children('span').slideDown(200) }, _spanhide (e) { var $tar = $(e.target) if(e.target.nodeName != 'LI'){ $tar = $tar.parents('li') } $tar.children('span').slideUp() } }, watch:{ '$route'(val){ var urlStr = window.location.href var route = urlStr.slice(urlStr.indexOf('#')+2) this.route = route } } } </script> <style lang="less"> @import './App.less'; @import './assets/css/icons.css'; @import './assets/css/bootstrap.css'; .fade-enter-active, .fade-leave-active { transition: opacity .5s } .fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ { opacity: 0 } .app{ >div.section{ margin-top: 58px; .col-md-2{ span{ margin-right: 5px; } } } .clearfix:after{ content:""; display:block; clear:both; } &-right{ position: fixed; right: 0; left: 0; top: 0; width: 100%; z-index: 100; &-box{ background: rgba(0,0,0,0.8); >ul{ width: 100%; padding: 10px 0; text-align: center; li{ display: inline-block; padding: 0 10px; margin-right: 10px; cursor: pointer; position: relative; &:last-child{ margin: 0; } >a{ display: block; } &:hover i{ opacity: .65; } &.active{ i:before{ opacity: .65; } } i:before{ font-size: 35px; color: #fff; } span{ display: none; box-sizing: content-box; position: absolute; top: 120%; left: -35%; width: 150%; padding: 5px; background: rgba(0, 0, 0, 0.8); color: #fff; font-size: 16px; } } } } } } </style>
21,275
https://github.com/pmd/pmd/blob/master/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/rule/design/uselessoverridingmethod/BaseClass.java
Github Open Source
Open Source
BSD-3-Clause, Apache-2.0
2,023
pmd
pmd
Java
Code
42
133
/* * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.java.rule.design.uselessoverridingmethod; public class BaseClass { protected void doBase() { } protected void doBaseWithArg(String foo) { } protected void doBaseWithArgs(String foo, int bar) { } protected void methodWithInterface(CharSequence arg) { } }
50,779