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/alexyeskin/CoreLitecoin/blob/master/CoreLitecoin/LTCOutpoint.m
Github Open Source
Open Source
WTFPL
2,020
CoreLitecoin
alexyeskin
Objective-C
Code
110
381
// CoreBitcoin by Oleg Andreev <oleganza@gmail.com>, WTFPL. #import "LTCOutpoint.h" #import "LTCTransaction.h" #import "LTCHashID.h" @implementation LTCOutpoint - (id) initWithHash:(NSData*)hash index:(uint32_t)index { if (hash.length != 32) return nil; if (self = [super init]) { _txHash = hash; _index = index; } return self; } - (id) initWithTxID:(NSString*)txid index:(uint32_t)index { NSData* hash = LTCHashFromID(txid); return [self initWithHash:hash index:index]; } - (NSString*) txID { return LTCIDFromHash(self.txHash); } - (void) setTxID:(NSString *)txID { self.txHash = LTCHashFromID(txID); } - (NSUInteger) hash { const NSUInteger* words = _txHash.bytes; return words[0] + self.index; } - (BOOL) isEqual:(LTCOutpoint*)object { return [self.txHash isEqual:object.txHash] && self.index == object.index; } - (id) copyWithZone:(NSZone *)zone { return [[LTCOutpoint alloc] initWithHash:_txHash index:_index]; } @end
26,600
https://github.com/Prokyo/ProkyoNet/blob/master/client/src/main/java/de/prokyo/network/client/ProkyoClientInitializer.java
Github Open Source
Open Source
MIT
2,019
ProkyoNet
Prokyo
Java
Code
70
370
package de.prokyo.network.client; import de.prokyo.network.common.pipeline.PacketDecoder; import de.prokyo.network.common.pipeline.PacketEncoder; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.LengthFieldPrepender; import io.netty.handler.timeout.ReadTimeoutHandler; import lombok.RequiredArgsConstructor; /** * Initializes the client connection. */ @RequiredArgsConstructor public class ProkyoClientInitializer extends ChannelInitializer { private final ProkyoClient client; @Override protected void initChannel(Channel channel) throws Exception { channel.pipeline() .addLast("timeout", new ReadTimeoutHandler(30)) .addLast("frame-decoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)) .addLast("prokyoDecoder", new PacketDecoder()) .addLast("frame-prepender", new LengthFieldPrepender(4)) .addLast("prokyoEncoder", new PacketEncoder()) .addLast("prokyoPacketHandler", new ProkyoDuplexHandler(this.client)); channel.attr(ProkyoClient.ATTRIBUTE_KEY).set(this.client); } }
25,826
https://github.com/jvaneikeren/orbital7.extensions/blob/master/src/Orbital7.Extensions/GenericListExtensions.cs
Github Open Source
Open Source
MIT
2,020
orbital7.extensions
jvaneikeren
C#
Code
149
460
using System; using System.Linq; namespace System.Collections.Generic { public static class GenericListExtensions { public static int Replace<T>( this IList<T> source, T oldValue, T newValue) { if (source == null) throw new ArgumentNullException(nameof(source)); var index = source.IndexOf(oldValue); if (index != -1) source[index] = newValue; return index; } public static void ReplaceAll<T>( this IList<T> source, T oldValue, T newValue) { if (source == null) throw new ArgumentNullException(nameof(source)); int index = -1; do { index = source.IndexOf(oldValue); if (index != -1) source[index] = newValue; } while (index != -1); } public static IEnumerable<T> Replace<T>( this IEnumerable<T> source, T oldValue, T newValue) { if (source == null) throw new ArgumentNullException("source"); return source.Select(x => EqualityComparer<T>.Default.Equals(x, oldValue) ? newValue : x); } public static IEnumerable<TSource> DistinctBy<TSource, TKey>( this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> seenKeys = new HashSet<TKey>(); foreach (TSource element in source) { if (seenKeys.Add(keySelector(element))) { yield return element; } } } } }
35,634
https://github.com/n-fisher/Rimworld-Boss-Fights-Mod/blob/master/Source/BFLords.cs
Github Open Source
Open Source
MIT
null
Rimworld-Boss-Fights-Mod
n-fisher
C#
Code
590
2,148
using RimWorld; using Verse; using Verse.AI; using Verse.AI.Group; namespace Boss_Fight_Mod { public class LordJob_BossAssault : LordJob_AssaultColony { public LordJob_BossAssault(Faction assaulterFaction, bool canKidnap = true, bool canTimeoutOrFlee = false, bool sappers = false, bool useAvoidGridSmart = true, bool canSteal = false) : base(assaulterFaction, canKidnap, canTimeoutOrFlee, sappers, useAvoidGridSmart, canSteal) { } public override StateGraph CreateGraph() { StateGraph stateGraph = new StateGraph(); stateGraph.AddToil(new LordToil_AssaultColony { avoidGridMode = AvoidGridMode.Smart }); return stateGraph; } } public class LordToil_BossAssault : LordToil_AssaultColony { public override void UpdateAllDuties() { foreach (Pawn p in lord.ownedPawns) { p.mindState.duty = new BossFightDuty(); } } } public class BossFightDuty : PawnDuty { //TODO: Create custom jobgivers to allow more boss-like behavior // JobGiver_AITrashBuildingsDistant public BossFightDuty() { locomotion = LocomotionUrgency.Sprint; canDig = true; def = new DutyDef { defName = "BossAssaultColony", alwaysShowWeapon = true, thinkNode = new ThinkNode_Priority { subNodes = { //unnecessary for now, need to reenable with adding human bosses //new JobGiver_TakeCombatEnhancingDrug(), new JobGiver_BossFightEnemy(), new JobGiver_AITrashColonyClose(), new JobGiver_AITrashBuildingsDistant(), new JobGiver_AIGotoNearestHostile(), new JobGiver_AITrashBuildingsDistant(), new JobGiver_AISapper() } } }; } } public class JobGiver_BossFightEnemy : JobGiver_AIFightEnemy { const float TargetAcquireRadius = 1000; const float TargetKeepRadius = 50; const int TicksSinceEngageToLoseTarget = 200; const int ExpiryTicks = 60; /* public override float GetPriority(Pawn pawn) { return base.GetPriority(pawn); } public override void ResolveReferences() { base.ResolveReferences(); } public override string ToString() { return base.ToString(); } public override ThinkResult TryIssueJobPackage(Pawn pawn, JobIssueParams jobParams) { return base.TryIssueJobPackage(pawn, jobParams); } protected override void ResolveSubnodes() { base.ResolveSubnodes(); }*/ protected override Job TryGiveJob(Pawn pawn) { UpdateEnemyTarget(pawn); Thing target = pawn.mindState.enemyTarget; if (target == null) { return null; } Verb verb = pawn.TryGetAttackVerb(); if (verb == null) { return null; } else if (verb.verbProps.MeleeRange) { return MeleeAttackJob(target); } if (((CoverUtility.CalculateOverallBlockChance(pawn.Position, target.Position, pawn.Map) > 0.01f && pawn.Position.Standable(pawn.Map)) || (pawn.Position - target.Position).LengthHorizontalSquared < 25) && verb.CanHitTarget(target)) { return new Job(JobDefOf.WaitCombat, ExpiryTicks, true); } if (!TryFindShootingPosition(pawn, out IntVec3 intVec)) { return null; } if (intVec == pawn.Position) { return new Job(JobDefOf.WaitCombat, ExpiryTicks, true); } Job job = new Job(JobDefOf.Goto, intVec); job.expiryInterval = ExpiryTicks; job.checkOverrideOnExpire = true; return job; } protected override Job MeleeAttackJob(Thing enemyTarget) { Job job = new Job(JobDefOf.AttackMelee, enemyTarget); job.expiryInterval = ExpiryTicks; job.checkOverrideOnExpire = true; job.expireRequiresEnemiesNearby = true; return job; } //TODO: Populate when ready for armed bosses protected override bool TryFindShootingPosition(Pawn pawn, out IntVec3 dest) { Log.Warning("Trying to find a shooting position for a boss. This shouldn't happen in this version."); dest = default(IntVec3); return false; } protected override void UpdateEnemyTarget(Pawn pawn) { Thing target = pawn.mindState.enemyTarget; if (target != null && (target.Destroyed || Find.TickManager.TicksGame - pawn.mindState.lastEngageTargetTick > 400 || !pawn.CanReach(target, PathEndMode.Touch, Danger.Deadly, false, TraverseMode.ByPawn) || (pawn.Position - target.Position).LengthHorizontalSquared > TargetKeepRadius * TargetKeepRadius || ((IAttackTarget) target).ThreatDisabled())) { target = null; } if (target == null) { target = FindAttackTargetIfPossible(pawn); if (target != null) { pawn.mindState.lastEngageTargetTick = Find.TickManager.TicksGame; pawn.GetLord()?.Notify_PawnAcquiredTarget(pawn, target); } } else { Thing newTarget = FindAttackTargetIfPossible(pawn); if (newTarget != null && newTarget != target) { pawn.mindState.lastEngageTargetTick = Find.TickManager.TicksGame; } target = newTarget; } pawn.mindState.enemyTarget = target; if (target is Pawn colonist && colonist.Faction == Faction.OfPlayer && pawn.Position.InHorDistOf(colonist.Position, TargetAcquireRadius)) { Find.TickManager.slower.SignalForceNormalSpeed(); } } private Thing FindAttackTargetIfPossible(Pawn pawn) { return pawn.TryGetAttackVerb() == null ? null : FindAttackTarget(pawn); } protected override Thing FindAttackTarget(Pawn pawn) { TargetScanFlags targetScanFlags = TargetScanFlags.NeedLOSToPawns | TargetScanFlags.NeedReachableIfCantHitFromMyPos | TargetScanFlags.NeedThreat; /*if (PrimaryVerbIsIncendiary(pawn)) { targetScanFlags |= TargetScanFlags.NeedNonBurning; }*/ return (Thing)AttackTargetFinder.BestAttackTarget(pawn, targetScanFlags, x => ExtraTargetValidator(pawn, x), 0f, TargetAcquireRadius, default(IntVec3), float.MaxValue, false); } /*private bool PrimaryVerbIsIncendiary(Pawn pawn) { if (pawn.equipment != null && pawn.equipment.Primary != null) { List<Verb> allVerbs = pawn.equipment.Primary.GetComp<CompEquippable>().AllVerbs; for (int i = 0; i < allVerbs.Count; i++) { if (allVerbs[i].verbProps.isPrimary) { return allVerbs[i].IsIncendiary(); } } } return false; }*/ } }
41,812
https://github.com/MaceM8/validarium/blob/master/packages/core/src/utils/index.js
Github Open Source
Open Source
MIT
2,021
validarium
MaceM8
JavaScript
Code
16
37
export { default as isNilOrAllIsNil } from './isNilOrAllIsNil'; export { default as allIsNil } from './allIsNil';
35,986
https://github.com/itamuria/expose/blob/master/R/dose_resp_ind.r
Github Open Source
Open Source
MIT
null
expose
itamuria
R
Code
146
366
#' Extract the information from the simulation data frame to analyse the dose response effects #' #' @param allsim dataset with all simulations values #' @param dataset dataset with all variables #' @param dr a vector with dose response values #' @return a data frame with dose response values #' @export dose_resp_ind <- function(allsim, dataset, dr = seq(0, 1, 0.1)) { dataset <- data.frame(dataset) N <- dim(dataset)[1] sim <- dim(allsim)[2] size <- length(dr) m2 <- NA sum_dr <- data.frame(matrix(NA, size, 3)) names(sum_dr) <- c("Quantile", "Mean", "SE") pos <- 1 for (g in 1:size) { newpos <- pos + N - 1 m3 <- as.matrix(allsim[pos:newpos, ]) for (f in 1:sim) { m1 <- mean(as.matrix(allsim[pos:newpos, f])) m2 <- c(m2, m1) } m2 <- m2[-1] se <- stats::sd(m2) sum_dr[g, 2] <- mean(m3) sum_dr[g, 3] <- se sum_dr[g, 1] <- paste0("DR_", dr[g]) pos <- newpos + 1 } return(sum_dr) }
13,994
https://github.com/fredmorcos/attic/blob/master/Others/Lowfat/src/lffont.cpp
Github Open Source
Open Source
Unlicense
2,022
attic
fredmorcos
C++
Code
366
895
//////////////////////////////////////////////////////////////////////////////// //3456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789 // // lowfat - an "engine" for natural document viewing for free desktop-systems // // copyright (c) 2007 Mirco Müller // // lowfat 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. // // lowfat 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 Foobar; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // //////////////////////////////////////////////////////////////////////////////// #include <fstream> #include <iostream> #include "include/lffont.h" #include "include/texture.h" LfFont::LfFont() { } LfFont::LfFont (const std::string& name) { std::ifstream file ((name + ".metrics").c_str ()); file >> height_; pixelHeight_ = height_; fontTexture_ = Texture::make (name + ".tga"); const float texWidth (fontTexture_->getWidth ()); const float texHeight (fontTexture_->getHeight ()); height_ /= texHeight; maxWidth_ = 0.0f; while (!file.eof ()) { int idx; float x; float y; float width; file >> idx; file >> x; file >> y; file >> width; pixelWidth_[idx] = width; if (width > maxWidth_) maxWidth_ = width; x /= texWidth + 1.0 / (texWidth * 2); y /= texHeight + 1.0 / (texHeight * 2); --width; width /= texWidth; x_[idx] = x; y_[idx] = y; width_[idx] = width; } } LfFont::~LfFont () { } float LfFont::getSCoordLeft (int i) const { return x_[i]; } float LfFont::getTCoordTop (int i) const { return y_[i]; } float LfFont::getSCoordRight (int i) const { return x_[i] + width_[i]; } float LfFont::getTCoordBottom (int i) const { return y_[i] + height_; } float LfFont::getSCoordWidth (int i) const { return width_[i]; } float LfFont::getTCoordHeight () const { return height_; } float LfFont::getWidth (int i) const { return pixelWidth_[i]; } float LfFont::getHeight () const { return pixelHeight_; } float LfFont::getMaxWidth () const { return maxWidth_; } TexturePtr LfFont::getTexture () const { return fontTexture_; }
11,450
https://github.com/mvarbanov97/BESL/blob/master/BESL.Domain/Entities/TeamInvite.cs
Github Open Source
Open Source
MIT
2,020
BESL
mvarbanov97
C#
Code
48
112
namespace BESL.Domain.Entities { using BESL.Domain.Infrastructure; public class TeamInvite : BaseDeletableModel<string> { public int TeamId { get; set; } public string TeamName { get; set; } public string SenderUsername { get; set; } public string PlayerId { get; set; } public Player Player { get; set; } } }
45,399
https://github.com/agrothe/saasy/blob/master/SaaSy.Web/Resources/Areas/Identity/Pages/Account/Login.Designer.cs
Github Open Source
Open Source
MIT
2,020
saasy
agrothe
C#
Code
605
1,558
//------------------------------------------------------------------------------ // <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> //------------------------------------------------------------------------------ namespace SaaSy.Web.Resources.Areas.Identity.Pages.Account { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Login { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Login() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SaaSy.Web.Resources.Areas.Identity.Pages.Account.Login", typeof(Login).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Email Address. /// </summary> public static string Email { get { return ResourceManager.GetString("Email", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Log in with your email address. /// </summary> public static string EmailLogin { get { return ResourceManager.GetString("EmailLogin", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The Email field is required. /// </summary> public static string EmailRequired { get { return ResourceManager.GetString("EmailRequired", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Forgot your password?. /// </summary> public static string ForgotYourPassword { get { return ResourceManager.GetString("ForgotYourPassword", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Please enter a valid email. /// </summary> public static string InvalidEmail { get { return ResourceManager.GetString("InvalidEmail", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Invalid login attempt.. /// </summary> public static string InvalidLoginAttempt { get { return ResourceManager.GetString("InvalidLoginAttempt", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Please enter a password with at least 8 mixed case letters, numbers and special characters.. /// </summary> public static string InvalidPassword { get { return ResourceManager.GetString("InvalidPassword", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Log in. /// </summary> public static string LogIn { get { return ResourceManager.GetString("LogIn", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Log in using your {0} account. /// </summary> public static string LogInUsingAccount { get { return ResourceManager.GetString("LogInUsingAccount", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use another service to log in.. /// </summary> public static string OauthLogin { get { return ResourceManager.GetString("OauthLogin", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Password. /// </summary> public static string Password { get { return ResourceManager.GetString("Password", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The Password field is required. /// </summary> public static string PasswordRequired { get { return ResourceManager.GetString("PasswordRequired", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Register as a new user. /// </summary> public static string RegisterAsNewUser { get { return ResourceManager.GetString("RegisterAsNewUser", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Remember me?. /// </summary> public static string RememberMe { get { return ResourceManager.GetString("RememberMe", resourceCulture); } } } }
25,915
https://github.com/worknenjoy/ahorta-client/blob/master/src/url.js
Github Open Source
Open Source
MIT
2,021
ahorta-client
worknenjoy
JavaScript
Code
18
76
//console.log(process.env.NODE_ENV) // export const host = process.env.NODE_ENV === 'production' ? 'https://ahorta.herokuapp.com' : 'https://ahorta-testing.herokuapp.com' export const host = 'https://ahorta.herokuapp.com'
832
https://github.com/phytertek/urb/blob/master/scripts/update-local-ip-for-app.js
Github Open Source
Open Source
MIT
null
urb
phytertek
JavaScript
Code
227
596
const os = require('os'); const fs = require('fs'); let IPAddress = process.argv[ 2 ] if( IPAddress == undefined ) { // Find out IP address const interfaces = os.networkInterfaces(); const addresses = []; for (var k in interfaces) for (var k2 in interfaces[k]) { const address = interfaces[ k ][ k2 ]; if ( address.family === 'IPv4' && !address.internal ) addresses.push(address.address); } if( addresses.length >= 0 ) IPAddress = addresses[ 0 ] } if( IPAddress != undefined ) { console.log( "IP Address:" + IPAddress ) updateIPInFile( './ios/UniversalRelayBoilerplate/AppDelegate.m', 'jsCodeLocation = [NSURL URLWithString:@"http:', ' jsCodeLocation = [NSURL URLWithString:@"http://' + IPAddress + ':8081/index.ios.bundle?platform=ios&dev=true"];' ) updateIPInFile( './app/app.js', 'let graphQLServerURL = "http://', 'let graphQLServerURL = "http://' + IPAddress + ':4444/graphql";' ) updateIPInFile( './.env', 'HOST=', 'HOST=' + IPAddress ) } else console.log( "IP Address not specified and could not be found" ) function updateIPInFile( fileName, searchString, newContentOfLine ) { let fileLines = fs.readFileSync( fileName, 'utf8' ).split( '\n' ) let index = 0 while( index < fileLines.length ) { if( fileLines[ index ].indexOf( searchString ) > -1 ) { if( fileLines[ index ] == newContentOfLine ) console.log( '[' + fileName + '] is already up to date' ) else { fileLines[ index ] = newContentOfLine; fs.writeFileSync( fileName, fileLines.join( '\n' ) ) console.log( '[' + fileName + '] has been updated with local IP ' + IPAddress ) } break } else index++ } }
44,687
https://github.com/rexxitall/fb-framework/blob/master/inc/fbfw/math/float2.bi
Github Open Source
Open Source
MIT
2,020
fb-framework
rexxitall
FreeBasic
Code
1,827
3,730
#ifndef __FBFW_MATH_FLOAT2__ #define __FBFW_MATH_FLOAT2__ namespace Math /' 2D vector | x | | y | '/ type _ Float2 declare constructor() declare constructor( _ byval as float => 0.0, _ byval as float => 0.0 ) declare constructor( _ byref as Float2 ) declare destructor() declare operator _ let( byref as Float2 ) declare operator _ cast() as string '' Swizzlings declare function yx() as Float2 declare function xx() as Float2 declare function yy() as Float2 '' Convenience functions declare function _ sideDistance( _ byref as const Float2, _ byref as const Float2 ) _ as float declare function _ dot( byref as Float2 ) as float declare function _ cross( byref as Float2 ) as float declare function _ length() as float declare sub _ setLength( byval as float ) declare function _ ofLength( byval as float ) as Float2 declare function _ squaredLength() as float declare function _ normalized() as Float2 declare sub _ normalize() declare sub _ turnLeft() declare function _ turnedLeft() as Float2 declare sub _ turnRight() declare function _ turnedRight() as Float2 declare sub _ rotate( byval as Math.Radians ) declare function _ rotated( byval as Math.Radians ) as Math.Float2 declare function _ angle() as Math.Radians declare function _ distance( byref as Float2 ) as float declare function _ squaredDistance( byref as Float2 ) as float declare sub _ lookAt( byref as Float2 ) as float _ x, y end type constructor Float2() x => 0.0 y => 0.0 end constructor constructor Float2( _ byval nx as float => 0.0, _ byval ny as float => 0.0 ) x => nx y => ny end constructor constructor Float2( _ byref rhs as Float2 ) x => rhs.x y => rhs.y end constructor destructor _ Float2() end destructor operator Float2.let( _ byref rhs as Float2 ) x => rhs.x y => rhs.y end operator operator Float2.cast() as string return( _ "| " & str( x ) & " |" & chr( 10 ) & chr( 13 ) & _ "| " & str( y ) & " |" & chr( 10 ) & chr( 13 ) ) end operator '' Swizzlings function Float2.yx() as Float2 return( Float2( y, x ) ) end function function Float2.xx() as Float2 return( Float2( x, x ) ) end function function Float2.yy() as Float2 return( Float2( y, y ) ) end function '' Basic arithmetic operators operator + ( _ byref lhs as Float2, _ byref rhs as Float2 ) as Float2 return( Float2( lhs.x + rhs.x, lhs.y + rhs.y ) ) end operator operator + ( _ byref lhs as Float2, _ byref rhs as float ) as Float2 return( Float2( lhs.x + rhs, lhs.y + rhs ) ) end operator operator + ( _ byref lhs as float, _ byref rhs as Float2 ) as Float2 return( Float2( lhs + rhs.x, lhs + rhs.y ) ) end operator operator - ( _ byref lhs as Float2, _ byref rhs as Float2 ) as Float2 return( Float2( lhs.x - rhs.x, lhs.y - rhs.y ) ) end operator operator - ( _ byref lhs as Float2, _ byref rhs as float ) as Float2 return( Float2( lhs.x - rhs, lhs.y - rhs ) ) end operator operator - ( _ byref lhs as float, _ byref rhs as Float2 ) as Float2 return( Float2( lhs - rhs.x, lhs - rhs.y ) ) end operator operator - ( byref lhs as Float2 ) as Float2 return( Float2( -lhs.x, -lhs.y ) ) end operator operator * ( _ byref lhs as Float2, _ byref rhs as Float2 ) as Float2 return( Float2( lhs.x * rhs.x, lhs.y * rhs.y ) ) end operator operator * ( _ byref lhs as Float2, _ byref rhs as float ) as Float2 return( Float2( lhs.x * rhs, lhs.y * rhs ) ) end operator operator * ( _ byref lhs as float, _ byref rhs as Float2 ) as Float2 return( Float2( lhs * rhs.x, lhs * rhs.y ) ) end operator operator * ( _ byref lhs as Float2, _ byref rhs as integer ) as Float2 return( Float2( lhs.x * rhs, lhs.y * rhs ) ) end operator operator * ( _ byref lhs as integer, _ byref rhs as Float2 ) as Float2 return( Float2( lhs * rhs.x, lhs * rhs.y ) ) end operator operator / ( _ byref lhs as Float2, _ byref rhs as Float2 ) as Float2 return( Float2( lhs.x / rhs.x, lhs.y / rhs.y ) ) end operator operator / ( _ byref lhs as Float2, _ byref rhs as float ) as Float2 return( Float2( lhs.x / rhs, lhs.y / rhs ) ) end operator operator \ ( _ byref lhs as Float2, _ byref rhs as integer ) as Float2 return( Float2( lhs.x \ rhs, lhs.y \ rhs ) ) end operator operator > ( _ byref lhs as Float2, _ byref rhs as Float2 ) as integer return( _ lhs.x > rhs.x andAlso _ lhs.y > rhs.y ) end operator operator < ( _ byref lhs as Float2, _ byref rhs as Float2 ) as integer return( _ lhs.x < rhs.x andAlso _ lhs.y < rhs.y ) end operator operator <= ( _ byref lhs as Float2, _ byref rhs as Float2 ) as integer return( _ lhs.x <= rhs.x andAlso _ lhs.y <= rhs.y ) end operator operator >= ( _ byref lhs as Float2, _ byref rhs as Float2 ) as integer return( _ lhs.x >= rhs.x andAlso _ lhs.y >= rhs.y ) end operator operator <> ( _ byref lhs as Float2, _ byref rhs as Float2 ) as integer return( _ lhs.x <> rhs.x orElse _ lhs.y <> rhs.y ) end operator operator = ( _ byref lhs as Float2, _ byref rhs as Float2 ) as integer return( _ lhs.x = rhs.x andAlso _ lhs.y = rhs.y ) end operator operator _ abs( _ byref rhs as Float2 ) _ as Float2 return( Float2( _ abs( rhs.x ), _ abs( rhs.y ) ) ) end operator /' Returns the dot product of this vector with another vector v. '/ function _ Float2.dot( _ byref v as Float2 ) _ as float return( x * v.x + y * v.y ) end function /' The cross product is not defined in 2d, so this function returns the z component of the cross product of this vector with vector v, if augmented to 3d. '/ function _ Float2.cross( _ byref v as Float2 ) _ as float return( x * v.y - y * v.x ) end function '' Returns the length of this vector function _ Float2.length() _ as float return( sqr( x ^ 2 + y ^ 2 ) ) end function '' Set the length for this vector sub _ Float2.setLength( _ byval value as float ) dim as float _ a => atan2( y, x ) x => value * cos( a ) y => value * sin( a ) end sub function _ Float2.ofLength( _ byval value as float ) _ as Float2 var _ v => Float2( x, y ) v.setLength( value ) return( v) end function /' Returns the squared length of this vector. Useful when one just want to compare two vectors to see which is longest, as this avoids computing the square root. '/ function _ Float2.squaredLength() _ as float return( x ^ 2 + y ^ 2 ) end function '' Returns a normalized copy of this vector function _ Float2.normalized() _ as Float2 dim as float _ l => sqr( x ^ 2 + y ^ 2 ) l => iif( l > 0.0!, 1.0! / l, 1.0! ) return( Float2( x * l, y * l ) ) end function '' Normalizes this vector sub _ Float2.normalize() dim as float _ l => sqr( x ^ 2 + y ^ 2 ) l => iif( l > 0.0!, 1.0! / l, 1.0! ) x *=> l y *=> l end sub /' turnLeft and turnRight rotate this vector 90 degrees to the left and right. Very useful to quickly find normals in 2D, as the normal of any vector is simply the vector rotated 90 degrees. So, if you want to find the normal of vector v, you can express it like this: n = normalized( turnLeft( v ) ) '/ sub _ Float2.turnLeft() this => Float2( y, -x ) end sub function _ Float2.turnedLeft() _ as Float2 return( Float2( y, -x ) ) end function sub _ Float2.turnRight() this => Float2( -y, x ) end sub function _ Float2.turnedRight() _ as Float2 return( Float2( -y, x ) ) end function /' Rotates this vector by anAngle '/ sub _ Float2.rotate( _ byval anAngle as Math.Radians ) dim as float _ si => sin( anAngle ), _ co => cos( anAngle ) this => Float2( _ x * co - y * si, _ x * si + y * co ) end sub function _ Float2.rotated( _ byval anAngle as Math.Radians ) _ as Math.Float2 dim as float _ si => sin( anAngle ), _ co => cos( anAngle ) return( Float2( _ x * co - y * si, _ x * si + y * co ) ) end function '' Returns the angle that this vector points to function _ Float2.angle() _ as Math.Radians return( atan2( y, x ) ) end function '' Returns the distance between this vector and another one function _ Float2.distance( _ byref v as Float2 ) _ as float return( ( this - v ).length ) end function /' Returns the squared distance to another vector. Useful to compare distances. '/ function _ Float2.squaredDistance( _ byref v as Float2 ) _ as float return( _ ( x - v.x ) ^ 2 + _ ( y - v.y ) ^ 2 ) end function /' Returns the distance of this Float2 from the half-space defined by p1 -> p2. '/ function _ Float2.sideDistance( _ byref p1 as const Float2, _ byref p2 as const Float2 ) _ as float return( _ ( p1.x - x ) * ( p2.y - y ) - _ ( p2.x - x ) * ( p1.y - y ) ) end function sub _ Float2.lookAt( _ byref another as Float2 ) dim as float _ l => length, _ nl => 1.0 / l x => ( ( another.x - x ) * nl ) * l y => ( ( another.y - y ) * nl ) * l end sub function _ vMax overload( _ byref p as Float2, _ byval v as float ) _ as Float2 return( Float2( _ fMax( p.x, v ), _ fMax( p.y, v ) ) ) end function function _ vMin overload( _ byref p as Float2, _ byval v as float ) _ as Float2 return( Float2( _ fMin( p.x, v ), _ fMin( p.y, v ) ) ) end function end namespace #endif
43,301
https://github.com/open-ms/all-svn-branches/blob/master/include/OpenMS/ANALYSIS/MAPMATCHING/LabeledPairFinder.h
Github Open Source
Open Source
Zlib, Apache-2.0
2,018
all-svn-branches
open-ms
C
Code
578
1,208
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2013. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -------------------------------------------------------------------------- // $Maintainer: $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #ifndef OPENMS_ANALYSIS_MAPMATCHING_LABELEDPAIRFINDER_H #define OPENMS_ANALYSIS_MAPMATCHING_LABELEDPAIRFINDER_H #include <OpenMS/ANALYSIS/MAPMATCHING/BaseGroupFinder.h> #include <boost/math/tr1.hpp> #include <cmath> namespace OpenMS { /** @brief The LabeledPairFinder allows the matching of labeled features (features with a fixed distance). Finds feature pairs that have a defined distance in RT and m/z in the same map. @htmlinclude OpenMS_LabeledPairFinder.parameters @todo Implement support for labeled MRM experiments, Q1 m/z value and charges. (Andreas) @todo Implement support for more than one mass delta, e.g. from missed cleavages and so on (Andreas) @ingroup FeatureGrouping */ class OPENMS_DLLAPI LabeledPairFinder : public BaseGroupFinder { public: /// Default constructor LabeledPairFinder(); /// Destructor inline virtual ~LabeledPairFinder() { } /// Returns an instance of this class static BaseGroupFinder * create() { return new LabeledPairFinder(); } /// Returns the name of this module static const String getProductName() { return "labeled_pair_finder"; } /** @brief Run the algorithm @note Exactly one @em input map has to be provided. @note The @em output map has to have two file descriptions, containing the same file name. The file descriptions have to be labeled 'heavy' and 'light'. @exception Exception::IllegalArgument is thrown if the input data is not valid. */ virtual void run(const std::vector<ConsensusMap> & input_maps, ConsensusMap & result_map); protected: /// return the p-value at position x for the bi-Gaussian distribution with mean @p m and standard deviation @p sig1 (left) and @p sig2 (right) inline DoubleReal PValue_(DoubleReal x, DoubleReal m, DoubleReal sig1, DoubleReal sig2) { if (m < x) { return 1 - boost::math::tr1::erf((x - m) / sig2 / 0.707106781); } else { return 1 - boost::math::tr1::erf((m - x) / sig1 / 0.707106781); } } private: /// Copy constructor not implemented => private LabeledPairFinder(const LabeledPairFinder & source); /// Assignment operator not implemented => private LabeledPairFinder & operator=(const LabeledPairFinder & source); }; // end of class LabeledPairFinder } // end of namespace OpenMS #endif // OPENMS_ANALYSIS_MAPMATCHER_LABELEDPAIRFINDER_H
49,285
https://github.com/FuzzySlipper/Framework/blob/master/Assets/Framework/UI/Easing.meta
Github Open Source
Open Source
MIT
2,020
Framework
FuzzySlipper
Unity3D Asset
Code
14
71
fileFormatVersion: 2 guid: 9d5eb743d570546f08d99d18162e4c08 folderAsset: yes timeCreated: 1438601493 licenseType: Store DefaultImporter: userData: assetBundleName: assetBundleVariant:
2,174
https://github.com/damianivanov/CS-ReactJS/blob/master/Project/client/src/services/taskService.js
Github Open Source
Open Source
MIT
null
CS-ReactJS
damianivanov
JavaScript
Code
266
761
import http from "./http-client"; import { getJWT } from "./userService"; // const headers = { // "auth-token": getJWT(), // }; export async function getMytasks() { const headers = { "auth-token": getJWT(), }; try { const myTasks = await http.get(`/tasks/myActiveTasks`, { headers: headers, }); return myTasks.data; } catch (error) { console.log(error.response.data.message); return error; } } export async function getTask(id) { const headers = { "auth-token": getJWT(), }; try { const task = await http.get(`/tasks/${id}`, { headers: headers, }); return task.data; } catch (error) { console.log(error.response.data.message); return error; } } export async function assignTask(task) { const headers = { "auth-token": getJWT(), }; try { const result = await http.post(`/tasks/`, task, { headers: headers, }); return result; } catch (error) { return error.response; } } export async function getTaskForProject(id) { const headers = { "auth-token": getJWT(), }; try { const task = await http.get(`/projects/${id}/tasks`, { headers: headers, }); return task.data; } catch (error) { console.log(error.response.data.message); return error; } } export async function deleteTask(id) { const headers = { "auth-token": getJWT(), }; try { const result = await http.delete(`/tasks/${id}`, { headers: headers, }); return result; } catch (error) { return error.response; } } export async function editTask(task) { task.id = task._id; delete task._id; delete task.__v; const headers = { "auth-token": getJWT(), }; try { const updated = await http.put(`/tasks/${task.id}`, task, { headers: headers, }); return updated; } catch (error) { console.log(error.response.data.message); return error.response; } } export async function completeTask(task) { const headers = { "auth-token": getJWT(), }; try { const updated = await http.post(`/tasks/${task.id}/results`, task, { headers: headers, }); return updated; } catch (error) { console.log(error.response.data.message); return error.response; } }
12,287
https://github.com/gistnu/ProTraveller/blob/master/src/providers/course-service/course-service.js
Github Open Source
Open Source
MIT
null
ProTraveller
gistnu
JavaScript
Code
232
718
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; var CourseServiceProvider = /** @class */ (function () { function CourseServiceProvider(http) { this.http = http; } CourseServiceProvider.prototype.getCourse = function () { return this.http.get('http://www2.cgistln.nu.ac.th/app_gistnu/php/protraveller.php').map(function (res) { return res.json(); }); }; CourseServiceProvider.prototype.getCourseDetail = function (id_prov) { return this.http.get('http://www2.cgistln.nu.ac.th/app_gistnu/php/select_prov.php?id_prov=' + id_prov).map(function (res) { return res.json(); }); }; CourseServiceProvider.prototype.getProvDetail = function (id_place) { return this.http.get('http://www2.cgistln.nu.ac.th/app_gistnu/php/select_place.php?id_place=' + id_place).map(function (res) { return res.json(); }); }; CourseServiceProvider.prototype.getHospital = function () { return this.http.get('http://www2.cgistln.nu.ac.th/app_gistnu/php/select_hospital.php').map(function (res) { return res.json(); }); }; CourseServiceProvider = __decorate([ Injectable(), __metadata("design:paramtypes", [Http]) ], CourseServiceProvider); return CourseServiceProvider; }()); export { CourseServiceProvider }; //# sourceMappingURL=course-service.js.map
37,411
https://github.com/fanglinchen/PrivacyStreams-Android/blob/master/privacystreams-core/src/main/java/com/github/privacystreams/location/LocationProcessor.java
Github Open Source
Open Source
Apache-2.0
2,017
PrivacyStreams-Android
fanglinchen
Java
Code
80
290
package com.github.privacystreams.location; import com.github.privacystreams.commons.ItemFunction; import com.github.privacystreams.core.Item; import com.github.privacystreams.core.UQI; import com.github.privacystreams.utils.Assertions; import java.util.List; /** * Created by yuanchun on 28/12/2016. * Process the location field in an item. */ abstract class LocationProcessor<Tout> extends ItemFunction<Tout> { private final String coordinatesField; LocationProcessor(String coordinatesField) { this.coordinatesField = Assertions.notNull("coordinatesField", coordinatesField); this.addParameters(this.coordinatesField); } @Override public final Tout apply(UQI uqi, Item input) { List<Double> coordinates = input.getValueByField(this.coordinatesField); double latitude = coordinates.get(0); double longitude = coordinates.get(1); return this.processLocation(latitude, longitude); } protected abstract Tout processLocation(double latitude, double longitude); }
48,173
https://github.com/amarildolikmeta/oac-explore/blob/master/utils/misc.py
Github Open Source
Open Source
MIT
null
oac-explore
amarildolikmeta
Python
Code
73
261
import torch def mellow_max(x, r, b=None): n = len(x) if b is None: shift = torch.stack(x).max(0)[0] else: shift = b mellow_max_loss = 0 for i in range(n): mellow_max_loss += torch.exp(x[i] - shift) if b is None: mellow_max_loss = torch.log(mellow_max_loss) / r else: mellow_max_loss = (torch.log(mellow_max_loss) + shift) / r return mellow_max_loss def reorder_and_match(source, target_order): new_target = torch.ones_like(source) for i in range(target_order.shape[0]): for j in range(target_order.shape[1]): new_target[target_order[i, j][0], j] = source[i, j] return new_target
33,934
https://github.com/wizardone/forminator/blob/master/spec/forminator_flow_spec.rb
Github Open Source
Open Source
MIT
null
forminator
wizardone
Ruby
Code
162
492
require 'spec_helper' RSpec.describe Forminator::Flow do let(:steps) { [FirstStep, SecondStep] } describe '#initialize' do it 'initializes the flow with steps' do flow = described_class.new(steps: steps) expect(flow.steps).to match_array steps end end describe '#current_step' do it 'returns the current step in the flow' do flow = described_class.new(steps: steps) expect(flow.current_step).to eq steps.first end end describe '#next_step' do it 'returns the next step in the flow' do flow = described_class.new(steps: steps) expect(flow.next_step).to eq steps.last end end describe '#previous_step' do it 'returns the previous step in the flow' do flow = described_class.new(steps: steps) expect(flow.next_step).to eq steps.last end end describe '#add' do it 'adds another step' do flow = described_class.new(steps: steps) flow.add(step: ThirdStep) expect(flow.steps).to include(ThirdStep) end it 'does not add another step if the step is not a subclass of forminator' do flow = described_class.new(steps: steps) expect { flow.add(step: BogusStep) }.to raise_error(Forminator::InvalidStep) end end describe '#remove' do it 'removes a step from the steps array' do flow = described_class.new(steps: steps) flow.remove(step: SecondStep) expect(flow.steps).to_not include(SecondStep) expect(flow.steps).to match_array([FirstStep]) end end end
38,730
https://github.com/yolgan67/react-sample-projects/blob/master/demo-cart/src/App.js
Github Open Source
Open Source
MIT
2,022
react-sample-projects
yolgan67
JavaScript
Code
124
406
import React from 'react'; import { ChakraProvider, Box, theme } from '@chakra-ui/react'; import { HashRouter as Router, Switch, Route } from 'react-router-dom'; import NavBar from './components/Navbar'; import Home from './components/Home'; import ProductDetails from './components/ProductDetails'; import ProductAddEdit from './components/ProductAddEdit'; import Cart from './components/Cart'; import { Provider } from 'react-redux'; import { store, persistor } from './store'; import { PersistGate } from 'redux-persist/integration/react'; function App() { return ( <Provider store={store}> <PersistGate loading={null} persistor={persistor}> <Router hashType="slash"> <ChakraProvider theme={theme}> <NavBar /> <Box textAlign="center" fontSize="xl" height="calc(100vh - 64px)" width="90%" pt={16} ml={'auto'} mr={'auto'} > <Switch> <Route exact path="/"> <Home /> </Route> <Route exact path="/product/add"> <ProductAddEdit /> </Route> <Route exact path="/product/:id"> <ProductDetails /> </Route> <Route exact path="/cart"> <Cart /> </Route> </Switch> </Box> </ChakraProvider> </Router> </PersistGate> </Provider> ); } export default App;
37,215
https://github.com/utastudents/selalib/blob/master/src/quadrature/fekete.py
Github Open Source
Open Source
CECILL-B
2,022
selalib
utastudents
Python
Code
494
1,633
import math #-------------------------------------------- # # Class to define a point with cartesian coordinates # #-------------------------------------------- class Point(object): def __init__(self, x, y): self.X = x self.Y = y def translation(self, dx, dy): self.X = self.X + dx self.Y = self.Y + dy def distance(self, other): # Distance to origin (0,0) dx = self.X - other.X dy = self.Y - other.Y return math.hypot(dx,dy) def __add__(self,other): x = self.X + other.X y = self.Y + other.Y return Point(x,y) def __mul__(self, val): return Point(self.X * val, self.Y * val) def __eq__(self, other): return ((self.X==other.X)and(self.Y==other.Y)) def __neq__(self, other): return ((self.X<>other.X)or(self.Y<>other.Y)) def __str__(self): return "(%s,%s)"%(self.X, self.Y) class Vector(Point): def __init__(self, p1, p2): self.X = p2.X - p1.X self.Y = p2.Y - p1.Y def __str__(self): return "(%s,%s)"%(self.X, self.Y) # def __add__(self, other): # res = Vector(self.X + other.X, self.Y + other.Y) # return res # def __mul__(self, other): # res = Vector(self.X * other.X, self.Y * other.Y) # return res # def __mul__(self, val): # res = Vector(self.X * val, self.Y * val) # return res def norm(self, other): # Same as distance for a point dx = self.X - other.X dy = self.Y - other.Y return math.hypot(dx,dy) #********************************************************** # Defines and returns coordinates of the Fekete # points of degree 3, plus associated weights # Reference: # Mark Taylor, Beth Wingate, Rachel Vincent, # An Algorithm for Computing Fekete Points in the Triangle, # SIAM Journal on Numerical Analysis, # Volume 38, Number 5, 2000, pages 1707-1720. #********************************************************** def fekete3(p1, p2, p3) : # Coordinates of base orbits points as defined in Ref orbit1 = Point(1./3., 1./3.) orbit2 = Point(0.0 , 0.0 ) orbit3 = Point(0.0 , 0.2763932023) orbits = [orbit1, orbit2, orbit3] weight1 = 0.45 weight2 = 1./60. weight3 = 1./12. weights = [weight1, weight2, weight3] # List containing points fekPts = [] fekWei = [] # Defining Fekete points parting from p1 v1 = Vector(p1, p2) v2 = Vector(p1, p3) for i in range(3) : orb = orbits[i] new_fek = (v1*orb.X + v2*orb.Y) + p1 new_fek2 = (v1*orb.Y + v2*orb.X) + p1 if (fekPts.count(new_fek) == 0) : fekPts.append(new_fek) fekWei.append(weights[i]) if (fekPts.count(new_fek2) == 0) : fekPts.append(new_fek2) fekWei.append(weights[i]) # Defining Fekete points parting from p2 v1 = Vector(p2, p1) v2 = Vector(p2, p3) for i in range(1,3) : orb = orbits[i] new_fek = (v1*orb.X + v2*orb.Y) + p2 new_fek2 = (v1*orb.Y + v2*orb.X) + p2 if (fekPts.count(new_fek) == 0) : fekPts.append(new_fek) fekWei.append(weights[i]) if (fekPts.count(new_fek2) == 0) : fekPts.append(new_fek2) fekWei.append(weights[i]) # Defining Fekete points parting from p3 v1 = Vector(p3, p2) v2 = Vector(p3, p1) for i in range(1,3) : orb = orbits[i] new_fek = (v1*orb.X + v2*orb.Y) + p3 new_fek2 = (v1*orb.Y + v2*orb.X) + p3 if (fekPts.count(new_fek) == 0) : fekPts.append(new_fek) fekWei.append(weights[i]) if (fekPts.count(new_fek2) == 0) : fekPts.append(new_fek2) fekWei.append(weights[i]) return [fekPts, fekWei] def main(): #Defining the vertices of the triangle p1 = Point(0,0) p2 = Point(1,0) p3 = Point(0,1) [fekPts, fekWei] = fekete3(p1, p2, p3) for i in range(len(fekPts)) : print '{0:2d} {1:6f} {2:6f} {3:6f}'.format(i+1, fekPts[i].X, fekPts[i].Y, fekWei[i]) main()
30,811
https://github.com/Flickswitch/vpp/blob/master/vendor/github.com/ligato/vpp-agent/plugins/vpp/puntplugin/vppcalls/vpp1908/dump_vppcalls.go
Github Open Source
Open Source
Apache-2.0
null
vpp
Flickswitch
Go
Code
563
1,949
// Copyright (c) 2019 Cisco and/or its affiliates. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package vpp1908 import ( "bytes" vpp_punt "github.com/ligato/vpp-agent/api/models/vpp/punt" "github.com/ligato/vpp-agent/plugins/vpp/binapi/vpp1908/punt" "github.com/ligato/vpp-agent/plugins/vpp/puntplugin/vppcalls" ) // DumpExceptions returns dump of registered punt exceptions. func (h *PuntVppHandler) DumpExceptions() (punts []*vppcalls.ExceptionDetails, err error) { reasons, err := h.dumpPuntReasons() if err != nil { return nil, err } reasonMap := make(map[uint32]string, len(reasons)) for _, r := range reasons { reasonMap[r.ID] = r.Reason.Name } if punts, err = h.dumpPuntExceptions(reasonMap); err != nil { h.log.Errorf("punt exception dump failed: %v", err) return nil, err } return punts, nil } func (h *PuntVppHandler) dumpPuntExceptions(reasons map[uint32]string) (punts []*vppcalls.ExceptionDetails, err error) { h.log.Debug("=> dumping exception punts") req := h.callsChannel.SendMultiRequest(&punt.PuntSocketDump{ Type: punt.PUNT_API_TYPE_EXCEPTION, }) for { d := &punt.PuntSocketDetails{} stop, err := req.ReceiveReply(d) if stop { break } if err != nil { return nil, err } if d.Punt.Type != punt.PUNT_API_TYPE_EXCEPTION { h.log.Warnf("VPP returned invalid punt type in exception punt dump: %v", d.Punt.Type) continue } puntData := d.Punt.Punt.GetException() reason := reasons[puntData.ID] socketPath := string(bytes.Trim(d.Pathname, "\x00")) h.log.Debugf(" - dumped exception punt: %+v (pathname: %s, reason: %s)", puntData, socketPath, reason) punts = append(punts, &vppcalls.ExceptionDetails{ Exception: &vpp_punt.Exception{ Reason: reason, SocketPath: vppConfigSocketPath, }, }) } return punts, nil } // DumpRegisteredPuntSockets returns punt to host via registered socket entries func (h *PuntVppHandler) DumpRegisteredPuntSockets() (punts []*vppcalls.PuntDetails, err error) { if punts, err = h.dumpPuntL4(); err != nil { h.log.Errorf("punt L4 dump failed: %v", err) return nil, err } return punts, nil } func (h *PuntVppHandler) dumpPuntL4() (punts []*vppcalls.PuntDetails, err error) { h.log.Debug("=> dumping L4 punts") req := h.callsChannel.SendMultiRequest(&punt.PuntSocketDump{ Type: punt.PUNT_API_TYPE_L4, }) for { d := &punt.PuntSocketDetails{} stop, err := req.ReceiveReply(d) if stop { break } if err != nil { return nil, err } if d.Punt.Type != punt.PUNT_API_TYPE_L4 { h.log.Warnf("VPP returned invalid punt type in L4 punt dump: %v", d.Punt.Type) continue } puntData := d.Punt.Punt.GetL4() socketPath := string(bytes.Trim(d.Pathname, "\x00")) h.log.Debugf(" - dumped L4 punt: %+v (pathname: %s)", puntData, socketPath) punts = append(punts, &vppcalls.PuntDetails{ PuntData: &vpp_punt.ToHost{ Port: uint32(puntData.Port), L3Protocol: parseL3Proto(puntData.Af), L4Protocol: parseL4Proto(puntData.Protocol), SocketPath: vppConfigSocketPath, }, SocketPath: socketPath, }) } return punts, nil } // DumpPuntReasons returns all known punt reasons from VPP func (h *PuntVppHandler) DumpPuntReasons() (reasons []*vppcalls.ReasonDetails, err error) { if reasons, err = h.dumpPuntReasons(); err != nil { h.log.Errorf("punt reasons dump failed: %v", err) return nil, err } return reasons, nil } func (h *PuntVppHandler) dumpPuntReasons() (reasons []*vppcalls.ReasonDetails, err error) { h.log.Debugf("=> dumping punt reasons") req := h.callsChannel.SendMultiRequest(&punt.PuntReasonDump{}) for { d := &punt.PuntReasonDetails{} stop, err := req.ReceiveReply(d) if stop { break } if err != nil { return nil, err } h.log.Debugf(" - dumped punt reason: %+v", d.Reason) reasons = append(reasons, &vppcalls.ReasonDetails{ Reason: &vpp_punt.Reason{ Name: d.Reason.Name, }, ID: d.Reason.ID, }) } return reasons, nil } func parseL3Proto(p punt.AddressFamily) vpp_punt.L3Protocol { switch p { case punt.ADDRESS_IP4: return vpp_punt.L3Protocol_IPv4 case punt.ADDRESS_IP6: return vpp_punt.L3Protocol_IPv6 } return vpp_punt.L3Protocol_UNDEFINED_L3 } func parseL4Proto(p punt.IPProto) vpp_punt.L4Protocol { switch p { case punt.IP_API_PROTO_TCP: return vpp_punt.L4Protocol_TCP case punt.IP_API_PROTO_UDP: return vpp_punt.L4Protocol_UDP } return vpp_punt.L4Protocol_UNDEFINED_L4 }
37,034
https://github.com/jianxuanbing/aspnetboilerplate/blob/master/src/Project/BeiDreamAbp.Presentation/Views/Editions/_CreateOrEditModal.cshtml
Github Open Source
Open Source
MIT
2,016
aspnetboilerplate
jianxuanbing
HTML+Razor
Code
109
596
@using Abp.Application.Editions @using Abp.Extensions @using BeiDreamAbp.Presentation.Models.Common.Modals @model BeiDreamAbp.Presentation.Models.Editions.CreateOrEditEditionModalViewModel <div id="CreateOrEditLanguageModal"> @Html.Partial("~/Views/Common/Modals/_ModalHeader.cshtml", new ModalHeaderViewModel(Model.IsEditMode ? ("编辑版本: " + Model.Edition.DisplayName) : "创建新版本")) <div class="modal-body"> <div> <!-- Nav tabs --> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"> <a href="#home" aria-controls="home" role="tab" data-toggle="tab"> 版本信息 </a> </li> <li role="presentation"> <a href="#profile" aria-controls="profile" role="tab" data-toggle="tab"> 特性参数列表 </a> </li> </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="home"> <form name="EditionInformationsForm" role="form" novalidate class="form-validation"> @if (Model.IsEditMode) { <input type="hidden" name="Id" value="@Model.Edition.Id" /> } <div class="form-group form-md-line-input form-md-floating-label"> <input class="form-control@(Model.Edition.DisplayName.IsNullOrEmpty() ? "" : " edited")" type="text" name="DisplayName" value="@Model.Edition.DisplayName" required maxlength="@Edition.MaxDisplayNameLength"> <label>@L("EditionName")</label> </div> </form> </div> <div role="tabpanel" class="tab-pane" id="profile"> profile </div> </div> </div> </div> @Html.Partial("~/Views/Common/Modals/_ModalFooterWithSaveAndCancel.cshtml") </div>
17,986
https://github.com/simonmonk/prog_pico_ed1/blob/master/05_03_morse_send_morse.py
Github Open Source
Open Source
MIT
2,022
prog_pico_ed1
simonmonk
Python
Code
108
304
codes = { "a" : ".-", "b" : "-...", "c" : "-.-.", "d" : "-..", "e" : ".", "f" : "..-.", "g" : "--.", "h" : "....", "i" : "..", "j" : ".---", "k" : "-.-", "l" : ".-..", "m" : "--", "n" : "-.", "o" : "---", "p" : ".--.", "q" : "--.-", "r" : ".-.", "s" : "...", "t" : "-", "u" : "..-", "v" : "...-", "w" : ".--", "x" : "-..-", "y" : "-.--", "z" : "--.." } def send_morse_for(character): if character == ' ': print("space") else: dots_n_dashes = codes.get(character.lower()) if dots_n_dashes: print(character + " " + dots_n_dashes) else: print("unknown character: " + character)
342
https://github.com/LX-s-Team/CookingLevel-Forge/blob/master/build/tmp/expandedArchives/forge-1.18.1-39.0.40_mapped_parchment_2021.12.19-1.18.1-sources.jar_8da1e53bade44c6d138d26d6ab1ad1d3/net/minecraft/nbt/LongArrayTag.java
Github Open Source
Open Source
MIT
null
CookingLevel-Forge
LX-s-Team
Java
Code
476
1,556
package net.minecraft.nbt; import it.unimi.dsi.fastutil.longs.LongSet; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.ArrayUtils; public class LongArrayTag extends CollectionTag<LongTag> { private static final int SELF_SIZE_IN_BITS = 192; public static final TagType<LongArrayTag> TYPE = new TagType.VariableSize<LongArrayTag>() { public LongArrayTag load(DataInput p_128865_, int p_128866_, NbtAccounter p_128867_) throws IOException { p_128867_.accountBits(192L); int i = p_128865_.readInt(); p_128867_.accountBits(64L * (long)i); long[] along = new long[i]; for(int j = 0; j < i; ++j) { along[j] = p_128865_.readLong(); } return new LongArrayTag(along); } public StreamTagVisitor.ValueResult parse(DataInput p_197501_, StreamTagVisitor p_197502_) throws IOException { int i = p_197501_.readInt(); long[] along = new long[i]; for(int j = 0; j < i; ++j) { along[j] = p_197501_.readLong(); } return p_197502_.visit(along); } public void skip(DataInput p_197499_) throws IOException { p_197499_.skipBytes(p_197499_.readInt() * 8); } public String getName() { return "LONG[]"; } public String getPrettyName() { return "TAG_Long_Array"; } }; private long[] data; public LongArrayTag(long[] pData) { this.data = pData; } public LongArrayTag(LongSet pDataSet) { this.data = pDataSet.toLongArray(); } public LongArrayTag(List<Long> pDataList) { this(toArray(pDataList)); } private static long[] toArray(List<Long> pDataList) { long[] along = new long[pDataList.size()]; for(int i = 0; i < pDataList.size(); ++i) { Long olong = pDataList.get(i); along[i] = olong == null ? 0L : olong; } return along; } public void write(DataOutput pOutput) throws IOException { pOutput.writeInt(this.data.length); for(long i : this.data) { pOutput.writeLong(i); } } public byte getId() { return 12; } public TagType<LongArrayTag> getType() { return TYPE; } public String toString() { return this.getAsString(); } /** * Creates a deep copy of the value held by this tag. Primitive and string tage will return the same tag instance * while all other objects will return a new tag instance with the copied data. */ public LongArrayTag copy() { long[] along = new long[this.data.length]; System.arraycopy(this.data, 0, along, 0, this.data.length); return new LongArrayTag(along); } public boolean equals(Object pOther) { if (this == pOther) { return true; } else { return pOther instanceof LongArrayTag && Arrays.equals(this.data, ((LongArrayTag)pOther).data); } } public int hashCode() { return Arrays.hashCode(this.data); } public void accept(TagVisitor pVisitor) { pVisitor.visitLongArray(this); } public long[] getAsLongArray() { return this.data; } public int size() { return this.data.length; } public LongTag get(int p_128811_) { return LongTag.valueOf(this.data[p_128811_]); } public LongTag set(int p_128813_, LongTag p_128814_) { long i = this.data[p_128813_]; this.data[p_128813_] = p_128814_.getAsLong(); return LongTag.valueOf(i); } public void add(int p_128832_, LongTag p_128833_) { this.data = ArrayUtils.add(this.data, p_128832_, p_128833_.getAsLong()); } public boolean setTag(int pIndex, Tag pNbt) { if (pNbt instanceof NumericTag) { this.data[pIndex] = ((NumericTag)pNbt).getAsLong(); return true; } else { return false; } } public boolean addTag(int pIndex, Tag pNbt) { if (pNbt instanceof NumericTag) { this.data = ArrayUtils.add(this.data, pIndex, ((NumericTag)pNbt).getAsLong()); return true; } else { return false; } } public LongTag remove(int p_128830_) { long i = this.data[p_128830_]; this.data = ArrayUtils.remove(this.data, p_128830_); return LongTag.valueOf(i); } public byte getElementType() { return 4; } public void clear() { this.data = new long[0]; } public StreamTagVisitor.ValueResult accept(StreamTagVisitor p_197497_) { return p_197497_.visit(this.data); } }
37,936
https://github.com/xmn-services/buckets-network/blob/master/libs/file/encrypted_file_disk_repository.go
Github Open Source
Open Source
MIT
null
buckets-network
xmn-services
Go
Code
106
318
package file import ( "github.com/xmn-services/buckets-network/libs/cryptography/encryption" ) type encryptedFileDiskRepository struct { encryption encryption.Encryption repository Repository } func createEncryptedFileDiskRepository(encryption encryption.Encryption, repository Repository) Repository { out := encryptedFileDiskRepository{ encryption: encryption, repository: repository, } return &out } // Exists returns true if the file exists, false otherwise func (app *encryptedFileDiskRepository) Exists(relativePath string) bool { return app.repository.Exists(relativePath) } // Retrieve retrieves data from file using its name func (app *encryptedFileDiskRepository) Retrieve(relativePath string) ([]byte, error) { encrypted, err := app.repository.Retrieve(relativePath) if err != nil { return nil, err } return app.encryption.Decrypt(string(encrypted)) } // RetrieveAll retrieves all files in a given directory func (app *encryptedFileDiskRepository) RetrieveAll(relativePath string) ([]string, error) { return app.repository.RetrieveAll(relativePath) }
41,760
https://github.com/AllenZMC/strimzi-kafka-operator/blob/master/documentation/modules/metrics/proc-metrics-kafka-deploy-options.adoc
Github Open Source
Open Source
Apache-2.0
2,021
strimzi-kafka-operator
AllenZMC
AsciiDoc
Code
217
558
// This assembly is included in the following assemblies: // // metrics/assembly_metrics-kafka.adoc [id='proc-metrics-kafka-deploy-options-{context}'] = Deploying Prometheus metrics configuration Strimzi provides xref:ref-metrics-yaml-files-{context}[example custom resource configuration YAML files] with relabeling rules. To apply metrics configuration of relabeling rules, do one of the following: * xref:proc-metrics-kafka-{context}[Copy the example configuration to your own custom resource definition] * xref:proc-metrics-deploying-kafka-{context}[Deploy the custom resource with the metrics configuration] [id='proc-metrics-kafka-{context}'] == Copying Prometheus metrics configuration to a custom resource To use Grafana dashboards for monitoring, copy xref:ref-metrics-yaml-files-{context}[the example metrics configuration to a custom resource]. In this procedure, the `Kafka` resource is updated, but the procedure is the same for all components that support monitoring. .Procedure Perform the following steps for each `Kafka` resource in your deployment. . Update the `Kafka` resource in an editor. + [source,shell,subs="+quotes,attributes"] ---- kubectl edit kafka _KAFKA-CONFIG-FILE_ ---- . Copy the xref:ref-metrics-yaml-files-{context}[example configuration in `kafka-metrics.yaml`] to your own `Kafka` resource definition. . Save the file, and wait for the updated resource to be reconciled. [id='proc-metrics-deploying-kafka-{context}'] == Deploying a Kafka cluster with Prometheus metrics configuration To use Grafana dashboards for monitoring, you can deploy xref:ref-metrics-config-files-{context}[an example Kafka cluster with metrics configuration]. In this procedure, The `kafka-metrics.yaml` file is used for the `Kafka` resource. .Procedure * Deploy the Kafka cluster with the xref:ref-metrics-yaml-files-{context}[example metrics configuration]. + [source,shell,subs="+attributes"] ---- kubectl apply -f kafka-metrics.yaml ----
16,306
https://github.com/benetech/Winnow2.0/blob/master/winnow/utils/brightness.py
Github Open Source
Open Source
MIT
2,022
Winnow2.0
benetech
Python
Code
101
313
import os import numpy as np from joblib import load DEFAULT_DIRECTORY = os.path.join(os.path.dirname(__file__), "models") GRAY_ESTIMATION_MODEL = os.path.join(DEFAULT_DIRECTORY, "gb_gray_model.joblib") def load_gray_estimation_model(): """ Loads pretrained gray_max estimation model. This model has been trained to estimate the maximum level of brightness detected within all sampled frames of a video from the video-level features. The model was optimized to maximize precision instead of recall (so less false positives would be filtered out). Returns: Scikit-learn[Estimator]: A pretrained GB model """ model = load(GRAY_ESTIMATION_MODEL) return model def get_gray_max(video_level_features) -> float: model = load_gray_estimation_model() predictions = model.predict(video_level_features) return predictions[0] def get_brightness_estimation(video_level_features) -> float: video_level_features = np.nan_to_num(video_level_features) return get_gray_max(video_level_features)
32,283
https://github.com/SJ-magic-work-Isetan2017/work___IS_Dmx/blob/master/th_Event.cpp
Github Open Source
Open Source
MIT
null
work___IS_Dmx
SJ-magic-work-Isetan2017
C++
Code
158
812
/************************************************************ ************************************************************/ #include <unistd.h> #include "th_Event.h" /************************************************************ function ************************************************************/ /****************************** ******************************/ THREAD__EVENT_TIMETABLE::THREAD__EVENT_TIMETABLE() { for(int i = 0; i < NUM_BUFFERS; i++){ TimeTable[i] = new TIME_N_DATASET__EVENT[NUM_SAMPLES_PER_BUFFER]; } } /****************************** ******************************/ THREAD__EVENT_TIMETABLE::~THREAD__EVENT_TIMETABLE() { for(int i = 0; i < NUM_BUFFERS; i++){ delete[] TimeTable[i]; } } /****************************** ******************************/ void THREAD__EVENT_TIMETABLE::set_LogFile_id() { LogFile_id = THREAD_TIMETABLE__EVENT; } /****************************** ******************************/ FILE* THREAD__EVENT_TIMETABLE::open_ScenarioFile() { FILE* fp = fopen("../../../Dmx_Anim.txt", "r"); return fp; } /****************************** ******************************/ void THREAD__EVENT_TIMETABLE::print_ScenarioFileName() { printf("Dmx_Anim.txt not found\n\n"); } /****************************** ******************************/ void THREAD__EVENT_TIMETABLE::SetTime_DataToCharge(int time) { data_to_charge.time_ms = time; } /****************************** ******************************/ void THREAD__EVENT_TIMETABLE::chargeTimeTable_byCopying(int BufferId_toCharge, int Charge_id) { TimeTable[BufferId_toCharge][Charge_id] = data_to_charge; } /****************************** ******************************/ void THREAD__EVENT_TIMETABLE::SetData_DataToCharge(FILE* fp) { char buf[BUF_SIZE]; fscanf(fp, "%s", buf); data_to_charge.EventId = atoi(buf); } /****************************** ******************************/ void THREAD__EVENT_TIMETABLE::set_outputData(int BufferId, int id) { data_to_output = TimeTable[BufferId][id]; } /****************************** ******************************/ void THREAD__EVENT_TIMETABLE::set_outputData_None() { TIME_N_DATASET__EVENT temp = {0, 0/* EVENT__NONE(StageManager.h) */}; data_to_output = temp; } /****************************** ******************************/ int THREAD__EVENT_TIMETABLE::get_TimeData_from_TimeTable(int BufferId, int id) { return TimeTable[BufferId][id].time_ms; } /****************************** ******************************/ int THREAD__EVENT_TIMETABLE::checkEvent() { return data_to_output.EventId; }
3,011
https://github.com/Nukepayload2/ryu/blob/master/visualbasic/D2s.vb
Github Open Source
Open Source
BSL-1.0, Apache-2.0
null
ryu
Nukepayload2
Visual Basic
Code
2,794
6,126
Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Module D2s <Obsolete("Types with embedded references are not supported in this version of your compiler.")> Private Function mulShiftAll(m As ULong, mul As Span(Of ULong), j As Integer, ByRef vp As ULong, ByRef vm As ULong, mmShift As UInteger) As ULong m <<= 1 ' m is maximum 55 bits Dim tmp As ULong = Nothing Dim lo As ULong = umul128(m, mul(0), tmp) Dim hi As ULong = Nothing Dim mid As ULong = tmp + umul128(m, mul(1), hi) hi += Convert.ToUInt64(mid < tmp) ' overflow into hi Dim lo2 As ULong = lo + mul(0) Dim mid2 As ULong = mid + mul(1) + Convert.ToUInt64(lo2 < lo) Dim hi2 As ULong = hi + Convert.ToUInt64(mid2 < mid) vp = shiftright128(mid2, hi2, (j - 64 - 1)) If mmShift = 1 Then Dim lo3 As ULong = lo - mul(0) Dim mid3 As ULong = mid - mul(1) - Convert.ToUInt64(lo3 > lo) Dim hi3 As ULong = hi - Convert.ToUInt64(mid3 > mid) vm = shiftright128(mid3, hi3, (j - 64 - 1)) Else Dim lo3 As ULong = lo + lo Dim mid3 As ULong = mid + mid + Convert.ToUInt64(lo3 < lo) Dim hi3 As ULong = hi + hi + Convert.ToUInt64(mid3 < mid) Dim lo4 As ULong = lo3 - mul(0) Dim mid4 As ULong = mid3 - mul(1) - Convert.ToUInt64(lo4 > lo3) Dim hi4 As ULong = hi3 - Convert.ToUInt64(mid4 > mid3) vm = shiftright128(mid4, hi4, (j - 64)) End If Return shiftright128(mid, hi, (j - 64 - 1)) End Function Private Function decimalLength17(v As ULong) As Integer ' This is slightly faster than a loop. ' The average output length is 16.38 digits, so we check high-to-low. ' Function precondition: v is not an 18, 19, or 20-digit number. ' (17 digits are sufficient for round-tripping.) Debug.Assert(v < 100000000000000000UL) If v >= 10000000000000000UL Then Return 17 End If If v >= 1000000000000000UL Then Return 16 End If If v >= 100000000000000UL Then Return 15 End If If v >= 10000000000000UL Then Return 14 End If If v >= 1000000000000UL Then Return 13 End If If v >= 100000000000UL Then Return 12 End If If v >= 10000000000UL Then Return 11 End If If v >= 1000000000UL Then Return 10 End If If v >= 100000000UL Then Return 9 End If If v >= 10000000UL Then Return 8 End If If v >= 1000000UL Then Return 7 End If If v >= 100000UL Then Return 6 End If If v >= 10000UL Then Return 5 End If If v >= 1000UL Then Return 4 End If If v >= 100UL Then Return 3 End If If v >= 10UL Then Return 2 End If Return 1 End Function ' A floating decimal representing m * 10^e. Private Structure floating_decimal_64 Public mantissa As ULong ' Decimal exponent's range is -324 to 308 ' inclusive, and can fit in a short if needed. Public exponent As Integer End Structure <Obsolete("Types with embedded references are not supported in this version of your compiler.")> Private Function d2d(ieeeMantissa As ULong, ieeeExponent As UInteger) As floating_decimal_64 Dim e2 As Integer Dim m2 As ULong If ieeeExponent = Nothing Then ' We subtract 2 so that the bounds computation has 2 additional bits. e2 = 1 - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS - 2 m2 = ieeeMantissa Else e2 = CInt(ieeeExponent) - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS - 2 m2 = (1UL << DOUBLE_MANTISSA_BITS) Or ieeeMantissa End If Dim even As Boolean = (m2 And 1UL) = Nothing Dim acceptBounds As Boolean = even ' Step 2: Determine the interval of valid decimal representations. Dim mv As ULong = 4UL * m2 ' Implicit bool -> int conversion. True is 1, false is Nothing. Dim mmShift As UInteger = Convert.ToUInt32(ieeeMantissa <> Nothing OrElse ieeeExponent <= 1UI) ' We would compute mp and mm like this: ' ulong mp = 4 * m2 + 2; ' ulong mm = mv - 1 - mmShift; ' Step 3: Convert to a decimal power base using 128-bit arithmetic. Dim vr, vp, vm As ULong Dim e10 As Integer Dim vmIsTrailingZeros As Boolean = False Dim vrIsTrailingZeros As Boolean = False If e2 >= Nothing Then ' I tried special-casing q == Nothing, but there was no effect on performance. ' This expression is slightly faster than max(0, log10Pow2(e2) - 1). Dim q As UInteger = log10Pow2(e2) - Convert.ToUInt32(e2 > 3) e10 = CInt(q) Dim k As Integer = DOUBLE_POW5_INV_BITCOUNT + pow5bits(CInt(q)) - 1 Dim i As Integer = -e2 + CInt(q) + k vr = mulShiftAll(m2, DOUBLE_POW5_INV_SPLIT(CInt(q)), i, vp, vm, mmShift) If q <= 21 Then ' This should use q <= 22, but I think 21 is also safe. Smaller values ' may still be safe, but it's more difficult to reason about them. ' Only one of mp, mv, and mm can be a multiple of 5, if any. Dim mvMod5 As UInteger = (CUInt(mv)) - 5UI * (CUInt(div5(mv))) If mvMod5 = Nothing Then vrIsTrailingZeros = multipleOfPowerOf5(mv, q) ElseIf acceptBounds Then ' Same as min(e2 + (~mm & 1), pow5Factor(mm)) >= q ' <=> e2 + (~mm & 1) >= q && pow5Factor(mm) >= q ' <=> true && pow5Factor(mm) >= q, since e2 >= q. vmIsTrailingZeros = multipleOfPowerOf5(mv - 1UL - mmShift, q) Else ' Same as min(e2 + 1, pow5Factor(mp)) >= q. vp -= Convert.ToUInt64(multipleOfPowerOf5(mv + 2UL, q)) End If End If Else ' This expression is slightly faster than max(0, log10Pow5(-e2) - 1). Dim q As UInteger = log10Pow5(-e2) - Convert.ToUInt32(-e2 > 1) e10 = CInt(q) + e2 Dim i As Integer = -e2 - CInt(q) Dim k As Integer = pow5bits(i) - DOUBLE_POW5_BITCOUNT Dim j As Integer = CInt(q) - k vr = mulShiftAll(m2, DOUBLE_POW5_SPLIT(i), j, vp, vm, mmShift) If q <= 1 Then ' {vr,vp,vm} is trailing zeros if {mv,mp,mm} has at least q trailing Nothing bits. ' mv = 4 * m2, so it always has at least two trailing Nothing bits. vrIsTrailingZeros = True If acceptBounds Then ' mm = mv - 1 - mmShift, so it has 1 trailing Nothing bit iff mmShift == 1. vmIsTrailingZeros = mmShift = 1 Else ' mp = mv + 2, so it always has at least one trailing Nothing bit. vp -= 1UL End If ElseIf q < 63 Then ' TODO(ulfjack): Use a tighter bound here. ' We want to know if the full product has at least q trailing zeros. ' We need to compute min(p2(mv), p5(mv) - e2) >= q ' <=> p2(mv) >= q && p5(mv) - e2 >= q ' <=> p2(mv) >= q (because -e2 >= q) vrIsTrailingZeros = multipleOfPowerOf2(mv, CInt(q)) End If End If ' Step 4: Find the shortest decimal representation in the interval of valid representations. Dim removed As Integer = Nothing Dim lastRemovedDigit As Byte = Nothing Dim output As ULong ' On average, we remove ~2 digits. If vmIsTrailingZeros OrElse vrIsTrailingZeros Then ' General case, which happens rarely (~0.7%). Do Dim vpDiv10 As ULong = div10(vp) Dim vmDiv10 As ULong = div10(vm) If vpDiv10 <= vmDiv10 Then Exit Do End If Dim vmMod10 As UInteger = (CUInt(vm)) - 10UI * (CUInt(vmDiv10)) Dim vrDiv10 As ULong = div10(vr) Dim vrMod10 As UInteger = (CUInt(vr)) - 10UI * (CUInt(vrDiv10)) vmIsTrailingZeros = vmIsTrailingZeros And vmMod10 = Nothing vrIsTrailingZeros = vrIsTrailingZeros And lastRemovedDigit = Nothing lastRemovedDigit = CByte(vrMod10) vr = vrDiv10 vp = vpDiv10 vm = vmDiv10 removed += 1 Loop If vmIsTrailingZeros Then Do Dim vmDiv10 As ULong = div10(vm) Dim vmMod10 As UInteger = (CUInt(vm)) - 10UI * (CUInt(vmDiv10)) If vmMod10 <> Nothing Then Exit Do End If Dim vpDiv10 As ULong = div10(vp) Dim vrDiv10 As ULong = div10(vr) Dim vrMod10 As UInteger = (CUInt(vr)) - 10UI * (CUInt(vrDiv10)) vrIsTrailingZeros = vrIsTrailingZeros And lastRemovedDigit = Nothing lastRemovedDigit = CByte(vrMod10) vr = vrDiv10 vp = vpDiv10 vm = vmDiv10 removed += 1 Loop End If If vrIsTrailingZeros AndAlso lastRemovedDigit = 5 AndAlso vr Mod 2UL = Nothing Then ' Round even if the exact number is .....50..0. lastRemovedDigit = 4 End If ' We need to take vr + 1 if vr is outside bounds or we need to round up. output = vr + Convert.ToUInt64((vr = vm AndAlso (Not acceptBounds OrElse Not vmIsTrailingZeros)) OrElse lastRemovedDigit >= 5) Else ' Specialized for the common case (~99.3%). Percentages below are relative to this. Dim roundUp As Boolean = False Dim vpDiv100 As ULong = div100(vp) Dim vmDiv100 As ULong = div100(vm) If vpDiv100 > vmDiv100 Then ' Optimization: remove two digits at a time (~86.2%). Dim vrDiv100 As ULong = div100(vr) Dim vrMod100 As UInteger = (CUInt(vr)) - 100UI * (CUInt(vrDiv100)) roundUp = vrMod100 >= 50UI vr = vrDiv100 vp = vpDiv100 vm = vmDiv100 removed += 2 End If ' Loop iterations below (approximately), without optimization above: ' Nothing: Nothing.03%, 1: 13.8%, 2: 70.6%, 3: 14.0%, 4: 1.40%, 5: Nothing.14%, 6+: Nothing.02% ' Loop iterations below (approximately), with optimization above: ' Nothing: 70.6%, 1: 27.8%, 2: 1.40%, 3: Nothing.14%, 4+: Nothing.02% Do Dim vpDiv10 As ULong = div10(vp) Dim vmDiv10 As ULong = div10(vm) If vpDiv10 <= vmDiv10 Then Exit Do End If Dim vrDiv10 As ULong = div10(vr) Dim vrMod10 As UInteger = (CUInt(vr)) - 10UI * (CUInt(vrDiv10)) roundUp = vrMod10 >= 5UI vr = vrDiv10 vp = vpDiv10 vm = vmDiv10 removed += 1 Loop ' We need to take vr + 1 if vr is outside bounds or we need to round up. output = vr + Convert.ToUInt64(vr = vm Or roundUp) End If Dim exp As Integer = e10 + removed Dim fd As floating_decimal_64 fd.exponent = exp fd.mantissa = output Return fd End Function <Obsolete("Types with embedded references are not supported in this version of your compiler.")> Private Function to_chars(v As floating_decimal_64, sign As Boolean, result As Span(Of Char)) As Integer ' Step 5: Print the decimal representation. Dim index As Integer = Nothing If sign Then 'INSTANT VB WARNING: An assignment within expression was extracted from the following statement: 'ORIGINAL LINE: result[index++] = "-"c; result(index) = "-"c index += 1 End If Dim output As ULong = v.mantissa Dim olength As Integer = decimalLength17(output) ' Print the decimal digits. ' The following code is equivalent to: ' for (uint i = Nothing; i < olength - 1; ++i) { ' uint c = output % 10; output /= 10; ' result[index + olength - i] = (char) ('0' + c); ' } ' result[index] = '0' + output % 10; Dim i As Integer = Nothing ' We prefer 32-bit operations, even on 64-bit platforms. ' We have at most 17 digits, and uint can store 9 digits. ' If output doesn't fit into uint, we cut off 8 digits, ' so the rest will fit into uint. Dim output2 As UInteger If (output >> 32) <> Nothing Then ' Expensive 64-bit division. Dim q As ULong = div1e8(output) output2 = (CUInt(output)) - 100000000UI * (CUInt(q)) output = q Dim c As UInteger = output2 Mod 10000UI output2 \= 10000UI Dim d As UInteger = output2 Mod 10000UI Dim c0 As UInteger = (c Mod 100UI) << 1UI Dim c1 As UInteger = (c \ 100UI) << 1UI Dim d0 As UInteger = (d Mod 100UI) << 1UI Dim d1 As UInteger = (d \ 100UI) << 1UI memcpy(result.Slice(index + olength - i - 1), DIGIT_TABLE, c0, 2) memcpy(result.Slice(index + olength - i - 3), DIGIT_TABLE, c1, 2) memcpy(result.Slice(index + olength - i - 5), DIGIT_TABLE, d0, 2) memcpy(result.Slice(index + olength - i - 7), DIGIT_TABLE, d1, 2) i += 8 End If output2 = CUInt(output) Do While output2 >= 10000UI Dim c As UInteger = output2 Mod 10000UI output2 \= 10000UI Dim c0 As UInteger = (c Mod 100UI) << 1UI Dim c1 As UInteger = (c \ 100UI) << 1UI memcpy(result.Slice(index + olength - i - 1), DIGIT_TABLE, c0, 2) memcpy(result.Slice(index + olength - i - 3), DIGIT_TABLE, c1, 2) i += 4 Loop If output2 >= 100UI Then Dim c As UInteger = (output2 Mod 100UI) << 1UI output2 \= 100UI memcpy(result.Slice(index + olength - i - 1), DIGIT_TABLE, c, 2) i += 2 End If If output2 >= 10UI Then Dim c As UInteger = output2 << 1 ' We can't use memcpy here: the decimal dot goes between these two digits. result(index + olength - i) = DIGIT_TABLE(CInt(c + 1UI)) result(index) = DIGIT_TABLE(CInt(c)) Else result(index) = ChrW(AscW("0"c) + CInt(output2)) End If ' Print decimal point if needed. If olength > 1 Then result(index + 1) = "."c index += olength + 1 Else index += 1 End If ' Print the exponent. 'INSTANT VB WARNING: An assignment within expression was extracted from the following statement: 'ORIGINAL LINE: result[index++] = "E"c; result(index) = "E"c index += 1 Dim exp As Integer = v.exponent + CInt(olength) - 1 If exp < Nothing Then 'INSTANT VB WARNING: An assignment within expression was extracted from the following statement: 'ORIGINAL LINE: result[index++] = "-"c; result(index) = "-"c index += 1 exp = -exp End If If exp >= 100 Then Dim c As Integer = exp Mod 10 memcpy(result.Slice(index), DIGIT_TABLE, 2 * (exp \ 10), 2) result(index + 2) = ChrW(AscW("0"c) + c) index += 3 ElseIf exp >= 10 Then memcpy(result.Slice(index), DIGIT_TABLE, 2 * exp, 2) index += 2 Else 'INSTANT VB WARNING: An assignment within expression was extracted from the following statement: 'ORIGINAL LINE: result[index++] = (char)("0"c + exp); result(index) = ChrW(AscW("0"c) + exp) index += 1 End If Return index End Function Private Function d2d_small_int(ieeeMantissa As ULong, ieeeExponent As UInteger, ByRef v As floating_decimal_64) As Boolean Dim m2 As ULong = (1UL << DOUBLE_MANTISSA_BITS) Or ieeeMantissa Dim e2 As Integer = CInt(ieeeExponent) - DOUBLE_BIAS - DOUBLE_MANTISSA_BITS If e2 > Nothing Then ' f = m2 * 2^e2 >= 2^53 is an integer. ' Ignore this case for now. Return False End If If e2 < -52 Then ' f < 1. Return False End If ' Since 2^52 <= m2 < 2^53 and Nothing <= -e2 <= 52: 1 <= f = m2 / 2^-e2 < 2^53. ' Test if the lower -e2 bits of the significand are Nothing, i.e. whether the fraction is Nothing. Dim mask As ULong = (1UL << -e2) - 1UL Dim fraction As ULong = m2 And mask If fraction <> Nothing Then Return False End If ' f is an integer in the range [1, 2^53). ' Note: mantissa might contain trailing (decimal) Nothing's. ' Note: since 2^53 < 10^16, there is no need to adjust decimalLength17(). v.mantissa = m2 >> -e2 v.exponent = Nothing Return True End Function <Obsolete("Types with embedded references are not supported in this version of your compiler.")> Private Function d2s_buffered_n(f As Double, result As Span(Of Char)) As Integer ' Step 1: Decode the floating-point number, and unify normalized and subnormal cases. Dim bits As ULong = double_to_bits(f) ' Decode bits into sign, mantissa, and exponent. Dim ieeeSign As Boolean = ((bits >> (DOUBLE_MANTISSA_BITS + DOUBLE_EXPONENT_BITS)) And 1UL) <> Nothing Dim ieeeMantissa As ULong = bits And ((1UL << DOUBLE_MANTISSA_BITS) - 1UL) Dim ieeeExponent As UInteger = CUInt((bits >> DOUBLE_MANTISSA_BITS) And ((1UI << DOUBLE_EXPONENT_BITS) - 1UL)) ' Case distinction; exit early for the easy cases. If ieeeExponent = ((1UI << DOUBLE_EXPONENT_BITS) - 1UI) OrElse (ieeeExponent = Nothing AndAlso ieeeMantissa = Nothing) Then Return copy_special_str(result, ieeeSign, Convert.ToBoolean(ieeeExponent), Convert.ToBoolean(ieeeMantissa)) End If Dim v As floating_decimal_64 = Nothing Dim isSmallInt As Boolean = d2d_small_int(ieeeMantissa, ieeeExponent, v) If isSmallInt Then ' For small integers in the range [1, 2^53), v.mantissa might contain trailing (decimal) zeros. ' For scientific notation we need to move these zeros into the exponent. ' (This is not needed for fixed-point notation, so it might be beneficial to trim ' trailing zeros in to_chars only if needed - once fixed-point notation output is implemented.) Do Dim q As ULong = div10(v.mantissa) Dim r As UInteger = CUInt(v.mantissa) - 10UI * CUInt(q) If r <> Nothing Then Exit Do End If v.mantissa = q v.exponent += 1 Loop Else v = d2d(ieeeMantissa, ieeeExponent) End If Return to_chars(v, ieeeSign, result) End Function <Obsolete("Types with embedded references are not supported in this version of your compiler.")> Private Sub d2s_buffered(f As Double, result As Span(Of Char)) Dim index As Integer = d2s_buffered_n(f, result) ' Terminate the string. result(index) = Nothing End Sub <StructLayout(LayoutKind.Sequential, Size:=24 * 2)> Private Structure StackAllocChar24 Dim FirstValue As Char End Structure #Disable Warning BC40000 Public Function DoubleToString(f As Double) As String Return DoubleToStringInternal(f) End Function #Enable Warning BC40000 <MethodImpl(MethodImplOptions.AggressiveInlining)> <Obsolete("Types with embedded references are not supported in this version of your compiler.")> Private Function DoubleToStringInternal(f As Double) As String Dim allocated As StackAllocChar24 Dim result As Span(Of Char) = MemoryMarshal.CreateSpan(allocated.FirstValue, 24) Dim index As Integer = d2s_buffered_n(f, result) Return New String(result.Slice(0, index)) End Function End Module
19,423
https://github.com/caligaris/azure-powershell/blob/master/src/ResourceManager/KeyVault/Commands.KeyVault/Commands/ManagedStorageAccounts/SetAzureKeyVaultManagedStorageSasDefinition.cs
Github Open Source
Open Source
Apache-2.0, MIT
2,018
azure-powershell
caligaris
C#
Code
1,855
5,446
// ---------------------------------------------------------------------------------- // // Copyright Microsoft 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. // ---------------------------------------------------------------------------------- using System; using Microsoft.Azure.Commands.KeyVault.Models; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Management.Automation; using System.Text; using System.Xml; namespace Microsoft.Azure.Commands.KeyVault { [Cmdlet( VerbsCommon.Set, CmdletNoun.AzureKeyVaultManagedStorageSasDefinition, SupportsShouldProcess = true, HelpUri = Constants.KeyVaultHelpUri, DefaultParameterSetName = ParameterSetRawSas )] [OutputType( typeof( ManagedStorageSasDefinition ) )] public partial class SetAzureKeyVaultManagedStorageSasDefinition : KeyVaultCmdletBase { private const string ParameterSetRawSas = "RawSas"; [Parameter( Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, HelpMessage = "Vault name. Cmdlet constructs the FQDN of a vault based on the name and currently selected environment." )] [ValidateNotNullOrEmpty] public string VaultName { get; set; } [Parameter( Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true, HelpMessage = "Key Vault managed storage account name. Cmdlet constructs the FQDN of a managed storage account name from vault name, currently " + "selected environment and manged storage account name." )] [ValidateNotNullOrEmpty] [Alias( Constants.StorageAccountName )] public string AccountName { get; set; } [Parameter( Mandatory = true, Position = 2, ValueFromPipelineByPropertyName = true, HelpMessage = "Storage sas definition name. Cmdlet constructs the FQDN of a storage sas definition from vault name, currently " + "selected environment, storage account name and sas definition name." )] [ValidateNotNullOrEmpty] [Alias( Constants.SasDefinitionName )] public string Name { get; set; } [Parameter( Mandatory = true, Position = 3, ValueFromPipelineByPropertyName = true, HelpMessage = "Sas definition parameters that will be used to create the sas token.", ParameterSetName = ParameterSetRawSas )] [Obsolete("-Parameter will be removed and replaced by -TemplateUri and -SasType in May 2018")] [ValidateNotNull] public Hashtable Parameter { get; set; } [Parameter( Mandatory = false, HelpMessage = "Disables the use of sas definition for generation of sas token." )] public SwitchParameter Disable { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable representing tags of sas definition." )] [Alias( Constants.TagsAlias )] public Hashtable Tag { get; set; } #region Common SAS Arguments private const string TargetStorageVersionHelpMessage = "Specifies the signed storage service version to use to authenticate requests made with the SAS token."; [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocAccountSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceBlobSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceContainerSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceFileSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceShareSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceQueueSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetAdhocServiceTableSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceBlobSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceContainerSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceFileSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceShareSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceQueueSas )] [Parameter( HelpMessage = TargetStorageVersionHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceTableSas )] [ValidateNotNullOrEmpty] public string TargetStorageVersion { get { return _targetStorageVersion; } set { _targetStorageVersion = value; } } private string _targetStorageVersion = "2016-05-31"; // default version private static class SharedAccessProtocols { public const string HttpsOnly = "HttpsOnly"; public const string HttpsOrHttp = "HttpsOrHttp"; } private const string ProtocolHelpMessage = "Protocol can be used in the request with the SAS token. Possbile values include 'HttpsOnly','HttpsOrHttp'"; [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocAccountSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceBlobSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceContainerSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceFileSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceShareSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceQueueSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetAdhocServiceTableSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceBlobSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceContainerSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceFileSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceShareSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceQueueSas )] [Parameter( HelpMessage = ProtocolHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceTableSas )] [ValidateNotNull] [ValidateSet( SharedAccessProtocols.HttpsOnly, SharedAccessProtocols.HttpsOrHttp )] public string Protocol { get; set; } // ReSharper disable once InconsistentNaming private const string IPAddressOrRangeHelpMessage = "IP, or IP range ACL (access control list) of the request that would be accepted by Azure Storage. E.g. '168.1.5.65' or '168.1.5.60-168.1.5.70'"; [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocAccountSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceBlobSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceContainerSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceFileSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceShareSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceQueueSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetAdhocServiceTableSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceBlobSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceContainerSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceFileSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceShareSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceQueueSas )] [Parameter( HelpMessage = IPAddressOrRangeHelpMessage, ParameterSetName = ParameterSetStoredPolicyServiceTableSas )] [ValidateNotNullOrEmpty] // ReSharper disable once InconsistentNaming public string IPAddressOrRange { get; set; } private const string ValidityPeriodHelpMessage = "Validity period that will get used to set the expiry time of sas token from the time it gets generated"; [Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocAccountSas )] [Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceBlobSas )] [Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceContainerSas )] [Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceShareSas )] [Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceFileSas )] [Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceQueueSas )] [Parameter( Mandatory = true, HelpMessage = ValidityPeriodHelpMessage, ParameterSetName = ParameterSetAdhocServiceTableSas )] [ValidateNotNull] public TimeSpan? ValidityPeriod { get; set; } private const string PermissionsMessage = "Permissions. Possible values include 'Add','Create','Delete','List','Process','Query','Read','Update','Write'"; [Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocAccountSas )] [Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceBlobSas )] [Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceContainerSas )] [Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceFileSas )] [Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceShareSas )] [Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceQueueSas )] [Parameter( Mandatory = true, HelpMessage = PermissionsMessage, ParameterSetName = ParameterSetAdhocServiceTableSas )] [ValidateSet( SasPermissions.Add, SasPermissions.Create, SasPermissions.Delete, SasPermissions.List, SasPermissions.Process, SasPermissions.Read, SasPermissions.Query, SasPermissions.Update, SasPermissions.Write )] [ValidateNotNull] public string[] Permission { get; set; } protected KeyValuePair<string, string>? TargetStorageVersionParameter { get { if ( string.IsNullOrWhiteSpace( TargetStorageVersion ) ) return null; return new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedVersion, TargetStorageVersion ); } } protected KeyValuePair<string, string>? ProtocolParameter { get { if ( string.IsNullOrWhiteSpace( Protocol ) ) return null; if ( Protocol.Equals( SharedAccessProtocols.HttpsOnly, StringComparison.OrdinalIgnoreCase ) ) return new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedProtocols, "https" ); if ( Protocol.Equals( SharedAccessProtocols.HttpsOrHttp, StringComparison.OrdinalIgnoreCase ) ) return new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedProtocols, "https,http" ); throw new ArgumentOutOfRangeException(); } } // ReSharper disable once InconsistentNaming protected KeyValuePair<string, string>? IPAddressOrRangeParameter { get { if ( string.IsNullOrWhiteSpace( IPAddressOrRange ) ) return null; return new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedIp, IPAddressOrRange ); } } protected KeyValuePair<string, string>? ValidityPeriodParameter { get { if ( ValidityPeriod == null ) return null; return new KeyValuePair<string, string>( SasDefinitionParameterConstants.ValidityPeriod, XmlConvert.ToString( ValidityPeriod.Value ) ); } } protected void AddIfNotNull( KeyValuePair<string, string>? keyVaultPair, IDictionary<string, string> targetDictionary ) { if ( keyVaultPair != null ) targetDictionary.Add( keyVaultPair.Value.Key, keyVaultPair.Value.Value ); } private static class SasPermissions { public const string Read = "Read"; public const string Write = "Write"; public const string Delete = "Delete"; public const string List = "List"; public const string Add = "Add"; public const string Create = "Create"; public const string Update = "Update"; public const string Process = "Process"; public const string Query = "Query"; } private KeyValuePair<string, string>? PermissionParameter { get { if ( Permission == null || Permission.Length == 0 ) return null; var builder = new StringBuilder(); var permissionsSet = new HashSet<string>( Permission, StringComparer.OrdinalIgnoreCase ); if ( ParameterSetName.Equals( ParameterSetAdhocAccountSas ) ) { //order is important here if ( permissionsSet.Contains( SasPermissions.Read ) ) builder.Append( "r" ); if ( permissionsSet.Contains( SasPermissions.Write ) ) builder.Append( "w" ); if ( permissionsSet.Contains( SasPermissions.Delete ) ) builder.Append( "d" ); if ( permissionsSet.Contains( SasPermissions.List ) ) builder.Append( "l" ); if ( permissionsSet.Contains( SasPermissions.Add ) ) builder.Append( "a" ); if ( permissionsSet.Contains( SasPermissions.Create ) ) builder.Append( "c" ); if ( permissionsSet.Contains( SasPermissions.Update ) ) builder.Append( "u" ); if ( permissionsSet.Contains( SasPermissions.Process ) ) builder.Append( "p" ); // query is not allowed with account sas if ( permissionsSet.Contains( SasPermissions.Query ) ) throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, Properties.Resources.InvalidSasPermission, SasPermissions.Query ) ); } else { //order is important here if ( permissionsSet.Contains( SasPermissions.Query ) ) builder.Append( "r" ); if ( permissionsSet.Contains( SasPermissions.Read ) ) builder.Append( "r" ); if ( permissionsSet.Contains( SasPermissions.Add ) ) builder.Append( "a" ); if ( permissionsSet.Contains( SasPermissions.Create ) ) builder.Append( "c" ); if ( permissionsSet.Contains( SasPermissions.Write ) ) builder.Append( "w" ); if ( permissionsSet.Contains( SasPermissions.Update ) ) builder.Append( "u" ); if ( permissionsSet.Contains( SasPermissions.Delete ) ) builder.Append( "d" ); if ( permissionsSet.Contains( SasPermissions.List ) ) builder.Append( "l" ); if ( permissionsSet.Contains( SasPermissions.Process ) ) builder.Append( "p" ); } return new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedPermissions, builder.ToString() ); } } #endregion private IDictionary<string, string> GetParameters() { switch ( ParameterSetName ) { case ParameterSetRawSas: { var dictionary = new Dictionary<string, string>(); #pragma warning disable CS0618 foreach ( DictionaryEntry p in Parameter ) #pragma warning restore CS0618 { if ( p.Key == null || string.IsNullOrEmpty( p.Key.ToString() ) ) throw new ArgumentException( "An invalid parameter was specified." ); dictionary[p.Key.ToString()] = ( p.Value == null ) ? string.Empty : p.Value.ToString(); } return dictionary; } case ParameterSetAdhocAccountSas: return GetParameters( SasDefinitionParameterConstants.AccountSasTypeValue, null, null ); case ParameterSetAdhocServiceContainerSas: case ParameterSetStoredPolicyServiceContainerSas: return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeBlobValue, "c" ); case ParameterSetAdhocServiceBlobSas: case ParameterSetStoredPolicyServiceBlobSas: return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeBlobValue, "b" ); case ParameterSetAdhocServiceShareSas: case ParameterSetStoredPolicyServiceShareSas: return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeFileValue, "s" ); case ParameterSetAdhocServiceFileSas: case ParameterSetStoredPolicyServiceFileSas: return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeFileValue, "f" ); case ParameterSetAdhocServiceTableSas: case ParameterSetStoredPolicyServiceTableSas: return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeTableValue, null ); case ParameterSetAdhocServiceQueueSas: case ParameterSetStoredPolicyServiceQueueSas: return GetParameters( SasDefinitionParameterConstants.ServiceSasTypeValue, SasDefinitionParameterConstants.ServiceSasTypeQueueValue, null ); default: throw new InvalidOperationException( string.Format( CultureInfo.InvariantCulture, "Invalid parameter set {0}", ParameterSetName ) ); } } private IDictionary<string, string> GetParameters( string sasType, string serviceSasType, string resourceType ) { var parameters = new Dictionary<string, string>(); AddIfNotNull( new KeyValuePair<string, string>( SasDefinitionParameterConstants.SasType, sasType ), parameters ); AddIfNotNull( string.IsNullOrWhiteSpace( serviceSasType ) ? (KeyValuePair<string, string>?) null : new KeyValuePair<string, string>( SasDefinitionParameterConstants.ServiceSasType, serviceSasType ), parameters ); AddIfNotNull( TargetStorageVersionParameter, parameters ); AddIfNotNull( ProtocolParameter, parameters ); AddIfNotNull( IPAddressOrRangeParameter, parameters ); AddIfNotNull( ValidityPeriodParameter, parameters ); AddIfNotNull( ServicesParameter, parameters ); AddIfNotNull( ResourceTypeParameter, parameters ); AddIfNotNull( string.IsNullOrWhiteSpace( resourceType ) ? (KeyValuePair<string, string>?) null : new KeyValuePair<string, string>( SasDefinitionParameterConstants.SignedResourceTypes, resourceType ), parameters ); AddIfNotNull( PermissionParameter, parameters ); AddIfNotNull( ApiVersionParameter, parameters ); AddIfNotNull( BlobParameter, parameters ); AddIfNotNull( ContainerParameter, parameters ); AddIfNotNull( PathParameter, parameters ); AddIfNotNull( ShareParameter, parameters ); AddIfNotNull( QueueParameter, parameters ); AddIfNotNull( TableParameter, parameters ); AddIfNotNull( PolicyParamater, parameters ); AddIfNotNull( SharedAccessBlobHeaderCacheControlParameter, parameters ); AddIfNotNull( SharedAccessBlobHeaderContentDispositionParameter, parameters ); AddIfNotNull( SharedAccessBlobHeaderContentEncodingParameter, parameters ); AddIfNotNull( SharedAccessBlobHeaderContentLanguageParameter, parameters ); AddIfNotNull( SharedAccessBlobHeaderContentTypeParameter, parameters ); AddIfNotNull( StartPartitionKeyParameter, parameters ); AddIfNotNull( EndPartitionKeyParameter, parameters ); AddIfNotNull( StartRowKeyParameter, parameters ); AddIfNotNull( EndRowKeyParameter, parameters ); return parameters; } public override void ExecuteCmdlet() { if ( ShouldProcess( Name, Properties.Resources.SetManagedStorageSasDefinition ) ) { var sasDefinition = DataServiceClient.SetManagedStorageSasDefinition( VaultName, AccountName, Name, GetParameters(), new ManagedStorageSasDefinitionAttributes( !Disable.IsPresent ), Tag ); WriteObject( sasDefinition ); } } } }
44,930
https://github.com/CANToolz/CANToolz/blob/master/setup.py
Github Open Source
Open Source
BSD-3-Clause, MIT, Apache-2.0
2,021
CANToolz
CANToolz
Python
Code
51
234
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Alexey Sintsov' from setuptools import setup, find_packages setup( name='CANToolz', version='3.7.0', description='Framework for black-box Controller Area Network (CAN) bus analysis.', author='Alexey Sintsov', author_email='alex.sintsov@gmail.com', license='Apache 2.0', keywords='framework black-box CAN analysis security', packages=find_packages(), scripts=['bin/cantoolz'], include_package_data=True, zip_safe=False, url='https://github.com/CANToolz/CANToolz', install_requires=[ 'flask', 'pyserial', 'mido', 'numpy', 'bitstring' ], )
17,319
https://github.com/chiamaka-123/BabylonNative/blob/master/Core/Graphics/Source/Apple/macOS/GraphicsPlatform.mm
Github Open Source
Open Source
MIT
2,022
BabylonNative
chiamaka-123
Objective-C++
Code
73
312
#include <Babylon/GraphicsPlatform.h> #include <GraphicsImpl.h> #include <AppKit/Appkit.h> #include <MetalKit/MetalKit.h> namespace Babylon { void GraphicsImpl::ConfigureBgfxPlatformData(const WindowConfiguration& config, bgfx::PlatformData& pd) { pd.ndt = nullptr; pd.nwh = config.WindowPtr; pd.context = nullptr; pd.backBuffer = nullptr; pd.backBufferDS = nullptr; } void GraphicsImpl::ConfigureBgfxPlatformData(const ContextConfiguration& config, bgfx::PlatformData& pd) { pd.ndt = nullptr; pd.nwh = nullptr; pd.context = config.Context; pd.backBuffer = nullptr; pd.backBufferDS = nullptr; } float GraphicsImpl::UpdateDevicePixelRatio() { std::scoped_lock lock{m_state.Mutex}; MTKView* view = GetNativeWindow<WindowType>(); m_state.Resolution.DevicePixelRatio = view.window.screen.backingScaleFactor; return m_state.Resolution.DevicePixelRatio; } }
19,978
https://github.com/roboterclubaachen/xpcc-doc/blob/master/docs/api/classxpcc_1_1_angle.js
Github Open Source
Open Source
BSD-3-Clause
2,019
xpcc-doc
roboterclubaachen
JavaScript
Code
10
57
var classxpcc_1_1_angle = [ [ "Type", "classxpcc_1_1_angle.html#adfdd030c52e037e1e807e239827476d3", null ] ];
19,372
https://github.com/benzei/dataexplorer/blob/master/Presentation.Tests/Views/ScatterPlots/Scalers/VectorScalerTests.cs
Github Open Source
Open Source
BSD-3-Clause
2,014
dataexplorer
benzei
C#
Code
65
240
using System.Windows; using DataExplorer.Presentation.Views.ScatterPlots.Scalers; using NUnit.Framework; namespace DataExplorer.Presentation.Tests.Views.ScatterPlots.Scalers { [TestFixture] public class VectorScalerTests { private VectorScaler _scaler; [SetUp] public void SetUp() { _scaler = new VectorScaler(); } [Test] public void TestScaleVectorShouldScaleVector() { var vector = new Vector(0, 0); var controlSize = new Size(10, 10); var viewExtent = new Rect(0, 0, 10, 10); var result = _scaler.ScaleVector(vector, controlSize, viewExtent); Assert.That(result.X, Is.EqualTo(0)); Assert.That(result.Y, Is.EqualTo(0)); } } }
2,826
https://github.com/tonywh/es50w-project1/blob/master/password.py
Github Open Source
Open Source
MIT
null
es50w-project1
tonywh
Python
Code
58
236
import hashlib, binascii, os # Returns salt + password-hash ready for storing. def hash_password(password): salt = hashlib.sha256(os.urandom(60)).hexdigest().encode('ascii') hash_bin = hashlib.pbkdf2_hmac('sha512', password.encode('utf-8'), salt, 100000) hash = binascii.hexlify(hash_bin) return (salt + hash).decode('ascii') # Returns True on correct match def verify_password(stored_password, provided_password): salt = stored_password[:64] stored_hash = stored_password[64:] hash_bin = hashlib.pbkdf2_hmac('sha512', provided_password.encode('utf-8'), salt.encode('ascii'), 100000) hash = binascii.hexlify(hash_bin).decode('ascii') return hash == stored_hash
37,168
https://github.com/Hephateus/Alice/blob/master/src/types/core/TextBasedChannel.ts
Github Open Source
Open Source
MIT
2,021
Alice
Hephateus
TypeScript
Code
28
55
import { DMChannel, NewsChannel, TextChannel, ThreadChannel } from "discord.js"; /** * Channels where users can type. */ export type TextBasedChannel = DMChannel | TextChannel | NewsChannel | ThreadChannel;
35,015
https://github.com/pnnl/cuVite/blob/master/compare.cpp
Github Open Source
Open Source
BSD-3-Clause
2,020
cuVite
pnnl
C++
Code
1,231
3,323
#include "compare.hpp" extern std::ofstream ofs; //Only a single process performs the cluster comparisons //Assume that clusters have been numbered in a contiguous manner //Assume that C1 is the truth data void compare_communities(std::vector<GraphElem> const& C1, std::vector<GraphElem> const& C2) { // number of vertices of two sets must match const GraphElem N1 = C1.size(); const GraphElem N2 = C2.size(); assert(N1>0 && N2>0); assert(N1 == N2); int nT; #pragma omp parallel { nT = omp_get_num_threads(); } //Compute number of communities in each set: GraphElem nC1=-1; #pragma omp parallel for reduction(max: nC1) for(GraphElem i = 0; i < N1; i++) { if (C1[i] > nC1) { nC1 = C1[i]; } } nC1++; // nC1 contains index, so need to +1 GraphElem nC2=-1; #pragma omp parallel for reduction(max: nC2) for(GraphElem i = 0; i < N2; i++) { if (C2[i] > nC2) { nC2 = C2[i]; } } nC2++; #if defined(DONT_CREATE_DIAG_FILES) std::cout << "Number of unique communities in C1 = " << nC1 << ", and C2 = " << nC2 << std::endl; #else ofs << "Number of unique communities in C1 = " << nC1 << ", and C2 = " << nC2 << std::endl; #endif //////////STEP 1: Create a CSR-like datastructure for communities in C1 GraphElem* commPtr1 = new GraphElem[nC1+1]; GraphElem* commIndex1 = new GraphElem[N1]; GraphElem* commAdded1 = new GraphElem[nC1]; GraphElem* clusterDist1 = new GraphElem[nC1]; //For Gini coefficient // Initialization #pragma omp parallel for for(GraphElem i = 0; i < nC1; i++) { commPtr1[i] = 0; commAdded1[i] = 0; } commPtr1[nC1] = 0; // Count the size of each community #pragma omp parallel for for(GraphElem i = 0; i < N1; i++) { #pragma omp atomic update commPtr1[C1[i]+1]++; } #pragma omp parallel for for(GraphElem i = 0; i < nC1; i++) { clusterDist1[i] = commPtr1[i+1]; //Zeroth position is not valid } //Prefix sum: for(GraphElem i=0; i<nC1; i++) { commPtr1[i+1] += commPtr1[i]; } //Group vertices with the same community in particular order #pragma omp parallel for for (GraphElem i=0; i<N1; i++) { long ca; #pragma omp atomic capture ca = commAdded1[C1[i]]++; GraphElem Where = commPtr1[C1[i]] + ca; commIndex1[Where] = i; //The vertex id } delete []commAdded1; #ifdef DEBUG_PRINTF ofs << "Done building structure for C1..." << std::endl; #endif //////////STEP 2: Create a CSR-like datastructure for communities in C2 GraphElem* commPtr2 = new GraphElem[nC2+1]; GraphElem* commIndex2 = new GraphElem[N2]; GraphElem* commAdded2 = new GraphElem[nC2]; GraphElem* clusterDist2 = new GraphElem[nC2]; //For Gini coefficient // Initialization #pragma omp parallel for for(GraphElem i = 0; i < nC2; i++) { commPtr2[i] = 0; commAdded2[i] = 0; } commPtr2[nC2] = 0; // Count the size of each community #pragma omp parallel for for(GraphElem i = 0; i < N2; i++) { #pragma omp atomic update commPtr2[C2[i]+1]++; } #pragma omp parallel for for(GraphElem i = 0; i < nC2; i++) { clusterDist2[i] = commPtr2[i+1]; //Zeroth position is not valid } //Prefix sum: for(GraphElem i=0; i<nC2; i++) { commPtr2[i+1] += commPtr2[i]; } //Group vertices with the same community in particular order #pragma omp parallel for for (GraphElem i=0; i<N2; i++) { long ca; #pragma omp atomic capture ca = commAdded2[C2[i]]++; GraphElem Where = commPtr2[C2[i]] + ca; commIndex2[Where] = i; //The vertex id } delete []commAdded2; #ifdef DEBUG_PRINTF ofs << "Done building structure for C2..." << std::endl; #endif //////////STEP 3: Compute statistics: // thread-private vars GraphElem tSameSame[nT], tSameDiff[nT], tDiffSame[nT], nAgree[nT]; #pragma omp parallel for for (int i=0; i < nT; i++) { tSameSame[i] = 0; tSameDiff[i] = 0; tDiffSame[i] = 0; nAgree[i] = 0; } //Compare all pairs of vertices from the perspective of C1 (ground truth): #pragma omp parallel { int tid = omp_get_thread_num(); #pragma omp for for(GraphElem ci = 0; ci < nC1; ci++) { GraphElem adj1 = commPtr1[ci]; GraphElem adj2 = commPtr1[ci+1]; for(GraphElem i = adj1; i < adj2; i++) { for(GraphElem j = i+1; j < adj2; j++) { //Check if the two vertices belong to the same community in C2 if(C2[commIndex1[i]] == C2[commIndex1[j]]) { tSameSame[tid]++; } else { tSameDiff[tid]++; } }//End of for(j) }//End of for(i) }//End of for(ci) }//End of parallel region #ifdef DEBUG_PRINTF ofs << "Done parsing C1..." << std::endl; #endif //Compare all pairs of vertices from the perspective of C2: #pragma omp parallel { int tid = omp_get_thread_num(); #pragma omp for for(GraphElem ci = 0; ci < nC2; ci++) { GraphElem adj1 = commPtr2[ci]; GraphElem adj2 = commPtr2[ci+1]; for(GraphElem i = adj1; i < adj2; i++) { for(GraphElem j = i+1; j < adj2; j++) { //Check if the two vertices belong to the same community in C2 if(C1[commIndex2[i]] == C1[commIndex2[j]]) { nAgree[tid]++; } else { tDiffSame[tid]++; } }//End of for(j) }//End of for(i) }//End of for(ci) }//End of parallel region #ifdef DEBUG_PRINTF ofs << "Done parsing C2..." << std::endl; #endif GraphElem SameSame = 0, SameDiff = 0, DiffSame = 0, Agree = 0; #pragma omp parallel for reduction(+:SameSame) reduction(+:SameDiff) \ reduction(+:DiffSame) reduction(+:Agree) for (int i=0; i < nT; i++) { SameSame += tSameSame[i]; SameDiff += tSameDiff[i]; DiffSame += tDiffSame[i]; Agree += nAgree[i]; } assert(SameSame == Agree); double precision = (double)SameSame / (double)(SameSame + DiffSame); double recall = (double)SameSame / (double)(SameSame + SameDiff); //F-score (F1 score) is the harmonic mean of precision and recall -- //multiplying the constant of 2 scales the score to 1 when both recall and precision are 1 double fScore = 2.0*((precision * recall) / (precision + recall)); //Compute Gini coefficient for each cluster: double Gini1 = compute_gini_coeff(clusterDist1, nC1); double Gini2 = compute_gini_coeff(clusterDist2, nC2); std::cout << "*******************************************" << std::endl; std::cout << "Communities comparison statistics:" << std::endl; std::cout << "*******************************************" << std::endl; std::cout << "|C1| (truth) : " << N1 << std::endl; std::cout << "#communities in C1 : " << nC1 << std::endl; std::cout << "|C2| (output) : " << N2 << std::endl; std::cout << "#communities in C2 : " << nC2 << std::endl; std::cout << "-------------------------------------------" << std::endl; std::cout << "Same-Same (True positive) : " << SameSame << std::endl; std::cout << "Same-Diff (False negative) : " << SameDiff << std::endl; std::cout << "Diff-Same (False positive) : " << DiffSame << std::endl; std::cout << "-------------------------------------------" << std::endl; std::cout << "Precision : " << precision << " (" << (precision*100) << ")" << std::endl; std::cout << "Recall : " << recall << " (" << (recall*100) << ")" << std::endl; std::cout << "F-score : " << fScore << std::endl; std::cout << "-------------------------------------------" << std::endl; std::cout << "Gini coefficient, C1 : " << Gini1 << std::endl; std::cout << "Gini coefficient, C2 : " << Gini2 << std::endl; std::cout << "*******************************************" << std::endl; //Cleanup: delete []commPtr1; delete []commIndex1; delete []commPtr2; delete []commIndex2; delete []clusterDist1; delete []clusterDist2; } //End of compare_communities(...) //WARNING: Assume that colorSize is populated with the frequency for each color //Will sort the array within the function double compute_gini_coeff(GraphElem *colorSize, int numColors) { //Step 1: Sort the color size vector -- use STL sort function #ifdef DEBUG_PRINTF double time1 = omp_get_wtime(); #endif std::sort(colorSize, colorSize+numColors); #ifdef DEBUG_PRINTF double time2 = omp_get_wtime(); ofs << "Time for sorting (in compute_gini_coeff): " << time2-time1 << std::endl; #endif //Step 2: Compute Gini coefficient double numFunc=0.0, denFunc=0.0; #pragma omp parallel for reduction(+:numFunc,denFunc) for (GraphElem i=0; i < numColors; i++) { numFunc = numFunc + ((i+1)*colorSize[i]); denFunc = denFunc + colorSize[i]; } #ifdef DEBUG_PRINTF ofs << "(Gini coeff) Numerator = " << numFunc << " Denominator = " << denFunc << std::endl; ofs << "(Gini coeff) Negative component = " << ((double)(numColors+1)/(double)numColors) << std::endl; #endif double giniCoeff = ((2*numFunc)/(numColors*denFunc)) - ((double)(numColors+1)/(double)numColors); return giniCoeff; //Return the Gini coefficient }//End of compute_gini_coeff(...)
33,763
https://github.com/verkri/designermarka/blob/master/plugins/sfCombinePlugin/lib/minifier/sfCombineMinifierYuiCss.class.php
Github Open Source
Open Source
MIT
null
designermarka
verkri
PHP
Code
74
228
<?php /** * sfCombineMinifierYuiCss * * @package sfCombinePlugin * @subpackage miniferYuiCss * @author Kevin Dew <kev@dewsolutions.co.uk> */ class sfCombineMinifierYuiCss extends sfCombineMinifierYuiAbstract implements sfCombineMinifierInterface { const TYPE = 'css'; /** * @see sfCombineMinifierInterface::minify * @param string $content * @param array $options * @return string */ static public function minify($content, array $options = array()) { $obj = new self($content, $options); return $obj->execute(); } /** * @see parent */ protected function _getType() { return self::TYPE; } }
26,336
https://github.com/grantweiss/down-to-party/blob/master/server/api/payments.js
Github Open Source
Open Source
MIT
null
down-to-party
grantweiss
JavaScript
Code
77
250
const router = require('express').Router() require('dotenv').config() const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY) module.exports = router router.post('/', async (req, res) => { let {amount, id, stripeId} = req.body try { await stripe.paymentIntents.create({ amount: amount, currency: 'USD', description: 'Huddle, Inc', payment_method: id, confirm: true, application_fee_amount: amount / 100 * 30, transfer_data: { destination: stripeId } }) res.json({ message: 'Payment Successful', success: true }) } catch (error) { console.log('stripe-routes.js 17 | error', error) res.json({ error, message: 'Payment Failed', success: false }) } })
30,517
https://github.com/palatable/lambda/blob/master/src/test/java/com/jnape/palatable/lambda/internal/iteration/UnfoldingIteratorTest.java
Github Open Source
Open Source
MIT
2,023
lambda
palatable
Java
Code
104
473
package com.jnape.palatable.lambda.internal.iteration; import com.jnape.palatable.lambda.adt.Maybe; import com.jnape.palatable.lambda.adt.hlist.Tuple2; import com.jnape.palatable.lambda.functions.Fn1; import org.junit.Test; import java.util.concurrent.atomic.AtomicInteger; import static com.jnape.palatable.lambda.adt.Maybe.just; import static com.jnape.palatable.lambda.adt.Maybe.nothing; import static com.jnape.palatable.lambda.adt.hlist.HList.tuple; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class UnfoldingIteratorTest { private static final Fn1<Integer, Maybe<Tuple2<String, Integer>>> STRINGIFY = x -> just(tuple(x.toString(), x + 1)); @Test public void hasNextIfFunctionProducesPresentValue() { assertThat(new UnfoldingIterator<>(STRINGIFY, 0).hasNext(), is(true)); } @Test public void doesNotHaveNextIfFunctionProducesEmptyValue() { assertThat(new UnfoldingIterator<String, Integer>(x -> nothing(), 0).hasNext(), is(false)); } @Test public void defersNextCallForAsLongAsPossible() { AtomicInteger invocations = new AtomicInteger(0); UnfoldingIterator<String, Integer> iterator = new UnfoldingIterator<>(x -> { invocations.incrementAndGet(); return just(tuple(x.toString(), x + 1)); }, 1); assertEquals(0, invocations.get()); iterator.next(); assertEquals(1, invocations.get()); } }
17,083
https://github.com/jugstalt/identityserver-legacy/blob/master/is4/IdentityServer/Areas/Admin/Pages/Users/EditUser/Index.cshtml
Github Open Source
Open Source
Apache-2.0
2,020
identityserver-legacy
jugstalt
C#
Code
80
359
@page @model IdentityServer.Areas.Admin.Pages.Users.EditUser.IndexModel @{ ViewData["Title"] = Model.Category; ViewData["Category"] = Model.Category; ViewData["ActivePage"] = EditUserNavPages.Index; } <h4>@ViewData["Title"]</h4> <partial name="_StatusMessage" model="Model.StatusMessage" /> <div class="row"> <div class="col-md-6"> @if (Model.EditorInfos?.EditorInfos != null && Model.EditorInfos.EditorInfos.Count() > 0) { <form id="profile-form" method="post"> <div asp-validation-summary="All" class="text-danger"></div> <input type="hidden" name="__current_admin_account_user_id" value="@Model.CurrentApplicationUser.Id" /> <input type="hidden" name="_category" value="@Model.Category" /> <partial name="_RenderEditors" model="Model" /> <button id="update-profile-button" type="submit" class="btn btn-default">Save</button> </form> } else { <p> No Editor definitions to admin accout settings... </p> } </div> </div> @section Scripts { <partial name="_ValidationScriptsPartial" /> }
17,849
https://github.com/calmilamsy/bin-bukkit/blob/master/src/main/java/org/bukkit/craftbukkit/inventory/CraftItemStack.java
Github Open Source
Open Source
CC0-1.0
2,020
bin-bukkit
calmilamsy
Java
Code
379
1,008
package org.bukkit.craftbukkit.inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.Material; public class CraftItemStack extends ItemStack { protected net.minecraft.server.ItemStack item; public CraftItemStack(net.minecraft.server.ItemStack item) { super( item != null ? item.id: 0, item != null ? item.count : 0, (short)(item != null ? item.damage : 0) ); this.item = item; } /* 'Overwritten' constructors from ItemStack, yay for Java sucking */ public CraftItemStack(final int type) { this(type, 0); } public CraftItemStack(final Material type) { this(type, 0); } public CraftItemStack(final int type, final int amount) { this(type, amount, (byte) 0); } public CraftItemStack(final Material type, final int amount) { this(type.getId(), amount); } public CraftItemStack(final int type, final int amount, final short damage) { this(type, amount, damage, null); } public CraftItemStack(final Material type, final int amount, final short damage) { this(type.getId(), amount, damage); } public CraftItemStack(final Material type, final int amount, final short damage, final Byte data) { this(type.getId(), amount, damage, data); } public CraftItemStack(int type, int amount, short damage, Byte data) { this(new net.minecraft.server.ItemStack(type, amount, data != null ? data : damage)); } /* * Unsure if we have to sync before each of these calls the values in 'item' * are all public. */ @Override public Material getType() { super.setTypeId(item != null ? item.id : 0); // sync, needed? return super.getType(); } @Override public int getTypeId() { super.setTypeId(item != null ? item.id : 0); // sync, needed? return item != null ? item.id : 0; } @Override public void setTypeId(int type) { if (type == 0) { super.setTypeId(0); super.setAmount(0); item = null; } else { if (item == null) { item = new net.minecraft.server.ItemStack(type, 1, 0); super.setAmount(1); } else { item.id = type; super.setTypeId(item.id); } } } @Override public int getAmount() { super.setAmount(item != null ? item.count : 0); // sync, needed? return (item != null ? item.count : 0); } @Override public void setAmount(int amount) { if (amount == 0) { super.setTypeId(0); super.setAmount(0); item = null; } else { super.setAmount(amount); item.count = amount; } } @Override public void setDurability(final short durability) { // Ignore damage if item is null if (item != null) { super.setDurability(durability); item.damage = durability; } } @Override public short getDurability() { if (item != null) { super.setDurability((short) item.damage); // sync, needed? return (short) item.damage; } else { return -1; } } @Override public int getMaxStackSize() { return item.getItem().getMaxStackSize(); } }
9,595
https://github.com/Rahsai94/awsproject/blob/master/node_modules/bootstrap-4-react/src/components/form/index.js
Github Open Source
Open Source
Apache-2.0
2,021
awsproject
Rahsai94
JavaScript
Code
147
413
import Form from './Form'; import FormGroup from './FormGroup'; import FormInput from './FormInput'; import FormSelect from './FormSelect'; import FormTextarea from './FormTextarea'; import FormFile from './FormFile'; import FormRange from './FormRange'; import FormPlainText from './FormPlainText'; import FormText from './FormText'; import FormCheck from './FormCheck'; import FormCheckInput from './FormCheckInput'; import FormCheckLabel from './FormCheckLabel'; import FormCheckbox from './FormCheckbox'; import FormRadio from './FormRadio'; import FormFeedback from './FormFeedback'; import FormLabelCol from './FormLabelCol'; import FormCustomCheckbox from './FormCustomCheckbox'; import FormCustomRadio from './FormCustomRadio'; import FormCustomSelect from './FormCustomSelect'; import FormCustomRange from './FormCustomRange'; import FormCustomFile from './FormCustomFile'; Form.Group = FormGroup; Form.Input = FormInput; Form.Select = FormSelect; Form.Textarea = FormTextarea; Form.File = FormFile; Form.Range = FormRange; Form.PlainText = FormPlainText; Form.Text = FormText; Form.Check = FormCheck; Form.CheckInput = FormCheckInput; Form.CheckLabel = FormCheckLabel; Form.Checkbox = FormCheckbox; Form.Radio = FormRadio; Form.Feedback = FormFeedback; Form.LabelCol = FormLabelCol; Form.CustomCheckbox = FormCustomCheckbox; Form.CustomRadio = FormCustomRadio; Form.CustomSelect = FormCustomSelect; Form.CustomRange = FormCustomRange; Form.CustomFile = FormCustomFile; export default Form;
6,683
https://github.com/JohnTranterInternetrix/zipmoney-php/blob/master/src/zipMoney/Resource.php
Github Open Source
Open Source
MIT
null
zipmoney-php
JohnTranterInternetrix
PHP
Code
251
728
<?php /** * @category zipMoney * @package zipMoney PHP Library * @author Sagar Bhandari <sagar.bhandari@zipmoney.com.au> * @copyright 2016 zipMoney Payments. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * @link http://www.zipmoney.com.au/ */ namespace zipMoney; use \zipMoney\Http as RestClient; class Resource { const RESOURCE_SETTINGS = 'settings'; const RESOURCE_CONFIGURE = 'configure'; const RESOURCE_QUOTE = 'quote'; const RESOURCE_ORDER_CANCEL = 'cancel'; const RESOURCE_ORDER_REFUND = 'refund'; const RESOURCE_CHECKOUT = 'checkout'; const RESOURCE_QUERY = 'query'; const RESOURCE_CAPTURE = 'capture'; const RESOURCE_HEART_BEAT = 'Heartbeat'; /** * Creates and prepares api resource with the given parameters * * @param string $resource * @param string $method * @param array $options * @param string $query_string * @return mixed false | RestClient */ public static function get($resource, $method = 'POST', $options = null, $query_string = null) { if(self::resource_valid($resource)){ $url = self::getUrl($resource, ( strtoupper($method) == "GET"? $query_string:null ) ); return new RestClient($url, "json", $options ); } return false; } /** * Checks if the given resource is valid * * @param string $resource * @return bool */ public static function resource_valid($resource) { $refl = new \ReflectionClass('zipMoney\\Resource'); $resources = $refl->getConstants(); if(in_array($resource, array_values($resources))) return true; return false; } /** * Builds the resource url with the given parameters * * @param string $resource * @param string $env * @param string $query_string * @return string */ public static function getUrl($resource, $env, $query_string = null) { $url = null; if(Configuration::isSandbox($env)) { $base_url = Configuration::ENV_TEST_BASE_URL; } else { $base_url = Configuration::ENV_LIVE_BASE_URL; } if ($base_url && $resource) { $url = $base_url . ltrim($resource, '/'); } return $url; } }
5,410
https://github.com/Sendiradid/island.is/blob/master/libs/island-ui/core/src/lib/IconRC/icons/CellularOutline.tsx
Github Open Source
Open Source
MIT
2,022
island.is
Sendiradid
TypeScript
Code
98
446
import * as React from 'react' import { SvgProps as SVGRProps } from '../Icon' const SvgCellularOutline = ({ title, titleId, ...props }: React.SVGProps<SVGSVGElement> & SVGRProps) => { return ( <svg className="cellular-outline_svg__ionicon" viewBox="0 0 512 512" aria-labelledby={titleId} {...props} > {title ? <title id={titleId}>{title}</title> : null} <rect x={416} y={96} width={64} height={320} rx={8} ry={8} fill="none" stroke="currentColor" strokeLinejoin="round" strokeWidth={32} /> <rect x={288} y={176} width={64} height={240} rx={8} ry={8} fill="none" stroke="currentColor" strokeLinejoin="round" strokeWidth={32} /> <rect x={160} y={240} width={64} height={176} rx={8} ry={8} fill="none" stroke="currentColor" strokeLinejoin="round" strokeWidth={32} /> <rect x={32} y={304} width={64} height={112} rx={8} ry={8} fill="none" stroke="currentColor" strokeLinejoin="round" strokeWidth={32} /> </svg> ) } export default SvgCellularOutline
8,905
https://github.com/afranck64/keras-easy/blob/master/keras_easy/models/tools/losses.py
Github Open Source
Open Source
MIT
2,021
keras-easy
afranck64
Python
Code
43
174
import keras.backend as K def mse(y_true, y_pred): return K.mean(K.square(y_pred - y_true), axis=-1) def rmse(y_true, y_pred): return K.sqrt(K.mean(K.square(y_pred - y_true), axis=-1)) #TODO: make use of <config> and config.data.nb_classes def get_loss(loss): if loss=="mse" or loss=="mean_squared_error": return mse if rmse=="rmse" or loss=="root_mean_squared_error": return rmse return loss
8,847
https://github.com/AthenaModel/athena/blob/master/docs/DevelopmentChecklists.mm
Github Open Source
Open Source
BSD-2-Clause
2,021
athena
AthenaModel
Objective-C++
Code
895
4,149
<map version="0.9.0"> <!--To view this file, download free mind mapping software Freeplane from http://freeplane.sourceforge.net --> <node ID="ID_1378351314" CREATED="1343246727593" MODIFIED="1343247768120"> <richcontent TYPE="NODE"> <html> <head> </head> <body> <p> Development </p> <p> Checklists </p> </body> </html></richcontent> <hook NAME="MapStyle" max_node_width="600"/> <node TEXT="Adding an entity attribute" FOLDED="true" POSITION="right" ID="ID_30726038" CREATED="1343246737341" MODIFIED="1343246746379"> <node TEXT="Data type" ID="ID_88865265" CREATED="1343246818415" MODIFIED="1343246820149"> <node TEXT="Add new data type (e.g., enum(n) type), if needed" ID="ID_1628477994" CREATED="1343246777383" MODIFIED="1343246792556"/> </node> <node TEXT="Schema" ID="ID_201879660" CREATED="1343246825401" MODIFIED="1343246829621"> <node TEXT="Add new column to relevant scenariodb(n) table" ID="ID_1687720079" CREATED="1343246793663" MODIFIED="1343246837902"/> </node> <node TEXT="GUI Views" ID="ID_52805764" CREATED="1343246846538" MODIFIED="1343246849015"> <node TEXT="Add new column to relevant GUI views" ID="ID_498201800" CREATED="1343246849617" MODIFIED="1343246858271"/> </node> <node TEXT="Mutators" ID="ID_246984085" CREATED="1343246870083" MODIFIED="1343246873776"> <node TEXT="Update entity mutators for new attribute" ID="ID_422764098" CREATED="1343246874131" MODIFIED="1343246885440"/> </node> <node TEXT="Orders" ID="ID_1502294059" CREATED="1343246886386" MODIFIED="1343246887503"> <node TEXT="Update entity orders for new attribute" ID="ID_67198273" CREATED="1343246887962" MODIFIED="1343246893535"/> </node> <node TEXT="Tests" ID="ID_1458031814" CREATED="1343252490174" MODIFIED="1343252491706"> <node TEXT="Update &quot;ted&quot; entity definitions" ID="ID_677048185" CREATED="1343252501374" MODIFIED="1343252517487"/> <node TEXT="010-* tests" ID="ID_1114615723" CREATED="1343246904299" MODIFIED="1343246915127"> <node TEXT="Update mutator tests" ID="ID_1304694577" CREATED="1343246915450" MODIFIED="1343246931063"/> </node> <node TEXT="020-* tests" ID="ID_1828401706" CREATED="1343246920618" MODIFIED="1343246926190"> <node TEXT="Update order tests" ID="ID_1940496400" CREATED="1343246932346" MODIFIED="1343246935590"/> </node> <node TEXT="Verify that all Athena tests pass" ID="ID_1912844312" CREATED="1343250822966" MODIFIED="1343250828531"/> </node> <node TEXT="Browser" ID="ID_1942579226" CREATED="1343246967387" MODIFIED="1343246972680"> <node TEXT="Update the browser/browsers for this entity type" ID="ID_1415752999" CREATED="1343246972956" MODIFIED="1343246980216"/> </node> <node TEXT="Appserver" ID="ID_1333353120" CREATED="1343246982338" MODIFIED="1343246994330"> <node TEXT="Update the relevant appserver pages" ID="ID_1129041384" CREATED="1343246984788" MODIFIED="1343246990680"/> </node> <node TEXT="Help pages" ID="ID_502437366" CREATED="1343246996492" MODIFIED="1343246998881"> <node TEXT="Update the relevant help pages" ID="ID_1531533085" CREATED="1343246999324" MODIFIED="1343247005218"/> <node TEXT="tab.help" ID="ID_1941006968" CREATED="1343252145358" MODIFIED="1343252175879"> <node TEXT="The browser tab(s)" ID="ID_1498633286" CREATED="1343252176697" MODIFIED="1343252180413"/> </node> <node TEXT="object_*.help" ID="ID_1854545082" CREATED="1343252158183" MODIFIED="1343252186364"> <node TEXT="The entity&apos;s object page, if any." ID="ID_1869418099" CREATED="1343252186656" MODIFIED="1343252194508"/> </node> <node TEXT="order_*.help" ID="ID_1295362261" CREATED="1343252195415" MODIFIED="1343252198413"> <node TEXT="The entity&apos;s order pages, if any." ID="ID_408374197" CREATED="1343252199056" MODIFIED="1343252205566"/> </node> </node> </node> <node TEXT="Defining a new tactic type" FOLDED="true" POSITION="right" ID="ID_1012865532" CREATED="1343318922846" MODIFIED="1343318934404"> <node TEXT="Determine the parameters; reuse the existing tactics table columns when appropriate" ID="ID_1045410495" CREATED="1343318953016" MODIFIED="1343319044216"/> <node TEXT="Add new parameters" ID="ID_1863562007" CREATED="1343318957063" MODIFIED="1343318997822"> <node TEXT="Database schema" ID="ID_388596873" CREATED="1343319020474" MODIFIED="1343319026127"> <node TEXT="Add columns to tactics table" ID="ID_231236546" CREATED="1343319026618" MODIFIED="1343319036447"/> </node> <node TEXT="shared/tactics.tcl" ID="ID_1898704481" CREATED="1343318998185" MODIFIED="1343319098362"> <node TEXT="Add new parms to optparms" ID="ID_275005185" CREATED="1343319060452" MODIFIED="1343319066513"/> <node TEXT="Update mutators" ID="ID_856943737" CREATED="1343319067395" MODIFIED="1343319071897"/> </node> <node TEXT="010-tactics.tcl" ID="ID_1169815907" CREATED="1343319779135" MODIFIED="1343319786588"> <node TEXT="Update" ID="ID_1275775442" CREATED="1343319786967" MODIFIED="1343319788604"/> </node> </node> <node TEXT="Add shared/tactic_dummy.tcl" ID="ID_1669462533" CREATED="1343319079460" MODIFIED="1343319104330"> <node TEXT="Parallel to other tactics" ID="ID_770902164" CREATED="1343319104734" MODIFIED="1343319110363"/> <node TEXT="Standard tactic subcommands" ID="ID_1341891367" CREATED="1343319870172" MODIFIED="1343319873873"/> <node TEXT="CREATE and UPDATE orders" ID="ID_579251997" CREATED="1343319874284" MODIFIED="1343319881425"/> </node> <node TEXT="Add 010-tactic_dummy.tcl" ID="ID_1218999489" CREATED="1343319800481" MODIFIED="1343319817677"> <node TEXT="Test tactic subcommands" ID="ID_988112363" CREATED="1343319818120" MODIFIED="1343319825214"/> </node> <node TEXT="Add 010-TACTIC-DUMMY.tcl" ID="ID_1826871238" CREATED="1343319826560" MODIFIED="1343319840528"> <node TEXT="Test tactic orders" ID="ID_1005667835" CREATED="1343319841875" MODIFIED="1343319853120"/> </node> <node TEXT="Update help" ID="ID_1238282535" CREATED="1343844172211" MODIFIED="1343844176751"> <node TEXT="Add tactic object to object_tactic.help" ID="ID_739272604" CREATED="1343844177506" MODIFIED="1343844188829"/> <node TEXT="Add order pages to order_tactic.help" ID="ID_1026057679" CREATED="1343844189218" MODIFIED="1343844195110"/> </node> </node> <node TEXT="Defining a gofer::NUMBER rule" POSITION="right" ID="ID_691294663" CREATED="1383083935142" MODIFIED="1383083944430"> <node TEXT="Determine the rule&apos;s name and parameters" ID="ID_1295330900" CREATED="1383083963521" MODIFIED="1383083974534"/> <node TEXT="Determine how to retrieve the desired number" ID="ID_292230656" CREATED="1383083975265" MODIFIED="1383083985574"/> <node TEXT="In gofer_number.tcl" ID="ID_1658391915" CREATED="1383083945976" MODIFIED="1383084177319"> <node TEXT="Add a case for the rule and its parameters to the dynaform at the top of the file." ID="ID_1145251164" CREATED="1383083956216" MODIFIED="1383084004319"/> <node TEXT="If in doubt, put it at the end." ID="ID_601355061" CREATED="1383084043244" MODIFIED="1383084049502"/> <node TEXT="Add a [gofer rule] object for the new rule, parallel to the existing rules." ID="ID_1029822361" CREATED="1383084005434" MODIFIED="1383084038617"/> <node TEXT="The rule objects should be in the same order as the dynaform cases." ID="ID_491007698" CREATED="1383084050924" MODIFIED="1383084077338"/> <node TEXT="Use the helpers from gofer.tcl and gofer_helpers.tcl as appropriate." ID="ID_403896074" CREATED="1383084101742" MODIFIED="1383084115236"/> <node TEXT="Add new helpers if appropriate" ID="ID_1705721843" CREATED="1383084133000" MODIFIED="1383084136636"/> <node TEXT="The narrative should be the matching execution function." ID="ID_1807602901" CREATED="1383858247051" MODIFIED="1383858266157"/> <node TEXT="The rule should always returns a numeric result when called with valid parameters." ID="ID_248264871" CREATED="1383858365566" MODIFIED="1383858384779"/> <node TEXT="Often, this means returning 0.0 or some similar value when the [sim state] is PREP." ID="ID_1421748599" CREATED="1383858386271" MODIFIED="1383858410827"/> </node> <node TEXT="In executive.tcl" ID="ID_1187749632" CREATED="1383858272659" MODIFIED="1383858284985"> <node TEXT="Add the matching executive function, in parallel to the existing ones." ID="ID_459111863" CREATED="1383858285852" MODIFIED="1383858298840"/> <node TEXT="The function should rely on the gofer for all parameter validation." ID="ID_1759732480" CREATED="1383858299228" MODIFIED="1383858313042"/> </node> <node TEXT="Test the gofer rule interactively" ID="ID_21552464" CREATED="1383084261654" MODIFIED="1383084268651"> <node TEXT="Use the COMPARE condition in a scenario." ID="ID_1930229849" CREATED="1383084268958" MODIFIED="1383084279371"/> <node TEXT="Test the dynaform layout and text." ID="ID_1868858426" CREATED="1383084279887" MODIFIED="1383084289660"/> <node TEXT="Spot check the behavior (i.e., no bgerrors)" ID="ID_1131690357" CREATED="1383084291047" MODIFIED="1383084328701"/> </node> <node TEXT="Test the executive function interactively using the [expr] command at the Athena CLI." ID="ID_1008762090" CREATED="1383858319077" MODIFIED="1383858336897"/> <node TEXT="Code Review, if needed" ID="ID_1925898206" CREATED="1383084465246" MODIFIED="1383084470556"/> <node TEXT="In 010-gofer_number.test" ID="ID_1062198334" CREATED="1383084116927" MODIFIED="1383857955813"> <node TEXT="Add tests for the new rule, parallel to the existing rules." ID="ID_18635815" CREATED="1383084125927" MODIFIED="1383084148166"/> <node TEXT="The rules should be in the same order as in gofer_number.tcl." ID="ID_658426211" CREATED="1383084148769" MODIFIED="1383084159230"/> </node> <node TEXT="In 010-gofer_helpers.test" ID="ID_1043928615" CREATED="1383084184162" MODIFIED="1383857963540"> <node TEXT="Add tests for any new or extended helpers." ID="ID_1980163295" CREATED="1383084191075" MODIFIED="1383084214252"/> </node> <node TEXT="In 030-function.test" ID="ID_1493838361" CREATED="1383858343485" MODIFIED="1383858352002"> <node TEXT="Add tests for the executive function." ID="ID_144214576" CREATED="1383858352382" MODIFIED="1383858358451"/> </node> <node TEXT="Run 010-gofer.test" ID="ID_1423632373" CREATED="1383084215946" MODIFIED="1383084233081"> <node TEXT="This verifies that the dynaform and rules are consistent." ID="ID_1743239617" CREATED="1383084234196" MODIFIED="1383084246905"/> </node> <node TEXT="In gofer.help" ID="ID_587268283" CREATED="1383084337609" MODIFIED="1383084357190"> <node TEXT="Add a page for the rule, parallel to the existing rules." ID="ID_479546257" CREATED="1383084357754" MODIFIED="1383084377023"/> <node TEXT="The rules should be in the same order as in gofer_number.tcl." ID="ID_1240544135" CREATED="1383084377298" MODIFIED="1383084387952"/> <node TEXT="Build the help and review it in the Detail Browser" ID="ID_857693444" CREATED="1383084388691" MODIFIED="1383084407825"/> </node> <node TEXT="Run &quot;athena_test all&quot;" ID="ID_752467800" CREATED="1383084410748" MODIFIED="1383084423553"> <node TEXT="Fix any problems." ID="ID_661967420" CREATED="1383084428437" MODIFIED="1383084431521"/> <node TEXT="Update tests as needed" ID="ID_83381592" CREATED="1383084431965" MODIFIED="1383084436185"/> </node> </node> </node> </map>
3,975
https://github.com/anthonycanino1/entbench-pi/blob/master/batik/classes/org/apache/batik/ext/awt/image/codec/util/SingleTileRenderedImage.java
Github Open Source
Open Source
Apache-2.0
2,016
entbench-pi
anthonycanino1
Java
Code
482
8,969
package org.apache.batik.ext.awt.image.codec.util; public class SingleTileRenderedImage extends org.apache.batik.ext.awt.image.codec.util.SimpleRenderedImage { java.awt.image.Raster ras; public SingleTileRenderedImage(java.awt.image.Raster ras, java.awt.image.ColorModel colorModel) { super( ); this. ras = ras; this. tileGridXOffset = (this. minX = ras. getMinX( )); this. tileGridYOffset = (this. minY = ras. getMinY( )); this. tileWidth = (this. width = ras. getWidth( )); this. tileHeight = (this. height = ras. getHeight( )); this. sampleModel = ras. getSampleModel( ); this. colorModel = colorModel; } public java.awt.image.Raster getTile(int tileX, int tileY) { if (tileX != 0 || tileY != 0) { throw new java.lang.IllegalArgumentException( org.apache.batik.ext.awt.image.codec.util.PropertyUtil. getString( "SingleTileRenderedImage0")); } return ras; } public static final java.lang.String jlc$CompilerVersion$jl7 = "2.7.0"; public static final long jlc$SourceLastModified$jl7 = 1471109864000L; public static final java.lang.String jlc$ClassType$jl7 = ("H4sIAAAAAAAAAMVYfWwUxxWfO39/4Q++zJfBxhAZyG1IAxUyIQHHDqZnY9kO" + "UkzDMbc351u8t7vsztpnpzSEqoVULaUUCK0S/ikRCSIhqhq1VZuIKmqTKGml" + "JLRpWoVUbaXSpqhBVdOqtE3fzOzeftydA3/V0s6tZ957896bN7/33l64hios" + "E7URjcbotEGsWK9Gh7BpkVSPii1rFOYS8uNl+G97rg5uiqLKMTQng60BGVuk" + "TyFqyhpDyxTNoliTiTVISIpxDJnEIuYkpoqujaH5itWfNVRFVuiAniKMYBc2" + "46gZU2oqSZuSfkcARcvioInENZG2hpe746he1o1pj7zVR97jW2GUWW8vi6Km" + "+D48iSWbKqoUVyzanTPRWkNXp8dVncZIjsb2qRscF+yIbyhwQcfzjR/dOJZp" + "4i6YizVNp9w8a5hYujpJUnHU6M32qiRr7UefR2VxVOcjpqgz7m4qwaYSbOpa" + "61GB9g1Es7M9OjeHupIqDZkpRFF7UIiBTZx1xAxxnUFCNXVs58xg7Yq8tcLK" + "AhNPrpVOPL6n6TtlqHEMNSraCFNHBiUobDIGDiXZJDGtrakUSY2hZg0Oe4SY" + "ClaVGeekWyxlXMPUhuN33cImbYOYfE/PV3COYJtpy1Q38+aleUA5/1WkVTwO" + "ti7wbBUW9rF5MLBWAcXMNIa4c1jKJxQtRdHyMEfexs7PAAGwVmUJzej5rco1" + "DBOoRYSIirVxaQRCTxsH0godAtCkaHFJoczXBpYn8DhJsIgM0Q2JJaCq4Y5g" + "LBTND5NxSXBKi0On5Dufa4Objz6sbdeiKAI6p4isMv3rgKktxDRM0sQkcA8E" + "Y/2a+Cm84MUjUYSAeH6IWNB873PX713XdulVQbOkCM3O5D4i04R8NjnnzaU9" + "XZvKmBrVhm4p7PADlvNbNuSsdOcMQJgFeYlsMeYuXhr+6YMHz5MPoqi2H1XK" + "umpnIY6aZT1rKCox7ycaMTElqX5UQ7RUD1/vR1XwHlc0ImZ3ptMWof2oXOVT" + "lTr/H1yUBhHMRbXwrmhp3X03MM3w95yBEKqCB9XDsxyJP/5LEZUyepZIWMaa" + "ounSkKkz+y0JECcJvs1ISYj6CcnSbRNCUNLNcQlDHGSIs8BuJp6ikpKF45dk" + "QCNZOGYEIkslo6DcMGgPB5XqZyQxFn3G/2nfHPPH3KlIBI5qaRgoVLhj23UV" + "WBLyCXtb7/XnEq+LIGQXx/EkRVtBlZhQJcZV4bAKqsS4KjGuijj+EqqgSIRr" + "MI+pJCjhmCcAMACx67tGHtqx90hHGUSoMVUOZ8RIOwKZq8dDFTcVJOSLLQ0z" + "7VfWvxxF5XHUgmVqY5Uloq3mOECcPOGgQH0ScpqXWlb4UgvLiaYukxQgW6kU" + "40ip1ieJyeYpmueT4CY+dsWl0mmnqP7o0umpR3c9ckcURYPZhG1ZAUDI2IdY" + "DshjfWcYRYrJbTx89aOLpw7oHp4E0pObVQs4mQ0d4RgJuychr1mBX0i8eKCT" + "u70G8J5iuJ8ApW3hPQJw1e1CP7OlGgxO62YWq2zJ9XEtzZj6lDfDg7eZv8+D" + "sKhj97cDnrXOhea/bHWBwcaFIthZnIWs4Knl7hHjyV/9/E+f4u52s1Cjr3wY" + "IbTbh3xMWAvHuGYvbEdNQoDuvdND3zh57fBuHrNAsbLYhp1s7AHEgyMEN3/x" + "1f3vvn/l7OWoF+cUUr+dhAoqlzeSzaPaWYyE3VZ7+gByqoAiLGo6H9AgPpW0" + "gpMqYRfr342r1r/wl6NNIg5UmHHDaN0nC/DmF21DB1/f8482LiYis8zt+cwj" + "E+lgrid5q2niaaZH7tG3ln3zFfwkJBYAc0uZIRyfo9wHUW55K2ROzumhyjC2" + "IEG7q4tCq7CvbrLLp/JD38Dp7uDjXcxhXDbia91sWGX5L0/wfvoqtIR87PKH" + "Dbs+fOk6tzZY4vljZQAb3SI82bA6B+IXhsFtO7YyQHfXpcHPNqmXboDEMZAo" + "A7hbO00Ax1wgshzqiqpf//jlBXvfLEPRPlSr6jjVh/klRTVwO4iVAbzOGffc" + "K4JjqhqGJm4qKjC+YIId0PLiR9+bNSg/rJnvL/zu5nNnrvAoNYSMJXlUXhpA" + "Zd4oeMBw/u1P/+Lc109NiVKjqzQahvha/7VTTR763T8LXM5xsEgZFOIfky48" + "sbhnywec3wMkxt2ZK0x7AOoe753ns3+PdlT+JIqqxlCT7BTmu7Bqs2s+BsWo" + "5VbrULwH1oOFpaiiuvOAuzQMhr5tw1DopVt4Z9TsvSGEfvwIG+Fpd4ChPYx+" + "EcRfBjjLbXxcw4bb/fGQF1U+iyiKykzMyTcKSGXjZjYMCin3FAtAsXQbG9bm" + "9+J/leEqzI9nXoQhdo2WlSqUeZF/9tCJM6mdT60XMdYSLD57obd69pf/eSN2" + "+revFaljaqhu3K6SSaKGonpZIKoHeA/hhch7c47//ged49tupcxgc22fUEiw" + "/5eDEWtKX5SwKq8c+vPi0S2ZvbdQMSwPuTMs8pmBC6/dv1o+HuUNk4jdgkYr" + "yNQdjNhak0BnqI0G4nZlPgBa2MEugmeTEwCbimftIrGTz4WlWEOo72aUQPXI" + "jmrETlpQ6SlZSOyTTvN059Be+Ujn0B9EJC0qwiDo5j8tfXXXO/ve4D6vZoec" + "t9R3wBAMvpqlSZjwMfxF4Pkve5jqbEI0IS09Tie0It8KMbSdFTZDBkgHWt6f" + "eOLqs8KAMEaGiMmRE1/+OHb0hLgWop9eWdDS+nlETy3MYcM+pl37bLtwjr4/" + "Xjzww6cPHI462fdBwBLF+dTBziiSv3Xzgi4Xet73WOOPjrWU9cFl60fVtqbs" + "t0l/KhhwVZad9J2B13574edozPxNUWQNuJZNKHxMz1Ir8AFTVDVO6KjTZW70" + "0C85C/rdRPplE71GjqKFJfoklqBbCz7niE8Q8nNnGqsXnnngHY5D+c8E9RCU" + "aVtV/SnE915pmCQt7K4XCUW44iBFXTfd1lFUzn64QY8I/i9AS3Ez/BRV8F8/" + "75egVZidF7j4r5/rMYpaS3FBjMHop/4KtGnFqIESRj/l1yhqClPC/vzXT3ec" + "olqPDip38eInOQnSgYS9njLcyvXuW+mes0YoInKRYH7Mh+L8TwpFX0pdGcAU" + "/lXRvXi2+K4IzfSZHYMPX9/4lOiOZBXPzDApdXDdRKOWzyjtJaW5siq3d92Y" + "83zNKhcDmoXCHs4v8V25XkADgwX+4lDrYHXmO4h3z25+6WdHKt8C9NqNInA/" + "5+4uLL1yhg2pfHe8EFYg+/KeprvrW9Nb1qX/+hte3BaWtGH6hHz53ENvH289" + "C71PXT/EJBxMjteE901rw0SeNMdQg2L15kBFkKJgNYBZc9gdxex7I/eL486G" + "/CzrrSnqKEThwi8S0AhMEXObbmspB/XqvJnA5043KduGEWLwZnyZigqgFEmp" + "LBEfMAw3SdV82+CIZYexm09y7mf4KxvO/w+gW8xxcRgAAA=="); public static final java.lang.String jlc$CompilerVersion$jl5 = "2.7.0"; public static final long jlc$SourceLastModified$jl5 = 1471109864000L; public static final java.lang.String jlc$ClassType$jl5 = ("H4sIAAAAAAAAAMVae8zjWHX3fPMedndmB9hdtuxjdgfa3dDPSezEiZalxImT" + "OInjJI4d220Z/H7E8duJE7q8+oBCS1dloSDBtn+A2qLloaqolSqqraoWEKgS" + "FepLKqCqUmkpEvtHadVtS6+d7z0zC6v+0U/ytXPvOeeec885v/v6nvsudDYK" + "oYLvOWvD8eJdLY13baeyG699LdrtDSojKYw0telIUTQFdTeURz53+fsvPm1e" + "2YHOidArJdf1Yim2PDeaaJHnLDV1AF0+rCUcbRHF0JWBLS0lOIktBx5YUfzE" + "AHrFEdYYuj7YVwEGKsBABThXAW4cUgGmOzU3WTQzDsmNowB6O3RqAJ3zlUy9" + "GLp2XIgvhdJiT8wotwBIuJD95oBROXMaQg8f2L61+SaDP1SAn/mNt1z5vdPQ" + "ZRG6bLlMpo4ClIhBJyJ0x0JbyFoYNVRVU0XoblfTVEYLLcmxNrneInQ1sgxX" + "ipNQOxikrDLxtTDv83Dk7lAy28JEib3wwDzd0hx1/9dZ3ZEMYOs9h7ZuLWxn" + "9cDASxZQLNQlRdtnOTO3XDWGHjrJcWDj9T4gAKznF1psegddnXElUAFd3frO" + "kVwDZuLQcg1AetZLQC8xdP9thWZj7UvKXDK0GzF030m60bYJUF3MByJjiaFX" + "nyTLJQEv3X/CS0f8893hGz/wNrfr7uQ6q5riZPpfAEwPnmCaaLoWaq6ibRnv" + "eHzwYemeL7x3B4IA8atPEG9p/uDnXnjzGx58/ktbmh+7BQ0t25oS31A+Id/1" + "tdc2H6ufztS44HuRlTn/mOV5+I/2Wp5IfZB59xxIzBp39xufn/y58M5Pad/Z" + "gS6R0DnFc5IFiKO7FW/hW44WdjRXC6VYU0noouaqzbydhM6D74HlattaWtcj" + "LSahM05edc7Lf4Mh0oGIbIjOg2/L1b39b1+Kzfw79SEIOg8e6A7wPARt//J3" + "DMWw6S00WFIk13I9eBR6mf0RrLmxDMbWhGUQ9XM48pIQhCDshQYsgTgwtb2G" + "LDOlVQxbC+B+WPGAw7YDw4DIcrQpUG4CtAeOUsmMZDeLPv//qd80G48rq1On" + "gKteexIoHJBjXc8BLDeUZxKceOEzN76yc5A4eyMZQw2gyu5Wld1clRxkgSq7" + "uSq7uSpb999GFejUqVyDV2UqbSmBm+cAMACU3vEY87O9t773kdMgQv3VGeCj" + "jBS+PaI3DyGGzIFUAXEOPf+R1bu4dxR3oJ3j0JyZAaouZeyjDFAPgPP6yZS8" + "ldzL7/n29z/74ae8w+Q8hvV7mHEzZ5bzj5wc8NBTNBWg6KH4xx+WPn/jC09d" + "34HOACAB4BlLINgBLj14so9juf/EPo5mtpwFButeuJCcrGkf/C7FZuitDmvy" + "SLgr/74bjPErsmR4BDyFvezI31nrK/2sfNU2cjKnnbAix+knGf/jf/MX/4zk" + "w70P6ZePTJKMFj9xBEYyYZdzwLj7MAamoaYBur//yOiDH/rue346DwBA8eit" + "OryelU0AH8CFYJh/8UvB337zG5/4+s5h0MRgHk1kx1LSAyOzeujSSxgJenv9" + "oT4AhhyQklnUXGfdhadauiXJjpZF6X9dfl3p8//6gSvbOHBAzX4YveGHCzis" + "fw0OvfMrb/n3B3Mxp5RsGjwcs0OyLba+8lByIwyldaZH+q6/fOCjX5Q+DlAa" + "IGNkbbQc7HbyMdjJLX81mIZyzsMUnUgRmO32W19zohX064UUyGIndzqc0z2e" + "l7vZgOWyobytkhUPRUeT53h+Hlnu3FCe/vr37uS+98cv5NYeXy8djRVK8p/Y" + "hmdWPJwC8feeRIquFJmADn1++DNXnOdfBBJFIFEBSBnRIUCa9Fhk7VGfPf93" + "f/Kn97z1a6ehnTZ0yfEktS3lSQpdBNmhRSYAv9T/qTdvg2N1ARRXclOhm4zf" + "BtV9+a8zQMHHbo9P7Wy5c5ji9/0n7cjv/of/uGkQcmS6xSx/gl+En/vY/c03" + "fSfnP4SIjPvB9GZUB0vDQ97ypxb/tvPIuT/bgc6L0BVlb93JSU6SJZ4I1lrR" + "/mIUrE2PtR9fN20XCU8cQOBrT8LTkW5PgtPhbAK+M+rs+9IJPMpH+TJ4ru2l" + "6rWTeHQKyj+aOcu1vLyeFT++56GtqB+Av1Pg+Z/syeqziu3Ef7W5t/p4+GD5" + "4YPp7XQo5azFLeBlZTUrWluJ9duGx5uyopOeAshztryL7eYCBrdW73T2+RMA" + "oqJ88Q04dMuVtvnWiUG4O8r1ffU4kKkgPq7bDrafsVfy0M48sbtdwZ7QtfMj" + "6wpC965DYQMPLIbf/49Pf/XXHv0miK8edHaZ+R6E1ZEeh0m2P/il5z70wCue" + "+db7c8QFcMv9wov3vzmTOnspi7NilBXjfVPvz0xl8kXOAKASlYOkpubWvmRa" + "jUJrAeaS5d7iF37q6jfnH/v2p7cL25M5dIJYe+8z7/vB7gee2TmynXj0phX9" + "UZ7tliJX+s69EQ6hay/VS87R/qfPPvVHv/PUe7ZaXT2+OCbA3u/Tf/XfX939" + "yLe+fIt11hnH+z84Nr7zV7poRDb2/yhO0GcrNk1nOo3UYXRcKGx6Op6aDXHd" + "KZGNlF2T4263FYiuUJ/T7HzTomQFqZSSWowto03su/6GIQKPYwcSyzb7RQa2" + "5pMmQ5qBGZQ4MSH7i2Da7yyc3mDizwCdLPGMH5g4p9JBTCD6ht5oerxWGwjM" + "FaNqLNYrWK1elYcYjCBOFTUtLyIwdmIrshcTnWjWr3dMDPfnHDOyrFLYpgWm" + "lgydQqeOhUYlsYJBn5qOXaNaxDtcMp+u28Ha9FvrdDr0HGtqTTmSIf201XMJ" + "MhHmvhckttStWPFMH3KTNpdYDdfqUwKulNGqIbJlL2DEhNHnSmOiLC2PdImh" + "2CmbvoahVVMreSXfxjbcpI7Zs3KHnc1qS6vaXxRaaM1iZnI/8FhuvZHc6Wgy" + "mw95v6ZyriKSdiSXg0mktAtrUl6bq7Gib+wJrNI90UetqmBtuKFfX9Wkiikk" + "tt9j3S5bpZByYE1CjNX0SZlLOVqx/cDYYAs0WEkCI9O+VC118LpRIiKMqtO2" + "1k18MmiJc3/SbmMsaeFTMS2ljTR12XZzyHNRpZYamBDUYmXQb5jDUehz9GhQ" + "davT2Am6BDVkQqnZHnZxi/XkFtlpWbzYa3XiUJqzjFA2RaNIaygjgL0q19G0" + "+WydOjw1Ys1kiCAKuZAFWtAJeMQhTVroxf66NEZqBcnR2EYFLs3m3HRFxxa2" + "knF2Vg/bFWqAzxoKTw1JCVVKdr+XjuOJ2l1ThK6lETZqNDorbsH2NppdCRWv" + "1MJpbyIwpBVyqTSeNKdp1C0antqIm3Op2+55yobHfcGttcxeRBpUcVzu9aRm" + "gAoVY4BPh63KMGV4vG8VabfSSnQJBdPYphrJqmb1G2QVOCOilkho9Odx2ppQ" + "xWgMIqFGCHBZKjQXNZRibVZgGlq3Ss6GeA1DRjxWQng1cbixTM+bFEJXWqhV" + "RCe1oe26G4mt8+Kyv8BDzlygPrCo5SyH8jBhIpVWqHHPaGuCE1GakPBmWKgK" + "VHdToUZeYJW7Jb6fLHyXFKqSOC2F/aaXYmtFoqaEE/AVdoxN2FYJXk5K/Krr" + "KEVyISJ+TM08vezxNDd1piHcLa1Z3OxSE5lfhQvTR/giQlHIql5Z40Q/aOJ1" + "vhWl694IrgwIkV1rvkjOKEnyEpeZ9+ebwrrYI5pKbxmVSEawq03FZeTJsMkO" + "B0Nl7LS6HYaManjS86vW3O+30Yo6HzeHIt0RCHIeOV61pVAdY4RX+EBcj9O2" + "i3Tgsqt3R6Mu0ndInKwE0sTwuIFplxGWm+GDdZOPZQzmXSIoDMjOmE9hYj7h" + "YtwRzXFPETlUbvSDiEH7diexbLtABIHBkJOQIgt+r2mbi6bSoBrNtIrFnW4c" + "pPWi2e2wjEdxLC3WJiS96otBTW21pwrXo5nBYFzcYJw+W6Zpu8J3WWPBBUKF" + "dbwAWdDA+BHdMcbdIqP4AT9zZJQ1lgNLEpJ5OjZm1TmLFi2/ZGm9tSb4i0Sb" + "ok2hoEYzp7hYuMEI84rAiRNEqStzhZ0II9HslMQG2yLLpCq0ItPWZ4owEcKe" + "PE1rdYke+CvM6/ooUfRpmRtH6GJcVNGJ0UvWihmWFjhftGpavzlNsGKn1qtY" + "Sa/W8GeIORr3ViWt1BxhtNMxUrpaFmZBedOr80S8Ee2q09JbBqaJy1qhFfVN" + "u44pLTfkaVOTYLk7w1eK1CZjU3TJWYT2XQczu/aag+swUdDRpFKOSk07RFYC" + "KU9lE0mpWWPZTTrCUibU4dhrJUt12EI2ZgXT8aQbDhuRPBBMvxRhjS5hgIwe" + "InBa0pHl0oUdjJ557YLCsmFBNRte4Gw0ZiONpJmwJhBOxAoGvg68hjXoeNVu" + "vWGM/FnR8KlAmOghgpbDUgivnOpwSBoVdgGmLGlYdJtwa9EuA4gowXoNrZUH" + "lmBFtU1cUFY2UXCM0FIrQdm1JEnsgtBAHBfZtPXVvIcLDaWYiORkrXv1VZed" + "VSr98oTeJAtzbTfLJNHBAjRuBlhzKYeDgQ/3Wkit5WNJy+aV1ORbsiXVS9Gs" + "w1cGRXilL70gJic1bNTvtuSooNPzKnCAgC4dWxw3ZIQha2W5UcULJG9G7ZjG" + "hPW4q/O+0h0NgwUvey2CEhteAzNlulhspKWVEZmbwAp8HYZtB+eX+oAYTUYO" + "E1ZtmzPhuTOZcisatbiGvKE7uq700Z4N5uROD8wVfbtZEEhSLY4G1qRekIeM" + "AYc9dzmAN0nFHbrhsuENBYbq8Q7Lm35DVFFPo/AVnJRGcGGglIr1ocX17WAz" + "lsylKcEYN51OsCoyrQ14qpJGhCG2aVKfr9FaJJvueqUpyIqap3FZ7BdTrEF7" + "GlZB3AgpjFRnWuiRQZA6zSmGTxcJhgdROSrg0cyrcHLIDlbdkke3fcmykiXd" + "SDZjygwr8arU8nwuRsX6NFoyHUJfrshOoe2raNMcCWmBUCY6btsDmU+VFSrL" + "sN4Zt0tswVpb/fV8Q62nSp/p8LZoC1TTcpF2I25E/Fju1OVFvdCDHY0INmTd" + "5b2xqXrlmcMErCa24Xrc7FHVhTqtFnlKFZhBq4J5slqtA1dozLBcCLVlW3Js" + "KTATpF9lGKnf8VwAon2vqzVg01RMTEExGDY0Fa3Hia+khlIu6yxhreCK1iJm" + "cZ+vMKt+UFMKy5FVZMriUlbHFLMaJVMqqvkLvFmF1WXJK3QTdjhHbdWYC+F6" + "OFbtoSnNi7gbkMUO6orOyMClMkUkxkKbEqumbC30mAw70w06c2YE7WFliR2P" + "eNJehMTU8cdVxhEZej2dLofFSh3XCqztFvE60WsWg5XV8ip2LdZ5nqfhpYa2" + "qkvRA/u9+gRZ4Q1q6QcOI9orSk/b6Gi+1Cp2IBNkkWSK9amlFcm41qdkRm1P" + "xRY+N7qzuKpr9CCIav0GRUgdi1pMiBJcoLty0RwYM8+vazO1xRRch5iuEUpQ" + "qILvIJg8iFd2iMK8vVmtqsqoS6LVsq7iK3zQLqhTfGNZzBLhN4aF8lqMITOa" + "HtnhjK0rbada1Lk4kKO46MB901xxoqTWe2W8hFQwVFO9zSgdsrPxMOmJw343" + "pTYlMqw12lOuxdHVvj0VZ1ix2KxVmnCoTka+Q2Cljh302z3dmzsBLjc3mGsR" + "tXEN5FAniHjXdY2uUGkVlBpRnzRZiYs5mHGJeqniL5rjGOujfJOdoaiFt/mp" + "rpacNrtxq+hYqJGwVW8wCLGB8QlXa9dgrKIZnGipbcxGwwocUoIvMUgbt6mu" + "58NoP+647YAkmIkNO6W1GTSdURNebvgpoimeE4xalo/UNNKlxy5jCEzdtQfK" + "eskns8JCi4oCWNb2J0IXo8zCoDZd+W2+6KsdpcHCDj9Z8la50EfJjc6IXYEa" + "8WCr4NAWLeL8aNNq+CrfUid9erZZ23FPmlUiK0DUelmoIZth31RaC49vdiN0" + "WePKFX7eaBkrvoA6rVDo8gsaNZFNuVKoztRuP64168NgSLoNuFJAk8EAWGKU" + "fb2r1Yi2YBTgvuaHy3BWH8qlgIcLZqwhuDQDs3rVBKskhBguu+VavYmVRvwU" + "Jnp4StmxRtSLpXBVZLQhpY6N8qBUmePteb9nDAVcVOqGmmopRsLaAK1VO3Bz" + "E4aMG/SJqbmyakyxYVIET8vyIvJxmA+WPbdRKaJIX006xGywEt21aBmB0SYW" + "/gAndKqxQhiVq5ULTVIUtHRRrK+xhY720yUNrwrGrJamysQAm68nn8y2ZebL" + "2xnfnR8CHNxpgQ1x1sC8jB3htulaVrzu4GQl/zt38h7k6CHo4ckWlO1yH7jd" + "VVW+w/3Eu595VqU/WdrZOxFUYuhi7Pk/6WhLzTkiKjtpePz2u3kqv6k7PKn6" + "4rv/5f7pm8y3vozz+4dO6HlS5O9Sz32583rl13eg0wfnVjfdIR5neuL4adWl" + "UIuT0J0eO7N64GBkr2Yj9hrw1PdGtn7rM/RbRsGpPAq2vj9x4Hr0MPctR3wu" + "x9Bpy80Pnt+RM779JU5qfz4r1jF03tDi6d6FWfEwjDY/7GDh2OFnDN17m6ud" + "7Jz6vptuoLe3pspnnr184d5n2b/ObzcObjYvDqALeuI4R48Fj3yf80NNt3Ib" + "Lm4PCf389b4YeuxHvomKoTPZK7fkl7f8vxpD138U/hg6m7+P8j4dQw++NC/g" + "yt9HuT4YQ/fdjgu4EpRHqT8cQ6+6FTWgBOVRyo/G0JWTlKD//H2U7mMxdOmQ" + "LobObT+OkvwmkA5Iss/f8vdPG598ORd+C/9ERKSnjgPKQchd/WEhdwSDHj2G" + "HPk/QuxnebL9V4gbymef7Q3f9kL1k9s7KMWRNptMyoUBdH57HXaAFNduK21f" + "1rnuYy/e9bmLr9tHtbu2Ch/m7xHdHrr1hQ+YJOL8imbzh/f+/ht/+9lv5Cel" + "/wvO73ufoSIAAA=="); }
51,164
https://github.com/aswinda/brokepacker/blob/master/app/Http/Controllers/backend/AdminInnsController.php
Github Open Source
Open Source
MIT
2,016
brokepacker
aswinda
PHP
Code
303
1,069
<?php namespace App\Http\Controllers\backend; use App\Http\Controllers\Controller; use App\Model\User as User; use App\Model\Product as Product; use App\Model\Provinces as Provinces; use App\Model\Districts as Districts; use App\Model\Agents_routes as Agents_routes; use App\Model\Agents as Agents; use App\Model\Inns as Inns; use App\Model\ProductCategory as ProductCategory; use Input; use Hash; use Redirect; use File; class AdminInnsController extends Controller { /* |-------------------------------------------------------------------------- | Home Controller |-------------------------------------------------------------------------- | | This controller renders your application's "dashboard" for users that | are authenticated. Of course, you are free to change or remove the | controller as you wish. It is just here to get your app started! | */ /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard to the user. * * @return Response */ public function index() { $inns = Inns::listInns(); return view('backend.inns.index') ->with('tab1', 'Inns') ->with('title', 'Inns') ->with('titleDescription', 'Manage Routes') ->with('inns', $inns); } public function create() { $inns = Inns::all(); $districts = Districts::all(); return view('backend.inns.create') ->with('tab1', 'Inns') ->with('tab2', 'Inns') ->with('title', 'Inns') ->with('titleDescription', 'Create') ->with('inns', $inns) ->with('districts', $districts); } public function store() { //menyimpan data yang di create dengan variabel baru $inn = new Inns; $inn->name = Input::get('name'); $inn->address = Input::get('address'); $inn->district_id = Input::get('district'); $inn->price = Input::get('price'); $inn->save(); // sukses menyimpan redirect kemana return Redirect::to('admin/inns') ->with('message', 'Inns has been added'); } public function edit($id) { //ngambil data agents dan districts $districts = Districts::all(); //ngambil satu parameter dengan id yang terselek $inns = Inns::editInns($id); return view('backend.inns.edit') ->with('tab1', 'Inns') ->with('title', 'Inns') ->with('titleDescription', 'Edit') ->with('inns', $inns) ->with('districts', $districts); } public function update($id) { $districts = Districts::all(); //untuk mencari id yang telah di update $inns = Inns::find($id); $inns->name = Input::get('name'); $inns->address = Input::get('address'); $inns->district_id = Input::get('district'); $inns->price = Input::get('price'); //untuk menyimpan $inns->save(); return Redirect::to('admin/inns') ->with('message', 'Inns has been updated!'); } public function delete($id) { Inns::destroy($id); return Redirect::to('admin/inns') ->with('message', 'Routes has been deleted!'); } }
35,520
https://github.com/itplants/coder/blob/master/coder-base/static/apps/logchartscatter/js/index.js
Github Open Source
Open Source
Apache-2.0
null
coder
itplants
JavaScript
Code
2,628
11,450
var pointinterval=60000; // 10分 60X10X1000msewc var filename='/mnt/data/tempController.log'; var removefilename=''; var mdata=[]; // 読み込んだデータ var minValue = '-10'; var maxValue = '40'; var XMLlist=[]; var chart; var now = new Date(); function readResource(){ console.log("readResource"); $.ajaxSetup({ async: false }); $.getJSON( "/app/logchartscatter/command",//url {"command":"cat", "arg":["resources/logchartscatter.res"]},//data function(data) { $.each(data, function(key, val) { rdata = val; } ); rdata=rdata.replace("<br>",""); console.log("readResource:"+rdata); var selectItem=rdata.split(' ')[1]; console.log("selectItem:"+selectItem); if(selectItem){ var radio=''; if(selectItem==='temp'){ radio=document.getElementById("radioTemp"); if(radio){ radio.checked=true; } } else if(selectItem==='hum'){ radio=document.getElementById("radioHum"); if(radio){ radio.checked=true; } } else if(selectItem==='illum'){ radio=document.getElementById("radioIllum"); if(radio){ radio.checked=true; } } else if(selectItem==='pwm'){ radio=document.getElementById("radioPWM"); if(radio){ radio.checked=true; } } else if(selectItem==='const'){ radio=document.getElementById("radioConst"); if(radio){ radio.checked=true; } } else if(selectItem==='AH'){ radio=document.getElementById("radioAH"); if(radio){ radio.checked=true; } else if(selectItem==='press'){ radio=document.getElementById("radioPress"); if(radio){ radio.checked=true; } } } } } ); $.ajaxSetup({ async: true }); } function saveResource(req){ console.log("saveResource"); var saveData="Select "+req; console.log("saveResource:"+saveData); $.ajaxSetup({ async: false }); $.getJSON( "/app/logchartscatter/writeFile",//url {"filename":"resources/logchartscatter.res", "data":saveData},//data function(data) { $.each(data, function(key, val) { rdata = val; }); }); $.ajaxSetup({ async: true }); } var dfd=[]; function rmFile(n,filename){ dfd[n]=$.getJSON( "/app/highchartscatter/command",//url {"command":"rmXML", "arg":filename} );//data $.when(dfd[n]).done(function(data) { lsDataFile(); }); } function oneDayLogRemove(){ if(!filename){ message('select file'); return; } var filenames=[]; var alartfile=[]; filename=filename.substr(0,24); for(i=0;i<XMLlist.length;i++){ if(XMLlist[i].indexOf(filename)>=0){ if(XMLlist[i].indexOf('.log')>=0){ filenames.push(XMLlist[i]); alartfile.push(XMLlist[i].replace('./data/','')); } } } console.log(filenames); // 「OK」時の処理開始 + 確認ダイアログの表示 var dfd=[]; if(window.confirm(alartfile+'を本当に削除しますか?')){ // oneDayLogRm(filenames[0]); for(i=0;i<filenames.length;i++){ rmFile(i,filenames[i]); } } } function oneDayLogRm(fn){ //console.log('Making CSV file...1 '+fn); fn=fn.substr(7,24); fn = fn.replace('tempController',''); //console.log('Making CSV file... '+fn); message('tempController'+fn+'.csv ファイルを作成し、1日分のログを削除します。'); $.getJSON( "/app/logchartscatter/command",//url {"command":"oneDayLog", "arg":[filename,'-r']},//data function(data) { //dataがサーバから受け取るjson値 $.each(data, function(key, val) { rdata = val; }); // lsDataFile(message('')); }); } function fileRemove(){ if(!filename){ message('select file'); return; } // 「OK」時の処理開始 + 確認ダイアログの表示 if(window.confirm(filename+'を本当に削除しますか?')){ if(filename.indexOf('/mnt/data/')<0) filename = '/mnt/data/'+filename; var dfd1=$.getJSON( "/app/highchartscatter/command",//url {"command":"rmXML", "arg":[filename]});//data $.when(dfd1).done(function(data) { // 処理 var sdata=''; $.each(data, function(key, val) { sdata = val; }); // // 何故か、空白が+になって返ってくる // sdata=sdata.split('<br>').join('\n'); // sdata=sdata.split('+').join(' '); lsDataFile(); console.log(sdata); }); } } function selectDefault(){ // console.log('selectDefault'); filename='tempController.log'; var d=document.getElementsByName('tag'); // console.log(d.length); for(i=0;i<d.length;i++){ // console.log('name='+d[i].innerHTML); if(d[i].innerHTML===filename){ // console.log('name='+d[i].innerHTML); d[i].style.backgroundColor = "#22ff22"; } } } function lsDataFile( f ) { // $.ajaxSetup({ async: false }); $.getJSON( "/app/highchartscatter/command",//url {"command":"ls", "args":['./data/tempController*']},//data function(data) { //dataがサーバから受け取るjson値 //var rdata=''; $.each(data, function(key, val) { rdata = val; } ); //resultmessage(rdata); //document.getElementById("list").innerHTML=rdata; console.log(rdata); XMLlist=rdata.split('<br>'); //if(XMLlist[0].indexOf('.log')<0) return; for(i=0;i<XMLlist.length-1;i++){ if(XMLlist[i].indexOf('.err')>=0){ console.log('del '+XMLlist[i]); XMLlist.splice(i,1); } } var ls=document.getElementById("list"); var flist='<table>'; for(i=0;i<XMLlist.length-1;i+=2){ // flist += '<tr><td >['+i+']</td>'+'<td name="tag" onmouseover='+gc+' onmouseout='+wc+'>'+XMLlist[i]+'<td><td>['+(i+1)+']</td>'+'<td name="tag" onmouseover='+gc+' onmouseout='+wc+'>'+XMLlist[i+1]+'<td><tr>'; flist += '<tr><td >['+i+']</td>'+'<td name="tag" >'+XMLlist[i].replace('./data/','')+'<td><td>['+(i+1)+']</td>'+'<td name="tag" >'+XMLlist[i+1].replace('./data/','')+'<td><tr>'; } flist += '</table>'; ls.innerHTML=flist; addListners(); // console.log(rdata); selectDefault(); if(f) f(); }); } function addListners(){ // 各エレメントを取得 var elements = document.getElementsByName("tag"); var element_result = document.getElementById("result"); // ------------------------------------------------------------ // マウスのボタンを押すと実行される関数 // ------------------------------------------------------------ function MouseDownFunc(e){ for(var i=0;i<elements.length;i++) elements[i].style.backgroundColor = "#ffffff"; e.target.style.backgroundColor = "#22ff22"; // element_result.innerHTML = "マウスのボタンが押された (type:\"" + e.type + "\" button:" + e.button + ' target '+e.target + ") " + e.target.innerHTML; } // ------------------------------------------------------------ // マウスのボタンを離すと実行される関数 // ------------------------------------------------------------ function MouseUpFunc(e){ // e.target.style.backgroundColor = "#ffffff"; filename = e.target.innerHTML; var it=document.getElementById('input'); if(it) it.innerHTML=filename; var ot=document.getElementById('output'); removefilename=filenameDate(filename); console.log('|'+removefilename+'|'); if(ot) ot.innerHTML=removefilename; //element_result.innerHTML = "マウスのボタンが離された (type:\"" + e.type + "\" button:" + e.button + 'target '+e.target+") " + e.target.innerHTML; } // ------------------------------------------------------------ // クリックすると実行される関数 // ------------------------------------------------------------ function MouseClickFunc(e){ element_result.innerHTML = "マウスがクリックされた (type:\"" + e.type + "\" button:" + e.button + 'target '+e.target + ") " + e.target.innerHTML; e.target.style.backgroundColor = "#22ff22"; oldelm = e.target; filename = e.target.innerHTML; document.getElementById('input').innerHTML= filename; filename = '/mnt/data/'+filename; var dataname=''; if(radios){ for(i=0;i<radios.length;i++){ if(radios[i].checked){ dataname=radios[i].value; } } } // console.log(dataname); var series=0; loadDataFile(filename, dataname, series); } // ------------------------------------------------------------ // ダブルクリックすると実行される関数 // ------------------------------------------------------------ function MouseDoubleClickFunc(e){ element_result.innerHTML = "マウスがダブルクリックされた (type:\"" + e.type + "\" button:" + e.button + ") " + e.target.innerHTML; } function MouseOverFunc(e){ console.log('Over'); e.target.style.backgroundColor = "#22ff22"; element_result.innerHTML = "マウスがOverされた (type:\"" + e.type + "\" button:" + e.button + ") " + e.target.innerHTML; } function MouseOutFunc(e){ if(e){ e.target.style.backgroundColor = "#ffffff"; console.log('Out'); element_result.innerHTML = "マウスがOutされた (type:\"" + e.type + "\" button:" + e.button + ") " + e.target.innerHTML; } } // ------------------------------------------------------------ // イベントのリッスンを開始する // ------------------------------------------------------------ // イベントリスナーに対応している for(var i=0;i<elements.length;i++){ var element = elements[i]; if(element.addEventListener){ // // element.addEventListener("onmouseout" , MouseOutFunc); // // element.addEventListener("onmouseover" , MouseOverFunc); // マウスのボタンを押すと実行されるイベント element.addEventListener("mousedown" , MouseDownFunc); // マウスのボタンを離すと実行されるイベント element.addEventListener("mouseup" , MouseUpFunc); // クリックすると実行されるイベント // element.addEventListener("click" , MouseClickFunc); // ダブルクリックすると実行されるイベント // element.addEventListener("dblclick" , MouseDoubleClickFunc); // コンテキストメニューが表示される直前に実行されるイベント /* element.addEventListener("contextmenu" , function (e){ // コンテキストメニューの表示を無効化 return false; }); */ // element.preventDefault(); // アタッチイベントに対応している for IE }else if(element.attachEvent){ // element.attachEvent("onmouseover" , MouseOverFunc); // マウスのボタンを押すと実行されるイベント element.attachEvent("onmousedown" , MouseDownFunc); // マウスのボタンを離すと実行されるイベント element.attachEvent("onmouseup" , MouseUpFunc); // クリックすると実行されるイベント //element.attachEvent("onclick" , MouseClickFunc); // ダブルクリックすると実行されるイベント //element.attachEvent("ondblclick" , MouseDoubleClickFunc); // コンテキストメニューが表示される直前に実行されるイベント element.attachEvent("oncontextmenu" , function (e){ // コンテキストメニューの表示を無効化 return false; }); } } } function allDayLog(){ //message('tempController'+filename+'.csv ファイルを作成します。'); $.getJSON( "/app/logchartscatter/command",//url {"command":"allDayLog", "arg":[]},//data function(data) { //dataがサーバから受け取るjson値 $.each(data, function(key, val) { rdata = val; }); // lsDataFile(message('')); }); } function oneDayLog(){ if(filename.indexOf('_00.log') < 0 ){ message('指定日のlogファイルを選択してください。'); return; } filename = filename.replace('tempController','').replace('_00.log',''); filename=filename.substr(0,10); console.log('Making CSV file... '+filename); message('tempController'+filename+'.csv ファイルを作成します。'); $.getJSON( "/app/logchartscatter/command",//url {"command":"oneDayLog", "arg":[filename]},//data function(data) { //dataがサーバから受け取るjson値 $.each(data, function(key, val) { rdata = val; }); // lsDataFile(message('')); }); } function loadDataFile( req, datalabel, s ) { rdata=''; //console.log('req=readLog '+req) message(''); messageConsole('data loading...'); var dfd=''; if(req.indexOf('.log')>=0){ dfd=$.getJSON( "/app/logchartscatter/command",//url {"command":"readLog", "arg":[req,'0']} ); } else if(req.indexOf('.csv')>=0){// CSV dfd=$.getJSON( "/app/logchartscatter/command",//url {"command":"cat", "arg":[req]} // {"command":"readLog", "arg":[req]} ); } $.when(dfd).done(function(rdata) { //処理 setDatatoChart(rdata, datalabel, s); messageConsole(''); }); } function addP(point, datalabel, mdata, prog, prgVal){ var i=0; var lineNo=8;// date, temp, hum, press, dir*pwm, constration, AH, illum var sw=0; lineNo=mdata[0].length; //console.log('lineNo='+lineNo); var n=mdata.length-lineNo; var m=parseInt(mdata.length-1); var arx=[]; var ary=[]; var artmp=[],arhum=[],arillum=[],arpwm=[],arpel=[],arcons=[],arah=[],arlux=[]; point.chart.yAxis.title=datalabel; //point.chart.xAxis.title='time'; // 日本時間表示設定 Highcharts.setOptions({ global: { useUTC: false } }); point = chart.series[0];// 24 series var timeOffset=0;//4*60*60*1000-60*7*1000; if(mdata.length<=2){ messageConsole('no data in this file...'+mdata.length-1); } //console.log('Date '+mdata[i]); k=0; for(i=0;i<mdata.length-1;i++){ if( mdata[i] ){ //var d=mdata[i][0].split(' '); arx[i]=Date.parse(mdata[i][0]); //console.log('arx['+i+']'+arx[i]); if(datalabel=='temp' ){ary[i]=parseFloat(mdata[i][1]);artmp[k]=[arx[i],parseFloat(mdata[i][1])]} if(datalabel=='hum' ) ary[i]=arhum[k]=[arx[i],parseFloat(mdata[i][2])]; if(datalabel=='press') ary[i]=arillum[k]=[arx[i],parseFloat(mdata[i][3])]; if(datalabel=='pwm') {ary[i]=parseFloat(mdata[i][4]);arpwm[k]=[arx[i],parseFloat(mdata[i][4])]} if(datalabel=='peltier') ary[i]=arpel[k]=[arx[i],parseFloat(mdata[i][5])]; if(datalabel=='condensation') ary[i]=arcons[k]=[arx[i],parseFloat(mdata[i][6])]; if(datalabel=='AH') ary[i]=arah[k]=[arx[i],parseFloat(mdata[i][7])]; if(datalabel=='illum'){ ary[i]=arlux[k]=[arx[i],parseFloat(mdata[i][8])]; // console.log('mdata[i][8]:'+parseFloat(mdata[i][8])); } k+=1; } } if(datalabel=='temp' ){ $( function () { now = new Date(); // グラフオブジェクトの生成 chart = new Highcharts.Chart({ chart: { type: 'area', zoomType: 'xy', renderTo: 'container' }, title: { text: 'ITBOX thermo graph' }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, xAxis: { type: 'datetime', labels: { overflow: 'justify' } }, yAxis: { title: { text: '温度変動', tickWidth: 10, }, max: 40, min: 0 }, legend: { enabled: false }, rangeSelector: { selected: 0 }, plotOptions: { area: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1}, stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ] }, marker: { radius: 2 }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, //threshold: null, // pointInterval: 10000, // one hour // pointStart: Date.UTC(2016, 11, 20, 0, 0, 0) // pointStart: Date.parse(mdata[0][0]) } }, series: [{ type: 'line', name: 'Temp', //pointInterval: pointinterval, data: artmp,// for normalize graph tooltip: { valueSuffix: ' ℃' } }] }); }); } if(datalabel=='hum'){ $( function () { now = new Date(); // グラフオブジェクトの生成 chart = new Highcharts.Chart({ chart: { type: 'scatter', zoomType: 'xy', renderTo: 'container' }, title: { text: 'ITBOX hum graph' }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, xAxis: { type: 'datetime', format: "YYYYMMDDHHmmss", minRange: 100 // fourteen days }, yAxis: { title: { text: '相対湿度(%RH)', tickWidth: 10, }, max: 100, min: 0 }, legend: { enabled: false }, plotOptions: { area: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1}, stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ] }, marker: { radius: 2 }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, //threshold: null } }, series: [{ type: 'line', name: 'Hum', pointInterval: pointinterval, data: arhum,// for normalize graph tooltip: { valueSuffix: '%RH' } }] }); }); } if(datalabel=='press'){ $( function () { now = new Date(); // グラフオブジェクトの生成 chart = new Highcharts.Chart({ chart: { type: 'scatter', zoomType: 'xy', renderTo: 'container' }, title: { text: 'ITBOX pressure graph' }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, xAxis: { type: 'datetime', format: "YYYYMMDD HHmmss", minRange: 100 // fourteen days }, yAxis: { title: { text: '気圧変動', }, max: 1000, min: 900 }, legend: { enabled: false }, plotOptions: { area: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1}, stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ] }, marker: { radius: 2 }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, //threshold: null } }, series: [{ type: 'line', name: 'press', pointInterval: pointinterval, data: arillum,// for normalize graph tooltip: { valueSuffix: 'hPa' } }] }); }); } if(datalabel=='illum'){ console.log(arlux[0]); $( function () { now = new Date(); // グラフオブジェクトの生成 chart = new Highcharts.Chart({ chart: { type: 'scatter', zoomType: 'xy', renderTo: 'container' }, title: { text: 'ITBOX illum graph' }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, xAxis: { type: 'datetime', format: "YYYYMMDD HHmmss", minRange: 100 // fourteen days }, yAxis: { title: { text: '照度変動', }, max: 10000, min: 0 }, legend: { enabled: false }, plotOptions: { area: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1}, stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ] }, marker: { radius: 2 }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, //threshold: null } }, series: [{ type: 'line', name: 'illum', pointInterval: pointinterval, data: arlux,// for normalize graph tooltip: { valueSuffix: 'Lux' } }] }); }); } if(datalabel=='pwm'){ $( function () { now = new Date(); // グラフオブジェクトの生成 chart = new Highcharts.Chart({ chart: { type: 'scatter', zoomType: 'xy', renderTo: 'container' }, title: { text: 'ITBOX power graph' }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, xAxis: { type: 'datetime', format: "YYYYMMDD HHmmss", minRange: 100 // fourteen days }, yAxis: { title: { text: 'PWM変動', }, max: 100, min: -100 }, legend: { enabled: false }, plotOptions: { area: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1}, stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ] }, marker: { radius: 2 }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, // threshold: null } }, series: [{ type: 'line', name: 'power', pointInterval: pointinterval, data: arpwm,// for normalize graph arpwm tooltip: { valueSuffix: 'PWM(%)' } }] }); }); } if(datalabel=='peltier'){ $( function () { now = new Date(); // グラフオブジェクトの生成 chart = new Highcharts.Chart({ chart: { type: 'scatter', zoomType: 'xy', renderTo: 'container' }, title: { text: 'ITBOX peltier temp graph' }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, xAxis: { type: 'datetime', format: "YYYYMMDD HHmmss", minRange: 100 // fourteen days }, yAxis: { title: { text: 'ペルチェ温度変動', }, max: 50, min: -40 }, legend: { enabled: false }, plotOptions: { area: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1}, stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ] }, marker: { radius: 2 }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, //threshold: null } }, series: [{ type: 'line', name: 'peltier', pointInterval: pointinterval, data: arpel,// for normalize graph tooltip: { valueSuffix: '℃' } }] }); }); } if(datalabel=='condensation'){ $( function () { now = new Date(); // グラフオブジェクトの生成 chart = new Highcharts.Chart({ chart: { type: 'scatter', zoomType: 'xy', renderTo: 'container' }, title: { text: 'ITBOX condensation temp graph' }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, xAxis: { type: 'datetime', format: "YYYYMMDD HHmmss", minRange: 100 // fourteen days }, yAxis: { title: { text: '露点変動', }, max: 40, min: 0 }, legend: { enabled: false }, plotOptions: { area: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1}, stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ] }, marker: { radius: 2 }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, //threshold: null } }, series: [{ type: 'line', name: '露点', pointInterval: pointinterval, data: arcons,// for normalize graph tooltip: { valueSuffix: '℃' } }] }); }); } if(datalabel=='AH'){ $( function () { now = new Date(); // グラフオブジェクトの生成 chart = new Highcharts.Chart({ chart: { type: 'scatter', zoomType: 'xy', renderTo: 'container' }, title: { text: 'ITBOX absolute humidity graph' }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, xAxis: { type: 'datetime', format: "YYYYMMDD HHmmss", minRange: 100 // fourteen days }, yAxis: { title: { text: '絶対湿度', }, max: 20, min: 0 }, legend: { enabled: false }, plotOptions: { area: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1}, stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ] }, marker: { radius: 2 }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, //threshold: null } }, series: [{ type: 'line', name: 'AH', pointInterval: pointinterval, data: arah,// for normalize graph tooltip: { valueSuffix: 'kg/m^3' } }] }); }); } } function setDatatoChart(data, datalabel, s){ //dataがサーバから受け取るjson値をパースする var sdata=''; $.each(data, function(key, val) { sdata = val; }); if(typeof sdata === 'undefined' ) return false; sdata=sdata.split('<br>'); for(j=0;j<sdata.length-1;j++){ if(sdata[j].split) mdata[j]=sdata[j].split(','); console.log('mdata['+j+']='+mdata[j]); } for(j=1;j<mdata.length-1;j++){ if(mdata[j][1] < 10) console.log('mdata['+j+']='+mdata[j][1]); if(mdata[j][1] === 0){ //console.log('!!! mdata['+j+']='+mdata[j][1]); for(k=1;k<mdata[0].length-1;k++){ mdata[j][k]=mdata[j-1][k]; } } } /////!!!!!!///// var point = chart.series[s];//.data; point.yAxis.Minimum = minValue; point.yAxis.Maximum = maxValue; //console.log('mdata2='+mdata[0].toString().split(',')[0]); //point.pointStart=Date.parse(mdata[0].toString().split(',')[0]); var prog = document.getElementById('progress'); var prgVal = document.getElementById('prgVal'); addP(point, datalabel, mdata, prog, prgVal); // initial value if(typeof mdata === "undefined"){ point.addPoint(0.0); point.addPoint(40.0); } return true; } function printProperties(obj) { var properties = ''; for (var prop in obj){ properties += prop + "=" + obj[prop] + "\n"; } alert(properties); } var sdata=''; function readDataFile(){ if(!filename){ message('select file'); return; } var radios = document.getElementsByName('radiosw'); var dataname=''; if(radios){ for(i=0;i<radios.length;i++){ if(radios[i].checked){ dataname=radios[i].value; } } } // if(filename.indexOf("/mnt/data/")<0) filename = '/mnt/data/'+filename; console.log('Loading... '+filename+' '+dataname); var seriese=0; mdata=[]; loadDataFile(filename, dataname, seriese); //console.log('Wait a moment...'); } function filenameDate(filename){ var now = new Date(); filename=filename.replace('./data/',''); console.log('filename='+filename); var month=now.getMonth()+1; if(month.length==1) month='0'+month; var day=now.getDate(); if(day.length==1) day='0'+day; var hour=now.getHours(); if(hour.length==1) hour='0'+hour; var min=now.getMinutes(); if(min.length==1) min='0'+min; timedate = (now.getYear()+1900)+''+month +''+day+''+hour+''+min; var f=filename.split('.'); return f[0]+timedate+'.'+f[1]; } function message(mes){ if ($(document)) { document.getElementById("message").innerHTML=mes; } } function resultmessage(mes){ if ($(document)) { document.getElementById("result").innerHTML=mes; } } function messageConsole(mes){ if ($(document)) { document.getElementById("messageConsole").innerHTML=mes; } } function cancel() { window.location.href="/"; } var rdata=''; // return from command function filePutContents(filename , dataVal) { message("filePutContents:"+filename); // $.ajaxSetup({ async: false }); $.getJSON( "/app/logchartscatter/filePutContents",//url {"command":"filePutContents", "arg":[filename,dataVal]},//data function(data) { //dataがサーバから受け取るjson値 $.each(data, function(key, val) { rdata = val; } ); // resultmessage(rdata); } ); return rdata; } function newfile() { if(window.confirm('本当に'+filename+'を'+removefilename.replace('/mnt/data/','')+'に変更しますか?')){ message("newfile:"); resultmessage(''); if(filename.indexOf('/mnt/data/')<0) filename='/mnt/data/'+filename; if(removefilename.indexOf('/mnt/data/')<0) removefilename='/mnt/data/'+removefilename; var movedfile=removefilename;//filenameDate(filename); message('movefile from '+filename+' to '+movedfile); // $.ajaxSetup({ async: false }); $.getJSON( "/app/logchartscatter/newfile",//url {"command":"mv", "arg":[filename, movedfile]},//data function(data) { //dataがサーバから受け取るjson値 $.each(data, function(key, val) { rdata = val; } ); resultmessage(rdata); lsDataFile(); // var point = chart.series[0];//.data; // point.remove(true); } ); // return rdata; } } function update(){ resultmessage(''); } function makeChart() { $('#rollback').click(function(){ update(); }); // 初回の測定値の取得と、定期処理(5分毎に自動更新) // Logger.getVal(); //update(); //setInterval(Logger.getVal ,5 * 60 * 1000); //setInterval(update , pointinterval); // グラフオブジェクトの生成 // $('#container').highcharts({ chart = new Highcharts.Chart({ chart: { zoomType: 'xy', renderTo: 'container' }, title: { text: 'itplanter thermo graph' }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in' }, xAxis: { type: 'datetime', format: "YYYYMMDDHHmmss", minRange: 100 // fourteen days }, yAxis: { title: { text: '温度変動', max: maxValue, min: minValue } }, legend: { enabled: false }, plotOptions: { area: { fillColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1}, stops: [ [0, Highcharts.getOptions().colors[0]], [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')] ] }, marker: { radius: 2 }, lineWidth: 1, states: { hover: { lineWidth: 1 } }, threshold: null } }, series: [{ type: 'area', name: 'Temp', pointInterval: pointinterval, pointStart: Date.UTC(now.getYear(), now.getMonth()+1, now.getDate(),now.getHours(),now.getMinutes()), // pointStart: moment().add(9, 'hours').format("YYYY-MM-DD-HH:mm:ss"), data: [0,40],// for normalize graph tooltip: { valueSuffix: ' ℃' } }] }); } $(document).ready( function() { makeChart(); readResource(); lsDataFile(); });
17,858
https://github.com/ozwolf-software/raml-mock-server/blob/master/src/main/java/net/ozwolf/mockserver/raml/specification/FilePathSpecification.java
Github Open Source
Open Source
Apache-2.0
2,022
raml-mock-server
ozwolf-software
Java
Code
180
529
package net.ozwolf.mockserver.raml.specification; import net.ozwolf.mockserver.raml.RamlSpecification; import org.raml.model.Raml; import org.raml.parser.loader.FileResourceLoader; import org.raml.parser.loader.ResourceLoader; import org.raml.parser.visitor.RamlDocumentBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; /** * # File Path RAML Specification * * Create a RAML specification based on a filepath location. * * ## Example Usage * * ```java * RamlSpecification specification = new FilePathSpecification("my-service", "src/main/resource/apispecs/apispecs.raml"); * ``` */ public class FilePathSpecification extends RamlSpecification { private final String filePath; /** * Create a new file path RAML specification * * @param name The name of the specification * @param filePath The location on the file path the RAML file can be found. */ public FilePathSpecification(String name, String filePath) { super(name); this.filePath = filePath; } @Override protected Raml getRaml() { try { File file = new File(filePath); if (!file.exists()) throw new IllegalArgumentException(String.format("[ %s ] does not exist.", file.getPath())); if (file.exists() && !file.canRead()) throw new IllegalStateException(String.format("[ %s ] cannot be read.", file.getPath())); if (file.exists() && !file.isFile()) throw new IllegalArgumentException(String.format("[ %s ] is not a file.", file.getPath())); ResourceLoader loader = new FileResourceLoader(file.getParent()); return new RamlDocumentBuilder(loader).build(new FileInputStream(file), file.getAbsolutePath()); } catch (IOException e) { throw new RuntimeException(e); } } }
25,777
https://github.com/kartverket/Geonorge.Kartkatalog/blob/master/Kartverket.Metadatakatalog/Controllers/ThumbnailController.cs
Github Open Source
Open Source
MIT
2,017
Geonorge.Kartkatalog
kartverket
C#
Code
347
1,109
using System; using System.IO; using System.Linq; using System.Net; using System.Web.Mvc; using Kartverket.Metadatakatalog.Models; using Kartverket.Metadatakatalog.Service; namespace Kartverket.Metadatakatalog.Controllers { public class ThumbnailController : Controller { private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly IMetadataService _metadataService; public ThumbnailController(IMetadataService metadataService) { _metadataService = metadataService; } [OutputCache(Duration = 86400)] public ActionResult Index(string uuid, string type="default") { try { MetadataViewModel model = _metadataService.GetMetadataViewModelByUuid(uuid); if (model.Thumbnails != null && model.Thumbnails.Any()) { Thumbnail thumbnail = model.Thumbnails[0]; Thumbnail thumbnailSmall = null; Thumbnail thumbnailMedium = null; Thumbnail thumbnailLarge = null; foreach (var thumb in model.Thumbnails) { if (thumb.Type == "thumbnail" || thumb.Type == "miniatyrbilde") { thumbnailSmall = thumb; } else if (thumb.Type == "medium") { thumbnailMedium = thumb; } else if (thumb.Type == "large_thumbnail") { thumbnailLarge = thumb; } } if (thumbnailSmall != null && type != null && string.Equals(type, "small", StringComparison.InvariantCultureIgnoreCase)) { thumbnail = thumbnailSmall; } else if (thumbnailMedium != null && type != null && string.Equals(type, "medium", StringComparison.InvariantCultureIgnoreCase)) { thumbnail = thumbnailMedium; } else if (thumbnailSmall != null && type != null && string.Equals(type, "medium", StringComparison.InvariantCultureIgnoreCase)) { thumbnail = thumbnailSmall; } else if (thumbnailLarge != null && type != null && string.Equals(type, "large", StringComparison.InvariantCultureIgnoreCase)) { thumbnail = thumbnailLarge; } string url = thumbnail.URL; string mimeType = GetMimeTypeFromUrl(url); Stream stream = DownloadImage(url); return new FileStreamResult(stream, mimeType); } } catch (Exception exception) { Log.Error("Metadata with uuid: " + uuid + " not found in Geonetwork.", exception); } return HttpNotFound(); } public ActionResult RemoveCache(string uuid) { var url = Url.Action("Index", "Thumbnail", new { uuid = uuid }); System.Web.HttpResponse.RemoveOutputCacheItem(url); return new HttpStatusCodeResult(HttpStatusCode.OK); } private string GetMimeTypeFromUrl(string url) { int lastIndexOfDot = url.LastIndexOf('.'); string fileExtension = url.Substring(lastIndexOfDot+1); return "image/" + fileExtension.ToLower(); } private Stream DownloadImage(string uri) { HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse) request.GetResponse(); Stream outputStream = null; if ((response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect)) { Stream inputStream = response.GetResponseStream(); if (inputStream != null) { outputStream = new MemoryStream(); byte[] buffer = new byte[4096]; int bytesRead; do { bytesRead = inputStream.Read(buffer, 0, buffer.Length); outputStream.Write(buffer, 0, bytesRead); } while (bytesRead != 0); outputStream.Position = 0; } } return outputStream; } } }
42,059
https://github.com/DragonFlyBSD/DPorts/blob/master/security/suricata/dragonfly/patch-src_util-fmemopen.h
Github Open Source
Open Source
BSD-2-Clause
2,023
DPorts
DragonFlyBSD
C
Code
27
109
--- src/util-fmemopen.h.orig 2019-10-14 11:25:49 UTC +++ src/util-fmemopen.h @@ -37,7 +37,7 @@ #define USE_FMEM_WRAPPER 1 #endif -#ifdef __OpenBSD__ +#if defined __OpenBSD__ || defined __DragonFly__ #define USE_FMEM_WRAPPER 1 #endif
37,047
https://github.com/WOCyo/policr-mini/blob/master/assets/src/admin/components/PageBody.js
Github Open Source
Open Source
MIT
2,022
policr-mini
WOCyo
JavaScript
Code
17
51
import tw, { styled } from "twin.macro"; export default styled.div` color: #687078; ${tw`mt-2 flex-1 flex flex-col`} `;
34,036
https://github.com/PratthanaSuparat8/sample_app/blob/master/app/controllers/static_pages_controller.rb
Github Open Source
Open Source
MIT, Beerware, LicenseRef-scancode-unknown-license-reference
2,016
sample_app
PratthanaSuparat8
Ruby
Code
14
31
class StaticPagesController < ApplicationController def home end def kingsong1 end def kingsong2 end end
352
https://github.com/DeathSkullPain/MysticalGame/blob/master/mods/mtechs/mtechs.lua
Github Open Source
Open Source
CC0-1.0
null
MysticalGame
DeathSkullPain
Lua
Code
238
692
mtechs = {} local m = mtechs m.actions = {} m.components = {} m.entities = {} m.systems = {} --[[ order of registration is 1. actions 2. components 3. systems 4. entities (after server startup) ]]-- function m.register_action(self, aid) local a = {} a.systems = {} self.actions[action.aid] = a end function m.register_component(self, cid) local c = {} c.entities = {} self.components[cid] = c end function m.register_system(self, sid, actions, components, handle) local s = {} s.actions = {} for action in pairs(actions) do s.actions[action] = true self.actions[action].systems[sid] = true end s.components = {} for component in pairs(components) do s.components[component] = true end s.entities = {} s.handle = handle self.systems[sid] = s end function m.get_systems_for_components(self, components) local systems = {} for sid,system in pairs(self.systems) do local found_all = true for component in pairs(components) do if not system.components[component] then found_all = false break end end if found_all then systems[#systems + 1] = sid end end return systems end function m.add_entity(self, entity_name, components) local e e.eid = entity_name .. tostring(#self.entities + 1) e.components = {} e.systems = {} for cid in pairs(components) do self.components[cid].entities[e.eid] = true e.components[cid] = true end local systems = self.get_systems_for_components(self, e.components) for sid in pairs(systems) do self.systems[sid].entities[e.eid] = true e.systems[sid] = true end self.entities[eid] = e return e.eid end function m.remove_entity(self, eid) local e = self.entities[eid] for sid,system in pairs(e.systems) do self.systems[sid].entities[eid] = nil end for cid,component in pairs(e.components) do self.components[cid].entities[eid] = nil end self.entities[eid] = nil end
48,332
https://github.com/drolean/Servidor-WOW/blob/master/RealmServer/PacketReader/CMSG_CHANNEL_OWNER.cs
Github Open Source
Open Source
Unlicense
2,021
Servidor-WOW
drolean
C#
Code
45
157
using Common.Helpers; namespace RealmServer.PacketReader { /// <summary> /// Handles an incoming request of current owner /// </summary> public class CMSG_CHANNEL_OWNER : Common.Network.PacketReader { public string ChannelName; public CMSG_CHANNEL_OWNER(byte[] data) : base(data) { ChannelName = ReadCString(); #if DEBUG Log.Print(LogType.Debug, $"[CMSG_CHANNEL_OWNER] ChannelName: {ChannelName}"); #endif } } }
35,243
https://github.com/dileepkp/jena-core-opal/blob/master/src/test/java/org/apache/jena/rdfxml/xmloutput/TestMacEncodings.java
Github Open Source
Open Source
Apache-2.0
null
jena-core-opal
dileepkp
Java
Code
346
916
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jena.rdfxml.xmloutput; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import junit.framework.TestSuite; import org.apache.jena.rdf.model.Model ; import org.apache.jena.rdf.model.test.ModelTestBase ; import org.apache.jena.rdfxml.xmlinput.MoreTests ; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestMacEncodings extends ModelTestBase { private static Logger logger = LoggerFactory.getLogger( TestMacEncodings.class ); public TestMacEncodings( String name ) { super( name ); } public static TestSuite suite() { TestSuite suite = new TestSuite( TestMacEncodings.class ); suite.setName("Encodings (particular MacRoman etc.)"); try { OutputStream out = new ByteArrayOutputStream(); new OutputStreamWriter(out,"MacRoman"); InUse = true; } catch (Exception e){ InUse = false; } if (!InUse){ logger.warn("MacRoman not supported on this Java installation: mac encoding tests suppressed."); return suite; } suite.addTest(new MoreTests("testARPMacRoman")); suite.addTest(new MoreTests("testARPMacArabic")); return suite; } static private boolean InUse = false; /* public void test00InitMacTests() { try { OutputStream out = new ByteArrayOutputStream(); Writer wrtr = new OutputStreamWriter(out,"MacRoman"); InUse = true; } catch (Exception e){ InUse = false; } if (!InUse){ logger.warn("MacRoman not supported on this Java installation: mac encoding tests suppressed."); } } */ public void testXMLWriterMacRoman() throws IOException { if (!InUse) return; XMLOutputTestBase.blockLogger(); Model m = createMemModel(); OutputStream fos = new ByteArrayOutputStream(); Writer w = new OutputStreamWriter(fos,"MacRoman"); m.write(w, "RDF/XML"); assertTrue(XMLOutputTestBase.unblockLogger()); } public void testXMLWriteMacArabic() throws IOException { if (!InUse) return; XMLOutputTestBase.blockLogger(); Model m = createMemModel(); OutputStream fos = new ByteArrayOutputStream(); Writer w = new OutputStreamWriter(fos,"MacRoman"); m.write(w, "RDF/XML"); assertTrue(XMLOutputTestBase.unblockLogger()); } }
18,533
https://github.com/ucd-plse/mpi-error-prop/blob/master/src/wpds/Source/wali/util/StringUtils.cpp
Github Open Source
Open Source
BSD-3-Clause, MIT
2,020
mpi-error-prop
ucd-plse
C++
Code
89
305
/*! * @author Nicholas Kidd */ #include "StringUtils.hpp" namespace wali { namespace util { void StringUtils::Tokenize( const std::string& str, std::vector<std::string>& tokens, const std::string& delimiters ) { // Skip delimiters at beginning. std::string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". std::string::size_type pos = str.find_first_of(delimiters, lastPos); while (std::string::npos != pos || std::string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } } }
24,382
https://github.com/AkshayJainG/wrongsecrets/blob/master/src/main/java/org/owasp/wrongsecrets/challenges/docker/Challenge8.java
Github Open Source
Open Source
MIT
2,022
wrongsecrets
AkshayJainG
Java
Code
120
487
package org.owasp.wrongsecrets.challenges.docker; import lombok.extern.slf4j.Slf4j; import org.owasp.wrongsecrets.RuntimeEnvironment; import org.owasp.wrongsecrets.ScoreCard; import org.owasp.wrongsecrets.challenges.Challenge; import org.owasp.wrongsecrets.challenges.Spoiler; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import java.security.SecureRandom; import java.util.List; import java.util.Random; import static org.owasp.wrongsecrets.RuntimeEnvironment.Environment.DOCKER; @Slf4j @Component @Order(8) public class Challenge8 extends Challenge { private static final String alphabet = "0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"; private final Random secureRandom = new SecureRandom(); private final String randomValue; public Challenge8(ScoreCard scoreCard) { super(scoreCard); randomValue = generateRandomString(10); log.info("Initializing challenge 8 with value {}", randomValue); } @Override public Spoiler spoiler() { return new Spoiler(randomValue); } @Override public boolean answerCorrect(String answer) { return randomValue.equals(answer); } public List<RuntimeEnvironment.Environment> supportedRuntimeEnvironments() { return List.of(DOCKER); } private String generateRandomString(int length) { StringBuilder builder = new StringBuilder(length); for (int i = 0; i < length; i++) { builder.append(alphabet.charAt(secureRandom.nextInt(alphabet.length()))); } return new String(builder); } }
28,122
https://github.com/darshanhs90/Java-HackerRank/blob/master/src/May2021GoogLeetcode/_0843GuessTheWord.java
Github Open Source
Open Source
MIT
2,019
Java-HackerRank
darshanhs90
Java
Code
135
400
package May2021GoogLeetcode; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class _0843GuessTheWord { public static void main(String[] args) { } interface Master { public int guess(String word); } public void findSecretWord(String[] wordlist, Master master) { int noOfGuesses = 0; int matches = 0; List<String> list = new ArrayList<String>(Arrays.asList(wordlist)); while (list.size() > 0 && matches != 6 && noOfGuesses < 10) { String currWord = list.remove(0); matches = master.guess(currWord); list = filterWords(matches, list, currWord); noOfGuesses++; } } public List<String> filterWords(int matches, List<String> list, String currWord) { List<String> newList = new ArrayList<String>(); for (int i = 0; i < list.size(); i++) { int currMatches = 0; String str = list.get(i); for (int j = 0; j < str.length(); j++) { if (str.charAt(j) == currWord.charAt(j)) currMatches++; } if (currMatches == matches) { newList.add(str); } } return newList; } }
14,096
https://github.com/tadano4w/JavaProjects/blob/master/spring-boot-demo/src/main/java/app/validation/BookListController.java
Github Open Source
Open Source
Unlicense
null
JavaProjects
tadano4w
Java
Code
65
368
package app.validation; import javax.validation.Valid; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; // Validation annotationを使用するサンプル //http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html //JSR-303/JSR-349 Bean Validation @Controller @RequestMapping("/booklist") public class BookListController { @RequestMapping("/") String index(Book book) { book.setName("名前"); book.setPrice(1000); return "/booklist/index"; } @RequestMapping(value = "/add", method = RequestMethod.POST) String add(@Valid @ModelAttribute("book") Book book, BindingResult errors) { // @ModelAttribute#valueを指定しすると明示的にモデル名が指定でき、それがビュー側で参照する際の名前になる。 // 指定しない場合は、クラス名を先頭小文字にした名前になる。 if (errors.hasErrors()) { return "/booklist/index"; } return "/booklist/index"; } }
34,453
https://github.com/DanielVII/joguete/blob/master/src/components/Carta/HabilUm/index.js
Github Open Source
Open Source
MIT
null
joguete
DanielVII
JavaScript
Code
7
18
import HabilUm from "./HabilUm"; export default HabilUm;
23,904
https://github.com/lefb766/mono/blob/master/mcs/class/dlr/Runtime/Microsoft.Scripting.Core/Compiler/StackSpiller.Temps.cs
Github Open Source
Open Source
Apache-2.0
2,022
mono
lefb766
C#
Code
1,079
2,627
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; #if !FEATURE_CORE_DLR namespace Microsoft.Scripting.Ast.Compiler { #else namespace System.Linq.Expressions.Compiler { #endif internal partial class StackSpiller { private class TempMaker { /// <summary> /// Current temporary variable /// </summary> private int _temp; /// <summary> /// List of free temporary variables. These can be recycled for new temps. /// </summary> private List<ParameterExpression> _freeTemps; /// <summary> /// Stack of currently active temporary variables. /// </summary> private Stack<ParameterExpression> _usedTemps; /// <summary> /// List of all temps created by stackspiller for this rule/lambda /// </summary> private List<ParameterExpression> _temps = new List<ParameterExpression>(); internal List<ParameterExpression> Temps { get { return _temps; } } internal ParameterExpression Temp(Type type) { ParameterExpression temp; if (_freeTemps != null) { // Recycle from the free-list if possible. for (int i = _freeTemps.Count - 1; i >= 0; i--) { temp = _freeTemps[i]; if (temp.Type == type) { _freeTemps.RemoveAt(i); return UseTemp(temp); } } } // Not on the free-list, create a brand new one. temp = Expression.Variable(type, "$temp$" + _temp++); _temps.Add(temp); return UseTemp(temp); } private ParameterExpression UseTemp(ParameterExpression temp) { Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); Debug.Assert(_usedTemps == null || !_usedTemps.Contains(temp)); if (_usedTemps == null) { _usedTemps = new Stack<ParameterExpression>(); } _usedTemps.Push(temp); return temp; } private void FreeTemp(ParameterExpression temp) { Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp)); if (_freeTemps == null) { _freeTemps = new List<ParameterExpression>(); } _freeTemps.Add(temp); } internal int Mark() { return _usedTemps != null ? _usedTemps.Count : 0; } // Free temporaries created since the last marking. // This is a performance optimization to lower the overall number of tempories needed. internal void Free(int mark) { // (_usedTemps != null) ==> (mark <= _usedTemps.Count) Debug.Assert(_usedTemps == null || mark <= _usedTemps.Count); // (_usedTemps == null) ==> (mark == 0) Debug.Assert(mark == 0 || _usedTemps != null); if (_usedTemps != null) { while (mark < _usedTemps.Count) { FreeTemp(_usedTemps.Pop()); } } } [Conditional("DEBUG")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal void VerifyTemps() { Debug.Assert(_usedTemps == null || _usedTemps.Count == 0); } } /// <summary> /// Rewrites child expressions, spilling them into temps if needed. The /// stack starts in the inital state, and after the first subexpression /// is added it is change to non-empty. This behavior can be overridden /// by setting the stack manually between adds. /// /// When all children have been added, the caller should rewrite the /// node if Rewrite is true. Then, it should call Finish with etiher /// the orignal expression or the rewritten expression. Finish will call /// Expression.Comma if necessary and return a new Result. /// </summary> private class ChildRewriter { private readonly StackSpiller _self; private readonly Expression[] _expressions; private int _expressionsCount; private List<Expression> _comma; private RewriteAction _action; private Stack _stack; private bool _done; internal ChildRewriter(StackSpiller self, Stack stack, int count) { _self = self; _stack = stack; _expressions = new Expression[count]; } internal void Add(Expression node) { Debug.Assert(!_done); if (node == null) { _expressions[_expressionsCount++] = null; return; } Result exp = _self.RewriteExpression(node, _stack); _action |= exp.Action; _stack = Stack.NonEmpty; // track items in case we need to copy or spill stack _expressions[_expressionsCount++] = exp.Node; } internal void Add(IList<Expression> expressions) { for (int i = 0, count = expressions.Count; i < count; i++) { Add(expressions[i]); } } internal void AddArguments(IArgumentProvider expressions) { for (int i = 0, count = expressions.ArgumentCount; i < count; i++) { Add(expressions.GetArgument(i)); } } private void EnsureDone() { // done adding arguments, build the comma if necessary if (!_done) { _done = true; if (_action == RewriteAction.SpillStack) { Expression[] clone = _expressions; int count = clone.Length; List<Expression> comma = new List<Expression>(count + 1); for (int i = 0; i < count; i++) { if (clone[i] != null) { Expression temp; clone[i] = _self.ToTemp(clone[i], out temp); comma.Add(temp); } } comma.Capacity = comma.Count + 1; _comma = comma; } } } internal bool Rewrite { get { return _action != RewriteAction.None; } } internal RewriteAction Action { get { return _action; } } internal Result Finish(Expression expr) { EnsureDone(); if (_action == RewriteAction.SpillStack) { Debug.Assert(_comma.Capacity == _comma.Count + 1); _comma.Add(expr); expr = MakeBlock(_comma); } return new Result(_action, expr); } internal Expression this[int index] { get { EnsureDone(); if (index < 0) { index += _expressions.Length; } return _expressions[index]; } } internal Expression[] this[int first, int last] { get { EnsureDone(); if (last < 0) { last += _expressions.Length; } int count = last - first + 1; ContractUtils.RequiresArrayRange(_expressions, first, count, "first", "last"); if (count == _expressions.Length) { Debug.Assert(first == 0); // if the entire array is requested just return it so we don't make a new array return _expressions; } Expression[] clone = new Expression[count]; Array.Copy(_expressions, first, clone, 0, count); return clone; } } } private ParameterExpression MakeTemp(Type type) { return _tm.Temp(type); } private int Mark() { return _tm.Mark(); } private void Free(int mark) { _tm.Free(mark); } [Conditional("DEBUG")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private void VerifyTemps() { _tm.VerifyTemps(); } /// <summary> /// Will perform: /// save: temp = expression /// return value: temp /// </summary> private ParameterExpression ToTemp(Expression expression, out Expression save) { ParameterExpression temp = MakeTemp(expression.Type); save = Expression.Assign(temp, expression); return temp; } /// <summary> /// Creates a special block that is marked as not allowing jumps in. /// This should not be used for rewriting BlockExpression itself, or /// anything else that supports jumping. /// </summary> private static Expression MakeBlock(params Expression[] expressions) { return MakeBlock((IList<Expression>)expressions); } /// <summary> /// Creates a special block that is marked as not allowing jumps in. /// This should not be used for rewriting BlockExpression itself, or /// anything else that supports jumping. /// </summary> private static Expression MakeBlock(IList<Expression> expressions) { return new SpilledExpressionBlock(expressions); } } /// <summary> /// A special subtype of BlockExpression that indicates to the compiler /// that this block is a spilled expression and should not allow jumps in. /// </summary> internal sealed class SpilledExpressionBlock : BlockN { internal SpilledExpressionBlock(IList<Expression> expressions) : base(expressions) { } internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args) { throw ContractUtils.Unreachable; } } }
27,980
https://github.com/pmelkowski/knotx/blob/master/knotx-repository-connector/knotx-repository-connector-http/src/main/java/io/knotx/repository/impl/HttpRepositoryConnectorProxyImpl.java
Github Open Source
Open Source
Apache-2.0
null
knotx
pmelkowski
Java
Code
573
2,284
/* * Copyright (C) 2016 Cognifide Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.knotx.repository.impl; import io.knotx.dataobjects.ClientRequest; import io.knotx.dataobjects.ClientResponse; import io.knotx.http.AllowedHeadersFilter; import io.knotx.http.MultiMapCollector; import io.knotx.http.StringToPatternFunction; import io.knotx.proxy.RepositoryConnectorProxy; import io.knotx.util.DataObjectsUtil; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpResponseStatus; import io.reactivex.Observable; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.RequestOptions; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.reactivex.core.MultiMap; import io.vertx.reactivex.core.buffer.Buffer; import io.vertx.reactivex.core.http.HttpClient; import io.vertx.reactivex.core.http.HttpClientRequest; import io.vertx.reactivex.core.http.HttpClientResponse; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.UnsupportedCharsetException; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; public class HttpRepositoryConnectorProxyImpl implements RepositoryConnectorProxy { private static final Logger LOGGER = LoggerFactory .getLogger(HttpRepositoryConnectorProxyImpl.class); private static final String ERROR_MESSAGE = "Unable to get template from the repository"; private final JsonObject clientOptions; private final JsonObject clientDestination; private final List<Pattern> allowedRequestHeaders; private final HttpClient httpClient; private final JsonObject customRequestHeader; public HttpRepositoryConnectorProxyImpl(Vertx vertx, JsonObject configuration) { clientOptions = configuration.getJsonObject("clientOptions", new JsonObject()); clientDestination = configuration.getJsonObject("clientDestination"); customRequestHeader = configuration.getJsonObject("customRequestHeader", new JsonObject()); allowedRequestHeaders = configuration.getJsonArray("allowedRequestHeaders", new JsonArray()) .stream() .map(object -> (String) object) .map(new StringToPatternFunction()) .collect(Collectors.toList()); httpClient = createHttpClient(vertx); } @Override public void process(ClientRequest request, Handler<AsyncResult<ClientResponse>> result) { MultiMap requestHeaders = buildHeaders(clientDestination.getString("hostHeader"), request.getHeaders()); RequestOptions httpRequestData = buildRequestData(request); if (LOGGER.isDebugEnabled()) { LOGGER.debug("GET HTTP Repository: {}://{}:{}/{} with headers [{}]", httpRequestData.isSsl() ? "https" : "http", httpRequestData.getHost(), httpRequestData.getPort(), httpRequestData.getURI(), DataObjectsUtil.toString(requestHeaders) ); } get(httpClient, httpRequestData, requestHeaders) .doOnNext(this::traceHttpResponse) .flatMap(this::processResponse) .subscribe( response -> result.handle(Future.succeededFuture(response)), error -> { LOGGER.error(ERROR_MESSAGE, error); result.handle(Future.succeededFuture(toInternalError())); } ); } private RequestOptions buildRequestData(ClientRequest request) { return new RequestOptions() .setSsl(clientDestination.getString("scheme", "http").equals("https")) .setURI(buildRepoUri(request)) .setPort(clientDestination.getInteger("port")) .setHost(clientDestination.getString("domain")); } private Observable<HttpClientResponse> get(HttpClient client, RequestOptions requestOptions, MultiMap headers) { return Observable.unsafeCreate(subscriber -> { HttpClientRequest req = client.get(requestOptions); req.headers().addAll(headers); if (headers.get(HttpHeaderNames.HOST.toString()) != null) { req.setHost(headers.get(HttpHeaderNames.HOST.toString())); } Observable<HttpClientResponse> resp = req.toObservable(); resp.subscribe(subscriber); req.end(); }); } private HttpClient createHttpClient(Vertx vertx) { return clientOptions.isEmpty() ? io.vertx.reactivex.core.Vertx.newInstance(vertx).createHttpClient() : io.vertx.reactivex.core.Vertx.newInstance(vertx) .createHttpClient(new HttpClientOptions(clientOptions)); } private String buildRepoUri(ClientRequest repoRequest) { StringBuilder uri = new StringBuilder(repoRequest.getPath()); MultiMap params = repoRequest.getParams(); if (params != null && params.names() != null && !params.names().isEmpty()) { uri.append("?") .append(params.names().stream() .map(name -> new StringBuilder(encode(name)).append("=") .append(encode(params.get(name)))) .collect(Collectors.joining("&")) ); } return uri.toString(); } private String encode(String value) { try { return URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("%2F", "/"); } catch (UnsupportedEncodingException ex) { LOGGER.fatal("Unexpected Exception - Unsupported encoding UTF-8", ex); throw new UnsupportedCharsetException("UTF-8"); } } private Observable<ClientResponse> processResponse(final HttpClientResponse response) { return Observable.just(Buffer.buffer()) .mergeWith(response.toObservable()) .reduce(Buffer::appendBuffer) .toObservable() .map(buffer -> toResponse(buffer, response)); } private ClientResponse toResponse(Buffer buffer, final HttpClientResponse httpResponse) { if (httpResponse.statusCode() >= 300 && httpResponse.statusCode() < 400) { //redirect responses LOGGER.info("Repository 3xx response: {}, Headers[{}]", httpResponse.statusCode(), DataObjectsUtil.toString(httpResponse.headers())); } else if (httpResponse.statusCode() != 200) { LOGGER.error("Repository error response: {}, Headers[{}]", httpResponse.statusCode(), DataObjectsUtil.toString(httpResponse.headers())); } return new ClientResponse() .setStatusCode(httpResponse.statusCode()) .setHeaders(httpResponse.headers()) .setBody(buffer.getDelegate()); } private ClientResponse toInternalError() { return new ClientResponse().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } private MultiMap buildHeaders(String hostHeader, MultiMap headers) { MultiMap result = filteredHeaders(headers); if (customRequestHeader.containsKey("name") && customRequestHeader.containsKey("value")) { result.set( customRequestHeader.getString("name"), customRequestHeader.getString("value") ); } //Overide host header if provided in client destination if (StringUtils.isNotBlank(hostHeader)) { result.set(HttpHeaderNames.HOST.toString(), hostHeader); } return result; } private MultiMap filteredHeaders(MultiMap headers) { return headers.names().stream() .filter(AllowedHeadersFilter.create(allowedRequestHeaders)) .collect(MultiMapCollector.toMultiMap(o -> o, headers::getAll)); } private void traceHttpResponse(HttpClientResponse response) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Got response from remote repository status [{}]", response.statusCode()); } } }
2,733
https://github.com/dayitv89/ios-Multi-Perceptron-NeuralNetwork/blob/master/ML/KRANN+TrainedNetwork/KRANNTrainedNetwork.m
Github Open Source
Open Source
MIT
2,015
ios-Multi-Perceptron-NeuralNetwork
dayitv89
Objective-C
Code
292
1,333
// // KRANNTrainedNetwork.m // ANN V2.1.4 // // Created by Kalvar on 2014/5/22. // Copyright (c) 2014 - 2015年 Kuo-Ming Lin (Kalvar Lin, ilovekalvar@gmail.com). All rights reserved. // #import "KRANNTrainedNetwork.h" @interface KRANNTrainedNetwork () @property (nonatomic, weak) NSCoder *_coder; @end @implementation KRANNTrainedNetwork (fixNSCodings) -(void)_encodeObject:(id)_object forKey:(NSString *)_key { [self._coder encodeObject:_object forKey:_key]; } -(void)_encodeDouble:(double)_object forKey:(NSString *)_key { [self._coder encodeDouble:_object forKey:_key]; } -(void)_encodeFloat:(float)_object forKey:(NSString *)_key { [self._coder encodeFloat:_object forKey:_key]; } -(void)_encodeInteger:(NSInteger)_object forKey:(NSString *)_key { [self._coder encodeInteger:_object forKey:_key]; } @end @implementation KRANNTrainedNetwork @synthesize inputs = _inputs; @synthesize inputWeights = _inputWeights; @synthesize hiddenLayers = _hiddenLayers; @synthesize allHiddenWeights = _allHiddenWeights; @synthesize allHiddenBiases = _allHiddenBiases; @synthesize outputBiases = _outputBiases; @synthesize outputResults = _outputResults; @synthesize outputGoals = _outputGoals; @synthesize learningRate = _learningRate; @synthesize convergenceError = _convergenceError; @synthesize fOfAlpha = _fOfAlpha; @synthesize limitIteration = _limitIteration; @synthesize trainingIteration = _trainingIteration; +(instancetype)sharedNetwork { static dispatch_once_t pred; static KRANNTrainedNetwork *_object = nil; dispatch_once(&pred, ^{ _object = [[KRANNTrainedNetwork alloc] init]; }); return _object; } -(instancetype)init { self = [super init]; if( self ) { } return self; } #pragma --mark NSCoding Auto Lifecycle /* * @ 以下在呼叫 [self init] 時就會被自動建立 */ -(void)encodeWithCoder:(NSCoder *)aCoder { self._coder = aCoder; [self _encodeObject:_inputs forKey:@"inputs"]; [self _encodeObject:_inputWeights forKey:@"inputWeights"]; [self _encodeObject:_hiddenLayers forKey:@"hiddenLayers"]; [self _encodeObject:_allHiddenWeights forKey:@"allHiddenWeights"]; [self _encodeObject:_allHiddenBiases forKey:@"allHiddenBiases"]; [self _encodeObject:_outputBiases forKey:@"outputBiases"]; [self _encodeObject:_outputResults forKey:@"outputResults"]; [self _encodeObject:_outputGoals forKey:@"outputGoals"]; [self _encodeFloat:_learningRate forKey:@"learningRate"]; [self _encodeDouble:_convergenceError forKey:@"convergenceError"]; [self _encodeFloat:_fOfAlpha forKey:@"fOfAlpha"]; [self _encodeInteger:_limitIteration forKey:@"limitIteration"]; [self _encodeInteger:_trainingIteration forKey:@"trainingIteration"]; } -(instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; if(self) { self._coder = aDecoder; _inputs = [aDecoder decodeObjectForKey:@"inputs"]; _inputWeights = [aDecoder decodeObjectForKey:@"inputWeights"]; _hiddenLayers = [aDecoder decodeObjectForKey:@"hiddenLayers"]; _allHiddenWeights = [aDecoder decodeObjectForKey:@"allHiddenWeights"]; _allHiddenBiases = [aDecoder decodeObjectForKey:@"allHiddenBiases"]; _outputBiases = [aDecoder decodeObjectForKey:@"outputBiases"]; _outputResults = [aDecoder decodeObjectForKey:@"outputResults"]; _outputGoals = [aDecoder decodeObjectForKey:@"outputGoals"]; _learningRate = [aDecoder decodeFloatForKey:@"learningRate"]; _convergenceError = [aDecoder decodeDoubleForKey:@"convergenceError"]; _fOfAlpha = [aDecoder decodeFloatForKey:@"fOfAlpha"]; _limitIteration = [aDecoder decodeIntegerForKey:@"limitIteration"]; _trainingIteration = [aDecoder decodeIntegerForKey:@"trainingIteration"]; } return self; } @end
11,361
https://github.com/ReinierMaas/morton/blob/master/benches/morton.rs
Github Open Source
Open Source
MIT
2,021
morton
ReinierMaas
Rust
Code
552
1,680
#[macro_use] extern crate bencher; use bencher::{black_box, Bencher}; use rand::{thread_rng, Rng}; use morton::utils::{idx_tile, idx_tile_tuple}; use morton::{deinterleave_morton, interleave_morton}; fn interleave_1000(b: &mut Bencher) { let x = thread_rng().gen::<u16>(); let y = thread_rng().gen::<u16>(); b.iter(|| { for _ in 0..1000 { black_box(interleave_morton(x, y)); } }); } fn deinterleave_1000(b: &mut Bencher) { let morton = thread_rng().gen::<u32>(); b.iter(|| { for _ in 0..1000 { black_box(deinterleave_morton(morton)); } }); } fn interleave_deinterleave_1000(b: &mut Bencher) { let x = thread_rng().gen::<u16>(); let y = thread_rng().gen::<u16>(); b.iter(|| { for _ in 0..1000 { black_box(deinterleave_morton(interleave_morton(x, y))); } }); } fn deinterleave_interleave_1000(b: &mut Bencher) { let morton = thread_rng().gen::<u32>(); b.iter(|| { for _ in 0..1000 { let (x, y) = deinterleave_morton(morton); black_box(interleave_morton(x, y)); } }); } fn horizontal_access_normal(b: &mut Bencher) { let mut tile_normal = vec![0; 2048 * 2048]; // 16MB allocate more then largest cache // fill tiles with some random numbers for y in 0..2048 { for x in 0..2048 { let random = thread_rng().gen::<u32>(); tile_normal[idx_tile(x, y, 2048)] = random; } } // bench horizontal access (x direction) b.iter(|| { for y in 0..2048 { for x in 0..2048 { black_box(tile_normal[idx_tile(x, y, 2048)]); } } }); } fn vertical_access_normal(b: &mut Bencher) { let mut tile_normal = vec![0; 2048 * 2048]; // 16MB allocate more then largest cache // fill tiles with some random numbers for x in 0..2048 { for y in 0..2048 { let random = thread_rng().gen::<u32>(); tile_normal[idx_tile(x, y, 2048)] = random; } } // bench vertical access (y direction) b.iter(|| { for x in 0..2048 { for y in 0..2048 { black_box(tile_normal[idx_tile(x, y, 2048) as usize]); } } }); } fn morton_access_normal(b: &mut Bencher) { let mut tile_morton = vec![0; 2048 * 2048]; // 16MB allocate more then largest cache // fill tiles with some random numbers for z in 0..2048 * 2048 { let random = thread_rng().gen::<u32>(); tile_morton[idx_tile_tuple(deinterleave_morton(z), 2048) as usize] = random; } // bench horizontal access (x direction) b.iter(|| { for z in 0..2048 * 2048 { black_box(tile_morton[idx_tile_tuple(deinterleave_morton(z), 2048) as usize]); } }); } fn horizontal_access_morton(b: &mut Bencher) { let mut tile_morton = vec![0; 2048 * 2048]; // 16MB allocate more then largest cache // fill tiles with some random numbers for y in 0..2048 { for x in 0..2048 { let random = thread_rng().gen::<u32>(); tile_morton[interleave_morton(x, y) as usize] = random; } } // bench horizontal access (x direction) b.iter(|| { for y in 0..2048 { for x in 0..2048 { black_box(tile_morton[interleave_morton(x, y) as usize]); } } }); } fn vertical_access_morton(b: &mut Bencher) { let mut tile_morton = vec![0; 2048 * 2048]; // 16MB allocate more then largest cache // fill tiles with some random numbers for x in 0..2048 { for y in 0..2048 { let random = thread_rng().gen::<u32>(); tile_morton[interleave_morton(x, y) as usize] = random; } } // bench vertical access (y direction) b.iter(|| { for x in 0..2048 { for y in 0..2048 { black_box(tile_morton[interleave_morton(x, y) as usize]); } } }); } fn morton_access_morton(b: &mut Bencher) { let mut tile_morton = vec![0; 2048 * 2048]; // 16MB allocate more then largest cache // fill tiles with some random numbers for z in 0..2048 * 2048 { let random = thread_rng().gen::<u32>(); tile_morton[z] = random; } // bench horizontal access (x direction) b.iter(|| { for z in 0..2048 * 2048 { black_box(tile_morton[z]); } }); } benchmark_group!( benches, interleave_1000, deinterleave_1000, interleave_deinterleave_1000, deinterleave_interleave_1000, horizontal_access_normal, vertical_access_normal, morton_access_normal, horizontal_access_morton, vertical_access_morton, morton_access_morton ); benchmark_main!(benches);
46,760
https://github.com/ohnx/fwredit/blob/master/backend/compile.sh
Github Open Source
Open Source
MIT
2,020
fwredit
ohnx
Shell
Code
28
87
#!/bin/bash # git clone https://github.com/emscripten-core/emsdk.git # cd emsdk # ./emsdk install latest # ./emsdk activate latest # source ./emsdk_env.sh emcc code.cpp -Iutil/ -O3 -s ASYNCIFY --js-library library.js --bind
21,191
https://github.com/benkonrath/dataset-dashboard/blob/master/pkg/database/migrations/0020-add-dataset-relationships.go
Github Open Source
Open Source
MIT
2,020
dataset-dashboard
benkonrath
Go
Code
54
157
package migrations // language=SQL const AddDatasetRelationships = ` ALTER TABLE corporations ADD COLUMN dataset_entity UUID REFERENCES datasets(dataset_id); ALTER TABLE brands ADD COLUMN dataset_entity UUID REFERENCES datasets(dataset_id); ALTER TABLE brand_categories ADD COLUMN dataset_entity UUID REFERENCES datasets(dataset_id); ALTER TABLE ixrules ADD COLUMN dataset_entity UUID REFERENCES datasets(dataset_id); ALTER TABLE corp_mappings ADD COLUMN dataset_entity UUID REFERENCES datasets(dataset_id); `
6,922
https://github.com/ScalablyTyped/SlinkyTyped/blob/master/a/applicationinsights/src/main/scala/typingsSlinky/applicationinsights/outDeclarationsContractsMod/PageViewData.scala
Github Open Source
Open Source
MIT
2,021
SlinkyTyped
ScalablyTyped
Scala
Code
42
147
package typingsSlinky.applicationinsights.outDeclarationsContractsMod import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation._ /** * An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView. */ @JSImport("applicationinsights/out/Declarations/Contracts", "PageViewData") @js.native class PageViewData () extends typingsSlinky.applicationinsights.outDeclarationsContractsGeneratedMod.PageViewData
12,069
https://github.com/keithhc2/observability/blob/master/dashboards-observability/public/services/timestamp/timestamp.ts
Github Open Source
Open Source
Apache-2.0
null
observability
keithhc2
TypeScript
Code
110
394
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ import { isEmpty, isEqual, map } from 'lodash'; import DSLService from '../requests/dsl'; // eslint-disable-next-line import/no-default-export export default class TimestampUtils { constructor(private dslService: DSLService) {} isTimeField(type: string) { return ['date', 'date_nanos'].some((dateTimeType) => isEqual(type, dateTimeType)); } async getTimestamp(index: string) { const indexMappings = await this.getIndexMappings(index); if (indexMappings?.[index]?.mappings?.properties) { const fieldMappings = indexMappings[index].mappings.properties; const timestamps = { default_timestamp: '', available_timestamps: [] as string[], }; map(fieldMappings, (mapping, field) => { if ( mapping.type && this.isTimeField(mapping.type) && isEmpty(timestamps.default_timestamp) ) { timestamps.default_timestamp = field; } else if (mapping.type && this.isTimeField(mapping.type)) { timestamps.available_timestamps.push(field); } }); return timestamps; } } async getIndexMappings(index: string) { return await this.dslService.fetchFields(index); } }
32,501
https://github.com/charlie5/lace/blob/master/3-mid/opengl/source/lean/model/opengl-model-sphere-lit_textured.adb
Github Open Source
Open Source
ISC
2,023
lace
charlie5
Ada
Code
695
2,091
with openGL.Geometry.lit_textured, openGL.Primitive.indexed; package body openGL.Model.sphere.lit_textured is --------- --- Forge -- function new_Sphere (Radius : in Real; lat_Count : in Positive := default_latitude_Count; long_Count : in Positive := default_longitude_Count; Image : in asset_Name := null_Asset) return View is Self : constant View := new Item; begin Self.define (Radius); Self.lat_Count := lat_Count; Self.long_Count := long_Count; Self.Image := Image; return Self; end new_Sphere; -------------- --- Attributes -- -- NB: - An extra vertex is required at the end of each latitude ring. -- - This last vertex has the same site as the rings initial vertex. -- - The last vertex has 's' texture coord of 1.0, whereas -- the initial vertex has 's' texture coord of 0.0. -- overriding function to_GL_Geometries (Self : access Item; Textures : access Texture.name_Map_of_texture'Class; Fonts : in Font.font_id_Map_of_font) return Geometry.views is pragma unreferenced (Fonts); use Geometry.lit_textured; lat_Count : Positive renames Self.lat_Count; long_Count : Positive renames Self.long_Count; Num_lat_strips : constant Positive := lat_Count - 1; lat_Spacing : constant Real := Degrees_180 / Real (lat_Count - 1); long_Spacing : constant Real := Degrees_360 / Real (long_Count); vertex_Count : constant Index_t := 1 + 1 -- North and south pole. + Index_t ((long_Count + 1) * (lat_Count - 2)); -- Each latitude ring. indices_Count : constant long_Index_t := long_Index_t (Num_lat_strips * (long_Count + 1) * 2); the_Vertices : aliased Geometry.lit_textured.Vertex_array := [1 .. vertex_Count => <>]; the_Sites : aliased Sites := [1 .. vertex_Count => <>]; the_Indices : aliased Indices := [1 .. indices_Count => <>]; the_Geometry : constant Geometry.lit_textured.view := Geometry.lit_textured.new_Geometry; begin set_Sites: declare use linear_Algebra, linear_Algebra_3d; north_Pole : constant Site := [0.0, 0.5, 0.0]; south_Pole : constant Site := [0.0, -0.5, 0.0]; the_Site : Site := north_Pole; vert_Id : Index_t := 1; -- Start at '1' (not '0')to account for north pole. a, b : Real := 0.0; -- Angular 'cursors' used to track lat/long for texture coords. latitude_line_First : Site; begin the_Sites (the_Vertices'First) := north_Pole; the_Vertices (the_Vertices'First).Site := north_Pole; the_Vertices (the_Vertices'First).Normal := Normalised (north_Pole); the_Vertices (the_Vertices'First).Coords := (S => 0.5, T => 1.0); the_Vertices (the_Vertices'First).Shine := 0.5; the_Sites (the_Vertices'Last) := south_Pole; the_Vertices (the_Vertices'Last).Site := south_Pole; the_Vertices (the_Vertices'Last).Normal := Normalised (south_Pole); the_Vertices (the_Vertices'Last).Coords := (S => 0.5, T => 0.0); the_Vertices (the_Vertices'Last).Shine := 0.5; for lat_Id in 2 .. lat_Count - 1 loop a := 0.0; b := b + lat_Spacing; the_Site := the_Site * z_Rotation_from (lat_Spacing); latitude_line_First := the_Site; -- Store initial latitude lines 1st point. vert_Id := vert_Id + 1; the_Sites (vert_Id) := the_Site; -- Add 1st point on a line of latitude. the_Vertices (vert_Id).Site := the_Site; the_Vertices (vert_Id).Normal := Normalised (the_Site); the_Vertices (vert_Id).Coords := (S => a / Degrees_360, T => 1.0 - b / Degrees_180); the_Vertices (vert_Id).Shine := 0.5; for long_Id in 1 .. long_Count loop a := a + long_Spacing; if long_Id /= long_Count then the_Site := the_Site * y_Rotation_from (-long_Spacing); else the_Site := latitude_line_First; -- Restore the_Vertex back to initial latitude lines 1st point. end if; vert_Id := vert_Id + 1; the_Sites (vert_Id) := the_Site; -- Add each succesive point on a line of latitude. the_Vertices (vert_Id).Site := the_Site; the_Vertices (vert_Id).Normal := Normalised (the_Site); the_Vertices (vert_Id).Coords := (S => a / Degrees_360, T => 1.0 - b / Degrees_180); the_Vertices (vert_Id).Shine := 0.5; end loop; end loop; end set_Sites; for i in the_Vertices'Range loop the_Vertices (i).Site := the_Vertices (i).Site * Self.Radius * 2.0; end loop; set_Indices: declare strip_Id : long_Index_t := 0; Upper : Index_t; Lower : Index_t; begin Upper := 1; Lower := 2; for lat_Strip in 1 .. num_lat_Strips loop for Each in 1 .. long_Count + 1 loop strip_Id := strip_Id + 1; the_Indices (strip_Id) := Upper; strip_Id := strip_Id + 1; the_Indices (strip_Id) := Lower; if lat_Strip /= 1 then Upper := Upper + 1; end if; if lat_Strip /= num_lat_Strips then Lower := Lower + 1; end if; end loop; if lat_Strip = 1 then Upper := 2; end if; Lower := Upper + Index_t (long_Count) + 1; end loop; end set_Indices; if Self.Image /= null_Asset then the_Geometry.Texture_is (Textures.fetch (Self.Image)); the_Geometry.is_Transparent (now => the_Geometry.Texture.is_Transparent); end if; the_Geometry.Vertices_are (the_Vertices); declare the_Primitive : constant Primitive.indexed.view := Primitive.indexed.new_Primitive (Primitive.triangle_Strip, the_Indices); begin the_Geometry.add (Primitive.view (the_Primitive)); end; return [1 => Geometry.view (the_Geometry)]; end to_GL_Geometries; end openGL.Model.sphere.lit_textured;
986
https://github.com/ican2002/gnbsim-eurecom/blob/master/gnbsim/encoding/ngap/go.mod
Github Open Source
Open Source
MIT
2,021
gnbsim-eurecom
ican2002
Go Module
Code
21
201
module github.com/hhorai/gnbsim/encoding/ngap go 1.13 require ( github.com/aead/cmac v0.0.0-20160719120800-7af84192f0b1 // indirect github.com/hhorai/gnbsim v0.0.0-20210214125543-31c2f406a8fb github.com/hhorai/gnbsim/encoding/gtp v0.0.0-20210214125543-31c2f406a8fb github.com/hhorai/gnbsim/encoding/nas v0.0.0-20210214125543-31c2f406a8fb github.com/wmnsk/milenage v1.0.4 // indirect )
32,997
https://github.com/milindsingh/commercetools-sdk-java-v2/blob/master/commercetools/commercetools-sdk-java-api/src/main/java-generated/com/commercetools/api/models/project/ProjectChangeCartsConfigurationBuilder.java
Github Open Source
Open Source
Apache-2.0
null
commercetools-sdk-java-v2
milindsingh
Java
Code
121
553
package com.commercetools.api.models.project; import java.util.*; import java.util.function.Function; import javax.annotation.Nullable; import io.vrap.rmf.base.client.Builder; import io.vrap.rmf.base.client.utils.Generated; @Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen") public final class ProjectChangeCartsConfigurationBuilder implements Builder<ProjectChangeCartsConfiguration> { @Nullable private com.commercetools.api.models.project.CartsConfiguration cartsConfiguration; public ProjectChangeCartsConfigurationBuilder cartsConfiguration( Function<com.commercetools.api.models.project.CartsConfigurationBuilder, com.commercetools.api.models.project.CartsConfigurationBuilder> builder) { this.cartsConfiguration = builder.apply(com.commercetools.api.models.project.CartsConfigurationBuilder.of()) .build(); return this; } public ProjectChangeCartsConfigurationBuilder cartsConfiguration( @Nullable final com.commercetools.api.models.project.CartsConfiguration cartsConfiguration) { this.cartsConfiguration = cartsConfiguration; return this; } @Nullable public com.commercetools.api.models.project.CartsConfiguration getCartsConfiguration() { return this.cartsConfiguration; } public ProjectChangeCartsConfiguration build() { return new ProjectChangeCartsConfigurationImpl(cartsConfiguration); } /** * builds ProjectChangeCartsConfiguration without checking for non null required values */ public ProjectChangeCartsConfiguration buildUnchecked() { return new ProjectChangeCartsConfigurationImpl(cartsConfiguration); } public static ProjectChangeCartsConfigurationBuilder of() { return new ProjectChangeCartsConfigurationBuilder(); } public static ProjectChangeCartsConfigurationBuilder of(final ProjectChangeCartsConfiguration template) { ProjectChangeCartsConfigurationBuilder builder = new ProjectChangeCartsConfigurationBuilder(); builder.cartsConfiguration = template.getCartsConfiguration(); return builder; } }
26,620
https://github.com/Werayootk/tiny-sato/blob/master/TinySato/TinySatoPrinterUnitExpception.cs
Github Open Source
Open Source
Apache-2.0
2,020
tiny-sato
Werayootk
C#
Code
47
161
namespace TinySato { using System; using System.Runtime.Serialization; [Serializable] public class TinySatoPrinterUnitException : TinySatoException { public TinySatoPrinterUnitException() { } public TinySatoPrinterUnitException(string message) : base(message) { } public TinySatoPrinterUnitException(string message, Exception inner) : base(message, inner) { } protected TinySatoPrinterUnitException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
35,670
https://github.com/66254264/Flap/blob/master/app/src/main/java/me/yifeiyuan/flapdev/components/databindingsample/SimpleDataBindingModel.java
Github Open Source
Open Source
Apache-2.0
2,022
Flap
66254264
Java
Code
34
129
package me.yifeiyuan.flapdev.components.databindingsample; /** * Flap Github: <a>https://github.com/AlanCheen/Flap</a> * * @author 程序亦非猿 [Follow me](<a> https://github.com/AlanCheen</a>) * @since 2020/3/26 3:28 PM * @since 1.5 */ public class SimpleDataBindingModel { public String text = "DataBinding Component"; }
34,346
https://github.com/CBIIT/caaers/blob/master/caAERS/software/core/src/main/db/migrate/015_Phase3_construction_1/026_ReportTracking.groovy
Github Open Source
Open Source
BSD-3-Clause, LicenseRef-scancode-unknown-license-reference
2,015
caaers
CBIIT
Groovy
Code
188
841
class CreateReportTracking extends edu.northwestern.bioinformatics.bering.Migration { void up() { createTable("report_tracking_status") { t -> t.addVersionColumn() t.addColumn("status", "boolean", nullable:false) t.addColumn("status_message", "string", limit:4000) t.addColumn("recorded_time", "date", nullable:false) t.addColumn('grid_id' , 'string' , nullable:true) } createTable("report_tracking") { t -> t.addVersionColumn() t.addColumn("sub_trk_id", "integer") t.addColumn("xml_trk_id", "integer") t.addColumn("attachment_trk_id", "integer") t.addColumn("emailn_trk_id", "integer") t.addColumn("esbcn_trk_id", "integer") t.addColumn("systemcn_trk_id", "integer") t.addColumn("syssub_trk_id", "integer") t.addColumn("response_trk_id", "integer") t.addColumn("emailsubn_trk_id", "integer") t.addColumn("grid_id" , "string" , nullable:true) t.addColumn("report_version_id", "integer") t.addColumn("attempt_number","integer") } execute('alter table report_tracking add constraint fk_trk_sts_id0 foreign key (xml_trk_id) references report_tracking_status (id)') execute('alter table report_tracking add constraint fk_trk_sts_id1 foreign key (attachment_trk_id) references report_tracking_status (id)') execute('alter table report_tracking add constraint fk_trk_sts_id2 foreign key (esbcn_trk_id) references report_tracking_status (id)') execute('alter table report_tracking add constraint fk_trk_sts_id3 foreign key (systemcn_trk_id) references report_tracking_status (id)') execute('alter table report_tracking add constraint fk_trk_sts_id4 foreign key (emailn_trk_id) references report_tracking_status (id)') execute('alter table report_tracking add constraint fk_trk_sts_id5 foreign key (emailsubn_trk_id) references report_tracking_status (id)') execute('alter table report_tracking add constraint fk_trk_sts_id6 foreign key (response_trk_id) references report_tracking_status (id)') execute('alter table report_tracking add constraint fk_trk_sts_id7 foreign key (sub_trk_id) references report_tracking_status (id)') execute('alter table report_tracking add constraint fk_trk_sts_id9 foreign key (syssub_trk_id) references report_tracking_status (id)') execute('alter table report_tracking add constraint fk_report_id11 foreign key (report_version_id) references report_versions (id)') } void down() { dropTable("report_tracking_status") dropTable("report_tracking") } }
14,554
https://github.com/KingLackland/Edgy/blob/master/iotplatform/src/views/Logout.vue
Github Open Source
Open Source
MIT
null
Edgy
KingLackland
Vue
Code
31
128
<template> <div> </div> </template> <script> export default { name: "Logout", created() { this.$store.dispatch('logout').then(() => { this.$router.push('/login') }).catch(() => { this.$store.dispatch('errorlogout').then(() => { this.$router.push('/login') }) }) } } </script> <style scoped> </style>
45,512
https://github.com/skylark-integration/skylark-webodf/blob/master/.original/WebODF-0.5.10/webodf/tests/odf/MaliciousDocumentTests.js
Github Open Source
Open Source
MIT
null
skylark-webodf
skylark-integration
JavaScript
Code
387
1,078
/** * Copyright (C) 2010-2014 KO GmbH <copyright@kogmbh.com> * * @licstart * This file is part of WebODF. * * WebODF is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License (GNU AGPL) * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * WebODF 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with WebODF. If not, see <http://www.gnu.org/licenses/>. * @licend * * @source: http://www.webodf.org/ * @source: https://github.com/kogmbh/WebODF/ */ /*global core, odf, runtime, NodeFilter, Node*/ /** * @constructor * @param {core.UnitTestRunner} runner * @implements {core.UnitTest} */ odf.MaliciousDocumentTests = function MaliciousDocumentTests(runner) { "use strict"; var r = runner, t, async = core.Async; /*jslint emptyblock:true*/ function noOp() { } /*jslint emptyblock:false*/ /** * Get the security canary injection attacks attempt to set * @returns {!string} */ function getCanary() { return runtime.getWindow().canary; } this.setUp = function () { var root = core.UnitTest.provideTestAreaDiv(); t = { root: root, doc: root.ownerDocument, cleanup: [] }; }; this.tearDown = function () { async.destroyAll(t.cleanup, noOp); core.UnitTest.cleanupTestAreaDiv(); }; /** * Return elements that have a clickTarget attribute defined on them * @param {!Node} node * @returns {!number} */ function acceptClickTarget(node) { if(node.nodeType === Node.ELEMENT_NODE && /**@type{!Element}*/(node).getAttribute("clickTarget")) { return NodeFilter.FILTER_ACCEPT; } return NodeFilter.FILTER_SKIP; } /** * Find elements specifically marked for click-based injection attacks */ function activateClickTargets() { var window = runtime.getWindow(), evObj = t.doc.createEvent('MouseEvents'), clickTargetsWalker = t.doc.createTreeWalker(t.root, NodeFilter.SHOW_ALL, acceptClickTarget, false), targetNode; clickTargetsWalker.currentNode = t.root; targetNode = clickTargetsWalker.nextNode(); while (targetNode) { evObj.initMouseEvent('click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null ); targetNode.dispatchEvent(evObj); targetNode = clickTargetsWalker.nextNode(); } } function loadInjectionDocument(callback) { t.odf = new odf.OdfContainer("odf/malicious-js.fodt", function(odf) { t.doc.importNode(odf.rootElement, true); t.root.appendChild(odf.rootElement); activateClickTargets(); t.canary = getCanary(); r.shouldBe(t, "t.canary", "undefined"); callback(); }); } this.tests = function() { return []; }; this.asyncTests = function () { return r.name([loadInjectionDocument]); }; }; odf.MaliciousDocumentTests.prototype.description = function () { "use strict"; return "Test WebODF handling of malicious documents"; }; (function () { "use strict"; return odf.MaliciousDocumentTests; }());
12,721
https://github.com/stevetranby/labs-tilemaps/blob/master/unity-example/Assets/Libs/OpenSteerDotNet/Vector3.cs
Github Open Source
Open Source
MIT
2,021
labs-tilemaps
stevetranby
C#
Code
2,455
5,314
/* ----------------------------------------------------------------------------- Mogre vector class nabbed and included in the package. Original information below This source file is part of OGRE (Object-oriented Graphics Rendering Engine) ported to C++/CLI For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2005 The OGRE Team Also see acknowledgements in Readme.html This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser 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, or go to http://www.gnu.org/copyleft/lesser.txt. ----------------------------------------------------------------------------- */ namespace OpenSteerDotNet { //value class Quaternion; /** Standard 3-dimensional vector. @remarks A direction in 3D space represented as distances along the 3 orthoganal axes (x, y, z). Note that positions, directions and scaling factors can be represented by a vector, depending on how you interpret the values. */ //[Serializable] public class Vector3 { //public: //DEFINE_MANAGED_NATIVE_CONVERSIONS_FOR_VALUECLASS( Vector3 ) public float x, y, z; public Vector3() { } public Vector3(Vector3 source) { x = source.x; y = source.y; z = source.z; } public Vector3( float fX, float fY, float fZ ) { x=fX; y=fY; z=fZ; } /* explicit Vector3( array<float>^ afCoordinate ) : x( afCoordinate[0] ), y( afCoordinate[1] ), z( afCoordinate[2] ) { } explicit Vector3( array<int>^ afCoordinate ) { x = (float)afCoordinate[0]; y = (float)afCoordinate[1]; z = (float)afCoordinate[2]; } explicit Vector3( float* const r ) : x( r[0] ), y( r[1] ), z( r[2] ) { } */ public Vector3( float scaler ) { x=scaler; y=scaler; z=scaler; } /* float default[int] { inline float get(int i) { assert( i < 3 ); return *(&x+i); } inline void set(int i, float value) { assert( i < 3 ); *(&x+i) = value; } } */ public static bool operator == ( Vector3 lvec, Vector3 rvec ) { return ( lvec.x == rvec.x && lvec.y == rvec.y && lvec.z == rvec.z ); } public static bool operator != ( Vector3 lvec, Vector3 rvec ) { return ( lvec.x != rvec.x || lvec.y != rvec.y || lvec.z != rvec.z ); } //virtual bool Equals(Vector3 other) { return *this == other; } // arithmetic operations public static Vector3 operator + ( Vector3 lvec, Vector3 rvec) { Vector3 kSum=new Vector3(); kSum.x = lvec.x + rvec.x; kSum.y = lvec.y + rvec.y; kSum.z = lvec.z + rvec.z; return kSum; } public static Vector3 operator - ( Vector3 lvec, Vector3 rvec) { Vector3 kDiff = new Vector3(); kDiff.x = lvec.x - rvec.x; kDiff.y = lvec.y - rvec.y; kDiff.z = lvec.z - rvec.z; return kDiff; } public static Vector3 operator * ( Vector3 lvec, float fScalar) { Vector3 kProd = new Vector3(); kProd.x = fScalar*lvec.x; kProd.y = fScalar*lvec.y; kProd.z = fScalar*lvec.z; return kProd; } public static Vector3 operator * ( float fScalar, Vector3 rvec) { Vector3 kProd = new Vector3(); kProd.x = fScalar*rvec.x; kProd.y = fScalar*rvec.y; kProd.z = fScalar*rvec.z; return kProd; } public static Vector3 operator * ( Vector3 lvec, Vector3 rvec) { Vector3 kProd = new Vector3(); kProd.x = lvec.x * rvec.x; kProd.y = lvec.y * rvec.y; kProd.z = lvec.z * rvec.z; return kProd; } public static Vector3 operator / ( Vector3 lvec, float fScalar) { // assert( fScalar != 0.0 ); Vector3 kDiv = new Vector3(); float fInv = 1.0f / fScalar; kDiv.x = lvec.x * fInv; kDiv.y = lvec.y * fInv; kDiv.z = lvec.z * fInv; return kDiv; } public static Vector3 operator / ( Vector3 lvec, Vector3 rvec ) { Vector3 kDiv = new Vector3(); kDiv.x = lvec.x / rvec.x; kDiv.y = lvec.y / rvec.y; kDiv.z = lvec.z / rvec.z; return kDiv; } public static Vector3 operator - ( Vector3 vec ) { Vector3 kNeg = new Vector3(); kNeg.x = -vec.x; kNeg.y = -vec.y; kNeg.z = -vec.z; return kNeg; } public static Vector3 operator + ( Vector3 lvec, float rhs ) { Vector3 ret=new Vector3(rhs); return ret += lvec; } public static Vector3 operator + ( float lhs, Vector3 rvec ) { Vector3 ret=new Vector3(lhs); return ret += rvec; } public static Vector3 operator - ( Vector3 lvec, float rhs ) { return lvec - new Vector3(rhs); } public static Vector3 operator - ( float lhs, Vector3 rvec ) { Vector3 ret=new Vector3(lhs); return ret -= rvec; } /** Returns the length (magnitude) of the vector. @warning This operation requires a square root and is expensive in terms of CPU operations. If you don't need to know the exact length (e.g. for just comparing lengths) use squaredLength() instead. */ public float Length { get { return (float) System.Math.Sqrt( x * x + y * y + z * z ); } } /** Returns the square of the length(magnitude) of the vector. @remarks This method is for efficiency - calculating the actual length of a vector requires a square root, which is expensive in terms of the operations required. This method returns the square of the length of the vector, i.e. the same as the length but before the square root is taken. Use this if you want to find the longest / shortest vector without incurring the square root. */ public float SquaredLength { get { return x * x + y * y + z * z; } } /** Calculates the dot (scalar) product of this vector with another. @remarks The dot product can be used to calculate the angle between 2 vectors. If both are unit vectors, the dot product is the cosine of the angle; otherwise the dot product must be divided by the product of the lengths of both vectors to get the cosine of the angle. This result can further be used to calculate the distance of a point from a plane. @param vec Vector with which to calculate the dot product (together with this one). @returns A float representing the dot product value. */ public float DotProduct(Vector3 vec) { return x * vec.x + y * vec.y + z * vec.z; } /** Normalises the vector. @remarks This method normalises the vector such that it's length / magnitude is 1. The result is called a unit vector. @note This function will not crash for zero-sized vectors, but there will be no changes made to their components. @returns The previous length of the vector. */ public float Normalise() { float fLength = (float) System.Math.Sqrt( x * x + y * y + z * z ); // Will also work for zero-sized vectors, but will change nothing if ( fLength > 1e-08 ) { float fInvLength = 1.0f / fLength; x *= fInvLength; y *= fInvLength; z *= fInvLength; } return fLength; } /** Calculates the cross-product of 2 vectors, i.e. the vector that lies perpendicular to them both. @remarks The cross-product is normally used to calculate the normal vector of a plane, by calculating the cross-product of 2 non-equivalent vectors which lie on the plane (e.g. 2 edges of a triangle). @param vec Vector which, together with this one, will be used to calculate the cross-product. @returns A vector which is the result of the cross-product. This vector will <b>NOT</b> be normalised, to maximise efficiency - call Vector3::normalise on the result if you wish this to be done. As for which side the resultant vector will be on, the returned vector will be on the side from which the arc from 'this' to rkVector is anticlockwise, e.g. UNIT_Y.CrossProduct(UNIT_Z) = UNIT_X, whilst UNIT_Z.CrossProduct(UNIT_Y) = -UNIT_X. This is because OGRE uses a right-handed coordinate system. @par For a clearer explanation, look a the left and the bottom edges of your monitor's screen. Assume that the first vector is the left edge and the second vector is the bottom edge, both of them starting from the lower-left corner of the screen. The resulting vector is going to be perpendicular to both of them and will go <i>inside</i> the screen, towards the cathode tube (assuming you're using a CRT monitor, of course). */ public Vector3 CrossProduct(Vector3 rkVector) { Vector3 kCross = new Vector3(); kCross.x = y * rkVector.z - z * rkVector.y; kCross.y = z * rkVector.x - x * rkVector.z; kCross.z = x * rkVector.y - y * rkVector.x; return kCross; } /** Returns a vector at a point half way between this and the passed in vector. */ public Vector3 MidPoint(Vector3 vec) { return new Vector3( ( x + vec.x ) * 0.5f, ( y + vec.y ) * 0.5f, ( z + vec.z ) * 0.5f ); } /** Returns true if the vector's scalar components are all greater that the ones of the vector it is compared against. */ public static bool operator < ( Vector3 lvec, Vector3 rvec ) { if( lvec.x < rvec.x && lvec.y < rvec.y && lvec.z < rvec.z ) return true; return false; } /** Returns true if the vector's scalar components are all smaller that the ones of the vector it is compared against. */ public static bool operator > ( Vector3 lvec, Vector3 rhs ) { if( lvec.x > rhs.x && lvec.y > rhs.y && lvec.z > rhs.z ) return true; return false; } /** Sets this vector's components to the minimum of its own and the ones of the passed in vector. @remarks 'Minimum' in this case means the combination of the lowest value of x, y and z from both vectors. Lowest is taken just numerically, not magnitude, so -1 < 0. */ public void MakeFloor(Vector3 cmp) { if( cmp.x < x ) x = cmp.x; if( cmp.y < y ) y = cmp.y; if( cmp.z < z ) z = cmp.z; } /** Sets this vector's components to the maximum of its own and the ones of the passed in vector. @remarks 'Maximum' in this case means the combination of the highest value of x, y and z from both vectors. Highest is taken just numerically, not magnitude, so 1 > -3. */ public void MakeCeil(Vector3 cmp) { if( cmp.x > x ) x = cmp.x; if( cmp.y > y ) y = cmp.y; if( cmp.z > z ) z = cmp.z; } /** Generates a vector perpendicular to this vector (eg an 'up' vector). @remarks This method will return a vector which is perpendicular to this vector. There are an infinite number of possibilities but this method will guarantee to generate one of them. If you need more control you should use the Quaternion class. */ public Vector3 Perpendicular { get { float fSquareZero = 0.000001f * 0.000001f;// 1e-06 * 1e-06; Vector3 perp = this.CrossProduct( Vector3.UNIT_X ); // Check length if( perp.SquaredLength < fSquareZero ) { /* This vector is the Y axis multiplied by a scalar, so we have to use another axis. */ perp = this.CrossProduct( Vector3.UNIT_Y ); } return perp; } } /** Generates a new random vector which deviates from this vector by a given angle in a random direction. @remarks This method assumes that the random number generator has already been seeded appropriately. @param angle The angle at which to deviate @param up Any vector perpendicular to this one (which could generated by cross-product of this vector and any other non-colinear vector). If you choose not to provide this the function will derive one on it's own, however if you provide one yourself the function will be faster (this allows you to reuse up vectors if you call this method more than once) @returns A random vector which deviates from this vector by angle. This vector will not be normalised, normalise it if you wish afterwards. */ /* Vector3 RandomDeviant( Radian angle ) { return RandomDeviant(angle, Vector3::ZERO); } Vector3 RandomDeviant( Radian angle, Vector3 up ); #ifndef OGRE_FORCE_ANGLE_TYPES inline Vector3 RandomDeviant( float angle, Vector3 up ) const { return RandomDeviant ( Radian(angle), up ); } inline Vector3 RandomDeviant( float angle ) { return RandomDeviant ( Radian(angle), Vector3::ZERO ); } #endif//OGRE_FORCE_ANGLE_TYPES /** Gets the shortest arc quaternion to rotate this vector to the destination vector. @remarks If you call this with a dest vector that is close to the inverse of this vector, we will rotate 180 degrees around the 'fallbackAxis' (if specified, or a generated axis if not) since in this case ANY axis of rotation is valid. */ /* Quaternion GetRotationTo(Vector3 dest, Vector3 fallbackAxis); Quaternion GetRotationTo(Vector3 dest); */ /** Returns true if this vector is zero length. */ public bool IsZeroLength { get { float sqlen = (x * x) + (y * y) + (z * z); return (sqlen < (1e-06 * 1e-06)); } } /** As normalise, except that this vector is unaffected and the normalised vector is returned as a copy. */ public Vector3 NormalisedCopy { get { Vector3 ret = new Vector3(this); ret.Normalise(); return ret; } } /** Calculates a reflection vector to the plane with the given normal . @remarks NB assumes 'this' is pointing AWAY FROM the plane, invert if it is not. */ public Vector3 Reflect(Vector3 normal) { return new Vector3( this - ( 2 * this.DotProduct(normal) * normal ) ); } /** Returns whether this vector is within a positional tolerance of another vector. @param rhs The vector to compare with @param tolerance The amount that each element of the vector may vary by and still be considered equal */ /* bool PositionEquals(Vector3 rhs, float tolerance) { return Math.floatEqual(x, rhs.x, tolerance) && Math::floatEqual(y, rhs.y, tolerance) && Math::floatEqual(z, rhs.z, tolerance); } inline bool PositionEquals(Vector3 rhs) { return PositionEquals(rhs, 1e-03); } * */ /** Returns whether this vector is within a directional tolerance of another vector. @param rhs The vector to compare with @param tolerance The maximum angle by which the vectors may vary and still be considered equal */ /* inline bool DirectionEquals(Vector3 rhs, Radian tolerance) { float dot = DotProduct(rhs); Radian angle = System::Math::Acos(dot); return Math::Abs(angle.ValueRadians) <= tolerance.ValueRadians; } * */ // special points public static Vector3 ZERO = new Vector3( 0, 0, 0 ); public static Vector3 UNIT_X = new Vector3( 1, 0, 0 ); public static Vector3 UNIT_Y = new Vector3( 0, 1, 0 ); public static Vector3 UNIT_Z = new Vector3( 0, 0, 1 ); public static Vector3 NEGATIVE_UNIT_X = new Vector3( -1, 0, 0 ); public static Vector3 NEGATIVE_UNIT_Y = new Vector3(0, -1, 0); public static Vector3 NEGATIVE_UNIT_Z = new Vector3(0, 0, -1); public static Vector3 UNIT_SCALE = new Vector3(1, 1, 1); /** Function for writing to a stream. */ /* virtual System::String^ ToString() override { return System::String::Format("Vector3({0}, {1}, {2})", x, y, z); } * */ }; }
49,200
https://github.com/expload233/ModPackDownloader/blob/master/modpackdownloader-core/src/main/java/com/nincraft/modpackdownloader/container/ThirdParty.java
Github Open Source
Open Source
MIT
2,022
ModPackDownloader
expload233
Java
Code
47
198
package com.nincraft.modpackdownloader.container; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = false) public class ThirdParty extends Mod { @SerializedName("url") @Expose private String url; private String buildFileName() { return getDownloadUrl().contains(".jar") ? getDownloadUrl().substring(getDownloadUrl().lastIndexOf('/') + 1, getDownloadUrl().lastIndexOf(".jar") + 4) : getRename(); } @Override public void init() { setDownloadUrl(url); setFileName(buildFileName()); } }
44,010
https://github.com/NewSchoolApp/newschool-institutional-site/blob/master/components/mobile/donateBolsaEduca/index.js
Github Open Source
Open Source
MIT
null
newschool-institutional-site
NewSchoolApp
JavaScript
Code
233
791
import React from "react"; import { Container, Flex, Card, Image, Description, Title, Text, Button, Row, Icon, TextRight, TextTitle, LinkDonate, } from "./style"; import PackImage from "../../mobile/pack-image/"; export default function DonateBolsaEduca() { return ( <Container> <Flex> <Description> <TextTitle> Apoie o desenvolvimento de um jovem </TextTitle> <Title>Bolsa de estudos</Title> <Text> Por apenas 29,90 por mês, você apoia um jovem a ter acesso ao aplicativo, onde este aluno poderá assistir aulas de desenvolvimento social, educativo, profissional e soft skills. <Text> Nosso maior objetivo é formar os protagonistas da quebrada e empoderá-los, para que saibam que podem alcançar seus objetivos e chegar aonde quiserem. </Text> </Text> </Description> <Card> <PackImage icon="tools.svg" background="gray/background-texture.png" image="gray/bolsaEduca.png" /> </Card> </Flex> <Flex> <Description> <Title>Como funciona?</Title> <Text> O jovem participa de oficinas de esporte e cultura, workshops, cursos rápidos e videoaulas, tudo gratuito e pensado para a quebrada. </Text> <Row> <Icon src="heart-hand.svg"></Icon> <TextRight>Recebemos sua doação</TextRight> </Row> <Row> <Icon src="house-heart.svg"></Icon> <TextRight>Transformamos a ferramenta em educação</TextRight> </Row> <Row> <Icon src="heart-coin.svg"></Icon> <TextRight>Oferecemos o serviço gratuito ao jovem</TextRight> </Row> <Row> <Icon src="partners.svg"></Icon> <TextRight>Revolucionamos o futuro</TextRight> </Row> </Description> <Description> <Title>Quem pode apoiar?</Title> <Text> A Bolsa de estudo pode ser adquirida por qualquer pessoa que apoia a causa e oferecida a um jovem de favela. </Text> <Text> Você doa um valor fixo mensal e +1 jovem é inserido, tendo acesso à educação de qualidade. </Text> <Button> <LinkDonate href="https://donorbox.org/new-school-doe-um-futuro" target="_blank" > SEJA UM DOADOR </LinkDonate> </Button> </Description> </Flex> </Container> ); }
7,458
https://github.com/liranpeng/E3SM-2CRM/blob/master/components/mpas-source/src/tools/registry/gen_inc.h
Github Open Source
Open Source
zlib-acknowledgement, FTL, RSA-MD
null
E3SM-2CRM
liranpeng
C
Code
247
784
// Copyright (c) 2013, Los Alamos National Security, LLC (LANS) // and the University Corporation for Atmospheric Research (UCAR). // // Unless noted otherwise source code is licensed under the BSD license. // Additional copyright and license information can be found in the LICENSE file // distributed with this code, or at http://mpas-dev.github.com/license.html // // #include "ezxml.h" void write_model_variables(ezxml_t registry); int write_field_pointers(FILE* fd); int write_field_pointer_arrays(FILE* fd); int set_pointer_name(int type, int ndims, char *pointer_name); int add_package_to_list(const char * package, const char * package_list); int build_struct_package_lists(ezxml_t currentPosition, char * out_packages); int get_dimension_information(ezxml_t registry, const char *test_dimname, int *has_time, int *decomp); int build_dimension_information(ezxml_t registry, ezxml_t var, int *ndims, int *has_time, int *decomp); int get_field_information(const char *vartype, const char *varval, char *default_value, const char *varmissval, char *missing_value, int *type); int write_set_field_pointer(FILE *fd, const char *spacing, const char *iterator_name, const char *pool_name); void write_default_namelist(ezxml_t registry); int parse_packages_from_registry(ezxml_t registry); int parse_namelist_records_from_registry(ezxml_t registry); int parse_dimensions_from_registry(ezxml_t registry); int parse_var_array(FILE *fd, ezxml_t registry, ezxml_t superStruct, ezxml_t varArray, const char * corename); int parse_var(FILE *fd, ezxml_t registry, ezxml_t superStruct, ezxml_t currentVar, const char * corename); int parse_struct(FILE *fd, ezxml_t registry, ezxml_t superStruct, int subpool, const char *parentname, const char * corename); int determine_struct_depth(int curLevel, ezxml_t superStruct); int generate_struct_links(FILE *fd, int curLevel, ezxml_t superStruct, ezxml_t registry); int generate_field_exchanges(FILE *fd, int curLevel, ezxml_t superStruct); int generate_field_halo_exchanges_and_copies(ezxml_t registry); int generate_field_inputs(FILE *fd, int curLevel, ezxml_t superStruct); int generate_field_outputs(FILE *fd, int curLevel, ezxml_t superStruct); int generate_field_reads_and_writes(ezxml_t registry); int generate_immutable_streams(ezxml_t registry); int push_attributes(ezxml_t currentPosition); int merge_structs_and_var_arrays(ezxml_t currentPosition); int merge_streams(ezxml_t registry); int parse_structs_from_registry(ezxml_t registry);
34,334
https://github.com/fnogcps/github-actions/blob/master/PHP/Misc/SimpleCalculator.php
Github Open Source
Open Source
ISC
2,019
github-actions
fnogcps
PHP
Code
66
208
<?php /* * [PHP] Simple Calculator (exercise) * github.com/fnogcps */ function Addition($a, $b) { return ($a + $b); } function Subtraction($a, $b) { return ($a - $b); } function Multiplication($a, $b) { return ($a * $b); } function Division($a, $b) { return ($a / $b); } echo '<br><b>Addition: </b>'. Addition(10, 5); echo '<br><b>Subtraction: </b>'. Subtraction(10, 5); echo '<br><b>Multiplication: </b>'. Multiplication(10, 5); echo '<br><b>Division: </b>'. Division(10, 5);
15,235
https://github.com/PenpenLi/xiaobaitbijie.github.com/blob/master/res/views/animation/magicExpress/emotion4/face4_6.plist
Github Open Source
Open Source
Zlib
2,020
xiaobaitbijie.github.com
PenpenLi
XML Property List
Code
110
1,102
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>frames</key> <dict> <key>face4_6_1.png</key> <dict> <key>frame</key> <string>{{96,190},{92,90}}</string> <key>offset</key> <string>{8,-11}</string> <key>rotated</key> <false/> <key>sourceColorRect</key> <string>{{50,41},{92,90}}</string> <key>sourceSize</key> <string>{176,150}</string> </dict> <key>face4_6_2.png</key> <dict> <key>frame</key> <string>{{96,96},{92,92}}</string> <key>offset</key> <string>{7,-10}</string> <key>rotated</key> <false/> <key>sourceColorRect</key> <string>{{49,39},{92,92}}</string> <key>sourceSize</key> <string>{176,150}</string> </dict> <key>face4_6_3.png</key> <dict> <key>frame</key> <string>{{2,96},{92,92}}</string> <key>offset</key> <string>{7,-10}</string> <key>rotated</key> <false/> <key>sourceColorRect</key> <string>{{49,39},{92,92}}</string> <key>sourceSize</key> <string>{176,150}</string> </dict> <key>face4_6_4.png</key> <dict> <key>frame</key> <string>{{2,190},{92,90}}</string> <key>offset</key> <string>{9,-11}</string> <key>rotated</key> <false/> <key>sourceColorRect</key> <string>{{51,41},{92,90}}</string> <key>sourceSize</key> <string>{176,150}</string> </dict> <key>face4_6_5.png</key> <dict> <key>frame</key> <string>{{96,2},{92,92}}</string> <key>offset</key> <string>{9,-10}</string> <key>rotated</key> <false/> <key>sourceColorRect</key> <string>{{51,39},{92,92}}</string> <key>sourceSize</key> <string>{176,150}</string> </dict> <key>face4_6_6.png</key> <dict> <key>frame</key> <string>{{2,2},{92,92}}</string> <key>offset</key> <string>{9,-10}</string> <key>rotated</key> <false/> <key>sourceColorRect</key> <string>{{51,39},{92,92}}</string> <key>sourceSize</key> <string>{176,150}</string> </dict> </dict> <key>metadata</key> <dict> <key>format</key> <integer>2</integer> <key>realTextureFileName</key> <string>face4_6.png</string> <key>size</key> <string>{256,512}</string> <key>smartupdate</key> <string>$TexturePacker:SmartUpdate:ca42436ba74dee035793fbc44c59b3fb:1db728e56c1ab35f7c82654f1b873805:8b142192739084de157d25559e9d356d$</string> <key>textureFileName</key> <string>face4_6.png</string> </dict> </dict> </plist>
19,879
https://github.com/surely66/touchgfx.github.io/blob/master/api/search/enumvalues_8.js
Github Open Source
Open Source
MIT
2,020
touchgfx.github.io
surely66
JavaScript
Code
5
125
var searchData= [ ['mcu_5factive',['MCU_ACTIVE',['../classtouchgfx_1_1_g_p_i_o_ac512ae76d933f4b84acf69c7a53e9ce8.html#ac512ae76d933f4b84acf69c7a53e9ce8ad48a9a2ece8fffba9b7ac23ce7c39f51',1,'touchgfx::GPIO']]] ];
3,453
https://github.com/bricsi0000000000000/Wallet/blob/master/Wallet/Controls/ChartValue.xaml.cs
Github Open Source
Open Source
MIT
null
Wallet
bricsi0000000000000
C#
Code
38
158
using Wallet.Models; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Wallet.Controls { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ChartValue : ContentView { public ChartValue(Finance finance) { InitializeComponent(); FinanceCategory category = FinanceCategoryManager.Get(finance.CategoryId); CategoryNameLabel.Text = category.Name; MoneyLabel.TextColor = Color.FromHex(category.ColorCode); MoneyLabel.Text = finance.Money.FormatToMoney(); } } }
36,313
https://github.com/riverKanies/CodeRiver/blob/master/blueprints/dumb/files/__root__/components/__name__/stories.js
Github Open Source
Open Source
MIT
null
CodeRiver
riverKanies
JavaScript
Code
78
220
import React from 'react' import { storiesOf } from '@kadira/storybook' import { WithNotes } from '@kadira/storybook-addon-notes' import { withKnobs, text } from '@kadira/storybook-addon-knobs' import <%= pascalEntityName %> from './component' const notes = 'This story demonstrates the props that can be passed to <%= pascalEntityName %>' const props = { title: '<%= pascalEntityName %> Title' } storiesOf('<%= pascalEntityName %>', module) .addDecorator(withKnobs) .add('with props', () => { return ( <WithNotes notes={notes}> <<%= pascalEntityName %> title={text('Title', props.title)} /> </WithNotes> ) })
1,516
https://github.com/adambowles/node-client/blob/master/dist/stream.js
Github Open Source
Open Source
MIT
2,017
node-client
adambowles
JavaScript
Code
251
713
'use strict'; // Module dependencies var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var _atmosphere = require('atmosphere.js'); var _atmosphere2 = _interopRequireDefault(_atmosphere); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Stream = (function () { function Stream(client) { _classCallCheck(this, Stream); this.client = client; this.stream = { url: this.client.options.streamBase, contentType: 'application/json', logLevel: 'debug', headers: { 'Authorization': this.client.authorization }, dropHeaders: false, attachHeadersAsQueryString: false, maxReconnectOnClose: 0, enableXDR: true, transport: 'streaming' }; this.stream.onOpen = function streamOpen() { console.log('Connected to stream'); }; this.stream.onError = function streamError(error) { console.log('Stream error: ' + error.reasonPhrase); }; } _createClass(Stream, [{ key: 'subscribe', value: function subscribe(type, callback) { this.stream.onMessage = function streamMessage(data) { var message = undefined; try { message = JSON.parse(data.responseBody); } catch (err) { // Ignore SyntaxErrors if ((err + '').substr(0, 11) !== 'SyntaxError') { console.log('Error parsing JSON: ' + err); } return; } if (Array.isArray(type) && type.indexOf(message.event) > -1 || typeof type === 'string' && message.event === type) { callback(message); } }; _atmosphere2.default.subscribe(this.stream); } }]); return Stream; })(); exports.default = Stream;
3,334
https://github.com/francedot/maui/blob/master/src/Controls/tests/Core.UnitTests/TickerSystemEnabledTests.cs
Github Open Source
Open Source
MIT
2,022
maui
francedot
C#
Code
279
1,085
using System.Threading.Tasks; using NUnit.Framework; namespace Microsoft.Maui.Controls.Core.UnitTests { [TestFixture] public class TickerSystemEnabledTests { [OneTimeSetUp] public void Init() { Device.PlatformServices = new MockPlatformServices(); } [OneTimeTearDown] public void End() { Device.PlatformServices = null; } async Task SwapFadeViews(View view1, View view2) { await view1.FadeTo(0, 1000); await view2.FadeTo(1, 1000); } [Test, Timeout(3000), Ignore("https://github.com/dotnet/maui/pull/1511")] public async Task DisablingTickerFinishesAnimationInProgress() { var view = AnimationReadyHandlerAsync.Prepare(new View { Opacity = 1 }, out var handler); await Task.WhenAll(view.FadeTo(0, 2000), handler.DisableTicker()); Assert.That(view.Opacity, Is.EqualTo(0)); } [Test, Timeout(3000), Ignore("https://github.com/dotnet/maui/pull/1511")] public async Task DisablingTickerFinishesAllAnimationsInChain() { var view1 = new View { Opacity = 1 }; var view2 = new View { Opacity = 0 }; var handler = AnimationReadyHandlerAsync.Prepare(view1, view2); await Task.WhenAll(SwapFadeViews(view1, view2), handler.DisableTicker()); Assert.That(view1.Opacity, Is.EqualTo(0)); } static Task<bool> RepeatFade(View view) { var tcs = new TaskCompletionSource<bool>(); var fadeIn = new Animation(d => { view.Opacity = d; }, 0, 1); var i = 0; fadeIn.Commit(view, "fadeIn", length: 2000, repeat: () => ++i < 2, finished: (d, b) => { tcs.SetResult(b); }); return tcs.Task; } [Test, Timeout(3000), Ignore("https://github.com/dotnet/maui/pull/1511")] public async Task DisablingTickerPreventsAnimationFromRepeating() { var view = AnimationReadyHandlerAsync.Prepare(new View { Opacity = 0 }, out var handler); await Task.WhenAll(RepeatFade(view), handler.DisableTicker()); Assert.That(view.Opacity, Is.EqualTo(1)); } [Test] public async Task NewAnimationsFinishImmediatelyWhenTickerDisabled() { var view = AnimationReadyHandlerAsync.Prepare(new View(), out var handler); await handler.DisableTicker(); await view.RotateYTo(200); Assert.That(view.RotationY, Is.EqualTo(200)); } [Test] public async Task AnimationExtensionsReturnTrueIfAnimationsDisabled() { var label = AnimationReadyHandlerAsync.Prepare(new Label { Text = "Foo" }, out var handler); await handler.DisableTicker(); var result = await label.ScaleTo(2, 500); Assert.That(result, Is.True); } [Test, Timeout(2000)] public async Task CanExitAnimationLoopIfAnimationsDisabled() { var label = AnimationReadyHandlerAsync.Prepare(new Label { Text = "Foo" }, out var handler); await handler.DisableTicker(); var run = true; while (run) { await label.ScaleTo(2, 500); run = !(await label.ScaleTo(0.5, 500)); } } } }
21,727
https://github.com/Ndarko1/family_device_inventory/blob/master/app/views/views.py
Github Open Source
Open Source
MIT
2,021
family_device_inventory
Ndarko1
Python
Code
641
2,284
""" This file contains the various routes for the flask app. """ from flask import abort, render_template, request, flash, redirect, url_for, Blueprint from app.models import db, Users, Devices from app.core import generate_id, add_instance, delete_instance, edit_instance, validate_login, WrongSignIn, hash_password from sqlalchemy.exc import IntegrityError from .forms import UserLogIn, AddUser, AddDevice, DeleteForm flask_app = Blueprint("flask_app", __name__) # initialize blueprint # Global variable to track user login in status logged_in = False @flask_app.route('/login', methods=['GET', 'POST']) def login(): """ login route """ form3 = UserLogIn() try: if form3.validate_on_submit(): if form3.sign_in.data: username = request.form.get('username') password = hash_password(request.form.get('password')) result = validate_login(username, password) if result is True: global logged_in logged_in = True return redirect(url_for('flask_app.index')) else: raise WrongSignIn if form3.sign_up.data: return redirect(url_for('flask_app.signup')) except AttributeError: flash('Please enter both your username and password!') except WrongSignIn: flash('Your username or password is incorrect!') return render_template('login.html', form3=form3) @flask_app.route('/signup', methods=['GET', 'POST']) def signup(): """ signup route """ form2 = AddUser() if form2.validate_on_submit(): try: # add the new user to the database add_instance(Users, uid=generate_id(), username=request.form.get('username'), password=hash_password(request.form.get('password')), usertype="FamilyMember", first_name=request.form.get('fname'), last_name=request.form.get('lname'), ) return redirect(url_for('flask_app.login')) except IntegrityError: flash("Sorry that username is already taken!") return render_template('signup.html', form2=form2) else: # show validaton errors for field, errors in form2.errors.items(): for error in errors: flash("Error in {}: {}".format( getattr(form2, field).label.text, error ), 'error') return render_template('signup.html', form2=form2) @flask_app.route('/') def index(): """ index route """ if logged_in is True: # get a list of unique values in the category column device_categories = Devices.query.with_entities( Devices.category).distinct() return render_template('index.html', device_categories=device_categories) else: return redirect(url_for('flask_app.login')) @flask_app.route('/inventory/<category>') def inventory(category): """ inventory route """ tech = Devices.query.filter_by( category=category).order_by(Devices.name).all() return render_template('device_list.html', tech=tech, category=category) # add a new device to the database @flask_app.route('/add_device', methods=['GET', 'POST']) def add_device(): """ add device route """ form1 = AddDevice() if form1.validate_on_submit(): add_instance(Devices, id=generate_id(), name=request.form['device_name'], device_type=request.form['device_type'], serial=request.form['device_serial'], model=request.form['device_model'], mac_address=request.form['device_mac'], status=request.form['status'], purchase_date=request.form['purchase_date'], owner_username=request.form['owner'], category=request.form['category'], notes=request.form['notes'] ) # create a message to send to the template message = f"The data for device {request.form['device_name']} \ has been submitted." return render_template('add_device.html', message=message) else: # show validaton errors for field, errors in form1.errors.items(): for error in errors: flash("Error in {}: {}".format( getattr(form1, field).label.text, error ), 'error') return render_template('add_device.html', form1=form1) # select a device to edit or delete @flask_app.route('/select_device/<letters>') def select_device(letters): """ select device route """ # Alphabetical sort of devices by name, chunked by letters between _ and _ a, b = list(letters) tech = Devices.query.filter( Devices.name.between(a, b)).order_by(Devices.name).all() return render_template('select_device.html', tech=tech) # edit or delete a device @flask_app.route('/edit_or_delete', methods=['POST']) def edit_or_delete(): """ edit or delete route """ id = request.form['id'] choice = request.form['choice'] device = Devices.query.filter(Devices.id == id).first() form1 = AddDevice() form2 = DeleteForm() return render_template('edit_or_delete.html', device=device, form1=form1, form2=form2, choice=choice) # result of delete - this function deletes the record @flask_app.route('/delete_result', methods=['POST']) def delete_result(): """ delete route """ id = request.form['id_field'] purpose = request.form['purpose'] if purpose == 'delete': deleted_device = delete_instance(Devices, id) db.session.commit() message = f"The device {deleted_device} has been deleted \ from the database." return render_template('result.html', message=message) else: # this calls an error handler abort(405) # result of edit - this function updates the record @flask_app.route('/edit_result', methods=['POST']) def edit_result(): """ edit result route """ id = request.form['id_field'] device = edit_instance(Devices, id, name=request.form['device_name'], device_type=request.form['device_type'], serial=request.form['device_serial'], model=request.form['device_model'], mac_address=request.form['device_mac'], status=request.form['status'], purchase_date=request.form['purchase_date'], owner_username=request.form['owner'], category=request.form['category'], notes=request.form['notes'] ) form1 = AddDevice() if form1.validate_on_submit(): # create a message to send to the template message = f"The data for device {device[1]} has been updated." return render_template('result.html', message=message) else: # show validaton errors device[0] = id for field, errors in form1.errors.items(): for error in errors: flash("Error in {}: {}".format( getattr(form1, field).label.text, error ), 'error') return render_template('edit_or_delete.html', form1=form1, device=device, choice='edit') # error routes @flask_app.errorhandler(404) def page_not_found(e): """ page not found error """ return render_template('error.html', pagetitle="404 Error - Page Not Found", pageheading="Page not found (Error 404)", error=e), 404 @flask_app.errorhandler(405) def form_not_posted(e): """ form not posted error """ return render_template('error.html', pagetitle="405 Error - Form Not Submitted", pageheading="Form was not submitted (Error 405)", error=e), 405 @flask_app.errorhandler(500) def internal_server_error(e): """ internal server error """ return render_template('error.html', pagetitle="500 Error - Internal Server Error", pageheading="Internal server error (500)", error=e), 500
4,391
https://github.com/LaplaceKorea/curve25519-spark2014/blob/master/src/conversion.adb
Github Open Source
Open Source
BSD-3-Clause
2,019
curve25519-spark2014
LaplaceKorea
Ada
Code
60
156
package body Conversion with SPARK_Mode is ------------------------- -- Equal_To_Conversion -- ------------------------- -- This lemma is proved with a manual induction. procedure Equal_To_Conversion (A, B : Integer_Curve25519; L : Product_Index_Type) is begin if L = 0 then return; -- Initialization of lemma end if; Equal_To_Conversion (A, B, L - 1); -- Calling lemma for L - 1 end Equal_To_Conversion; end Conversion;
31,860
https://github.com/tako0910/NanoWallet/blob/master/src/app/modules/languages/ptbr.js
Github Open Source
Open Source
MIT
2,021
NanoWallet
tako0910
JavaScript
Code
6,553
21,685
function PortugueseBRProvider($translateProvider) { 'ngInject' $translateProvider.translations('ptbr', { // HEADER COMPONENT WALLET_NAME_1: 'nano', WALLET_NAME_2: 'Wallet', APP_NAME_SUB: 'A interface de carteiras mais segura para sua conexão com a plataforma NEM', HEADER_LOGIN_BUTTON: 'Entrar', HEADER_SIGNUP_BUTTON: 'Criar carteira', HEADER_DASHBOARD: 'Painel', HEADER_WALLET: 'Carteira', HEADER_SERVICES: 'Serviços', HEADER_EXPLORER: 'Explorador', HEADER_NODE: 'Nodo', HEADER_ACCOUNT: 'Conta', HEADER_LANG_TITLE: 'Idioma', HEADER_LANG_SELECT: 'Selecione um idioma', HEADER_NODE_BLOCK_HEIGHT: 'Número do bloco', HEADER_NODE_CURRENT_NODE: 'Nodo atual', HEARDER_NODE_LIST: 'Lista de nodos', HEADER_NODE_SELECT: 'Selecione um nodo', HEADER_NODE_CUSTOM: 'Nodo personalizado', HEADER_NODE_CONNECT: 'Conectar', HEADER_NODE_CUSTOM_INFO: 'IP ou domínio do nodo', HEADER_NODE_CUSTOM_TOOLTIP: 'Preencha aqui o seu próprio nodo NIS', HEADER_PURGE: 'Limpar', HEADER_PURGE_MESSAGE: 'Por favor, confirme a limpeza de seu armazenamento local. Clicando em "Limpar" todas as carteiras no armazenamento local de seu navegador serão excluídas e não poderão ser recuperadas. Você confirma que fez o backup de todas as suas carteiras e que seus fundos estão seguros.', HEADER_OFFLINE_TX: 'Preparar uma transação offline', HEADER_RELEASE_TX: 'Comunicar uma transação à rede', // FOOTER COMPONENT FOOTER_POWERED_BY_1: 'Powered by', FOOTER_POWERED_BY_2: 'NEM technology.', FOOTER_VERSION: 'Versão', // DASHBOARD MODULE DASHBOARD_TITLE: 'Painel', DASHBOARD_UNCONFIRMED: 'Não confirmado', DASHBOARD_CONFIRMED: 'Confirmado', DASHBOARD_HARVEST_INCOME_TITLE: 'Receitas com coletas nos últimos 25 blocos', DASHBOARD_HARVEST_INCOME_NOTE: 'Apenas blocos com taxas acima de zero', DASHBOARD_HARVEST_INCOME_MESSAGE: 'Nenhuma taxa de transação encontrada nos últimos 25 blocos.', DASHBOARD_NEWS_TITLE: 'Últimas notícias', DASHBOARD_HARVESTED_BLOCKS_TITLE: 'Blocos coletados', DASHBOARD_HARVESTED_BLOCKS_TH: 'Taxas coletadas', DASHBOARD_MARKET_INFO_TITLE: 'Informações de mercado', DASHBOARD_MARKET_INFO_CAP: 'Capitalização de mercado', DASHBOARD_MARKET_INFO_PRICE: 'Preço', DASHBOARD_MARKET_INFO_VOLUME: 'Volume em 24h', DASHBOARD_MARKET_INFO_CHANGES: 'Variação % em (24h)', DASHBOARD_MARKET_INFO_CHANGES_1H: '1h', DASHBOARD_MARKET_INFO_CHANGES_24H: '24h', DASHBOARD_MARKET_INFO_CHANGES_7D: '7d', DASHBOARD_MARKET_INFO_NOTE: '<a href="http://coinmarketcap.com/" target="_blank">CoinMarketCap</a> dados atualizados a cada 5 minutos.', DASHBOARD_NOTICE_1: 'Bem vindo a Nano Wallet Beta!', DASHBOARD_NOTICE_2: 'Por favor <a href="https://github.com/NemProject/NanoWallet" target="_blank">reporte problemas aqui</a>.', DASHBOARD_NOTICE_3: 'O time da NEM sugere que você faça testes primeiramente na TestNet para familiarizar-se com a NanoWallet, antes de utilizar a rede principal MainNet. Um guia simples pode ser encontrado <a href="https://blog.nem.io/nanowallet-tutorial/" target="_blank">aqui</a>. Os usuários são responsáveis pela segurança de seus fundos e por manter um backup seguro de todas as suas chaves privadas. O time da NEM não é responsável por nenhuma perda de fundos pelo uso indevido deste aplicativo na rede principal (MainNet).', DASHBOARD_NOTICE_4: 'Sugerimos que escreva suas chaves privadas em um papel e as guarde em um lugar seguro. Você também pode importar suas contas em aplications para Android e iOS como backup.', DASHBOARD_NOTICE_5: 'Obrigado por sua participação!', // GENERAL GENERAL_BLOCK: 'Bloco', GENERAL_BLOCKS: 'Blocos', GENERAL_NO_RESULTS: 'Nada para exibir', GENERAL_ACCOUNT: 'Conta', GENERAL_ACCOUNTS: 'Contas', GENERAL_MULTISIG_ACCOUNT: 'Conta multiassinada', GENERAL_AMOUNT: 'Valor total', GENERAL_MESSAGE: 'Mensagem', GENERAL_DATE: 'Data', GENERAL_TAB_NORMAL: 'Normal', GENERAL_TAB_SEND: 'Enviar', GENERAL_TAB_MULTISIG: 'Multiassinatura', GENERAL_TOTAL: 'Total', GENERAL_REMOVE: 'Remover', GENERAL_MOSAIC: 'Mosaico', GENERAL_FEE: 'Taxa', GENERAL_LEVY: 'Imposto', GENERAL_LEVY_TYPES: 'Tipos de Imposto', GENERAL_LEVY_TYPES_NOTE: 'I - taxa constante; II - taxa com base percentual', GENERAL_LEVY_TYPE_1: 'Taxa constante', GENERAL_LEVY_TYPE_2: 'Taxa com base percentual', GENERAL_SEND: 'Enviar', GENERAL_TO: 'Para', GENERAL_HASH: 'Hash', GENERAL_HASH_FUNCTION: 'Função Hash', GENERAL_NAME: 'Nome', GENERAL_INFORMATION: 'Informação', GENERAL_ADDRESS: 'Endereço', GENERAL_PUBLIC_KEY: 'Chave pública', GENERAL_PRIVATE_KEY: 'Chave privada', GENERAL_CLEAR_ALL: 'Limpar todos', GENERAL_CLOSE: 'Fechar', GENERAL_COMING_SOON: 'Em breve', GENERAL_NONE: 'Nenhum', GENERAL_DROPBOX: 'Arreste e solte arquivos aqui ou clique para abrir o navegador de arquivos', GENERAL_NETWORK_FEE: 'Taxa da rede', GENERAL_YES: 'Sim', GENERAL_NO: 'Não', GENERAL_TAGS: 'Tags', GENERAL_SINK: 'Coletor', GENERAL_SINK_ADDRESS: 'Endereço coletor', GENERAL_STORAGE: 'Armazenamento', GENERAL_REASON: 'Razões', GENERAL_TRANSACTION_HASH: 'Hash da transação', GENERAL_TRANSACTION_ID: 'ID da transação', GENERAL_OWNER: 'Proprietário', GENERAL_RESULTS: 'Resultados', GENERAL_RESULT: 'Resultado', GENERAL_STATUS: 'Status', GENERAL_LOCATION: 'Localização', GENERAL_ACTION: 'Ação', GENERAL_ACTIONS: 'Ações', GENERAL_ADD: 'Adicionar', GENERAL_ADDED: 'Adicionado', GENERAL_REMOVED: 'Removido', GENERAL_COSIGNATORY: 'Cosignatário', GENERAL_COSIGNATORIES: 'Cosignatários', GENERAL_PROCESSING: 'Processando', GENERAL_ACCOUNT_LABEL: 'Nome da conta', GENERAL_OPTIONAL: '(opcional)', GENERAL_ERROR: 'Erro', GENERAL_EXAMPLE: 'Exemplo', GENERAL_PUBLIC: 'Público', GENERAL_NAMESPACES: 'Registro de nomes', GENERAL_NAMESPACE: 'Registro de nome', GENERAL_SUB_NAMESPACES: 'Registro de subnomes', GENERAL_SUB_NAMESPACE: 'Registro de subnome', GENERAL_MOSAICS: 'Mosaicos', GENERAL_VALUE: 'Valor', GENERAL_CONNECTION_ERROR: 'Houve um erro, talvez seu node esteja com problema ou sua conexão está offline.', GENERAL_HISTORY: 'Histórico', GENERAL_REVEAL: 'Revelação', GENERAL_QR: 'QR code', GENERAL_UPDATE: 'Atualização', GENERAL_UNKNOWN: 'Desconhecido', GENERAL_IMPORTANCE: 'Importância', GENERAL_TRANSACTIONS: 'Transações', GENERAL_REGISTER: 'Registrar', GENERAL_CREATE: 'Criar', GENERAL_RENEW: 'Renovar', GENERAL_CHARACTERS_LEFT: 'Caracteres restantes', GENERAL_CURRENCY: 'Mosaico/Moeda', GENERAL_EDIT: 'Editar', GENERAL_SEND_XEM: 'Enviar XEM', GENERAL_ACTIVE: 'Ativar', GENERAL_INACTIVE: 'Inativar', GENERAL_ACTIVATING: 'Ativando', GENERAL_DEACTIVATING: 'Desativando', GENERAL_REMOTE: 'Remoto', GENERAL_WARNING: 'Alerta', GENERAL_SCORE: 'Pontuação', GENERAL_LENGTH: 'Comprimento', GENERAL_GO_BACK: 'Voltar', GENERAL_NEXT: 'Próximo', GENERAL_START: 'Iniciar', GENERAL_ALIAS: 'Apelidos', GENERAL_CONTACTS: 'Contatos', GENERAL_ENCRYPTED: 'Criptografado', GENERAL_UNENCRYPTED: 'Sem criptografia', GENERAL_HEXADECIMAL: 'Hexadecimal', GENERAL_SELECT_ACCOUNT: 'Selecionar conta', GENERAL_INVOICE: 'Fatura', // HOME MODULE HOME_UNSUPPORTED_BROWSER: 'Sinto muito, mas você não pode usar a Nano Wallet de forma segura com este navegador...', HOME_RECOMMENDED_BROWSERS: 'Os navegadores recomendados são:', HOME_FEATURE_STAND_BY: 'Posicione o cursor sobre uma das funcionalidades para exibir suas informações.', HOME_FEATURE_1: 'Envie e receba XEM de forma fácil e quase instantaneamente com tempo de blocos de apenas 1 minuto!', // TRANSFER TRANSACTION MODULE TRANSFER_TRANSACTION_TITLE: 'Enviar uma transação', TRANSFER_TRANSACTION_NAME: 'Transação de transferência', TRANSFER_TRANSACTION_MULTISIG_NAME: 'Transação de transferência multiassinada', TRANSFER_TRANSACTION_INVOICE: 'Criar fatura', TRANSFER_TRANSACTION_TAB_INVOICE: 'Receber', TRANSFER_TRANSACTION_MOSAIC_TRANSFER: 'Transferência de mosaico', TRANSFER_TRANSACTION_ATTACH_MOSAIC: 'Anexar mosaico', TRANSFER_TRANSACTION_ATTACH: 'Anexar', TRANSFER_TRANSACTION_MOSAICS_ATTACHED: 'Mosaicos anexados', TRANSFER_TRANSACTION_ENCRYPT_MESSAGE: 'Encriptar mensagem', TRANSFER_TRANSACTION_MESSAGE_TYPE: 'Tipo de mensagem', // TRANSACTION LINES LINE_TX_DETAILS_FROM: 'De', LINE_TX_DETAILS_FROM_MULTISIG: 'De multiassinatura', LINE_TX_DETAILS_WAITING: 'Transação aguardando para ser incluída', LINE_TX_DETAILS_NEED_SIG: 'São necessárias as assinaturas dos cossignatários', LINE_TX_DETAILS_NEED_SIG_2: 'Sua assinatura é requerida', LINE_TX_DETAILS_MESS_DEC: 'Decodificar', LINE_TX_DETAILS_HASH: 'Hash', LINE_TX_DETAILS_DEC_MESS: 'Decodificar mensagem', LINE_TX_DETAILS_MOS_ATTACHED: 'Mosaicos anexados', LINE_TX_DETAILS_LEVY_TYPE_1: 'Constante', LINE_TX_DETAILS_LEVY_TYPE_2: 'Base percentual', LINE_TX_DETAILS_ISSUER: 'Emissor', LINE_TX_DETAILS_MULTISIG_FEE: 'Taxa de multiassinatura', LINE_TX_DETAILS_MULTISIG_HASH: 'Hash de multiassinatura', LINE_TX_DETAILS_COSIGN: 'Cossignatário da transação', LINE_TX_DETAILS_SIGNATURES: 'Assinatura(s)', LINE_TX_DETAILS_COSIGNATORY: 'Cossignatário', LINE_TX_DETAILS_TIMESTAMP: 'Timestamp', LINE_TX_DETAILS_MOS_CREATE: 'Criar mosaico', LINE_TX_DETAILS_MOS_EDIT: 'Editar mosaico', LINE_TX_DETAILS_NS_CREATE: 'Criar registro de nome', LINE_TX_DETAILS_NS_NEW_SUB: 'Novo registro de subnome', LINE_TX_DETAILS_NS_ROOT: 'Registro de nome raiz', LINE_TX_DETAILS_RECIPIENT: 'Destinatário', LINE_TX_DETAILS_MULTISIG_CREATE: 'Criar conta multiassinada', LINE_TX_DETAILS_MULTISIG_EDIT: 'Editar conta multiassinada', LINE_TX_DETAILS_MULTISIG_MOD: 'Modificações', LINE_TX_DETAILS_MULTISIG_MIN_COSIG: 'Mínimo de cossignatários', LINE_TX_DETAILS_MULTISIG_AFFECTED: 'Contas afetadas', // IMPORTANCE MODULE IMPORTANCE_TRANSFER_NAME: 'Transação de transferência de importância', IMPORTANCE_TRANSFER_MULTISIG_NAME: 'Transação de transferência de importância multiassinada', IMPORTANCE_TRANSFER_MODE: 'Modo', IMPORTANCE_TRANSFER_MODE_1: 'Ativar', IMPORTANCE_TRANSFER_MODE_2: 'Desativar', IMPORTANCE_TRANSFER_TITLE: 'Gerenciar contas delegadas', IMPORTANCE_TRANSFER_MULTISIGNATURE_TITLE: 'Gerenciar conta delegada de contas multiassinadas', IMPORTANCE_TRANSFER_CUSTOM_KEY: 'Usar uma chave pública personalizada', IMPORTANCE_TRANSFER_MODE_SELECT: 'Selecione um modo', IMPORTANCE_TRANSFER_REMOTE_ACCOUNT: 'Conta remota', IMPORTANCE_TRANSFER_REMOTE_PUBLIC: 'Chave pública remota', IMPORTANCE_TRANSFER_INFO_PART_1: 'Assim que uma transação de transferência de importância é incluída em um bloco, são necessárias 6 horas até que se torne ativa. Após a ativação, você terá acesso à seleção de nodos e aos comandos iniciar/parar colheita.', IMPORTANCE_TRANSFER_INFO_PART_2: 'Assegure-se de que você não tem uma conta delegada já ativada (se for uma conta importada). Nesse caso, se necessário, você pode usar a antiga chave pública delegada para desativar.', IMPORTANCE_TRANSFER_INFO_PART_MULTISIG: 'Para contas multiassinadas apenas o cossignatário que iniciou a transação de transferência de importância pode iniciar ou parar a colheita. Se algum outro cossignatário desejar retomar o controle sobre a colheita, ele apenas precisa desativar e reativar o estado remoto.', IMPORTANCE_TRANSFER_NO_BLOCKS_HARVESTED: 'Não há blocos colhidos', IMPORTANCE_TRANSFER_HARVESTING_PANEL: 'Painel de colheitas', IMPORTANCE_TRANSFER_REMOTE_ACTIVATING: 'Você deve esperar até que o estado remoto esteja ativo para iniciar a colheita delegada (6 horas).', IMPORTANCE_TRANSFER_REMOTE_INACTIVE: 'Você deve enviar uma transferência de importância, do painel à esquerda, para ativar a sua conta remota.', IMPORTANCE_TRANSFER_MULTISIG_NOT_INITIATOR: 'Você não é o cossignatário que iniciou a transferência de importância, portanto não é permitido que você visualize, inicie ou pare a colheita delegada diretamente. Por favor, entre em contato com o cossignatário que administra a conta remota. Você pode remover um administrador para controlar novamente a colheita desativando e reativando sua conta remota.', IMPORTANCE_TRANSFER_PRIVATE_KEY_PLACEHOLDER: 'Revelar chave privada da conta delegada', IMPORTANCE_TRANSFER_DELEGATED_KEYS: 'Chave da conta delegada', IMPORTANCE_TRANSFER_HARVESTING_STATUS: 'Estado da colheita', IMPORTANCE_TRANSFER_START_HARVESTING: 'Iniciar colheita delegada', IMPORTANCE_TRANSFER_STOP_HARVESTING: 'Parar colheita delegada', IMPORTANCE_TRANSFER_ACTIVATE_DEACTIVATE_REMOTE: 'Ativar / Desativar a conta delegada', IMPORTANCE_TRANSFER_SHOW_DELEGATED_KEYS: 'Exibir chaves das contas delegadas', // CREATE MOSAIC MODULE MOSAIC_DEFINITION_TITLE: 'Criar um mosaico', MOSAIC_DEFINITION_NAME: 'Transação de definição de mosaico', MOSAIC_DEFINITION_MULTISIG_NAME: 'Transação de definição de mosaico multiassinada', MOSAIC_DEFINITION_QUANTITY: 'Quantidade', MOSAIC_DEFINITION_DIV: 'Divisibilidade', MOSAIC_DEFINITION_TOTAL_SUPPLY: 'Suprimento total', MOSAIC_DEFINITION_FINAL_NAME: 'Nome completo', MOSAIC_DEFINITION_DESCRPITION: 'Descrição', MOSAIC_DEFINITION_INITIAL_SUPPLY: 'Suprimento inicial', MOSAIC_DEFINITION_MUTABLE_SUPPLY: 'Suprimento mutável', MOSAIC_DEFINITION_TRANSFERABLE: 'Transferível', MOSAIC_DEFINITION_PROPERTIES: 'Propriedades', MOSAIC_DEFINITION_MOSAIC_PROPERTIES: 'Propriedades do mosaico', MOSAIC_DEFINITION_REQUIRES_LEVY: 'Requer imposto', MOSAIC_DEFINITION_LEVY_LIMITATION: 'Limitação da interface: por enquanto, apenas mosaicos já criados podem ser usados como imposto.', MOSAIC_DEFINITION_LEVY_SELECT_MOSAIC: 'Selecione um mosaico para imposto', MOSAIC_DEFINITION_LEVY_ADDRESS: 'Endereço da conta destino de impostos', MOSAIC_DEFINITION_LEVY_FEE_TYPE: 'Tipo de taxa', MOSAIC_DEFINITION_LEVY_FEE_TYPE_1: 'Absoluta', MOSAIC_DEFINITION_LEVY_FEE_TYPE_2: 'Percentual', MOSAIC_DEFINITION_LEVY_FEE_TYPE_1_NOTE: 'Selecionando absoluta, resultará em um imposto constante de:', MOSAIC_DEFINITION_LEVY_FEE_TYPE_2_NOTE: 'Selecionando percentual, resultará em um imposto linear de:', MOSAIC_DEFINITION_LEVY_FEE_TYPE_2_NOTE_2: 'Enviando', MOSAIC_DEFINITION_LEVY_FEE_TYPE_2_NOTE_3: 'resultará no imposto de', MOSAIC_DEFINITION_PARENT: 'Registro de nome pai', MOSAIC_DEFINITION_INFORMATION_TITLE: 'Criando um Mosaico', MOSAIC_DEFINITION_INFORMATION: 'Deseja mais informações sobre mosaicos?', MOSAIC_DEFINITION_INFORMATION_1: 'O comprimento máximo para o nome de um mosaico é de 32 caracteres. Os caracteres permitidos são:', MOSAIC_DEFINITION_INFORMATION_2: 'O primeiro caractere deve ser uma letra do alfabeto ou um número.', MOSAIC_DEFINITION_INFORMATION_3: 'A descrição não deve exceder o comprimento de 512 caracteres. Não há limitações para os caracteres utilizados na descrição.', MOSAIC_DEFINITION_INFORMATION_4: 'O comportamento de um mosaico pode ser personalizado por um conjunto de propriedades:', MOSAIC_DEFINITION_INFORMATION_5: 'O suprimento é dado em unidades inteiras do mosaico, não nas suas menores sub-unidades em casas decimais. O suprimento inicial deve estar entre os limites de 0 (zero) e 9,000,000,000 (9 bilhões).', MOSAIC_DEFINITION_INFORMATION_6: 'A divisibilidade determina em até quantas casas decimais o mosaico pode ser subdividido. Assim, a divisibilidade de 3 significa que um mosaico pode ser dividido em sua menor parte composta por 0.001 mosaicos (mili mosaicos são a menor subunidade possível). A divisibilidade deve estar entre os limites de 0 (zero) e 6 (seis).', MOSAIC_DEFINITION_INFORMATION_7: 'Se habilitado, permite que o suprimento do mosaico seja alterado futuramente, caso o contrário o suprimento será imutável.', MOSAIC_DEFINITION_INFORMATION_8: 'Permite transferências do mosaico entre outras contas que não sejam a do seu criador. Se a propriedade \'transferível\' não está habilitada, apenas transferências que tenham o endereço do criador como remetente ou destinatário podem transferir mosaicos deste tipo. Se habilitado os mosaicos poderão ser transferidos livremente entre quaisquer contas.', MOSAIC_DEFINITION_INFORMATION_9: 'O criador pode exigir que uma taxa especial de imposto seja coletada do remetente e seja enviada para uma conta de sua escolha (assim o criador pode especificar sua própria conta como o recebedor da taxa). Os dados para configuração da taxa de imposto são os seguintes:', MOSAIC_DEFINITION_INFORMATION_10: 'O mosaico no qual a taxa deve ser paga. Qualquer mosaico já existente pode ser especificado.', MOSAIC_DEFINITION_INFORMATION_11: 'O endereço da conta de recebimento do imposto. Pode ser qualquer conta.', MOSAIC_DEFINITION_INFORMATION_12: 'A quantidade da taxa. A interpretação do cálculo depende do valor preenchido no campo \'tipo de taxa\', conforme acima.', MOSAIC_DEFINITION_INFORMATION_13: 'Há dois tipos de taxas possíveis, taxa absoluta e taxa percentual.', MOSAIC_DEFINITION_INFORMATION_14: 'A taxa é especificada com quantidade absoluta e assim não depende da quantidade que será transferida.', MOSAIC_DEFINITION_INFORMATION_15: 'A taxa é especificada como múltiplo percentual da quantidade que será transferida. A taxa é assim linearmente incrementada de acordo com a quantidade de mosaico transferida.', MOSAIC_DEFINITION_INFORMATION_16: 'Enviar mosaicos na cadeia de blocos da NEM requer uma taxa. A taxa exata é calculada dependendo do número total e da quantidade que está sendo enviada durante a transação. <b>Mosaicos para pequenos negócios</b> recebem um desconto de 0.05 XEM por mosaico por transferência. Estes são mosaicos com uma quantidade menor que 10,000 e uma divisibilidade de 0 (zero).', MOSAIC_DEFINITION_INFORMATION_17: 'Se você é dono de 100% do suprimento, você pode alterar todas as propriedades do mosaico, enviando uma nova transação de definição de mosaico com o mesmo nome "registrodenome:mosaico".', // EDIT MOSAIC MODULE MOSAIC_SUPPLY_CHANGE_TITLE: 'Alterar suprimento de mosaico', MOSAIC_SUPPLY_CHANGE_NAME: 'Transação de alteração de suprimento de mosaico', MOSAIC_SUPPLY_CHANGE_MULTISIG_NAME: 'Transação de alteração de suprimento de mosaico multiassinada', MOSAIC_SUPPLY_CHANGE_SELECT: 'Selecione um mosaico', MOSAIC_SUPPLY_CHANGE_TYPE: 'Alterar o tipo', MOSAIC_SUPPLY_CHANGE_TYPE_1: 'Criar', MOSAIC_SUPPLY_CHANGE_TYPE_2: 'Apagar', MOSAIC_SUPPLY_CHANGE_SUPPLY: 'Suprimento', MOSAIC_SUPPLY_CHANGE_CURRENT_SUPPLY: 'Suprimento atual', MOSAIC_SUPPLY_CHANGE_AMOUNT: 'Alterar quantidade', MOSAIC_SUPPLY_CHANGE_RES_SUPPLY: 'Suprimento resultante', // NAMESPACE MODULE NAMESPACE_PROVISION_TITLE: 'Criar registro de nome e subnome', NAMESPACE_PROVISION_NAME: 'Transação de registro de nome', NAMESPACE_PROVISION_MULTISIG_NAME: 'Transação de registro de nome multiassinada', NAMESPACE_PROVISION_PARENT: 'Registro de nome pai', NAMESPACE_PROVISION_NEW_ROOT: 'Novo registro de nome raiz', NAMESPACE_PROVISION_NS: 'Registro de nome', NAMESPACE_PROVISION_NS_NAME: 'Nome do registro', NAMESPACE_PROVISION_RESTRICTIONS: 'Restrições para registro de nome', NAMESPACE_PROVISION_INFORMATION_1: 'Registro de nomes possuem certas restrições em relação aos caracteres permitidos em sua composição, assim como no tamanho de suas partes. Um registro de nome raiz pode ter um comprimento de até 16 caracteres enquanto subnomes podem ter um comprimento de até 64 caracteres. Os caracteres válidos são:', NAMESPACE_PROVISION_INFORMATION_2: 'Uma parte só pode iniciar com uma letra do alfabeto ou um número, assim \'alice\' é uma parte permitida par um registro de nome raiz, mas \'_alice\' não é. Algumas palavras são reservadas e assim não são permitidas como registro de nome. Entre as partes de registro de nome desabilitadas estão:', NAMESPACE_PROVISION_INFORMATION_3: 'Esta lista não está finalizada e pode ser estendida no futuro. Assim \'user.alice\' ou \'alice.user\' não são permitidos no sistema de registro de nomes da NEM. O registro de nome pode ter até 3 partes, assim \'qm.metals.silver\' é válido enquanto \'qm.metals.silver.coin\' não é.', // RENEW NAMESPACE MODULE RENEW_NS_TITLE: 'Renovar registros de nome', RENEW_NS_NONE: 'Não há registros de nome para renovar', RENEW_NS_INFORMATION_TITLE: 'Renovação de Registros de Nomes', RENEW_NS_INFORMATION_TITLE_1: 'Taxas', RENEW_NS_INFORMATION_TITLE_2: 'Registros de Nome Raiz', RENEW_NS_INFORMATION_TITLE_3: 'Período de Renovação', RENEW_NS_INFORMATION_1: 'A renovação de um registro de nome tem o mesmo custo do registro de um novo nome, 100 XEM.', RENEW_NS_INFORMATION_2: 'Apenas registros de nome raiz precisam ser renovados. Todos os registros de subnomes serão renovados automaticamente na renovação do registro de nome raiz.', RENEW_NS_INFORMATION_3: 'Contratos de registro de nome são contratos de aluguel registrados na cadeia de blocos válidos por 1 ano. O contrato deve ser renovado um mês antes ou após a sua data de vencimento.', RENEW_NS_INFORMATION_4: 'Se não for renovado a tempo, todos os registros de subnome e mosaicos criados sob eles estarão perdidos.', RENEW_NS_ALERT_PART_1: '<b>Alerta!</b> O registro de nome:', RENEW_NS_ALERT_PART_2: 'vencerá em menos de um mês! ', RENEW_NS_ALERT_PART_3: 'Consulte a <b>página de renovação</b> para mais informações.', // ACCOUNT MODULE ACCOUNT_TITLE: 'Conta', ACCOUNT_ACCOUNT_INFORMATION: 'Informações de conta', ACCOUNT_IMPORTANCE_SCORE: 'Pontuação de importância', ACCOUNT_VESTED_BALANCE: 'Saldo coberto (vested)', ACCOUNT_HARVESTING: 'Colheita', ACCOUNT_REMOTE_STATUS: 'Estado Remoto', ACCOUNT_DELEGATED_PUBLIC: 'Chave pública delegada', ACCOUNT_HARVESTED_BLOCKS: 'Blocos coletados', ACCOUNT_START_STOP_HARVESTING: 'Iniciar / Parar colheita delegada', ACCOUNT_HARVESTING_NOTE: 'O nodo utilizado para colheita nesta conta está armazenado no <b>armazenamento local do seu navegador</b>. Se o armazenamento local de seu navegador for excluído o aplicativo não saberá qual nodo estava sendo utilizado, e então o <b>estado da colheita</b> será exibido como <b>inativo</b>. Neste caso, selecione o nodo que você estava utilizando, e isso irá restaurar o estado de colheita automaticamente. Se o estado não for restaurado, verifique se selecionou o nodo correto; caso contrário, significa que o nodo foi reiniciado e sua conta não está mais fazendo colheita.', ACCOUNT_HARVESTING_NODE_SELECT: 'Selecione um nodo para delegar a colheita', ACCOUNT_HARVESTING_START: 'Iniciar colheita delegada', ACCOUNT_HARVESTING_STOP: 'Parar colheita delegada', ACCOUNT_HARVESTING_NO_SLOTS: 'Não há espaços livres no nodo selecionado, por favor, escolha outro', ACCOUNT_HARVESTING_BELOW_THRESHOLD: 'Você precisa de 10,000 XEM cobertos (vested) para iniciar a colheita delegada', ACCOUNT_ACCOUNT_SELECT: 'Selecione outra conta', ACCOUNT_ACCOUNT_SELECT_LABEL: 'Selecionar Conta', ACCOUNT_WALLET_KEYS: 'Carteira & chaves', ACCOUNT_ADD_NEW_ACCOUNT: 'Adicionar nova conta', ACCOUNT_ADD_NEW_ACCOUNT_BTN: 'Adicionar nova conta na carteira', ACCOUNT_PRIVATE_KEY_NOTE: 'Sua chave privada detem o poder máximo sobre toda a sua conta. É uma prioridade garantir que ela está armazenada de forma segura, em algum lugar <b><u>offline</u></b>: encriptado com senha em um arquivo .wlt, escrito em um pedaço de papel, e em uma imagem, ou baixe o código QR em <b><u>Exportar carteira QR</u></b>.', ACCOUNT_PRIVATE_KEY_SHOW: 'Exibir chave privada', ACCOUNT_EXPORT_MOBILE: 'Exportar para dispositivos móveis (mobile)', ACCOUNT_INFO_QR_BTN: 'Compartilhar informações da conta QR', ACCOUNT_WALLET_QR_BTN: 'Carteira QR', ACCOUNT_WALLET_QR_BTN_2: 'Exportar carteira QR (Android e iOS)', ACCOUNT_BACKUP_WALLET: 'Backup carteira', ACCOUNT_BACKUP_WALLET_NOTE: 'É <b><u>muito importante</u></b> que você faça backups de suas carteiras para logar com elas ou suas XEM serão perdidas.', ACCOUNT_BACKUP_WALLET_DOWNLOAD: 'Baixar carteira', ACCOUNT_INFO_QR_TITLE: 'Informações da Conta QR', ACCOUNT_WALLET_QR_NOTE: 'Este QR só funciona no aplicativo NEMpay que será lançado', ACCOUNT_WALLET_QR_ANDROID_IOS_TITLE: 'Carteira QR para aplicativos Android & iOS', ACCOUNT_ADD_NEW_ACCOUNT_WARNING: 'Todas as contas são derivadas de sua chave privada primária e de sua senha, usando BIP32, então tanto sua chave primária como sua senha são necessárias para recuperar/recriar todas as suas contas secundárias. <br> Portanto é <b>altamente recomendável</b> que faça um backup de sua carteira, depois de adicionar novas contas, para não repetir a operação novamente se o armazenamento local for apagado.', ACCOUNT_CUSTOM_NODE: 'Usar um nodo personalizado', ACCOUNT_NODE_FROM_LIST: 'Usar um nodo da lista', ACCOUNT_DELEGATED_PRIVATE_KEY: 'Chave privada delegada', ACCOUNT_NO_PUBLIC_KEY: 'Você deve fazer uma transação para gerar uma chave pública automaticamente', ACCOUNT_SHOW_ON_TREZOR_BTN: 'Exibir na TREZOR', // PORTAL MODULE PORTAL_TITLE: 'Serviços', PORTAL_MULTISIG_TITLE: 'Contas Multiassinatura ou Multiusuários', PORTAL_MULTISIG_TEXT: 'Contas multiassinadas são contratos editáveis registrados na cadeia de blocos, a forma mais poderosa de tornar seus fundos seguros, permitir contas conjuntas, e são a fundação das DAOs.', PORTAL_MULTISIG_BTN_1: 'Converter uma conta para multiassinatura', PORTAL_MULTISIG_BTN_2: 'Editar um contrato multiassinado já existente', PORTAL_MULTISIG_BTN_3: 'Assinar transações de multiassinatura', PORTAL_HARVESTING_TITLE: 'Colheita Delegada', PORTAL_HARVESTING_TEXT: 'Colheita Delegada é a funcionalidade que permite "minerar" mesmo quando a sua conta não estiver aberta no seu navegador.', PORTAL_EXCHANGE_TITLE: 'Corretoras Instantâneas', PORTAL_EXCHANGE_TEXT: 'Use os widgets da Changelly ou ShapeShift para comprar XEM nos melhores preços!', PORTAL_EXCHANGE_BTN: 'Comprar XEM', PORTAL_NS_TITLE: 'Registro de nomes & Subdomínios', PORTAL_NS_TEXT: 'Registros de nomes são nomes de domínios. Cada registro de nome é único e autentica mosaicos (ativos) emitidos neles ou em seus subdomínios.', PORTAL_NS_BTN: 'Criar registro de nome', PORTAL_MOSAIC_TITLE: 'Mosaicos', PORTAL_MOSAIC_TEXT: 'Mosaicos NEM são ativos que possuem propriedades especiais e outras funcionalidades. Para ser capaz de criar um mosaico, uma conta deve alugar pelo menos um registro de nome raiz.', PORTAL_MOSAIC_BTN_1: 'Criar mosaico', PORTAL_MOSAIC_BTN_2: 'Editar mosaico', PORTAL_APOSTILLE_TITLE: 'Apostille', PORTAL_APOSTILLE_TEXT: 'Use o NEM Apostille para criar um serviço de notarização baseado na cadeia de blocos para registrar, acompanhar e auditar autenticidade de arquivos.', PORTAL_APOSTILLE_BTN_1: 'Criar', PORTAL_APOSTILLE_BTN_2: 'Auditar', PORTAL_ADDRESS_BOOK_TEXT: 'Associe nomes de etiqueta aos endereços para gerenciar mais facilmente os seus contatos.', PORTAL_ADDRESS_BOOK_BTN: 'Gerenciar caderno de contatos', PORTAL_INVOICE_TEXT: 'Criar uma fatura para compartilhar através de QR code', // ADDRESS BOOK MODULE ADDRESS_BOOK_TITLE: 'Caderno de contatos', ADDRESS_BOOK_NAVIGATION: 'Navegação', ADDRESS_BOOK_NEW: 'Novo contato', ADDRESS_BOOK_EDIT: 'Editar contato', ADDRESS_BOOK_REMOVE: 'Remover contato', ADDRESS_BOOK_NEW_BTN: 'Adicionar', ADDRESS_BOOK_EDIT_BTN: 'Salvar', ADDRESS_BOOK_REMOVE_BTN: 'Remover', ADDRESS_BOOK_EXPORT_BTN: 'Exportar caderno de contatos', ADDRESS_BOOK_IMPORT_BTN: 'Importar caderno de contatos', ADDRESS_BOOK_CONTACT_LABEL: 'Etiqueta', ADDRESS_BOOK_ACCOUNT_ADDRESS: 'Endereço da conta', ADDRESS_BOOK_ACTIONS: 'Ações', ADDRESS_BOOK_CONFIRM_DELETE: 'Confirma apagar todos os endereços do caderno de contatos', // EXPLORER MODULE NAV EXPLORER_NAV_HOME: 'Home', EXPLORER_NAV_NSM: 'Registro de nomes & Mosaicos', EXPLORER_NAV_APOSTILLES: 'Apostilles', // EXPLORER HOME MODULE EXPLORER_HOME_TITLE: 'Explorador - Home', EXPLORER_HOME_NS: 'Seus Registros de Nomes', EXPLORER_HOME_MOSAICS: 'Seus Mosaicos', EXPLORER_HOME_NS_MULTISIG: 'Registros de Nomes possuídos em multiassinatura', EXPLORER_HOME_MOSAICS_LEVY: 'Mosaico de Imposto', // EXPLORER NAMESPACES AND MOSAICS EXPLORER_NS_MOS_TITLE: 'Explorador - Registro de nomes e Mosaicos', EXPLORER_NS_MOS_SELECT_MOS: 'Detalhes do Mosaico selecionado', EXPLORER_NS_MOS_SEARCH: 'Buscar registro de nomes', // EXPLORER APOSTILLES MODULE EXPLORER_APOSTILLES_TITLE: 'Explorador - Apostilles', EXPLORER_APOSTILLES_YOURS: 'Seus apostilles', EXPLORER_APOSTILLES_PUBLIC: 'Coletor público', EXPLORER_APOSTILLES_NO_NTY: 'Nenhum arquivo de notarização carregado, por favor, clique aqui para importar um.', // ACCOUNT EXPLORER ACCOUNTS_EXPLORER_TITLE: 'Explorador - Contas', ACCOUNTS_EXPLORER_SEARCH: 'Buscar', // APOSTILLE HISTORY MODULE APOSTILLE_HISTORY_TITLE: 'Histórico Apostille', APOSTILLE_HISTORY_BTN_TRANSFER: 'Transferência / Divisão de posse', APOSTILLE_HISTORY_BACKUP: 'Backup dos dados de notarização', APOSTILLE_HISTORY_PURGE: 'Excluir dados de notarização', // CREATE APOSTILLE MODULE APOSTILLE_CREATE_TITLE: 'Criar apostilles', APOSTILLE_CREATE_HELP: 'Deseja mais informações sobre Apostille?', APOSTILLE_TRANSACTION_NAME: 'Transação Apostille', APOSTILLE_TRANSACTION_MULTISIG_NAME: 'Transação Apostille Multiassinada', APOSTILLE_KEEP_PRIVATE: 'Privado, transferível e editável', APOSTILLE_USE_DEDICATED: 'Usar conta dedicada', APOSTILLE_FILES_TO_NOTARIZE: 'Arquivos para notarizar', APOSTILLE_REJECTED: 'Rejeitado', APOSTILLE_FILE_HASH: 'Hash do arquivo', APOSTILLE_PRIVATE: 'Privado', APOSTILLE_FILENAME: 'Nome do arquivo', APOSTILLE_NAME_TOO_LONG: 'Nome do arquivo é muito longo, 32 caracteres é o máximo permitido.', APOSTILLE_MAX_NUMBER: 'O máximo de apostilles por lote é 25', APOSTILLE_INFORMATION_TITLE: 'Criando um Apostille', APOSTILLE_INFORMATION_1: 'Cada arquivo enviado é processado automaticamente com as opções configuradas no painel à esquerda. Você pode adicionar novos arquivos, mudar parâmetros e adicionar mais arquivos com diferentes opções. Também funcionará se você alternar para multiassinatura e adicionar mais arquivos.', APOSTILLE_INFORMATION_2: '"As opções <b>Privado, transferível e atualizável</b>" significa que os hashs de seus arquivos serão assinados com a sua chave privada e serão enviados para uma conta dedicada de hierarquia determinística (HD). Desta forma, não será possível que ninguém além de você, conhecer qual conteúdo foi registrado a não ser que você compartilhe o seu conteúdo.', APOSTILLE_INFORMATION_3: 'A conta dedicada HD pode ser colocada sob um contrato multiassinatura de forma que poderá ser transferido para outros utilizando-se de contratos multiassinaturas com combinações de 1-de-1 ou m-de-n. Também poderá haver informações adicionais enviadas através de mensagens com atualizações ou acréscimos ao documento original ou ao produto representado.', APOSTILLE_INFORMATION_4: 'Quando duas ou mais partes querem ambas aprovar um registro na cadeia de blocos, ex: vinculação de contratos, a conta fazendo a notarização na cadeia de blocos pode ser colocada em um contrato multiassinatura de n-de-n.', APOSTILLE_INFORMATION_5: 'Para contas em um contrato de multiassinatura que selecionou "<b>Privado, transferível e atualizável</b>", a chave privada inicial do cossignatário será utilizada para assinar o hash e criar uma conta HD dedicada, e não a conta que foi multiassinada.', APOSTILLE_INFORMATION_6: 'A conta HD é uma conta dedicada gerada a partir de um hash do nome do arquivo que é assinado pela sua chave privada. Este hash resultante desse processo é então usado para formar uma segunda chave privada. Esta é a chave privada do arquivo com data e hora; uma inovação na tecnologia de cadeia de blocos encontrada apenas na Apostille.', APOSTILLE_INFORMATION_7: 'A conta HD dedicada permite armazenar o hash assinado do arquivo original e suas atualizações em uma conta dedicada. Se <b>"Público"</b> estiver selecionado, a transação vai para o endereço da conta coletora pública (padrão).', APOSTILLE_INFORMATION_8: 'Depois que as transações são enviadas, o download de um arquivo é acionado. Ele contém seus arquivos assinados, seu certificado Apostille para esse arquivo e o novo arquivo .nty, ou atualizado, para acompanhar todos os arquivos que você registrou na cadeia NEM.', APOSTILLE_NO_NTY: 'Nenhum arquivo de notarização adicionado, por favor, clique aqui para importar um, ou um novo será criado automaticamente.', APOSTILLE_IMPORT_FILES: 'Importar arquivos', APOSTILLE_CREATE_TEXT: 'Criar um documento de texto', APOSTILLE_ENTER_TEXT: 'Entre o texto para notarizar...', APOSTILLE_DOCUMENT_TITLE: 'Título do documento', APOSTILLE_DROPBOX_MESSAGE: 'Por favor, digite sua senha e as tags desejadas antes de selecionar arquivos', APOSTILLE_DROPBOX_MESSAGE_2: 'Por favor, digite a sua senha antes de selecionar arquivos', // AUDIT APOSTILLE MODULE APOSTILLE_AUDIT_TITLE: 'Auditar apostilles', APOSTILLE_AUDIT_CHOOSE_NODE: 'Selecionar um nodo', APOSTILLE_AUDIT_CHOOSE_NODE_NOTE: 'Apenas alguns nodos são capazes de buscar em todo o histórico de transações (opção está desabilitada por padrão no NIS).', APOSTILLE_AUDIT_WRONG_FORMAT: 'Este arquivo não está no formato Apostille!', APOSTILLE_AUDIT_FAIL_NO_PUBLIC_KEY: 'A verificação falhou, o proprietário não possui chave pública!', APOSTILLE_AUDIT_SUCCESS: 'Arquivo auditado com sucesso!', APOSTILLE_AUDIT_FAIL: 'Verificação falhou!', APOSTILLE_AUDIT_WAITING: 'A transferência do Apostille deve estar aguardando pela confirmação!', APOSTILLE_AUDIT_NOT_FOUND: 'Transação não encontrada, verifique se não está aguardando pela confirmação, pois nesse caso o Apostille ainda é inválido', APOSTILLE_AUDIT_ERROR_UNCONFIRMED: 'Ocorreu um erro ao buscar dados não confirmados, mas a transação não foi encontrada', APOSTILLE_AUDIT_ERROR_SIGNER: 'Ocorreu um erro enquanto buscava pelos dados do signatário', APOSTILLE_AUDIT_ERROR_SIGNATURE: 'A verificação falhou, um erro ocorreu na verificação da assinatura!', APOSTILLE_AUDIT_INFORMATION_1: 'Arquivos que podem ser auditados devem estar no <b>formato apostille</b>', APOSTILLE_AUDIT_INFORMATION_2: 'Você pode reconhecê-los pelo nome do arquivo:', //APOSTILLE_AUDIT_NON_SIGNED: 'Exemplo não assinado:', //APOSTILLE_AUDIT_SIGNED: 'Exemplo assinado:', APOSTILLE_AUDIT_FILES: 'Auditar arquivos', APOSTILLE_AUDIT_FORMAT_EXAMPLE: 'Exemplo do formato Apostille', APOSTILLE_AUDIT_REMOVE_RECORDS: 'Remover registros localmente', // APOSTILLE MESSAGE MODULE APOSTILLE_MESSAGE_TITLE: 'Enviar mensagem para a conta de notarização', APOSTILLE_MESSAGE_NS_BRAND: 'Usar meu registro de nome para mensagem de marca', APOSTILLE_MESSAGE_ADD_MOSAIC: 'Adicionar mosaico', APOSTILLE_NTY_ACCOUNT: 'Conta de Notarização', APOSTILLE_REQUEST_MESSAGE: 'Mensagem de requisição', APOSTILLE_CREATE_MESSAGE_REQUEST: 'Criar uma mensagem de requisição', // TRANSFER APOSTILLE OWNLERSHIP MODULE APOSTILLE_TRANSFER_TITLE: 'Transferir ou dividir propriedade de Apostille', // UPADTE APOSTILLE MODULE APOSTILLE_UPDATE_TITLE: 'Atualizar apostille', // ERROR ALERTS ALERT_MISSING_FORM_DATA: 'Por favor, complete o formulário!', ALERT_ERROR_WALLET_DOWNLOAD: 'Não foi possível baixar a carteira pois ela não existe!', ALERT_PASSWORDS_NOT_MATCHING: 'As senhas fornecidas são diferentes!', ALERT_INVALID_KEY_FOR_ADDR: 'A chave privada não corresponde ao endereço fornecido!', ALERT_NO_WALLET_LOADED: 'Você não pode acessar o painel sem uma carteira', ALERT_WALLET_NAME_EXISTS: 'Uma carteira com o mesmo nome já existe carregada!', ALERT_INVALID_WALLET_FILE: 'Você está tentando carregar um arquivo que não é uma carteira!', //ALERT_NO_NODE_SET: 'Por favor entre com um nodo!', ALERT_INVALID_CUSTOM_NODE: 'Seu nodo personalizado é inválido!', ALERT_INVALID_WEBSOCKET_PORT: 'A porta websocket do nodo customizado é inválida!', ALERT_MIJIN_DISABLED: 'A rede Mijin está desabilitada, por favor, escolha outra rede!', ALERT_GET_NS_BY_ID_ERROR: 'Erro ao buscar informações do registro de nome, pela razão: ', ALERT_GET_ACCOUNT_DATA_ERROR: 'Erro ao buscar dados da conta, pela razão: ', ALERT_ERROR_OCCURRED: 'Um erro ocorreu! ', ALERT_INVALID_ADDR_FOR_NETWORK: ' não corresponde a rede ', ALERT_INVALID_PASSWORD: 'Senha fornecida não é válida!', ALERT_COSIG_ALREADY_IN_LIST: 'Cossignatário já está presente na lista de modificações!', ALERT_COSIGNATORY_HAS_NO_PUBLIC: 'Cossignatário deve ter ao menos uma transação para possuir uma chave pública!', ALERT_MULTISIG_HAS_NO_PUBLIC: 'Contas multiassinadas devem possuir ao menos uma transação para possuir uma chave pública!', ALERT_COSIG_CANNOT_BE_MULTISIG: 'A conta selecionada para conversão é cossignatário em outra conta multiassinada. Portanto não pode ser convertida.', ALERT_NO_NS_OWNED: 'A conta não possui nenhum registro de nome, por favor crie um ou mude de conta.', ALERT_UNLOCKED_INFO_ERROR: 'Um erro ocorreu ao buscar pelas informações de destravamento', ALERT_LOCK_ERROR: 'Erro ao travar conta, pela razão: ', ALERT_UNLOCK_ERROR: 'Erro ao destravar conta, pela razão: ', ALERT_SUPERNODES_ERROR: 'Um erro ocorreu ao buscar dados do supernodo!', ALERT_INVALID_NTY_FILE: 'Arquivo fornecido não é um arquivo de notarização!', ALERT_CREATE_WALLET_FAILED: 'Falha ao criar a carteira, pela razão: ', ALERT_DERIVATION_FROM_SEED_FAILED: 'Falhou ao derivar a conta da semente (seed), pela razão: ', ALERT_BIP32_GENERATION_FAILED: 'Falha ao gerar dados BIP32, pela razão: ', ALERT_NO_WALLET_DATA: 'Erro, dados da carteira vazios!', ALERT_CANNOT_LOGIN_WITHOU_WALLET: 'Erro, não é possível logar sem uma carteira!', ALERT_NO_WALLET_TO_SET: 'Erro, não é possível não escolher uma carteira!', ALERT_INVALID_WALLET_INDEX: 'Erro, índice da conta selecionada está fora dos limites!', ALERT_NO_CURRENT_WALLET: 'Erro, não é possível configurar uma conta de carteira se não há uma carteira atual!', ALERT_ALREADY_MULTISIG: 'Conta selecionada já é uma conta multiassinada!', ALERT_INVALID_MODIFICATION_ARRAY: 'Uma conta multiassinada não pode ser cossignatária de si mesmo, por favor verifique a sua lista de modificações!', ALERT_GET_MARKET_INFO_ERROR: 'Um erro ocorreu ao tentar buscar informações de mercado!', ALERT_MULTISIG_CANNOT_BE_COSIG: 'Uma conta multiassinada não pode ser configurada como cossignatária!', ALERT_PURGE_CANCELLED: 'Remoção cancelada!', ALERT_MAINNET_DISABLED: 'Mainnet está desabilitada, por favor escolha outra rede!', ALERT_EMPTY_DECODED_MSG: 'Um erro ocorreu, não há mensagem decodificada!', ALERT_INVALID_NS_NAME: 'Nome do registro de nomes é inválido!', ALERT_INVALID_MOSAIC_NAME: 'Nome do mosaico é inválido!', ALERT_MOSAIC_DESCRIPTION: 'Descrição do mosaico é muito comprida!', ALERT_GET_INCOMING_TXES_ERROR: 'Um erro ocorreu enquanto buscava por transações de entrada, pela razão: ', ALERT_GET_MOSAICS_DEFINITIONS_ERROR: 'Erro ao buscar definição de mosaicos, pela razão: ', ALERT_GET_SUB_NS_ERROR: 'Erro ao busca definição de registro de nomes, pela razão: ', ALERT_GET_MOSAICS_ERROR: 'Erro ao buscar mosaicos, pela razão: ', ALERT_GET_TRANSACTIONS_ERROR: 'Erro ao buscar transações, pela razão: ', ALERT_INVALID_ADDRESS_BOOK_FILE: 'Este arquivo não está no formato .adb!', ALERT_INVALID_ADDRESS: 'Endereço fornecido não é válido!', ALERT_INVALID_AMOUNT: 'Quantidade não é valida!', ALERT_INVALID_PRIVATE_KEY: 'Chave privada fornecida não é válida!', ALERT_FILE_SIZE_ERROR: ' é muito grande, o tamanho máximo permitido é de 100 MB', ALERT_MESSAGE_DECODE_KEY_ERROR: 'Houve uma falha ao desencriptar a mensagem pois a conta não possui uma chave pública visível na rede', ALERT_FETCH_TIME_SYNC_ERROR: 'Um erro ocorreu ao buscar o horário da rede!', ALERT_MULTISIG_MIN_SIGNATURE: 'Uma conta multiassinada precisa de pelo menos um cossignatário', ALERT_BTC_MARKET_ERROR: 'Erro ao buscar o preço do Bitcoin', ALERT_COSIG_REMOVAL_LIMIT: 'Apenas um cossignatário pode ser removido de cada vez.', ALERT_MULTISIG_MIN_SIGNATURE_INVALID: 'Número inválido para mínimo de assinaturas.', ALERT_INSUFFICIENT_BALANCE: 'Saldo insuficiente para realizar a transação.', ALERT_VOTING_ERROR: 'Voto inválido', ALERT_BRAIN_PASSWORD_TOO_SHORT: 'A senha para a carteira mental deve conter no mínimo 40 caracteres!', ALERT_NODE_SEEMS_OFFLINE: 'O nodo aparenta estar desconectado, por favor selecione outro', ALERT_WEAK_PASSPHRASE: 'A pontuação da senha deve ser de no mínimo 3', ALERT_BRAIN_WALLET_UPGRADE: 'A senha para a sua carteira mental parece fraca! Todas as carteiras mentais deve utilizar uma senha de no mínimo 40 caracteres. Aconselhamos que você crie uma carteira simples, a partir da página de registro, e mova seus fundos para ela. Mais informações <a href="https://forum.nem.io/t/2791" target="_blank"><u>aqui</u></a>.', ALERT_RECIPIENT_PUBLIC_KEY: 'O destinatário não possui uma chave pública visível na rede.', ALERT_ENCRYPT_MULTISIG: 'Não é possível enviar mensagens encriptadas a partir de uma conta multiassinatura.', ALERT_EXCHANGE_NEEDS_MESSAGE: 'O destinatário é uma carteira de corretora e por isso requer uma mensagem para que o depósito seja corretamente creditado. Por favor, leia atentamente as instruções de depósito de sua corretora!', ALERT_ACCOUNT_ALREADY_IN_ADDRESS_BOOK: 'O endereço já existe no caderno de contatos!', ALERT_MAX_MOSAIC_SUPPLY: 'O suprimento máximo para o mosaico é de 9\'000\'000\'000', ALERT_GET_MOSAIC_SUPPLY_ERROR: 'Erro ao buscar o suprimento do mosaic, pela razão: ', ALERT_ENCRYPTED_MSG_OFFLINE: 'Mensagens encriptadas não estão habilitadas para transações offline.', // SUCCESS ALERTS ALERT_CREATE_WALLET_SUCCESS: 'Carteira criada e carregada com sucesso!', ALERT_SUCCESS_PURGE: 'Armazenamento local removido com sucesso!', ALERT_SUCCESS_LOGOUT: 'Logout feito com sucesso!', ALERT_LOAD_WALLET_SUCCESS: 'Carteira carregada com sucesso!', ALERT_TRANSACTION_SUCCESS: 'Transação enviada com sucesso!', ALERT_GENERATE_ACCOUNT_SUCCESS: 'Conta gerada com sucesso. Lembre-se de baixar o arquivo .wlt atualizado de sua carteira!', ALERT_UPGRADE_SUCCESS: 'Carteira atualizada com sucesso!', ALERT_SIGNATURE_SUCCESS: 'Transação assinada com sucesso!', ALERT_NTY_FILE_SUCCESS: 'Arquivo .nty carregado com sucesso!', ALERT_INCOMING_TX_FROM: 'Transação de entrada vinda de ', ALERT_ADDRESS_BOOK_FILE_SUCCESS: 'Caderno de contatos importado com sucesso!', ALERT_VOTING_SUCCESS: 'Voto enviado com sucesso!', ALERT_POLL_CREATION_SUCCESS: 'Votação criada com sucesso!', ALERT_COPY_SIGNED_TX_SUCCESS: 'Transação assinada copiada com sucesso!', // CONVERT ACCOUNT TO MULTISIG AGGREGATE_MODIFICATION_TITLE: 'Converter uma conta para multiassinatura', AGGREGATE_MODIFICATION_NAME: 'Transação de modificação agregada', AGGREGATE_MODIFICATION_MULTISIG_NAME: 'Transação de modificação agregada multiassinatura', AGGREGATE_ACCOUNT_SELECT_TITLE: 'Conta para Converter', AGGREGATE_ACCOUNT_SELECT: 'Selecione uma conta para converter', AGGREGATE_CUSTOM_ACCOUNT: 'Chave de Importação', AGGREGATE_ACCOUNT_TO_CONVERT_PRIVATE_TITLE: 'Chave privada do endereço', AGGREGATE_ACCOUNT_TO_CONVERT: 'Conta para converter o endereço', AGGREGATE_ACCOUNT_TO_CONVERT_PRIVATE: 'Conta para converter a chave privada', AGGREGATE_ADD_PLACEHOLDER: 'Conta do cosignatário ou @apelido para adicionar', AGGREGATE_ADD_BTN_TITLE: 'Adicionar signatário', AGGREGATE_MIN_SIGNATURES: 'Mínimo de assinaturas requeridos', AGGREGATE_MIN_SIGNATURES_PLACEHOLDER: 'Mínimo de assinaturas necessárias para validar uma transação', AGGREGATE_MODIFICATION_LIST: 'Lista de modificações', AGGREGATE_COSIG_LIST: 'Lista de Endereços de Cosignatários', AGGREGATE_MODIFICATION_EDIT_TITLE: 'Editar um contrato multiassinatura', AGGREGATE_MODIFICATION_EDIT_SELECT_TITLE: 'Conta para editar', AGGREGATE_MODIFICATION_EDIT_SELECT: 'Selecione uma conta para editar', AGGREGATE_ADD_REMOVE_TITLE: 'Adicionar/Remover signatário', AGGREGATE_ADD_REMOVE_PLACEHOLDER: 'Conta do cosignatário ou @apelido para adicionar', AGGREGATE_MODIFICATION_RELATIVE_CHANGE: 'Mudanças de assinaturas necessárias', AGGREGATE_MODIFICATION_RELATIVE_CHANGE_PLACEHOLDER: 'Número de assinaturas para adicionar (n) ou remover (-n) - Remoções automatizadas', AGGREGATE_SELECTED_ACCOUNT_INFO: 'Informações da conta selecionada', AGGREGATE_MIN_SIGNATURES: 'Mínimo de assinaturas', AGGREGATE_SELECT_WALLET_ACCOUNT: 'Usar conta da carteira', AGGREGATE_ADD_COSIG: 'Adicionar cosignatário', AGGREGATE_REMOVE_COSIG: 'Remover cosignatário', // SIGN MULTISIGNATURE TRANSACTIONS SIGN_MULTISIG_TRANSACTIONS_TITLE: 'Assinar transações multiassinatura', // LOGIN MODULE LOGIN_MEMBER_TITLE: 'Você já é um NEMber?', LOGIN_UPGRADE_TITLE: 'A carteira necessita de uma atualização', LOGIN_UPGRADE_MESSAGE: 'A carteira selecionada precisa de uma atualização. Esta ação irá gerar uma chave pública filha e a adicionará à sua conta primária.', LOGIN_UPGRADE_BUTTON: 'Atualizar Carteira', LOGIN_IMPORT_BUTTON: 'Importar Carteira', LOGIN_SELECT_WALLET_YOURS: 'Selecionar carteira', LOGIN_SELECT_WALLET: 'Selecione uma carteira de seu armazenamento local', LOGIN_LOGIN_BUTTON: 'Entrar', LOGIN_NOTE: 'Não possui carteiras? Importe uma ou <a href="#!/signup">crie uma carteira</a>.', // SIGNUP MODULE SIGNUP_TITLE: 'Novo na NEM?', SIGNUP_SELECT_WALLET_TYPE: 'Selecione um tipo de carteira para criar', SIGNUP_SELECT_WALLET_TYPE_STAND_BY: 'Posicione o cursor em um tipo de carteira para exibir suas informações.', SIGNUP_CREATE_WALLET_TITLE: 'Carteira Simples', SIGNUP_CREATE_WALLET_INFO: 'Carteiras simples contêm uma chave privada primária que é gerada aleatoriamente.', SIGNUP_PRIVATE_KEY_WALLET_TITLE: 'Carteira de chave privada', SIGNUP_PRIVATE_KEY_WALLET_INFO: 'Carteiras de chave privada contêm uma chave privada que você deseja importar.', SIGNUP_BRAIN_WALLET_TITLE: 'Carteira Mental', SIGNUP_BRAIN_WALLET_INFO: 'Carteiras mentais contêm uma chave privada que é gerada a partir de uma senha. Isto faz com que a recuperação da carteira só seja possível utilizando-se exatamente desta mesma senha.', SIGNUP_CREATE_WALLET_BUTTON: 'Criar carteira simples', SIGNUP_PRIVATE_KEY_WALLET_BUTTON: 'Criar carteira de chave privada', SIGNUP_BRAIN_WALLET_BUTTON: 'Criar carteira mental', SIGNUP_CREATE_WALLET_WARNING: 'Por favor, saiba mais sobre os <a href="https://www.w3.org/TR/2014/WD-WebCryptoAPI-20140325/#RandomSource-interface" rel="nofollow" target="_blank"><b>perigos</b></a> que as chaves geradas no lado do cliente podem conter; não nos responsabilizamos por quaisquer perdas que venham a ocorrer por problemas relacionados a entropia na geração das chaves. Mesmo que seja muito difícil de acontecer, é recomendado que você use uma chave privada gerada a partir de uma fonte com forte entropia.', SIGNUP_NETWORK_SELECT: 'Selecione uma rede', SIGNUP_NETWORK_MAINNET: 'Mainnet é a rede principal <b><u>real</u></b> da NEM. Endereços começam com \'N\'.', SIGNUP_NETWORK_TESTNET: 'Testnet é a rede para <b><u>testes</u></b>. Endereços começam com \'T\'.', SIGNUP_NETWORK_MIJIN: 'Mijin é a versão privada da NEM. Endereços começam com \'M\'.', SIGNUP_BRAIN_WALLET_WARNING: 'Por favor, saiba mais sobre os <a href="https://en.bitcoin.it/wiki/Brainwallet" rel="nofollow" target="_blank"><b>perigos</b></a> que carteiras mentais podem conter. Carteiras mentais usam apenas uma senha que passa por múltiplos hashes. Portanto é crucial que você selecione uma senha SEGURA com no mínimo 40 caracteres. <a href="https://xkcd.com/936/" rel="nofollow" target="_blank"><b>XKCD #936</b></a>', SIGNUP_PRIVATE_KEY_WALLET_WARNING: 'Carteiras de chave privada usam APENAS uma senha para encriptar a chave privada importada. Portanto é crucial selecionar uma senha SEGURA.', SIGNUP_CREATE_START_WARNING: 'Por favor, siga cada passo com muita atenção!', SIGNUP_CREATE_START_CONNECTION_WARNING: 'É recomendado desconectar-se da internet enquanto estiver criando a sua carteira e fazendo backup de seus dados.', SIGNUP_CREATE_READY_BTN: 'Pronto', SIGNUP_CREATE_ENTER_NAME: 'Digite o nome da carteira', SIGNUP_CREATE_ENTER_PASSWORD: 'Digite uma senha', SIGNUP_CREATE_ENTER_PASSPHRASE: 'Digite uma senha de passe', SIGNUP_CREATE_CONFIRM_PASSWORD: 'Confirme a senha digitada acima', SIGNUP_CREATE_CONFIRM_PASSPHRASE: 'Confirme a senha de passe digitada acima', SIGNUP_CREATE_ENTER_PRIVATE_KEY: 'Entre com a chave privada', SIGNUP_CREATE_ADDRESS_FROM_PK: 'Endereço correspondente à chave acima', SIGNUP_CREATE_WALLET_ADD_ENTROPY_INFO: 'Agora iremos gerar a sua chave privada primária. <b>Por favor, clique em iniciar e mova o seu cursor ao redor da tela para adicionar mais entropia.</b>', SIGNUP_COMMON_WALLET_WARNING_TITLE: 'Protocolo de segurança da conta', SIGNUP_COMMON_WALLET_WARNING_1: 'As carteiras são armazenadas <b><u>temporariamente</u></b> no armazenamento local de seu navegador! Navegadores podem ser configurados (ex: por add-ons) para limpar o armazenamento local de vez em quando. Isto pode levar a perda dos dados e não pode ser desfeito de forma fácil. Neste caso, sua carteira estará perdida, por isso é muito importante se assegurar que você possui backup de todas as informações necessárias para restaurar a sua carteira.', SIGNUP_COMMON_WALLET_WARNING_2: 'Por favor, clique abaixo para baixar sua carteira. Trata-se do arquivo <b><i>.wlt</i></b> utilizado como backup para importar de volta a sua carteira, caso o armazenamento local de seu navegador seja apagado.', SIGNUP_COMMON_WALLET_WARNING_3: 'Se você não baixou o backup do arquivo <b><i>.wlt</i></b>, clique no botão abaixo para revelar os dados originais da carteira e criar o arquivo manualmente:', SIGNUP_COMMON_WALLET_WARNING_4: 'Mesmo que você possua o arquivo de sua carteira é <b><u>obrigatório</u></b> fazer o backup da chave primária de sua conta, clique no botão abaixo para revelar:', SIGNUP_COMMON_WALLET_WARNING_5: 'É a sua responsabilidade garantir que possui um backup seguro de sua chave privada antes de enviar quaisquer fundos para a sua conta.', SIGNUP_COMMON_WALLET_WARNING_6: 'Cada carteira possui uma <b><u>chave privada primária</u></b> (a sua é exibida abaixo) que é usada para criar contas secundárias determinísticas (BIP32). Este recurso requer o uso da <b><u>mesma senha</u></b> ou gerará contas secundárias diferentes para a mesma chave privada primária. Quando fizer backup de seus dados não se esqueça de <b><u>anotar a sua senha</u></b>.', SIGNUP_COMMON_WALLET_WARNING_BTN_1: 'Exibir o arquivo original da carteira', SIGNUP_COMMON_WALLET_WARNING_BTN_1_INFO: 'Para fazer um arquivo de carteira, crie um arquivo texto vazio e coloque a chave acima, codificada em base64, dentro dele. Salve o arquivo como <b><i>nomeDeSuaCarteira.wlt</i></b>.', SIGNUP_COMMON_WALLET_WARNING_BTN_2: 'Exibir chave privada', SIGNUP_COMMON_WALLET_WARNING_BTN_2_INFO: 'Para fazer backup de sua chave privada, imprima-a ou salve-a em um arquivo texto. É altamente recomendável salvar sua chave privada em uma local seguro desconectado.', SIGNUP_COMMON_WALLET_WARNING_FOOTER: 'Ao clicar abaixo, você concorda que possui sua chave privada, senha e arquivo de carteira guardados em um backup seguro.', SIGNUP_COMMON_WALLET_WARNING_CONFIRM_1: 'Eu possuo o arquivo de minha carteira', SIGNUP_COMMON_WALLET_WARNING_CONFIRM_2: 'Eu possuo a chave privada e a senha', SIGNUP_COMMON_WALLET_WARNING_CONFIRM_3: 'Eu concordo', SIGNUP_COMMON_WALLET_WARNING_UNDERSTOOD: 'Entendido', SIGNUP_COMMON_WALLET_WARNING_DOWNLOAD: 'Baixar Carteira', SIGNUP_ESTIMATED_PASSPHRASE_STRENGTH: 'Força estimada da senha', SIGNUP_ESTIMATED_GUESS_TIMES: 'Tempo estimado de suposição', // FAQ MODULE FAQ_TITLE: 'Perguntas Mais Frequentes', FAQ_QUESTION_1: 'Como a Nano Wallet funciona?', FAQ_ANSWER_1: 'A Nano Wallet é feita com AngularJS e ES6. É um aplicativo que funciona totalmente do lado do cliente e nunca envia nenhuma informação sensível através dos cabos; tudo acontece no seu navegador local, desde criar as chaves privadas até a assinatura das transações.', FAQ_QUESTION_2: 'É livre para utilizar?', FAQ_ANSWER_2: 'Absolutamente todas as operações são do lado do cliente, apenas você controla as suas moedas, sem terceiros envolvidos, e sem taxas extras.', FAQ_QUESTION_3: 'Porque eu já possuo um mosaico?', FAQ_ANSWER_3: 'Por que a XEM é a moeda padrão da cadeia de blocos da NEM, todo usuário já possui ela registrada em sua própria carteira, mesmo quando o saldo é 0. Seu registro de nome é NEM e o nome do mosaico é XEM', FAQ_QUESTION_4: 'Mapa de desenvolvimento?', FAQ_ANSWER_4: 'O atual mapa de desenvolvimento inclui integração de todos os recursos da Nano Wallet v1.x.x e a conclusão de projetos financiados pela comunidade para trabalhar através desta carteira.', FAQ_QUESTION_5: 'Como eu consigo XEM grátis?', FAQ_ANSWER_5: 'As torneiras de XEM estão atualmente fora de funcionamento, mas você pode consultar o fórum da NEM para saber mais sobre o programa de recompensas da NEM.', FAQ_QUESTION_6: 'Onde encontrar mais informações sobre a NEM?', FAQ_ANSWER_6_FORUM: 'Fórum oficial', FAQ_ANSWER_6_WEBSITE: 'Website oficial', FAQ_ANSWER_6_BTT: 'Assunto oficial na BitcoinTalk', FAQ_QUESTION_7: 'Nada é exibido no painel.', FAQ_ANSWER_7: 'Por favor, verifique o círculo do nodo na barra de navegação do topo. <br> Círculo vermelho significa que a conexão com o nodo falhou. <br> Clique no "Nodo" e selecione outro da lista ou use um nodo customizado. <br> <a href="https://supernodes.nem.io" target="_blank">Supernodes.nem.io</a> possui uma lista de nodos que você pode utilizar.</a>', FAQ_QUESTION_8: 'Cosignatários não podem ver a transação para assinar.', FAQ_ANSWER_8: 'Neste caso vá para "Serviços", procure por "Contas Multiassinatura ou Multiusuários" e clique em "Assinar transações multiassinatura".', FAQ_QUESTION_9: 'Quais são as melhores práticas de segurança?', FAQ_ANSWER_9: 'É altamente recomendável que sempre armazene suas chaves privadas em papel. <br> Você pode imprimí-las e arquivá-las em algum lugar seguro. <br><br> No que diz respeito aos arquivos de carteira, você sempre deve manter várias cópias em diferentes locais a frio (desconectados), como cartões usb. <br> Senhas devem ser únicas e complexas, por esta razão, sempre escreva-a primeiro. <br><br> Quando você desejar verificar a sua carteira ou realizar operações:<br> - Conecte o seu cartão usb <br> - Importe sua carteira para a Nano<br> - Desconecte o seu cartão usb.<br><br> Uma cópia da sua carteira ficará armazenada no armazenamento local para o momento que você precisar.<br> Assim que terminar, saia e remova as carteiras do seu armazenamento local com o botão de exclusão ao lado direito da barra do rodapé da página.', FAQ_QUESTION_10: 'Onde encontrar informações sobre a minha conta (endereço, etc) ?', FAQ_ANSWER_10: 'Se você olhar na barra de navegação do topo, você verá o botão <b><i>"Conta"</b></i> entre <b><i>"Nodo"</b></i> e <b><i>"Idioma"</b></i>. Lá você poderá encontrar seu endereço, chave pública, saldo coberto e outros dados importantes.', FAQ_QUESTION_11: 'Depositei XEM em uma corretora mas nada foi creditado?', FAQ_ANSWER_11_1: 'Primeiro você deve verificar que o hash da sua transação está apontando para uma transação existente no <a target="_blank" href="http://chain.nem.ninja">explorador</a> (por favor, saiba que o explorador está sempre alguns blocos atrasado).', FAQ_ANSWER_11_2: 'A maioria das corretoras exige uma mensagem de identificação da transação para creditar o seu depósito. Assegure-se que você seguiu cuidadosamente as instruções da corretora e adicionou a mensagem não encriptada conforme solicitado.', FAQ_ANSWER_11_3: 'Mesmo que tenha adicionado a mensagem, pode acontecer que as corretoras não processem o seu depósito, por motivos de problemas do lado deles.', FAQ_ANSWER_11_4: 'Você deve contatar o suporte da corretora, e explicar a situação enviando-os o hash da sua transação.', FAQ_QUESTION_12: 'Como verificar se eu estou em um fork?', FAQ_ANSWER_12_1: 'Clique em <b><i>"Nodo"</b></i>, na barra de navegação do topo, para abrir o painel do nodo.', FAQ_ANSWER_12_2: 'Verifique o número do bloco e compare com o número exibido <a target="_blank" href="http://bigalice3.nem.ninja:7890/chain/height">aqui</a>.', FAQ_ANSWER_12_3: 'Se for diferente em mais de 5 blocos, então, provavelmente você está em um fork.', FAQ_ANSWER_12_4: 'Para consertar, apenas escolha outro nodo da lista no painel de nodos, isso restaurará sua conta para o seu estado atual na rede real.', // FORM RELATED FORM_PASSWORD_FIELD_PLACEHOLDER: 'Digite a senha de sua carteira', FORM_WALLET_NAME_FIELD_PLACEHOLDER: 'Nome da carteira', FORM_SIGNUP_PASSWORD_FIELD_PLACEHOLDER: 'Senha', FORM_PASSWORD: 'Senha', FORM_PASSWORD_CONFIRM: 'Confirmar Senha', FORM_PASSPHRASE_CONFIRM: 'Confirmar Senha de Passe', FORM_CONFIRM_PASSWORD_FIELD_PLACEHOLDER: 'Confirmar sua senha', FORM_PASSPHRASE_FIELD_PLACEHOLDER: 'Senha de Passe', FORM_CONFIRM_PASSPHRASE_FIELD_PLACEHOLDER: 'Confirmar sua senha de passe', FORM_ADDRESS_FIELD_PLACEHOLDER: 'Endereço da conta', FORM_PRIVATE_KEY_FIELD_PLACEHOLDER: 'Chave privada', FORM_SIDE_BTN_BALANCE: 'Saldo', FORM_SIDE_BTN_PAY_TO: 'Pagar para', FORM_SIDE_BTN_TX_FEE: 'Taxa de transação', FORM_SIDE_BTN_RENTAL_FEE: 'Taxa de aluguel', FORM_SIDE_BTN_LEVY_FEE: 'Taxa de imposto', FORM_RECIPIENT_PLACEHOLDER: 'Endereço do destinatário ou @apelido', FORM_INVOICE_RECIPIENT_PLACEHOLDER: 'Endereço do destinatário', FORM_SIDE_BTN_ALIAS_OF: 'Apelido de', FORM_MESSAGE_PLACEHOLDER: 'Mensagem', FORM_MOSAIC_NAME_PLACEHOLDER: 'Nome do Mosaico', FORM_ADDRESS_ALIAS_PLACEHOLDER: 'Endereço da conta ou @apelido', FORM_BTN_GET_ALIAS: 'Pegar endereço de registro de nome', FORM_BTN_OPEN_ADB: 'Abrir caderno de contatos', FORM_SELECT_NAMESPACE: 'Selecione um registro de nome', // VOTING MODULE PORTAL_VOTING_TITLE: 'Votação', PORTAL_VOTING_TEXT: 'Criar e votar em votações', PORTAL_VOTING_BTN1: 'Ver Votações', PORTAL_VOTING_BTN2: 'Criar Votação', FORM_TITLE_FIELD_PLACEHOLDER: 'Título', FORM_DESCRIPTION_FIELD_PLACEHOLDER: 'Escreva a sua descrição aqui', FORM_OPTION_FIELD_PLACEHOLDER: 'escreva uma opção', FORM_WHITELIST_FIELD_PLACEHOLDER: 'endereço da conta', FORM_SELECT_MULTISIG: 'Selecione uma conta multiassinatura', FORM_SELECT_CONTACT: 'Selecione um contato', // TREZOR RELATED TREZOR_TITLE: 'TREZOR', TREZOR_TEXT: 'A carteira em hardware TREZOR permite que você segure suas XEM, mosaicos contas multiassinatura', TREZOR_BUTTON: 'Entrar com TREZOR', // CREATE OFFLINE TRANSACTION MODULE OFFLINE_TX_TITLE: 'Preparar uma transação offline', OFFLINE_TX_NO_WALLET: 'Por favor, importe uma carteira do módulo de login para ver o formulário.', OFFLINE_TX_INFO_1: 'Assegure-se de que está desconectado da internet quando estiver importando sua carteira e criando a transação!', OFFLINE_TX_INFO_2: 'Somente transações simples podem ser criadas por que a conexão é necessária para buscar mosaicos e informações de multiassinatura dos nodos da NEM.', OFFLINE_TX_INFO_3: 'Depois de clicar no botão "criar" no painel da esquerda, você encontrará a transação assinada abaixo.', OFFLINE_TX_INFO_4: 'Uma transação assinada é imutável e será efetivada apenas se transmitida para a rede antes do prazo padrão de 24 horas.', OFFLINE_TX_SIGNED: 'Transação assinada', OFFLINE_TX_RELEASE: 'Abrir no módulo de transmissão', // RELEASE OFFLINE TRANSACTION MODULE RELEASE_OFFLINE_TX_TITLE: 'Transmitir uma transação para a rede', RELEASE_OFFLINE_TX_PARAMETERS: 'Parâmetros da transação', RELEASE_OFFLINE_TX_INFO_1: 'Para transmitir uma transação você deve estar conectado à internet.', RELEASE_OFFLINE_TX_INFO_2: 'Assegure-se de que selecionou a rede correta e um nodo em funcionamento ou a transação será rejeitada.', RELEASE_OFFLINE_TX_INFO_3: 'Não é possível enviar uma transação assinada duas vezes. Uma transação assinada sempre gerará o mesmo hash e duas transações não podem possuir o mesmo hash.', RELEASE_OFFLINE_TX_INFO_4: 'Você pode transmitir a transação assinada de qualquer computador de forma segura.', // INVOICE MODULE CREATE_INVOICE_TITLE: 'Criar uma fatura' }); } export default PortugueseBRProvider;
16,452
https://github.com/leanprover-community/mathlib/blob/master/src/linear_algebra/prod.lean
Github Open Source
Open Source
Apache-2.0
2,023
mathlib
leanprover-community
Lean
Code
5,480
14,299
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard, Yury Kudryashov, Eric Wieser -/ import linear_algebra.span import order.partial_sups import algebra.algebra.prod /-! ### Products of modules > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines constructors for linear maps whose domains or codomains are products. It contains theorems relating these to each other, as well as to `submodule.prod`, `submodule.map`, `submodule.comap`, `linear_map.range`, and `linear_map.ker`. ## Main definitions - products in the domain: - `linear_map.fst` - `linear_map.snd` - `linear_map.coprod` - `linear_map.prod_ext` - products in the codomain: - `linear_map.inl` - `linear_map.inr` - `linear_map.prod` - products in both domain and codomain: - `linear_map.prod_map` - `linear_equiv.prod_map` - `linear_equiv.skew_prod` -/ universes u v w x y z u' v' w' y' variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'} variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x} variables {M₅ M₆ : Type*} section prod namespace linear_map variables (S : Type*) [semiring R] [semiring S] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [add_comm_monoid M₅] [add_comm_monoid M₆] variables [module R M] [module R M₂] [module R M₃] [module R M₄] variables [module R M₅] [module R M₆] variables (f : M →ₗ[R] M₂) section variables (R M M₂) /-- The first projection of a product is a linear map. -/ def fst : M × M₂ →ₗ[R] M := { to_fun := prod.fst, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } /-- The second projection of a product is a linear map. -/ def snd : M × M₂ →ₗ[R] M₂ := { to_fun := prod.snd, map_add' := λ x y, rfl, map_smul' := λ x y, rfl } end @[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl @[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl theorem fst_surjective : function.surjective (fst R M M₂) := λ x, ⟨(x, 0), rfl⟩ theorem snd_surjective : function.surjective (snd R M M₂) := λ x, ⟨(0, x), rfl⟩ /-- The prod of two linear maps is a linear map. -/ @[simps] def prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (M →ₗ[R] M₂ × M₃) := { to_fun := pi.prod f g, map_add' := λ x y, by simp only [pi.prod, prod.mk_add_mk, map_add], map_smul' := λ c x, by simp only [pi.prod, prod.smul_mk, map_smul, ring_hom.id_apply] } lemma coe_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ⇑(f.prod g) = pi.prod f g := rfl @[simp] theorem fst_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (fst R M₂ M₃).comp (prod f g) = f := by ext; refl @[simp] theorem snd_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : (snd R M₂ M₃).comp (prod f g) = g := by ext; refl @[simp] theorem pair_fst_snd : prod (fst R M M₂) (snd R M M₂) = linear_map.id := fun_like.coe_injective pi.prod_fst_snd /-- Taking the product of two maps with the same domain is equivalent to taking the product of their codomains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def prod_equiv [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] : ((M →ₗ[R] M₂) × (M →ₗ[R] M₃)) ≃ₗ[S] (M →ₗ[R] M₂ × M₃) := { to_fun := λ f, f.1.prod f.2, inv_fun := λ f, ((fst _ _ _).comp f, (snd _ _ _).comp f), left_inv := λ f, by ext; refl, right_inv := λ f, by ext; refl, map_add' := λ a b, rfl, map_smul' := λ r a, rfl } section variables (R M M₂) /-- The left injection into a product is a linear map. -/ def inl : M →ₗ[R] M × M₂ := prod linear_map.id 0 /-- The right injection into a product is a linear map. -/ def inr : M₂ →ₗ[R] M × M₂ := prod 0 linear_map.id theorem range_inl : range (inl R M M₂) = ker (snd R M M₂) := begin ext x, simp only [mem_ker, mem_range], split, { rintros ⟨y, rfl⟩, refl }, { intro h, exact ⟨x.fst, prod.ext rfl h.symm⟩ } end theorem ker_snd : ker (snd R M M₂) = range (inl R M M₂) := eq.symm $ range_inl R M M₂ theorem range_inr : range (inr R M M₂) = ker (fst R M M₂) := begin ext x, simp only [mem_ker, mem_range], split, { rintros ⟨y, rfl⟩, refl }, { intro h, exact ⟨x.snd, prod.ext h.symm rfl⟩ } end theorem ker_fst : ker (fst R M M₂) = range (inr R M M₂) := eq.symm $ range_inr R M M₂ end @[simp] theorem coe_inl : (inl R M M₂ : M → M × M₂) = λ x, (x, 0) := rfl theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl @[simp] theorem coe_inr : (inr R M M₂ : M₂ → M × M₂) = prod.mk 0 := rfl theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl theorem inl_eq_prod : inl R M M₂ = prod linear_map.id 0 := rfl theorem inr_eq_prod : inr R M M₂ = prod 0 linear_map.id := rfl theorem inl_injective : function.injective (inl R M M₂) := λ _, by simp theorem inr_injective : function.injective (inr R M M₂) := λ _, by simp /-- The coprod function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/ def coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ := f.comp (fst _ _ _) + g.comp (snd _ _ _) @[simp] theorem coprod_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M × M₂) : coprod f g x = f x.1 + g x.2 := rfl @[simp] theorem coprod_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inl R M M₂) = f := by ext; simp only [map_zero, add_zero, coprod_apply, inl_apply, comp_apply] @[simp] theorem coprod_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (coprod f g).comp (inr R M M₂) = g := by ext; simp only [map_zero, coprod_apply, inr_apply, zero_add, comp_apply] @[simp] theorem coprod_inl_inr : coprod (inl R M M₂) (inr R M M₂) = linear_map.id := by ext; simp only [prod.mk_add_mk, add_zero, id_apply, coprod_apply, inl_apply, inr_apply, zero_add] theorem comp_coprod (f : M₃ →ₗ[R] M₄) (g₁ : M →ₗ[R] M₃) (g₂ : M₂ →ₗ[R] M₃) : f.comp (g₁.coprod g₂) = (f.comp g₁).coprod (f.comp g₂) := ext $ λ x, f.map_add (g₁ x.1) (g₂ x.2) theorem fst_eq_coprod : fst R M M₂ = coprod linear_map.id 0 := by ext; simp theorem snd_eq_coprod : snd R M M₂ = coprod 0 linear_map.id := by ext; simp @[simp] theorem coprod_comp_prod (f : M₂ →ₗ[R] M₄) (g : M₃ →ₗ[R] M₄) (f' : M →ₗ[R] M₂) (g' : M →ₗ[R] M₃) : (f.coprod g).comp (f'.prod g') = f.comp f' + g.comp g' := rfl @[simp] lemma coprod_map_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (S : submodule R M) (S' : submodule R M₂) : (submodule.prod S S').map (linear_map.coprod f g) = S.map f ⊔ S'.map g := set_like.coe_injective $ begin simp only [linear_map.coprod_apply, submodule.coe_sup, submodule.map_coe], rw [←set.image2_add, set.image2_image_left, set.image2_image_right], exact set.image_prod (λ m m₂, f m + g m₂), end /-- Taking the product of two maps with the same codomain is equivalent to taking the product of their domains. See note [bundled maps over different rings] for why separate `R` and `S` semirings are used. -/ @[simps] def coprod_equiv [module S M₃] [smul_comm_class R S M₃] : ((M →ₗ[R] M₃) × (M₂ →ₗ[R] M₃)) ≃ₗ[S] (M × M₂ →ₗ[R] M₃) := { to_fun := λ f, f.1.coprod f.2, inv_fun := λ f, (f.comp (inl _ _ _), f.comp (inr _ _ _)), left_inv := λ f, by simp only [prod.mk.eta, coprod_inl, coprod_inr], right_inv := λ f, by simp only [←comp_coprod, comp_id, coprod_inl_inr], map_add' := λ a b, by { ext, simp only [prod.snd_add, add_apply, coprod_apply, prod.fst_add, add_add_add_comm] }, map_smul' := λ r a, by { dsimp, ext, simp only [smul_add, smul_apply, prod.smul_snd, prod.smul_fst, coprod_apply] } } theorem prod_ext_iff {f g : M × M₂ →ₗ[R] M₃} : f = g ↔ f.comp (inl _ _ _) = g.comp (inl _ _ _) ∧ f.comp (inr _ _ _) = g.comp (inr _ _ _) := (coprod_equiv ℕ).symm.injective.eq_iff.symm.trans prod.ext_iff /-- Split equality of linear maps from a product into linear maps over each component, to allow `ext` to apply lemmas specific to `M →ₗ M₃` and `M₂ →ₗ M₃`. See note [partially-applied ext lemmas]. -/ @[ext] theorem prod_ext {f g : M × M₂ →ₗ[R] M₃} (hl : f.comp (inl _ _ _) = g.comp (inl _ _ _)) (hr : f.comp (inr _ _ _) = g.comp (inr _ _ _)) : f = g := prod_ext_iff.2 ⟨hl, hr⟩ /-- `prod.map` of two linear maps. -/ def prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : (M × M₂) →ₗ[R] (M₃ × M₄) := (f.comp (fst R M M₂)).prod (g.comp (snd R M M₂)) lemma coe_prod_map (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : ⇑(f.prod_map g) = prod.map f g := rfl @[simp] theorem prod_map_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) (x) : f.prod_map g x = (f x.1, g x.2) := rfl lemma prod_map_comap_prod (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) (S : submodule R M₂) (S' : submodule R M₄) : (submodule.prod S S').comap (linear_map.prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ lemma ker_prod_map (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) : (linear_map.prod_map f g).ker = submodule.prod f.ker g.ker := begin dsimp only [ker], rw [←prod_map_comap_prod, submodule.prod_bot], end @[simp] lemma prod_map_id : (id : M →ₗ[R] M).prod_map (id : M₂ →ₗ[R] M₂) = id := linear_map.ext $ λ _, prod.mk.eta @[simp] lemma prod_map_one : (1 : M →ₗ[R] M).prod_map (1 : M₂ →ₗ[R] M₂) = 1 := linear_map.ext $ λ _, prod.mk.eta lemma prod_map_comp (f₁₂ : M →ₗ[R] M₂) (f₂₃ : M₂ →ₗ[R] M₃) (g₁₂ : M₄ →ₗ[R] M₅) (g₂₃ : M₅ →ₗ[R] M₆) : f₂₃.prod_map g₂₃ ∘ₗ f₁₂.prod_map g₁₂ = (f₂₃ ∘ₗ f₁₂).prod_map (g₂₃ ∘ₗ g₁₂) := rfl lemma prod_map_mul (f₁₂ : M →ₗ[R] M) (f₂₃ : M →ₗ[R] M) (g₁₂ : M₂ →ₗ[R] M₂) (g₂₃ : M₂ →ₗ[R] M₂) : f₂₃.prod_map g₂₃ * f₁₂.prod_map g₁₂ = (f₂₃ * f₁₂).prod_map (g₂₃ * g₁₂) := rfl lemma prod_map_add (f₁ : M →ₗ[R] M₃) (f₂ : M →ₗ[R] M₃) (g₁ : M₂ →ₗ[R] M₄) (g₂ : M₂ →ₗ[R] M₄) : (f₁ + f₂).prod_map (g₁ + g₂) = f₁.prod_map g₁ + f₂.prod_map g₂ := rfl @[simp] lemma prod_map_zero : (0 : M →ₗ[R] M₂).prod_map (0 : M₃ →ₗ[R] M₄) = 0 := rfl @[simp] lemma prod_map_smul [module S M₃] [module S M₄] [smul_comm_class R S M₃] [smul_comm_class R S M₄] (s : S) (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₄) : prod_map (s • f) (s • g) = s • prod_map f g := rfl variables (R M M₂ M₃ M₄) /-- `linear_map.prod_map` as a `linear_map` -/ @[simps] def prod_map_linear [module S M₃] [module S M₄] [smul_comm_class R S M₃] [smul_comm_class R S M₄] : ((M →ₗ[R] M₃) × (M₂ →ₗ[R] M₄)) →ₗ[S] ((M × M₂) →ₗ[R] (M₃ × M₄)) := { to_fun := λ f, prod_map f.1 f.2, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl} /-- `linear_map.prod_map` as a `ring_hom` -/ @[simps] def prod_map_ring_hom : (M →ₗ[R] M) × (M₂ →ₗ[R] M₂) →+* ((M × M₂) →ₗ[R] (M × M₂)) := { to_fun := λ f, prod_map f.1 f.2, map_one' := prod_map_one, map_zero' := rfl, map_add' := λ _ _, rfl, map_mul' := λ _ _, rfl } variables {R M M₂ M₃ M₄} section map_mul variables {A : Type*} [non_unital_non_assoc_semiring A] [module R A] variables {B : Type*} [non_unital_non_assoc_semiring B] [module R B] lemma inl_map_mul (a₁ a₂ : A) : linear_map.inl R A B (a₁ * a₂) = linear_map.inl R A B a₁ * linear_map.inl R A B a₂ := prod.ext rfl (by simp) lemma inr_map_mul (b₁ b₂ : B) : linear_map.inr R A B (b₁ * b₂) = linear_map.inr R A B b₁ * linear_map.inr R A B b₂ := prod.ext (by simp) rfl end map_mul end linear_map end prod namespace linear_map variables (R M M₂) variables [comm_semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] /-- `linear_map.prod_map` as an `algebra_hom` -/ @[simps] def prod_map_alg_hom : (module.End R M) × (module.End R M₂) →ₐ[R] module.End R (M × M₂) := { commutes' := λ _, rfl, ..prod_map_ring_hom R M M₂ } end linear_map namespace linear_map open submodule variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] lemma range_coprod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (f.coprod g).range = f.range ⊔ g.range := submodule.ext $ λ x, by simp [mem_sup] lemma is_compl_range_inl_inr : is_compl (inl R M M₂).range (inr R M M₂).range := begin split, { rw disjoint_def, rintros ⟨_, _⟩ ⟨x, hx⟩ ⟨y, hy⟩, simp only [prod.ext_iff, inl_apply, inr_apply, mem_bot] at hx hy ⊢, exact ⟨hy.1.symm, hx.2.symm⟩ }, { rw codisjoint_iff_le_sup, rintros ⟨x, y⟩ -, simp only [mem_sup, mem_range, exists_prop], refine ⟨(x, 0), ⟨x, rfl⟩, (0, y), ⟨y, rfl⟩, _⟩, simp } end lemma sup_range_inl_inr : (inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ := is_compl.sup_eq_top is_compl_range_inl_inr lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range := by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl theorem map_coprod_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) : map (coprod f g) (p.prod q) = map f p ⊔ map g q := begin refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)), { rw set_like.le_def, rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩, exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ }, { exact λ x hx, ⟨(x, 0), by simp [hx]⟩ }, { exact λ x hx, ⟨(0, x), by simp [hx]⟩ } end theorem comap_prod_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) : comap (prod f g) (p.prod q) = comap f p ⊓ comap g q := submodule.ext $ λ x, iff.rfl theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) : p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) := submodule.ext $ λ x, iff.rfl theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) : p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) := by rw [← map_coprod_prod, coprod_inl_inr, map_id] lemma span_inl_union_inr {s : set M} {t : set M₂} : span R (inl R M M₂ '' s ∪ inr R M M₂ '' t) = (span R s).prod (span R t) := by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image] @[simp] lemma ker_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : ker (prod f g) = ker f ⊓ ker g := by rw [ker, ← prod_bot, comap_prod_prod]; refl lemma range_prod_le (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : range (prod f g) ≤ (range f).prod (range g) := begin simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib], rintro _ x rfl, exact ⟨⟨x, rfl⟩, ⟨x, rfl⟩⟩ end lemma ker_prod_ker_le_ker_coprod {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : (ker f).prod (ker g) ≤ ker (f.coprod g) := by { rintros ⟨y, z⟩, simp {contextual := tt} } lemma ker_coprod_of_disjoint_range {M₂ : Type*} [add_comm_group M₂] [module R M₂] {M₃ : Type*} [add_comm_group M₃] [module R M₃] (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (hd : disjoint f.range g.range) : ker (f.coprod g) = (ker f).prod (ker g) := begin apply le_antisymm _ (ker_prod_ker_le_ker_coprod f g), rintros ⟨y, z⟩ h, simp only [mem_ker, mem_prod, coprod_apply] at h ⊢, have : f y ∈ f.range ⊓ g.range, { simp only [true_and, mem_range, mem_inf, exists_apply_eq_apply], use -z, rwa [eq_comm, map_neg, ← sub_eq_zero, sub_neg_eq_add] }, rw [hd.eq_bot, mem_bot] at this, rw [this] at h, simpa [this] using h, end end linear_map namespace submodule open linear_map variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] lemma sup_eq_range (p q : submodule R M) : p ⊔ q = (p.subtype.coprod q.subtype).range := submodule.ext $ λ x, by simp [submodule.mem_sup, set_like.exists] variables (p : submodule R M) (q : submodule R M₂) @[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ := by { ext ⟨x, y⟩, simp only [and.left_comm, eq_comm, mem_map, prod.mk.inj_iff, inl_apply, mem_bot, exists_eq_left', mem_prod] } @[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q := by ext ⟨x, y⟩; simp [and.left_comm, eq_comm] @[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ := by ext ⟨x, y⟩; simp @[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q := by ext ⟨x, y⟩; simp @[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp @[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp @[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)] @[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q := by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)] @[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inl] @[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ := by rw [ker, ← prod_bot, prod_comap_inr] @[simp] theorem range_fst : (fst R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_fst] @[simp] theorem range_snd : (snd R M M₂).range = ⊤ := by rw [range_eq_map, ← prod_top, prod_map_snd] variables (R M M₂) /-- `M` as a submodule of `M × N`. -/ def fst : submodule R (M × M₂) := (⊥ : submodule R M₂).comap (linear_map.snd R M M₂) /-- `M` as a submodule of `M × N` is isomorphic to `M`. -/ @[simps] def fst_equiv : submodule.fst R M M₂ ≃ₗ[R] M := { to_fun := λ x, x.1.1, inv_fun := λ m, ⟨⟨m, 0⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma fst_map_fst : (submodule.fst R M M₂).map (linear_map.fst R M M₂) = ⊤ := by tidy lemma fst_map_snd : (submodule.fst R M M₂).map (linear_map.snd R M M₂) = ⊥ := by { tidy, exact 0, } /-- `N` as a submodule of `M × N`. -/ def snd : submodule R (M × M₂) := (⊥ : submodule R M).comap (linear_map.fst R M M₂) /-- `N` as a submodule of `M × N` is isomorphic to `N`. -/ @[simps] def snd_equiv : submodule.snd R M M₂ ≃ₗ[R] M₂ := { to_fun := λ x, x.1.2, inv_fun := λ n, ⟨⟨0, n⟩, by tidy⟩, map_add' := by simp, map_smul' := by simp, left_inv := by tidy, right_inv := by tidy, } lemma snd_map_fst : (submodule.snd R M M₂).map (linear_map.fst R M M₂) = ⊥ := by { tidy, exact 0, } lemma snd_map_snd : (submodule.snd R M M₂).map (linear_map.snd R M M₂) = ⊤ := by tidy lemma fst_sup_snd : submodule.fst R M M₂ ⊔ submodule.snd R M M₂ = ⊤ := begin rw eq_top_iff, rintro ⟨m, n⟩ -, rw [show (m, n) = (m, 0) + (0, n), by simp], apply submodule.add_mem (submodule.fst R M M₂ ⊔ submodule.snd R M M₂), { exact submodule.mem_sup_left (submodule.mem_comap.mpr (by simp)), }, { exact submodule.mem_sup_right (submodule.mem_comap.mpr (by simp)), }, end lemma fst_inf_snd : submodule.fst R M M₂ ⊓ submodule.snd R M M₂ = ⊥ := by tidy lemma le_prod_iff {p₁ : submodule R M} {p₂ : submodule R M₂} {q : submodule R (M × M₂)} : q ≤ p₁.prod p₂ ↔ map (linear_map.fst R M M₂) q ≤ p₁ ∧ map (linear_map.snd R M M₂) q ≤ p₂ := begin split, { intros h, split, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).1 }, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).2 }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ h, exact ⟨hH ⟨_ , h, rfl⟩, hK ⟨ _, h, rfl⟩⟩, } end lemma prod_le_iff {p₁ : submodule R M} {p₂ : submodule R M₂} {q : submodule R (M × M₂)} : p₁.prod p₂ ≤ q ↔ map (linear_map.inl R M M₂) p₁ ≤ q ∧ map (linear_map.inr R M M₂) p₂ ≤ q := begin split, { intros h, split, { rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨hx, zero_mem p₂⟩, }, { rintros _ ⟨x, hx, rfl⟩, apply h, exact ⟨zero_mem p₁, hx⟩, }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ ⟨h1, h2⟩, have h1' : (linear_map.inl R _ _) x1 ∈ q, { apply hH, simpa using h1, }, have h2' : (linear_map.inr R _ _) x2 ∈ q, { apply hK, simpa using h2, }, simpa using add_mem h1' h2', } end lemma prod_eq_bot_iff {p₁ : submodule R M} {p₂ : submodule R M₂} : p₁.prod p₂ = ⊥ ↔ p₁ = ⊥ ∧ p₂ = ⊥ := by simp only [eq_bot_iff, prod_le_iff, (gc_map_comap _).le_iff_le, comap_bot, ker_inl, ker_inr] lemma prod_eq_top_iff {p₁ : submodule R M} {p₂ : submodule R M₂} : p₁.prod p₂ = ⊤ ↔ p₁ = ⊤ ∧ p₂ = ⊤ := by simp only [eq_top_iff, le_prod_iff, ← (gc_map_comap _).le_iff_le, map_top, range_fst, range_snd] end submodule namespace linear_equiv /-- Product of modules is commutative up to linear isomorphism. -/ @[simps apply] def prod_comm (R M N : Type*) [semiring R] [add_comm_monoid M] [add_comm_monoid N] [module R M] [module R N] : (M × N) ≃ₗ[R] (N × M) := { to_fun := prod.swap, map_smul' := λ r ⟨m, n⟩, rfl, ..add_equiv.prod_comm } section variables (R M M₂ M₃ M₄) variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R M₂] [module R M₃] [module R M₄] /-- Four-way commutativity of `prod`. The name matches `mul_mul_mul_comm`. -/ @[simps apply] def prod_prod_prod_comm : ((M × M₂) × (M₃ × M₄)) ≃ₗ[R] (M × M₃) × (M₂ × M₄) := { to_fun := λ mnmn, ((mnmn.1.1, mnmn.2.1), (mnmn.1.2, mnmn.2.2)), inv_fun := λ mmnn, ((mmnn.1.1, mmnn.2.1), (mmnn.1.2, mmnn.2.2)), map_smul' := λ c mnmn, rfl, ..add_equiv.prod_prod_prod_comm M M₂ M₃ M₄ } @[simp] lemma prod_prod_prod_comm_symm : (prod_prod_prod_comm R M M₂ M₃ M₄).symm = prod_prod_prod_comm R M M₃ M₂ M₄ := rfl @[simp] lemma prod_prod_prod_comm_to_add_equiv : (prod_prod_prod_comm R M M₂ M₃ M₄).to_add_equiv = add_equiv.prod_prod_prod_comm M M₂ M₃ M₄ := rfl end section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Product of linear equivalences; the maps come from `equiv.prod_congr`. -/ protected def prod : (M × M₃) ≃ₗ[R] (M₂ × M₄) := { map_smul' := λ c x, prod.ext (e₁.map_smulₛₗ c _) (e₂.map_smulₛₗ c _), .. e₁.to_add_equiv.prod_congr e₂.to_add_equiv } lemma prod_symm : (e₁.prod e₂).symm = e₁.symm.prod e₂.symm := rfl @[simp] lemma prod_apply (p) : e₁.prod e₂ p = (e₁ p.1, e₂ p.2) := rfl @[simp, norm_cast] lemma coe_prod : (e₁.prod e₂ : (M × M₃) →ₗ[R] (M₂ × M₄)) = (e₁ : M →ₗ[R] M₂).prod_map (e₂ : M₃ →ₗ[R] M₄) := rfl end section variables [semiring R] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R M₂} variables {module_M₃ : module R M₃} {module_M₄ : module R M₄} variables (e₁ : M ≃ₗ[R] M₂) (e₂ : M₃ ≃ₗ[R] M₄) /-- Equivalence given by a block lower diagonal matrix. `e₁` and `e₂` are diagonal square blocks, and `f` is a rectangular block below the diagonal. -/ protected def skew_prod (f : M →ₗ[R] M₄) : (M × M₃) ≃ₗ[R] M₂ × M₄ := { inv_fun := λ p : M₂ × M₄, (e₁.symm p.1, e₂.symm (p.2 - f (e₁.symm p.1))), left_inv := λ p, by simp, right_inv := λ p, by simp, .. ((e₁ : M →ₗ[R] M₂).comp (linear_map.fst R M M₃)).prod ((e₂ : M₃ →ₗ[R] M₄).comp (linear_map.snd R M M₃) + f.comp (linear_map.fst R M M₃)) } @[simp] lemma skew_prod_apply (f : M →ₗ[R] M₄) (x) : e₁.skew_prod e₂ f x = (e₁ x.1, e₂ x.2 + f x.1) := rfl @[simp] lemma skew_prod_symm_apply (f : M →ₗ[R] M₄) (x) : (e₁.skew_prod e₂ f).symm x = (e₁.symm x.1, e₂.symm (x.2 - f (e₁.symm x.1))) := rfl end end linear_equiv namespace linear_map open submodule variables [ring R] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- If the union of the kernels `ker f` and `ker g` spans the domain, then the range of `prod f g` is equal to the product of `range f` and `range g`. -/ lemma range_prod_eq {f : M →ₗ[R] M₂} {g : M →ₗ[R] M₃} (h : ker f ⊔ ker g = ⊤) : range (prod f g) = (range f).prod (range g) := begin refine le_antisymm (f.range_prod_le g) _, simp only [set_like.le_def, prod_apply, mem_range, set_like.mem_coe, mem_prod, exists_imp_distrib, and_imp, prod.forall, pi.prod], rintros _ _ x rfl y rfl, simp only [prod.mk.inj_iff, ← sub_mem_ker_iff], have : y - x ∈ ker f ⊔ ker g, { simp only [h, mem_top] }, rcases mem_sup.1 this with ⟨x', hx', y', hy', H⟩, refine ⟨x' + x, _, _⟩, { simp only [mem_ker.mp hx', map_add, zero_add]}, { simp [←eq_sub_iff_add_eq.1 H, map_add, add_left_inj, self_eq_add_right, mem_ker.mp hy'] } end end linear_map namespace linear_map /-! ## Tunnels and tailings Some preliminary work for establishing the strong rank condition for noetherian rings. Given a morphism `f : M × N →ₗ[R] M` which is `i : injective f`, we can find an infinite decreasing `tunnel f i n` of copies of `M` inside `M`, and sitting beside these, an infinite sequence of copies of `N`. We picturesquely name these as `tailing f i n` for each individual copy of `N`, and `tailings f i n` for the supremum of the first `n+1` copies: they are the pieces left behind, sitting inside the tunnel. By construction, each `tailing f i (n+1)` is disjoint from `tailings f i n`; later, when we assume `M` is noetherian, this implies that `N` must be trivial, and establishes the strong rank condition for any left-noetherian ring. -/ section tunnel -- (This doesn't work over a semiring: we need to use that `submodule R M` is a modular lattice, -- which requires cancellation.) variables [ring R] variables {N : Type*} [add_comm_group M] [module R M] [add_comm_group N] [module R N] open function /-- An auxiliary construction for `tunnel`. The composition of `f`, followed by the isomorphism back to `K`, followed by the inclusion of this submodule back into `M`. -/ def tunnel_aux (f : M × N →ₗ[R] M) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : M × N →ₗ[R] M := (Kφ.1.subtype.comp Kφ.2.symm.to_linear_map).comp f lemma tunnel_aux_injective (f : M × N →ₗ[R] M) (i : injective f) (Kφ : Σ K : submodule R M, K ≃ₗ[R] M) : injective (tunnel_aux f Kφ) := (subtype.val_injective.comp Kφ.2.symm.injective).comp i noncomputable theory /-- Auxiliary definition for `tunnel`. -/ -- Even though we have `noncomputable theory`, -- we get an error without another `noncomputable` here. noncomputable def tunnel' (f : M × N →ₗ[R] M) (i : injective f) : ℕ → Σ (K : submodule R M), K ≃ₗ[R] M | 0 := ⟨⊤, linear_equiv.of_top ⊤ rfl⟩ | (n+1) := ⟨(submodule.fst R M N).map (tunnel_aux f (tunnel' n)), ((submodule.fst R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' n))).symm.trans (submodule.fst_equiv R M N)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a nested sequence of submodules all isomorphic to `M`. -/ def tunnel (f : M × N →ₗ[R] M) (i : injective f) : ℕ →o (submodule R M)ᵒᵈ := ⟨λ n, order_dual.to_dual (tunnel' f i n).1, monotone_nat_of_le_succ (λ n, begin dsimp [tunnel', tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end)⟩ /-- Give an injective map `f : M × N →ₗ[R] M` we can find a sequence of submodules all isomorphic to `N`. -/ def tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : submodule R M := (submodule.snd R M N).map (tunnel_aux f (tunnel' f i n)) /-- Each `tailing f i n` is a copy of `N`. -/ def tailing_linear_equiv (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≃ₗ[R] N := ((submodule.snd R M N).equiv_map_of_injective _ (tunnel_aux_injective f i (tunnel' f i n))).symm.trans (submodule.snd_equiv R M N) lemma tailing_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ≤ (tunnel f i n).of_dual := begin dsimp [tailing, tunnel_aux], rw [submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end lemma tailing_disjoint_tunnel_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailing f i n) (tunnel f i (n+1)).of_dual := begin rw disjoint_iff, dsimp [tailing, tunnel, tunnel'], rw [submodule.map_inf_eq_map_inf_comap, submodule.comap_map_eq_of_injective (tunnel_aux_injective _ i _), inf_comm, submodule.fst_inf_snd, submodule.map_bot], end lemma tailing_sup_tunnel_succ_le_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailing f i n ⊔ (tunnel f i (n+1)).of_dual ≤ (tunnel f i n).of_dual := begin dsimp [tailing, tunnel, tunnel', tunnel_aux], rw [←submodule.map_sup, sup_comm, submodule.fst_sup_snd, submodule.map_comp, submodule.map_comp], apply submodule.map_subtype_le, end /-- The supremum of all the copies of `N` found inside the tunnel. -/ def tailings (f : M × N →ₗ[R] M) (i : injective f) : ℕ → submodule R M := partial_sups (tailing f i) @[simp] lemma tailings_zero (f : M × N →ₗ[R] M) (i : injective f) : tailings f i 0 = tailing f i 0 := by simp [tailings] @[simp] lemma tailings_succ (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : tailings f i (n+1) = tailings f i n ⊔ tailing f i (n+1) := by simp [tailings] lemma tailings_disjoint_tunnel (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tunnel f i (n+1)).of_dual := begin induction n with n ih, { simp only [tailings_zero], apply tailing_disjoint_tunnel_succ, }, { simp only [tailings_succ], refine disjoint.disjoint_sup_left_of_disjoint_sup_right _ _, apply tailing_disjoint_tunnel_succ, apply disjoint.mono_right _ ih, apply tailing_sup_tunnel_succ_le_tunnel, }, end lemma tailings_disjoint_tailing (f : M × N →ₗ[R] M) (i : injective f) (n : ℕ) : disjoint (tailings f i n) (tailing f i (n+1)) := disjoint.mono_right (tailing_le_tunnel f i _) (tailings_disjoint_tunnel f i _) end tunnel section graph variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_group M₃] [add_comm_group M₄] [module R M] [module R M₂] [module R M₃] [module R M₄] (f : M →ₗ[R] M₂) (g : M₃ →ₗ[R] M₄) /-- Graph of a linear map. -/ def graph : submodule R (M × M₂) := { carrier := {p | p.2 = f p.1}, add_mem' := λ a b (ha : _ = _) (hb : _ = _), begin change _ + _ = f (_ + _), rw [map_add, ha, hb] end, zero_mem' := eq.symm (map_zero f), smul_mem' := λ c x (hx : _ = _), begin change _ • _ = f (_ • _), rw [map_smul, hx] end } @[simp] lemma mem_graph_iff (x : M × M₂) : x ∈ f.graph ↔ x.2 = f x.1 := iff.rfl lemma graph_eq_ker_coprod : g.graph = ((-g).coprod linear_map.id).ker := begin ext x, change _ = _ ↔ -(g x.1) + x.2 = _, rw [add_comm, add_neg_eq_zero] end lemma graph_eq_range_prod : f.graph = (linear_map.id.prod f).range := begin ext x, exact ⟨λ hx, ⟨x.1, prod.ext rfl hx.symm⟩, λ ⟨u, hu⟩, hu ▸ rfl⟩ end end graph end linear_map
34,253
https://github.com/westcoastavgallery/westcoastavgallery.github.io/blob/master/media/akeeba_strapper/strapper.php
Github Open Source
Open Source
MIT
null
westcoastavgallery.github.io
westcoastavgallery
PHP
Code
1,635
5,294
<?php /** * Akeeba Strapper * A handy distribution of namespaced jQuery, jQuery UI and Twitter * Bootstrapper for use with Akeeba components. * * @copyright (c) 2012-2013 Akeeba Ltd * @license GNU General Public License version 2 or later */ defined('_JEXEC') or die(); if (!defined('FOF_INCLUDED')) { include_once JPATH_SITE . '/libraries/fof/include.php'; } class AkeebaStrapper { /** @var bool True when jQuery is already included */ public static $_includedJQuery = false; /** @var bool True when jQuery UI is already included */ public static $_includedJQueryUI = false; /** @var bool True when Bootstrap is already included */ public static $_includedBootstrap = false; /** @var array List of URLs to Javascript files */ public static $scriptURLs = array(); /** @var array List of script definitions to include in the head */ public static $scriptDefs = array(); /** @var array List of URLs to CSS files */ public static $cssURLs = array(); /** @var array List of URLs to LESS files */ public static $lessURLs = array(); /** @var array List of CSS definitions to include in the head */ public static $cssDefs = array(); /** @var string The jQuery UI theme to use, default is 'smoothness' */ protected static $jqUItheme = 'smoothness'; /** @var string A query tag to append to CSS and JS files for versioning purposes */ public static $tag = null; /** * Is this something running under the CLI mode? * @staticvar bool|null $isCli * @return null */ public static function isCli() { static $isCli = null; if (is_null($isCli)) { try { if (is_null(JFactory::$application)) { $isCli = true; } else { $isCli = version_compare(JVERSION, '1.6.0', 'ge') ? (JFactory::getApplication() instanceof JException) : false; } } catch (Exception $e) { $isCli = true; } } return $isCli; } public static function getPreference($key, $default = null) { static $config = null; if(is_null($config)) { // Load a configuration INI file which controls which files should be skipped $iniFile = FOFTemplateUtils::parsePath('media://akeeba_strapper/strapper.ini', true); $config = parse_ini_file($iniFile); } if (!array_key_exists($key, $config)) { $config[$key] = $default; } return $config[$key]; } /** * Loads our namespaced jQuery, accessible through akeeba.jQuery */ public static function jQuery() { if (self::isCli()) { return; } $jQueryLoad = self::getPreference('jquery_load', 'auto'); if (!in_array($jQueryLoad, array('auto', 'full', 'namespace', 'none'))) { $jQueryLoad = 'auto'; } self::$_includedJQuery = true; if ($jQueryLoad == 'none') { return; } elseif ($jQueryLoad == 'auto') { if (version_compare(JVERSION, '3.0', 'gt')) { $jQueryLoad = 'namespace'; JHtml::_('jquery.framework'); } else { $jQueryLoad = 'full'; } } if ($jQueryLoad == 'full') { self::$scriptURLs[] = FOFTemplateUtils::parsePath('media://akeeba_strapper/js/akeebajq.js'); self::$scriptURLs[] = FOFTemplateUtils::parsePath('media://akeeba_strapper/js/akjqmigrate.js'); } else { self::$scriptURLs[] = FOFTemplateUtils::parsePath('media://akeeba_strapper/js/namespace.js'); } } /** * Sets the jQuery UI theme to use. It must be the name of a subdirectory of * media/akeeba_strapper/css or templates/<yourtemplate>/media/akeeba_strapper/css * * @param $theme string The name of the subdirectory holding the theme */ public static function setjQueryUItheme($theme) { if (self::isCli()) { return; } self::$jqUItheme = $theme; } /** * Loads our namespaced jQuery UI and its stylesheet */ public static function jQueryUI() { if (self::isCli()) { return; } if (!self::$_includedJQuery) { self::jQuery(); } self::$_includedJQueryUI = true; $jQueryUILoad = self::getPreference('jqueryui_load', 1); if (!$jQueryUILoad) { return; } $theme = self::getPreference('jquery_theme', self::$jqUItheme); $url = FOFTemplateUtils::parsePath('media://akeeba_strapper/js/akeebajqui.js'); self::$scriptURLs[] = $url; self::$cssURLs[] = FOFTemplateUtils::parsePath("media://akeeba_strapper/css/$theme/theme.css"); } /** * Loads our namespaced Twitter Bootstrap. You have to wrap the output you want style * with an element having the class akeeba-bootstrap added to it. */ public static function bootstrap() { if (self::isCli()) { return; } if (version_compare(JVERSION, '3.2', 'gt')) { $key = 'joomla32'; $default = 'lite'; } elseif (version_compare(JVERSION, '3.0', 'gt')) { $key = 'joomla3'; $default = 'lite'; } else { $key = 'joomla2'; $default = 'full'; } $loadBootstrap = self::getPreference('bootstrap_' . $key, $default); if (!in_array($loadBootstrap, array('full','lite','none'))) { if ($key == 'joomla3') { $loadBootstrap = 'lite'; } elseif ($key == 'joomla32') { $loadBootstrap = 'lite'; } else { $loadBootstrap = 'full'; } } if (($key == 'joomla3') && in_array($loadBootstrap, array('lite', 'none'))) { // Use Joomla!'s Javascript JHtml::_('bootstrap.framework'); } if (!self::$_includedJQuery) { self::jQuery(); } if ($loadBootstrap == 'none') { return; } self::$_includedBootstrap = true; $source = self::getPreference('bootstrap_source', 'css'); if (!in_array($source, array('css','less'))) { $source = 'css'; } $altCss = array('media://akeeba_strapper/css/strapper.css'); if ($loadBootstrap == 'full') { array_unshift($altCss, 'media://akeeba_strapper/css/bootstrap.min.css'); self::$scriptURLs[] = FOFTemplateUtils::parsePath('media://akeeba_strapper/js/bootstrap.min.js'); if ($source == 'less') { self::$lessURLs[] = array('media://akeeba_strapper/less/bootstrap.j25.less', $altCss); } } else { switch ($key) { case 'joomla3': $qualifier = '.j3'; break; case 'joomla32': $qualifier = '.j32'; break; default: $qualifier = ''; break; } array_unshift($altCss, 'media://akeeba_strapper/css/bootstrap' . $qualifier . '.css'); if ($source == 'less') { self::$lessURLs[] = array('media://akeeba_strapper/less/bootstrap' . $qualifier . '.less', $altCss); } } if ($source == 'css') { foreach($altCss as $css) { self::$cssURLs[] = FOFTemplateUtils::parsePath($css); } } } /** * Adds an arbitraty Javascript file. * * @param $path string The path to the file, in the format media://path/to/file */ public static function addJSfile($path) { if (self::isCli()) { return; } self::$scriptURLs[] = FOFTemplateUtils::parsePath($path); } /** * Add inline Javascript * * @param $script string Raw inline Javascript */ public static function addJSdef($script) { if (self::isCli()) { return; } self::$scriptDefs[] = $script; } /** * Adds an arbitraty CSS file. * * @param $path string The path to the file, in the format media://path/to/file */ public static function addCSSfile($path) { if (self::isCli()) { return; } self::$cssURLs[] = FOFTemplateUtils::parsePath($path); } /** * Adds an arbitraty LESS file. * * @param $path string The path to the file, in the format media://path/to/file * @param $altPaths string|array The path to the alternate CSS files, in the format media://path/to/file */ public static function addLESSfile($path, $altPaths = null) { if (self::isCli()) { return; } self::$lessURLs[] = array($path, $altPaths); } /** * Add inline CSS * * @param $style string Raw inline CSS */ public static function addCSSdef($style) { if (self::isCli()) { return; } self::$cssDefs[] = $style; } /** * Do we need to preload? * * @return bool True if we need to preload */ public static function needPreload() { $isJ2 = version_compare(JVERSION, '3.0', 'lt'); $isJ3 = version_compare(JVERSION, '3.0', 'ge'); $preloadJ2 = (bool)self::getPreference('preload_joomla2', 1); $preloadJ3 = (bool)self::getPreference('preload_joomla3', 0); // Do not allow Joomla! 3+ preloading if jQueryLoad is "auto" or "namespace" (which are both // namespace in Joomla! 3+). Else only the namespacing for the jQuery library will be loaded, // without a jQuery library being loaded on forehand, which results in jQuery error(s). $jQueryLoad = self::getPreference('jquery_load', 'auto'); if(in_array($jQueryLoad, array('auto', 'namespace'))) { $preloadJ3 = false; } $needPreload = $isJ2 && $preloadJ2 || $isJ3 && $preloadJ3; return $needPreload; } } /** * This is a workaround which ensures that Akeeba's namespaced JavaScript and CSS will be loaded * without being tampered with by any system plugin. Moreover, since we are loading first, we can * be pretty sure that namespacing *will* work and we won't cause any incompatibilities with third * party extensions loading different versions of these GUI libraries. * * This code works by registering a system plugin hook :) It will grab the HTML and drop its own * JS and CSS definitions in the head of the script, before anything else has the chance to run. * * Peace. */ function AkeebaStrapperLoader() { // If there are no script defs, just go to sleep if ( empty(AkeebaStrapper::$scriptURLs) && empty(AkeebaStrapper::$scriptDefs) && empty(AkeebaStrapper::$cssDefs) && empty(AkeebaStrapper::$cssURLs) && empty(AkeebaStrapper::$lessURLs) ) { return; } // Get the query tag $tag = AkeebaStrapper::$tag; if (empty($tag)) { $tag = ''; } else { $tag = '?' . ltrim($tag, '?'); } $myscripts = ''; $preloadJ2 = (bool)AkeebaStrapper::getPreference('preload_joomla2', 1); $preload = AkeebaStrapper::needPreload(); if ($preload) { $buffer = JResponse::getBody(); } else { $preloadJ2 = false; $preload = false; } // Include Javascript files if (!empty(AkeebaStrapper::$scriptURLs)) foreach (AkeebaStrapper::$scriptURLs as $url) { if ($preloadJ2 && (basename($url) == 'bootstrap.min.js')) { // Special case: check that nobody else is using bootstrap[.min].js on the page. $scriptRegex = "/<script [^>]+(\/>|><\/script>)/i"; $jsRegex = "/([^\"\'=]+\.(js)(\?[^\"\']*){0,1})[\"\']/i"; preg_match_all($scriptRegex, $buffer, $matches); $scripts = @implode('', $matches[0]); preg_match_all($jsRegex, $scripts, $matches); $skip = false; foreach ($matches[1] as $scripturl) { $scripturl = basename($scripturl); if (in_array($scripturl, array('bootstrap.min.js', 'bootstrap.js'))) { $skip = true; } } if ($skip) continue; } if ($preload) { $myscripts .= '<script type="text/javascript" src="' . $url . $tag . '"></script>' . "\n"; } else { JFactory::getDocument()->addScript($url . $tag); } } // Include Javscript snippets if (!empty(AkeebaStrapper::$scriptDefs)) { if ($preload) { $myscripts .= '<script type="text/javascript" language="javascript">' . "\n"; } else { $myscripts = ''; } foreach (AkeebaStrapper::$scriptDefs as $def) { $myscripts .= $def . "\n"; } if ($preload) { $myscripts .= '</script>' . "\n"; } else { JFactory::getDocument()->addScriptDeclaration($myscripts); } } // Include LESS files if (!empty(AkeebaStrapper::$lessURLs)) { foreach (AkeebaStrapper::$lessURLs as $entry) { list($lessFile, $altFiles) = $entry; $url = FOFTemplateUtils::addLESS($lessFile, $altFiles, true); if ($preload) { if (empty($url)) { if (!is_array($altFiles) && empty($altFiles)) { $altFiles = array($altFiles); } if (!empty($altFiles)) { foreach ($altFiles as $altFile) { $url = FOFTemplateUtils::parsePath($altFile); $myscripts .= '<link type="text/css" rel="stylesheet" href="' . $url . $tag . '" />' . "\n"; } } } else { $myscripts .= '<link type="text/css" rel="stylesheet" href="' . $url . $tag . '" />' . "\n"; } } else { if (empty($url)) { if (!is_array($altFiles) && empty($altFiles)) { $altFiles = array($altFiles); } if (!empty($altFiles)) { foreach ($altFiles as $altFile) { $url = FOFTemplateUtils::parsePath($altFile); JFactory::getDocument()->addStyleSheet($url . $tag); } } } else { JFactory::getDocument()->addStyleSheet($url . $tag); } } } } // Include CSS files if (!empty(AkeebaStrapper::$cssURLs)) foreach (AkeebaStrapper::$cssURLs as $url) { if ($preload) { $myscripts .= '<link type="text/css" rel="stylesheet" href="' . $url . $tag . '" />' . "\n"; } else { JFactory::getDocument()->addStyleSheet($url . $tag); } } // Include style definitions if (!empty(AkeebaStrapper::$cssDefs)) { $myscripts .= '<style type="text/css">' . "\n"; foreach (AkeebaStrapper::$cssDefs as $def) { if ($preload) { $myscripts .= $def . "\n"; } else { JFactory::getDocument()->addScriptDeclaration($def . "\n"); } } $myscripts .= '</style>' . "\n"; } if ($preload) { $pos = strpos($buffer, "<head>"); if ($pos > 0) { $buffer = substr($buffer, 0, $pos + 6) . $myscripts . substr($buffer, $pos + 6); JResponse::setBody($buffer); } } } // Add our pseudo-plugin to the application event queue if (!AkeebaStrapper::isCli()) { $app = JFactory::getApplication(); if (AkeebaStrapper::needPreload()) { $app->registerEvent('onAfterRender', 'AkeebaStrapperLoader'); } else { $app->registerEvent('onBeforeRender', 'AkeebaStrapperLoader'); } }
28,043
https://github.com/RampNetwork/torus-website/blob/master/app/src/components/helpers/HelpTooltip/index.js
Github Open Source
Open Source
MIT
2,021
torus-website
RampNetwork
JavaScript
Code
6
12
export { default } from './HelpTooltip'
13,882
https://github.com/xyzniu/FPSGame/blob/master/app/src/main/java/com/xyzniu/fpsgame/listener/CameraTouchListener.java
Github Open Source
Open Source
Ruby, CC-BY-3.0, CC-BY-4.0
null
FPSGame
xyzniu
Java
Code
89
288
package com.xyzniu.fpsgame.listener; import android.opengl.GLSurfaceView; import android.view.MotionEvent; import android.view.View; import com.xyzniu.fpsgame.manager.PlayerManager; public class CameraTouchListener implements View.OnTouchListener { private GLSurfaceView view; float prevX = 0; public CameraTouchListener(GLSurfaceView view) { this.view = view; } @Override public boolean onTouch(View v, final MotionEvent event) { if (event != null) { if (event.getAction() == MotionEvent.ACTION_DOWN) { prevX = event.getX(); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { final float deltaX = event.getX() - prevX; prevX = event.getX(); view.queueEvent(new Runnable() { @Override public void run() { PlayerManager.dragCamera(deltaX); } }); } return true; } return false; } }
32,286
https://github.com/pgregory/wetracker/blob/master/docs/css/main.scss
Github Open Source
Open Source
MIT
2,022
wetracker
pgregory
SCSS
Code
120
391
--- # Only the main Sass file needs front matter (the dashes are enough) --- @charset "utf-8"; // Our variables $spacing-unit: 10px; $image-size: 50px; $icon-size: 15px; // Sizes $on-palm: 768px; // Use media queries like this: // @include media-query($on-palm) { // .wrapper { // padding-right: $spacing-unit / 2; // padding-left: $spacing-unit / 2; // } // } @mixin media-query($device) { @media screen and (max-width: $device) { @content; } } // Import partials from `sass_dir` (defaults to `_sass`) @import "styles", "highlight" ; .github-corner:hover .octo-arm { animation:octocat-wave 560ms ease-in-out } @keyframes octocat-wave { 0%,100% { transform:rotate(0) } 20%,60% { transform:rotate(-25deg) } 40%,80% { transform:rotate(10deg) } } @media (max-width:500px) { .github-corner:hover .octo-arm { animation:none } .github-corner .octo-arm { animation:octocat-wave 560ms ease-in-out } }
13,244
https://github.com/nguyentanle/ptw1_nhom_I/blob/master/admin/posts_delete.php
Github Open Source
Open Source
Apache-2.0
2,021
ptw1_nhom_I
nguyentanle
PHP
Code
44
157
<?php include_once('posts_connect.php'); if(isset($_REQUEST['ID_POST']) and $_REQUEST['ID_POST']!=""){ $id=$_GET['ID_POST']; $sql = "DELETE FROM post WHERE ID_POST='$id'"; if ($conn->query($sql) === TRUE) { echo "Xoá thành công!"; ?> <form method="get" action="posts_view.php"> <button type="submit">OK</button> </form> <?php } else { echo "Error updating record: " . $conn->error; } $conn->close(); } ?>
760