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/calavera/mcclimate/blob/master/test/mcclimate/compare/reporter/compared_basic_test.rb
Github Open Source
Open Source
MIT
2,015
mcclimate
calavera
Ruby
Code
83
344
require "test_helper" class ComparedBasicTest < Minitest::Test def setup @reporter = McClimate::Reporter::ComparedBasic.new end def test_report_new_score @reporter.report_new_score("foo.rb", "#bar", 3) report = {"foo.rb" => {"#bar" => [3]}} assert_equal report, @reporter.report[:new] end def test_report_worse_score @reporter.report_worse_score("foo.rb", "#bar", 3, 1) report = {"foo.rb" => {"#bar" => [3, 1]}} assert_equal report, @reporter.report[:worse] end def test_report_fixed_score @reporter.report_fixed_score("foo.rb", "#bar", 3, 100) report = {"foo.rb" => {"#bar" => [3, 100]}} assert_equal report, @reporter.report[:fixed] end def test_report_improved_score @reporter.report_improved_score("foo.rb", "#bar", 30, 100) report = {"foo.rb" => {"#bar" => [30, 100]}} assert_equal report, @reporter.report[:improved] end end
50,000
https://github.com/smithedwin201/SmartBand/blob/master/app/src/main/java/com/test/smartband/activity/TodaySportActivity.java
Github Open Source
Open Source
Apache-2.0
null
SmartBand
smithedwin201
Java
Code
57
233
package com.test.smartband.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; import com.test.smartband.R; public class TodaySportActivity extends AppCompatActivity { private ImageView backImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_today_step); initView(); backImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } /** * 初始化 */ private void initView() { backImage = (ImageView) findViewById(R.id.iv_back); } }
28,760
https://github.com/PlantandFoodResearch/irods/blob/master/iRODS/clients/icommands/test/rules3.0/ruleintegrityAVU.r
Github Open Source
Open Source
BSD-3-Clause
2,019
irods
PlantandFoodResearch
R
Code
155
569
integrityAVU { #Input parameter is: # Name of collection that will be checked # Attribute name whose presence will be verified #Output is: # List of all files in the collection that are missing the attribute #Verify that input path is a collection msiIsColl(*Coll,*Result, *Status); if(*Result == 0) { writeLine("stdout","Input path *Coll is not a collection"); fail; } *ContInxOld = 1; *Count = 0; #Loop over files in the collection msiMakeGenQuery("DATA_ID,DATA_NAME","COLL_NAME = '*Coll'", *GenQInp); msiExecGenQuery(*GenQInp, *GenQOut); msiGetContInxFromGenQueryOut(*GenQOut,*ContInxNew); while(*ContInxOld > 0) { foreach(*GenQOut) { msiGetValByKey(*GenQOut,"DATA_ID", *Dataid); msiMakeGenQuery("META_DATA_ATTR_NAME","DATA_ID = '*Dataid'", *GenQInp1); msiExecGenQuery(*GenQInp1, *GenQOut1); *Attrfound = 0; foreach(*GenQOut1) { msiGetValByKey(*GenQOut1,"META_DATA_ATTR_NAME",*Attrname); if(*Attrname == *Attr) { *Attrfound = 1; } } msiFreeBuffer(*GenQInp1); msiFreeBuffer(*GenQOut1); if(*Attrfound == 0) { msiGetValByKey(*GenQOut,"DATA_NAME", *File); writeLine("stdout","*File does not have attribute *Attr"); *Count = *Count + 1; } } *ContInxOld = *ContInxNew; if(*ContInxOld > 0) {msiGetMoreRows(*GenQInp,*GenQOut,*ContInxNew);} } writeLine("stdout","Number of files in *Coll missing attribute *Attr is *Count"); } INPUT *Coll = "/tempZone/home/rods/sub1", *Attr = "DC.Relation" OUTPUT ruleExecOut
33,499
https://github.com/crispab/codekvast/blob/master/product/server/common/src/test/java/io/codekvast/common/logging/LoggingUtilsTest.kt
Github Open Source
Open Source
MIT
2,022
codekvast
crispab
Kotlin
Code
117
508
package io.codekvast.common.logging import io.codekvast.common.logging.LoggingUtils.humanReadableByteCount import io.codekvast.common.logging.LoggingUtils.humanReadableDuration import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource import java.time.Duration import java.util.* import kotlin.test.assertEquals /** @author olle.hallin@crisp.se */ class LoggingUtilsTest { private var oldLocale: Locale? = null @BeforeEach fun beforeTest() { oldLocale = Locale.getDefault() Locale.setDefault(Locale.ENGLISH) } @AfterEach fun afterTest() { Locale.setDefault(oldLocale) } @ParameterizedTest @CsvSource( "123, 123 B", "12345, 12.3 kB", "123456789, 123.5 MB", "123456789012, 123.5 GB" ) fun shouldMakeHumanReadableByteCount(bytes: Long, expected: String) { assertEquals(actual = humanReadableByteCount(bytes), expected = expected) } @ParameterizedTest @CsvSource( "123456000, 34h 17m 36s", "603000, 10m 3s", "12345, 12s", "1000, 1s", "1001, 1.001s", "1999, 1.999s", "2000, 2s", "2001, 2s", "2499, 2s", "2500, 3s", "2501, 3s") fun shouldMakeHumanReadableDuration(millis: Long, expected: String) { assertEquals(expected = expected, actual = humanReadableDuration(Duration.ofMillis(millis))) } }
49,707
https://github.com/vituhugo/forum/blob/master/app/Module.php
Github Open Source
Open Source
MIT
null
forum
vituhugo
PHP
Code
44
158
<?php namespace App; use App\Observers\ModuleObserver; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; class Module extends Model { protected $fillable = ['name']; public function subjects() { return $this->hasMany(Subject::class); } public function issues() { return $this->hasMany(Subject::class)->join('issues', 'subjects.id', 'subject_id'); } public function getRouteKeyName() { return 'slug'; } }
10,795
https://github.com/SolonAuthpaper/HiQ-Robust-and-Fast-Decoding-of-High-Capacity-Color-QR-Codes/blob/master/Authpaper-B&W/AuthBarcodeScanner/src/edu/cuhk/ie/authbarcodescanner/android/history/HistoryDbHelper.java
Github Open Source
Open Source
Apache-2.0
null
HiQ-Robust-and-Fast-Decoding-of-High-Capacity-Color-QR-Codes
SolonAuthpaper
Java
Code
692
2,780
/* Copyright (C) 2014 Solon Li */ package edu.cuhk.ie.authbarcodescanner.android.history; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; /** * This class handles the database saving the scanned 2D barcode history. * Please access the database via HistoryFragment */ public class HistoryDbHelper extends SQLiteOpenHelper{ private static final String TAG=HistoryDbHelper.class.getSimpleName(); public boolean isEncode=false; private class TableStructure implements BaseColumns { public final String TABLE_NAME; public final String _ID = BaseColumns._ID; public final String COLUMN_NAME_TIME = "time"; public final String COLUMN_NAME_TEXT = "text"; public final String COLUMN_NAME_TYPE = "type"; public final String COLUMN_NAME_RESULT = "rawresult"; private final String TABLE_NAME_SCAN = "barcode_entries"; private final String TABLE_NAME_ENCODE = "encode_entries"; TableStructure(boolean isEncodeTable){ TABLE_NAME=(isEncodeTable)? TABLE_NAME_ENCODE : TABLE_NAME_SCAN; } } private final TableStructure FeedEntry; private final String SQL_CREATE_TABLE, SQL_DROP_TABLE, sortOrder, SQL_COUNT; private final String[] projection; public HistoryDbHelper(Context context, String name, CursorFactory factory, int version, boolean isReadingEncodeHistory) { super(context, name, factory, version); FeedEntry = new TableStructure(isReadingEncodeHistory); isEncode = isReadingEncodeHistory; SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + FeedEntry.TABLE_NAME + " (" + FeedEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + FeedEntry.COLUMN_NAME_TIME + " BIGINT NOT NULL," + FeedEntry.COLUMN_NAME_TEXT + " VARCHAR(128)," + FeedEntry.COLUMN_NAME_TYPE + " VARCHAR(128) NOT NULL," + FeedEntry.COLUMN_NAME_RESULT + " VARCHAR(255) NOT NULL" +" )"; SQL_DROP_TABLE = "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME; sortOrder=FeedEntry._ID + " DESC"; SQL_COUNT="SELECT COUNT(*) FROM " +FeedEntry.TABLE_NAME+" WHERE "+FeedEntry._ID+" = ?"; projection = new String[]{ FeedEntry._ID, FeedEntry.COLUMN_NAME_TIME, FeedEntry.COLUMN_NAME_TEXT, FeedEntry.COLUMN_NAME_TYPE, FeedEntry.COLUMN_NAME_RESULT }; } @Override public void onCreate(SQLiteDatabase db) { // TODO Create table here, notice that this is called only if a new db is initialized db.execSQL(SQL_CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){ } public long insertEntry(long time, String description, String type, String resultPath){ if(time<1 || description ==null || description.isEmpty() || type ==null || type.isEmpty() || resultPath ==null || resultPath.isEmpty()) return -1; try{ SQLiteDatabase db=this.getWritableDatabase(); db.execSQL(SQL_CREATE_TABLE); ContentValues values = new ContentValues(); values.put(FeedEntry.COLUMN_NAME_TIME, time); values.put(FeedEntry.COLUMN_NAME_TEXT, description); values.put(FeedEntry.COLUMN_NAME_TYPE, type); values.put(FeedEntry.COLUMN_NAME_RESULT, resultPath); long newRowId = db.insert(FeedEntry.TABLE_NAME,null,values); //return (newRowId >-1)? true:false; return newRowId; }catch(Exception e2){ //Log.d(TAG, "Something wrong on data insertion : "+e2.toString()+e2.getMessage()); } return -1; } /** * Get the latest entries * @param limit limit of number of entries * @return */ public HistoryDbEntry[] getLatestEntries(int limit){ // if limit less than 1, set no limit limit = (limit<1)? -1 : (limit >100)? 100 : limit; //TODO: return the data, how to deserialize the rawResult????? SQLiteDatabase db=this.getReadableDatabase(); Cursor c=null; try{ c = db.query(FeedEntry.TABLE_NAME,projection,null,null,null,null, sortOrder,(limit > 0)? ""+limit : null); }catch(Exception e2){ //Something goes wrong, try to reinitialize the db db.execSQL(SQL_CREATE_TABLE); } if(c==null) return null; int count=c.getCount(); if(count >0){ HistoryDbEntry[] results = new HistoryDbEntry[count]; c.moveToFirst(); for(int i=0;i<count;i++){ try{ HistoryDbEntry entry = new HistoryDbEntry( c.getInt(c.getColumnIndexOrThrow(FeedEntry._ID)), c.getLong(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_TIME)), c.getString(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_TEXT)), c.getString(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_TYPE)), c.getString(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_RESULT)) ); results[i]=entry; }catch(Exception e2){ results[i]=null; } if(!c.moveToNext()) break; } c.close(); return results; } c.close(); return null; } public HistoryDbEntry[] getEntriesLaterThan(Long lastUpdateTime){ SQLiteDatabase db=this.getReadableDatabase(); Cursor c=null; try{ c = db.query(FeedEntry.TABLE_NAME,projection,"time > "+lastUpdateTime,null,null,null, FeedEntry._ID + " ASC",null); }catch(Exception e2){ //Something goes wrong, try to reinitialize the db db.execSQL(SQL_CREATE_TABLE); } if(c==null) return null; int count=c.getCount(); if(count >0){ HistoryDbEntry[] results = new HistoryDbEntry[count]; c.moveToFirst(); for(int i=0;i<count;i++){ try{ HistoryDbEntry entry = new HistoryDbEntry( c.getInt(c.getColumnIndexOrThrow(FeedEntry._ID)), c.getLong(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_TIME)), c.getString(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_TEXT)), c.getString(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_TYPE)), c.getString(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_RESULT)) ); results[i]=entry; }catch(Exception e2){ results[i]=null; } if(!c.moveToNext()) break; } c.close(); return results; } c.close(); return null; } public boolean deleteEntry(int id){ SQLiteDatabase db=this.getWritableDatabase(); String whereClause = FeedEntry._ID+" = ?"; String[] whereArgs = { String.valueOf(id) }; Cursor c=db.rawQuery(SQL_COUNT, whereArgs); c.moveToFirst(); int count=c.getInt(0); c.close(); if(count <1) return true; //It is already deleted. count=db.delete(FeedEntry.TABLE_NAME, whereClause, whereArgs); return (count>0); } public int updateEntry(int id, String description) { SQLiteDatabase db=this.getWritableDatabase(); String whereClause = FeedEntry._ID+" = ?"; String[] whereArgs = { String.valueOf(id) }; Cursor c=db.rawQuery(SQL_COUNT, whereArgs); int count = c.getCount(); int recUpdated = 0; if (count == 1){ //can only edit one record c.moveToFirst(); ContentValues values = new ContentValues(); values.put(FeedEntry.COLUMN_NAME_TEXT, description); recUpdated = db.update(FeedEntry.TABLE_NAME, values, whereClause, whereArgs); } c.close(); return recUpdated; } public HistoryDbEntry findEntry(long id) { HistoryDbEntry entry = null; SQLiteDatabase db = this.getWritableDatabase(); String whereClause = FeedEntry._ID+" = ?"; String[] whereArgs = { String.valueOf(id) }; Cursor c = db.query(FeedEntry.TABLE_NAME, projection, whereClause, whereArgs, null, null, null); int count = c.getCount(); if (count == 1) { c.moveToFirst(); entry = new HistoryDbEntry( c.getInt(c.getColumnIndexOrThrow(FeedEntry._ID)), c.getLong(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_TIME)), c.getString(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_TEXT)), c.getString(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_TYPE)), c.getString(c.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_RESULT)) ); c.close(); } return entry; } }
28,225
https://github.com/alienworks/state-of-neo-server/blob/master/StateOfNeo/StateOfNeo.Data/Migrations/20180616183930_Initial.Designer.cs
Github Open Source
Open Source
MIT
2,020
state-of-neo-server
alienworks
C#
Code
212
1,569
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using StateOfNeo.Data; namespace StateOfNeo.Data.Migrations { [DbContext(typeof(StateOfNeoContext))] [Migration("20180616183930_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.0-rtm-30799") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("StateOfNeo.Data.Models.BlockchainInfo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>("BlockCount"); b.Property<string>("Net"); b.Property<decimal>("SecondsCount") .HasConversion(new ValueConverter<decimal, decimal>(v => default(decimal), v => default(decimal), new ConverterMappingHints(precision: 20, scale: 0))); b.HasKey("Id"); b.ToTable("BlockchainInfos"); }); modelBuilder.Entity("StateOfNeo.Data.Models.MainNetBlockInfo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal>("BlockHeight") .HasConversion(new ValueConverter<decimal, decimal>(v => default(decimal), v => default(decimal), new ConverterMappingHints(precision: 20, scale: 0))); b.Property<int>("SecondsCount"); b.Property<long>("TxCount"); b.Property<long>("TxNetworkFees"); b.Property<long>("TxOutputValues"); b.Property<long>("TxSystemFees"); b.HasKey("Id"); b.ToTable("MainNetBlockInfos"); }); modelBuilder.Entity("StateOfNeo.Data.Models.Node", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("FlagUrl"); b.Property<int?>("Height"); b.Property<double?>("Latitude"); b.Property<string>("Locale"); b.Property<string>("Location"); b.Property<double?>("Longitude"); b.Property<int?>("MemoryPool"); b.Property<string>("Net"); b.Property<int?>("Peers"); b.Property<string>("Protocol"); b.Property<string>("SuccessUrl"); b.Property<int>("Type"); b.Property<string>("Url"); b.Property<string>("Version"); b.HasKey("Id"); b.ToTable("Nodes"); }); modelBuilder.Entity("StateOfNeo.Data.Models.NodeAddress", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Ip"); b.Property<int>("NodeId"); b.Property<long?>("Port"); b.Property<int>("Type"); b.HasKey("Id"); b.HasIndex("NodeId"); b.ToTable("NodeAddresses"); }); modelBuilder.Entity("StateOfNeo.Data.Models.TestNetBlockInfo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<decimal>("BlockHeight") .HasConversion(new ValueConverter<decimal, decimal>(v => default(decimal), v => default(decimal), new ConverterMappingHints(precision: 20, scale: 0))); b.Property<int>("SecondsCount"); b.Property<long>("TxCount"); b.Property<long>("TxNetworkFees"); b.Property<long>("TxOutputValues"); b.Property<long>("TxSystemFees"); b.HasKey("Id"); b.ToTable("TestNetBlockInfos"); }); modelBuilder.Entity("StateOfNeo.Data.Models.TimeEvent", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreatedOn"); b.Property<DateTime?>("LastDownTime"); b.Property<int?>("NodeId"); b.Property<int>("Type"); b.HasKey("Id"); b.HasIndex("NodeId"); b.ToTable("TimeEvents"); }); modelBuilder.Entity("StateOfNeo.Data.Models.NodeAddress", b => { b.HasOne("StateOfNeo.Data.Models.Node", "Node") .WithMany("NodeAddresses") .HasForeignKey("NodeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("StateOfNeo.Data.Models.TimeEvent", b => { b.HasOne("StateOfNeo.Data.Models.Node") .WithMany("Events") .HasForeignKey("NodeId"); }); #pragma warning restore 612, 618 } } }
25,746
https://github.com/CccZss/Album/blob/master/project/src/components/home/myUpload.vue
Github Open Source
Open Source
MIT
null
Album
CccZss
Vue
Code
172
666
<template> <div class="wrap"> <ul class="menu"> <li @click="addAlbumHandel"><Icon type="ios-folder"></Icon> 新建相册</li> </ul> <div class="album-wrap"> <albumItem v-for="item in albumList" :key="item.albumId" :albumInfo="item" ></albumItem> </div> <Modal v-model="showAddAlbumModel" title="请输入相册名" @on-ok="ok"> <Input v-model="albumName"/> </Modal> </div> </template> <script> import { mapState, mapActions } from 'vuex' import albumItem from './albumItem' export default { data () { return { showAddAlbumModel: false, albumName: '' } }, computed: { ...mapState({ albumList: state => { return state.album.albumList } }) }, components: { albumItem }, methods: { ...mapActions({ getAllAlbum: 'album/getAllAlbum', addAlbum: 'album/addAlbum' }), addAlbumHandel () { this.showAddAlbumModel = true }, ok () { this.addAlbum({ albumName: this.albumName }).then(data => { if (data.state) { this.albumName = '' this.$Message.success(data.info) } else { this.$Message.error(data.info) } }).catch(err => { console.log(err) }) } }, mounted () { this.getAllAlbum().then(data => { if (!data.state) { this.$Message.error(data.info) this.$router.push({ name: 'login' }) } }).catch(err => { console.log(err) }) } } </script> <style scoped> .wrap { background-color: #f4f4f4; } .menu { background-color: #fbfbfb; padding-left: 100px; } .menu li { color: #777; font-size: 13px; cursor: pointer; line-height: 50px; display: inline-block; } .album-wrap { padding: 40px 80px; } </style>
51,123
https://github.com/tobykurien/Ruby101/blob/master/exercises/exercise2.rb
Github Open Source
Open Source
MIT
2,021
Ruby101
tobykurien
Ruby
Code
113
251
# Add functionality to numbers and time # Time works on seconds for arthimetic module NumExtras def days self * 60 * 60 * 24 end def weeks days * 7 end def months days * 30 end def years days * 365.25 end def ago Time.new - self end def from_now Time.new + self end end class Fixnum include NumExtras end class Float include NumExtras end class Time def weekday ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][wday] end end puts "Five days from now will be %p" % (Time.new + 5.days) puts "Seven weeks ago was %p" % 7.weeks.ago puts "Two years from now it will be %s a " % 2.years.from_now.weekday
35,607
https://github.com/sergv/alex/blob/master/src/Data/Ranged/RangedSet.hs
Github Open Source
Open Source
2,023
alex
sergv
Haskell
Code
1,109
2,373
module Data.Ranged.RangedSet ( -- ** Ranged Set Type RSet, rSetRanges, -- ** Ranged Set construction functions and their preconditions makeRangedSet, unsafeRangedSet, validRangeList, normaliseRangeList, rSingleton, rSetUnfold, -- ** Predicates rSetIsEmpty, rSetIsFull, (-?-), rSetHas, (-<=-), rSetIsSubset, (-<-), rSetIsSubsetStrict, -- ** Set Operations (-\/-), rSetUnion, (-/\-), rSetIntersection, (-!-), rSetDifference, rSetNegation, -- ** Useful Sets rSetEmpty, rSetFull, ) where import Data.Ranged.Boundaries import Data.Ranged.Ranges #if MIN_VERSION_base(4,9,0) && !MIN_VERSION_base(4,11,0) import Data.Semigroup #elif !MIN_VERSION_base(4,9,0) import Data.Monoid #endif import Data.List hiding (and, null) infixl 7 -/\- infixl 6 -\/-, -!- infixl 5 -<=-, -<-, -?- -- | An RSet (for Ranged Set) is a list of ranges. The ranges must be sorted -- and not overlap. newtype DiscreteOrdered v => RSet v = RSet {rSetRanges :: [Range v]} deriving (Eq, Show, Ord) #if MIN_VERSION_base(4,9,0) instance DiscreteOrdered a => Semigroup (RSet a) where (<>) = rSetUnion #endif instance DiscreteOrdered a => Monoid (RSet a) where #if MIN_VERSION_base(4,9,0) mappend = (<>) #else mappend = rSetUnion #endif mempty = rSetEmpty -- | Determine if the ranges in the list are both in order and non-overlapping. -- If so then they are suitable input for the unsafeRangedSet function. validRangeList :: DiscreteOrdered v => [Range v] -> Bool validRangeList [] = True validRangeList [Range lower upper] = lower <= upper validRangeList rs = and $ zipWith okAdjacent rs (tail rs) where okAdjacent (Range lower1 upper1) (Range lower2 upper2) = lower1 <= upper1 && upper1 <= lower2 && lower2 <= upper2 -- | Rearrange and merge the ranges in the list so that they are in order and -- non-overlapping. normaliseRangeList :: DiscreteOrdered v => [Range v] -> [Range v] normaliseRangeList = normalise . sort . filter (not . rangeIsEmpty) -- Private routine: normalise a range list that is known to be already sorted. -- This precondition is not checked. normalise :: DiscreteOrdered v => [Range v] -> [Range v] normalise (r1:r2:rs) = if overlap r1 r2 then normalise $ Range (rangeLower r1) (max (rangeUpper r1) (rangeUpper r2)) : rs else r1 : (normalise $ r2 : rs) where overlap (Range _ upper1) (Range lower2 _) = upper1 >= lower2 normalise rs = rs -- | Create a new Ranged Set from a list of ranges. The list may contain -- ranges that overlap or are not in ascending order. makeRangedSet :: DiscreteOrdered v => [Range v] -> RSet v makeRangedSet = RSet . normaliseRangeList -- | Create a new Ranged Set from a list of ranges. @validRangeList ranges@ -- must return @True@. This precondition is not checked. unsafeRangedSet :: DiscreteOrdered v => [Range v] -> RSet v unsafeRangedSet = RSet -- | Create a Ranged Set from a single element. rSingleton :: DiscreteOrdered v => v -> RSet v rSingleton v = unsafeRangedSet [singletonRange v] -- | True if the set has no members. rSetIsEmpty :: DiscreteOrdered v => RSet v -> Bool rSetIsEmpty = null . rSetRanges -- | True if the negation of the set has no members. rSetIsFull :: DiscreteOrdered v => RSet v -> Bool rSetIsFull = rSetIsEmpty . rSetNegation -- | True if the value is within the ranged set. Infix precedence is left 5. rSetHas, (-?-) :: DiscreteOrdered v => RSet v -> v -> Bool rSetHas (RSet ls) value = rSetHas1 ls where rSetHas1 [] = False rSetHas1 (r:rs) | value />/ rangeLower r = rangeHas r value || rSetHas1 rs | otherwise = False (-?-) = rSetHas -- | True if the first argument is a subset of the second argument, or is -- equal. -- -- Infix precedence is left 5. rSetIsSubset, (-<=-) :: DiscreteOrdered v => RSet v -> RSet v -> Bool rSetIsSubset rs1 rs2 = rSetIsEmpty (rs1 -!- rs2) (-<=-) = rSetIsSubset -- | True if the first argument is a strict subset of the second argument. -- -- Infix precedence is left 5. rSetIsSubsetStrict, (-<-) :: DiscreteOrdered v => RSet v -> RSet v -> Bool rSetIsSubsetStrict rs1 rs2 = rSetIsEmpty (rs1 -!- rs2) && not (rSetIsEmpty (rs2 -!- rs1)) (-<-) = rSetIsSubsetStrict -- | Set union for ranged sets. Infix precedence is left 6. rSetUnion, (-\/-) :: DiscreteOrdered v => RSet v -> RSet v -> RSet v -- Implementation note: rSetUnion merges the two lists into a single -- sorted list and then calls normalise to combine overlapping ranges. rSetUnion (RSet ls1) (RSet ls2) = RSet $ normalise $ merge ls1 ls2 where merge ms1 [] = ms1 merge [] ms2 = ms2 merge ms1@(h1:t1) ms2@(h2:t2) = if h1 < h2 then h1 : merge t1 ms2 else h2 : merge ms1 t2 (-\/-) = rSetUnion -- | Set intersection for ranged sets. Infix precedence is left 7. rSetIntersection, (-/\-) :: DiscreteOrdered v => RSet v -> RSet v -> RSet v rSetIntersection (RSet ls1) (RSet ls2) = RSet $ filter (not . rangeIsEmpty) $ merge ls1 ls2 where merge ms1@(h1:t1) ms2@(h2:t2) = rangeIntersection h1 h2 : if rangeUpper h1 < rangeUpper h2 then merge t1 ms2 else merge ms1 t2 merge _ _ = [] (-/\-) = rSetIntersection -- | Set difference. Infix precedence is left 6. rSetDifference, (-!-) :: DiscreteOrdered v => RSet v -> RSet v -> RSet v rSetDifference rs1 rs2 = rs1 -/\- (rSetNegation rs2) (-!-) = rSetDifference -- | Set negation. rSetNegation :: DiscreteOrdered a => RSet a -> RSet a rSetNegation set = RSet $ ranges1 $ setBounds1 where ranges1 (b1:b2:bs) = Range b1 b2 : ranges1 bs ranges1 [BoundaryAboveAll] = [] ranges1 [b] = [Range b BoundaryAboveAll] ranges1 _ = [] setBounds1 = case setBounds of (BoundaryBelowAll : bs) -> bs _ -> BoundaryBelowAll : setBounds setBounds = bounds $ rSetRanges set bounds (r:rs) = rangeLower r : rangeUpper r : bounds rs bounds _ = [] -- | The empty set. rSetEmpty :: DiscreteOrdered a => RSet a rSetEmpty = RSet [] -- | The set that contains everything. rSetFull :: DiscreteOrdered a => RSet a rSetFull = RSet [Range BoundaryBelowAll BoundaryAboveAll] -- | Construct a range set. rSetUnfold :: DiscreteOrdered a => Boundary a -- ^ A first lower boundary. -> (Boundary a -> Boundary a) -- ^ A function from a lower boundary to an upper boundary, which must -- return a result greater than the argument (not checked). -> (Boundary a -> Maybe (Boundary a)) -- ^ A function from a lower boundary to @Maybe@ the successor lower -- boundary, which must return a result greater than the argument -- (not checked). If ranges overlap then they will be merged. -> RSet a rSetUnfold bound upperFunc succFunc = RSet $ normalise $ ranges1 bound where ranges1 b = Range b (upperFunc b) : case succFunc b of Just b2 -> ranges1 b2 Nothing -> []
16,117
https://github.com/kreid333/bandwich/blob/master/public/js/scripts.js
Github Open Source
Open Source
MIT
2,023
bandwich
kreid333
JavaScript
Code
1,911
6,210
$(document).ready(function () { // jQuery targeting the big record/pause/stop buttons // feel free to change html ids to match those in handlebars. const mainRecordEl = $("#main-record"); const mainStopEl = $("#main-stop"); const mainPauseEl = $("#main-pause"); const saveTrackEl = $("#name-input"); const editTrackEl = $("#new-name"); const newProjectEl = $("#new-project"); const recIcon = $("#rec-icon"); const countdownEl = $("#count"); const trackOne = $("#track-one"); const trackTwo = $("#track-two"); const trackThree = $("#track-three"); const trackFour = $("#track-four"); // click events on the big record/pause/stop buttons mainRecordEl.on("click", function () { // conditional ensures a track is enabled and no audio stream is currently active if (track && !input) { let time = 3; countdownEl.css("display", "block") setTimeout(function() { // start record function is called with playAll audio as a callback for synchronous play/record startRecord(playAll); }, 3000); // countdown timer for the 3 second record delay const timeout = setInterval(function() { time--; countdownEl.text(time); if (time === 0) { clearInterval(timeout); countdownEl.css("display", "none") } }, 1000) } else if (!track) { alert("Please record enable one of the tracks!"); } }); mainStopEl.on("click", stopRecord); mainPauseEl.on("click", pauseRecord); URL = window.URL || window.webkitURL; let gumStream; let rec; let input; let track; let meter; const AudioContext = window.AudioContext || window.webkitAudioContext; function startRecord(cb) { console.log("record!"); recIcon.addClass("pulsing"); const audioContext = new AudioContext(); const constraints = { audio: true, video: false, }; mainRecordEl.disabled = true; mainStopEl.disabled = false; mainPauseEl.disabled = false; cb(); navigator.mediaDevices .getUserMedia(constraints) .then(function (stream) { console.log("getUserMedia success"); gumStream = stream; input = audioContext.createMediaStreamSource(stream); // recorder.js constructor rec = new Recorder(input, { // mono sound numChannels: 1, }); //start the recording process rec.record(); console.log("Recording started"); // creates the audio level meter meter = createAudioMeter(audioContext); input.connect(meter); // kick off the visual updating drawLoop(); }) .catch(function (err) { //enable the record button if getUserMedia() fails mainRecordEl.disabled = false; mainStopEl.disabled = true; mainPauseEl.disabled = true; }); } function pauseRecord() { console.log("Recording paused", rec.recording); recIcon.removeClass("pulsing"); if (rec.recording) { // pause rec.stop(); // here maybe we can target the pause button (mainPauseEl) and get it to blink/change color } else { // resume rec.record(); // same for here } } function stopRecord() { if (input) { console.log("Recording stopped"); //disable the stop button, enable the record too allow for new recordings mainRecordEl.disabled = false; mainStopEl.disabled = true; mainPauseEl.disabled = true; // stops the recording and gets the track rec.stop(); gumStream.getAudioTracks()[0].stop(); // creates wav blob and passes blob as argument to the callback rec.exportWAV(convertToBase64); recIcon.removeClass("pulsing"); recIcon.removeAttr("id","glow"); } else { stopAll(); recIcon.removeClass("pulsing"); recIcon.removeAttr("id","glow"); } } function postAudio(data) { // sends the audio data from the client to the server via POST request $.ajax({ url: "/api/audio", type: "POST", data: data, success: function (response) { // const stopBtn = $("#main-stop") // stopBtn.empty(); // const postAudio = $("<p>").text("Posting audio...").attr("style", "text-align: center;"); // stopBtn.append(postAudio); // sets an interval before reloading page to allow big POST request setTimeout(function () { location.reload(); trackCheck(track); }, 3000); }, error: function (err) { if (err) { console.log(err); } } }) } function convertToBase64(blob) { const fileName = new Date().toISOString() + ".wav"; const reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = function () { const base64data = reader.result; postAudio({ // sent to server side app.post // contents: req.body.audio and req.body.file audio: JSON.stringify(base64data), path: fileName, id: $("#proj-name").data("id"), track: track, }); }; } function trackCheck(track) { if (track === 1) { enableTrack(trackOne) } if (track === 2) { enableTrack(trackTwo) } if (track === 3) { enableTrack(trackThree) } if (track === 4) { enableTrack(trackFour) } } function enableTrack(enabledTrack){ enabledTrack.addClass("recorded-track"); enabledTrack.children().eq(0).children().eq(1).removeClass("hide"); enabledTrack.children().eq(1).children().eq(0).removeClass("disable"); enabledTrack.children().eq(1).children().eq(1).children().eq(0).removeClass("disable"); } function playAll() { // prevents play button with no associated audio if (audioSrc1 === "/" && audioSrc2 === "/" && audioSrc3 === "/" && audioSrc4 === "/" && !mainRecordEl.disabled) { alert("There is no recorded audio to play!") } else { // plays each audio track if exists if (audioSrc1 !== "/") { audio1.load(); audio1.play(); } if (audioSrc2 !== "/") { audio2.load(); audio2.play(); } if (audioSrc3 !== "/") { audio3.load(); audio3.play(); } if (audioSrc4 !== "/") { audio4.load(); audio4.play(); } } } function stopAll() { if (audioSrc1 !== "/") { audio1.pause(); } if (audioSrc2 !== "/") { audio2.pause(); } if (audioSrc3 !== "/") { audio3.pause(); } if (audioSrc4 !== "/") { audio4.pause(); } } function enableActive() { if (audioSrc1 !== "/") { enableTrack(trackOne); } if (audioSrc2 !== "/") { enableTrack(trackTwo); } if (audioSrc3 !== "/") { enableTrack(trackThree); } if (audioSrc4 !== "/") { enableTrack(trackFour); } } // the following three functions are forked with permission from cwilso/volume-meter function createAudioMeter(audioContext, clipLevel, averaging, clipLag) { var processor = audioContext.createScriptProcessor(512); processor.onaudioprocess = volumeAudioProcess; processor.clipping = false; processor.lastClip = 0; processor.volume = 0; processor.clipLevel = clipLevel || 0.98; processor.averaging = averaging || 0.95; processor.clipLag = clipLag || 750; processor.connect(audioContext.destination); processor.checkClipping = function () { if (!this.clipping) return false; if (this.lastClip + this.clipLag < window.performance.now()) this.clipping = false; return this.clipping; }; processor.shutdown = function () { this.disconnect(); this.onaudioprocess = null; }; return processor; } function volumeAudioProcess(event) { var buf = event.inputBuffer.getChannelData(0); var bufLength = buf.length; var sum = 0; var x; for (var i = 0; i < bufLength; i++) { x = buf[i]; if (Math.abs(x) >= this.clipLevel) { this.clipping = true; this.lastClip = window.performance.now(); } sum += x * x; } var rms = Math.sqrt(sum / bufLength); this.volume = Math.max(rms, this.volume * this.averaging); } function drawLoop(time) { let WIDTH = 300; let HEIGHT = 500; const canvas = document.getElementById("myCanvas" + track).getContext("2d"); canvas.clearRect(0, 0, WIDTH, HEIGHT); if (meter.checkClipping()) canvas.fillStyle = "red"; else canvas.fillStyle = "blue"; canvas.fillRect(0, 0, WIDTH, meter.volume * HEIGHT * 1.4); rafID = window.requestAnimationFrame(drawLoop); } let switchStatus = false; $(".check").on("change", function () { if ($(this).is(":checked")) { switchStatus = $(this).is(":checked"); track = $(this).data("track"); $( ".switch" ).css( "pointer-events", "none" ); $(this).parent().css("pointer-events", "initial"); recIcon.attr("id","glow"); } else { switchStatus = $(this).is(":checked"); recIcon.removeAttr("id","glow"); $( ".switch" ).css( "pointer-events", "initial" ); } }); // When new project button is clicked it sends user info (IP adress at some point...) // Promise is a reassign for the created project newProjectEl.on("click", function () { $.ajax("/api/project", { type: "POST", data: "userIpAddress", }).then(function (project) { location.assign("/workstation/" + project.id); }); }); saveTrackEl.on("click", function () { console.log(this.children[0].innerHTML); var currentTitle = this.children[0].innerHTML; $("#proj-name").hide(); $("#new-name").show(); $("#new-name").val(currentTitle); $("#new-name").focus(); }); editTrackEl.on("blur", function () { $("#new-name").hide(); $("#proj-name").show(); }); // when a user hits the save button it captures the text in the form and posts the song name // the post route in api-routes.js creates a new project in the database saveTrackEl.on("submit", function (event) { event.preventDefault(); const projectName = { name: $("#new-name").val(), id: $("#proj-name").data("id"), }; $.ajax("/api/project", { type: "PUT", data: projectName, }).then(function (project) { location.assign("/workstation/" + project); }); }); // when user hits the search-btn $("#projectsearch-btn").on("click", function () { // save the character they typed into the character-search input var searchedProject = $("#projects-search").val().trim(); console.log("click works"); console.log(searchedProject); // Using a RegEx Pattern to remove spaces from searchedCharacter // searchedProject = searchedProject.replace(/\s+/g, "").toLowerCase(); // run an AJAX GET-request for our servers api, // including the user's character in the url $.get("/api/projects/" + searchedProject, function (data) { // log the data to our console console.log(data); console.log("Get works"); // empty to well-section before adding new content $("#results-section").empty(); // if the data is not there, then return an error message if (data) { window.location.assign("/projects/" + searchedProject); } else { window.location.assign("/projects/no-results"); } }); }); // PLAY BTN FOR EACH TRACK // ======================================================== const mainPlayEl = $("#main-play"); const playBtn1 = $("#playBtn1"); const playBtn2 = $("#playBtn2"); const playBtn3 = $("#playBtn3"); const playBtn4 = $("#playBtn4"); const audioId1 = $("#audio1"); const audioId2 = $("#audio2"); const audioId3 = $("#audio3"); const audioId4 = $("#audio4"); var count1 = 0; var count2 = 0; var count3 = 0; var count4 = 0; var playPauseReset = 2; const audioSrc1 = audioId1.attr("src"); const audio1 = new Audio(audioSrc1); const audioSrc2 = audioId2.attr("src"); const audio2 = new Audio(audioSrc2); const audioSrc3 = audioId3.attr("src"); const audio3 = new Audio(audioSrc3); const audioSrc4 = audioId4.attr("src"); const audio4 = new Audio(audioSrc4); mainPlayEl.on("click", function () { playAll(); }); playBtn1.on("click", function () { if (count1 === 0) { playAudio(); playBtn1.removeClass("fas fa-play-circle"); playBtn1.addClass("fas fa-pause-circle"); console.log("Playing"); } else if (count1 === 1) { pauseAudio(); playBtn1.removeClass("fas fa-pause-circle"); playBtn1.addClass("fas fa-play-circle"); console.log("Stopping"); } count1 += 1; if (count1 === playPauseReset) count1 = 0; function playAudio() { audio1.play(); audio1.onended = function () { playBtn1.removeClass("fas fa-pause-circle"); playBtn1.addClass("fas fa-play-circle"); count1 = 0; }; } function pauseAudio() { audio1.pause(); } }); playBtn2.on("click", function () { if (count2 === 0) { playAudio(); playBtn2.removeClass("fas fa-play-circle"); playBtn2.addClass("fas fa-pause-circle"); console.log("Playing"); } else if (count2 === 1) { pauseAudio(); playBtn2.removeClass("fas fa-pause-circle"); playBtn2.addClass("fas fa-play-circle"); console.log("Stopping"); } count2 += 1; if (count2 === playPauseReset) count2 = 0; function playAudio() { audio2.play(); audio2.onended = function () { playBtn2.removeClass("fas fa-pause-circle"); playBtn2.addClass("fas fa-play-circle"); count2 = 0; }; } function pauseAudio() { audio2.pause(); } }); playBtn3.on("click", function () { if (count3 === 0) { playAudio(); playBtn3.removeClass("fas fa-play-circle"); playBtn3.addClass("fas fa-pause-circle"); console.log("Playing"); } else if (count3 === 1) { pauseAudio(); playBtn3.removeClass("fas fa-pause-circle"); playBtn3.addClass("fas fa-play-circle"); console.log("Stopping"); } count3 += 1; if (count3 === playPauseReset) count3 = 0; function playAudio() { audio3.play(); audio3.onended = function () { playBtn3.removeClass("fas fa-pause-circle"); playBtn3.addClass("fas fa-play-circle"); count3 = 0; }; } function pauseAudio() { audio3.pause(); } }); playBtn4.on("click", function () { if (count4 === 0) { playAudio(); playBtn4.removeClass("fas fa-play-circle"); playBtn4.addClass("fas fa-pause-circle"); console.log("Playing"); } else if (count4 === 1) { pauseAudio(); playBtn4.removeClass("fas fa-pause-circle"); playBtn4.addClass("fas fa-play-circle"); console.log("Stopping"); } count4 += 1; if (count4 === playPauseReset) count4 = 0; function playAudio() { audio4.play(); audio4.onended = function () { playBtn4.removeClass("fas fa-pause-circle"); playBtn4.addClass("fas fa-play-circle"); count4 = 0; }; } function pauseAudio() { audio4.pause(); } }); $(".home").on("click", function () { location.assign("/"); }); function disableTrack(button){ button.css("display","none"); button.parent().next().children().eq(0).addClass("disable"); button.parent().next().children().eq(1).children().eq(0).addClass("disable"); button.parent().parent().removeClass("recorded-track"); } $("#destroyBtn1").on("click", function () { disableTrack($("#destroyBtn1")); let gettingID = audioId1.attr("src"); gettingID = gettingID.split(""); let newID = []; for (let i = 0; i < gettingID.length; i++) { const parsedAudioName = parseInt(gettingID[i]); if (isNaN(parsedAudioName) === false && typeof parsedAudioName === "number") { newID.push(parsedAudioName); } } newID = parseInt(newID.join("")); console.log(newID); // gettingID = parseFloat(gettingID.pop()); audioId1.attr("src", "/"); $.ajax({ url: `/api/audio/${newID}`, method: "DELETE", success: function () { setTimeout(function () { location.reload(); }, 1000); console.log(111); }, }); }); $("#destroyBtn2").on("click", function () { disableTrack($("#destroyBtn2")); let gettingID = audioId2.attr("src"); gettingID = gettingID.split(""); let newID = []; for (let i = 0; i < gettingID.length; i++) { const parsedAudioName = parseInt(gettingID[i]); if (isNaN(parsedAudioName) === false && typeof parsedAudioName === "number") { newID.push(parsedAudioName); } } newID = parseInt(newID.join("")); console.log(newID); // gettingID = parseFloat(gettingID.pop()); audioId2.attr("src", "/"); $.ajax({ url: `/api/audio/${newID}`, method: "DELETE", success: function () { setTimeout(function () { location.reload(); }, 1000); console.log(111); }, }); }); $("#destroyBtn3").on("click", function () { disableTrack($("#destroyBtn3")); let gettingID = audioId3.attr("src"); gettingID = gettingID.split(""); let newID = []; for (let i = 0; i < gettingID.length; i++) { const parsedAudioName = parseInt(gettingID[i]); if (isNaN(parsedAudioName) === false && typeof parsedAudioName === "number") { newID.push(parsedAudioName); } } newID = parseInt(newID.join("")); console.log(newID); // gettingID = parseFloat(gettingID.pop()); audioId3.attr("src", "/"); $.ajax({ url: `/api/audio/${newID}`, method: "DELETE", success: function () { setTimeout(function () { location.reload(); }, 1000); console.log(111); }, }); }); $("#destroyBtn4").on("click", function () { disableTrack($("#destroyBtn4")); let gettingID = audioId4.attr("src"); gettingID = gettingID.split(""); let newID = []; for (let i = 0; i < gettingID.length; i++) { const parsedAudioName = parseInt(gettingID[i]); if (isNaN(parsedAudioName) === false && typeof parsedAudioName === "number") { newID.push(parsedAudioName); } } newID = parseInt(newID.join("")); console.log(newID); // gettingID = parseFloat(gettingID.pop()); audioId4.attr("src", "/"); $.ajax({ url: `/api/audio/${newID}`, method: "DELETE", success: function () { setTimeout(function () { location.reload(); }, 1000); console.log(111); }, }); }); $("#deleteproject-btn").on("click", function () { var deleteAlert = confirm("Are you sure you would like to delete this project?"); if(deleteAlert) { const projectName = { name: $("#new-name").val(), id: $("#proj-name").data("id"), }; $.ajax("/api/project/" + projectName.id, { type: "DELETE", data: projectName, }).then(function () { location.assign("/"); }); } }) // VOLUME SLIDERS $("#volumeSlider1").on("input", function(){ audio1.volume = $("#volumeSlider1").val(); }) $("#volumeSlider2").on("input", function(){ audio2.volume = $("#volumeSlider2").val(); }) $("#volumeSlider3").on("input", function(){ audio3.volume = $("#volumeSlider3").val(); }) $("#volumeSlider4").on("input", function(){ audio4.volume = $("#volumeSlider4").val(); }) // checks to see which tracks have content and toggles active state enableActive(); });
49,199
https://github.com/tofi86/readium-desktop/blob/master/src/common/redux/actions/downloader.ts
Github Open Source
Open Source
BSD-3-Clause
null
readium-desktop
tofi86
TypeScript
Code
155
467
import { Download } from "readium-desktop/common/models/download"; import { Action, ErrorAction } from "readium-desktop/common/models/redux"; export enum ActionType { AddRequest = "DOWNLOAD_ADD_REQUEST", AddSuccess = "DOWNLOAD_ADD_SUCCESS", PostProcess = "DOWNLOAD_POST_PROCESS", Error = "DOWNLOAD_ERROR", Success = "DOWNLOAD_SUCCESS", Progress = "DOWNLOAD_PROGRESS", CancelRequest = "DOWNLOAD_CANCEL_REQUEST", CancelSuccess = "DOWNLOAD_CANCEL_SUCCESS", } export function add(download: Download): Action { return { type: ActionType.AddRequest, payload: { download, }, }; } export function start(download: Download): Action { return { type: ActionType.AddSuccess, payload: { download, }, }; } export function progress(download: Download, progressValue: number): Action { return { type: ActionType.Progress, payload: { download, progress: progressValue, }, }; } export function finish(download: Download): Action { return { type: ActionType.Success, payload: { download, }, }; } export function fail(download: Download, errorMsg: string): ErrorAction { const error = new Error(errorMsg); return { type: ActionType.Error, payload: { download, }, error: true, meta: { download, }, }; } export function cancel(download: Download): Action { return { type: ActionType.CancelRequest, payload: { download, }, }; }
32,086
https://github.com/slimthierry/MlmRepository/blob/master/database/migrations/2020_06_16_190732_create_transactions.php
Github Open Source
Open Source
MIT
null
MlmRepository
slimthierry
PHP
Code
94
457
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTransactions extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('transactions', function (Blueprint $table) { $table->id(); // $table->unsignedInteger('account_id'); $table->unsignedInteger('client_membership_id'); // $table->string('currency', 3); $table->string('balance_before')->nullable()->default(0); $table->string('balance_after')->nullable()->default(0); $table->decimal('debit', 16, 4)->nullable(); $table->decimal('credit', 16, 4)->nullable(); // $table->enum('type', ['mobile', 'web']); // $table->decimal('label', 16,4)->nullable(0); // $table->decimal('amount', 16, 4); $table->string('payment_method')->nullable(); //paypal, stripe, paystack etc; $table->string('trans_status')->default('initiated'); //initiated, completed and payment failed, completed and successful; // $table->foreign('account_id','accounts')->references('id')->on('accounts')->onDelete('cascade'); $table->foreign('client_membership_id','clients_memberships')->references('id')->on('clients_memberships')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('transactions'); } }
6,151
https://github.com/isaqb-org/glossary/blob/master/docs/1-terms/H/term-hybrid-architecture-style.adoc
Github Open Source
Open Source
CC-BY-4.0
2,022
glossary
isaqb-org
AsciiDoc
Code
52
123
[#term-hybrid-architecture-style] // tag::EN[] ==== Hybrid Architecture Style Combination of two or more existing architecture styles or patterns. For example, an MVC construct embedded in a layer structure. // end::EN[] // tag::DE[] ==== Hybrider Architekturstil Kombination aus zwei oder mehreren existierenden Architekturstilen oder -mustern. Beispielsweise ein in eine Schichtstruktur eingebettetes MVC-Konstrukt. // end::DE[]
18,385
https://github.com/balakrishnavalluri-gep/eShopOnContainersAI/blob/master/src/Bots/Bot.Core.API/Dialogs/Catalog/CatalogDialog.cs
Github Open Source
Open Source
MIT
2,022
eShopOnContainersAI
balakrishnavalluri-gep
C#
Code
815
3,084
using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Schema; using Microsoft.Bot.Builder.Dialogs.Choices; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Microsoft.eShopOnContainers.Bot.API.Models.Basket; using Microsoft.Extensions.Logging; using Microsoft.Bot.Builder.TemplateManager; using Microsoft.eShopOnContainers.Bot.API.Dialogs.Shared; using Microsoft.eShopOnContainers.Bot.API.Dialogs.Basket; using Microsoft.eShopOnContainers.Bot.API.Dialogs.Login; using Microsoft.eShopOnContainers.Bot.API.Services.Catalog; using Microsoft.eShopOnContainers.Bot.API.Services.Basket; namespace Microsoft.eShopOnContainers.Bot.API.Dialogs.Catalog { public class CatalogDialog : ComponentDialog { public const string Name = nameof(CatalogDialog) + ".MainDriver"; private const string PromptProductQuantity = nameof(CatalogDialog) + "." + nameof(PromptProductQuantity); private const string PromptChoices = nameof(CatalogDialog) + "." + nameof(PromptChoices); private const string PromptNumber = nameof(CatalogDialog) + "." + nameof(PromptNumber); private readonly DomainPropertyAccessors accessors; private readonly ICatalogAIService catalogAIService; private readonly ICatalogService catalogService; private readonly IBasketService basketService; private readonly ILogger<CatalogDialog> logger; private TemplateManager sharedResponses = new Shared.SharedResponses(); public CatalogDialog(DomainPropertyAccessors accessors, ICatalogAIService catalogAIService, ICatalogService catalogService, IDialogFactory dialogFactory, IBasketService basketService, ILogger<CatalogDialog> logger) : base(Name) { this.accessors = accessors; this.catalogAIService = catalogAIService; this.catalogService = catalogService; this.basketService = basketService; this.logger = logger; AddDialog(new ChoicePrompt(PromptChoices, ChoiceValidator)); AddDialog(new NumberPrompt<int>(PromptNumber)); AddDialog(new WaterfallDialog(Name, new WaterfallStep[] { ShowProductCarouselStep, ProcessNextStep, ProcessChildDialogEnd })); AddDialog(new WaterfallDialog(PromptProductQuantity, new WaterfallStep[] { ShowProductPromptQuantity, ProcessProductPromptQuantity })); AddDialog(dialogFactory.LoginDialog); AddDialog(dialogFactory.BasketDialog); InitialDialogId = Name; } private Task<bool> ChoiceValidator(PromptValidatorContext<FoundChoice> promptContext, CancellationToken cancellationToken) { var isValidChoiceOrJson = promptContext.Recognized.Succeeded || JObjectHelper.TryParse(promptContext.Context.Activity.Text, out JObject json); return Task.FromResult(isValidChoiceOrJson); } private Task<DialogTurnResult> ProcessChildDialogEnd(WaterfallStepContext stepContext, CancellationToken cancellationToken) => stepContext.ReplaceDialogAsync(Id); private async Task<DialogTurnResult> ShowProductPromptQuantity(WaterfallStepContext dc, CancellationToken cancellationToken) { var productName = (dc.Options as BasketItem).ProductName; return await dc.PromptAsync(PromptNumber, new PromptOptions { Prompt = MessageFactory.Text($"How many '{productName}' do you want to buy?") }, cancellationToken); } private async Task<DialogTurnResult> ProcessProductPromptQuantity(WaterfallStepContext dc, CancellationToken cancellationToken) { var quantity = (int)dc.Result; var tempBasketItem = dc.Options as BasketItem; tempBasketItem.Quantity = quantity; var authUser = await accessors.AuthUserProperty.GetAsync(dc.Context); try { await basketService.AddItemToBasket(authUser.UserId, tempBasketItem, authUser.AccessToken); } catch (Exception ex) { logger.LogError(ex.Message); } return await dc.BeginDialogAsync(BasketDialog.Name); } private async Task<DialogTurnResult> ShowProductCarouselStep(WaterfallStepContext dc, CancellationToken cancellationToken) { var context = dc.Context; var catalogFilter = await accessors.CatalogFilterProperty.GetAsync(context); var products = await GetProducts(catalogFilter, catalogAIService, catalogService); int pageCount = (products.Count + CatalogFilterData.PageSize - 1) / CatalogFilterData.PageSize; if (products.Count != 0) { var authUser = await accessors.AuthUserProperty.GetAsync(dc.Context, () => new Models.User.AuthUser()); bool logged = authUser.IsAuthenticated; const bool supportsMarkdown = false; var text = $"Page {catalogFilter.PageIndex + 1} of {pageCount} ( {products.Count} items )"; var items = CatalogCarousel(products, logged, supportsMarkdown); await context.SendActivityAsync(MessageFactory.Carousel(items, text)); var choices = CreateNextChoices(catalogFilter.PageIndex, pageCount, logged).ToArray(); return await dc.PromptAsync(PromptChoices, new PromptOptions() { Prompt = MessageFactory.Text("choose one option"), Choices = choices.Select(c => c.Choice).ToList() }); } else { await context.SendActivitiesAsync(new[] { MessageFactory.Text("There are no results matching your search"), MessageFactory.Text("Type what do you want to do.") }); return await dc.EndDialogAsync(); } } private async Task<DialogTurnResult> ProcessNextStep(WaterfallStepContext dc, CancellationToken cancellationToken) { var context = dc.Context; var catalogFilter = await accessors.CatalogFilterProperty.GetAsync(context); var message = dc.Context.Activity.AsMessageActivity(); if (message != null && JObjectHelper.TryParse(message.Text, out JObject json, logger)) { var action = json.GetValue("ActionType").ToString(); if (action == BotActionTypes.AddBasket) { var tempBasketItem = new BasketItem { ProductName = json.GetValue("ProductName").ToString(), ProductId = json.GetValue("ProductId").ToString(), PictureUrl = json.GetValue("PictureUrl").ToString(), UnitPrice = json.GetValue("UnitPrice").ToObject<decimal>() }; return await dc.BeginDialogAsync(PromptProductQuantity, tempBasketItem); } } var foundChoice = dc.Result as FoundChoice; var selectedType = (dc.Result as FoundChoice).Value.ToLowerInvariant(); if (selectedType == "home") { await sharedResponses.ReplyWith(dc.Context, SharedResponses.TypeMore); return await dc.EndDialogAsync(); } else if (selectedType.ToLowerInvariant() == "login") { return await dc.BeginDialogAsync(LoginDialog.Name); } else if (selectedType == "show previous") { catalogFilter.PageIndex--; await accessors.CatalogFilterProperty.SetAsync(context, catalogFilter); return await dc.ReplaceDialogAsync(Id); } else { catalogFilter.PageIndex++; await accessors.CatalogFilterProperty.SetAsync(context, catalogFilter); return await dc.ReplaceDialogAsync(Id); } } private async Task<Models.Catalog.Catalog> GetProducts(CatalogFilterData ci, ICatalogAIService catalogAIService, ICatalogService catalogService) { int? brandId = -1; if (ci != null && !string.IsNullOrEmpty(ci.Brand)) { var brands = await catalogService.GetBrandsAsync(); brandId = Convert.ToInt32(brands.FirstOrDefault(b => b.Text.Equals(ci.Brand, StringComparison.InvariantCultureIgnoreCase))?.Id); } if (brandId < 1) brandId = null; int? typeId = -1; if (ci != null && !string.IsNullOrEmpty(ci.Type)) { var types = await catalogService.GetTypesAsync(); typeId = Convert.ToInt32(types.FirstOrDefault(b => b.Text.Equals(ci.Type, StringComparison.InvariantCultureIgnoreCase))?.Id); } if (typeId < 1) typeId = null; var products = ci.Tags != null && !ci.Tags.Any() ? Models.Catalog.Catalog.Empty : await catalogAIService.GetCatalogItems(ci.PageIndex, CatalogFilterData.PageSize, brandId, typeId, ci.Tags); return products; } private IEnumerable<(Choice Choice, Func<DialogContext, Task<DialogTurnResult>> ChoiceFunc)> CreateNextChoices(int currentPage, int pageCount, bool logged) { if (currentPage > 0) yield return ( new Choice("Show previous"), async (DialogContext dc) => { var catalogFilter = await accessors.CatalogFilterProperty.GetAsync(dc.Context); catalogFilter.PageIndex--; await accessors.CatalogFilterProperty.SetAsync(dc.Context, catalogFilter); return await dc.ReplaceDialogAsync(Id); } ); yield return ( new Choice("Home"), async (DialogContext dc) => { await sharedResponses.ReplyWith(dc.Context, SharedResponses.TypeMore); return await dc.EndDialogAsync(); } ); if (!logged) yield return ( new Choice("Login"), async (DialogContext dc) => await dc.BeginDialogAsync(LoginDialog.Name) ); if (currentPage + 1 < pageCount) yield return ( new Choice("Show next"), async (DialogContext dc) => { var catalogFilter = await accessors.CatalogFilterProperty.GetAsync(dc.Context); catalogFilter.PageIndex++; await accessors.CatalogFilterProperty.SetAsync(dc.Context, catalogFilter); return await dc.ReplaceDialogAsync(Id); } ); } private List<Attachment> CatalogCarousel(Models.Catalog.Catalog catalog, bool isAuthenticated, bool isMarkdownSupported) { var attachments = new List<Attachment>(); foreach (var item in catalog.Data) { var productThumbnail = BuildCatalogItemCard(item, isAuthenticated, isMarkdownSupported); attachments.Add(productThumbnail.ToAttachment()); } return attachments; } private ThumbnailCard BuildCatalogItemCard(Models.Catalog.CatalogItem catalogItem, bool isAuthenticated, bool isMarkdownSupported) { var addToBasketAction = new List<CardAction>(); if (isAuthenticated) { CardAction addToBasketButton = new CardAction() { Type = ActionTypes.PostBack, Value = $@"{{ 'ActionType': '{BotActionTypes.AddBasket}', 'ProductId': '{catalogItem.Id}' , 'ProductName': '{catalogItem.Name}', 'PictureUrl': '{catalogItem.PictureUri}', 'UnitPrice': '{catalogItem.Price}'}}", Title = "Add to cart", //DisplayText = $"{catalogItem.Name} added to cart" }; addToBasketAction.Add(addToBasketButton); } return UIHelper.CreateCatalogItemCard(catalogItem, addToBasketAction, isMarkdownSupported); } } }
30,057
https://github.com/SDWebImage/SDWebImagePDFCoder/blob/master/SDWebImagePDFCoder/Classes/SDWebImagePDFCoderDefine.m
Github Open Source
Open Source
MIT
2,022
SDWebImagePDFCoder
SDWebImage
Objective-C
Code
21
90
// // SDWebImagePDFCoderDefine.m // SDWebImagePDFCoder // // Created by lizhuoli on 2018/10/28. // #import "SDWebImagePDFCoderDefine.h" SDImageCoderOption _Nonnull const SDImageCoderDecodePDFPageNumber = @"decodePDFPageNumber";
3,009
https://github.com/RobCod/PERP/blob/master/gamemodes/perp/entities/entities/weather_tornado/cl_init.lua
Github Open Source
Open Source
MIT
2,021
PERP
RobCod
Lua
Code
98
419
include('shared.lua') local sirenPos = {Vector(-6527.918945, -8544.065430, 1261.234253), Vector(922.109436, 4752.591797, 913.729919), Vector(3499.881104, -6526.524414, 464.601379)}; function ENT:Draw() end function ENT:Think ( ) if self.NextWindGust < CurTime() then self.NextWindGust = CurTime() + 2 sound.Play('ambient/wind/windgust.wav', self:GetPos() + Vector(0, 0, 20), math.random(75, 100), 100); end if (self:GetNetworkedInt("size", 0) != 0 && !self.madeEffect) then local Effect = EffectData(); Effect:SetEntity(self); Effect:SetScale(self:GetNetworkedInt("size", 0)); util.Effect('tornado', Effect); self.madeEffect = true; end if (self.nextThrowSirenSound < CurTime()) then for _, pos in pairs(sirenPos) do sound.Play('perp2.5/tsiren.mp3', pos, 150, 100); self.nextThrowSirenSound = CurTime() + SoundDuration('perp2.5/tsiren.mp3'); end end end function ENT:Initialize ( ) self:DrawShadow(false); self.NextWindGust = 0; self.nextThrowSirenSound = CurTime() + 5 end
23,208
https://github.com/N0N4M3pl/plantuml-C4/blob/master/src/style.puml
Github Open Source
Open Source
MIT
2,020
plantuml-C4
N0N4M3pl
PlantUML
Code
184
861
@startuml C4-style ' ---------------------------------------------------- ' Document ' ---------------------------------------------------- !define LAYOUT_TOP_DOWN top to bottom direction !define LAYOUT_LEFT_RIGHT left to right direction !define LINE_STRAIGHT skinparam Linetype ortho skinparam defaultTextAlignment center skinparam wrapWidth 200 skinparam maxMessageSize 150 skinparam PathHoverColor #RED ' ---------------------------------------------------- ' Colors ' ---------------------------------------------------- !define COLOR_GRAY_1 #ecf0f1 !define COLOR_GRAY_2 #b6c1c5 !define COLOR_GRAY_3 #84939c !define COLOR_GRAY_4 #566775 !define COLOR_GRAY_5 #2c3e50 !define COLOR_YELLOW_1 #fffa6f !define COLOR_YELLOW_2 #f8df46 !define COLOR_YELLOW_3 #f1c40f !define COLOR_ORANGE_1 #ffe386 !define COLOR_ORANGE_2 #f2b24e !define COLOR_ORANGE_3 #e67e22 !define COLOR_RED_1 #ffb99c !define COLOR_RED_2 #f87b57 !define COLOR_RED_3 #eb1e1e !define COLOR_GREEN_1 #85ffb7 !define COLOR_GREEN_2 #5ee594 !define COLOR_GREEN_3 #2ecc71 !define COLOR_TURQUOISE_1 #93e8ea !define COLOR_TURQUOISE_2 #63d0d3 !define COLOR_TURQUOISE_3 #1ab9bc !define COLOR_BLUE_1 #98e1ff !define COLOR_BLUE_2 #65bded !define COLOR_BLUE_3 #3498db ' Document !define COLOR_FONT_DARK COLOR_GRAY_5 !define COLOR_FONT_LIGHT COLOR_GRAY_1 ' Common !define COLOR_BOUNDARY_BG white !define COLOR_BOUNDARY_BD COLOR_GRAY_2 !define COLOR_PERSON_BG COLOR_GRAY_4 !define COLOR_PERSON_BD COLOR_GRAY_4 !define COLOR_RELATION COLOR_GRAY_4 ' Context !define COLOR_SYSTEM_BG COLOR_GRAY_1 !define COLOR_SYSTEM_BD COLOR_GRAY_4 !define COLOR_SYSTEM_EXTERNAL_BG COLOR_GRAY_1 !define COLOR_SYSTEM_EXTERNAL_BD COLOR_GRAY_2 ' Container !define COLOR_BOUNDARY_SYSTEM_BG COLOR_GRAY_1 !define COLOR_BOUNDARY_SYSTEM_BD COLOR_GRAY_4 !define COLOR_CONTAINER_BG COLOR_BLUE_2 !define COLOR_CONTAINER_BD COLOR_GRAY_4 ' Component !define COLOR_BOUNDARY_CONTAINER_BG COLOR_GRAY_1 !define COLOR_BOUNDARY_CONTAINER_BD COLOR_BLUE_2 !define COLOR_COMPONENT_BG COLOR_GRAY_1 !define COLOR_COMPONENT_BD COLOR_BLUE_3 ' ---------------------------------------------------- ' ---------------------------------------------------- @enduml
23,095
https://github.com/jcapellman/monogame-tutorials/blob/master/chapter-11/end/Engine/States/BaseGameState.cs
Github Open Source
Open Source
MIT
2,020
monogame-tutorials
jcapellman
C#
Code
220
813
using System; using System.Collections.Generic; using System.Linq; using chapter_11.Engine.Input; using chapter_11.Engine.Objects; using chapter_11.Engine.Sound; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace chapter_11.Engine.States { public abstract class BaseGameState { protected bool _debug = false; protected bool _indestructible = false; private ContentManager _contentManager; protected int _viewportHeight; protected int _viewportWidth; protected SoundManager _soundManager = new SoundManager(); private readonly List<BaseGameObject> _gameObjects = new List<BaseGameObject>(); protected InputManager InputManager {get; set;} public void Initialize(ContentManager contentManager, int viewportWidth, int viewportHeight) { _contentManager = contentManager; _viewportHeight = viewportHeight; _viewportWidth = viewportWidth; SetInputManager(); } public abstract void LoadContent(); public abstract void HandleInput(GameTime gameTime); public abstract void UpdateGameState(GameTime gameTime); public event EventHandler<BaseGameState> OnStateSwitched; public event EventHandler<BaseGameStateEvent> OnEventNotification; protected abstract void SetInputManager(); public void UnloadContent() { _contentManager.Unload(); } public void Update(GameTime gameTime) { UpdateGameState(gameTime); _soundManager.PlaySoundtrack(); } protected Texture2D LoadTexture(string textureName) { return _contentManager.Load<Texture2D>(textureName); } protected SpriteFont LoadFont(string fontName) { return _contentManager.Load<SpriteFont>(fontName); } protected SoundEffect LoadSound(string soundName) { return _contentManager.Load<SoundEffect>(soundName); } protected void NotifyEvent(BaseGameStateEvent gameEvent) { OnEventNotification?.Invoke(this, gameEvent); foreach (var gameObject in _gameObjects) { if (gameObject != null) gameObject.OnNotify(gameEvent); } _soundManager.OnNotify(gameEvent); } protected void SwitchState(BaseGameState gameState) { OnStateSwitched?.Invoke(this, gameState); } protected void AddGameObject(BaseGameObject gameObject) { _gameObjects.Add(gameObject); } protected void RemoveGameObject(BaseGameObject gameObject) { _gameObjects.Remove(gameObject); } public virtual void Render(SpriteBatch spriteBatch) { foreach (var gameObject in _gameObjects.Where(a => a != null).OrderBy(a => a.zIndex)) { if (_debug) { gameObject.RenderBoundingBoxes(spriteBatch); } gameObject.Render(spriteBatch); } } } }
6,053
https://github.com/AAI-USZ/FixJS/blob/master/input/50-100/after/c10c8bc6adfaba93cafe84b41a6b63604a2d68cd_3_1.js
Github Open Source
Open Source
MIT
2,022
FixJS
AAI-USZ
JavaScript
Code
25
73
function() { var parser1 = letter.then(function() { return 'not a parser' }); assert.throws(function() { parser1.parse('x'); }); var parser2 = letter.then('x'); assert.throws(function() { letter.parse('xx'); }); }
36,565
https://github.com/sgs-weather-and-environmental-systems/rstt/blob/master/gr-rstt/lib/qa_error_correction.cc
Github Open Source
Open Source
Apache-2.0
2,021
rstt
sgs-weather-and-environmental-systems
C++
Code
929
3,585
/* -*- c++ -*- */ /* * Copyright 2013 Jiří Pinkava <j-pi@seznam.cz>. * * This is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * This software 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. */ #include "qa_error_correction.h" #include "error_correction_impl.h" #include <cppunit/TestAssert.h> namespace gr { namespace rstt { // valid void qa_error_correction::t1() { const unsigned short in[240] = { // frame header 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, 0x10, // valid subframe 0x65, 0x02, 0x01, 0x02, 0x03, 0x04, 0xc3, 0x89, // padding subframe 0xff, 100, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // dummy ECC 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; CPPUNIT_ASSERT( error_correction_impl::is_frame_valid(in) == 2); } // invalid CRC void qa_error_correction::t2() { const unsigned short in[240] = { // frame header 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, 0x10, // valid subframe 0x65, 0x02, 0xff, 0x02, 0x03, 0x04, 0xc3, 0x89, // padding subframe 0xff, 100, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // dummy ECC 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; CPPUNIT_ASSERT( error_correction_impl::is_frame_valid(in) == -1); } // invalid length void qa_error_correction::t3() { const unsigned short in[240] = { // frame header 0x2A, 0x2A, 0x2A, 0x2A, 0x2A, 0x10, // valid subframe 0x65, 0x02, 0x01, 0x02, 0x03, 0x04, 0xc3, 0x89, // padding subframe 0xff, 127, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // dummy ECC 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; CPPUNIT_ASSERT( error_correction_impl::is_frame_valid(in) == -1); } } /* namespace rstt */ } /* namespace gr */
38,725
https://github.com/65-7a/forge-client/blob/master/src/main/java/com/callumwong/gammazero/gui/clickgui/components/CheckBox.java
Github Open Source
Open Source
MIT
null
forge-client
65-7a
Java
Code
373
1,102
/* * Copyright (c) 2021 Callum Wong * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.callumwong.gammazero.gui.clickgui.components; import com.callumwong.gammazero.gui.clickgui.AbstractComponent; import com.callumwong.gammazero.gui.clickgui.IRenderer; import com.callumwong.gammazero.gui.clickgui.Window; import java.awt.*; public class CheckBox extends AbstractComponent { private static final int PREFERRED_HEIGHT = 22; private boolean selected; private String title; private final int preferredHeight; private boolean hovered; private ValueChangeListener<Boolean> listener; public CheckBox(IRenderer renderer, String title, int preferredHeight) { super(renderer); this.preferredHeight = preferredHeight; setTitle(title); } public CheckBox(IRenderer renderer, String title) { this(renderer, title, PREFERRED_HEIGHT); } @Override public void render() { renderer.drawRect(x, y, preferredHeight, preferredHeight, hovered ? com.callumwong.gammazero.gui.clickgui.Window.SECONDARY_FOREGROUND : com.callumwong.gammazero.gui.clickgui.Window.TERTIARY_FOREGROUND); if (selected) { Color color = hovered ? com.callumwong.gammazero.gui.clickgui.Window.TERTIARY_FOREGROUND : com.callumwong.gammazero.gui.clickgui.Window.SECONDARY_FOREGROUND; renderer.drawRect(x + 2, y + 3, preferredHeight - 5, preferredHeight - 5, new Color(color.getRed(), color.getGreen(), color.getBlue())); } renderer.drawOutline(x, y, preferredHeight, preferredHeight, 1.0f, hovered ? com.callumwong.gammazero.gui.clickgui.Window.SECONDARY_OUTLINE : com.callumwong.gammazero.gui.clickgui.Window.SECONDARY_FOREGROUND); renderer.drawString(x + preferredHeight + preferredHeight / 4, y + renderer.getStringHeight(title) / 4, title, Window.FOREGROUND); } @Override public boolean mouseMove(int x, int y, boolean offscreen) { updateHovered(x, y, offscreen); return false; } private void updateHovered(int x, int y, boolean offscreen) { hovered = !offscreen && x >= this.x && y >= this.y && x <= this.x + getWidth() && y <= this.y + getHeight(); } @Override public boolean mousePressed(int button, int x, int y, boolean offscreen) { if (button == 0) { updateHovered(x, y, offscreen); if (hovered) { boolean newVal = !selected; boolean change = true; if (listener != null) { change = listener.onValueChange(newVal); } if (change) selected = newVal; return true; } } return false; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; setWidth(renderer.getStringWidth(title) + preferredHeight + preferredHeight / 4); setHeight(preferredHeight); } public void setListener(ValueChangeListener<Boolean> listener) { this.listener = listener; } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } }
29,352
https://github.com/facebook/flipper/blob/master/iOS/Plugins/FlipperKitPluginUtils/FlipperKitLayoutHelpers/FlipperKitLayoutHelpers/SKInvalidation.h
Github Open Source
Open Source
MIT
2,023
flipper
facebook
Objective-C
Code
57
161
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #import <Foundation/Foundation.h> @protocol SKInvalidationDelegate - (void)invalidateNode:(id<NSObject>)node; - (void)updateNodeReference:(id<NSObject>)node; @end @interface SKInvalidation : NSObject + (instancetype)sharedInstance; + (void)enableInvalidations; @property(nonatomic, weak) id<SKInvalidationDelegate> delegate; @end
10,888
https://github.com/cursive-works/wagtailmedia/blob/master/src/wagtailmedia/wagtail_hooks.py
Github Open Source
Open Source
BSD-3-Clause
2,022
wagtailmedia
cursive-works
Python
Code
178
821
from django.conf.urls import include from django.urls import path, reverse from django.utils.translation import gettext_lazy as _ from django.utils.translation import ungettext from wagtail.admin.menu import MenuItem from wagtail.admin.search import SearchArea from wagtail.admin.site_summary import SummaryItem from wagtail.core import hooks from wagtailmedia import admin_urls from wagtailmedia.forms import GroupMediaPermissionFormSet from wagtailmedia.models import get_media_model from wagtailmedia.permissions import permission_policy @hooks.register("register_admin_urls") def register_admin_urls(): return [ path("media/", include((admin_urls, "wagtailmedia"), namespace="wagtailmedia")), ] class MediaMenuItem(MenuItem): def is_shown(self, request): return permission_policy.user_has_any_permission( request.user, ["add", "change", "delete"] ) @hooks.register("register_admin_menu_item") def register_media_menu_item(): return MediaMenuItem( _("Media"), reverse("wagtailmedia:index"), name="media", classnames="icon icon-media", order=300, ) class MediaSummaryItem(SummaryItem): order = 300 template = "wagtailmedia/homepage/site_summary_media.html" def get_context(self): return { "total_media": get_media_model().objects.count(), } def is_shown(self): return permission_policy.user_has_any_permission( self.request.user, ["add", "change", "delete"] ) @hooks.register("construct_homepage_summary_items") def add_media_summary_item(request, items): items.append(MediaSummaryItem(request)) class MediaSearchArea(SearchArea): def is_shown(self, request): return permission_policy.user_has_any_permission( request.user, ["add", "change", "delete"] ) @hooks.register("register_admin_search_area") def register_media_search_area(): return MediaSearchArea( _("Media"), reverse("wagtailmedia:index"), name="media", classnames="icon icon-media", order=400, ) @hooks.register("register_group_permission_panel") def register_media_permissions_panel(): return GroupMediaPermissionFormSet @hooks.register("describe_collection_contents") def describe_collection_media(collection): media_count = get_media_model().objects.filter(collection=collection).count() if media_count: url = reverse("wagtailmedia:index") + ("?collection_id=%d" % collection.id) return { "count": media_count, "count_text": ungettext( "%(count)s media file", "%(count)s media files", media_count ) % {"count": media_count}, "url": url, }
40,253
https://github.com/mauricio/jesque/blob/master/src/main/java/com/officedrop/jesque/utils/VersionUtils.java
Github Open Source
Open Source
Apache-2.0
2,013
jesque
mauricio
Java
Code
274
648
/* * Copyright 2011 Greg Haines * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.officedrop.jesque.utils; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Grabs the version number from the Maven metadata. * * @author Greg Haines */ public final class VersionUtils { public static final String DEVELOPMENT = "DEVELOPMENT"; public static final String ERROR = "ERROR"; private static final Logger log = LoggerFactory.getLogger(VersionUtils.class); private static final String pomPropertiesResName = "/META-INF/maven/com.officedrop/jesque/pom.properties"; private static final String versionPropName = "version"; private static final AtomicReference<String> versionRef = new AtomicReference<String>(null); /** * @return the current version of this software */ public static String getVersion() { String version = versionRef.get(); if (version == null) { versionRef.set(readVersion()); version = versionRef.get(); } return version; } private static String readVersion() { String version = DEVELOPMENT; final InputStream stream = VersionUtils.class.getResourceAsStream(pomPropertiesResName); if (stream != null) { try { final Properties props = new Properties(); props.load(stream); version = (String) props.get(versionPropName); } catch (Exception e) { log.warn("Could not determine version from POM properties", e); version = ERROR; } finally { try { stream.close(); } catch (Exception e){} } } return version; } private VersionUtils(){} // Utiltity class }
5,268
https://github.com/matenet/matecar/blob/master/application/views/zaplecze/wybrane_auto_edytuj_zdjecia.php
Github Open Source
Open Source
MIT
null
matecar
matenet
PHP
Code
361
1,697
<h2>Edytuj auto</h2> <?php $marka = array_column($auta, 'marka'); $model = array_column($auta, 'model'); $nr_rejestracyjny = array_column($auta, 'nr_rejestracyjny'); $cena = array_column($auta, 'cena'); $kaucja = array_column($auta, 'kaucja'); $pojemnosc_silnika = array_column($auta, 'pojemnosc_silnika'); $moc = array_column($auta, 'moc'); $spalanie = array_column($auta, 'spalanie'); $kategoria = array_column($auta, 'kategoria'); $nadwozie = array_column($auta, 'nadwozie'); $rodzaj_paliwa = array_column($auta, 'rodzaj_paliwa'); $skrzynia_biegow = array_column($auta, 'skrzynia_biegow'); $naped = array_column($auta, 'naped'); $liczba_drzwi = array_column($auta, 'liczba_drzwi'); $pojemnosc_bagaznika = array_column($auta, 'pojemnosc_bagaznika'); $liczba_miejsc = array_column($auta, 'liczba_miejsc'); $kolor = array_column($auta, 'kolor'); $przebieg = array_column($auta, 'przebieg'); $wyposazenie_dodatkowe = array_column($auta, 'wyposazenie_dodatkowe'); $linki_zdjec = array_column($auta, 'linki_zdjec'); ?> <?php $polaczone_linki = $linki_zdjec[0]; try { $rozbite_linki = explode(", ",$linki_zdjec[0]); } catch(Exception $e) { $rozbite_linki = $linki_zdjec[0]; } ?> <div class="cars-grid-wrapper"> <div class="car-img-wrapper"> <?php if (isset($rozbite_linki[1])): for($i=0; $i<10;$i++): if (isset($rozbite_linki [$i])): ?> <img src="<?php echo $rozbite_linki [$i]; ?>" alt="" class="show-car-img"> <?php endif; ?> <?php endfor; ?> <?php else: ?> <img src="<?php echo $rozbite_linki [0]; ?>" alt="" class="show-car-img"> <?php endif; ?> </div> </div> <?php function zrobLinkiZdjec() { $ci =& get_instance(); $ilosc_img=$ci->session->userdata('ilosc_zdjec'); for($i=0; $i<=$ilosc_img; $i++) { $link_number="image-link-".$i; echo '<img src="' . $ci->input->post($link_number) . '" ' . 'class="dodaj-auto-img">'; } } function polaczLinkiZdjec() { $ci =& get_instance(); $ilosc_img=$ci->session->userdata('ilosc_zdjec'); $output=''; for($i=0; $i<=$ilosc_img; $i++) { $link_number="image-link-".$i; if($i==0) { $output = $ci->input->post($link_number); } else { $output .= ', ' . $ci->input->post($link_number); } } return $output; } ?> <section class="add-car-summary-wrapper"> <?php echo form_open('zaplecze/dodaj_auto_do_bazy'); ?> <input type="text" name="kategoria" value="<?php echo $kategoria[0]; ?>"> <input type="text" name="nadwozie" value="<?php echo $nadwozie[0]; ?>"> <input type="text" name="marka" value="<?php echo $marka[0]; ?>"> <input type="text" name="model" value="<?php echo $model[0]; ?>"> <input type="text" name="nr_rejestracyjny" value="<?php echo $nr_rejestracyjny[0]; ?>"> <input type="number" name="pojemnosc_silnika" value="<?php echo $pojemnosc_silnika[0]; ?>"> <input type="text" name="rodzaj_paliwa" value="<?php echo $rodzaj_paliwa[0]; ?>"> <input type="hidden" name="moc" value="<?php echo $moc[0]; ?>"> <input type="hidden" name="spalanie" value="<?php echo $spalanie[0]; ?>"> <input type="text" name="skrzynia_biegow" value="<?php echo $skrzynia_biegow[0]; ?>"> <input type="text" name="naped" value="<?php echo $naped[0]; ?>"> <input type="hidden" name="liczba_miejsc" value="<?php echo $liczba_miejsc[0]; ?>"> <input type="hidden" name="liczba_drzwi" value="<?php echo $liczba_drzwi[0]; ?>"> <input type="hidden" name="pojemnosc_bagaznika" value="<?php echo $pojemnosc_bagaznika[0]; ?>"> <input type="hidden" name="przebieg" value="<?php echo $przebieg[0]; ?>"> <input type="text" name="kolor" value="<?php echo $kolor[0]; ?>"> <input type="hidden" name="cena" value="<?php echo $cena[0]; ?>"> <input type="hidden" name="kaucja" value="<?php echo $kaucja[0]; ?>"> <input type="text" name="wyposazenie_dodatkowe" value="<?php echo $wyposazenie_dodatkowe[0]; ?>"> <input type="hidden" name="linki_zdjec" value="<?php echo polaczLinkiZdjec(); ?>"> <?php echo form_submit('wyslij_dane','Zapisz zmiany'); ?> <?php echo form_close(); ?> </section> </div>
42,060
https://github.com/jaykrell/cm3/blob/master/m3-scheme/scheme-lib/src/mbe.scm
Github Open Source
Open Source
BSD-4-Clause-UC, BSD-4-Clause, BSD-3-Clause
2,022
cm3
jaykrell
Scheme
Code
1,287
4,340
;; $Id$ ;; ;; downloaded from norvig.com 2008/11/18 ;; ;; moved reverse! and append! to basic-defs.scm ;; removed => (not in early JScheme) ;Hygienic R5RS macro-by-example for SILK ;-*-scheme-*- ;Dorai Sitaram ds26@gte.com http://www.cs.rice.edu/~dorai/ ;April 17, 1998 ;some common Scheme utilities (require-modules "basic-mbe") (define *gentemp-counter* -1) (define gentemp (lambda () (set! *gentemp-counter* (+ *gentemp-counter* 1)) (string->symbol (string-append "GenTemp%" (number->string *gentemp-counter*))))) ;Hygiene (define hyg:rassq (lambda (k al) (let loop ((al al)) (if (null? al) #f (let ((c (car al))) (if (eq? (cdr c) k) c (loop (cdr al)))))))) (define hyg:tag (lambda (e kk al) (cond ((pair? e) (let* ((a-te-al (hyg:tag (car e) kk al)) (d-te-al (hyg:tag (cdr e) kk (cdr a-te-al)))) (cons (cons (car a-te-al) (car d-te-al)) (cdr d-te-al)))) ((vector? e) (list->vector (hyg:tag (vector->list e) kk al))) ((symbol? e) (cond ((eq? e '...) (cons '... al)) ((memq e kk) (cons e al)) ((hyg:rassq e al) ((lambda (c) (cons (car c) al)) (hyg:rassq e al)) ) (else (let ((te (gentemp))) (cons te (cons (cons te e) al)))))) (else (cons e al))))) ;untagging (define hyg:untag (lambda (e al tmps) (if (pair? e) (let ((a (hyg:untag (car e) al tmps))) (if (list? e) (case a ((quote) (hyg:untag-no-tags e al)) ((if begin) `(,a ,@(map (lambda (e1) (hyg:untag e1 al tmps)) (cdr e)))) ((set! define) `(,a ,(hyg:untag-vanilla (cadr e) al tmps) ,@(map (lambda (e1) (hyg:untag e1 al tmps)) (cddr e)))) ((lambda) (hyg:untag-lambda (cadr e) (cddr e) al tmps)) ((letrec) (hyg:untag-letrec (cadr e) (cddr e) al tmps)) ((let) (let ((e2 (cadr e))) (if (symbol? e2) (hyg:untag-named-let e2 (caddr e) (cdddr e) al tmps) (hyg:untag-let e2 (cddr e) al tmps)))) ((let*) (hyg:untag-let* (cadr e) (cddr e) al tmps)) ((do) (hyg:untag-do (cadr e) (caddr e) (cdddr e) al tmps)) ((case) `(case ,(hyg:untag-vanilla (cadr e) al tmps) ,@(map (lambda (c) `(,(hyg:untag-vanilla (car c) al tmps) ,@(hyg:untag-list (cdr c) al tmps))) (cddr e)))) ((cond) `(cond ,@(map (lambda (c) (hyg:untag-list c al tmps)) (cdr e)))) (else (cons a (hyg:untag-list (cdr e) al tmps)))) (cons a (hyg:untag-list* (cdr e) al tmps)))) (hyg:untag-vanilla e al tmps)))) (define hyg:untag-list (lambda (ee al tmps) (map (lambda (e) (hyg:untag e al tmps)) ee))) (define hyg:untag-list* (lambda (ee al tmps) (let loop ((ee ee)) (if (pair? ee) (cons (hyg:untag (car ee) al tmps) (loop (cdr ee))) (hyg:untag ee al tmps))))) (define hyg:untag-no-tags (lambda (e al) (cond ((pair? e) (cons (hyg:untag-no-tags (car e) al) (hyg:untag-no-tags (cdr e) al))) ((vector? e) (list->vector (hyg:untag-no-tags (vector->list e) al))) ((not (symbol? e)) e) ((assq e al) (cdr (assq e al)) ) (else e)))) (define hyg:untag-lambda (lambda (bvv body al tmps) (let ((tmps2 (append! (hyg:flatten bvv) tmps))) `(lambda ,bvv ,@(hyg:untag-list body al tmps2))))) (define hyg:untag-letrec (lambda (varvals body al tmps) (let ((tmps (append! (map car varvals) tmps))) `(letrec ,(map (lambda (varval) `(,(car varval) ,(hyg:untag (cadr varval) al tmps))) varvals) ,@(hyg:untag-list body al tmps))))) (define hyg:untag-let (lambda (varvals body al tmps) (let ((tmps2 (append! (map car varvals) tmps))) `(let ,(map (lambda (varval) `(,(car varval) ,(hyg:untag (cadr varval) al tmps))) varvals) ,@(hyg:untag-list body al tmps2))))) (define hyg:untag-named-let (lambda (lname varvals body al tmps) (let ((tmps2 (cons lname (append! (map car varvals) tmps)))) `(let ,lname ,(map (lambda (varval) `(,(car varval) ,(hyg:untag (cadr varval) al tmps))) varvals) ,@(hyg:untag-list body al tmps2))))) (define hyg:untag-let* (lambda (varvals body al tmps) (let ((tmps2 (append! (reverse! (map car varvals)) tmps))) `(let* ,(let loop ((varvals varvals) (i (length varvals))) (if (null? varvals) '() (let ((varval (car varvals))) (cons `(,(car varval) ,(hyg:untag (cadr varval) al (list-tail tmps2 i))) (loop (cdr varvals) (- i 1)))))) ,@(hyg:untag-list body al tmps2))))) (define hyg:untag-do (lambda (varinistps exit-test body al tmps) (let ((tmps2 (append! (map car varinistps) tmps))) `(do ,(map (lambda (varinistp) (let ((var (car varinistp))) `(,var ,@(hyg:untag-list (cdr varinistp) al (cons var tmps))))) varinistps) ,(hyg:untag-list exit-test al tmps2) ,@(hyg:untag-list body al tmps2))))) (define hyg:untag-vanilla (lambda (e al tmps) (cond ((pair? e) (cons (hyg:untag-vanilla (car e) al tmps) (hyg:untag-vanilla (cdr e) al tmps))) ((vector? e) (list->vector (hyg:untag-vanilla (vector->list e) al tmps))) ((not (symbol? e)) e) ((memq e tmps) e) ((assq e al) (cdr (assq e al))) (else e)))) (define hyg:flatten (lambda (e) (let loop ((e e) (r '())) (cond ((pair? e) (loop (car e) (loop (cdr e) r))) ((null? e) r) (else (cons e r)))))) ;End of hygiene filter. ;finds the leftmost index of list l where something equal to x ;occurs (define mbe:position (lambda (x l) (let loop ((l l) (i 0)) (cond ((not (pair? l)) #f) ((equal? (car l) x) i) (else (loop (cdr l) (+ i 1))))))) ;tests if expression e matches pattern p where k is the list of ;keywords (define mbe:matches-pattern? (lambda (p e k) (cond ((mbe:ellipsis? p) (and (or (null? e) (pair? e)) (let* ((p-head (car p)) (p-tail (cddr p)) (e-head=e-tail (mbe:split-at-ellipsis e p-tail))) (and e-head=e-tail (let ((e-head (car e-head=e-tail)) (e-tail (cdr e-head=e-tail))) (and (andmap (lambda (x) (mbe:matches-pattern? p-head x k)) e-head) (mbe:matches-pattern? p-tail e-tail k))))))) ((pair? p) (and (pair? e) (mbe:matches-pattern? (car p) (car e) k) (mbe:matches-pattern? (cdr p) (cdr e) k))) ((symbol? p) (if (memq p k) (eq? p e) #t)) (else (equal? p e))))) ;gets the bindings of pattern variables of pattern p for ;expression e; ;k is the list of keywords (define mbe:get-bindings (lambda (p e k) (cond ((mbe:ellipsis? p) (let* ((p-head (car p)) (p-tail (cddr p)) (e-head=e-tail (mbe:split-at-ellipsis e p-tail)) (e-head (car e-head=e-tail)) (e-tail (cdr e-head=e-tail))) (cons (cons (mbe:get-ellipsis-nestings p-head k) (map (lambda (x) (mbe:get-bindings p-head x k)) e-head)) (mbe:get-bindings p-tail e-tail k)))) ((pair? p) (append (mbe:get-bindings (car p) (car e) k) (mbe:get-bindings (cdr p) (cdr e) k))) ((symbol? p) (if (memq p k) '() (list (cons p e)))) (else '())))) ;expands pattern p using environment r; ;k is the list of keywords (define mbe:expand-pattern (lambda (p r k) (cond ((mbe:ellipsis? p) (append (let* ((p-head (car p)) (nestings (mbe:get-ellipsis-nestings p-head k)) (rr (mbe:ellipsis-sub-envs nestings r))) (map (lambda (r1) (mbe:expand-pattern p-head (append r1 r) k)) rr)) (mbe:expand-pattern (cddr p) r k))) ((pair? p) (cons (mbe:expand-pattern (car p) r k) (mbe:expand-pattern (cdr p) r k))) ((symbol? p) (if (memq p k) p (let ((x (assq p r))) (if x (cdr x) p)))) (else p)))) ;returns a list that nests a pattern variable as deeply as it ;is ellipsed (define mbe:get-ellipsis-nestings (lambda (p k) (let sub ((p p)) (cond ((mbe:ellipsis? p) (cons (sub (car p)) (sub (cddr p)))) ((pair? p) (append (sub (car p)) (sub (cdr p)))) ((symbol? p) (if (memq p k) '() (list p))) (else '()))))) ;finds the subenvironments in r corresponding to the ellipsed ;variables in nestings (define mbe:ellipsis-sub-envs (lambda (nestings r) (ormap (lambda (c) (if (mbe:contained-in? nestings (car c)) (cdr c) #f)) r))) ;checks if nestings v and y have an intersection (define mbe:contained-in? (lambda (v y) (if (or (symbol? v) (symbol? y)) (eq? v y) (ormap (lambda (v_i) (ormap (lambda (y_j) (mbe:contained-in? v_i y_j)) y)) v)))) ;split expression e so that its second half matches with ;pattern p-tail (define mbe:split-at-ellipsis (lambda (e p-tail) (if (null? p-tail) (cons e '()) (let ((i (mbe:position (car p-tail) e))) (if i (cons (butlast e (- (length e) i)) (list-tail e i)) (error 'mbe:split-at-ellipsis 'bad-arg)))))) ;tests if x is an ellipsing pattern, i.e., of the form ;(blah ... . blah2) (define mbe:ellipsis? (lambda (x) (and (pair? x) (pair? (cdr x)) (eq? (cadr x) '...)))) ;syntax-rules (define syntax-rules (macro (keywords . clauses) (let ((macro-name (caar clauses))) `(macro __syntax-rules-arg__ ,(mbe:syntax-rules-proc macro-name keywords clauses '__syntax-rules-arg__ '__syntax-rules-keywords__))))) (define mbe:syntax-rules-proc (lambda (macro-name keywords clauses arg-sym keywords-sym) (let ((keywords (cons macro-name keywords))) `(let ((,arg-sym (cons ',macro-name ,arg-sym)) (,keywords-sym ',keywords-sym)) (cond ,@(map (lambda (clause) (let ((in-pattern (car clause)) (out-pattern (cadr clause))) `((mbe:matches-pattern? ',in-pattern ,arg-sym ,keywords-sym) (let ((tagged-out-pattern+alist (hyg:tag ',out-pattern (append! (hyg:flatten ',in-pattern) ,keywords-sym) '()))) (hyg:untag (mbe:expand-pattern (car tagged-out-pattern+alist) (mbe:get-bindings ',in-pattern ,arg-sym ,keywords-sym) ,keywords-sym) (cdr tagged-out-pattern+alist) '()))))) clauses) (else (error ',macro-name 'no-matching-clause ',clauses))))))) (define define-syntax (macro arg (cons 'define arg))) (define let-syntax (macro arg (cons 'let arg))) (define letrec-syntax (macro arg (cons 'letrec arg))) ;end of file
23,878
https://github.com/nvander/incubator-rya/blob/master/extras/indexing/src/main/java/mvm/rya/indexing/IndexPlanValidator/ExternalIndexMatcher.java
Github Open Source
Open Source
Apache-2.0
2,015
incubator-rya
nvander
Java
Code
20
110
package mvm.rya.indexing.IndexPlanValidator; import java.util.Iterator; import java.util.List; import java.util.Set; import mvm.rya.indexing.external.tupleSet.ExternalTupleSet; import org.openrdf.query.algebra.TupleExpr; public interface ExternalIndexMatcher { public Iterator<TupleExpr> getIndexedTuples(); }
17,896
https://github.com/Phader/runelite/blob/master/runescape-client/src/main/java/ClanMate.java
Github Open Source
Open Source
BSD-2-Clause
2,020
runelite
Phader
Java
Code
359
1,360
import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("jt") @Implements("ClanMate") public class ClanMate extends Buddy { @ObfuscatedName("c") @ObfuscatedSignature( signature = "Lju;" ) @Export("friend") TriBool friend; @ObfuscatedName("t") @ObfuscatedSignature( signature = "Lju;" ) @Export("ignored") TriBool ignored; ClanMate() { this.friend = TriBool.TriBool_unknown; this.ignored = TriBool.TriBool_unknown; } @ObfuscatedName("c") @ObfuscatedSignature( signature = "(I)V", garbageValue = "-526388551" ) @Export("clearIsFriend") void clearIsFriend() { this.friend = TriBool.TriBool_unknown; } @ObfuscatedName("t") @ObfuscatedSignature( signature = "(I)Z", garbageValue = "2130139941" ) @Export("isFriend") public final boolean isFriend() { if (this.friend == TriBool.TriBool_unknown) { this.fillIsFriend(); } return this.friend == TriBool.TriBool_true; } @ObfuscatedName("o") @ObfuscatedSignature( signature = "(I)V", garbageValue = "-2012869833" ) @Export("fillIsFriend") void fillIsFriend() { this.friend = KeyHandler.friendSystem.friendsList.contains(super.username) ? TriBool.TriBool_true : TriBool.TriBool_false; } @ObfuscatedName("e") @ObfuscatedSignature( signature = "(I)V", garbageValue = "1620040890" ) @Export("clearIsIgnored") void clearIsIgnored() { this.ignored = TriBool.TriBool_unknown; } @ObfuscatedName("i") @ObfuscatedSignature( signature = "(B)Z", garbageValue = "-84" ) @Export("isIgnored") public final boolean isIgnored() { if (this.ignored == TriBool.TriBool_unknown) { this.fillIsIgnored(); } return this.ignored == TriBool.TriBool_true; } @ObfuscatedName("g") @ObfuscatedSignature( signature = "(I)V", garbageValue = "-749177789" ) @Export("fillIsIgnored") void fillIsIgnored() { this.ignored = KeyHandler.friendSystem.ignoreList.contains(super.username) ? TriBool.TriBool_true : TriBool.TriBool_false; } @ObfuscatedName("o") @ObfuscatedSignature( signature = "(Ljava/lang/CharSequence;IZI)Z", garbageValue = "-1733263063" ) static boolean method5073(CharSequence var0, int var1, boolean var2) { if (var1 >= 2 && var1 <= 36) { boolean var3 = false; boolean var4 = false; int var5 = 0; int var6 = var0.length(); for (int var7 = 0; var7 < var6; ++var7) { char var8 = var0.charAt(var7); if (var7 == 0) { if (var8 == '-') { var3 = true; continue; } if (var8 == '+') { continue; } } int var10; if (var8 >= '0' && var8 <= '9') { var10 = var8 - '0'; } else if (var8 >= 'A' && var8 <= 'Z') { var10 = var8 - '7'; } else { if (var8 < 'a' || var8 > 'z') { return false; } var10 = var8 - 'W'; } if (var10 >= var1) { return false; } if (var3) { var10 = -var10; } int var9 = var5 * var1 + var10; if (var9 / var1 != var5) { return false; } var5 = var9; var4 = true; } return var4; } else { throw new IllegalArgumentException("" + var1); } } }
9,931
https://github.com/steinwurf/sak/blob/master/src/sak/input_stream.hpp
Github Open Source
Open Source
BSD-3-Clause
2,017
sak
steinwurf
C++
Code
283
593
// Copyright (c) 2012 Steinwurf ApS // All Rights Reserved // // Distributed under the "BSD License". See the accompanying LICENSE.rst file. #pragma once #include <cstdint> #include <functional> namespace sak { /// Input stream abstraction class input_stream { public: /// Destructor virtual ~input_stream() {} /// Request a read from the io device /// @param buffer from where to read /// @param bytes to read virtual void read(uint8_t* buffer, uint32_t bytes) = 0; /// Returns the number of bytes available for reading /// @return number of bytes available virtual uint32_t bytes_available() = 0; /// Indicates if more data will be produced. For a live stream, /// the function will return true after the stream finishes. /// For a finite stream (e.g. a file) the function will always /// return true. virtual bool stopped() = 0; public: /// Signal emitted when data can be read typedef std::function<void ()> ready_read_callback; /// Specify callbacks to allow the caller to determine if /// new data has arrived which is ready to be read. /// @param callback the callback function void on_ready_read(const ready_read_callback& callback) { m_ready_read_callback = callback; } /// Signal emitted on error typedef std::function<void (const std::string&)> error_callback; /// Specify the callback function that is invoked when an error occurs. /// @param callback the callback function void on_error(const error_callback& callback) { m_error_callback = callback; } /// Signal emitted when the stream is stopped typedef std::function<void ()> stopped_callback; /// Specify the callback function that is invoked when the stream /// is stopped. /// @param callback the callback function void on_stopped(const stopped_callback& callback) { m_stopped_callback = callback; } protected: /// The ready read signal ready_read_callback m_ready_read_callback; /// The error signal error_callback m_error_callback; /// The stopped signals stopped_callback m_stopped_callback; }; }
46,394
https://github.com/lneninger/quickbookdestop-integrator/blob/master/src/_Examples Direct QB Connect Interop/MCInvoiceAddQBFC/Intuit_QBFC/SessionFramework/ENEdition.cs
Github Open Source
Open Source
Apache-2.0
2,021
quickbookdestop-integrator
lneninger
C#
Code
66
156
// Copyright (c) 2007-2013 by Intuit Inc. // All rights reserved // Usage governed by the QuickBooks SDK Developer's License Agreement using System; namespace MCInvoiceAddQBFC.Session_Framework { public enum ENEdition { edUS = 0, edCA = 1, edUK = 2, } static class QBEdition { public static readonly string[] codes = { "US", "CA", "UK" }; public static string getEdition(ENEdition ed) { return codes[(int)ed]; } } }
41,973
https://github.com/nishkalavallabhi/MRLSubmission2021/blob/master/code/gen_mbert_vecs.py
Github Open Source
Open Source
Apache-2.0
2,021
MRLSubmission2021
nishkalavallabhi
Python
Code
140
615
import torch from transformers import * import sys setup = sys.argv[1] if setup == 'mbert': tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased') model = BertModel.from_pretrained('bert-base-multilingual-cased', output_hidden_states=True) outputfile = "../mbert_last_layer_CLS_token.out" elif setup == 'xlmr': tokenizer = XLMRobertaTokenizer.from_pretrained('xlm-roberta-base') model = XLMRobertaModel.from_pretrained('xlm-roberta-base', output_hidden_states=True) outputfile = "../xlmr_last_layer_CLS_token.out" else: print("Wrong setup") exit(1) import glob dir_names = ["DE", "CZ", "IT"] maxlen = 512 nr_sents_clip = 0 with open(outputfile, "w") as fw: with torch.no_grad(): #remove gradient computation for lang_name in dir_names: data_dir = "../Datasets/"+lang_name for fname in glob.glob(data_dir+"/*txt"): print(fname) text = open(fname, "r").read() # vec = tokenizer.encode(text, add_special_tokens=True) vec = tokenizer.encode_plus(text, add_special_tokens=True, max_length=maxlen)["input_ids"] if len(vec) == maxlen: nr_sents_clip += 1 # vec1 = vec[0:maxlen-1]+vec[-1:] text_tensor = torch.tensor([vec]) text_vec = model(text_tensor) cls_vec = text_vec[0][0][0].detach().numpy() cls_vec = list(map(str, cls_vec)) #ave_vec = text_vec[0][0][1:-1].numpy().mean(axis=0) # ave_vec = list(map(str, ave_vec)) # if text_vec[0][0].numpy().shape[0] == maxlen: nr_sents_clip += 1 print(fname, ",".join(cls_vec), sep="\t", file=fw) print("Nr. clipped sentences {}".format(nr_sents_clip))
26,729
https://github.com/kevinmckinley/dd-agent/blob/master/tests/checks/mock/test_kubernetes.py
Github Open Source
Open Source
BSD-3-Clause
null
dd-agent
kevinmckinley
Python
Code
592
4,342
# stdlib import mock # 3p import simplejson as json # project from tests.checks.common import AgentCheckTest, Fixtures from checks import AgentCheck CPU = "CPU" MEM = "MEM" FS = "fs" NET = "net" NET_ERRORS = "net_errors" DISK = "disk" DISK_USAGE = "disk_usage" PODS = "pods" METRICS = [ ('kubernetes.memory.usage', MEM), ('kubernetes.filesystem.usage', FS), ('kubernetes.filesystem.usage_pct', FS), ('kubernetes.cpu.usage.total', CPU), ('kubernetes.network.tx_bytes', NET), ('kubernetes.network.rx_bytes', NET), ('kubernetes.network_errors', NET_ERRORS), ('kubernetes.diskio.io_service_bytes.stats.total', DISK), ('kubernetes.filesystem.usage_pct', DISK_USAGE), ('kubernetes.filesystem.usage', DISK_USAGE), ('kubernetes.pods.running', PODS), ] class TestKubernetes(AgentCheckTest): CHECK_NAME = 'kubernetes' def test_fail(self): # To avoid the disparition of some gauges during the second check mocks = {'_retrieve_metrics': lambda x: json.loads(Fixtures.read_file("metrics.json"))} config = { "instances": [{"host": "foo"}] } with mock.patch('utils.kubeutil.KubeUtil.retrieve_pods_list', side_effect=lambda: json.loads(Fixtures.read_file("pods_list.json", string_escape=False))): with mock.patch('utils.kubeutil.KubeUtil.extract_kube_labels', side_effect=lambda x: json.loads(Fixtures.read_file("kube_labels.json"))): # Can't use run_check_twice due to specific metrics self.run_check(config, mocks=mocks, force_reload=True) self.assertServiceCheck("kubernetes.kubelet.check", status=AgentCheck.CRITICAL) def test_metrics(self): # To avoid the disparition of some gauges during the second check mocks = { '_retrieve_metrics': lambda x: json.loads(Fixtures.read_file("metrics.json")), } config = { "instances": [ { "host": "foo", "enable_kubelet_checks": False } ] } # parts of the json returned by the kubelet api is escaped, keep it untouched with mock.patch('utils.kubeutil.KubeUtil.retrieve_pods_list', side_effect=lambda: json.loads(Fixtures.read_file("pods_list.json", string_escape=False))): with mock.patch('utils.kubeutil.KubeUtil.extract_kube_labels', side_effect=lambda x: json.loads(Fixtures.read_file("kube_labels.json"))): # Can't use run_check_twice due to specific metrics self.run_check_twice(config, mocks=mocks, force_reload=True) expected_tags = [ (['container_name:/kubelet', 'pod_name:no_pod'], [MEM, CPU, NET, DISK]), (['kube_replication_controller:propjoe', 'kube_namespace:default', 'container_name:k8s_POD.e4cc795_propjoe-dhdzk_default_ba151259-36e0-11e5-84ce-42010af01c62_ef0ed5f9', 'pod_name:default/propjoe-dhdzk'], [MEM, CPU, FS, NET, NET_ERRORS]), (['container_name:/kube-proxy', 'pod_name:no_pod'], [MEM, CPU, NET]), (['kube_replication_controller:kube-dns-v8', 'kube_namespace:kube-system', 'container_name:k8s_POD.2688308a_kube-dns-v8-smhcb_kube-system_b80ffab3-3619-11e5-84ce-42010af01c62_295f14ff', 'pod_name:kube-system/kube-dns-v8-smhcb'], [MEM, CPU, FS, NET, NET_ERRORS]), (['container_name:/docker-daemon', 'pod_name:no_pod'], [MEM, CPU, DISK, NET]), (['kube_replication_controller:kube-dns-v8', 'kube_namespace:kube-system', 'container_name:k8s_etcd.2e44beff_kube-dns-v8-smhcb_kube-system_b80ffab3-3619-11e5-84ce-42010af01c62_e3e504ad', 'pod_name:kube-system/kube-dns-v8-smhcb'], [MEM, CPU, FS, NET, NET_ERRORS, DISK]), (['kube_replication_controller:fluentd-cloud-logging-kubernetes-minion', 'kube_namespace:kube-system', 'container_name:k8s_POD.e4cc795_fluentd-cloud-logging-kubernetes-minion-mu4w_kube-system_d0feac1ad02da9e97c4bf67970ece7a1_49dd977d', 'pod_name:kube-system/fluentd-cloud-logging-kubernetes-minion-mu4w'], [MEM, CPU, FS, NET, NET_ERRORS, DISK]), (['kube_replication_controller:kube-dns-v8', 'kube_namespace:kube-system', 'container_name:k8s_skydns.1e752dc0_kube-dns-v8-smhcb_kube-system_b80ffab3-3619-11e5-84ce-42010af01c62_7c1345a1', 'pod_name:kube-system/kube-dns-v8-smhcb'], [MEM, CPU, FS, NET, NET_ERRORS]), (['container_name:/', 'pod_name:no_pod'], [MEM, CPU, FS, NET, NET_ERRORS, DISK]), (['container_name:/system/docker', 'pod_name:no_pod'], [MEM, CPU, DISK, NET]), (['kube_replication_controller:propjoe', 'kube_namespace:default', 'container_name:k8s_propjoe.21f63023_propjoe-dhdzk_default_ba151259-36e0-11e5-84ce-42010af01c62_19879457', 'pod_name:default/propjoe-dhdzk'], [MEM, CPU, FS, NET, NET_ERRORS]), (['container_name:/system', 'pod_name:no_pod'], [MEM, CPU, NET, DISK]), (['kube_replication_controller:kube-ui-v1', 'kube_namespace:kube-system', 'container_name:k8s_POD.3b46e8b9_kube-ui-v1-sv2sq_kube-system_b7e8f250-3619-11e5-84ce-42010af01c62_209ed1dc', 'pod_name:kube-system/kube-ui-v1-sv2sq'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:kube-dns-v8', 'kube_namespace:kube-system', 'container_name:k8s_kube2sky.1afa6a47_kube-dns-v8-smhcb_kube-system_b80ffab3-3619-11e5-84ce-42010af01c62_624bc34c', 'pod_name:kube-system/kube-dns-v8-smhcb'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:propjoe', 'kube_namespace:default', 'container_name:k8s_POD.e4cc795_propjoe-lkc3l_default_3a9b1759-4055-11e5-84ce-42010af01c62_45d1185b', 'pod_name:default/propjoe-lkc3l'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:haproxy-6db79c7bbcac01601ac35bcdb18868b3', 'kube_namespace:default', 'container_name:k8s_POD.e4cc795_haproxy-6db79c7bbcac01601ac35bcdb18868b3-rr7la_default_86527bf8-36cd-11e5-84ce-42010af01c62_5ad59bf3', 'pod_name:default/haproxy-6db79c7bbcac01601ac35bcdb18868b3-rr7la'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:haproxy-6db79c7bbcac01601ac35bcdb18868b3', 'kube_namespace:default', 'container_name:k8s_haproxy.69b6303b_haproxy-6db79c7bbcac01601ac35bcdb18868b3-rr7la_default_86527bf8-36cd-11e5-84ce-42010af01c62_a35b9731', 'pod_name:default/haproxy-6db79c7bbcac01601ac35bcdb18868b3-rr7la'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:kube-ui-v1','kube_namespace:kube-system', 'container_name:k8s_kube-ui.c17839c_kube-ui-v1-sv2sq_kube-system_b7e8f250-3619-11e5-84ce-42010af01c62_d2b9aa90', 'pod_name:kube-system/kube-ui-v1-sv2sq'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:propjoe','kube_namespace:default', 'container_name:k8s_propjoe.21f63023_propjoe-lkc3l_default_3a9b1759-4055-11e5-84ce-42010af01c62_9fe8b7b0', 'pod_name:default/propjoe-lkc3l'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:kube-dns-v8','kube_namespace:kube-system', 'container_name:k8s_healthz.4469a25d_kube-dns-v8-smhcb_kube-system_b80ffab3-3619-11e5-84ce-42010af01c62_241c34d1', 'pod_name:kube-system/kube-dns-v8-smhcb'], [MEM, CPU, FS, NET, NET_ERRORS, DISK]), (['kube_replication_controller:fluentd-cloud-logging-kubernetes-minion','kube_namespace:kube-system', 'container_name:k8s_fluentd-cloud-logging.7721935b_fluentd-cloud-logging-kubernetes-minion-mu4w_kube-system_d0feac1ad02da9e97c4bf67970ece7a1_2c3c0879', 'pod_name:kube-system/fluentd-cloud-logging-kubernetes-minion-mu4w'], [MEM, CPU, FS, NET, NET_ERRORS, DISK]), (['container_name:dd-agent', 'pod_name:no_pod'], [MEM, CPU, FS, NET, NET_ERRORS, DISK]), (['kube_replication_controller:l7-lb-controller'], [PODS]), (['kube_replication_controller:redis-slave'], [PODS]), (['kube_replication_controller:frontend'], [PODS]), (['kube_replication_controller:heapster-v11'], [PODS]), ] for m, _type in METRICS: for tags, types in expected_tags: if _type in types: self.assertMetric(m, count=1, tags=tags) self.coverage_report() def test_historate(self): # To avoid the disparition of some gauges during the second check mocks = {'_retrieve_metrics': lambda x: json.loads(Fixtures.read_file("metrics.json"))} config = { "instances": [ { "host": "foo", "enable_kubelet_checks": False, "use_histogram": True, } ] } # parts of the json returned by the kubelet api is escaped, keep it untouched with mock.patch('utils.kubeutil.KubeUtil.retrieve_pods_list', side_effect=lambda: json.loads(Fixtures.read_file("pods_list.json", string_escape=False))): with mock.patch('utils.kubeutil.KubeUtil.extract_kube_labels', side_effect=lambda x: json.loads(Fixtures.read_file("kube_labels.json"))): # Can't use run_check_twice due to specific metrics self.run_check_twice(config, mocks=mocks, force_reload=True) metric_suffix = ["count", "avg", "median", "max", "95percentile"] expected_tags = [ (['pod_name:no_pod'], [MEM, CPU, NET, DISK, DISK_USAGE, NET_ERRORS]), (['kube_replication_controller:propjoe', 'kube_namespace:default', 'pod_name:default/propjoe-dhdzk'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:kube-dns-v8', 'kube_namespace:kube-system', 'pod_name:kube-system/kube-dns-v8-smhcb'], [MEM, CPU, FS, NET, NET_ERRORS, DISK]), (['kube_replication_controller:fluentd-cloud-logging-kubernetes-minion', 'kube_namespace:kube-system', 'pod_name:kube-system/fluentd-cloud-logging-kubernetes-minion-mu4w'], [MEM, CPU, FS, NET, NET_ERRORS, DISK]), (['kube_replication_controller:kube-dns-v8', 'kube_namespace:kube-system', 'pod_name:kube-system/kube-dns-v8-smhcb'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:propjoe', 'kube_namespace:default', 'pod_name:default/propjoe-dhdzk'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:kube-ui-v1','kube_namespace:kube-system', 'pod_name:kube-system/kube-ui-v1-sv2sq'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:propjoe', 'kube_namespace:default', 'pod_name:default/propjoe-lkc3l'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:haproxy-6db79c7bbcac01601ac35bcdb18868b3', 'kube_namespace:default', 'pod_name:default/haproxy-6db79c7bbcac01601ac35bcdb18868b3-rr7la'], [MEM, CPU, FS, NET, NET_ERRORS]), (['kube_replication_controller:l7-lb-controller'], [PODS]), (['kube_replication_controller:redis-slave'], [PODS]), (['kube_replication_controller:frontend'], [PODS]), (['kube_replication_controller:heapster-v11'], [PODS]), ] for m, _type in METRICS: for m_suffix in metric_suffix: for tags, types in expected_tags: if _type in types: self.assertMetric("{0}.{1}".format(m, m_suffix), count=1, tags=tags) self.coverage_report()
46,733
https://github.com/dlabaj/patternfly-react/blob/master/packages/react-console/src/components/AccessConsoles/__tests__/AccessConsoles.test.tsx
Github Open Source
Open Source
MIT
2,023
patternfly-react
dlabaj
TSX
Code
338
1,084
import React from 'react'; import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { AccessConsoles } from '../AccessConsoles'; import { SerialConsole } from '../../SerialConsole'; import { VncConsole } from '../../VncConsole'; import { DesktopViewer } from '../../DesktopViewer'; import { constants } from '../../common/constants'; const { SERIAL_CONSOLE_TYPE, LOADING } = constants; const MyVncConsoleTestWrapper = () => <p>VNC console text</p>; const SerialConsoleConnected = () => <p>Serial console text</p>; const vnc = { address: 'my.host.com', port: 5902, tlsPort: '5903' }; describe('AccessConsoles', () => { beforeAll(() => { window.HTMLCanvasElement.prototype.getContext = () => ({ canvas: {} } as any); }); test('with SerialConsole as a single child', () => { const { asFragment } = render( <AccessConsoles> <SerialConsole onData={jest.fn()} onConnect={jest.fn()} onDisconnect={jest.fn()} status={LOADING} /> </AccessConsoles> ); expect(asFragment()).toMatchSnapshot(); }); test('with VncConsole as a single child', () => { const { asFragment } = render( <AccessConsoles> <VncConsole host="foo.bar.host" textDisconnected="Disconnected state text" /> </AccessConsoles> ); expect(asFragment()).toMatchSnapshot(); }); test('with SerialConsole and VncConsole as children', () => { const { asFragment } = render( <AccessConsoles> <VncConsole host="foo.bar.host" textDisconnected="Disconnected state text" /> <SerialConsole onData={jest.fn()} onConnect={jest.fn()} onDisconnect={jest.fn()} status={LOADING} /> </AccessConsoles> ); expect(asFragment()).toMatchSnapshot(); }); test('with wrapped SerialConsole as a child', () => { const { asFragment } = render( <AccessConsoles> <SerialConsoleConnected /> </AccessConsoles> ); expect(asFragment()).toMatchSnapshot(); }); test('with preselected SerialConsole', () => { const { asFragment } = render( <AccessConsoles preselectedType={SERIAL_CONSOLE_TYPE}> <SerialConsole onData={jest.fn()} onConnect={jest.fn()} onDisconnect={jest.fn()} status={LOADING} /> </AccessConsoles> ); expect(asFragment()).toMatchSnapshot(); }); test('switching SerialConsole and VncConsole', async () => { const user = userEvent.setup(); render( <AccessConsoles> <MyVncConsoleTestWrapper /> <SerialConsole onData={jest.fn()} onConnect={jest.fn()} onDisconnect={jest.fn()} status={LOADING} /> </AccessConsoles> ); // VNC (first option) is initially selected expect(screen.queryByText(/Loading/)).toBeNull(); expect(screen.getByText('VNC console text')).toBeInTheDocument(); // Open dropdown and select "Serial console" option await user.click(screen.getByRole('button', { name: 'Options menu' })); await user.click(screen.getByText('Serial console', { selector: 'button' })); // VNC content is no longer visible, and loading contents of the Serial console are visible. expect(screen.getByText(/Loading/)).toBeInTheDocument(); expect(screen.queryByText('VNC console text')).toBeNull(); }); test('Empty', () => { const { asFragment } = render(<AccessConsoles />); expect(asFragment()).toMatchSnapshot(); }); test('with DesktopViewer', () => { const { asFragment } = render( <AccessConsoles> <DesktopViewer vnc={vnc} /> </AccessConsoles> ); expect(asFragment()).toMatchSnapshot(); }); });
15,374
https://github.com/csmberkeley/site-v2/blob/master/js/controllers/bios-controller.js
Github Open Source
Open Source
MIT
2,018
site-v2
csmberkeley
JavaScript
Code
1,306
3,115
(function() { angular.module('CSM') .controller('BiosController', function($scope) { /* * Each bio json object has the following properties: * name: the person's first/last/name * details: the person's bio * imgName: the path of the image relative to img/people, or img/team * for exec members * courses: a mapping of "CS61A", "CS61B", "CS61C", "CS70", "CS88", * "EE16A", "EXEC" to the person's role in the course */ const PLACEHOLDER_BIO = { "name": "Coming soon!", "details": "Bios will be posted once mentor interviews are complete.", "imgName": "", "courses": { "CS61A": "", "CS61B": "", "CS61C": "", "CS70": "", "CS88": "", "EE16A": "" } } const COURSES = ["CS61A", "CS61B", "CS61C", "CS70", "CS88", "EE16A", "EXEC"]; const EXEC_BIOS = [ { "name": "Jason Goodman", "courses": { "EXEC": "President" }, "imgName": "jason-exec.jpg" }, { "name": "Chris Allsman", "courses": { "EXEC": "Internal Vice President" }, "imgName": "chris-exec.jpg", "details": "Hi there! I'm a 4th year computer science major from Fresno, California and my pronouns are they/them! I've been with CSM for 6 semesters now, teaching 61A for most of that time. Now I'm excited to help facilitate mentoring sections and some exciting events as IVP! Outside of teaching and education, my interests include cooking, (computational) biology, and avant-garde 20th century music." }, { "name": "Suraj Rampure", "courses": { "EXEC": "External Vice President" }, "imgName": "suraj-exec-sp19.png", "details": "Hey, I\u2019m a third year EECS major from Windsor, Ontario (right across the border from Detroit). I like cars, tech, teaching and rooting for LeBron (go Cavs Lakers!). This is my fifth semester as a part of CSM, and this is my fourth semester as a TA; currently, I\u2019m TA\u2019ing Data 100, but have TA\u2019d CS 61A and Data 8 in the past. I also teach http://imt-decal.org." }, { "name": "Yiling Kao", "courses": { "EXEC": "Communications" }, "imgName": "yiling-kao-square.jpg", "details": "Hello! I'm Yiling (pronounced Ee-ling), a third year Computer Science & Cognitive Science major, and I'm from Irvine, CA, a <20-minute drive away from Disneyland, good boba, and dog beaches a.k.a all my favorite things. I like swimming, sleeping, fruits, and corny jokes and am always down for music and book recommendations. Looking forward to meeting you all!" }, { "name": "Jose Chavez", "courses": { "EXEC": "Socials Chair" }, "imgName": "jose-chavez-exec.jpg", "details": "Hello! I am fourth year Computer Science and Film major. I am a member in the Cal Band and also a TA for CS184. Last summer, for General Motors and Cruise, I built an Android application that allowed autonomous car riders to chat with the car and ask for recommendations on where to eat, shop, and more! Some of free time includes playing flag football, performing in small events with the Cal Band, or director a movie of mine! " }, { "name": "Jonathan Shi", "courses": { "EXEC": "Tech Chair" }, "imgName": "jonathan-shi-exec.jpg", "details": "Hello there! I'm a 2nd year EECS major from the Bay Area. I like programming languages where the compiler yells at you a lot. Outside CSM, I play soprano/alto sax for the Intermission Orchestra, and I spend an inordinate amount of my breaks watching anime. I also play chess and Super Smash Bros. at a reasonable level, so hmu." }, { "name": "Alex Stennet", "courses": { "EXEC": "CS 61A Coordinator" }, "imgName": "alex-stennet.jpg" }, { "name": "Catherine Cang", "courses": { "EXEC": "CS 61A Coordinator" }, "imgName": "catherine-cang1.jpg" }, { "name": "Alan Ton", "courses": { "EXEC": "CS 61B Coordinator" }, "imgName": "alan-ton.jpeg", "details": "Hi! I'm a 3rd year EECS student from Walnut, CA and this is my 4th semester teaching CS61B with CSM." }, { "name": "Danny Chu", "courses": { "EXEC": "CS 61B Coordinator" }, "imgName": "danny-exec.jpg", "details": "Mentoring is bad for you." }, { "name": "Kristen Kafkaloff", "courses": { "EXEC": "CS 70 Coordinator" }, "imgName": "kristen-exec.jpg", "details": "Hi! I love teaching and have been teaching since high school. CSM gave me the extra support I needed to get the most out of CS70 while I was taking it and it\u2019s why I enjoy the course so much. I love outdoorsy stuff, playing basketball, and basically anything on Pinterest (DIY, banana bread, etc). I also LOVE Disney - I know the words to most Disney songs (HSM, Frozen, you name it). " }, { "name": "Max Ovsiankin", "courses": { "EXEC": "CS 70 Coordinator" }, "imgName": "max-ovsiankin-square.jpeg" }, { "name": "Michelle Mao", "courses": { "EXEC": "EE 16A Coordinator" }, "imgName": "michelle-mao-exec.jpg", "details": "I was born in Michigan but spent most of my life in Shanghai--the best city in the world. On campus and aside from CSM, you'll find me working with AWE, performing with the Overtones, or building apps. Off campus I love cooking, biking, and snowboarding. I'm taking a design/philosophy class and the Ethics and Friendship DeCal this semester. Hit me up to chat!" }, { "name": "Dominic Carrano", "courses": { "EXEC": "EE 16A Coordinator" }, "imgName": "dominic-exec.jpg", "details": "Hey there, I'm Dominic! I'm a third year EECS major from Livermore, California interested in signal processing. This is my third semester in CSM for EE 16A, and second as a TA for EE 120. In my free time, I enjoy exercising at the RSF, as well as playing and watching soccer. Looking forward to a great semester!" }, { "name": "Katherine Liu", "courses": { "EXEC": "CS 61C Coordinator" }, "imgName": "katherine-liu-exec.jpg", "details": "Hi! My name's Katherine, and I'm a third year CS major. I love reading and writing, with a particular emphasis on slam poetry. I also love alternative music and dark pop (which lends itself to a lot of indie artists), podcasts (99 Percent Invisible and Serial are my favorites, but I'm always open to more suggestions), and parentheses (except in Scheme). I'm really excited for this semester with y'all!" }, { "name": "Daniel Zhang", "courses": { "EXEC": "CS 61C Coordinator" }, "imgName": "daniel-zhang-exec.jpg" }, { "name": "Alex Kassil", "courses": { "EXEC": "CS 88 Coordinator" }, "imgName": "alex-kassil.png", "details": "HELLO! My name is Alex and I am a second year CS+Math Major. I've been a CS88 TA twice and a Stat 140 tutor once, this is my first time tutoring 61B! I am so excited and I hope you sign up for my section. Come for fun, occasional food, and plenty of high energy learning. :D :D :D" }, { "name": "Chae Park", "courses": { "EXEC": "CS 88 Coordinator" }, "imgName": "chae-exec.jpg", "details": "Hi! I am Chae, and I am a third-year CS major from Carlsbad, CA! In my free time, I enjoy baking, cafe hopping, and drinking boba. My pronouns are she/her" }, { "name": "Aditya Baradwaj", "courses": { "EXEC": "Advisor" }, "imgName": "aditya.jpg" }, { "name": "Jerry Huang", "courses": { "EXEC": "Advisor" }, "imgName": "jerry-exec.jpg" }, { "name": "Yannan Tuo", "courses": { "EXEC": "Advisor" }, "imgName": "yannan-tuo-square.jpg", "details": "\"when nothing goes right, go left\" :^)" }, { "name": "Paul Bitutsky", "courses": { "EXEC": "Advisor" }, "imgName": "paul-exec.jpg" }, { "name": "Varsha Ramakrishnan", "courses": { "EXEC": "Advisor" }, "imgName": "varsha-exec-sp19.jpg", "details": "Hello! I\u2019m a 3rd year EECS major interested in machine learning for virtual and augmented reality. In my free time, I play Nintendo games, read sci-fi novels, and obsess over LotR and the Silmarillion. Go Bears!" }, { "name": "Mudit Gupta", "courses": { "EXEC": "Advisor" }, "imgName": "mudit-exec-sp19.jpg", "details": "Hiya, I'm Mudit \u2013\u2013 a senior in EECS. I spent most of my time outside of my classes doing teaching-related things. I've TAed EE16A, and Head TAed CS170 and now CS61B. Feel free to reach out to me for anything!" } ]; const COURSE_BIOS = [ PLACEHOLDER_BIO ] let bios = EXEC_BIOS.concat(COURSE_BIOS); let split_bios = {}; for (let course of COURSES) { split_bios[course] = []; } for (let i = 0; i < bios.length; ++i) { for (let [course, role] of Object.entries(bios[i].courses)) { if (role !== "Coordinator") { split_bios[course].push(bios[i]); } } } for (var i = 0; i < COURSES.length; ++i) { $scope[COURSES[i]] = split_bios[COURSES[i]].sort((b1, b2) => { return b1["name"].localeCompare(b2["name"]); }); } }); })();
33,002
https://github.com/mrugenmike/pronet-application/blob/master/node_modules/client-session/test/main.js
Github Open Source
Open Source
MIT
2,015
pronet-application
mrugenmike
JavaScript
Code
675
3,153
var cs = require('../index.js'); var assert = require('assert'); //test unit try{ var cs_ins = cs('a'); }catch(e){ assert.equal(e,'secretKey\'s length must longer than 6.') } //test unit try{ var key = 'a' for(var i=0;i<100;i++){ key+='a'; } var cs_ins = cs(key); }catch(e){ assert.equal(e,'secretKey\'s length must shorter than 64.') } //test unit try{ var key = 'a!!!!!!!!!!' var cs_ins = cs(key); }catch(e){ assert.equal(e,'secretKey\'s length must be Letters and Numbers.') } //test unit try{ var cs_ins = cs(null,{maxAge:-1}); }catch(e){ assert.equal(e,'maxAge must be larger than 0 or equal 0, unit is second.') } //test unit try{ var cs_ins = cs(null,{secure:-1}); }catch(e){ assert.equal(e,'secure must be a boolean.') } //test unit try{ var cs_ins = cs(null,{httpOnly:-1}); }catch(e){ assert.equal(e,'httpOnly must be a boolean.') } //test unit var cs_ins = cs(null,{ path:'/test', maxAge:7200, secure:true, httpOnly:false, }); assert.equal(typeof cs_ins.csget,'function') assert.equal(typeof cs_ins.csset,'function') assert.equal(typeof cs_ins.connect,'function') assert.equal(typeof cs_ins.opt,'object') assert.equal(cs_ins.opt.path,'/test') assert.equal(cs_ins.opt.maxAge,7200) assert.equal(cs_ins.opt.secure,true) assert.equal(cs_ins.opt.httpOnly,false) //test unit //use default key var cs_ins_2 = cs(); var req = {headers:{}} var res = { headers:{}, getHeader:function(){ return null }, setHeader:function(cookie){ res.headers = cookie } } var count = 1 var cb = function(){ count++ } cs_ins_2.csget(req,res,cb); assert.equal(count,2); assert.equal(JSON.stringify(req.csession),'{}'); //test unit //use default key var cs_ins_2 = cs(); var req = {headers:{ 'cookie':'.ASPXAUTH=A317020; uin=snoopyxdy' }} var res = { headers:{}, getHeader:function(){ return null }, setHeader:function(cookie){ res.headers = cookie } } var count = 1 var cb = function(){ count++ } cs_ins_2.csget(req,res,cb); assert.equal(count,2); assert.equal(JSON.stringify(req.csession),'{}'); //test unit //use default key var cs_ins_2 = cs(); var req = {headers:{}} var res = { headers:{}, getHeader:function(){ return null }, setHeader:function(name, cookie){ console.log(name,cookie) res.headers.cookie = cookie } } cs_ins_2.csset(req,res); var next_csession = res.headers.cookie; assert.equal(typeof res.headers.cookie,'string'); assert.equal(res.headers.cookie.indexOf('csession=') !== -1, true); assert.equal(res.headers.cookie.indexOf('Max-Age=3600;') !== -1, true); assert.equal(res.headers.cookie.indexOf('Path=/;') !== -1, true); assert.equal(res.headers.cookie.indexOf('HttpOnly') !== -1, true); console.log(next_csession) var req = { headers:{ cookie:next_csession } } cs_ins_2.csget(req,res); assert.equal(typeof req.csession, 'object'); assert.equal(JSON.stringify(req.csession), '{}'); //test unit //use default key var cs_ins_2 = cs(null,{ path:'/test', maxAge:0, secure:true, httpOnly:false, }); var req = {headers:{}} var res = { headers:{}, getHeader:function(){ return null }, setHeader:function(name, cookie){ console.log(name,cookie) res.headers.cookie = cookie } } cs_ins_2.csset(req,res); var next_csession = res.headers.cookie; console.log(next_csession) assert.equal(typeof res.headers.cookie,'string'); assert.equal(res.headers.cookie.indexOf('csession=') !== -1, true); assert.equal(res.headers.cookie.indexOf('Max-Age=3600;') === -1, true); assert.equal(res.headers.cookie.indexOf('Path=/test;') !== -1, true); assert.equal(res.headers.cookie.indexOf('HttpOnly') === -1, true); assert.equal(res.headers.cookie.indexOf('Secure') !== -1, true); console.log(next_csession) var req = { headers:{ cookie:next_csession } } cs_ins_2.csget(req,res); assert.equal(typeof req.csession, 'object'); assert.equal(JSON.stringify(req.csession), '{}'); //test unit add null value //session content var cs_ins_3 = cs(); var req = {headers:{},csession:{"a":1,"bbb":"放到","ccc":"1312jj312l312","dd":null}} var res = { headers:{}, getHeader:function(){ return null }, setHeader:function(name, cookie){ console.log(name,cookie) res.headers.cookie = cookie } } cs_ins_3.csset(req,res); var next_csession = res.headers.cookie; assert.equal(typeof res.headers.cookie,'string'); assert.equal(res.headers.cookie.indexOf('csession=') !== -1, true); assert.equal(res.headers.cookie.indexOf('Max-Age=3600;') !== -1, true); assert.equal(res.headers.cookie.indexOf('Path=/;') !== -1, true); assert.equal(res.headers.cookie.indexOf('HttpOnly') !== -1, true); //next_csession += 'a' //console.log(next_csession) var req2 = { headers:{ cookie:next_csession } } cs_ins_3.csget(req2,res); assert.equal(typeof req2.csession, 'object'); assert.equal(JSON.stringify(req2.csession), '{"a":1,"bbb":"放到","ccc":"1312jj312l312"}'); //test unit //custom key var cs_ins_3 = cs('abcdefghijklmn'); var req = {headers:{},csession:{"a":1,"bbb":"放到","ccc":"1312jj312l312"}} var res = { headers:{}, getHeader:function(){ return null }, setHeader:function(name, cookie){ console.log(name,cookie) res.headers.cookie = cookie } } cs_ins_3.csset(req,res); var next_csession = res.headers.cookie; assert.equal(typeof res.headers.cookie,'string'); assert.equal(res.headers.cookie.indexOf('csession=') !== -1, true); assert.equal(res.headers.cookie.indexOf('Max-Age=3600;') !== -1, true); assert.equal(res.headers.cookie.indexOf('Path=/;') !== -1, true); assert.equal(res.headers.cookie.indexOf('HttpOnly') !== -1, true); //next_csession += 'a' //console.log(next_csession) var req2 = { headers:{ cookie:next_csession } } cs_ins_3.csget(req2,res); assert.equal(typeof req2.csession, 'object'); assert.equal(JSON.stringify(req2.csession), '{"a":1,"bbb":"放到","ccc":"1312jj312l312"}'); //sign error1 var cs_ins_4 = cs('aaaaaaaaaa'); var req = {headers:{},csession:{"a":1,"bbb":"放到","ccc":"1312jj312l312"}} var res = { headers:{}, getHeader:function(){ return null }, setHeader:function(name, cookie){ console.log(name,cookie) res.headers.cookie = cookie } } cs_ins_4.csset(req,res); var next_csession = res.headers.cookie; assert.equal(typeof res.headers.cookie,'string'); assert.equal(res.headers.cookie.indexOf('csession=') !== -1, true); assert.equal(res.headers.cookie.indexOf('Max-Age=3600;') !== -1, true); assert.equal(res.headers.cookie.indexOf('Path=/;') !== -1, true); assert.equal(res.headers.cookie.indexOf('HttpOnly') !== -1, true); //next_csession += 'a' console.log(next_csession) next_csession1 = next_csession.split('csession=')[1] next_csession1 = 'a' + next_csession1 console.log(next_csession1) var req4 = { headers:{ cookie:'csession='+next_csession1 } } cs_ins_4.csget(req4,res); assert.equal(typeof req4.csession, 'object'); assert.equal(JSON.stringify(req4.csession), '{}'); assert.equal(req4['_check_csession_error'], 4); //custom key //set use key1 var cs_ins_4 = cs('key1key1key1'); var req = {headers:{},csession:{"a":1,"bbb":"放到","ccc":"1312jj312l312"}} var res = { headers:{}, getHeader:function(){ return null }, setHeader:function(name, cookie){ console.log(name,cookie) res.headers.cookie = cookie } } cs_ins_4.csset(req,res); var next_csession = res.headers.cookie; assert.equal(typeof res.headers.cookie,'string'); assert.equal(res.headers.cookie.indexOf('csession=') !== -1, true); assert.equal(res.headers.cookie.indexOf('Max-Age=3600;') !== -1, true); assert.equal(res.headers.cookie.indexOf('Path=/;') !== -1, true); assert.equal(res.headers.cookie.indexOf('HttpOnly') !== -1, true); console.log(res.headers.cookie) //get use key2 var cs_ins_6 = cs('key2key2key2') var req6 = { headers:{ cookie:next_csession } } var res6 ={headers:{}} cs_ins_6.csget(req6,res6); assert.equal(typeof req6.csession, 'object'); assert.equal(JSON.stringify(req6.csession), '{}'); assert.equal(req6['_check_csession_error'], 3); console.log('test all success') process.exit(0);
37,439
https://github.com/deemount/accounting/blob/master/benchmarks/appendstructslice32_test.go
Github Open Source
Open Source
MIT
2,021
accounting
deemount
Go
Code
137
553
package benchmarks import ( "testing" "github.com/google/uuid" ) // BenchmarkAppendStructSlice16 func BenchmarkAppendStructSlice32(b *testing.B) { var testDataStructSlice1 = []TestExchangeOrder{ { ID: uuid.New(), CustomerID: 1, Type: "buy", Asset: "EUR", }, { ID: uuid.New(), CustomerID: 2, Type: "buy", Asset: "EUR", }, { ID: uuid.New(), CustomerID: 3, Type: "buy", Asset: "EUR", }, { ID: uuid.New(), CustomerID: 4, Type: "buy", Asset: "EUR", }, { ID: uuid.New(), CustomerID: 5, Type: "buy", Asset: "EUR", }, { ID: uuid.New(), CustomerID: 6, Type: "buy", Asset: "EUR", }, { ID: uuid.New(), CustomerID: 7, Type: "buy", Asset: "EUR", }, { ID: uuid.New(), CustomerID: 8, Type: "buy", Asset: "EUR", }, } b.ResetTimer() for n := 0; n < b.N; n++ { testZeroIntegerIndex1 := 0 result1 := make([]TestExchangeOrder, 32) for i := 0; i < 32; i++ { if i%4 == 0 { result1[i] = testDataStructSlice1[testZeroIntegerIndex1] testZeroIntegerIndex1++ } } } }
12,981
https://github.com/gugenstudio/Xcomp/blob/master/libs/DMath/src/DMT_VecN.h
Github Open Source
Open Source
MIT
2,022
Xcomp
gugenstudio
C
Code
2,212
6,181
//================================================================== /// DMT_VecN.h /// /// Created by Davide Pasca - 2009/5/9 /// See the file "license.txt" that comes with this project for /// copyright info. //================================================================== #ifndef DMT_VECN_H #define DMT_VECN_H #include <stdint.h> #include <cstddef> #include <array> #include <numeric> #include <cmath> #include <functional> #include <algorithm> #include "DMathBase.h" #include "DMT_VecNMask.h" //================================================================== #define FOR_I_N for (int i=0; i<(int)N; ++i) template<typename T, size_t N> class VecN { public: std::array<T,N> v {}; //================================================================== constexpr VecN() {} constexpr VecN( const T& a_ ) { v.fill( a_ ); } constexpr VecN( const std::array<T,N> &src_ ) : v(src_) {} constexpr VecN( const VecN& a, const std::function<T (const T&)> &fun ) { FOR_I_N v[i] = fun( a[i] ); } constexpr static size_t size() { return N; } constexpr void LoadFromMemory( const T (&src)[N] ) { std::copy( std::begin(src), std::end(src), v.begin() ); } constexpr void SetZero() { v.fill( T(0) ); } constexpr bool IsZero() const { return std::all_of( v.begin(), v.end(), [](auto x){ return !x; } ); } bool IsSimilar( const VecN &other, const T &eps ) const { FOR_I_N if ( DAbs( v[i] - other[i] ) > eps ) return false; return true; } constexpr bool IsValid() const { if constexpr ( std::is_floating_point<T>::value ) { for (const auto &x : v) if ( x != x || std::isnan( x ) ) return false; } else if constexpr ( std::is_object<T>::value && !std::is_same< decltype( std::declval<T>().IsValid() ), void>::value ) { for (const auto &x : v) if ( !x.IsValid() ) return false; } return true; } VecN operator +(const T& rval) const {VecN t; FOR_I_N t[i]=v[i]+rval; return t;} VecN operator -(const T& rval) const {VecN t; FOR_I_N t[i]=v[i]-rval; return t;} VecN operator *(const T& rval) const {VecN t; FOR_I_N t[i]=v[i]*rval; return t;} VecN operator /(const T& rval) const {VecN t; FOR_I_N t[i]=v[i]/rval; return t;} VecN operator +(const VecN &rval) const{VecN t; FOR_I_N t[i]=v[i]+rval[i]; return t;} VecN operator -(const VecN &rval) const{VecN t; FOR_I_N t[i]=v[i]-rval[i]; return t;} VecN operator *(const VecN &rval) const{VecN t; FOR_I_N t[i]=v[i]*rval[i]; return t;} VecN operator /(const VecN &rval) const{VecN t; FOR_I_N t[i]=v[i]/rval[i]; return t;} VecN operator -() const { VecN tmp; FOR_I_N tmp.v[i] = -v[i]; return tmp; } VecN operator +=(const VecN &rval) { *this = *this + rval; return *this; } friend bool operator ==( const VecN &l, const VecN &r ) { return l.v == r.v; } friend bool operator !=( const VecN &l, const VecN &r ) { return l.v != r.v; } friend bool operator <( const VecN &l, const VecN &r ) { return l.v < r.v; } constexpr T AddReduce() const { return std::accumulate( v.begin(), v.end(), 0 ); } constexpr T GetDot( const VecN& rval ) const { T acc = 0; FOR_I_N acc += v[i] * rval[i]; return acc; } constexpr VecN GetNormalized() const { return *this * DRSqrt( GetDot( *this ) ); } constexpr T GetLengthSqr() const { return GetDot( *this ); } constexpr T GetLength() const { return DSqrt( GetDot( *this ) ); } constexpr const T &operator [] (size_t i) const { return v[i]; } constexpr T &operator [] (size_t i) { return v[i]; } }; #define _DTPL template<typename T,size_t N> DMT_FINLINE constexpr #define _DTYP VecN<T,N> _DTPL _DTYP DSqrt( const _DTYP &a ) {_DTYP t; FOR_I_N t[i] = DSqrt(a[i] ); return t; } _DTPL _DTYP DRSqrt(const _DTYP &a ) {_DTYP t; FOR_I_N t[i] = DRSqrt(a[i] ); return t; } _DTPL _DTYP DPow( const _DTYP &a, const _DTYP &b ) { _DTYP t; FOR_I_N t[i] = DPow(a[i], b[i] ); return t; } _DTPL _DTYP DSign( const _DTYP &a ) {_DTYP t; FOR_I_N t[i] = DSign(a[i] ); return t; } _DTPL _DTYP DAbs( const _DTYP &a ) {_DTYP t; FOR_I_N t[i] = DAbs(a[i] ); return t; } _DTPL _DTYP DMin( const _DTYP &a, const _DTYP &b ) { _DTYP t; FOR_I_N t[i] = DMin(a[i], b[i] ); return t; } _DTPL _DTYP DMax( const _DTYP &a, const _DTYP &b ) { _DTYP t; FOR_I_N t[i] = DMax(a[i], b[i] ); return t; } _DTPL _DTYP DSin( const _DTYP &a ) {_DTYP t; FOR_I_N t[i] = DSin(a[i] ); return t; } _DTPL _DTYP DCos( const _DTYP &a ) {_DTYP t; FOR_I_N t[i] = DCos(a[i] ); return t; } _DTPL _DTYP DFloor(const _DTYP &a) { return {a, [](auto x){ return DFloor( x ); }}; } _DTPL _DTYP DCeil(const _DTYP &a) { return {a, [](auto x){ return DCeil( x ); }}; } _DTPL auto DClamp( const _DTYP &a, const _DTYP &l, const _DTYP &r ) { _DTYP t; FOR_I_N t[i] = DClamp( a[i], l[i], r[i] ); return t; } _DTPL _DTYP operator + (const T &lval, const _DTYP &rval) { return rval + lval; } _DTPL _DTYP operator - (const T &lval, const _DTYP &rval) { return -(rval - lval); } _DTPL _DTYP operator * (const T &lval, const _DTYP &rval) { return rval * lval; } _DTPL T DDot( const _DTYP& a, const _DTYP& b ) { T acc = 0; FOR_I_N acc += a[i] * b[i]; return acc; } #undef _DTPL #undef _DTYP template <typename TV, size_t N, typename TP> DMT_FINLINE VecN<TV,N> DPow( const VecN<TV,N> &a, const TP &p ) { VecN<TV,N> tmp; for (int i=0; i < (int)N; ++i) tmp[i] = pow( a[i], (TV)p ); return tmp; } /* template <class T, size_t N> VecNMask CmpMaskLT( const VecN<T,N> &lval, const VecN<T,N> &rval ) { DMT_ASSERT( 0 ); return VecNMaskEmpty; } template <class T, size_t N> VecNMask CmpMaskGT( const VecN<T,N> &lval, const VecN<T,N> &rval ) { DMT_ASSERT( 0 ); return VecNMaskEmpty; } template <class T, size_t N> VecNMask CmpMaskEQ( const VecN<T,N> &lval, const VecN<T,N> &rval ) { DMT_ASSERT( 0 ); return VecNMaskEmpty; } template <class T, size_t N> VecNMask CmpMaskNE( const VecN<T,N> &lval, const VecN<T,N> &rval ) { DMT_ASSERT( 0 ); return VecNMaskEmpty; } template <class T, size_t N> VecNMask CmpMaskLE( const VecN<T,N> &lval, const VecN<T,N> &rval ) { DMT_ASSERT( 0 ); return VecNMaskEmpty; } template <class T, size_t N> VecNMask CmpMaskGE( const VecN<T,N> &lval, const VecN<T,N> &rval ) { DMT_ASSERT( 0 ); return VecNMaskEmpty; } */ #undef FOR_I_N //================================================================== #define FOR_I_N for (int i=0; i<DMT_SIMD_FLEN; ++i) #if defined(DMATH_USE_M128) template<> class VecN<float,DMT_SIMD_FLEN> { //================================================================== /// 128 bit 4-way float SIMD //================================================================== public: __m128 v {}; //================================================================== constexpr VecN() {} constexpr VecN( const __m128 &v_ ) { v = v_; } constexpr VecN( const VecN &v_ ) { v = v_.v; } constexpr VecN( const float& a_ ) { v = _mm_set_ps1( a_ ); } void SetZero() { v = _mm_setzero_ps(); } size_t size() const { return DMT_SIMD_FLEN; } // TODO: add specialized AddReduce() float AddReduce() const { return (*this)[0] + (*this)[1] + (*this)[2] + (*this)[3]; } VecN operator + (const float& rval) const { return _mm_add_ps( v, _mm_set_ps1( rval ) ); } VecN operator - (const float& rval) const { return _mm_sub_ps( v, _mm_set_ps1( rval ) ); } VecN operator * (const float& rval) const { return _mm_mul_ps( v, _mm_set_ps1( rval ) ); } VecN operator / (const float& rval) const { return _mm_div_ps( v, _mm_set_ps1( rval ) ); } VecN operator + (const VecN &rval) const { return _mm_add_ps( v, rval.v ); } VecN operator - (const VecN &rval) const { return _mm_sub_ps( v, rval.v ); } VecN operator * (const VecN &rval) const { return _mm_mul_ps( v, rval.v ); } VecN operator / (const VecN &rval) const { return _mm_div_ps( v, rval.v ); } VecN operator -() const { return _mm_sub_ps( _mm_setzero_ps(), v ); } VecN operator +=(const VecN &rval) { *this = *this + rval; return *this; } friend VecNMask CmpMaskLT( const VecN &lval, const VecN &rval ) { return _mm_cmplt_ps( lval.v, rval.v ); } friend VecNMask CmpMaskGT( const VecN &lval, const VecN &rval ) { return _mm_cmpgt_ps( lval.v, rval.v ); } friend VecNMask CmpMaskEQ( const VecN &lval, const VecN &rval ) { return _mm_cmpeq_ps( lval.v, rval.v ); } friend VecNMask CmpMaskNE( const VecN &lval, const VecN &rval ) { return _mm_cmpneq_ps( lval.v, rval.v ); } friend VecNMask CmpMaskLE( const VecN &lval, const VecN &rval ) { return _mm_cmple_ps( lval.v, rval.v ); } friend VecNMask CmpMaskGE( const VecN &lval, const VecN &rval ) { return _mm_cmpge_ps( lval.v, rval.v ); } friend bool operator ==( const VecN &lval, const VecN &rval ) { return VecNMaskEmpty == CmpMaskNE( lval, rval ); } friend bool operator !=( const VecN &lval, const VecN &rval ) { return VecNMaskFull != CmpMaskEQ( lval, rval ); } //#if defined(_MSC_VER) // const float &operator [] (size_t i) const { return v.m128_f32[i]; } // float &operator [] (size_t i) { return v.m128_f32[i]; } //#else const float &operator [] (size_t i) const { return ((const float *)&v)[i]; } float &operator [] (size_t i) { return ((float *)&v)[i]; } //#endif }; #elif defined(DMATH_USE_M512) template<> class VecN<float,DMT_SIMD_FLEN> { //================================================================== /// 512 bit 16-way float SIMD //================================================================== public: __m512 v {}; //================================================================== constexpr VecN() {} constexpr VecN( const __m512 &v_ ) { v = v_; } constexpr VecN( const VecN &v_ ) { v = v_.v; } constexpr VecN( const float& a_ ) { v = _mm512_set_1to16_ps( a_ ); } constexpr VecN( const float *p_ ) { v = _mm512_expandd( (void *)p_, _MM_FULLUPC_NONE, _MM_HINT_NONE ); } // unaligned void SetZero() { v = _mm512_setzero_ps(); } float AddReduce() const { return _mm512_reduce_add_ps( v ); } VecN operator + (const float& rval) const { return _mm512_add_ps( v, _mm512_set_1to16_ps( rval ) ); } VecN operator - (const float& rval) const { return _mm512_sub_ps( v, _mm512_set_1to16_ps( rval ) ); } VecN operator * (const float& rval) const { return _mm512_mul_ps( v, _mm512_set_1to16_ps( rval ) ); } VecN operator / (const float& rval) const { return _mm512_div_ps( v, _mm512_set_1to16_ps( rval ) ); } VecN operator + (const VecN &rval) const { return _mm512_add_ps( v, rval.v ); } VecN operator - (const VecN &rval) const { return _mm512_sub_ps( v, rval.v ); } VecN operator * (const VecN &rval) const { return _mm512_mul_ps( v, rval.v ); } VecN operator / (const VecN &rval) const { return _mm512_div_ps( v, rval.v ); } VecN operator -() const { return _mm512_sub_ps( _mm512_setzero_ps(), v ); } VecN operator +=(const VecN &rval) { *this = *this + rval; return *this; } // TODO: verify that it works ! friend VecNMask CmpMaskLT( const VecN &lval, const VecN &rval ) { return _mm512_cmplt_ps( lval.v, rval.v ); } friend VecNMask CmpMaskGT( const VecN &lval, const VecN &rval ) { return ~_mm512_cmple_ps( lval.v, rval.v ); } friend VecNMask CmpMaskEQ( const VecN &lval, const VecN &rval ) { return _mm512_cmpeq_ps( lval.v, rval.v ); } friend VecNMask CmpMaskNE( const VecN &lval, const VecN &rval ) { return _mm512_cmpneq_ps( lval.v, rval.v ); } friend VecNMask CmpMaskLE( const VecN &lval, const VecN &rval ) { return _mm512_cmple_ps( lval.v, rval.v ); } friend VecNMask CmpMaskGE( const VecN &lval, const VecN &rval ) { return ~_mm512_cmplt_ps( lval.v, rval.v ); } friend bool operator ==( const VecN &lval, const VecN &rval ) { return VecNMaskEmpty == CmpMaskNE( lval, rval ); } friend bool operator !=( const VecN &lval, const VecN &rval ) { return VecNMaskFull != CmpMaskEQ( lval, rval ); } const float &operator [] (size_t i) const { return v.v[i]; } float &operator [] (size_t i) { return v.v[i]; } }; #endif // specialization of functions #define _DTPL template<> DMT_FINLINE #define _DTYP VecN<float,DMT_SIMD_FLEN> #if defined(DMATH_USE_M128) //================================================================== //================================================================== //================================================================== _DTPL _DTYP DSqrt( const _DTYP &a ) { return _mm_sqrt_ps( a.v ); } _DTPL _DTYP DRSqrt( const _DTYP &a ) { return _mm_rsqrtnr_ps( a.v ); } //_DTPL _DTYP DRSqrt( const _DTYP &a ) { return _mm_rsqrt_ps( a.v ); } // TODO: get a proper _mm_pow_ps !!! //_DTPL _DTYP DPow( const _DTYP &a, const _DTYP &b ){ return _mm_pow_ps( a.v, b.v ); } _DTPL _DTYP DPow( const _DTYP &a, const _DTYP &b ) { _DTYP tmp; for (size_t i=0; i < DMT_SIMD_FLEN; ++i) tmp[i] = powf( a[i], b[i] ); return tmp; } //================================================================== _DTPL _DTYP DSign( const _DTYP &a ) { const __m128 zero = _mm_setzero_ps(); const __m128 selectPos = _mm_cmpgt_ps( a.v, zero ); // > 0 const __m128 selectNeg = _mm_cmplt_ps( a.v, zero ); // < 0 __m128 res = _mm_and_ps( selectPos, _mm_set_ps1( 1.0f ) ); res = _mm_or_ps( res, _mm_and_ps( selectNeg, _mm_set_ps1( -1.0f ) ) ); return res; } _DTPL _DTYP DAbs( const _DTYP &a ) { static const uint32_t notSignBitMask = ~0x80000000; return _mm_and_ps( a.v, _mm_set_ps1( *(float *)&notSignBitMask ) ); } _DTPL _DTYP DMin( const _DTYP &a, const _DTYP &b ) { return _mm_min_ps( a.v, b.v ); } _DTPL _DTYP DMax( const _DTYP &a, const _DTYP &b ) { return _mm_max_ps( a.v, b.v ); } #elif defined(DMATH_USE_M512) //================================================================== //================================================================== //================================================================== _DTPL _DTYP DSqrt( const _DTYP &a ) { return _mm512_sqrt_ps( a.v ); } _DTPL _DTYP DRSqrt( const _DTYP &a ) { return _mm512_rsqrt_ps( a.v ); } _DTPL _DTYP DPow( const _DTYP &a, const _DTYP &b ){ return _mm512_pow_ps( a.v, b.v ); } //================================================================== _DTPL _DTYP DSign( const _DTYP &a ) { const __m512 zero = _mm512_setzero_ps(); const __mmask selectPos = _mm512_cmpnle_ps( a.v, zero ); // > const __mmask selectNeg = _mm512_cmplt_ps( a.v, zero ); // < __m512 res = _mm512_mask_movd( zero, selectPos, _mm512_set_1to16_ps( 1.0f ) ); res = _mm512_mask_movd( res , selectNeg, _mm512_set_1to16_ps( -1.0f ) ); return res; } _DTPL _DTYP DAbs( const _DTYP &a ) { return _mm512_maxabs_ps( a.v, a.v ); } _DTPL _DTYP DMin( const _DTYP &a, const _DTYP &b ) { return _mm512_min_ps( a.v, b.v ); } _DTPL _DTYP DMax( const _DTYP &a, const _DTYP &b ) { return _mm512_max_ps( a.v, b.v ); } #else //================================================================== //================================================================== //================================================================== #endif #undef _DTPL #undef _DTYP #undef FOR_I_N #endif
17,760
https://github.com/ZZHGit/ExSwift/blob/master/ExSwiftTests/ExSwiftFloatTests.swift
Github Open Source
Open Source
BSD-2-Clause-FreeBSD
2,015
ExSwift
ZZHGit
Swift
Code
67
267
// // ExSwiftFloatTests.swift // ExSwift // // Created by pNre on 04/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import XCTest class ExSwiftFloatTests: XCTestCase { func testAbs() { XCTAssertGreaterThan(Float(-1.0).abs(), Float(0)) } func testSqrt() { XCTAssertEqual(Float(2), Float(4.0).sqrt()) } func testFloor () { XCTAssertEqual(Float(2), Float(2.9).floor()) } func testCeil () { XCTAssertEqual(Float(3), Float(2.9).ceil()) } func testRound () { XCTAssertEqual(Float(3), Float(2.5).round()) XCTAssertEqual(Float(2), Float(2.4).round()) } func testRandom() { } }
1,636
https://github.com/GeneRainier/salmon-run-working/blob/master/SalmonRunWorking/Assets/Scripts/Managers/MenuManager.cs
Github Open Source
Open Source
MIT
null
salmon-run-working
GeneRainier
C#
Code
245
593
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; /* * Manager script to handle the various UI elements such as buttons and panels * * Authors: Benjamin Person (Editor 2020) */ public class MenuManager : MonoBehaviour { // The buttons along the tower panel in the UI [Header("Tower Buttons")] [SerializeField] private Button anglerButton = null; [SerializeField] private Button rangerButton = null; [SerializeField] private Button damButton = null; [SerializeField] private Button salmonLadderButton = null; [SerializeField] private Button seaLionButton = null; [SerializeField] private Button truckButton = null; [SerializeField] private Button tunnelButton = null; /* * Enables the towers of a particular type * * @param tower The type of tower we are enabling */ public void Enable(TowerType tower) { Toggle(tower, true); } /* * Disables the towers of a particular type * * @param tower The type of tower we are enabling */ public void Disable(TowerType tower) { Toggle(tower, false); } /* * Toggles the button for a type of tower based on whether it is enabled currently * * @param tower The type of tower we are enabling the buttons for * @param toggle Whether we are enabling or disabling */ public void Toggle(TowerType tower, bool toggle) { switch (tower) { case TowerType.Angler: anglerButton.interactable = toggle; break; case TowerType.Ranger: rangerButton.interactable = toggle; break; case TowerType.Dam: damButton.interactable = toggle; break; case TowerType.Ladder: salmonLadderButton.interactable = toggle; break; case TowerType.SeaLion: seaLionButton.interactable = toggle; break; case TowerType.Truck: truckButton.interactable = toggle; break; case TowerType.Tunnel: tunnelButton.interactable = toggle; break; } } }
7,249
https://github.com/HuttonICS/germinate-server/blob/master/src/main/resources/jhi/germinate/server/util/database/migration/V3.3.2__update.sql
Github Open Source
Open Source
Apache-2.0
2,020
germinate-server
HuttonICS
SQL
Code
56
156
/**************************************************/ /* GERMINATE 3 */ /* MIGRATION SCRIPT */ /* v3.3.1 -> v3.3.2 */ /**************************************************/ DROP TABLE IF EXISTS `databaseversions`; /* Rename `date` to `date_start` and add a new column called `date_end` */ ALTER TABLE `datasets` CHANGE COLUMN `date` `date_start` DATE NULL DEFAULT NULL AFTER `description`; ALTER TABLE `datasets` ADD COLUMN `date_end` DATE NULL AFTER `date_start`;
25,209
https://github.com/OctaPal/microservices-demo-1/blob/master/01_Terraform_IaC/create-tf-remote-storage.sh
Github Open Source
Open Source
Apache-2.0
null
microservices-demo-1
OctaPal
Shell
Code
78
256
#!/bin/bash RESOURCE_GROUP_NAME=rg-terraform STORAGE_ACCOUNT_NAME=hipsterisaac CONTAINER_NAME=tfstate # Create resource group # az group create --name $RESOURCE_GROUP_NAME --location eastus Create storage account az storage account create --resource-group $RESOURCE_GROUP_NAME --name $STORAGE_ACCOUNT_NAME --sku Standard_LRS --encryption-services blob # Get storage key ACCOUNT_KEY=$(az storage account keys list --resource-group $RESOURCE_GROUP_NAME --account-name $STORAGE_ACCOUNT_NAME --query '[0].value' -o tsv) # Create blob storage container az storage container create --name tfstate --account-name $STORAGE_ACCOUNT_NAME --account-key $ACCOUNT_KEY # Create service principal # az ad sp create-for-rbac -n "" --role Contributor --scopes /subscriptions/<SUBCRIPTION_ID>/resourceGroups/$RESOURCE_GROUP_NAME
19,724
https://github.com/TrendingTechnology/pydatagovgr/blob/master/pydatagovgr/__init__.py
Github Open Source
Open Source
MIT
2,021
pydatagovgr
TrendingTechnology
Python
Code
7
23
from .client import DataGovClient __version__ = "0.1.9"
895
https://github.com/iQueSoft/iOSDemo_VideoRecord/blob/master/VideoRecordSample/Business layer/VideoProcessor/VRSVideoProcessor.m
Github Open Source
Open Source
MIT
2,015
iOSDemo_VideoRecord
iQueSoft
Objective-C
Code
400
1,549
// // VRSVideoProcessor.m // VideoRecordSample // // Created by Ruslan Shevtsov on 4/3/15. // Copyright (c) 2015 iQueSoft rights reserved. // #import "VRSVideoProcessor.h" // Frameworks #import <AVFoundation/AVFoundation.h> #import <AssetsLibrary/AssetsLibrary.h> // Models #import "VRSVideo.h" // Managers #import "VRSFileManager.h" @interface VRSVideoProcessor () @property (nonatomic, strong) NSMutableSet *assests; @property (nonatomic, strong) NSMutableSet *sessions; @end @implementation VRSVideoProcessor - (void)concateVideos:(NSMutableArray *)anVideos outputURL:(NSURL *)anOutputURL completion:(void(^)(BOOL isCompletion))aCompletionBlock { if (![anVideos count]) { aCompletionBlock(NO); return; } __block NSMutableArray *audioTracks = [NSMutableArray new]; __block NSMutableArray *videoTracks = [NSMutableArray new]; NSMutableArray *assests = [NSMutableArray array]; for (int index = ((int)[anVideos count] - 1); index >= 0; index--) { NSURL *url = ((VRSVideo *)anVideos[index]).fileURL; AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:@{AVURLAssetPreferPreciseDurationAndTimingKey: @YES}]; if (asset) { [assests addObject:asset]; } [videoTracks addObjectsFromArray:[asset tracksWithMediaType:AVMediaTypeVideo]]; [audioTracks addObjectsFromArray:[asset tracksWithMediaType:AVMediaTypeAudio]]; } if (![videoTracks count]) { aCompletionBlock(NO); return; } [self.assests addObjectsFromArray:assests]; AVMutableComposition *composition = [AVMutableComposition new]; if ([audioTracks count] > 0) { AVMutableCompositionTrack *audioTrackComposition = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid]; for (int index = 0; index < ((int)[audioTracks count]); index++) { AVAssetTrack *audioTrack = audioTracks[index]; CMTime duration; CMTime audioDuration = audioTrack.timeRange.duration; duration = audioDuration; if ([videoTracks count] > index) { AVAssetTrack *videoTrack = videoTracks[index]; CMTime videoDuration = videoTrack.timeRange.duration; if (CMTimeCompare(audioDuration, videoDuration) == 1) { duration = videoDuration; } } [audioTrackComposition insertTimeRange:CMTimeRangeMake(kCMTimeZero, duration) ofTrack:audioTrack atTime:kCMTimeZero error:nil]; } } AVMutableCompositionTrack *videoTrackComposition = [composition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid]; [videoTracks enumerateObjectsUsingBlock:^(AVAssetTrack *track, NSUInteger index, BOOL *stop) { AVAssetTrack *videoTrack = videoTracks[index]; CMTime duration; CMTime videoDuration = videoTrack.timeRange.duration; duration = videoDuration; if ([audioTracks count] > index) { AVAssetTrack *audioTrack = audioTracks[index]; CMTime audioDuration = audioTrack.timeRange.duration; if (CMTimeCompare(videoDuration, audioDuration) == 1) { duration = audioDuration; } } [videoTrackComposition insertTimeRange:CMTimeRangeMake(kCMTimeZero, duration) ofTrack:videoTrack atTime:kCMTimeZero error:nil]; }]; NSURL *outputURL = anOutputURL; AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPreset1280x720]; exportSession.outputFileType = AVFileTypeQuickTimeMovie; exportSession.shouldOptimizeForNetworkUse = YES; exportSession.outputURL = outputURL; [self.sessions addObject:exportSession]; __weak typeof(self) weakSelf = self; DDLogDebug(@"Video processing: start concate videos"); [exportSession exportAsynchronouslyWithCompletionHandler:^ { switch (exportSession.status) { case AVAssetExportSessionStatusFailed: { DDLogError(@"Video processing: export session status failed"); RemoveFile(outputURL); aCompletionBlock(NO); break; } case AVAssetExportSessionStatusCompleted: { DDLogDebug(@"Video processing: success"); aCompletionBlock(YES); break; } case AVAssetExportSessionStatusCancelled: { DDLogError(@"Video processing: export session status cancelled"); RemoveFile(outputURL); aCompletionBlock(NO); break; } default: { break; } } [weakSelf.sessions removeObject:exportSession]; [assests enumerateObjectsUsingBlock:^(id asset, NSUInteger idx, BOOL *stop) { [weakSelf.assests removeObject:asset]; }]; }]; } #pragma mark - #pragma mark Lazy load - (NSMutableSet *)sessions { if (_sessions == nil) { _sessions = [NSMutableSet set]; } return _sessions; } - (NSMutableSet *)assests { if (_assests == nil) { _assests = [NSMutableSet set]; } return _assests; } @end
12,044
https://github.com/T4rk1n/dazzler/blob/master/src/html/components/Progress.tsx
Github Open Source
Open Source
MIT
2,021
dazzler
T4rk1n
TSX
Code
35
125
import * as React from 'react'; import {enhanceProps} from 'commons'; import {HtmlOmittedProps, DazzlerHtmlProps} from '../../commons/js/types'; type Props = Omit<React.DetailedHTMLProps<React.ProgressHTMLAttributes<HTMLProgressElement>, HTMLProgressElement>, HtmlOmittedProps> & DazzlerHtmlProps; const Progress = (props: Props) => <progress {...enhanceProps(props)} /> export default React.memo(Progress);
36,999
https://github.com/venishjoe/omnis/blob/master/src/net/venishjoe/omnis/controllers/OmnisGUIEditorController.java
Github Open Source
Open Source
MIT
null
omnis
venishjoe
Java
Code
1,013
6,801
/* * The MIT License (MIT) * * Copyright (c) 2013 Venish Joe, http://venishjoe.net, venish@venishjoe.net * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.venishjoe.omnis.controllers; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.ResourceBundle; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.SelectionMode; import javafx.scene.control.TablePosition; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.stage.DirectoryChooser; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.StageStyle; import net.venishjoe.omnis.commons.OmnisCoreUtils; import net.venishjoe.omnis.data.model.OmnisCategoryTreeDataModel; import net.venishjoe.omnis.data.model.OmnisDirScannerPathsDataModel; import net.venishjoe.omnis.data.model.OmnisEditorScanTypeDataModel; import net.venishjoe.omnis.data.model.OmnisEditorTableColumnsDataModel; import net.venishjoe.omnis.data.process.OmnisEditorDataProcessor; import net.venishjoe.omnis.gui.OmnisGUIHelper; import net.venishjoe.omnis.staticdata.OmnisGlobalConstants; import net.venishjoe.omnis.staticdata.OmnisGlobalMessages; import net.venishjoe.omnis.staticdata.OmnisGlobalVariables; import net.venishjoe.omnis.thirdparty.dialog.Dialog; import org.apache.log4j.Logger; public class OmnisGUIEditorController implements Initializable, EventHandler<ActionEvent>, ChangeListener<TreeItem<OmnisCategoryTreeDataModel>> { private static Logger logger = Logger.getLogger(OmnisGUIEditorController.class); @FXML private TreeView<OmnisCategoryTreeDataModel> omnisEditorTree; @FXML private TextField omnisEditorMainCatTxt; @FXML private TextField omnisEditorSubCatTxt; @FXML private TextField omnisEditorIconTxt; @FXML private ImageView omnisEditorCatImgView; @FXML private TableView<OmnisDirScannerPathsDataModel> omnisEditorScanTable; @FXML private Button omnisEditorDeleteCatButton; @FXML private ComboBox<OmnisEditorScanTypeDataModel> omnisEditorNewDirCB; @FXML private TextField omnisEditorNewDirTxt; @FXML private Button omnisEditorNewDirAddButton; @FXML private Button omnisEditorNewDirDeleteButton; @FXML private Button omnisEditorAddCatButton; @FXML private HBox omnisEditorStatusBarHB; @FXML private TextField omnisEditorNewDirExcTxt; @FXML private Label omnisEditorNewDirExcLbl; @FXML private ImageView omnisEditorFileChooserIV; @FXML private ImageView omisEditorAddCatIconIV; @FXML private TextField _H_omnisEditorHiddenSubCatId; @FXML private TextField _H_omnisEditorHiddenMainCat; @FXML private TextField _H_omnisEditorHiddenIsSubCat; private OmnisEditorDataProcessor omnisEditorDataProcessor; private OmnisGUIHelper omnisGUIHelper; @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public void initialize(URL location, ResourceBundle resources) { logger.debug("Entering OmnisGUIEditorController.initialize()"); try { omnisEditorDataProcessor = new OmnisEditorDataProcessor(); omnisGUIHelper = new OmnisGUIHelper(); //Populating the tree omnisEditorTree.setRoot(omnisEditorDataProcessor.createTreeView()); omnisEditorTree.setShowRoot(false); omnisEditorTree.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); omnisEditorTree.getSelectionModel().selectedItemProperty().addListener(this); //Load Editor Table Columns OmnisEditorTableColumnsDataModel omnisEditorTableColumnsDataModel; ArrayList<OmnisEditorTableColumnsDataModel> omnisEditorTableColumnsDataModelAL = (ArrayList<OmnisEditorTableColumnsDataModel>) omnisEditorDataProcessor.getOmnisEditorTableColums(); for(int indexi=0;indexi<omnisEditorTableColumnsDataModelAL.size();indexi++){ omnisEditorTableColumnsDataModel = (OmnisEditorTableColumnsDataModel) omnisEditorTableColumnsDataModelAL.get(indexi); omnisEditorScanTable.getColumns().add(omnisGUIHelper.createOmnisEditorTableColumn( omnisEditorTableColumnsDataModel.getOmnisEditorTableColumnName(), omnisEditorTableColumnsDataModel.getOmnisEditorTableColumnProperty(), omnisEditorTableColumnsDataModel.getOmnisEditorTableColumnMinWidth())); } //Populate Add New Directory ComboBox omnisEditorNewDirCB.setItems(omnisEditorDataProcessor.getOmnisEditorNewDirectoryScanTypeData()); omnisEditorNewDirCB.getSelectionModel().selectFirst(); //Disabling single row selection. //omnisEditorScanTable.getSelectionModel().setCellSelectionEnabled(true); //Listener for Table omnisEditorScanTable.getSelectionModel().getSelectedCells().addListener(new ListChangeListener<TablePosition>() { @Override public void onChanged(Change<? extends TablePosition> tablePosition) { //Enable Delete Directory Button omnisEditorNewDirDeleteButton.setDisable(false); }}); /* * Disabling Listener for Text Field. Replaced with Image View. //Listener for Directory Chooser omnisEditorNewDirTxt.focusedProperty().addListener(new ChangeListener<Boolean>() { public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if(newValue.booleanValue()) { //Someone clicked the text field. Present Directory Chooser } } } ); */ //Enable & Disable fields according to selection omnisEditorDeleteCatButton.setDisable(true); omnisEditorNewDirCB.setDisable(true); omnisEditorNewDirTxt.setDisable(true); omnisEditorFileChooserIV.setDisable(true); omnisEditorFileChooserIV.setOpacity(OmnisGlobalConstants.OMNIS_IMAGE_OPACITY_DISABLED); omnisEditorNewDirAddButton.setDisable(true); omnisEditorNewDirDeleteButton.setDisable(true); omnisEditorAddCatButton.setDisable(false); omnisEditorMainCatTxt.setDisable(false); omnisEditorSubCatTxt.setDisable(true); omnisEditorIconTxt.setDisable(false); omisEditorAddCatIconIV.setDisable(false); omnisEditorFileChooserIV.setOpacity(OmnisGlobalConstants.OMNIS_IMAGE_OPACITY_ENABLED); omnisEditorNewDirExcTxt.setDisable(true); omnisEditorNewDirExcLbl.setDisable(true); } catch (Exception genericException) { logger.error(OmnisGlobalConstants.OMNIS_EXCEPTION_PREFIX + genericException.getStackTrace()[0].getMethodName(), genericException); Dialog.showThrowable(OmnisGlobalConstants.OMNIS_DIALOG_TITLE, OmnisGlobalMessages.OMNISGUICONTROLLEREDITOR_INIT_ERROR, genericException); } } @FXML protected void omnisEditorCloseButtonClicked(ActionEvent closeButtonClicked) { logger.debug("Entering OmnisGUIEditorController.omnisEditorCloseButtonClicked()"); try { OmnisGlobalVariables.OMNIS_EDITOR_GUI_STAGE.close(); } catch (Exception genericException) { logger.error(OmnisGlobalConstants.OMNIS_EXCEPTION_PREFIX + genericException.getStackTrace()[0].getMethodName(), genericException); Dialog.showThrowable(OmnisGlobalConstants.OMNIS_DIALOG_TITLE, OmnisGlobalMessages.OMNISGUIMAINCONTROLLER_SEARCH_ERROR, genericException); } } @SuppressWarnings("unchecked") @Override @FXML public void changed(ObservableValue<? extends TreeItem<OmnisCategoryTreeDataModel>> omnisCategoryTreeDataModelOV, TreeItem<OmnisCategoryTreeDataModel> omnisCategoryTreeDataModelOSV, TreeItem<OmnisCategoryTreeDataModel> omnisCategoryTreeDataModelNSV) { logger.debug("Entering OmnisGUIEditorController.changed()"); HashMap<String, Object> omnisEditorDetailsHM; omnisEditorDataProcessor = new OmnisEditorDataProcessor(); try { if (omnisCategoryTreeDataModelNSV != null) { OmnisCategoryTreeDataModel omnisCategoryTreeDataModelSV = omnisCategoryTreeDataModelNSV.getValue(); //Enable/Disable fields according to selection if (omnisCategoryTreeDataModelNSV.getChildren().size() == 0){ omnisEditorDeleteCatButton.setDisable(false); omnisEditorNewDirCB.setDisable(false); omnisEditorNewDirTxt.setDisable(false); omnisEditorFileChooserIV.setDisable(false); omnisEditorFileChooserIV.setOpacity(OmnisGlobalConstants.OMNIS_IMAGE_OPACITY_ENABLED); omnisEditorNewDirAddButton.setDisable(false); omnisEditorAddCatButton.setDisable(true); omnisEditorMainCatTxt.setDisable(true); omnisEditorSubCatTxt.setDisable(true); omnisEditorIconTxt.setDisable(true); omisEditorAddCatIconIV.setDisable(true); omnisEditorFileChooserIV.setOpacity(OmnisGlobalConstants.OMNIS_IMAGE_OPACITY_DISABLED); omnisEditorNewDirDeleteButton.setDisable(true); omnisEditorNewDirExcTxt.setDisable(false); omnisEditorNewDirExcLbl.setDisable(false); } else { omnisEditorDeleteCatButton.setDisable(true); omnisEditorNewDirCB.setDisable(true); omnisEditorNewDirTxt.setDisable(true); omnisEditorFileChooserIV.setDisable(true); omnisEditorFileChooserIV.setOpacity(OmnisGlobalConstants.OMNIS_IMAGE_OPACITY_DISABLED); omnisEditorNewDirAddButton.setDisable(true); omnisEditorAddCatButton.setDisable(false); omnisEditorMainCatTxt.setDisable(true); omnisEditorSubCatTxt.setDisable(false); omnisEditorIconTxt.setDisable(true); omisEditorAddCatIconIV.setDisable(true); omnisEditorFileChooserIV.setOpacity(OmnisGlobalConstants.OMNIS_IMAGE_OPACITY_DISABLED); omnisEditorNewDirDeleteButton.setDisable(true); omnisEditorNewDirExcTxt.setDisable(true); omnisEditorNewDirExcLbl.setDisable(true); } omnisEditorDetailsHM = omnisEditorDataProcessor.getCategoryEditorDetails(omnisCategoryTreeDataModelNSV.isLeaf(), omnisCategoryTreeDataModelSV.getOmnisMainCategoryId(), omnisCategoryTreeDataModelSV.getOmnisSubCategoryId()); omnisEditorMainCatTxt.setText(omnisEditorDetailsHM.get(OmnisGlobalConstants.OMNIS_EDITOR_MAIN_CATEGORY_NAME_KEY).toString()); omnisEditorSubCatTxt.setText(omnisEditorDetailsHM.get(OmnisGlobalConstants.OMNIS_EDITOR_SUB_CATEGORY_NAME_KEY).toString()); _H_omnisEditorHiddenSubCatId.setText(omnisEditorDetailsHM.get(OmnisGlobalConstants.OMNIS_EDITOR_SUB_CATEGORY_ID_KEY).toString()); _H_omnisEditorHiddenMainCat.setText(omnisEditorDetailsHM.get(OmnisGlobalConstants.OMNIS_EDITOR_MAIN_CATEGORY_ID_KEY).toString()); _H_omnisEditorHiddenIsSubCat.setText(Boolean.toString(omnisCategoryTreeDataModelNSV.isLeaf())); //Replaced full resource path with only file name //omnisEditorIconTxt.setText(omnisEditorDetailsHM.get(OmnisGlobalConstants.OMNIS_EDITOR_MAIN_CATEGORY_ICON_PATH_KEY).toString()); omnisEditorIconTxt.setText(OmnisCoreUtils.tokenizeStringLastValue( omnisEditorDetailsHM.get(OmnisGlobalConstants.OMNIS_EDITOR_MAIN_CATEGORY_ICON_PATH_KEY).toString(), OmnisGlobalConstants.OMNIS_EDITOR_ICON_PATH_URL_TOKENIZER_TOKEN)); omnisEditorCatImgView.setImage(new Image( getClass().getResource(omnisEditorDetailsHM.get( OmnisGlobalConstants.OMNIS_EDITOR_MAIN_CATEGORY_ICON_PATH_KEY).toString()).toString())); omnisEditorScanTable.setItems((ObservableList<OmnisDirScannerPathsDataModel>) omnisEditorDetailsHM.get(OmnisGlobalConstants.OMNIS_EDITOR_DIR_SCANNER_PATHS_KEY)); } } catch (Exception genericException) { logger.error(OmnisGlobalConstants.OMNIS_EXCEPTION_PREFIX + genericException.getStackTrace()[0].getMethodName(), genericException); Dialog.showThrowable(OmnisGlobalConstants.OMNIS_DIALOG_TITLE, OmnisGlobalMessages.OMNISGUICONTROLLEREDITOR_INIT_ERROR, genericException); } } @Override public void handle(ActionEvent arg0) { logger.debug("Entering OmnisGUIEditorController.handle()"); } @FXML protected void omnisEditorTableRecordClick(MouseEvent mouseEvent) { logger.debug("Entering OmnisGUIEditorController.omnisEditorTableRecordClick()"); try{ if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){ } } catch (Exception genericException) { logger.error(OmnisGlobalConstants.OMNIS_EXCEPTION_PREFIX + genericException.getStackTrace()[0].getMethodName(), genericException); Dialog.showThrowable(OmnisGlobalConstants.OMNIS_DIALOG_TITLE, OmnisGlobalMessages.OMNISGUIMAINCONTROLLER_TABLE_RCD_DBLCLICK_ERROR, genericException); } } @FXML protected void omnisEditorAddDirButtonClicked(ActionEvent addDirButtonClicked) { logger.debug("Entering OmnisGUIEditorController.omnisEditorAddDirButtonClicked()"); int numberOfRowsInserted = 0; try { //Validate if we have all data to insert OmnisEditorScanTypeDataModel omnisEditorScanTypeSelectedObject = (OmnisEditorScanTypeDataModel) omnisEditorNewDirCB.getValue(); if (omnisEditorNewDirTxt.getText().trim() != null && !omnisEditorNewDirTxt.getText().trim().equalsIgnoreCase("") && _H_omnisEditorHiddenSubCatId.getText() != null) { //Validation Passed. Proceed with Insert omnisEditorDataProcessor = new OmnisEditorDataProcessor(); numberOfRowsInserted = omnisEditorDataProcessor.insertNewDirectoryScannerPath(Integer.parseInt(_H_omnisEditorHiddenSubCatId.getText()), omnisEditorScanTypeSelectedObject.getOmnisEditorScanTypeId(), omnisEditorNewDirTxt.getText().trim(), omnisEditorNewDirExcTxt.getText().trim()); Dialog.showInfo(OmnisGlobalConstants.OMINIS_DIALOG_GUI_TITLEBAR_TEXT, numberOfRowsInserted + OmnisGlobalMessages.OMNISGUICONTROLLEREDIOR_DIR_PATH_INSERT_INFO); //Auto Refresh Table omnisEditorScanTable.setItems((ObservableList<OmnisDirScannerPathsDataModel>) omnisEditorDataProcessor.getOmnisEditorDirScanTableData(Boolean.parseBoolean(_H_omnisEditorHiddenIsSubCat.getText()), Integer.parseInt(_H_omnisEditorHiddenSubCatId.getText()), Integer.parseInt(_H_omnisEditorHiddenMainCat.getText()))); } else { Dialog.showError(OmnisGlobalConstants.OMINIS_DIALOG_GUI_TITLEBAR_TEXT, OmnisGlobalMessages.OMNISGUICONTROLLEREDIOR_DIR_PATH_INSERT_VALIDATION_ERROR); } } catch (Exception genericException) { logger.error(OmnisGlobalConstants.OMNIS_EXCEPTION_PREFIX + genericException.getStackTrace()[0].getMethodName(), genericException); Dialog.showThrowable(OmnisGlobalConstants.OMNIS_DIALOG_TITLE, OmnisGlobalMessages.OMNISGUIMAINCONTROLLER_SEARCH_ERROR, genericException); } } @FXML protected void omnisEditorDeleteDirButtonClicked(ActionEvent deleteDirButtonClicked) { logger.debug("Entering OmnisGUIEditorController.omnisEditorDeleteDirButtonClicked()"); try { omnisEditorDataProcessor = new OmnisEditorDataProcessor(); int numberOfDeletedRows = 0; OmnisDirScannerPathsDataModel omnisDirScannerPathsDataModel = omnisEditorScanTable.getSelectionModel().getSelectedItem(); if (omnisDirScannerPathsDataModel != null) { numberOfDeletedRows = omnisEditorDataProcessor.deleteOmnisEditorDirectoryScannerPath( Integer.parseInt(omnisDirScannerPathsDataModel.getOmnisDirectoryScanId())); } Dialog.showInfo(OmnisGlobalConstants.OMINIS_DIALOG_GUI_TITLEBAR_TEXT, numberOfDeletedRows + OmnisGlobalMessages.OMNISGUICONTROLLEREDIOR_DIR_PATH_DELETION_INFO); //Auto Refresh Table omnisEditorScanTable.setItems((ObservableList<OmnisDirScannerPathsDataModel>) omnisEditorDataProcessor.getOmnisEditorDirScanTableData(Boolean.parseBoolean(_H_omnisEditorHiddenIsSubCat.getText()), Integer.parseInt(_H_omnisEditorHiddenSubCatId.getText()), Integer.parseInt(_H_omnisEditorHiddenMainCat.getText()))); } catch (Exception genericException) { logger.error(OmnisGlobalConstants.OMNIS_EXCEPTION_PREFIX + genericException.getStackTrace()[0].getMethodName(), genericException); Dialog.showThrowable(OmnisGlobalConstants.OMNIS_DIALOG_TITLE, OmnisGlobalMessages.OMNISGUIMAINCONTROLLER_SEARCH_ERROR, genericException); } } @FXML protected void omnisEditorScanTypeCatCBChanged(ActionEvent omnisEditorScanTypeCatCBChangedEvent) { logger.debug("Entering OmnisGUIEditorController.omnisEditorScanTypeCatCBChanged()"); try { omnisEditorNewDirExcTxt.setDisable(false); omnisEditorNewDirExcLbl.setDisable(false); OmnisEditorScanTypeDataModel omnisEditorScanTypeSelectedObject = (OmnisEditorScanTypeDataModel) omnisEditorNewDirCB.getValue(); if (omnisEditorScanTypeSelectedObject != null) { if (omnisEditorScanTypeSelectedObject.getOmnisEditorScanTypeId() == OmnisGlobalConstants.OMNIS_EDITOR_NEW_DIR_SCAN_TYPE_DIR_ONLY_ID) { omnisEditorNewDirExcTxt.setDisable(true); omnisEditorNewDirExcLbl.setDisable(true); } } } catch (Exception genericException) { logger.error(OmnisGlobalConstants.OMNIS_EXCEPTION_PREFIX + genericException.getStackTrace()[0].getMethodName(), genericException); Dialog.showThrowable(OmnisGlobalConstants.OMNIS_DIALOG_TITLE, OmnisGlobalMessages.OMNISGUIMAINCONTROLLER_CAT_CHANGE_ERROR, genericException); } } @FXML protected void omnisEditorDirChooserOnClick(MouseEvent omnisEditorDirChooserOnClickEvent) { logger.debug("Entering OmnisGUIEditorController.omnisEditorDirChooserOnClick()"); try { //Present File Chooser and set text field with selected data DirectoryChooser omnisEditorDirectoryChooser = new DirectoryChooser(); omnisEditorDirectoryChooser.setTitle(OmnisGlobalConstants.OMINIS_EDITOR_GUI_FILE_CHOOSER_TITLEBAR_TEXT); omnisEditorDirectoryChooser.setInitialDirectory(new File (OmnisGlobalConstants.OMNIS_EDITOR_FILE_CHOOSER_DEFAULT_DIRECTORY)); File omnisEditorSelectedDirectory = omnisEditorDirectoryChooser.showDialog(OmnisGlobalVariables.OMNIS_EDITOR_GUI_STAGE); omnisEditorNewDirTxt.setText(omnisEditorSelectedDirectory.getAbsolutePath()); } catch (Exception genericException) { logger.error(OmnisGlobalConstants.OMNIS_EXCEPTION_PREFIX + genericException.getStackTrace()[0].getMethodName(), genericException); Dialog.showThrowable(OmnisGlobalConstants.OMNIS_DIALOG_TITLE, OmnisGlobalMessages.OMNISGUIMAINCONTROLLER_CAT_CHANGE_ERROR, genericException); } } @FXML protected void omnisEditorIconChooserOnClick(MouseEvent omnisEditorIconChooserOnClickEvent) { logger.debug("Entering OmnisGUIEditorController.omnisEditorIconChooserOnClick()"); try { Parent omnisIconChooserPageParent = FXMLLoader.load(getClass().getResource(OmnisGlobalConstants.OMINIS_ICON_CHOOSER_FXML)); Stage omnisIconChooserPageStage = new Stage(); omnisIconChooserPageStage.initModality(Modality.APPLICATION_MODAL); omnisIconChooserPageStage.initStyle(StageStyle.UTILITY); omnisIconChooserPageStage.getIcons().add(new Image(getClass().getResource(OmnisGlobalConstants.OMNIS_TITLE_BAR_IMAGE).toString())); omnisIconChooserPageStage.setTitle(OmnisGlobalConstants.OMINIS_ICON_CHOOSER_GUI_TITLEBAR_TEXT); omnisIconChooserPageStage.setScene(new Scene(omnisIconChooserPageParent, OmnisGlobalConstants.OMNIS_ICON_CHOOSER_WINDOW_RES_WIDTH, OmnisGlobalConstants.OMNIS_ICON_CHOOSER_WINDOW_RES_HEIGHT)); omnisIconChooserPageStage.setResizable(false); omnisIconChooserPageStage.showAndWait(); } catch (Exception genericException) { logger.error(OmnisGlobalConstants.OMNIS_EXCEPTION_PREFIX + genericException.getStackTrace()[0].getMethodName(), genericException); Dialog.showThrowable(OmnisGlobalConstants.OMNIS_DIALOG_TITLE, OmnisGlobalMessages.OMNISGUIMAINCONTROLLER_CAT_CHANGE_ERROR, genericException); } } }
50,728
https://github.com/sultania1ankit/projects/blob/master/bashrc_mod/cold_flasher.py
Github Open Source
Open Source
MIT
2,022
projects
sultania1ankit
Python
Code
137
1,118
import os import sys mcu=sys.argv[1] project=sys.argv[2] avr_try="avrdude -v -p m328p -b 19200 -c avrisp -P /dev/ttyACM0 -U flash:w:/home/ankit_sultania/MPLABXProjects/RTOS_try1.X/dist/default/production/RTOS_try1.X.production.hex" avr_main="avrdude -v -p m328p -b 19200 -c avrisp -P /dev/ttyACM0 -U flash:w:/home/ankit_sultania/MPLABXProjects/m328_tester.X/dist/default/production/m328_tester.X.production.hex" avr_boot="avrdude -v -p m328p -b 19200 -c avrisp -P /dev/ttyACM0 -U flash:w:/home/ankit_sultania/MPLABXProjects/boot_loader.X/dist/default/production/boot_loader.X.production.hex" #STM 32 skilancer folder stm_flash_DF_pre_production="st-flash write /home/ankit_sultania/STM32CubeIDE/skilancer/DF_pre_production/Debug/DF_pre_production.bin 0x8000000" stm_flash_Model_A="st-flash write /home/ankit_sultania/STM32CubeIDE/skilancer/Model_A/Debug/Model_A.bin 0x8000000" stm_flash_Model_B="st-flash write /home/ankit_sultania/STM32CubeIDE/skilancer/Model_B/Debug/Model_B.bin 0x8000000" stm_flash_Model_B_22="st-flash write /home/ankit_sultania/STM32CubeIDE/skilancer/Model_B_22/Debug/Model_B_22.bin 0x8000000" stm_flash_Model_B_31="st-flash write /home/ankit_sultania/STM32CubeIDE/skilancer/Model_B_31/Debug/Model_B_31.bin 0x8000000" stm_flash_Model_C="st-flash write /home/ankit_sultania/STM32CubeIDE/skilancer/Model_C/Debug/Model_C.bin 0x8000000" stm_flash_Model_D_05="st-flash write /home/ankit_sultania/STM32CubeIDE/skilancer/Model_D_05/Debug/Model_D_05.bin 0x8000000" if(mcu=="STM32F"): if(project=="A"): os.system(stm_flash_Model_A) elif(project=="B"): os.system(stm_flash_Model_B) elif(project=="B_22"): os.system(stm_flash_Model_B_22) elif(project=="B_31"): os.system(stm_flash_Model_B_31) elif(project=="C"): os.system(stm_flash_Model_C) else: sys.stdout.write("No project named \""+str(project)+"\" is associated with MCU \""+str(mcu)+"\" .\n") sys.stdout.flush() elif(mcu=="STM32L"): if(project=="DF_pre"): os.system(stm_flash_Model_A) elif(project=="DF_05"): os.system(stm_flash_Model_B) else: sys.stdout.write("No project named \""+str(project)+"\" is associated with MCU \""+str(mcu)+"\" .\n") sys.stdout.flush() elif(mcu=="STM8L"): sys.stdout.write("No projects found.\n") sys.stdout.flush() else: sys.stdout.write("MCU not registered.\n") sys.stdout.flush() # avrdude -v -p m328p -b 19200 -c avrisp -P /dev/ttyACM0 -U flash:w:ssd1306_128x64_i2c.ino.hex
32,282
https://github.com/Ahmed-Ashraf-eng/cms/blob/master/resources/views/emails/welcome.blade.php
Github Open Source
Open Source
MIT
null
cms
Ahmed-Ashraf-eng
PHP
Code
18
39
Hello {{$user->name}} Thanks for creating an account . please verify your email using this link {{route('verify' , $user->verification_token)}}
11,353
https://github.com/DevChive/XenForms/blob/master/Source/Core/Networking/XenMessageContext.cs
Github Open Source
Open Source
MIT
2,020
XenForms
DevChive
C#
Code
173
427
using System; using XenForms.Core.Messages; namespace XenForms.Core.Networking { /// <summary> /// Encapsulates a single toolbox request and designer response. /// </summary> public class XenMessageContext { public string Message { get; set; } public XenMessage Request { get; set; } public XenMessage Response { get; set; } internal bool ShouldQueue { get; set; } public XenMessageContext() { Request = null; Response = null; } public XenMessageContext(XenMessage request, XenMessage response) { Request = request; Response = response; } } public static class XenMessageContextExtensions { public static T Get<T>(this XenMessageContext ctx) where T : XenMessage { var request = ctx.Request as T; if (request != null) { return request; } var response = ctx.Response as T; return response; } public static T SetResponse<T>(this XenMessageContext ctx, Action<T> action = null) where T : Response, new() { var response = XenMessage.Create<T>(); ctx.Response = response; action?.Invoke(response); return (T) ctx.Response; } public static T SetRequest<T>(this XenMessageContext ctx, Action<T> action = null) where T : Request, new() { var request = XenMessage.Create<T>(); ctx.Request = request; action?.Invoke(request); return (T) ctx.Request; } } }
23,952
https://github.com/IlyasM/relayWorking/blob/master/lib/RelayRootContainer.js
Github Open Source
Open Source
BSD-3-Clause
2,016
relayWorking
IlyasM
JavaScript
Code
336
2,043
var _extends=Object.assign || function(target){for(var i=1;i < arguments.length;i++) {var source=arguments[i];for(var key in source) {if(Object.prototype.hasOwnProperty.call(source,key)){target[key] = source[key];}}}return target;};function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError('Cannot call a class as a function');}}function _inherits(subClass,superClass){if(typeof superClass !== 'function' && superClass !== null){throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;} 'use strict'; var GraphQLFragmentPointer=require('./GraphQLFragmentPointer'); var React=require('react-native'); var RelayDeprecated=require('./RelayDeprecated'); var RelayStore=require('./RelayStore'); var RelayStoreData=require('./RelayStoreData'); var RelayPropTypes=require('./RelayPropTypes'); var StaticContainer=require('react-static-container'); var getRelayQueries=require('./getRelayQueries'); var invariant=require('fbjs/lib/invariant'); var mapObject=require('fbjs/lib/mapObject');var PropTypes=React.PropTypes; var storeData=RelayStoreData.getDefaultInstance();var RelayRootContainer=(function(_React$Component){_inherits(RelayRootContainer,_React$Component); function RelayRootContainer(props,context){_classCallCheck(this,RelayRootContainer); _React$Component.call(this,props,context); this.mounted = true; this.state = this._runQueries(this.props);}RelayRootContainer.prototype. getChildContext = function getChildContext(){ return {route:this.props.route};};RelayRootContainer.prototype. _runQueries = function _runQueries( _ref) {var _this=this;var Component=_ref.Component;var forceFetch=_ref.forceFetch;var refetchRoute=_ref.refetchRoute;var route=_ref.route; var querySet=getRelayQueries(Component,route); var onReadyStateChange=function(readyState){ if(!_this.mounted){ _this._handleReadyStateChange(_extends({},readyState,{mounted:false})); return;}var _state= _this.state;var fragmentPointers=_state.fragmentPointers;var pendingRequest=_state.pendingRequest; if(request !== pendingRequest){ return;} if(readyState.aborted || readyState.done || readyState.error){ pendingRequest = null;} if(readyState.ready && !fragmentPointers){ fragmentPointers = mapObject( querySet, function(query){return query? GraphQLFragmentPointer.createForRoot( storeData.getQueuedStore(), query): null;});} _this.setState({ activeComponent:Component, activeRoute:route, error:readyState.error, fragmentPointers:fragmentPointers, pendingRequest:pendingRequest, readyState:_extends({},readyState,{mounted:true}), fetchState:{ done:readyState.done, stale:readyState.stale}});}; if(typeof refetchRoute !== 'undefined'){ RelayDeprecated.warn({ was:'RelayRootContainer.refetchRoute', now:'RelayRootContainer.forceFetch'}); forceFetch = refetchRoute;} var request=forceFetch? RelayStore.forceFetch(querySet,onReadyStateChange): RelayStore.primeCache(querySet,onReadyStateChange); return { activeComponent:null, activeRoute:null, error:null, fragmentPointers:null, pendingRequest:request, readyState:null, fetchState:{ done:false, stale:false}};};RelayRootContainer.prototype. _shouldUpdate = function _shouldUpdate(){ return ( this.props.Component === this.state.activeComponent && this.props.route === this.state.activeRoute);};RelayRootContainer.prototype. _retry = function _retry(){ ! this.state.error?process.env.NODE_ENV !== 'production'?invariant(false, 'RelayRootContainer: Can only invoke `retry` in a failure state.'):invariant(false):undefined; this.setState(this._runQueries(this.props));};RelayRootContainer.prototype. componentWillReceiveProps = function componentWillReceiveProps(nextProps){ if(nextProps.Component !== this.props.Component || nextProps.route !== this.props.route){ if(this.state.pendingRequest){ this.state.pendingRequest.abort();} this.setState(this._runQueries(nextProps));}};RelayRootContainer.prototype. componentDidUpdate = function componentDidUpdate( prevProps, prevState) { var readyState=this.state.readyState; if(readyState){ if(!prevState || readyState !== prevState.readyState){ this._handleReadyStateChange(readyState);}}};RelayRootContainer.prototype. _handleReadyStateChange = function _handleReadyStateChange(readyState){ var onReadyStateChange=this.props.onReadyStateChange; if(onReadyStateChange){ onReadyStateChange(readyState);}};RelayRootContainer.prototype. componentWillUnmount = function componentWillUnmount(){ if(this.state.pendingRequest){ this.state.pendingRequest.abort();} this.mounted = false;};RelayRootContainer.prototype. render = function render(){ var children=null; var shouldUpdate=this._shouldUpdate(); if(shouldUpdate && this.state.error){ var renderFailure=this.props.renderFailure; if(renderFailure){ children = renderFailure(this.state.error,this._retry.bind(this));}}else if(shouldUpdate && this.state.fragmentPointers){ var renderFetched=this.props.renderFetched; if(renderFetched){ children = renderFetched(_extends({}, this.props.route.params, this.state.fragmentPointers), this.state.fetchState);}else { var Component=this.props.Component; children = React.createElement(Component,_extends({}, this.props.route.params, this.state.fragmentPointers));}}else { var renderLoading=this.props.renderLoading; if(renderLoading){ children = renderLoading();}else { children = undefined;} if(children === undefined){ children = null; shouldUpdate = false;}} return ( React.createElement(StaticContainer,{shouldUpdate:shouldUpdate}, children));};return RelayRootContainer;})(React.Component); RelayRootContainer.propTypes = { Component:RelayPropTypes.Container, forceFetch:PropTypes.bool, onReadyStateChange:PropTypes.func, renderFailure:PropTypes.func, renderFetched:PropTypes.func, renderLoading:PropTypes.func, route:RelayPropTypes.QueryConfig.isRequired}; RelayRootContainer.childContextTypes = { route:RelayPropTypes.QueryConfig.isRequired}; module.exports = RelayRootContainer;
27,436
https://github.com/ilias500/xsd2pgschema/blob/master/src/xpath2json.java
Github Open Source
Open Source
Apache-2.0, LicenseRef-scancode-unknown-license-reference
2,019
xsd2pgschema
ilias500
Java
Code
1,368
5,495
/* xsd2pgschema - Database replication tool based on XML Schema Copyright 2018-2019 Masashi Yokochi https://sourceforge.net/projects/xsd2pgschema/ 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. */ import net.sf.xsd2pgschema.*; import net.sf.xsd2pgschema.docbuilder.*; import net.sf.xsd2pgschema.implement.XPathEvaluatorImpl; import net.sf.xsd2pgschema.option.*; import net.sf.xsd2pgschema.serverutil.*; import net.sf.xsd2pgschema.type.*; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.NoSuchAlgorithmException; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import javax.xml.parsers.ParserConfigurationException; import org.nustaq.serialization.FSTConfiguration; import org.xml.sax.SAXException; import com.github.antlr.grammars_v4.xpath.xpathListenerException; /** * XPath 1.0 query evaluation to JSON over PostgreSQL. * * @author yokochi */ public class xpath2json { /** * The main method. * * @param args the arguments */ public static void main(String[] args) { /** Whether to output processing message to stdout or not (stderr). */ boolean stdout_msg = false; /** The JSON directory name. */ String json_dir_name = "json_result"; /** The output file name or pattern. */ String out_file_name = ""; /** The PostgreSQL data model option. */ PgSchemaOption option = new PgSchemaOption(true); /** The FST configuration. */ FSTConfiguration fst_conf = FSTConfiguration.createDefaultConfiguration(); fst_conf.registerClass(PgSchemaServerQuery.class,PgSchemaServerReply.class,PgSchema.class); // FST optimization /** The PostgreSQL option. */ PgOption pg_option = new PgOption(); /** The JSON builder option. */ JsonBuilderOption jsonb_option = new JsonBuilderOption(); /** The XPath queries. */ ArrayList<String> xpath_queries = new ArrayList<String>(); /** The XPath variable reference. */ HashMap<String, String> variables = new HashMap<String, String>(); for (int i = 0; i < args.length; i++) { if (args[i].equals("--xsd") && i + 1 < args.length) option.root_schema_location = args[++i]; else if (args[i].equals("--out") && i + 1 < args.length) out_file_name = args[++i]; else if (args[i].equals("--xpath-query") && i + 1 < args.length) xpath_queries.add(args[++i]); else if (args[i].equals("--xpath-var") && i + 1 < args.length) { String[] variable = args[++i].split("="); if (variable.length != 2) { System.err.println("Invalid variable definition."); showUsage(); } variables.put(variable[0], variable[1]); } else if (args[i].equals("--db-host") && i + 1 < args.length) pg_option.pg_host = args[++i]; else if (args[i].equals("--db-port") && i + 1 < args.length) pg_option.pg_port = Integer.valueOf(args[++i]); else if (args[i].equals("--db-name") && i + 1 < args.length) pg_option.name = args[++i]; else if (args[i].equals("--db-user") && i + 1 < args.length) pg_option.user = args[++i]; else if (args[i].equals("--db-pass") && i + 1 < args.length) pg_option.pass = args[++i]; else if (args[i].equals("--test-ddl")) pg_option.test = true; else if (args[i].equals("--fill-default-value")) option.fill_default_value = true; else if (args[i].equals("--obj-json")) jsonb_option.type = JsonType.object; else if (args[i].equals("--col-json")) jsonb_option.type = JsonType.column; else if (args[i].equals("--json-attr-prefix") && i + 1 < args.length) jsonb_option.setAttrPrefix(args[++i]); else if (args[i].equals("--json-simple-cont-name") && i + 1 < args.length) jsonb_option.setSimpleContentName(args[++i]); else if (args[i].equals("--json-array-all")) jsonb_option.array_all = true; else if (args[i].equals("--json-allow-frag")) jsonb_option.allow_frag = true; else if (args[i].equals("--json-indent-offset") && i + 1 < args.length) jsonb_option.setIndentOffset(args[++i]); else if (args[i].equals("--json-key-value-offset") && i + 1 < args.length) jsonb_option.setKeyValueOffset(args[++i]); else if (args[i].equals("--json-insert-doc-key")) jsonb_option.insert_doc_key = true; else if (args[i].equals("--json-no-linefeed")) jsonb_option.setLineFeed(false); else if (args[i].equals("--json-compact")) jsonb_option.setCompact(); else if (args[i].equals("--schema-ver") && i + 1 < args.length) jsonb_option.setSchemaVer(args[++i]); else if (args[i].equals("--out-dir") && i + 1 < args.length) json_dir_name = args[++i]; else if (args[i].equals("--doc-key")) option.setDocKeyOption(true); else if (args[i].equals("--no-doc-key")) option.setDocKeyOption(false); else if (args[i].equals("--no-rel")) option.cancelRelDataExt(); else if (args[i].equals("--no-wild-card")) option.wild_card = false; else if (args[i].equals("--ser-key")) option.serial_key = true; else if (args[i].equals("--xpath-key")) option.xpath_key = true; else if (args[i].equals("--case-insensitive")) { option.setCaseInsensitive(); jsonb_option.setCaseInsensitive(); } else if (args[i].equals("--pg-public-schema")) option.pg_named_schema = false; else if (args[i].equals("--pg-named-schema")) option.pg_named_schema = true; else if (args[i].equals("--pg-map-big-integer")) option.pg_integer = PgIntegerType.big_integer; else if (args[i].equals("--pg-map-long-integer")) option.pg_integer = PgIntegerType.signed_long_64; else if (args[i].equals("--pg-map-integer")) option.pg_integer = PgIntegerType.signed_int_32; else if (args[i].equals("--pg-map-big-decimal")) option.pg_decimal = PgDecimalType.big_decimal; else if (args[i].equals("--pg-map-double-decimal")) option.pg_decimal = PgDecimalType.double_precision_64; else if (args[i].equals("--pg-map-float-decimal")) option.pg_decimal = PgDecimalType.single_precision_32; else if (args[i].equals("--no-cache-xsd")) option.cache_xsd = false; else if (args[i].equals("--hash-by") && i + 1 < args.length) option.hash_algorithm = args[++i]; else if (args[i].equals("--hash-size") && i + 1 < args.length) option.hash_size = PgHashSize.getSize(args[++i]); else if (args[i].equals("--ser-size") && i + 1 < args.length) option.ser_size = PgSerSize.getSize(args[++i]); else if (args[i].equals("--doc-key-name") && i + 1 < args.length) option.setDocumentKeyName(args[++i]); else if (args[i].equals("--ser-key-name") && i + 1 < args.length) option.setSerialKeyName(args[++i]); else if (args[i].equals("--xpath-key-name") && i + 1 < args.length) option.setXPathKeyName(args[++i]); else if (args[i].equals("--discarded-doc-key-name") && i + 1 < args.length) option.addDiscardedDocKeyName(args[++i]); else if (args[i].equals("--inplace-doc-key-name") && i + 1 < args.length) { option.addInPlaceDocKeyName(args[++i]); option.setDocKeyOption(false); } else if (args[i].equals("--doc-key-if-no-inplace")) { option.document_key_if_no_in_place = true; option.setDocKeyOption(false); } else if (args[i].equals("--no-pgschema-serv")) option.pg_schema_server = false; else if (args[i].equals("--pgschema-serv-host") && i + 1 < args.length) option.pg_schema_server_host = args[++i]; else if (args[i].equals("--pgschema-serv-port") && i + 1 < args.length) option.pg_schema_server_port = Integer.valueOf(args[++i]); else if (args[i].equals("--verbose")) option.verbose = true; else { System.err.println("Illegal option: " + args[i] + "."); showUsage(); } } option.resolveDocKeyOption(); if (option.root_schema_location.isEmpty()) { System.err.println("XSD schema location is empty."); showUsage(); } if (!out_file_name.isEmpty() && !out_file_name.equals("stdout")) { stdout_msg = true; Path json_dir_path = Paths.get(json_dir_name); if (!Files.isDirectory(json_dir_path)) { try { Files.createDirectory(json_dir_path); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } } InputStream is = null; boolean server_alive = option.pingPgSchemaServer(fst_conf); boolean no_data_model = server_alive ? !option.matchPgSchemaServer(fst_conf) : true; if (no_data_model) { is = PgSchemaUtil.getSchemaInputStream(option.root_schema_location, null, false); if (is == null) showUsage(); } try { XPathEvaluatorImpl evaluator = new XPathEvaluatorImpl(is, option, fst_conf, pg_option, stdout_msg); // reuse the instance for repetition if (!pg_option.name.isEmpty()) pg_option.clear(); JsonBuilder jsonb = new JsonBuilder(evaluator.client.schema, jsonb_option); for (int id = 0; id < xpath_queries.size(); id++) { String xpath_query = xpath_queries.get(id); evaluator.translate(xpath_query, variables, stdout_msg); if (!pg_option.name.isEmpty()) evaluator.composeJson(id, xpath_queries.size(), json_dir_name, out_file_name, jsonb); } evaluator.client.schema.closePreparedStatement(true); } catch (IOException | NoSuchAlgorithmException | ParserConfigurationException | SAXException | PgSchemaException | xpathListenerException | SQLException e) { e.printStackTrace(); System.exit(1); } } /** * Show usage. */ private static void showUsage() { PgSchemaOption option = new PgSchemaOption(true); JsonBuilderOption jsonb_option = new JsonBuilderOption(); System.err.println("xpath2json: XPath 1.0 qeury evaluation to JSON over PostgreSQL"); System.err.println("Usage: --xsd SCHEMA_LOCATION --db-name DATABASE --db-user USER --db-pass PASSWORD (default=\"\")"); System.err.println(" --db-host PG_HOST_NAME (default=\"" + PgSchemaUtil.pg_host + "\")"); System.err.println(" --db-port PG_PORT_NUMBER (default=" + PgSchemaUtil.pg_port + ")"); System.err.println(" --test-ddl (perform consistency test on PostgreSQL DDL)"); System.err.println(" --xpath-query XPATH_QUERY (repeatable)"); System.err.println(" --xpath-var KEY=VALUE (repeat until you specify all variables)"); System.err.println(" --out OUTPUT_FILE_OR_PATTERN (default=stdout)"); System.err.println(" --out-dir OUTPUT_DIRECTORY"); System.err.println(" --schema-ver JSON_SCHEMA_VER (choose from \"draft_v7\" (default), \"draft_v6\", \"draft_v4\", or \"latest\" as \"" + JsonSchemaVersion.defaultVersion().toString() + "\")"); System.err.println(" --obj-json (use object-oriented JSON format)"); System.err.println(" --col-json (use column-oriented JSON format, default)"); System.err.println(" --no-rel (turn off relational model extension)"); System.err.println(" --no-wild-card (turn off wild card extension)"); System.err.println(" --doc-key (append " + option.document_key_name + " column in all relations, default with relational model extension)"); System.err.println(" --no-doc-key (remove " + option.document_key_name + " column from all relations, effective only with relational model extension)"); System.err.println(" --ser-key (append " + option.serial_key_name + " column in child relation of list holder)"); System.err.println(" --xpath-key (append " + option.xpath_key_name + " column in all relations)"); System.err.println("Option: --case-insensitive (all table and column names are lowercase)"); System.err.println(" --pg-public-schema (utilize \"public\" schema, default)"); System.err.println(" --pg-named-schema (enable explicit named schema)"); System.err.println(" --pg-map-big-integer (map xs:integer to BigInteger according to the W3C rules)"); System.err.println(" --pg-map-long-integer (map xs:integer to signed long 64 bits)"); System.err.println(" --pg-map-integer (map xs:integer to signed int 32 bits, default)"); System.err.println(" --pg-map-big-decimal (map xs:decimal to BigDecimal according to the W3C rules, default)"); System.err.println(" --pg-map-double-decimal (map xs:decimal to double precision 64 bits)"); System.err.println(" --pg-map-float-decimal (map xs:decimal to single precision 32 bits)"); System.err.println(" --no-cache-xsd (retrieve XML Schemata without caching)"); System.err.println(" --hash-by ALGORITHM [MD2 | MD5 | SHA-1 (default) | SHA-224 | SHA-256 | SHA-384 | SHA-512]"); System.err.println(" --hash-size BIT_SIZE [int (32 bits) | long (64 bits, default) | native (default bits of algorithm) | debug (string)]"); System.err.println(" --ser-size BIT_SIZE [short (16 bits); | int (32 bits, default)]"); System.err.println(" --doc-key-name DOC_KEY_NAME (default=\"" + option.def_document_key_name + "\")"); System.err.println(" --ser-key-name SER_KEY_NAME (default=\"" + option.def_serial_key_name + "\")"); System.err.println(" --xpath-key-name XPATH_KEY_NAME (default=\"" + option.def_xpath_key_name + "\")"); System.err.println(" --discarded-doc-key-name DISCARDED_DOCUMENT_KEY_NAME"); System.err.println(" --inplace-doc-key-name INPLACE_DOCUMENT_KEY_NAME"); System.err.println(" --doc-key-if-no-inplace (append document key if no in-place document key, select --no-doc-key options by default)"); System.err.println(" --no-pgschema-serv (not utilize PgSchema server)"); System.err.println(" --pgschema-serv-host PG_SCHEMA_SERV_HOST_NAME (default=\"" + PgSchemaUtil.pg_schema_server_host + "\")"); System.err.println(" --pgschema-serv-port PG_SCHEMA_SERV_PORT_NUMBER (default=" + PgSchemaUtil.pg_schema_server_port + ")"); System.err.println(" --json-attr-prefix ATTR_PREFIX_CODE (default=\"" + jsonb_option.getAttrPrefix() + "\")"); System.err.println(" --json-simple-cont-name SIMPLE_CONTENT_NAME (default=\"" + jsonb_option.getSimpleContentName() + "\")"); System.err.println(" --json-array-all (use JSON array if possible)"); System.err.println(" --json-allow-frag (allow fragmented JSON document)"); System.err.println(" --json-indent-offset INTEGER (default=" + jsonb_option.getIndentOffset() + ", min=0, max=4)"); System.err.println(" --json-key-value-offset INTEGER (default=" + jsonb_option.getKeyValueOffset() + ", min=0, max=4)"); System.err.println(" --json-insert-doc-key (insert document key in result)"); System.err.println(" --json-no-linefeed (dismiss line feed code)"); System.err.println(" --json-compact (equals to set --json-indent-offset 0 --json-key-value-offset 0 --json-no-linefeed)"); System.err.println(" --verbose (verbose mode)"); System.exit(1); } }
48,031
https://github.com/bexcool/PavlOS/blob/master/PavlOS/Core/Shell/Input/InputListener.cs
Github Open Source
Open Source
Apache-2.0
null
PavlOS
bexcool
C#
Code
833
2,587
using Mosa.External.x86.Driver; using Mosa.External.x86.Driver.Input; using PavlOS.Core.Shell; using PavlOS.Core.Shell.Controls.Base; using PavlOS.Core.Shell.Rendering; using PavlOS.Core.Utility; using PavlOS_Dev.Core.Shell.Controls.Base; using System; using System.Collections.Generic; using System.Drawing; using System.Text; using static PavlOS.Core.Shell.Utility.ShellUtil; namespace PavlOS.Core { public class InputListener { public static bool LeftMousePressed; private bool AlreadyChangedWindowFocus = false, AlreadyWindowInteraction = false; int OffsetDragX, OffsetDragY, OffsetResizeX, OffsetResizeY; public void CheckInput() { AlreadyChangedWindowFocus = false; // Check window input for (int i = ShellCore.AllWindows.Count - 1; i >= 0; i--) for (int j = ShellCore.AllWindows.Count - 1; j >= 0; j--) { Window window = (Window)ShellCore.AllWindows[j]; if (window.IndexZ == i) { #region Window Focus // Focused if (!AlreadyWindowInteraction && !LeftMousePressed && !AlreadyChangedWindowFocus && PS2Mouse.MouseStatus == MouseStatus.Left && PS2Mouse.X >= window.X && PS2Mouse.X <= window.X + window.Width && PS2Mouse.Y >= window.Y && PS2Mouse.Y <= window.Y + window.Height) { AlreadyChangedWindowFocus = true; window.Focus(); } #endregion #region Window Drag and Resize // Reset window variables if (window == ShellCore.FocusedWindow && PS2Mouse.MouseStatus != MouseStatus.Left) { window.WindowDrag = false; window.WindowResizeX = false; window.WindowResizeY = false; AlreadyWindowInteraction = false; Renderer.CurrentCursor = Cursor.Arrow; } // Check drag if (window == ShellCore.FocusedWindow && PS2Mouse.MouseStatus == MouseStatus.Left && !LeftMousePressed && PS2Mouse.X > window.X + Window.BorderWeight && PS2Mouse.X < window.X + window.Width - Window.BorderWeight && PS2Mouse.Y > window.Y + 3 && PS2Mouse.Y < window.Y + Window.TitleBarHeight && !window.WindowDrag) { window.WindowDrag = true; AlreadyWindowInteraction = true; OffsetDragX = PS2Mouse.X - window.X; OffsetDragY = PS2Mouse.Y - window.Y; } // Check resize X if (window == ShellCore.FocusedWindow && PS2Mouse.X > window.X + window.Width - Window.BorderWeight && PS2Mouse.X < window.X + window.Width + Window.ResizeBorderWeight && PS2Mouse.Y > window.Y && PS2Mouse.Y < window.Y + window.Height + Window.ResizeBorderWeight) { Renderer.CurrentCursor = Cursor.HorizontalResize; if (PS2Mouse.MouseStatus == MouseStatus.Left && !LeftMousePressed && !window.WindowResizeX) { window.WindowResizeX = true; AlreadyWindowInteraction = true; OffsetResizeX = PS2Mouse.X - window.X - window.Width; } } // Check resize Y if (window == ShellCore.FocusedWindow && PS2Mouse.Y > window.Y + window.Height - Window.BorderWeight && PS2Mouse.Y < window.Y + window.Height + Window.ResizeBorderWeight && PS2Mouse.X > window.X && PS2Mouse.X < window.X + window.Width + Window.ResizeBorderWeight) { Renderer.CurrentCursor = Cursor.VerticalResize; if (PS2Mouse.MouseStatus == MouseStatus.Left && !LeftMousePressed && !window.WindowResizeY) { window.WindowResizeY = true; AlreadyWindowInteraction = true; OffsetResizeY = PS2Mouse.Y - window.Y - window.Height; } } // Set diagonal cursor if (window == ShellCore.FocusedWindow && PS2Mouse.Y > window.Y + window.Height - Window.BorderWeight && PS2Mouse.Y < window.Y + window.Height + Window.ResizeBorderWeight && PS2Mouse.X > window.X && PS2Mouse.X < window.X + window.Width + Window.ResizeBorderWeight && PS2Mouse.X > window.X + window.Width - Window.BorderWeight && PS2Mouse.X < window.X + window.Width + Window.ResizeBorderWeight && PS2Mouse.Y > window.Y && PS2Mouse.Y < window.Y + window.Height + Window.ResizeBorderWeight) Renderer.CurrentCursor = Cursor.DiagonalResize; if (window.WindowDrag) { window.X = Math.Clamp(PS2Mouse.X - OffsetDragX, 0, GraphicsDriver.Width - window.Width); window.Y = Math.Clamp(PS2Mouse.Y - OffsetDragY, 0, GraphicsDriver.Height - window.Height); } if (window.WindowResizeX) { window.Width = Math.Clamp(PS2Mouse.X - window.X - OffsetResizeX, window.MinWidth, GraphicsDriver.Width); } if (window.WindowResizeY) { window.Height = Math.Clamp(PS2Mouse.Y - window.Y - OffsetResizeY, window.MinHeight, GraphicsDriver.Height); } #endregion foreach (Control control in window.Controls) { // Clicked if (PS2Mouse.MouseStatus != MouseStatus.Left && LeftMousePressed && PS2Mouse.X >= window.X + control.X + Window.BorderWeight && PS2Mouse.X <= window.X + control.X + Window.BorderWeight + control.Width + control.Padding.LeftRight - 1 && PS2Mouse.Y >= window.Y + control.Y + Window.TitleBarHeight && PS2Mouse.Y <= window.Y + control.Y + Window.TitleBarHeight + control.Height + control.Padding.TopBottom - 1) { control._OnClick(); } // Pressed if (PS2Mouse.MouseStatus != MouseStatus.None && PS2Mouse.X >= window.X + control.X + Window.BorderWeight && PS2Mouse.X <= window.X + control.X + Window.BorderWeight + control.Width + control.Padding.LeftRight - 1 && PS2Mouse.Y >= window.Y + control.Y + Window.TitleBarHeight && PS2Mouse.Y <= window.Y + control.Y + Window.TitleBarHeight + control.Height + control.Padding.TopBottom - 1) { if (!control.Pressed) { control.Pressed = true; control._MousePressed(); } } else { if (control.Pressed) { control.Pressed = false; control._MouseReleased(); } } // Hovered if (PS2Mouse.X >= window.X + control.X + Window.BorderWeight && PS2Mouse.X <= window.X + control.X + Window.BorderWeight + control.Width + control.Padding.LeftRight - 1 && PS2Mouse.Y >= window.Y + control.Y + Window.TitleBarHeight && PS2Mouse.Y <= window.Y + control.Y + Window.TitleBarHeight + control.Height + control.Padding.TopBottom - 1) { if (!control.Hovered) { control.Hovered = true; control._MouseEnter(); } } else { if (control.Hovered) { control.Hovered = false; control._MouseLeave(); } } } } } foreach (Control control in ShellCore.AllSystemControls) { // Clicked if (PS2Mouse.MouseStatus != MouseStatus.Left && LeftMousePressed && PS2Mouse.X >= control.X && PS2Mouse.X <= control.X + control.Width + control.Padding.LeftRight - 1 && PS2Mouse.Y >= control.Y && PS2Mouse.Y <= control.Y + control.Height + control.Padding.TopBottom - 1) { control._OnClick(); } // Pressed if (PS2Mouse.MouseStatus != MouseStatus.None && PS2Mouse.X >= control.X && PS2Mouse.X <= control.X + control.Width + control.Padding.LeftRight - 1 && PS2Mouse.Y >= control.Y && PS2Mouse.Y <= control.Y + control.Height + control.Padding.TopBottom - 1) { if (!control.Pressed) { control.Pressed = true; control._MousePressed(); } } else { if (control.Pressed) { control.Pressed = false; control._MouseReleased(); } } // Hovered if (PS2Mouse.X >= control.X && PS2Mouse.X <= control.X + control.Width + control.Padding.LeftRight - 1 && PS2Mouse.Y >= control.Y && PS2Mouse.Y <= control.Y + control.Height + control.Padding.TopBottom - 1) { if (!control.Hovered) { control.Hovered = true; control._MouseEnter(); } } else { if (control.Hovered) { control.Hovered = false; control._MouseLeave(); } } } LeftMousePressed = PS2Mouse.MouseStatus == MouseStatus.Left; } } }
27,393
https://github.com/matoruru/purescript-react-material-ui-svgicon/blob/master/src/MaterialUI/SVGIcon/Icon/SignalCellularNoSim.purs
Github Open Source
Open Source
MIT
null
purescript-react-material-ui-svgicon
matoruru
PureScript
Code
45
163
module MaterialUI.SVGIcon.Icon.SignalCellularNoSim ( signalCellularNoSim , signalCellularNoSim_ ) where import Prelude (flip) import MaterialUI.SVGIcon.Type (SVGIcon, SVGIcon_) import React (unsafeCreateElement, ReactClass) as R foreign import signalCellularNoSimImpl :: forall a. R.ReactClass a signalCellularNoSim :: SVGIcon signalCellularNoSim = flip (R.unsafeCreateElement signalCellularNoSimImpl) [] signalCellularNoSim_ :: SVGIcon_ signalCellularNoSim_ = signalCellularNoSim {}
1,768
https://github.com/exoscale/cli/blob/master/cmd/sks_kubeconfig.go
Github Open Source
Open Source
Apache-2.0
2,022
cli
exoscale
Go
Code
629
2,056
package cmd import ( "encoding/base64" "encoding/json" "fmt" "time" exoapi "github.com/exoscale/egoscale/v2/api" "github.com/spf13/cobra" "gopkg.in/yaml.v2" ) type sksKubeconfigCmd struct { cliCommandSettings `cli-cmd:"-"` _ bool `cli-cmd:"kubeconfig"` Cluster string `cli-arg:"#" cli-usage:"CLUSTER-NAME|ID"` User string `cli-arg:"#"` ExecCredential bool `cli-short:"x" cli-usage:"output an ExecCredential object to use with a kubeconfig user.exec mode"` Groups []string `cli-flag:"group" cli-short:"g" cli-usage:"client certificate group. Can be specified multiple times. Defaults to system:masters"` TTL int64 `cli-short:"t" cli-usage:"client certificate validity duration in seconds"` Zone string `cli-short:"z" cli-usage:"SKS cluster zone"` } func (c *sksKubeconfigCmd) cmdAliases() []string { return []string{"kc"} } func (c *sksKubeconfigCmd) cmdShort() string { return "Generate a Kubernetes kubeconfig file for an SKS cluster" } func (c *sksKubeconfigCmd) cmdLong() string { return `This command generates a kubeconfig file to be used for authenticating to an SKS cluster API. The "user" command argument corresponds to the CN field of the generated X.509 client certificate. Optionally, you can specify client certificate groups using the "-g|--group" option: those groups will be set in the "O" field of the certificate. See [1] for more information about Kubernetes authentication certificates. Example usage: # Obtain "cluster-admin" credentials $ exo sks kubeconfig my-cluster admin \ -g system:masters \ -t $((86400 * 7)) > $HOME/.kube/my-cluster.config $ kubeconfig --kubeconfig=$HOME/.kube/my-cluster.config get pods Note: if no TTL value is specified, the API applies a default value as a safety measure. Please look up the API documentation for more information. ## Using exo CLI as Kubernetes credential plugin If you wish to avoid leaving sensitive credentials on your system, you can use exo CLI as a Kubernetes client-go credential plugin[2] to generate and return a kubeconfig dynamically when invoked by kubectl without storing it on disk. To achieve this configuration, edit your kubeconfig file so that the "users" section relating to your cluster ("my-sks-cluster" in the following example) looks like: apiVersion: v1 kind: Config clusters: - name: my-sks-cluster cluster: certificate-authority-data: **BASE64-ENCODED CLUSTER CERTIFICATE** server: https://153fcc53-1197-46ae-a8e0-ccf6d09efcb0.sks-ch-gva-2.exo.io:443 users: - name: exo@my-sks-cluster user: # The "exec" section replaces "client-certificate-data"/"client-key-data" exec: apiVersion: "client.authentication.k8s.io/v1beta1" command: exo args: - sks - kubeconfig - my-sks-cluster - --zone=ch-gva-2 - --exec-credential - user contexts: - name: my-sks-cluster context: cluster: my-sks-cluster user: exo@my-sks-cluster current-context: my-sks-cluster Notes: * The "exo" CLI binary must be installed in a directory listed in your PATH shell environment variable. * You can specify the "--group" flag in the user.exec.args section referencing a non-admin group to restrict the privileges of the operator using kubectl. [1]: https://kubernetes.io/docs/reference/access-authn-authz/authentication/#x509-client-certs [2]: https://kubernetes.io/docs/reference/access-authn-authz/authentication/#client-go-credential-plugins ` } func (c *sksKubeconfigCmd) cmdPreRun(cmd *cobra.Command, args []string) error { cmdSetZoneFlagFromDefault(cmd) return cliCommandDefaultPreRun(c, cmd, args) } func (c *sksKubeconfigCmd) cmdRun(_ *cobra.Command, _ []string) error { ctx := exoapi.WithEndpoint(gContext, exoapi.NewReqEndpoint(gCurrentAccount.Environment, c.Zone)) // We cannot use the flag's default here as it would be additive if len(c.Groups) == 0 { c.Groups = []string{"system:masters"} } cluster, err := cs.FindSKSCluster(ctx, c.Zone, c.Cluster) if err != nil { return err } b64Kubeconfig, err := cs.GetSKSClusterKubeconfig( ctx, c.Zone, cluster, c.User, c.Groups, time.Duration(c.TTL)*time.Second, ) if err != nil { return fmt.Errorf("error retrieving kubeconfig: %w", err) } kubeconfig, err := base64.StdEncoding.DecodeString(b64Kubeconfig) if err != nil { return fmt.Errorf("error decoding kubeconfig content: %w", err) } if !c.ExecCredential { fmt.Print(string(kubeconfig)) return nil } k := struct { Users []struct { Name string `yaml:"name"` User map[string]string `yaml:"user"` } `yaml:"users"` }{} if err := yaml.Unmarshal(kubeconfig, &k); err != nil { return fmt.Errorf("error decoding kubeconfig content: %w", err) } ecClientCertificateData, err := base64.StdEncoding.DecodeString(k.Users[0].User["client-certificate-data"]) if err != nil { return fmt.Errorf("error decoding kubeconfig content: %w", err) } ecClientKeyData, err := base64.StdEncoding.DecodeString(k.Users[0].User["client-key-data"]) if err != nil { return fmt.Errorf("error decoding kubeconfig content: %w", err) } ecOut, err := json.Marshal(map[string]interface{}{ "apiVersion": "client.authentication.k8s.io/v1beta1", "kind": "ExecCredential", "status": map[string]string{ "clientCertificateData": string(ecClientCertificateData), "clientKeyData": string(ecClientKeyData), }, }) if err != nil { return fmt.Errorf("error encoding exec credential content: %w", err) } fmt.Print(string(ecOut)) return nil } func init() { cobra.CheckErr(registerCLICommand(sksCmd, &sksKubeconfigCmd{ cliCommandSettings: defaultCLICmdSettings(), })) // FIXME: remove this someday. cobra.CheckErr(registerCLICommand(deprecatedSKSCmd, &sksKubeconfigCmd{ cliCommandSettings: defaultCLICmdSettings(), })) }
30,004
https://github.com/indigo-iam/iam/blob/master/iam-login-service/src/main/java/it/infn/mw/iam/api/client/registration/service/ClientRegistrationService.java
Github Open Source
Open Source
Apache-2.0
2,023
iam
indigo-iam
Java
Code
159
392
/** * Copyright (c) Istituto Nazionale di Fisica Nucleare (INFN). 2016-2021 * * 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 it.infn.mw.iam.api.client.registration.service; import java.text.ParseException; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import org.springframework.security.core.Authentication; import it.infn.mw.iam.api.common.client.RegisteredClientDTO; public interface ClientRegistrationService { RegisteredClientDTO registerClient(@Valid RegisteredClientDTO request, Authentication authentication) throws ParseException; RegisteredClientDTO retrieveClient(@NotBlank String clientId, Authentication authentication); RegisteredClientDTO updateClient(@NotBlank String clientId, @Valid RegisteredClientDTO request, Authentication authentication) throws ParseException; void deleteClient(@NotBlank String clientId, Authentication authentication); RegisteredClientDTO redeemClient(@NotBlank String clientId, @NotBlank String registrationAccessToken, Authentication authentication); }
47,637
https://github.com/moraycreative/lindenconstructionco/blob/master/wp-content/themes/construction/vamtam/admin/helpers/config_generator/checkbox.php
Github Open Source
Open Source
MIT
null
lindenconstructionco
moraycreative
PHP
Code
75
215
<?php /** * single checkbox */ $option = $value; $value = wpv_sanitize_bool( wpv_get_option( $id, $default ) ); ?> <div class="wpv-config-row <?php echo esc_attr( $class ) ?>"> <div class="ritlte"> <?php wpv_description( $id, $desc ) ?> </div> <div class="rcontent clearfix"> <label> <input type="checkbox" name="<?php echo esc_attr( $id ) ?>" id="<?php echo esc_attr( $id ) ?>" value="true" class="<?php wpv_static( $option )?>" <?php checked( $value, true ) ?> /> <?php echo $name // xss ok ?> </label> </div> </div>
42,349
https://github.com/apache/pdfbox/blob/master/fontbox/src/test/java/org/apache/fontbox/ttf/gsub/GlyphArraySplitterRegexImplTest.java
Github Open Source
Open Source
Apache-2.0, BSD-3-Clause, LicenseRef-scancode-generic-cla, APAFML, LicenseRef-scancode-apple-excl, LicenseRef-scancode-unknown-license-reference, LicenseRef-scancode-unknown
2,023
pdfbox
apache
Java
Code
346
1,084
/* * 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.fontbox.ttf.gsub; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; class GlyphArraySplitterRegexImplTest { @Test void testSplit_1() { // given Set<List<Integer>> matchers = new HashSet<>(Arrays.asList(Arrays.asList(84, 93), Arrays.asList(102, 82), Arrays.asList(104, 87))); GlyphArraySplitter testClass = new GlyphArraySplitterRegexImpl(matchers); List<Integer> glyphIds = Arrays.asList(84, 112, 93, 104, 82, 61, 96, 102, 93, 104, 87, 110); // when List<List<Integer>> tokens = testClass.split(glyphIds); // then assertEquals(Arrays.asList(Arrays.asList(84, 112, 93, 104, 82, 61, 96, 102, 93), Arrays.asList(104, 87), Arrays.asList(110)), tokens); } @Test void testSplit_2() { // given Set<List<Integer>> matchers = new HashSet<>( Arrays.asList(Arrays.asList(67, 112, 96), Arrays.asList(74, 112, 76))); GlyphArraySplitter testClass = new GlyphArraySplitterRegexImpl(matchers); List<Integer> glyphIds = Arrays.asList(67, 112, 96, 103, 93, 108, 93); // when List<List<Integer>> tokens = testClass.split(glyphIds); // then assertEquals(Arrays.asList(Arrays.asList(67, 112, 96), Arrays.asList(103, 93, 108, 93)), tokens); } @Test void testSplit_3() { // given Set<List<Integer>> matchers = new HashSet<>( Arrays.asList(Arrays.asList(67, 112, 96), Arrays.asList(74, 112, 76))); GlyphArraySplitter testClass = new GlyphArraySplitterRegexImpl(matchers); List<Integer> glyphIds = Arrays.asList(94, 67, 112, 96, 112, 91, 103); // when List<List<Integer>> tokens = testClass.split(glyphIds); // then assertEquals(Arrays.asList(Arrays.asList(94), Arrays.asList(67, 112, 96), Arrays.asList(112, 91, 103)), tokens); } @Test void testSplit_4() { // given Set<List<Integer>> matchers = new HashSet<>( Arrays.asList(Arrays.asList(67, 112), Arrays.asList(76, 112))); GlyphArraySplitter testClass = new GlyphArraySplitterRegexImpl(matchers); List<Integer> glyphIds = Arrays.asList(94, 167, 112, 91, 103); // when List<List<Integer>> tokens = testClass.split(glyphIds); // then assertEquals(Arrays.asList(Arrays.asList(94, 167, 112, 91, 103)), tokens); } }
20,546
https://github.com/AlexeyKashintsev/PlatypusJS/blob/master/designer/PlatypusDatamodel/src/com/eas/client/model/gui/view/model/SelectedField.java
Github Open Source
Open Source
Apache-2.0
null
PlatypusJS
AlexeyKashintsev
Java
Code
60
151
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.eas.client.model.gui.view.model; import com.eas.client.metadata.Field; import com.eas.client.model.Entity; /** * * @author mg */ public class SelectedField<E extends Entity<?, ?, E>> { public E entity; public Field field; public SelectedField(E aEntity, Field aField) { super(); entity = aEntity; field = aField; } }
10,997
https://github.com/itiki/sql-generator/blob/master/src/test/scala/com/geishatokyo/sqlgen/project/MergeSplitProjectTest.scala
Github Open Source
Open Source
MIT
2,015
sql-generator
itiki
Scala
Code
140
596
package com.geishatokyo.sqlgen.project import com.geishatokyo.sqlgen.{Context, Executor} import com.geishatokyo.sqlgen.process.input.{InputHelpers, SingleXLSLoader} import com.geishatokyo.sqlgen.process.ensure.EnsureProcessProvider import com.geishatokyo.sqlgen.process.output.{XLSOutputProvider, SQLOutputProvider} import com.geishatokyo.sqlgen.process.merge.MergeSplitProcessProvider import com.geishatokyo.sqlgen.process.{MapContext, Proc} import org.specs2.mutable.Specification import InputHelpers._ /** * * User: takeshita * Create: 12/07/13 11:47 */ class MergeSplitProjectTest extends Specification { "MergeSplit executor" should{ "apply project specification" in{ val e = new MergeSplitExecutorSample val wb = e.execute(file("MergeSplitTest.xls")) wb("User").column("name").cells.map(_.value) must_== List("test","test2","あああ") wb("User").column("familyname").cells.map(_.value) must_== List("tanaka","yamada","satou") wb("User").column("gender").cells.map(_.value) must_== List("male","female","female") } } } class MergeSplitExecutorSample extends Executor[MergeSplitProjectSample] with EnsureProcessProvider with MergeSplitProcessProvider with SQLOutputProvider with XLSOutputProvider{ val project = new MergeSplitProjectSample val context: Context = new MapContext type ProjectType = MergeSplitProjectSample protected def executor: Proc = { ensureSettingProc then mergeAndSplitProc then outputSqlProc().skipOnError then outputXlsProc().skipOnError } } class MergeSplitProjectSample extends BaseProject with MergeSplitProject{ merge sheet "User" from( at("Sheet1"){ column("name") column("gender") } , at("Sheet2"){ column("familyName") } ) merge sheet "User" select ("name" as "gender") from "Sheet3" where "gender" is "id" }
8,094
https://github.com/Danielle-Kensy/mobile-android-lessons/blob/master/PokedexDetails/lib/models/pokemon.dart
Github Open Source
Open Source
MIT
null
mobile-android-lessons
Danielle-Kensy
Dart
Code
41
118
class Pokemon { final String picture; final String description; final double height; final double weight; final List<String> type; final String skill; final List<String> weakness; Pokemon({ required this.picture, required this.description, required this.height, required this.weight, required this.type, required this.skill, required this.weakness, }); }
46,349
https://github.com/PacificBiosciences/pancake/blob/master/src/pancake/MapperBatchUtility.cpp
Github Open Source
Open Source
BSD-3-Clause-Clear, BSL-1.0, BSD-3-Clause, MIT
2,022
pancake
PacificBiosciences
C++
Code
1,945
6,393
// Authors: Ivan Sovic #include <pacbio/alignment/AlignmentTools.h> #include <pacbio/pancake/MapperBatchUtility.h> #include <pacbio/pancake/OverlapWriterBase.h> #include <pbcopper/logging/Logging.h> namespace PacBio { namespace Pancake { std::vector<PacBio::Pancake::MapperBatchChunk> ConstructBatchData( const std::vector<std::pair<std::vector<std::string>, std::vector<std::string>>>& inData) { std::vector<PacBio::Pancake::MapperBatchChunk> batchData; for (const auto& dataPair : inData) { const auto& queries = dataPair.first; const auto& targets = dataPair.second; PacBio::Pancake::MapperBatchChunk chunk; // Add the target sequences to the chunk. for (size_t i = 0; i < targets.size(); ++i) { const auto& seq = targets[i]; const int32_t seqId = i; auto seqCache = PacBio::Pancake::FastaSequenceCached(std::to_string(seqId), seq.c_str(), seq.size(), seqId); chunk.targetSeqs.AddRecord(std::move(seqCache)); } // Add the query sequences to the chunk. for (size_t i = 0; i < queries.size(); ++i) { const auto& seq = queries[i]; const int32_t seqId = i; auto seqCache = PacBio::Pancake::FastaSequenceCached(std::to_string(seqId), seq.c_str(), seq.size(), seqId); chunk.querySeqs.AddRecord(std::move(seqCache)); } batchData.emplace_back(std::move(chunk)); } return batchData; } const char* FetchSequenceFromCacheStore(const FastaSequenceCachedStore& cacheStore, const int32_t seqId, bool doAssert, const std::string& sourceFunction, const std::string& assertMessage, const Overlap* ovl) { FastaSequenceCached seqCache; const bool rvGetSequence = cacheStore.GetSequence(seqCache, seqId); if (doAssert && rvGetSequence == false) { std::ostringstream oss; // Need to print out the source function name, because there is no stack trace. oss << "(" << sourceFunction << ") Could not find sequence with ID = " << seqId << " in cacheStore. " << assertMessage; // Optionally print out the overlap. if (ovl) { oss << "Overlap: " << OverlapWriterBase::PrintOverlapAsM4(*ovl, true) << "."; } oss << " Skipping and continuing anyway."; PBLOG_ERROR << oss.str(); assert(false); return NULL; } return seqCache.c_str(); } void PrepareSequencesForBatchAlignment( const std::vector<MapperBatchChunk>& batchChunks, const std::vector<FastaSequenceCachedStore>& querySeqsRev, const std::vector<std::vector<MapperBaseResult>>& mappingResults, const MapperSelfHitPolicy selfHitPolicy, std::vector<PairForBatchAlignment>& retPartsGlobal, std::vector<PairForBatchAlignment>& retPartsSemiglobal, std::vector<AlignmentStitchInfo>& retAlnStitchInfo, int32_t& retLongestSequence) { retPartsGlobal.clear(); retPartsSemiglobal.clear(); retAlnStitchInfo.clear(); retLongestSequence = 0; // Results are a vector for every chunk (one chunk is one ZMW). for (size_t resultId = 0; resultId < mappingResults.size(); ++resultId) { const auto& result = mappingResults[resultId]; const auto& chunk = batchChunks[resultId]; // One chunk can have multiple queries (subreads). for (size_t ordinalQueryId = 0; ordinalQueryId < result.size(); ++ordinalQueryId) { // Find the actual sequence ID from one valid mapping. int32_t Aid = -1; for (size_t mapId = 0; mapId < result[ordinalQueryId].mappings.size(); ++mapId) { if (result[ordinalQueryId].mappings[mapId] == nullptr || result[ordinalQueryId].mappings[mapId]->mapping == nullptr) { continue; } Aid = result[ordinalQueryId].mappings[mapId]->mapping->Aid; break; } if (Aid < 0) { continue; } // Prepare the forward query data. // Fetch the query sequence without throwing if it doesn't exist for some reason. const char* qSeqFwd = FetchSequenceFromCacheStore(chunk.querySeqs, Aid, true, __FUNCTION__, "Query fwd. Aid = " + std::to_string(Aid), NULL); if (qSeqFwd == NULL) { PBLOG_ERROR << "qSeqFwd == NULL! Skipping and continuing anyway."; assert(false); continue; } // Prepare the reverse query data. const char* qSeqRev = FetchSequenceFromCacheStore(querySeqsRev[resultId], Aid, true, __FUNCTION__, "Query rev. Aid = " + std::to_string(Aid), NULL); if (qSeqRev == NULL) { PBLOG_ERROR << "qSeqRev == NULL! Skipping and continuing anyway."; assert(false); continue; } // Each query can have multiple mappings. for (size_t mapId = 0; mapId < result[ordinalQueryId].mappings.size(); ++mapId) { if (result[ordinalQueryId].mappings[mapId] == nullptr) { continue; } const auto& mapping = result[ordinalQueryId].mappings[mapId]; if (mapping->mapping == nullptr) { continue; } // Shorthand to the mapped data. const auto& aln = mapping->mapping; // Skip self-hits unless the default policy is used, in which case align all. if (selfHitPolicy != MapperSelfHitPolicy::DEFAULT && aln->Aid == aln->Bid) { continue; } // Fetch the target sequence without throwing if it doesn't exist for some reason. const char* tSeq = FetchSequenceFromCacheStore(chunk.targetSeqs, mapping->mapping->Bid, true, __FUNCTION__, "Target.", mapping->mapping.get()); if (tSeq == NULL) { PBLOG_ERROR << "tSeq == NULL. Overlap: " << *mapping->mapping << ". Skipping and continuing anyway."; assert(false); continue; } // AlignmentStitchVector singleQueryStitches; AlignmentStitchInfo singleAlnStitches(resultId, ordinalQueryId, mapId); // Each mapping is split into regions in between seed hits for alignment. for (size_t regId = 0; regId < mapping->regionsForAln.size(); ++regId) { const auto& region = mapping->regionsForAln[regId]; // Prepare the sequences for alignment. const char* qSeqInStrand = region.queryRev ? qSeqRev : qSeqFwd; const char* tSeqInStrand = tSeq; int32_t qStart = region.qStart; int32_t tStart = region.tStart; const int32_t qSpan = region.qSpan; const int32_t tSpan = region.tSpan; PairForBatchAlignment part{qSeqInStrand + qStart, qSpan, tSeqInStrand + tStart, tSpan, region.type, region.queryRev}; retLongestSequence = std::max(retLongestSequence, std::max(qSpan, tSpan)); if (region.type == RegionType::GLOBAL) { singleAlnStitches.parts.emplace_back(AlignmentStitchPart{ region.type, static_cast<int64_t>(retPartsGlobal.size()), static_cast<int64_t>(regId)}); retPartsGlobal.emplace_back(std::move(part)); } else { singleAlnStitches.parts.emplace_back(AlignmentStitchPart{ region.type, static_cast<int64_t>(retPartsSemiglobal.size()), static_cast<int64_t>(regId)}); retPartsSemiglobal.emplace_back(std::move(part)); } } retAlnStitchInfo.emplace_back(std::move(singleAlnStitches)); } } } } OverlapPtr StitchSingleAlignment(const OverlapPtr& aln, const std::vector<AlignmentRegion>& regionsForAln, const std::vector<AlignmentResult>& internalAlns, const std::vector<AlignmentResult>& flankAlns, const std::vector<AlignmentStitchPart>& parts) { if (parts.empty()) { return nullptr; } auto ret = createOverlap(aln); ret->Cigar.clear(); int32_t newQueryStart = -1; int32_t newTargetStart = -1; int32_t newQueryEnd = 0; int32_t newTargetEnd = 0; Alignment::DiffCounts diffs; int32_t score = 0; for (const auto& part : parts) { const auto& region = regionsForAln[part.regionId]; if (part.regionType == RegionType::FRONT) { const auto& partAln = flankAlns[part.partId]; if (partAln.valid == false) { return nullptr; } PacBio::Data::Cigar cigar = partAln.cigar; std::reverse(cigar.begin(), cigar.end()); MergeCigars(ret->Cigar, cigar); newQueryStart = region.qStart + region.qSpan - partAln.lastQueryPos; newTargetStart = region.tStart + region.tSpan - partAln.lastTargetPos; newQueryEnd = region.qStart + region.qSpan; newTargetEnd = region.tStart + region.tSpan; diffs += partAln.diffs; score += partAln.score; } else if (part.regionType == RegionType::BACK) { const auto& partAln = flankAlns[part.partId]; if (partAln.valid == false) { return nullptr; } MergeCigars(ret->Cigar, partAln.cigar); if (newQueryStart < 0) { newQueryStart = region.qStart; newTargetStart = region.tStart; } newQueryEnd = region.qStart + partAln.lastQueryPos; newTargetEnd = region.tStart + partAln.lastTargetPos; diffs += partAln.diffs; score += partAln.score; } else { const auto& partAln = internalAlns[part.partId]; if (partAln.valid == false) { return nullptr; } MergeCigars(ret->Cigar, partAln.cigar); if (newQueryStart < 0) { newQueryStart = region.qStart; newTargetStart = region.tStart; } newQueryEnd = region.qStart + partAln.lastQueryPos; newTargetEnd = region.tStart + partAln.lastTargetPos; diffs += partAln.diffs; score += partAln.score; } } // Skip if the alignment is not valid. if (ret == nullptr) { return ret; } // If there is no alignment, reset the overlap. if (ret->Cigar.empty()) { return nullptr; } ret->Astart = newQueryStart; ret->Aend = newQueryEnd; ret->Bstart = newTargetStart; ret->Bend = newTargetEnd; // Reverse the CIGAR and the coordinates if needed. if (ret->Brev) { // CIGAR reversal. std::reverse(ret->Cigar.begin(), ret->Cigar.end()); // Reverse the query coordinates. std::swap(ret->Astart, ret->Aend); ret->Astart = ret->Alen - ret->Astart; ret->Aend = ret->Alen - ret->Aend; // Get the forward-oriented target coordinates. std::swap(ret->Bstart, ret->Bend); ret->Bstart = ret->Blen - ret->Bstart; ret->Bend = ret->Blen - ret->Bend; } // Set the alignment identity and edit distance. // Alignment::DiffCounts diffs = CigarDiffCounts(ret->Cigar); diffs.Identity(false, false, ret->Identity, ret->EditDistance); ret->Score = score; // std::cerr << "Testing: " << *ret // << "\n"; // std::cerr << " - qSpan = " << (diffs.numEq + diffs.numX + diffs.numI) << "\n"; // std::cerr << " - tSpan = " << (diffs.numEq + diffs.numX + diffs.numD) << "\n"; // std::cerr << " - diffs = " << diffs << "\n"; // std::cerr << "\n"; return ret; } void StitchAlignmentsInParallel(std::vector<std::vector<MapperBaseResult>>& mappingResults, const std::vector<MapperBatchChunk>& batchChunks, const std::vector<FastaSequenceCachedStore>& querySeqsRev, const std::vector<AlignmentResult>& internalAlns, const std::vector<AlignmentResult>& flankAlns, const std::vector<AlignmentStitchInfo>& alnStitchInfo, Parallel::FireAndForget* faf) { // Determine how many records should land in each thread, spread roughly evenly. const int32_t numThreads = faf ? faf->NumThreads() : 1; const int32_t numRecords = alnStitchInfo.size(); const std::vector<std::pair<int32_t, int32_t>> jobsPerThread = PacBio::Pancake::DistributeJobLoad<int32_t>(numThreads, numRecords); const auto Submit = [&jobsPerThread, &batchChunks, &querySeqsRev, &internalAlns, &flankAlns, &alnStitchInfo, &mappingResults](int32_t idx) { const int32_t jobStart = jobsPerThread[idx].first; const int32_t jobEnd = jobsPerThread[idx].second; PacBio::BAM::Cigar revCigar; for (int32_t jobId = jobStart; jobId < jobEnd; ++jobId) { const AlignmentStitchInfo& singleAlnInfo = alnStitchInfo[jobId]; // Not initialized for some reason, skip it. if (singleAlnInfo.ordinalBatchId < 0 || singleAlnInfo.ordinalQueryId < 0 || singleAlnInfo.ordinalMapId < 0) { PBLOG_ERROR << "One of the ordinal values used to access a vector element is negative!" << " singleAlnInfo: " << singleAlnInfo << ". Skipping and continuing anyway."; assert(false); continue; } // Check that the mapping result was not filtered. if (mappingResults[singleAlnInfo.ordinalBatchId][singleAlnInfo.ordinalQueryId] .mappings[singleAlnInfo.ordinalMapId] == nullptr) { continue; } auto& mapping = mappingResults[singleAlnInfo.ordinalBatchId][singleAlnInfo.ordinalQueryId] .mappings[singleAlnInfo.ordinalMapId]; // Check that the mapping result was not filtered. if (mapping->mapping == nullptr) { continue; } auto& aln = mapping->mapping; // Do the stitching, and swap. OverlapPtr newAln = StitchSingleAlignment(aln, mapping->regionsForAln, internalAlns, flankAlns, singleAlnInfo.parts); std::swap(aln, newAln); if (aln == nullptr) { continue; } { // Validation of the final alignment. const auto& chunk = batchChunks[singleAlnInfo.ordinalBatchId]; // Fetch the query seq and its reverse complement without throwing. const char* querySeqFwd = FetchSequenceFromCacheStore(chunk.querySeqs, mapping->mapping->Aid, true, __FUNCTION__, "Query fwd.", aln.get()); const char* querySeqRev = FetchSequenceFromCacheStore( querySeqsRev[singleAlnInfo.ordinalBatchId], mapping->mapping->Aid, true, __FUNCTION__, "Query rev.", aln.get()); const char* querySeq = (aln->Brev) ? querySeqRev : querySeqFwd; if (querySeq == NULL) { PBLOG_ERROR << "querySeq == NULL. Overlap: " << OverlapWriterBase::PrintOverlapAsM4(*aln, true) << ". Skipping and continuing anyway."; assert(false); aln = nullptr; continue; } // Fetch the target seq without throwing. const char* targetSeq = FetchSequenceFromCacheStore(chunk.targetSeqs, mapping->mapping->Bid, true, __FUNCTION__, "Target.", aln.get()); if (targetSeq == NULL) { PBLOG_ERROR << "targetSeq == NULL. Overlap: " << *mapping->mapping << ". Skipping and continuing anyway."; assert(false); aln = nullptr; continue; } // Coordinates relative to strand (internally we represent the B sequence as // reverse, but here we take the reverse of the query, so strands need to be swapped). const int32_t qStart = (aln->Brev) ? (aln->Alen - aln->Aend) : aln->Astart; const int32_t tStart = aln->BstartFwd(); // Reverse the CIGAR if needed. if (aln->Brev) { revCigar.clear(); revCigar.insert(revCigar.end(), aln->Cigar.rbegin(), aln->Cigar.rend()); } PacBio::BAM::Cigar& cigarInStrand = (aln->Brev) ? revCigar : aln->Cigar; // Run the actual validation. try { ValidateCigar(querySeq + qStart, aln->ASpan(), targetSeq + tStart, aln->BSpan(), cigarInStrand, "Full length validation, fwd."); } catch (std::exception& e) { PBLOG_WARN << "[Note: Exception caused by ValidateCigar in StitchAlignments] " << e.what() << "\n"; PBLOG_DEBUG << "singleAlnInfo: " << singleAlnInfo; PBLOG_DEBUG << "Aligned: \"" << *newAln << "\""; PBLOG_DEBUG << mappingResults[singleAlnInfo.ordinalBatchId] [singleAlnInfo.ordinalQueryId] << "\n"; aln = nullptr; continue; } } } }; Parallel::Dispatch(faf, jobsPerThread.size(), Submit); } void SetUnalignedAndMockedMappings(std::vector<std::vector<MapperBaseResult>>& mappingResults, const bool mockPerfectAlignment, const int32_t matchScoreForMockAlignment) { for (size_t chunkId = 0; chunkId < mappingResults.size(); ++chunkId) { auto& result = mappingResults[chunkId]; // One chunk can have multiple queries (subreads). for (size_t qId = 0; qId < result.size(); ++qId) { // Each query can have multiple alignments. for (size_t mapId = 0; mapId < result[qId].mappings.size(); ++mapId) { if (result[qId].mappings[mapId] == nullptr || result[qId].mappings[mapId]->mapping == nullptr) { continue; } OverlapPtr& aln = result[qId].mappings[mapId]->mapping; if (mockPerfectAlignment && aln->Aid == aln->Bid) { aln = CreateMockedAlignment(aln, matchScoreForMockAlignment); } if (aln->Cigar.empty()) { aln = nullptr; } } } } } std::vector<std::vector<FastaSequenceId>> ComputeQueryReverseComplements( const std::vector<MapperBatchChunk>& batchChunks, const std::vector<std::vector<MapperBaseResult>>& mappingResults, const bool onlyWhenRequired, Parallel::FireAndForget* faf) { /* * This function computes the reverse complements of the query sequences. * * As an optimization, if the onlyWhenRequired == true then the reverse complement for * a query will be computed only if there is a mapping that maps the reverse strand * of a query. * Otherwise, an entry in the return vector will be generated, but the sequence will be * an empty string. */ // Figure out which queries need to be reversed. std::vector<std::vector<uint8_t>> shouldReverse(batchChunks.size()); for (size_t i = 0; i < batchChunks.size(); ++i) { shouldReverse[i].resize(batchChunks[i].querySeqs.Size(), !onlyWhenRequired); } if (onlyWhenRequired) { for (size_t chunkId = 0; chunkId < mappingResults.size(); ++chunkId) { auto& result = mappingResults[chunkId]; // One chunk can have multiple queries (subreads). for (size_t qId = 0; qId < result.size(); ++qId) { for (size_t mapId = 0; mapId < result[qId].mappings.size(); ++mapId) { if (result[qId].mappings[mapId] == nullptr || result[qId].mappings[mapId]->mapping == nullptr) { continue; } const OverlapPtr& aln = result[qId].mappings[mapId]->mapping; shouldReverse[chunkId][qId] |= aln->Brev; } } } } // Determine how many records should land in each thread, spread roughly evenly. const int32_t numThreads = faf ? faf->NumThreads() : 1; const int32_t numRecords = batchChunks.size(); const std::vector<std::pair<int32_t, int32_t>> jobsPerThread = PacBio::Pancake::DistributeJobLoad<int32_t>(numThreads, numRecords); std::vector<std::vector<FastaSequenceId>> querySeqsRev(batchChunks.size()); const auto Submit = [&batchChunks, &jobsPerThread, &shouldReverse, &querySeqsRev](int32_t idx) { const int32_t jobStart = jobsPerThread[idx].first; const int32_t jobEnd = jobsPerThread[idx].second; for (int32_t chunkId = jobStart; chunkId < jobEnd; ++chunkId) { auto& revSeqs = querySeqsRev[chunkId]; for (size_t qId = 0; qId < batchChunks[chunkId].querySeqs.records().size(); ++qId) { const auto& query = batchChunks[chunkId].querySeqs.records()[qId]; std::string queryRev; if (shouldReverse[chunkId][qId]) { queryRev = PacBio::Pancake::ReverseComplement(query.c_str(), 0, query.size()); } revSeqs.emplace_back(PacBio::Pancake::FastaSequenceId( query.Name(), std::move(queryRev), query.Id())); } } }; Parallel::Dispatch(faf, jobsPerThread.size(), Submit); return querySeqsRev; } } // namespace Pancake } // namespace PacBio
18,904
https://github.com/Arnauld/swoop/blob/master/src/main/java/swoop/support/ResourceBasedContent.java
Github Open Source
Open Source
MIT
2,013
swoop
Arnauld
Java
Code
115
370
package swoop.support; import java.io.IOException; import java.io.InputStream; import swoop.Action; import swoop.Request; import swoop.Response; import swoop.SwoopException; import swoop.util.IO; public class ResourceBasedContent extends Action { public static String resourcePath(Class<?> clazz) { return clazz.getPackage().getName().replace('.', '/'); } private String resourcePath; public ResourceBasedContent(String resourcePath) { super(); this.resourcePath = resourcePath; } public ResourceBasedContent(String path, String resourcePath) { super(path); this.resourcePath = resourcePath; } @Override public void handle(Request request, Response response) { response.body(resourceAsString(resourcePath)); } private static String resourceAsString(String resourcePath) { InputStream input = ResourceBasedContent.class.getClassLoader().getResourceAsStream(resourcePath); if(input==null) { throw new SwoopException("Missing resource <" + resourcePath + ">"); } try { return IO.toString(input, "utf8").toString(); } catch(IOException ioe) { throw new SwoopException("Failed to load resource <" + resourcePath + ">", ioe); } finally { IO.closeQuietly(input); } } }
13,914
https://github.com/wkoiking/xyzzy/blob/master/site-lisp/kamail3/send.l
Github Open Source
Open Source
BSD-2-Clause
2,022
xyzzy
wkoiking
Common Lisp
Code
382
1,666
;;; -*- Mode: Lisp; Package: EDITOR -*- ;;; ;;; This file is not part of xyzzy. ;;; ; $Id: send.l 793 2008-02-08 20:49:27Z torihat $ ; ; kamail3/send.l ; ; by HATTORI Masashi (eval-when (:compile-toplevel :load-toplevel :execute) (require "kamail3/defs")) (provide "kamail3/send") (in-package "kamail3") (defstruct smtpconf server port auth user pass realm) (defvar *smtp-config-current* nil) (defvar *send-show-sending-message* t) (defvar *send-message-save* nil) (defun send-smtp-select () (unless *smtp-config-list* (return-from send-smtp-select)) (if (= 1 (length *smtp-config-list*)) (car *smtp-config-list*) (let ((server (completing-read "SMTP Server: " (mapcar #'(lambda (x) (smtpconf-server x)) *smtp-config-list*) :default (and (smtpconf-p *smtp-config-current*) (smtpconf-server *smtp-config-current*))))) (when server (smtp-config-get server)) ))) (defun smtp-config-get (server) (car (member server *smtp-config-list* :test #'equal :key #'smtpconf-server))) (defun send-buffer-set () (set-buffer (get-buffer-create *buffer-send*)) (setq need-not-save t)) (defun send-buffer-send () (let* ((smtpconf (send-smtp-select))) (unless (smtpconf-p smtpconf) (kamail3-error "SMTP設定が取得できません。")) (junk::smtp-send-buffer (smtpconf-server smtpconf) :port (smtpconf-port smtpconf) :msgid-add t :auth (smtpconf-auth smtpconf) :user (smtpconf-user smtpconf) :pass (smtpconf-pass smtpconf) :realm (smtpconf-realm smtpconf) :show *send-show-sending-message*) )) (defun send-buffer-save-and-clear () (let ((file (fetched-file-store))) (when (and file *send-message-save*) (fetch-sync (list (list file (attr-folder-string *folder-sent*) nil *attr-status-seen*)))) (delete-buffer *buffer-send*))) (defun send-buffer-create (draft) (let* ((header (draft-header draft)) (body (draft-body draft)) (attachments (draft-attachments draft)) (content-type (junk::mail-get-header-content "content-type" header)) (charset (junk::mail-get-content-charset content-type))) (send-buffer-set) (erase-buffer (selected-buffer)) (send-print-header (draft-header draft) charset) (if attachments (let ((body-header (draft-body-header draft)) (boundary (draft-boundary draft))) (send-print-body-part body-header body boundary) (dolist (attachment attachments) (let ((filename (car attachment)) (part-header (cdr attachment))) (send-print-attachment part-header filename boundary))) (send-print-boundary boundary t)) (send-print-body header body)) )) (defun send-insert-attachment (file) (let ((in (open file :encoding :binary))) (unwind-protect (insert (si:base64-encode in)) (close in)))) #| (defun send-insert-attachment (file) (insert-file-noconv file)) |# (defun send-print-boundary (boundary &optional end-p) (insert (format nil "--~A~A~%" boundary (if end-p "--" "")))) (defun send-print-attachment (header file boundary) (let* ((content-type (junk::mail-get-header-content "content-type" header)) (charset (junk::mail-get-content-charset content-type)) beg) (send-print-boundary boundary) (send-print-header header charset) (setq beg (point)) (send-insert-attachment file) ;(junk::mail-encode-encoding header beg) (goto-char (point-max)) (or (bolp) (insert "\n")))) (defun send-print-body-part (header body boundary) (let* ((content-type (junk::mail-get-header-content "content-type" header)) (charset (junk::mail-get-content-charset content-type))) (send-print-boundary boundary) (send-print-header header charset) (send-print-body header body))) (defun send-print-body (header body) (let ((beg (point))) (insert body) (junk::mail-encode-encoding header beg) (goto-char (point-max)) (or (bolp) (insert "\n")))) (defun send-print-header (header charset) (let ((beg (point))) (dolist (h header) (let ((field (car h)) (value (cdr h))) (when value (insert (format nil "~A: ~A~%" (string-capitalize field) (if (listp value) (junk::string-join value ",\n ") value)))))) (insert "\n") (goto-char beg) (junk::mail-encode-mime-header charset) (goto-char (point-max))))
42,296
https://github.com/ayzhanglei/SimplCommerce/blob/master/src/SimplCommerce.Web/Areas/Admin/ViewModels/Cms/CarouselWidgetForm.cs
Github Open Source
Open Source
Apache-2.0
2,016
SimplCommerce
ayzhanglei
C#
Code
38
109
using System.Collections.Generic; namespace SimplCommerce.Web.Areas.Admin.ViewModels.Cms { public class CarouselWidgetForm { public long Id { get; set; } public string Name { get; set; } public int Zone { get; set; } public IList<CarouselWidgetItemForm> Items = new List<CarouselWidgetItemForm>(); } }
16,336
https://github.com/iLeonelPerea/ux-pal/blob/master/api/handler/handler.js
Github Open Source
Open Source
MIT
2,016
ux-pal
iLeonelPerea
JavaScript
Code
264
1,174
'use strict'; var mongodb = require('mongodb'); var MongoClient = mongodb.MongoClient; var url = 'mongodb://admin:password@ds023593.mlab.com:23593/uxpal'; function dbConnect(cb){ MongoClient.connect(url, function (err, db) { if(err){ return cb(err); }else{ return cb(db); } }); } module.exports.register = function(event, cb){ var userInfo ={"username":event.username,"password":event.password,"email":event.email}; dbConnect(function(db){ var user = db.collection('user'); user.find({username: event.username}) .toArray(function (err, result) { if (err) { return cb(false); }else{ if(result.length > 0){ return cb({err:false,usernameExists:true}); }else{ user.insert(userInfo,function(err, result){ if(err){ return cb(err); }else{ return cb({err:false,usernameExists:false,data:result.ops[0]}) } }); } } //db.close(); }); }); }; module.exports.signIn = function(event, cb){ dbConnect(function(db){ var user = db.collection('user'); user.find({$and:[{username: event.username},{password:event.password}]}) .toArray(function (err, result) { if (err) { return cb(false); }else{ if(result.length > 0){ return cb(true); }else{ return cb(false); } } //db.close(); }); }); }; module.exports.createProject = function(event,cb){ dbConnect(function(db){ var projects = db.collection('projects'); projects.find({isTemplate:true},{isTemplate:0,_id:0}).toArray(function(err,result){ if(err){ return cb(err); }else{ var template = result[0]; template.projectName = event.projectName; template.projectOwner = event.username; template.projectDescription = event.description; projects.insert(template, function (err, result) { if (err) { return cb(err); } else { return cb({err:false,data:result.ops[0]}); } //db.close(); }); } }) }); } module.exports.getProjects = function(event,cb){ dbConnect(function(db){ var user = db.collection('projects'); user.find({projectOwner:event.username},{projectName:1,_id:0}) .toArray(function (err, result) { if (err) { return cb(false); }else{ if(result.length > 0){ return cb({err:false,projectExist:true,data:result[0]}); }else{ return cb({err:false,projectExist:false}); } } //db.close(); }); }); } module.exports.getProjectData = function(event,cb){ dbConnect(function(db){ var user = db.collection('projects'); user.find({projectName:event.projectName,projectOwner:event.username}) .toArray(function (err, result) { if (err) { return cb(false); }else{ if(result.length > 0){ console.log(result); return cb({err:false,projectExist:true,data:result[0]}); }else{ return cb({err:false,projectExist:false}); } } //db.close(); }); }); } module.exports.updateProject = function(event,cb){ dbConnect(function(db){ var projects = db.collection('projects'); projects.findAndRemove({"projectName":event.projectName,"projectOwner":event.projectOwner}, function(err, result) { if(err){ return cb(err); }else{ projects.insert(event, function (err, data) { if (err) { return cb(err); } else { return cb({err:false,data:data.ops[0]}); } //db.close(); }); } }); }); }
33,230
https://github.com/tianqichongzhen/minix3/blob/master/lib/i386/em/em_exg.s
Github Open Source
Open Source
BSD-3-Clause
2,022
minix3
tianqichongzhen
GAS
Code
46
160
.sect .text; .sect .rom; .sect .data; .sect .bss .define .exg ! #bytes in ecx .sect .text .exg: push edi mov edi,esp add edi,8 mov ebx,edi add ebx,ecx sar ecx,2 1: mov eax,(ebx) xchg eax,(edi) mov (ebx),eax add edi,4 add ebx,4 loop 1b 2: pop edi ret
33,799
https://github.com/d2s/kontena/blob/master/cli/lib/kontena/cli/master/config_command.rb
Github Open Source
Open Source
Apache-2.0
2,022
kontena
d2s
Ruby
Code
54
180
module Kontena module Cli module Master class ConfigCommand < Kontena::Command subcommand "set", "Set a config value", load_subcommand('master/config/set_command') subcommand "get", "Get a config value", load_subcommand('master/config/get_command') subcommand "unset", "Clear a config value", load_subcommand('master/config/unset_command') subcommand ["load", "import"], "Upload config to Master", load_subcommand('master/config/import_command') subcommand ["dump", "export"], "Download config from Master", load_subcommand('master/config/export_command') def execute end end end end end
39,178
https://github.com/dpnolte/ReactiveUI.Routing/blob/master/src/ReactiveUI.Routing/IRoutedAppHost.cs
Github Open Source
Open Source
MIT
2,017
ReactiveUI.Routing
dpnolte
C#
Code
108
247
using System; using System.Reactive; using System.Threading.Tasks; namespace ReactiveUI.Routing { /// <summary> /// Defines an interface for objects that bind cross-platform routers and presenters /// to their host platform. /// </summary> public interface IRoutedAppHost { /// <summary> /// Triggers the start of the app host, /// which kicks off the router. /// </summary> void Start(); /// <summary> /// Triggers the start of the app host, /// which kicks off the router. /// </summary> /// <returns></returns> Task StartAsync(); /// <summary> /// Causes the application to save its state. /// </summary> void SaveState(); /// <summary> /// Causes the application to save its state. /// </summary> /// <returns></returns> Task SaveStateAsync(); } }
837
https://github.com/Crawping/fishjam-template-library/blob/master/Temp/CyberLink4CC/sample/clock/tengine/gnu/configure
Github Open Source
Open Source
BSD-3-Clause
2,015
fishjam-template-library
Crawping
Shell
Code
45
147
#!/bin/sh cd src; rm -f upnpclock.cpp.lnk; ln -sf ../../../unix/ClockMain.cpp upnpclock.cpp; cd .. cd sh7727; rm -f Makefile.lnk; ln -fs ../src/Makefile Makefile; cd .. cd sh7727.debug; rm -f Makefile.lnk; ln -fs ../src/Makefile Makefile; cd .. cd sh7727.dl; rm -f Makefile.lnk; ln -fs ../src/Makefile Makefile; cd ..
13,528
https://github.com/smilesnake/apollo/blob/master/apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/filter/ClientAuthenticationFilter.java
Github Open Source
Open Source
Apache-2.0
null
apollo
smilesnake
Java
Code
346
1,383
package com.ctrip.framework.apollo.configservice.filter; import com.ctrip.framework.apollo.configservice.util.AccessKeyUtil; import com.ctrip.framework.apollo.core.signature.Signature; import com.google.common.net.HttpHeaders; import java.io.IOException; import java.util.List; import java.util.Objects; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.StringUtils; /** * 客户端认证过滤器 * * @author nisiyong */ @Slf4j public class ClientAuthenticationFilter implements Filter { private static final Long TIMESTAMP_INTERVAL = 60 * 1000L; /** * 访问密钥工具类 */ private final AccessKeyUtil accessKeyUtil; public ClientAuthenticationFilter(AccessKeyUtil accessKeyUtil) { this.accessKeyUtil = accessKeyUtil; } @Override public void init(FilterConfig filterConfig) throws ServletException { //nothing } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; // 从请求中提取的应用id String appId = accessKeyUtil.extractAppIdFromRequest(request); if (StringUtils.isBlank(appId)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidAppId"); return; } // 查询可用的密钥 List<String> availableSecrets = accessKeyUtil.findAvailableSecret(appId); if (CollectionUtils.isNotEmpty(availableSecrets)) { // http请求中header时间戳 String timestamp = request.getHeader(Signature.HTTP_HEADER_TIMESTAMP); // header中的认证字符串 String authorization = request.getHeader(HttpHeaders.AUTHORIZATION); // 检查时间戳,1分钟内有效 if (!checkTimestamp(timestamp)) { log.warn("Invalid timestamp. appId={},timestamp={}", appId, timestamp); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "RequestTimeTooSkewed"); return; } // 检查签名 String uri = request.getRequestURI(); String query = request.getQueryString(); if (!checkAuthorization(authorization, availableSecrets, timestamp, uri, query)) { log.warn("Invalid authorization. appId={},authorization={}", appId, authorization); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); return; } } chain.doFilter(request, response); } @Override public void destroy() { //nothing } /** * 检查时间戳范围(检查时间戳,1分钟内有效) * * @param timestamp 时间戳 * @return true, 有效,否则,false */ private boolean checkTimestamp(String timestamp) { // 请求时间(毫秒) long requestTimeMillis = 0L; try { requestTimeMillis = Long.parseLong(timestamp); } catch (NumberFormatException e) { // nothing to do } long x = System.currentTimeMillis() - requestTimeMillis; // 时间差为±TIMESTAMP_INTERVAL, return x >= -TIMESTAMP_INTERVAL && x <= TIMESTAMP_INTERVAL; } /** * 检查认证 * * @param authorization 认证字符串 * @param availableSecrets 可用的密钥 * @param timestamp 时间戳 * @param path 路径 * @param query 查询参数 * @return true, 认证有效,否则,false */ private boolean checkAuthorization(String authorization, List<String> availableSecrets, String timestamp, String path, String query) { String signature = null; if (authorization != null) { String[] split = authorization.split(":"); if (split.length > 1) { signature = split[1]; } } // 循环遍历,检查签名 for (String secret : availableSecrets) { // 构建签名 String availableSignature = accessKeyUtil.buildSignature(path, query, timestamp, secret); // 签名相等说明可用 if (Objects.equals(signature, availableSignature)) { return true; } } return false; } }
14,268
https://github.com/micahhahn/Passado/blob/master/Passado/Query/Delete/IJoinable.cs
Github Open Source
Open Source
MIT
null
Passado
micahhahn
C#
Code
23
81
using System; using System.Collections.Generic; using System.Text; namespace Passado.Query.Delete { public interface IJoinable<TDatabase, TTable1> { } public interface IJoinable<TDatabase, TTable1, TTable2> { } }
2,213
https://github.com/bsu-slim/jstlm/blob/master/src/sequence/Text.java
Github Open Source
Open Source
MIT
null
jstlm
bsu-slim
Java
Code
229
744
package sequence; import java.util.HashMap; import java.util.LinkedList; import java.util.Set; public class Text<T> { /* * Holds the "vocabulary" for the tree */ public LinkedList<Integer> items; HashMap<T,Integer> vocab; int index; public Text() { vocab = new HashMap<T,Integer>(); items = new LinkedList<Integer>(); this.index = 0; //vocab.put((T)Constants.ROOT, index++); } public Set<T> getVocabulary() { return vocab.keySet(); } public void pushFront(int item) { items.addFirst(item); } public void pushBack(int item) { items.add(item); } public void put(T word, int i) { vocab.put(word, i); index++; } public int pop() { return items.pop(); } public void cut() { items.removeFirst(); } public int size() { return this.items.size(); } public void clear() { this.items.clear(); } public int at(int i) { if (size() == 0) return 0; if (i == -1) i = size() -1; return items.get(i); } public void print() { } public int offer(T word) { if (get(word) == -1){ vocab.put(word, index); return index++; } return vocab.get(word); } public int get(T word) { if (vocab.containsKey(word)) { return vocab.get(word); } return -1; } public boolean has(T word) { if (get(word) == -1) return false; return true; } public int vocabSize() { return this.vocab.size(); } public T getWordFromVocabIndex(int ind) { for (T word : vocab.keySet()) { if (vocab.get(word) == ind) return word; } //return (T)Constants.UNK; return null; } public T getWordFromIndex(int ind) { for (T word : vocab.keySet()) { if (vocab.get(word) == this.at(ind)) return word; } //return (T)Constants.UNK; return null; } }
17,356
https://github.com/tianshaojun/maoyan/blob/master/src/components/common/movie-list/MovieItem.vue
Github Open Source
Open Source
MIT
2,020
maoyan
tianshaojun
Vue
Code
195
847
<template> <div class="item"> <div class="main-block"> <div class="avatar" sort-flag=""> <div class="default-img-bg"> <img :src="item.img | replaceWH('128.180')" onerror="this.style.visibility='hidden'"> </div> </div> <div class="mb-outline-b content-wrapper"> <div class="column content"> <div class="box-flex movie-title"> <div class="title line-ellipsis v3d_title">{{ item.nm }}</div> <span class="version" :class="item.version"></span> <span :class="{'pre-show': item.preShow}"></span> </div> <div v-if="$route.name==='intheater'" class="detail column"> <div class="score line-ellipsis"> <span class="score-suffix">观众评 </span> <span class="grade">{{ item.sc }}</span> </div> <div class="actor line-ellipsis">{{ item.star || '暂无演职人员信息' }}</div> <div class="show-info line-ellipsis">{{ item.showInfo }}</div> </div> <div v-else class="detail column"> <div class="wantsee line-ellipsis"> <span class="person">{{item.wish}}</span> <span class="p-suffix">人想看</span> </div> <div class="actor line-ellipsis">主演: {{item.star || '暂无主演信息'}}</div> <div class="actor line-ellipsis">{{ item.rt }} 上映</div> </div> </div> </div> <div class="button-block"> <movie-button v-if="$route.name==='intheater'" :globalReleased="item.globalReleased"> {{ item.globalReleased | globalReleasedText }} </movie-button> <movie-button v-else :showst="item.showst"> {{ item.showst | showStText }} </movie-button> </div> </div> </div> </div> </template> <script> import MovieButton from 'components/common/movie-list/MovieButton' export default { props: { item: Object }, components: { MovieButton }, filters: { globalReleasedText (value) { return !value ? '预售' : '购票' }, showStText (value) { return value === 4 ? '预售' : '想看' } } } </script> <style lang="stylus" scoped> @import '~styles/ellipsis.styl' @import '~styles/border.styl' .default-img-bg img width .64rem height .9rem .line-ellipsis ellipsis() .movie-title display flex .content-wrapper height auto !important max-height none !important border 0 0 1px 0, #ccc </style>
17,271
https://github.com/colbyfayock/egghead-demo-github-action-futurama-zoidberg-quote/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,021
egghead-demo-github-action-futurama-zoidberg-quote
colbyfayock
Ignore List
Code
28
35
# You do not want to add the dist directory here, as we need # the files locally in order to run the them in the action node_modules
14,167
https://github.com/Zo3i/codewarsPy/blob/master/sortOdd.py
Github Open Source
Open Source
Apache-2.0
null
codewarsPy
Zo3i
Python
Code
48
152
def sort_array(source_array): odd = sorted(list(filter(lambda x: x % 2 ==1, source_array))) j = 0 strs = ''.join(str(e) for e in source_array) for i in source_array: if i % 2 == 1: print('i=',i) print(odd[j]) strs = strs.replace(str(i), str(odd[j])) j += 1 print(odd) print(strs) print(sort_array([5, 3, 2, 8, 1, 4]))
33,709
https://github.com/pedro-filho-81/LivrosDeJava/blob/master/ComoProgramar/Capitulo04/ExemplosCap04/OutrosDesenhos/OutrosDesenhos01.java
Github Open Source
Open Source
MIT
null
LivrosDeJava
pedro-filho-81
Java
Code
88
242
import java.awt.Graphics; import javax.swing.JPanel; public class OutrosDesenhos01 extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); int getLargura = getWidth(); // getLargura int getAltura = getHeight(); // getAltura // desenha uma linha a partir do canto superior esquerdo (0, 0) até o canto // inferior direito g.drawLine(0, 0, getLargura, getAltura); // g.drawLine(0, 0, getLargura, getAltura); // g.drawLine(0, 0, getLargura, getAltura); // desenha uma linha a partir do canto inferior esquerdo até o canto superior // direito //g.drawLine(0, getAltura, getLargura, 0); } // fim paintComponent } // fim classe
45,299
https://github.com/ajadex/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/master/src/System.IdentityModel.Tokens.Jwt/WSSecurity10Constants.cs
Github Open Source
Open Source
Apache-2.0
null
azure-activedirectory-identitymodel-extensions-for-dotnet
ajadex
C#
Code
214
520
//----------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // 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. //----------------------------------------------------------------------- namespace System.IdentityModel.Tokens { using System.Diagnostics.CodeAnalysis; /// <summary> /// Defines constants needed from WS-Security 1.0. /// </summary> [SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Suppressed for private or internal fields.")] internal static class WSSecurityConstantsInternal { #pragma warning disable 1591 public const string Namespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; public const string Prefix = "wsse"; public const string Base64EncodingType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"; public const string Base64Binary = "Base64Binary"; public const string Base64BinaryLower = "base64Binary"; public static class Attributes { public const string ValueType = "ValueType"; public const string EncodingType = "EncodingType"; public const string EncodingTypeLower = "encodingType"; } public static class Elements { public const string BinarySecurityToken = "BinarySecurityToken"; } #pragma warning restore 1591 } }
20,684
https://github.com/crontabpy/documentation/blob/master/content/manual/adoc/en/framework/gui_framework/gui_vcl/gui_components/gui_DateField.adoc
Github Open Source
Open Source
CC-BY-4.0
null
documentation
crontabpy
AsciiDoc
Code
756
1,912
:sourcesdir: ../../../../../../source [[gui_DateField]] ====== DateField ++++ <div class="manual-live-demo-container"> <a href="https://demo.cuba-platform.com/sampler/open?screen=simple-datefield" class="live-demo-btn" target="_blank">LIVE DEMO</a> </div> ++++ ++++ <div class="manual-live-demo-container"> <a href="http://files.cuba-platform.com/javadoc/cuba/6.10/com/haulmont/cuba/gui/components/DateField.html" class="api-docs-btn" target="_blank">API DOCS</a> </div> ++++ `DateField` is a field to display and enter date and time. It is an input field, inside which there is a button with a drop-down calendar. To the right, there is a time field. image::gui_dateFieldSimple.png[align="center"] XML name of the component: `dateField`. The `DateField` component is implemented for *Web Client* and *Desktop Client*. * To create a date field associated with data, you should use the <<gui_attr_datasource,datasource>> and <<gui_attr_property,property>> attributes: + [source, xml] ---- include::{sourcesdir}/gui_vcl/datefield_1.xml[] ---- + In the example above, the screen has the `orderDs` data source for the `Order` entity, which has the `date` property. The reference to the data source is specified in the <<gui_attr_datasource,datasource>> attribute of the `dateField` component; the name of the entity attribute which value should be displayed in the field is specified in the <<gui_attr_property,property>> attribute. * If the field is associated with an entity attribute, it will automatically take the appropriate form: ** If the attribute has the `java.sql.Date` type or the `@Temporal(TemporalType.DATE)` annotation is specified, the time field will not be displayed. The date format is defined by the `date` <<datatype,datatype>> and is specified in the <<main_message_pack,main localized message pack>> in the `dateFormat` key. ** Otherwise, the time field with hours and minutes will be displayed. The time format is defined by the `time` <<datatype,datatype>> and is specified in the main localized message pack in the `timeFormat` key. [[gui_DateField_dateFormat]] * You can change the date and time format using the `dateFormat` attribute. An attribute value can be either a format string itself or a key in a message pack (if the value starts with `msg://`). + The format is defined by rules of the `SimpleDateFormat` class (http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html). If there are no `H` or `h` characters in the format, the time field will not be displayed. + [source, xml] ---- include::{sourcesdir}/gui_vcl/datefield_2.xml[] ---- + image::gui_dateField_format.png[align="center"] + [WARNING] ==== `DateField` is primarily intended for quick input by filling placeholders from keyboard. Therefore the component supports only formats with digits and separators. Complex formats with textual representation of weekdays or months will not work. ==== [[gui_DateField_range]] * You can specify available dates by using `rangeStart` and `rangeEnd` attributes. If a range is set, all dates outside the range will be disabled. You can set range dates in the "yyyy-MM-dd" format in XML or programmatically by using corresponding setters. + [source, xml] ---- include::{sourcesdir}/gui_vcl/datefield_4.xml[] ---- + image::gui_datefield_month_range.png[align="center"] * Changes of the `DateField` value, as well as of any other components implementing the `Field` interface, can be tracked using a `ValueChangeListener`. [[gui_DateField_resolution]] * Date and time accuracy can be defined using a `resolution` attribute. An attribute value should match the `DateField.Resolution` enumeration − `SEC`, `MIN`, `HOUR`, `DAY`, `MONTH`, `YEAR`. Default is `MIN`, i.e., to within a minute. + If `resolution="DAY"` and `dateFormat` is not specified, the format will be taken from one specified in the <<main_message_pack,main message pack>> with the `dateFormat` key. + If `resolution="MIN"` and `dateFormat` is not specified, the format will be taken from one specified in the main message pack with the `dateTimeFormat` key. Below is a field definition for entering a date up to within a month. + [source, xml] ---- include::{sourcesdir}/gui_vcl/datefield_3.xml[] ---- image::gui_dateField_resolution.png[align="center"] * `DateField` can perform timestamp value conversions between server and user time zones if the user's <<timeZone,time zone>> is set by `setTimeZone()` method. The time zone is assigned automatically from the current <<userSession,user session>> when the component is bound to an entity attribute of the timestamp type. If the component is not bound to such attribute, you can call `setTimeZone()` in the screen controller to make the `DateField` perform required conversions.. [[gui_datefield_borderless]] * In Web Client with a Halo-based theme, you can set predefined `borderless` style name to the DateField component to remove borders and background from the field. This can be done either in the XML descriptor or in the screen controller: + [source, xml] ---- include::{sourcesdir}/gui_vcl/datefield_5.xml[] ---- + When setting a style programmatically, select the `HaloTheme` class constant with the `DATEFIELD_` prefix: + [source, java] ---- include::{sourcesdir}/gui_vcl/datefield_6.java[] ---- ''' Attributes of dateField:: <<gui_attr_align,align>> - <<gui_attr_caption,caption>> - <<gui_attr_contextHelpText,contextHelpText>> - <<gui_attr_contextHelpTextHtmlEnabled,contextHelpTextHtmlEnabled>> - <<gui_attr_datasource,datasource>> - <<gui_DateField_dateFormat,dateFormat>> - <<gui_attr_description,description>> - <<gui_attr_editable,editable>> - <<gui_attr_enable,enable>> - <<gui_attr_height,height>> - <<gui_attr_icon,icon>> - <<gui_attr_id,id>> - <<gui_attr_property,property>> - <<gui_attr_stylename,stylename>> - <<gui_attr_required,required>> - <<gui_DateField_range,rangeEnd>> - <<gui_DateField_range,rangeStart>> - <<gui_attr_requiredMessage,requiredMessage>> - <<gui_DateField_resolution,resolution>> - <<gui_attr_tabIndex,tabIndex>> - <<gui_attr_visible,visible>> - <<gui_attr_width,width>> Elements of dateField:: <<gui_validator,validator>> Predefined styles of dateField:: <<gui_datefield_borderless,borderless>> - <<gui_attr_stylename_small,small>> - <<gui_attr_stylename_tiny,tiny>> API:: <<gui_api_addValueChangeListener,addValueChangeListener>> - <<gui_api_commit,commit>> - <<gui_api_discard,discard>> - <<gui_api_isModified,isModified>> - <<gui_api_contextHelp,setContextHelpIconClickHandler>> '''
38,561
https://github.com/andrepestana-aot/forms-flow-ai/blob/master/forms-flow-web/src/components/Dashboard/index.js
Github Open Source
Open Source
Apache-2.0
2,022
forms-flow-ai
andrepestana-aot
JavaScript
Code
19
47
import React from "react"; import Dashboard from "./Dashboard"; import "./dashboard.scss"; export default React.memo(() => { return <Dashboard />; });
5,201
https://github.com/Propertyinsight/ember-cli-browser-service/blob/master/app/services/browser.js
Github Open Source
Open Source
MIT
null
ember-cli-browser-service
Propertyinsight
JavaScript
Code
212
652
import Ember from 'ember'; export default Ember.Service.extend({ _detection: null, detect: function() { // http://stackoverflow.com/a/2401861/188740 if (!this.get('_detection')) this.set('_detection', (function() { var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; if (/trident/i.test(M[1])) { tem = /\brv[ :]+(\d+)/g.exec(ua) || []; return 'IE ' + (tem[1] || ''); } if (M[1] === 'Chrome') { tem = ua.match(/\b(OPR|Edge)\/(\d+)/); if (tem != null) return tem.slice(1).join(' ').replace('OPR', 'Opera'); } M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?']; if ((tem = ua.match(/version\/(\d+)/i)) != null) { M.splice(1, 1, tem[1]) }; return M.join(' '); })()); // Sample values: // // MSIE 8 // MSIE 9 // MSIE 10 // IE 11 // Chrome 41 // Chrome 42 (using 42 Beta) // Chrome 43 (using 43 Dev) // Firefox 35 // Firefox 37 (using 37 Beta) // Firefox 3 (usng 3.6) // Safari 8 // Safari 6 (using 6.1) // Safari 8 (using iPhone 6) // Chrome 4 (Samsung S5 native browser) // Opera 27 return this.get('_detection'); }, agent: function() { var a = this.detect().split(' ')[0]; if (a === 'MSIE'){ a = 'IE'; } return a; }, version: function() { var parts = this.detect().split(' '); if (parts.length < 2){ return 0; } var matches = parts[1].match(/\d+/); if (!matches || matches.length < 1){ return 0; } return parseInt(matches[0], 10); } });
28,316
https://github.com/sarfaraz1373/Image-Editor/blob/master/main.py
Github Open Source
Open Source
MIT
2,021
Image-Editor
sarfaraz1373
Python
Code
343
1,706
# Create by Packetsss # Personal use is allowed # Commercial use is prohibited from widgets import * class Start(QWidget): def __init__(self): super().__init__() uic.loadUi(f"{pathlib.Path(__file__).parent.absolute()}\\ui\\startup.ui", self) self.setWindowIcon(QIcon(f"{pathlib.Path(__file__).parent.absolute()}\\icon\\icon.png")) self.button = self.findChild(QPushButton, "browse") self.button.clicked.connect(self.on_click) self.files, self.main_window = None, None def on_click(self): files, _ = QFileDialog.getOpenFileNames(self, "Choose Image File", "", "Image Files (*.jpg *.png *.jpeg *.ico);;All Files (*)") if files: self.files = files self.close() self.main_window = Main(self.files) self.main_window.show() class Main(QWidget): def __init__(self, files): # initialize super().__init__() uic.loadUi(f"{pathlib.Path(__file__).parent.absolute()}\\ui\\main.ui", self) self.setWindowIcon(QIcon(f"{pathlib.Path(__file__).parent.absolute()}\\icon\\icon.png")) self.move(120, 100) self.img_list, self.rb = [], None for f in files: self.img_list.append(Images(f)) self.img_id = 0 self.img_class = self.img_list[self.img_id] self.img = QPixmap(qimage2ndarray.array2qimage(cv2.cvtColor(self.img_class.img, cv2.COLOR_BGR2RGB))) # find widgets and connect them self.vbox = self.findChild(QVBoxLayout, "vbox") self.vbox1 = self.findChild(QVBoxLayout, "vbox1") self.base_frame = self.findChild(QFrame, "base_frame") self.filter_btn = self.findChild(QPushButton, "filter_btn") self.filter_btn.clicked.connect(self.filter_frame) self.adjust_btn = self.findChild(QPushButton, "adjust_btn") self.adjust_btn.clicked.connect(self.adjust_frame) self.ai_btn = self.findChild(QPushButton, "ai_btn") self.ai_btn.clicked.connect(self.ai_frame) self.save_btn = self.findChild(QPushButton, "save_btn") self.save_btn.clicked.connect(self.click_save) self.slider = self.findChild(QSlider, "slider") self.slider.setParent(None) # display img self.gv = self.findChild(QGraphicsView, "gv") self.scene = QGraphicsScene() self.scene_img = self.scene.addPixmap(self.img) self.gv.setScene(self.scene) # zoom in self.zoom_moment = False self._zoom = 0 # misc self.rotate_value, self.brightness_value, self.contrast_value, self.saturation_value = 0, 0, 1, 0 self.flip = [False, False] self.zoom_factor = 1 def update_img(self, movable=False): self.img = QPixmap(qimage2ndarray.array2qimage(cv2.cvtColor(self.img_class.img, cv2.COLOR_BGR2RGB))) self.scene.removeItem(self.scene_img) self.scene_img = self.scene.addPixmap(self.img) if movable: self.scene_img.setFlag(QGraphicsItem.ItemIsMovable) else: self.fitInView() def get_zoom_factor(self): return self.zoom_factor def filter_frame(self): filter_frame = Filter(self) self.base_frame.setParent(None) self.vbox.addWidget(filter_frame.frame) def adjust_frame(self): adjust_frame = Adjust(self) self.base_frame.setParent(None) self.vbox.addWidget(adjust_frame.frame) def ai_frame(self): self.rb = ResizableRubberBand(self) ai_frame = Ai(self) self.base_frame.setParent(None) self.vbox.addWidget(ai_frame.frame) def click_save(self): try: file, _ = QFileDialog.getSaveFileName(self, 'Save File', f"{self.img_class.img_name}." f"{self.img_class.img_format}", "Image Files (*.jpg *.png *.jpeg *.ico);;All Files (*)") self.img_class.save_img(file) except Exception: pass def wheelEvent(self, event): if self.zoom_moment: if event.angleDelta().y() > 0: factor = 1.25 self._zoom += 1 else: factor = 0.8 self._zoom -= 1 if self._zoom > 0: self.gv.scale(factor, factor) elif self._zoom == 0: self.fitInView() else: self._zoom = 0 def fitInView(self): rect = QRectF(self.img.rect()) if not rect.isNull(): self.gv.setSceneRect(rect) unity = self.gv.transform().mapRect(QRectF(0, 0, 1, 1)) self.gv.scale(1 / unity.width(), 1 / unity.height()) view_rect = self.gv.viewport().rect() scene_rect = self.gv.transform().mapRect(rect) factor = min(view_rect.width() / scene_rect.width(), view_rect.height() / scene_rect.height()) self.gv.scale(factor, factor) self._zoom = 0 self.zoom_factor = factor def main(): app = QApplication(sys.argv) window = Start() window.show() app.exec_() if __name__ == "__main__": main()
12,391
https://github.com/liyanlong/vue-admin-bootstrap/blob/master/src/utils/transitionEvent.js
Github Open Source
Open Source
MIT
2,017
vue-admin-bootstrap
liyanlong
JavaScript
Code
46
138
function transitionEnd () { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return transEndEventNames[name]; } } return false } export default { end: transitionEnd() };
42,744
https://github.com/dbac/jdk8/blob/master/src/share/native/sun/font/layout/KhmerReordering.h
Github Open Source
Open Source
MIT
null
jdk8
dbac
C
Code
1,110
2,077
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ /* * (C) Copyright IBM Corp. 1998-2005 - All Rights Reserved * * This file is a modification of the ICU file IndicReordering.h * by Jens Herden and Javier Sola for Khmer language * */ #ifndef __KHMERREORDERING_H #define __KHMERREORDERING_H /** * \file * \internal */ #include "LETypes.h" #include "OpenTypeTables.h" U_NAMESPACE_BEGIN class LEGlyphStorage; // Vocabulary // Base -> A consonant or an independent vowel in its full (not subscript) form. It is the // center of the syllable, it can be souranded by coeng (subscript) consonants, vowels, // split vowels, signs... but there is only one base in a syllable, it has to be coded as // the first character of the syllable. // split vowel --> vowel that has two parts placed separately (e.g. Before and after the consonant). // Khmer language has five of them. Khmer split vowels either have one part before the // base and one after the base or they have a part before the base and a part above the base. // The first part of all Khmer split vowels is the same character, identical to // the glyph of Khmer dependent vowel SRA EI // coeng --> modifier used in Khmer to construct coeng (subscript) consonants // Differently than indian languages, the coeng modifies the consonant that follows it, // not the one preceding it Each consonant has two forms, the base form and the subscript form // the base form is the normal one (using the consonants code-point), the subscript form is // displayed when the combination coeng + consonant is encountered. // Consonant of type 1 -> A consonant which has subscript for that only occupies space under a base consonant // Consonant of type 2.-> Its subscript form occupies space under and before the base (only one, RO) // Consonant of Type 3 -> Its subscript form occupies space under and after the base (KHO, CHHO, THHO, BA, YO, SA) // Consonant shifter -> Khmer has to series of consonants. The same dependent vowel has different sounds // if it is attached to a consonant of the first series or a consonant of the second series // Most consonants have an equivalent in the other series, but some of theme exist only in // one series (for example SA). If we want to use the consonant SA with a vowel sound that // can only be done with a vowel sound that corresponds to a vowel accompanying a consonant // of the other series, then we need to use a consonant shifter: TRIISAP or MUSIKATOAN // x17C9 y x17CA. TRIISAP changes a first series consonant to second series sound and // MUSIKATOAN a second series consonant to have a first series vowel sound. // Consonant shifter are both normally supercript marks, but, when they are followed by a // superscript, they change shape and take the form of subscript dependent vowel SRA U. // If they are in the same syllable as a coeng consonant, Unicode 3.0 says that they // should be typed before the coeng. Unicode 4.0 breaks the standard and says that it should // be placed after the coeng consonant. // Dependent vowel -> In khmer dependent vowels can be placed above, below, before or after the base // Each vowel has its own position. Only one vowel per syllable is allowed. // Signs -> Khmer has above signs and post signs. Only one above sign and/or one post sign are // Allowed in a syllable. // // struct KhmerClassTable // This list must include all types of components that can be used inside a syllable { enum CharClassValues // order is important here! This order must be the same that is found in each horizontal // line in the statetable for Khmer (file KhmerReordering.cpp). { CC_RESERVED = 0, CC_CONSONANT = 1, // consonant of type 1 or independent vowel CC_CONSONANT2 = 2, // Consonant of type 2 CC_CONSONANT3 = 3, // Consonant of type 3 CC_ZERO_WIDTH_NJ_MARK = 4, // Zero Width non joiner character (0x200C) CC_CONSONANT_SHIFTER = 5, CC_ROBAT = 6, // Khmer special diacritic accent -treated differently in state table CC_COENG = 7, // Subscript consonant combining character CC_DEPENDENT_VOWEL = 8, CC_SIGN_ABOVE = 9, CC_SIGN_AFTER = 10, CC_ZERO_WIDTH_J_MARK = 11, // Zero width joiner character CC_COUNT = 12 // This is the number of character classes }; enum CharClassFlags { CF_CLASS_MASK = 0x0000FFFF, CF_CONSONANT = 0x01000000, // flag to speed up comparing CF_SPLIT_VOWEL = 0x02000000, // flag for a split vowel -> the first part is added in front of the syllable CF_DOTTED_CIRCLE = 0x04000000, // add a dotted circle if a character with this flag is the first in a syllable CF_COENG = 0x08000000, // flag to speed up comparing CF_SHIFTER = 0x10000000, // flag to speed up comparing CF_ABOVE_VOWEL = 0x20000000, // flag to speed up comparing // position flags CF_POS_BEFORE = 0x00080000, CF_POS_BELOW = 0x00040000, CF_POS_ABOVE = 0x00020000, CF_POS_AFTER = 0x00010000, CF_POS_MASK = 0x000f0000 }; typedef le_uint32 CharClass; typedef le_int32 ScriptFlags; LEUnicode firstChar; // for Khmer this will become x1780 LEUnicode lastChar; // and this x17DF const CharClass *classTable; CharClass getCharClass(LEUnicode ch) const; static const KhmerClassTable *getKhmerClassTable(); }; class KhmerReordering /* not : public UObject because all methods are static */ { public: static le_int32 reorder(const LEUnicode *theChars, le_int32 charCount, le_int32 scriptCode, LEUnicode *outChars, LEGlyphStorage &glyphStorage); static const FeatureMap *getFeatureMap(le_int32 &count); private: // do not instantiate KhmerReordering(); static le_int32 findSyllable(const KhmerClassTable *classTable, const LEUnicode *chars, le_int32 prev, le_int32 charCount); }; U_NAMESPACE_END #endif
11,148
https://github.com/dagpan/active-record-practice-playlister-static-generator-lab-nyc04-seng-ft-012720/blob/master/app/models/artist.rb
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, LicenseRef-scancode-public-domain
2,020
active-record-practice-playlister-static-generator-lab-nyc04-seng-ft-012720
dagpan
Ruby
Code
18
77
class Artist < ActiveRecord::Base has_many :songs has_many :genres, through: :songs def to_slug self.name.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '') end end
38,715
https://github.com/RoelKluin/igv/blob/master/src/main/java/org/broad/igv/data/ZipUtils.java
Github Open Source
Open Source
MIT
2,022
igv
RoelKluin
Java
Code
532
1,185
/* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.data; import org.broad.igv.util.FileUtils; import java.io.*; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * @author jrobinso */ public class ZipUtils { public static void zipDirectory(File dir2Zip, File outputFile) { try { //create a ZipOutputStream to zip the data to ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outputFile)); //assuming that there is a directory named inFolder (If there //isn't create one) in the same directory as the one the code //call the zipDir method zipDirRecursive(dir2Zip, dir2Zip, zos); //close the stream zos.close(); } catch (Exception e) { e.printStackTrace(); } } //here is the code for the method public static void zipDirRecursive(File zipDir, File currentDir, ZipOutputStream zos) { try { //create a new File object based on the directory we have to zip //get a listing of the directory content String[] dirList = zipDir.list(); byte[] readBuffer = new byte[2156]; int bytesIn = 0; //loop through dirList, and zip the files for (File f : currentDir.listFiles()) { if (f.isDirectory()) { //if the File object is a directory, call this //function again to add its content recursively zipDirRecursive(zipDir, f, zos); //loop again continue; } else { //if we reached here, the File object f was not a directory //create a FileInputStream on top of f FileInputStream fis = new FileInputStream(f); //create a new zipentry. Use a relative path String relativePath = FileUtils.getRelativePath(zipDir.getAbsolutePath(), f.getAbsolutePath(), System.getProperty("file.separator")); String piPath = FileUtils.getPlatformIndependentPath(relativePath); if (piPath.startsWith("./")) { piPath = piPath.substring(2); } ZipEntry anEntry = new ZipEntry(piPath); anEntry.setMethod(ZipEntry.STORED); anEntry.setCompressedSize(f.length()); anEntry.setSize(f.length()); anEntry.setCrc(getCrc(f)); zos.putNextEntry(anEntry); //now write the content of the file to the ZipOutputStream while ((bytesIn = fis.read(readBuffer)) != -1) { zos.write(readBuffer, 0, bytesIn); } //close the Stream fis.close(); } } } catch (Exception e) { e.printStackTrace(); } } private static long getCrc(File file) throws IOException { CRC32 crc = new CRC32(); crc.reset(); byte[] buffer = new byte[1024]; int bytesRead = 0; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); while ((bytesRead = bis.read(buffer)) != -1) { crc.update(buffer, 0, bytesRead); } bis.close(); return crc.getValue(); } }
43,859
https://github.com/jiongjiongwang/FirstCocos2Ddemo/blob/master/proj.ios_mac/MyLink.h
Github Open Source
Open Source
MIT
null
FirstCocos2Ddemo
jiongjiongwang
C
Code
92
532
// // MyLink.hpp // MyFirstDemo // // Created by dn210 on 16/12/21. // // #ifndef MyLink_hpp #define MyLink_hpp #include <stdio.h> #endif /* MyLink_hpp */ #include "cocos2d.h" //定义一个结构体,用于传递持续时间和音符号 struct LinkEventData { //1-音符的持续时间 float duraTime; //2-音符号 int pianoNum; //指向下一个结构体的指针 struct LinkEventData *next; }; class TempLinkOC : public cocos2d::Ref { public: float _getPlayTime; int midiIndex; //有关通知的方法 /* void Play(Ref* sender); void DTTime(Ref* sender); void PlayMIDI(Ref* sender); void DeleteEvent(Ref* sender); */ void addObserver(); //关掉所有音的方法(静态方法) static void CloseAllSound(); //外接声明一个方法,用于接收外来的播放时间和间隔时间,用于生成事件 void CreateEvent(float playTime,float dtTime); //外接一个方法,用于接收外来的播放时间和间隔时间,用于生成事件,并返回生成事件结构体 LinkEventData* CreateEventGetData(float playTime,float dtTime); //外接声明一个方法,用接收外来的事件索引来播放事件 void PlayEvent(int midiIndex); //外接一个方法,用于接收外来的事件索引来删除某个事件 void DeleteEvent(int midiIndex); };
16,229
https://github.com/infodog/pigeon40-core/blob/master/pigeon-client/src/main/java/net/xinshi/pigeon50/client/distributedclient/lockclient/IdentityKeygen.java
Github Open Source
Open Source
MIT
null
pigeon40-core
infodog
Java
Code
134
391
package net.xinshi.pigeon50.client.distributedclient.lockclient; import org.apache.commons.lang.StringUtils; import java.lang.management.ManagementFactory; import java.util.UUID; /** * Created by IntelliJ IDEA. * User: zhengxiangyang * Date: 11-11-1 * Time: 下午12:06 * To change this template use File | Settings | File Templates. */ public class IdentityKeygen { private static ThreadLocal context = new ThreadLocal(); private static ThreadLocal tickContext = new ThreadLocal(); public static String get() { String uuid = (String) context.get(); if (uuid == null) { uuid = UUID.randomUUID().toString(); String threadName = Thread.currentThread().getName(); String host = ManagementFactory.getRuntimeMXBean().getName(); uuid = threadName + "@" + host + "@" + uuid; context.set(uuid); } String enableLockTick = System.getProperty("enableLockTick"); Long tick = new Long(0); if(StringUtils.equals(enableLockTick,"true")){ tick = (Long) tickContext.get(); if(tick==null){ tick = new Long(0); tickContext.set(tick); } else{ tick = tick + 1; tickContext.set(tick); } } return uuid + "@" + tick; // return Thread.currentThread().getName(); } }
19,191
https://github.com/DrZoddiak/Nucleus/blob/master/nucleus-modules/src/main/java/io/github/nucleuspowered/nucleus/modules/vanish/listener/VanishListener.java
Github Open Source
Open Source
MIT
2,022
Nucleus
DrZoddiak
Java
Code
273
1,431
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.vanish.listener; import com.google.inject.Inject; import io.github.nucleuspowered.nucleus.modules.vanish.VanishKeys; import io.github.nucleuspowered.nucleus.modules.vanish.VanishPermissions; import io.github.nucleuspowered.nucleus.modules.vanish.config.VanishConfig; import io.github.nucleuspowered.nucleus.modules.vanish.services.VanishService; import io.github.nucleuspowered.nucleus.core.scaffold.listener.ListenerBase; import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection; import io.github.nucleuspowered.nucleus.core.services.interfaces.IMessageProviderService; import io.github.nucleuspowered.nucleus.core.services.interfaces.IPermissionService; import io.github.nucleuspowered.nucleus.core.services.interfaces.IReloadableService; import io.github.nucleuspowered.nucleus.core.services.interfaces.IStorageManager; import io.github.nucleuspowered.nucleus.core.services.interfaces.IUserPreferenceService; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.event.ClickEvent; import org.spongepowered.api.Sponge; import org.spongepowered.api.data.Keys; import org.spongepowered.api.entity.living.player.server.ServerPlayer; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.filter.Getter; import org.spongepowered.api.event.network.ServerSideConnectionEvent; import java.util.UUID; public class VanishListener implements IReloadableService.Reloadable, ListenerBase { private VanishConfig vanishConfig = new VanishConfig(); private final VanishService service; private final IPermissionService permissionService; private final IMessageProviderService messageProviderService; private final IUserPreferenceService userPreferenceService; private final IStorageManager storageManager; @Inject public VanishListener(final INucleusServiceCollection serviceCollection) { this.service = serviceCollection.getServiceUnchecked(VanishService.class); this.permissionService = serviceCollection.permissionService(); this.messageProviderService = serviceCollection.messageProvider(); this.userPreferenceService = serviceCollection.userPreferenceService(); this.storageManager = serviceCollection.storageManager(); } @Listener(order = Order.LAST) public void onAuth(final ServerSideConnectionEvent.Auth auth) { if (this.vanishConfig.isTryHidePlayers()) { final UUID uuid = auth.profile().uuid(); Sponge.server().userManager() .find(uuid) .flatMap(x -> x.get(Keys.LAST_DATE_PLAYED)) .ifPresent(y -> this.service.setLastVanishedTime(uuid, y)); } } @Listener public void onLogin(final ServerSideConnectionEvent.Join event, @Getter("player") final ServerPlayer player) { final boolean persist = this.service.isVanished(player.uniqueId()); final boolean shouldVanish = (this.permissionService.hasPermission(player, VanishPermissions.VANISH_ONLOGIN) && this.userPreferenceService.get(player.uniqueId(), VanishKeys.VANISH_ON_LOGIN).orElse(false)) || persist; if (shouldVanish) { if (!this.permissionService.hasPermission(player, VanishPermissions.VANISH_PERSIST)) { // No permission, no vanish. this.service.unvanishPlayer(player.user()); return; } else if (this.vanishConfig.isSuppressMessagesOnVanish()) { event.setMessageCancelled(true); } this.service.vanishPlayer(player.user(), true); this.messageProviderService.sendMessageTo(player, "vanish.login"); if (!persist) { // on login player.sendMessage(this.messageProviderService.getMessageFor(player, "vanish.onlogin.prefs") .clickEvent(ClickEvent.runCommand("/nuserprefs vanish-on-login false"))); } } else if (this.vanishConfig.isForceNucleusVanish()) { // unvanish this.service.unvanishPlayer(player.user()); } } @Listener public void onQuit(final ServerSideConnectionEvent.Disconnect event, @Getter("player") final ServerPlayer player) { if (player.get(Keys.VANISH).orElse(false)) { this.storageManager.getUserService().get(player.uniqueId()) .thenAccept(x -> x.ifPresent(t -> t.set(VanishKeys.VANISH_STATUS, false))); if (this.vanishConfig.isSuppressMessagesOnVanish()) { event.setAudience(Audience.empty()); } } this.service.clearLastVanishTime(player.uniqueId()); } @Override public void onReload(final INucleusServiceCollection serviceCollection) { this.vanishConfig = serviceCollection.configProvider().getModuleConfig(VanishConfig.class); } }
28,496
https://github.com/ErdemYesiltas/pixijs/blob/master/packages/sound-extras/global.d.ts
Github Open Source
Open Source
MIT
null
pixijs
ErdemYesiltas
TypeScript
Code
34
90
declare namespace GlobalMixins { // PixiJS 6.1+ supports mixin types for LoaderResource interface LoaderResource { /** Reference to Sound object created. */ sound?: import('@pixi/sound-extras').Sound; } interface IResourceMetadata { tags?: string | string[]; } }
33,431
https://github.com/MOIPA/RetailManager/blob/master/Backend/src/main/java/com/dql/retailmanager/service/impl/MemberService.java
Github Open Source
Open Source
MIT
2,021
RetailManager
MOIPA
Java
Code
179
728
package com.dql.retailmanager.service.impl; import com.dql.retailmanager.Utils.PageUtils; import com.dql.retailmanager.dao.mapper.MemberDao; import com.dql.retailmanager.entity.Member; import com.dql.retailmanager.entity.User; import com.dql.retailmanager.entity.form.SearchForm; import com.dql.retailmanager.entity.form.UpdateMemberForm; import com.dql.retailmanager.service.IMemberService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Date; import java.util.List; @Service public class MemberService implements IMemberService { @Resource MemberDao memberDao; /** * @param id * @return */ @Override public Member findMemberById(int id) { return memberDao.selectByPrimaryKey(id); } /** * @param member * @return */ @Override public int createMember(Member member) { member.setCreateTime(new Date()); return memberDao.insert(member); } /** * @param id * @return */ @Override public int deleteMemberById(int id) { return memberDao.deleteByPrimaryKey(id); } /** * @param member * @return */ @Override public int updateMember(Member member) { return memberDao.updateByPrimaryKey(member); } @Override public Object listMemberByPage(SearchForm pageRequest) { return PageUtils.getPageResult(pageRequest, getPageInfo(pageRequest)); } /** * 调用分页插件完成分页 * * @param pageRequest * @return */ @Override public PageInfo<Member> getPageInfo(SearchForm pageRequest) { int pageNum = pageRequest.getPage(); int pageSize = pageRequest.getLimit(); PageHelper.startPage(pageNum, pageSize); List<Member> memberList = memberDao.selectPage(pageRequest); return new PageInfo<Member>(memberList); } @Override public int updateMemberPass(UpdateMemberForm memberForm) { Member m = memberDao.selectByName(memberForm.getName(), memberForm.getOldpass()); if (m == null) return -2; m.setPwd(memberForm.getNewpass()); return memberDao.updateByPrimaryKey(m); } @Override public Member findMemberByName(String name) { return memberDao.findMemberByName(name); } }
49,490
https://github.com/CaptainABOfficial/bmac/blob/master/database/migrations/2018_09_30_131714_add_event_variables_to_events_table.php
Github Open Source
Open Source
MIT
2,021
bmac
CaptainABOfficial
PHP
Code
63
287
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddEventVariablesToEventsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('events', function (Blueprint $table) { $table->boolean('is_oceanic_event')->default(false)->after('endBooking'); $table->boolean('multiple_bookings_allowed')->default(true)->after('endBooking'); $table->boolean('uses_times')->default(false)->after('endBooking'); $table->boolean('import_only')->default(false)->after('endBooking'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('events', function (Blueprint $table) { $table->dropColumn(['is_oceanic_event', 'multiple_bookings_allowed', 'uses_times', 'import_only']); }); } }
1,399
https://github.com/fromlabs/sqltree_query/blob/master/web/users_schema.g.dart
Github Open Source
Open Source
BSD-3-Clause
null
sqltree_query
fromlabs
Dart
Code
326
1,288
library users_schema; import 'package:sqltree_schema/sqltree_schema_builder.dart'; final USERSDB_Schema _USERSDB_DEFAULT = createUSERSDB_Schema(""); USERS_Table get USERS => _USERSDB_DEFAULT.USERS; USERSDB_Schema createUSERSDB_Schema(String name) => registerSharedSchema(new _USERSDB_SchemaImpl(name)); abstract class USERSDB_Schema implements SqlSchema { USERS_Table get USERS; } class _USERSDB_SchemaImpl extends SqlSchemaImpl implements USERSDB_Schema { _USERSDB_SchemaImpl(String name) : super(name); _USERSDB_SchemaImpl.cloneFrom(_USERSDB_SchemaImpl target, bool freeze) : super.cloneFrom(target, freeze); @override USERS_Table get USERS => this["USERS"]; @override SqlTableImpl createTable(String name) { switch (name) { case "USERS": return new _USERS_TableImpl(this); default: throw new UnsupportedError("Table not exist $name"); } } @override _USERSDB_SchemaImpl clone({bool freeze}) => super.clone(freeze: freeze); @override _USERSDB_SchemaImpl createClone(bool freeze) => new _USERSDB_SchemaImpl.cloneFrom(this, freeze); } abstract class USERS_Table implements SqlTable { SqlColumn get ID; SqlColumn get GROUP_ID; SqlColumn get AUTHOR_ID; SqlColumn get REVIEWER_ID; SqlColumn get PUBLISHER_ID; SqlColumn get STATUS; SqlColumn get MAIN_LOCALE; SqlColumn get CATEGORY; SqlColumn get TITLE; SqlColumn get ABSTRACT; SqlColumn get ABSTRACT_IMAGE_URL; SqlColumn get BODY; SqlColumn get PUBLISHING_DATE; SqlColumn get CREATION_TIMESTAMP; USERS_Table alias(String alias); USERS_Table clone({bool freeze}); } class _USERS_TableImpl extends SqlTableImpl implements USERS_Table { static final Set<String> _pkNames = new Set.from(["ID"]); static final Set<String> _columnNames = new Set.from(["ID", "GROUP_ID", "AUTHOR_ID", "REVIEWER_ID", "PUBLISHER_ID", "STATUS", "MAIN_LOCALE", "CATEGORY", "TITLE", "ABSTRACT", "ABSTRACT_IMAGE_URL", "BODY", "PUBLISHING_DATE", "CREATION_TIMESTAMP"]); _USERS_TableImpl(SqlSchema schema) : super("USERS", schema); _USERS_TableImpl.aliased(String alias, _USERS_TableImpl target) : super.aliased(alias, target); _USERS_TableImpl.cloneFrom(_USERS_TableImpl target, bool freeze) : super.cloneFrom(target, freeze); @override SqlColumn get ID => this["ID"]; @override SqlColumn get GROUP_ID => this["GROUP_ID"]; @override SqlColumn get AUTHOR_ID => this["AUTHOR_ID"]; @override SqlColumn get REVIEWER_ID => this["REVIEWER_ID"]; @override SqlColumn get PUBLISHER_ID => this["PUBLISHER_ID"]; @override SqlColumn get STATUS => this["STATUS"]; @override SqlColumn get MAIN_LOCALE => this["MAIN_LOCALE"]; @override SqlColumn get CATEGORY => this["CATEGORY"]; @override SqlColumn get TITLE => this["TITLE"]; @override SqlColumn get ABSTRACT => this["ABSTRACT"]; @override SqlColumn get ABSTRACT_IMAGE_URL => this["ABSTRACT_IMAGE_URL"]; @override SqlColumn get BODY => this["BODY"]; @override SqlColumn get PUBLISHING_DATE => this["PUBLISHING_DATE"]; @override SqlColumn get CREATION_TIMESTAMP => this["CREATION_TIMESTAMP"]; @override Set<String> get primaryKeyNames => _pkNames; @override Set<String> get columnNames => _columnNames; @override USERS_Table alias(String alias) => super.alias(alias); @override _USERS_TableImpl clone({bool freeze}) => super.clone(freeze: freeze); @override _USERS_TableImpl createClone(bool freeze) => new _USERS_TableImpl.cloneFrom(this, freeze); @override SqlTable createTableAlias(String alias) => new _USERS_TableImpl.aliased(alias, this); }
5,299
https://github.com/UncleEricB/fossor/blob/master/fossor/checks/netiface_errors.py
Github Open Source
Open Source
BSD-2-Clause, BSD-2-Clause-Views
2,019
fossor
UncleEricB
Python
Code
346
827
# Copyright 2017 LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license. # See LICENSE in the project root for license information. import platform from datetime import datetime, timedelta from collections import namedtuple from fossor.checks.check import Check class NetIFace(Check): """NetIFace polls SARs EDEV (network error) statistics and notifies if stat > ERROR_THRESHOLD. EDEV: statistics on failures (errors) from the network devices are reported""" NIC_STATS = { # Total number of bad packets received per second 'rxerr': 0, # Total number of errors that happened per second while transmitting packets 'txerr': 0, # Number of received packets dropped per second because of a lack of space in linux buff. 'rxdrop': 0, # Number of transmitted packets dropped per second because of a lack of space in linux buffers 'txdrop': 0, # Number of carrier-errors (link) that happened per second while transmitting packets. 'txcarr': 0, } def _parse_sar(self, stdout): """Massage stdout from subprocess.Popen in the Sar namedtuple. Errors worth keeping are defined within NetIFace.NIC_STATS :param stdout: str of data received from subprocess.Popen.""" Sar = namedtuple('Sar', 'rxerr, coll, txerr, rxdrop, txdrop, txcarr') return Sar(*stdout.split()[2:8]) def run(self, variables: dict): """Check for Network Interface Errors using Sar data""" # pull in global variables or configure sane defaults for SAR time window. # sar -[se] switches only allow for a 24 hour window. This check will further shrink # the allowed window to 12 hours. minutes = int(variables.get('minutes', 60)) if minutes > 43200 or minutes < 0: minutes = 60 start_time = (datetime.now() + timedelta(minutes=-minutes)).strftime('%H:%M:%S') end_time = datetime.now().strftime('%H:%M:%S') # this check relies on data massaged via SAR and therefore Linux only. if platform.system() != 'Linux': return cmd = f'/usr/bin/sar -n EDEV -s {start_time} -e {end_time}' self.log.debug(f'executing cmd={cmd}') out, err, return_code = self.shell_call(cmd) nic_stats = out # Get just averages nic_stats = [line for line in nic_stats.splitlines() if line.startswith('Average')] if not nic_stats: self.log.debug("No nics found.") return for line in nic_stats: sar = self._parse_sar(line) result = '' nic = line.split()[1] for stat in NetIFace.NIC_STATS: val = float(getattr(sar, stat)) if val > NetIFace.NIC_STATS[stat]: result += f'stat={stat}, interface={nic} has surpassed threshold. value={val}\n' return result
19,518
https://github.com/harshsd/deepsphinx/blob/master/deepsphinx/lm.py
Github Open Source
Open Source
MIT
2,021
deepsphinx
harshsd
Python
Code
178
769
''' Language modelling for the tensorflow model''' import tensorflow as tf from deepsphinx.fst import fst_costs class LMCellWrapper(tf.contrib.rnn.RNNCell): '''This class wraps a decoding cell to add LM scores''' def __init__(self, dec_cell, fst, max_states, reuse=None): super(LMCellWrapper, self).__init__(_reuse=reuse) self.dec_cell = dec_cell self.fst = fst self._output_size = dec_cell.output_size self.max_states = max_states # LSTM state, FST states and number of FST states self._state_size = (dec_cell.state_size, tf.TensorShape((max_states)), tf.TensorShape((max_states)), tf.TensorShape((1))) @property def state_size(self): '''State size of the cell''' return self._state_size @property def output_size(self): '''Output size of the cell''' return self._output_size def __call__(self, inputs, state): '''Step once given the input and return score and next state''' cell_state, fst_states, state_probs, num_fst_states = state cell_out, cell_state = self.dec_cell(inputs, cell_state) def fst_costs_env(states, probs, num, inp): '''Python function''' return fst_costs(states, probs, num, inp, self.fst, self.max_states) func_appl = tf.py_func(fst_costs_env, [fst_states, state_probs, num_fst_states, tf.argmax(inputs, 1)], [tf.int32, tf.float32, tf.int32, tf.float32], stateful=False) next_state, next_state_probs, next_num_states, lm_scores = func_appl next_state.set_shape(fst_states.shape) next_num_states.set_shape(num_fst_states.shape) next_state_probs.set_shape(state_probs.shape) lm_scores.set_shape(cell_out.shape) fin_score = tf.nn.log_softmax( cell_out) + 0.5 * tf.nn.log_softmax(lm_scores) return fin_score, (cell_state, next_state, next_state_probs, next_num_states) def zero_state(self, batch_size, dtype): '''Zero state''' return (self.dec_cell.zero_state(batch_size, dtype), tf.zeros((batch_size, self.max_states), tf.int32), tf.zeros((batch_size, self.max_states), tf.float32), tf.ones((batch_size, 1), tf.int32))
34,797
https://github.com/Grin747/spring-basics-course-project/blob/master/src/main/java/com/yet/spring/core/beans/EventType.java
Github Open Source
Open Source
MIT
null
spring-basics-course-project
Grin747
Java
Code
11
40
package com.yet.spring.core.beans; public enum EventType { INFO, ERROR, DEBUG, WARN }
42,063
https://github.com/alucard263096/AMKRemoteClass/blob/master/Documents/AnyChat/AnyChatCoreSDK_Android_r4840/src/AnyChatQueue/src/com/bairuitech/common/CustomApplication.java
Github Open Source
Open Source
Apache-2.0
null
AMKRemoteClass
alucard263096
Java
Code
176
617
package com.bairuitech.common; import android.app.Application; public class CustomApplication extends Application{ private int mUserID; //本地用户Id private int userType; //用户类型:普通客户、座席两种 private int CurrentAreaId; //当前营业厅的Id private int CurrentQueueId; //当前队列Id private String selfUserName; //本地用户名字 private String targetUserName; //对方用户名字 private int RoomId; //进入房间号 private int TargetUserId; //对方用户Id public void onCreate() { super.onCreate(); } public void setUserID(int sUserID) { mUserID = sUserID; } public int getUserID() { return mUserID; } public int getUserType() { return userType; } public void setUserType(int userType) { this.userType = userType; } public int getCurrentAreaId() { return CurrentAreaId; } public void setCurrentAreaId(int currentAreaId) { CurrentAreaId = currentAreaId; } public int getCurrentQueueId() { return CurrentQueueId; } public void setCurrentQueueId(int currentQueueId) { CurrentQueueId = currentQueueId; } public String getSelfUserName() { return selfUserName; } public void setSelfUserName(String selfUserName) { this.selfUserName = selfUserName; } public int getRoomId() { return RoomId; } public void setRoomId(int roomId) { RoomId = roomId; } public int getTargetUserId() { return TargetUserId; } public void setTargetUserId(int targetUserId) { TargetUserId = targetUserId; } public String getTargetUserName() { return targetUserName; } public void setTargetUserName(String targetUserName) { this.targetUserName = targetUserName; } }
15,754
https://github.com/bardasoft/SharedControls/blob/master/Forms/FormSettings.cs
Github Open Source
Open Source
MIT
2,017
SharedControls
bardasoft
C#
Code
726
2,186
/* * The contents of this file are subject to MIT Licence. Please * view License.txt for further details. * * The Original Code was created by Simon Carter (s1cart3r@gmail.com) * * Copyright (c) 2012 Simon Carter * * Purpose: Shared Settings form, allows applications to dynamically add settings panel in tree * */ using System; using System.Collections.Generic; using System.Windows.Forms; using Shared; #pragma warning disable IDE1005 // Delegate invocation can be simplified #pragma warning disable IDE1006 // naming rule violation namespace SharedControls.Forms { /// <summary> /// Settings Form /// </summary> public partial class FormSettings : BaseForm, IMessageFilter { #region Private Members private const int WM_KEYDOWN = 0x100; private Dictionary<TreeNode, Setting> _settings = new Dictionary<TreeNode, Setting>(); /// <summary> /// Name of application /// </summary> private string _applicationName = "Unknown"; /// <summary> /// Helpdesk location /// </summary> private string _helpDeskLocation; #endregion Private Member #region Constructors /// <summary> /// Constructor - initialises new instance /// </summary> public FormSettings() { InitializeComponent(); } /// <summary> /// Constructor - initialises new instance /// </summary> /// <param name="applicationName">Name of application</param> /// <param name="helpDeskLocation">url for helpdesk location</param> public FormSettings(string applicationName, string helpDeskLocation) { _applicationName = applicationName; _helpDeskLocation = helpDeskLocation; InitializeComponent(); } #endregion Constructors #region Overridden Methods /// <summary> /// LanguageChanged method - called when UI culture is changed /// </summary> /// <param name="culture">Current UI culture</param> protected override void LanguageChanged(System.Globalization.CultureInfo culture) { this.Text = String.Format("{0} {1}", _applicationName, "Settings"); lblDescription.Text = "Settings"; btnCancel.Text = "Cancel"; btnSave.Text = "Save"; foreach (KeyValuePair<TreeNode, Setting> value in _settings) value.Value.SettingsPanel.LanguageChanged(culture); } /// <summary> /// Loads child settings controls /// </summary> protected override void LoadSettings() { this.Cursor = Cursors.WaitCursor; tvOptions.BeginUpdate(); try { if (tvOptions.SelectedNode != null) { Setting setting = _settings[tvOptions.SelectedNode]; UnloadSettingPanel(setting); } tvOptions.Nodes.Clear(); _settings.Clear(); TreeNode parent = null; RaiseAddSettings(new SettingsLoadArgs(parent)); tvOptions.ExpandAll(); if (tvOptions.Nodes.Count > 0) { if (tvOptions.SelectedNode == null) tvOptions.SelectedNode = tvOptions.Nodes[0]; tvOptions.Nodes[0].EnsureVisible(); } } finally { tvOptions.EndUpdate(); this.Cursor = Cursors.Arrow; } } #endregion Overridden Methods #region Properties #endregion Properties #region Public Methods /// <summary> /// Loads a new setting option to the form /// </summary> /// <param name="name">Name of setting control</param> /// <param name="description">Description of setting</param> /// <param name="parent">Parent tree node, or null if no parent</param> /// <param name="settingsPanel">Settings Panel to be shown when user selects the setting</param> /// <returns>TreeNode item which controls the settings panel</returns> public TreeNode LoadControlOption(string name, string description, TreeNode parent, BaseSettings settingsPanel) { TreeNode Result = null; if (parent == null) { Result = tvOptions.Nodes.Add(name); } else { Result = parent.Nodes.Add(name); } Setting setting = new Setting(name, description, settingsPanel); _settings.Add(Result, setting); settingsPanel.SettingsParentForm = this; settingsPanel.SettingsLoaded(); settingsPanel.TreeNode = Result; return (Result); } /// <summary> /// Forces the settings form to load all settings /// </summary> public void LoadAllSettings() { LoadSettings(); } /// <summary> /// Updates settings /// </summary> public void UpdateSettings() { } #endregion Public Methods #region Private Methods private void LoadSettingsPanel(Setting setting) { lblDescription.Text = setting.Description; if (setting.SettingsPanel != null) { setting.SettingsPanel.Parent = this; setting.SettingsPanel.Left = 206; setting.SettingsPanel.Top = 41; setting.SettingsPanel.Visible = true; setting.SettingsPanel.SettingShown(); } } private void UnloadSettingPanel(Setting setting) { if (setting.SettingsPanel != null) { setting.SettingsPanel.Visible = false; setting.SettingsPanel.Parent = null; setting.SettingsPanel.SettingHidden(); } } private void tvOptions_AfterSelect(object sender, TreeViewEventArgs e) { Setting setting = _settings[e.Node]; LoadSettingsPanel(setting); } private void tvOptions_BeforeSelect(object sender, TreeViewCancelEventArgs e) { if (tvOptions.SelectedNode != null) { Setting setting = _settings[tvOptions.SelectedNode]; UnloadSettingPanel(setting); } } private void btnSave_Click(object sender, EventArgs e) { foreach (KeyValuePair<TreeNode, Setting> setting in _settings) { if (setting.Value.SettingsPanel != null) { if (!setting.Value.SettingsPanel.SettingsConfirm()) { Setting currentSetting = _settings[tvOptions.SelectedNode]; UnloadSettingPanel(currentSetting); LoadSettingsPanel(setting.Value); return; } if (!setting.Value.SettingsPanel.SettingsSave()) { Setting currentSetting = _settings[tvOptions.SelectedNode]; UnloadSettingPanel(currentSetting); LoadSettingsPanel(setting.Value); return; } } } DialogResult = System.Windows.Forms.DialogResult.OK; } private void FormSettings_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (e.KeyCode == Keys.F1) { } } private void FormSettings_KeyPress(object sender, KeyPressEventArgs e) { } /// <summary> /// Filter for windows messages /// </summary> /// <param name="m">Message being received</param> /// <returns>always returns false, indicating that other filters should also process messages</returns> public bool PreFilterMessage(ref System.Windows.Forms.Message m) { switch (m.Msg) { case WM_KEYDOWN: switch ((int)m.WParam) { case 112: //f1 Setting setting = _settings[tvOptions.SelectedNode]; if (setting.SettingsPanel.HelpID > 0) System.Diagnostics.Process.Start(String.Format(_helpDeskLocation, setting.SettingsPanel.HelpID)); break; } break; } return (false); } private void FormSettings_Shown(object sender, EventArgs e) { SplashForm.HideSplashForm(); } #endregion Private Methods #region Event Wrappers private void RaiseAddSettings(SettingsLoadArgs args) { if (AddSettings != null) AddSettings(this, args); } #endregion Event Wrappers #region Events /// <summary> /// Event raised when calling application can add custom setting panels to the Settings Form /// </summary> public event SettingsLoadDelegate AddSettings; #endregion Events } }
50,183
https://github.com/RobertWilbrandt/c10lp_refkit_soc_demo/blob/master/soc/segment_display.py
Github Open Source
Open Source
BSD-3-Clause
null
c10lp_refkit_soc_demo
RobertWilbrandt
Python
Code
132
461
"""Submodule for controlling the 7-Segment display""" from litex.soc.interconnect.csr import AutoCSR, CSRStorage from migen import Array, If, Module, Signal class SegmentDisplay(Module, AutoCSR): def __init__(self, an_pads, c_pads, sys_clk_freq, rate): self._d = CSRStorage(3, description="Dot segments") self._s0 = CSRStorage(8, description="Segments of first digit") self._s1 = CSRStorage(8, description="Segments of second digit") self._s2 = CSRStorage(8, description="Segments of third digit") self._s3 = CSRStorage(8, description="Segments of fourth digit") # Counter resets at specified rate cnt_steps = int(sys_clk_freq / rate) scan_cnt = Signal(max=cnt_steps) self.sync += If(scan_cnt == 0, scan_cnt.eq(cnt_steps - 1)).Else( scan_cnt.eq(scan_cnt - 1) ) # Rotate through digits scan_sel = Signal(max=5) self.sync += If( scan_cnt == 1, If(scan_sel == 0, scan_sel.eq(4)).Else(scan_sel.eq(scan_sel - 1)), ) self.comb += an_pads.eq(~(1 << scan_sel)) # Assign segments by selecting correct register digits = Array( [ self._d.storage, self._s0.storage, self._s1.storage, self._s2.storage, self._s3.storage, ] ) self.comb += c_pads.eq(~digits[scan_sel])
38,453
https://github.com/alice-larp/alice-larp-sdk-deprecated/blob/master/packages/alice-worker-manager/test/model_helpers.ts
Github Open Source
Open Source
Apache-2.0
null
alice-larp-sdk-deprecated
alice-larp
TypeScript
Code
298
883
import { Event } from 'alice-model-engine-api'; import { merge } from 'lodash'; import Container from 'typedi'; import { Document } from '../src/db/interface'; import { dbName } from '../src/db_init/util'; import { ConfigToken, DBConnectorToken } from '../src/di_tokens'; import { delay } from '../src/utils'; function testDbName(alias: string): string { return dbName(Container.get(ConfigToken), alias); } export function createModelObj(id?: string, fields?: any) { if (!fields) { fields = { value: '' }; } if (!id) { id = Math.floor(Math.random() * 10000).toString().padStart(4, '0'); } const model = merge({ _id: id, timestamp: Date.now(), }, fields); return model; } export function saveModel(model: any) { const modelsDb = Container.get(DBConnectorToken).use(testDbName('models')); return modelsDb.put(model); } export async function createModel(id?: string, fields?: any): Promise<Document> { const model = createModelObj(id, fields); await saveModel(model); return model; } export function getModel(id: string, dbAlias: string = 'models') { const modelsDb = Container.get(DBConnectorToken).use(testDbName(dbAlias)); return modelsDb.getOrNull(id); } // Waits until model with given timestamp will be generated export async function getModelAtTimestamp(id: string, timestamp: number, dbAlias: string = 'models') { while (true) { const model = await getModel(id, dbAlias); if (model && 'timestamp' in model && model.timestamp == timestamp) return model; await delay(10); } } export function getModelVariants(id: string, aliases: string[] = ['models', 'workingModels', 'defaultViewModels']) { const pending = aliases.map((alias) => getModel(id, alias)); return Promise.all(pending); } export function getModelVariantsAtTimestamp(id: string, timestamp: number, aliases: string[] = ['models', 'workingModels', 'defaultViewModels']) { const pending = aliases.map((alias) => getModelAtTimestamp(id, timestamp, alias)); return Promise.all(pending); } export function pushEvent(event: Event) { const eventsDb = Container.get(DBConnectorToken).use(testDbName('events')); return eventsDb.put(event); } export async function pushRefreshEvent(characterId: string, timestamp: number) { const metadataDb = Container.get(ConfigToken).db.metadata; const metadata: any = await Container.get(DBConnectorToken).use(metadataDb).getOrNull(characterId) || { _id: characterId }; metadata.scheduledUpdateTimestamp = timestamp; await Container.get(DBConnectorToken).use(metadataDb).put(metadata); } export function saveObject(dbAlias: string, doc: any) { const db = Container.get(DBConnectorToken).use(testDbName(dbAlias)); return db.put(doc); } export function getObject(dbAlias: string, id: string) { const db = Container.get(DBConnectorToken).use(testDbName(dbAlias)); return db.getOrNull(id); }
3,390
https://github.com/denismitr/laravel-permissions/blob/master/src/Loader.php
Github Open Source
Open Source
MIT
2,019
laravel-permissions
denismitr
PHP
Code
124
440
<?php namespace Denismitr\Permissions; use Denismitr\Permissions\Exceptions\PermissionDoesNotExist; use Denismitr\Permissions\Models\Permission; use Illuminate\Contracts\Auth\Access\Authorizable; use Illuminate\Contracts\Auth\Access\Gate; use Illuminate\Contracts\Cache\Repository; use Illuminate\Support\Collection; class Loader { /** @var Gate */ protected $gate; /** @var Repository */ protected $cache; /** * @var string */ protected $cacheKey = 'denismitr.permissions.cache'; /** * Loader constructor. * @param Gate $gate * @param Repository $cache */ public function __construct(Gate $gate, Repository $cache) { $this->gate = $gate; $this->cache = $cache; } public function registerPermissions(): bool { $this->gate->before(function (Authorizable $user, string $ability) { try { if (method_exists($user, 'hasPermissionTo')) { return $user->hasPermissionTo($ability) ?: null; } } catch (PermissionDoesNotExist $e) {} }); return true; } public function forgetCachedPermissions() { $this->cache->forget($this->cacheKey); } /** * @return Collection */ public function getPermissions(): Collection { return $this->cache->remember($this->cacheKey, config('permissions.cache_expiration_time'), function () { return app(Permission::class)->with('groups')->get(); }); } }
29,250