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/fomenkoyegor/rgarage/blob/master/resources/js/components/Task.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
rgarage
|
fomenkoyegor
|
Vue
|
Code
| 442
| 2,123
|
<template>
<div class="col-12 task bg-white" :class="{'complite':task.status}" style="width: 100%">
<div>
<div class="title row align-content-center">
<div class="col-1 row justify-content-center align-content-center">
<input type="checkbox" :checked="task.status" @change="onComplite">
</div>
<div class="col-9 task__name">
{{task.name}}
</div>
<div class="col-2 controls row justify-content-around">
<button class="del btn btn-sm"
>
<!-- {{task.priority}}-->
{{index+1}}
</button>
<button class="edit btn btn-sm"
data-toggle="modal" :data-target="'#updateModal'+task.id"
>
<i class="fa fa-pencil" aria-hidden="true"></i>
</button>
<button class="del btn btn-sm"
data-toggle="modal" :data-target="'#deleteTaskModal'+task.id"
>
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button>
<button class="showdate btn btn-dark btn-sm"
v-if="task.date"
data-toggle="tooltip" data-placement="top" :title="task.date"
>
<i class="fa fa-exclamation-circle" aria-hidden="true"></i>
</button>
</div>
</div>
<div class="modal fade" :id="'deleteTaskModal'+task.id" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">{{task.created_at.toString()}}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
DELETE <strong>{{task.name}}</strong> ?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button
type="button"
class="btn btn-danger"
@click="onDeleteTask"
>
delete
</button>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" :id="'updateModal'+task.id" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel2"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel2">update task</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div>
<div class="form-group">
<label for="name">
name: <strong>{{task.name}}</strong>
</label>
<input
type="text"
class="form-control"
id="name"
placeholder="Enter name "
v-model.trim="$v.name.$model"
:class="{
'is-invalid':$v.name.$error,
'is-valid':!$v.name.$invalid
}"
>
<div class="valid-feedback">nameis valid</div>
<div class="invalid-feedback">
<span v-if="!$v.name.required">name is required</span>
<span v-if="!$v.name.minLength">
name is min length
{{$v.name.$params.minLength.min}}
</span>
<span v-if="!$v.name.maxLength">
name must have at
{{$v.name.$params.maxLength.max}}
</span>
</div>
</div>
</div>
<div class="form-group">
<label for="date">
deadline <strong>{{task.date}}</strong>
</label>
<input type="date"
v-model="date"
id="date"
class="form-control"
>
</div>
<input :disabled="$v.$invalid" @click="save" type="submit" class="btn btn-primary">
<button class="btn btn-secondary " @click="onCancel">cancel</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import {required, maxLength, minLength} from 'vuelidate/lib/validators';
export default {
data: () => ({
name: '',
date: ''
}),
validations: {
name: {
required,
minLength: minLength(3),
maxLength: maxLength(255),
},
},
mounted(){
this.name = this.task.name;
this.date = this.task.date;
},
props: {
task: {
id: Number,
name: String,
status: Boolean,
priority: Number,
date: Date,
created_at: Date
},
index:Number
},
methods: {
save() {
this.update({
...this.task,
name:this.name,
date:this.date
})
},
modalDeleteToggle() {
$('#deleteTaskModal' + this.task.id).modal('toggle');
},
onCancel(){
this.name = this.task.name;
this.date = this.task.date;
this.modalUpdateToggle();
},
modalUpdateToggle() {
$('#updateModal' + this.task.id).modal('hide');
},
onDeleteTask() {
axios.delete('/tasks/' + this.task.id)
.then(res => {
if (res.data) {
this.$emit('delete', res.data);
this.modalDeleteToggle();
}
})
.catch(err => {
console.log(err);
console.log(err.response.data.errors);
if (err.response.data.errors.name) {
console.log(err.response.data.errors.name);
}
})
},
onComplite() {
this.update({...this.task, status: !this.task.status})
},
update(task) {
axios.patch('/tasks/' + task.id, task)
.then(res => {
if (res.data) {
console.log(res.data);
this.modalUpdateToggle();
this.$emit('update', res.data);
}
})
.catch(err => {
console.log(err);
console.log(err.response.data.errors);
if (err.response.data.errors.name) {
console.log(err.response.data.errors.name);
}
})
}
}
}
</script>
<style lang="scss">
.task {
border-bottom: 1px solid;
padding: 0.4em;
width: 100%;
&:last-of-type {
border: none;
padding-bottom: 1em;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
overflow: hidden;
}
}
.task.complite {
background-color: lightblue !important;
}
.task.complite .task__name {
text-decoration: line-through;
}
</style>
| 15,606
|
https://github.com/yy406961/vue-typescript-test/blob/master/src/components/Table/pagination.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
vue-typescript-test
|
yy406961
|
Vue
|
Code
| 80
| 306
|
<template>
<div :class="pagerStyles.pagination">
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page.sync="option.currentPage"
:page-sizes="option.pageSizes"
:page-size.sync="option.pageSize"
:layout="layoutTest || option.layout"
:total="option.total"
>
</el-pagination>
</div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator'
@Component
export default class pagination extends Vue {
@Prop() private option!: any
private currentPage: number = 1
private layoutTest: string = 'total, prev, pager, next, jumper'
private layout: string = 'total, sizes, prev, pager, next, jumper'
handleSizeChange(val: any) {
this.$emit('handleSizeChange', val)
}
handleCurrentChange(val: any) {
this.$emit('handleCurrentChange', val)
}
}
</script>
<style module="pagerStyles"></style>
| 49,747
|
https://github.com/apple/swift/blob/master/test/SILOptimizer/zeroInitializer.swift
|
Github Open Source
|
Open Source
|
Apache-2.0, Swift-exception
| 2,023
|
swift
|
apple
|
Swift
|
Code
| 128
| 426
|
// RUN: %target-swift-frontend -O -parse-stdlib -emit-ir -module-name ZeroInit -verify %s | %FileCheck %s
// REQUIRES: swift_in_compiler
import Swift
@frozen
public struct TestInt {
@usableFromInline
var _value : Builtin.Int32
@_transparent
public init() {
_value = Builtin.zeroInitializer()
}
}
@frozen
public struct TestFloat {
@usableFromInline
var _value : Builtin.FPIEEE32
@_transparent
public init() {
_value = Builtin.zeroInitializer()
}
}
@frozen
public struct TestVector {
@usableFromInline
var _value : Builtin.Vec4xFPIEEE32
@_transparent
public init() {
_value = Builtin.zeroInitializer()
}
}
public struct Foo {
public static var x : TestInt = TestInt()
public static var y : TestFloat = TestFloat()
public static var z : TestVector = TestVector()
}
// CHECK: @"$s8ZeroInit3FooV1xAA7TestIntVvpZ" ={{.*}} global %T8ZeroInit7TestIntV zeroinitializer
// CHECK: @"$s8ZeroInit3FooV1yAA9TestFloatVvpZ" ={{.*}} global %T8ZeroInit9TestFloatV zeroinitializer
// CHECK: @"$s8ZeroInit3FooV1zAA10TestVectorVvpZ" ={{.*}} global %T8ZeroInit10TestVectorV zeroinitializer
// CHECK-NOT: swift_once
| 18,832
|
https://github.com/inthiyazbasha9876/obs_v2/blob/master/zuul-auth-ojas-parent/ojas-obs-interview-mode/src/main/java/com/ojas/obs/interviewmode/repository/InterviewModeRepository.java
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
obs_v2
|
inthiyazbasha9876
|
Java
|
Code
| 17
| 88
|
package com.ojas.obs.interviewmode.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.ojas.obs.interviewmode.model.InterviewMode;
@Repository
public interface InterviewModeRepository extends JpaRepository<InterviewMode, Integer> {
}
| 5,243
|
https://github.com/schoetty/pageflow/blob/master/app/assets/javascripts/pageflow/page_transitions.js
|
Github Open Source
|
Open Source
|
MIT
| null |
pageflow
|
schoetty
|
JavaScript
|
Code
| 60
| 250
|
pageflow.pageTransitions = {
repository: {},
register: function(name, options) {
this.repository[name] = options;
},
get: function(name) {
if (!this.repository.hasOwnProperty(name)) {
throw 'Unknown page transition "' + name + '"';
}
return this.repository[name];
},
names: function() {
return _.keys(this.repository);
}
};
pageflow.pageTransitions.register('fade', {duration: 1100});
pageflow.pageTransitions.register('crossfade', {duration: 1100});
pageflow.pageTransitions.register('fade_to_black', {duration: 2100});
pageflow.pageTransitions.register('cut', {duration: 1100});
pageflow.pageTransitions.register('scroll', {duration: 1100});
pageflow.pageTransitions.register('scroll_right', {duration: 1100});
pageflow.pageTransitions.register('scroll_left', {duration: 1100});
| 31,941
|
https://github.com/moinnn/laravel-dbsim/blob/master/static/dbsim.js
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
laravel-dbsim
|
moinnn
|
JavaScript
|
Code
| 48
| 227
|
var doSubmit = function() {
$.ajax({
url: './',
dataType: 'json',
type: 'POST',
data: { q: $('#q').val() }
}).done(function(data) {
data.query = $('<div />').text(data.query).html();
data.query = hljs.highlightAuto(data.query).value;
$('#query_target').html(data.query);
$('#binding_target').text(JSON.stringify(data.bindings));
}).fail(function(jqXHR) {
$('#query_target').html(jqXHR.responseText).wrapInner('<span class="error" />');
});
};
var timeout;
$('#q').focus()
.elastic()
.on('keydown', function() {
clearTimeout(timeout);
timeout = setTimeout(doSubmit, 1000);
});
| 41,176
|
https://github.com/sol/doctest/blob/master/test/PropertySpec.hs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
doctest
|
sol
|
Haskell
|
Code
| 750
| 1,544
|
{-# LANGUAGE OverloadedStrings #-}
module PropertySpec (main, spec) where
import Test.Hspec
import Data.String.Builder
import Property
import Interpreter (withInterpreter)
main :: IO ()
main = hspec spec
isFailure :: PropertyResult -> Bool
isFailure (Failure _) = True
isFailure _ = False
spec :: Spec
spec = do
describe "runProperty" $ do
it "reports a failing property" $ withInterpreter [] $ \repl -> do
runProperty repl "False" `shouldReturn` Failure "*** Failed! Falsified (after 1 test):"
it "runs a Bool property" $ withInterpreter [] $ \repl -> do
runProperty repl "True" `shouldReturn` Success
it "runs a Bool property with an explicit type signature" $ withInterpreter [] $ \repl -> do
runProperty repl "True :: Bool" `shouldReturn` Success
it "runs an implicitly quantified property" $ withInterpreter [] $ \repl -> do
runProperty repl "(reverse . reverse) xs == (xs :: [Int])" `shouldReturn` Success
it "runs an implicitly quantified property even with GHC 7.4" $
-- ghc will include a suggestion (did you mean `id` instead of `is`) in
-- the error message
withInterpreter [] $ \repl -> do
runProperty repl "foldr (+) 0 is == sum (is :: [Int])" `shouldReturn` Success
it "runs an explicitly quantified property" $ withInterpreter [] $ \repl -> do
runProperty repl "\\xs -> (reverse . reverse) xs == (xs :: [Int])" `shouldReturn` Success
it "allows to mix implicit and explicit quantification" $ withInterpreter [] $ \repl -> do
runProperty repl "\\x -> x + y == y + x" `shouldReturn` Success
it "reports the value for which a property fails" $ withInterpreter [] $ \repl -> do
runProperty repl "x == 23" `shouldReturn` Failure "*** Failed! Falsified (after 1 test):\n0"
it "reports the values for which a property that takes multiple arguments fails" $ withInterpreter [] $ \repl -> do
let vals x = case x of (Failure r) -> tail (lines r); _ -> error "Property did not fail!"
vals `fmap` runProperty repl "x == True && y == 10 && z == \"foo\"" `shouldReturn` ["False", "0", show ("" :: String)]
it "defaults ambiguous type variables to Integer" $ withInterpreter [] $ \repl -> do
runProperty repl "reverse xs == xs" >>= (`shouldSatisfy` isFailure)
describe "freeVariables" $ do
it "finds a free variables in a term" $ withInterpreter [] $ \repl -> do
freeVariables repl "x" `shouldReturn` ["x"]
it "ignores duplicates" $ withInterpreter [] $ \repl -> do
freeVariables repl "x == x" `shouldReturn` ["x"]
it "works for terms with multiple names" $ withInterpreter [] $ \repl -> do
freeVariables repl "\\z -> x + y + z == foo 23" `shouldReturn` ["x", "y", "foo"]
it "works for names that contain a prime" $ withInterpreter [] $ \repl -> do
freeVariables repl "x' == y''" `shouldReturn` ["x'", "y''"]
it "works for names that are similar to other names that are in scope" $ withInterpreter [] $ \repl -> do
freeVariables repl "length_" `shouldReturn` ["length_"]
describe "parseNotInScope" $ do
context "when error message was produced by GHC 7.4.1" $ do
it "extracts a variable name of variable that is not in scope from an error message" $ do
parseNotInScope . build $ do
"<interactive>:4:1: Not in scope: `x'"
`shouldBe` ["x"]
it "ignores duplicates" $ do
parseNotInScope . build $ do
"<interactive>:4:1: Not in scope: `x'"
""
"<interactive>:4:6: Not in scope: `x'"
`shouldBe` ["x"]
it "works for variable names that contain a prime" $ do
parseNotInScope . build $ do
"<interactive>:2:1: Not in scope: x'"
""
"<interactive>:2:7: Not in scope: y'"
`shouldBe` ["x'", "y'"]
it "works for error messages with suggestions" $ do
parseNotInScope . build $ do
"<interactive>:1:1:"
" Not in scope: `is'"
" Perhaps you meant `id' (imported from Prelude)"
`shouldBe` ["is"]
context "when error message was produced by GHC 8.0.1" $ do
it "extracts a variable name of variable that is not in scope from an error message" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error: Variable not in scope: x"
`shouldBe` ["x"]
it "ignores duplicates" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error: Variable not in scope: x :: ()"
""
"<interactive>:1:6: error: Variable not in scope: x :: ()"
`shouldBe` ["x"]
it "works for variable names that contain a prime" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error: Variable not in scope: x' :: ()"
""
"<interactive>:1:7: error: Variable not in scope: y'' :: ()"
`shouldBe` ["x'", "y''"]
it "works for error messages with suggestions" $ do
parseNotInScope . build $ do
"<interactive>:1:1: error:"
" • Variable not in scope: length_"
" • Perhaps you meant ‘length’ (imported from Prelude)"
`shouldBe` ["length_"]
| 15,562
|
https://github.com/Weird-Street/spectrum/blob/master/mercury/queues/processReputationEvent.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
spectrum
|
Weird-Street
|
JavaScript
|
Code
| 203
| 759
|
// flow
const debug = require('debug')('mercury:queue:process-reputation-event');
import processThreadCreated from '../functions/processThreadCreated';
import processThreadDeleted from '../functions/processThreadDeleted';
import processMessageCreated from '../functions/processMessageCreated';
import processReactionCreated from '../functions/processReactionCreated';
import processReactionDeleted from '../functions/processReactionDeleted';
import processThreadReactionCreated from '../functions/processThreadReactionCreated';
import processThreadReactionDeleted from '../functions/processThreadReactionDeleted';
import processMessageDeleted from '../functions/processMessageDeleted';
import processThreadDeletedByModeration from '../functions/processThreadDeletedByModeration';
import {
THREAD_CREATED,
THREAD_DELETED,
THREAD_DELETED_BY_MODERATION,
MESSAGE_CREATED,
MESSAGE_DELETED,
REACTION_CREATED,
REACTION_DELETED,
THREAD_REACTION_CREATED,
THREAD_REACTION_DELETED,
} from '../constants';
import type { Job, ReputationEventJobData } from 'shared/bull/types';
export default async (job: Job<ReputationEventJobData>) => {
const { type, userId, entityId } = job.data;
debug(`\nnew job: ${job.id}`);
debug(`\nprocessing reputation type: ${type}`);
debug(`\nprocessing reputation entityId: ${entityId}`);
// if the event came in with bad data, escape
if (!type || !userId || !entityId) return Promise.resolve();
// parse event types
try {
switch (type) {
case THREAD_CREATED: {
return await processThreadCreated(job.data);
}
case THREAD_DELETED: {
return await processThreadDeleted(job.data);
}
case THREAD_DELETED_BY_MODERATION: {
return await processThreadDeletedByModeration(job.data);
}
case MESSAGE_CREATED: {
return await processMessageCreated(job.data);
}
case REACTION_CREATED: {
return await processReactionCreated(job.data);
}
case REACTION_DELETED: {
return await processReactionDeleted(job.data);
}
case THREAD_REACTION_CREATED: {
return await processThreadReactionCreated(job.data);
}
case THREAD_REACTION_DELETED: {
return await processThreadReactionDeleted(job.data);
}
case MESSAGE_DELETED: {
return await processMessageDeleted(job.data);
}
default: {
debug('❌ No reputation event type matched');
return Promise.resolve();
}
}
} catch (err) {
console.error('❌ Error in job:\n');
console.error(err);
}
};
| 24,501
|
https://github.com/Chronostasys/LimFx.Common/blob/master/src/LimFx.Common/Services/LimFxRateLimitAttribute.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
LimFx.Common
|
Chronostasys
|
C#
|
Code
| 155
| 591
|
using AbotEsge.Util;
using LimFx.Business.Exceptions;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Timers;
namespace LimFx.Business.Services
{
public class LimFxRateLimitAttribute : ActionFilterAttribute, IDisposable
{
static BloomFilter<IPAddress> blackList = new BloomFilter<IPAddress>(20000, 0.001f);
static ConcurrentDictionary<string, int> requesterInfos = new ConcurrentDictionary<string, int>();
static Timer resettimer;
static Timer unBlocTimer;
private readonly int _value;
public LimFxRateLimitAttribute(int rate)
{
_value = rate;
}
static void ResetRequests(object sender, ElapsedEventArgs e)
{
requesterInfos.Clear();
}
static void ResetBlackList(object sender, ElapsedEventArgs e)
{
blackList.Clear();
}
public static void Init(double resetMs = 1000, double blockTimeMs = 1000)
{
resettimer?.Dispose();
unBlocTimer?.Dispose();
requesterInfos.Clear();
blackList.Clear();
unBlocTimer = new Timer(blockTimeMs);
unBlocTimer.Elapsed += ResetBlackList;
resettimer = new Timer(resetMs);
resettimer.Elapsed += ResetRequests;
resettimer.Start();
unBlocTimer.Start();
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var ip = context.HttpContext.Connection.RemoteIpAddress;
var key = ip.ToString() + context.HttpContext.Request.Path.ToString();
if (!requesterInfos.TryAdd(key, 0))
{
requesterInfos[key]++;
if (requesterInfos[key] >= _value)
{
blackList.Add(ip);
}
}
if (blackList.Contains(ip))
{
throw new _429Exception();
}
base.OnActionExecuting(context);
}
public void Dispose()
{
resettimer?.Dispose();
unBlocTimer?.Dispose();
}
}
}
| 45,470
|
https://github.com/MiniProfiler/dotnet/blob/master/src/MiniProfiler.Shared/Storage/DatabaseStorageBase.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
dotnet
|
MiniProfiler
|
C#
|
Code
| 1,160
| 3,114
|
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
namespace StackExchange.Profiling.Storage
{
/// <summary>
/// Understands how to save MiniProfiler results to a MSSQL database, allowing more permanent storage and querying of slow results.
/// </summary>
public abstract class DatabaseStorageBase : IAsyncStorage, IDatabaseStorageConnectable
{
/// <summary>
/// The table <see cref="MiniProfiler"/>s are stored in.
/// </summary>
public readonly string MiniProfilersTable = "MiniProfilers";
/// <summary>
/// The table <see cref="Timing"/>s are stored in.
/// </summary>
public readonly string MiniProfilerTimingsTable = "MiniProfilerTimings";
/// <summary>
/// The table <see cref="ClientTiming"/>s are stored in.
/// </summary>
public readonly string MiniProfilerClientTimingsTable = "MiniProfilerClientTimings";
/// <summary>
/// Gets or sets how we connect to the database used to save/load MiniProfiler results.
/// </summary>
protected string ConnectionString { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseStorageBase"/> class.
/// Returns a new <c>SqlServerDatabaseStorage</c> object that will insert into the database identified by connectionString.
/// </summary>
/// <param name="connectionString">The connection String</param>
protected DatabaseStorageBase(string connectionString)
{
ConnectionString = connectionString;
}
/// <summary>
/// Initializes a new instance of the <see cref="DatabaseStorageBase"/> class.
/// Returns a new <c>SqlServerDatabaseStorage</c> object that will insert into the database identified by connectionString.
/// </summary>
/// <param name="connectionString">The connection String</param>
/// <param name="profilersTable">The table name to use for MiniProfilers.</param>
/// <param name="timingsTable">The table name to use for MiniProfiler Timings.</param>
/// <param name="clientTimingsTable">The table name to use for MiniProfiler Client Timings.</param>
protected DatabaseStorageBase(string connectionString, string profilersTable, string timingsTable, string clientTimingsTable)
{
ConnectionString = connectionString;
MiniProfilersTable = profilersTable;
MiniProfilerTimingsTable = timingsTable;
MiniProfilerClientTimingsTable = clientTimingsTable;
}
/// <summary>
/// Returns a connection to the data store.
/// </summary>
protected abstract DbConnection GetConnection();
/// <summary>
/// Saves 'profiler' to a database under its <see cref="MiniProfiler.Id"/>.
/// </summary>
/// <param name="profiler">The <see cref="MiniProfiler"/> to save.</param>
public abstract void Save(MiniProfiler profiler);
/// <summary>
/// Asynchronously saves 'profiler' to a database under its <see cref="MiniProfiler.Id"/>.
/// </summary>
/// <param name="profiler">The <see cref="MiniProfiler"/> to save.</param>
public abstract Task SaveAsync(MiniProfiler profiler);
/// <summary>
/// Returns the MiniProfiler identified by 'id' from the database or null when no MiniProfiler exists under that 'id'.
/// </summary>
/// <param name="id">The profiler ID to load.</param>
/// <returns>The loaded <see cref="MiniProfiler"/>.</returns>
public abstract MiniProfiler? Load(Guid id);
/// <summary>
/// Asynchronously returns the MiniProfiler identified by 'id' from the database or null when no MiniProfiler exists under that 'id'.
/// </summary>
/// <param name="id">The profiler ID to load.</param>
/// <returns>The loaded <see cref="MiniProfiler"/>.</returns>
public abstract Task<MiniProfiler?> LoadAsync(Guid id);
/// <summary>
/// Whether this storage provider should call SetUnviewed methods (separately) after saving.
/// </summary>
public virtual bool SetUnviewedAfterSave => false;
/// <summary>
/// Sets a particular profiler session so it is considered "unviewed".
/// </summary>
/// <param name="user">The user to set this profiler ID as unviewed for.</param>
/// <param name="id">The profiler ID to set unviewed.</param>
public abstract void SetUnviewed(string? user, Guid id);
/// <summary>
/// Asynchronously sets a particular profiler session so it is considered "unviewed".
/// </summary>
/// <param name="user">The user to set this profiler ID as unviewed for.</param>
/// <param name="id">The profiler ID to set unviewed.</param>
public abstract Task SetUnviewedAsync(string? user, Guid id);
/// <summary>
/// Sets a particular profiler session to "viewed".
/// </summary>
/// <param name="user">The user to set this profiler ID as viewed for.</param>
/// <param name="id">The profiler ID to set viewed.</param>
public abstract void SetViewed(string? user, Guid id);
/// <summary>
/// Asynchronously sets a particular profiler session to "viewed".
/// </summary>
/// <param name="user">The user to set this profiler ID as viewed for.</param>
/// <param name="id">The profiler ID to set viewed.</param>
public abstract Task SetViewedAsync(string? user, Guid id);
/// <summary>
/// Returns a list of <see cref="MiniProfiler.Id"/>s that haven't been seen by <paramref name="user"/>.
/// </summary>
/// <param name="user">User identified by the current <c>MiniProfilerOptions.UserProvider</c>.</param>
/// <returns>The list of keys for the supplied user</returns>
public abstract List<Guid> GetUnviewedIds(string? user);
/// <summary>
/// Asynchronously returns a list of <see cref="MiniProfiler.Id"/>s that haven't been seen by <paramref name="user"/>.
/// </summary>
/// <param name="user">User identified by the current <c>MiniProfilerOptions.UserProvider</c>.</param>
/// <returns>The list of keys for the supplied user</returns>
public abstract Task<List<Guid>> GetUnviewedIdsAsync(string? user);
/// <summary>
/// Returns the MiniProfiler Ids for the given search criteria.
/// </summary>
/// <param name="maxResults">The max number of results.</param>
/// <param name="start">Search window start.</param>
/// <param name="finish">Search window end.</param>
/// <param name="orderBy">Result order.</param>
/// <returns>The list of GUID keys.</returns>
public abstract IEnumerable<Guid> List(int maxResults, DateTime? start = null, DateTime? finish = null, ListResultsOrder orderBy = ListResultsOrder.Descending);
/// <summary>
/// Asynchronously returns the MiniProfiler Ids for the given search criteria.
/// </summary>
/// <param name="maxResults">The max number of results.</param>
/// <param name="start">Search window start.</param>
/// <param name="finish">Search window end.</param>
/// <param name="orderBy">Result order.</param>
/// <returns>The list of GUID keys.</returns>
public abstract Task<IEnumerable<Guid>> ListAsync(int maxResults, DateTime? start = null, DateTime? finish = null, ListResultsOrder orderBy = ListResultsOrder.Descending);
/// <summary>
/// Connects timings from the database, shared here for use in multiple providers.
/// </summary>
/// <param name="profiler">The profiler to connect the timing tree to.</param>
/// <param name="timings">The raw list of Timings to construct the tree from.</param>
/// <param name="clientTimings">The client timings to connect to the profiler.</param>
protected void ConnectTimings(MiniProfiler profiler, List<Timing> timings, List<ClientTiming> clientTimings)
{
if (profiler?.RootTimingId.HasValue == true && timings.Count > 0)
{
var rootTiming = timings.SingleOrDefault(x => x.Id == profiler.RootTimingId.Value);
if (rootTiming != null)
{
profiler.Root = rootTiming;
foreach (var timing in timings)
{
timing.Profiler = profiler;
}
timings.Remove(rootTiming);
var timingsLookupByParent = timings.ToLookup(x => (Guid)x.ParentTimingId!, x => x);
PopulateChildTimings(rootTiming, timingsLookupByParent);
}
if (clientTimings.Count > 0 || profiler.ClientTimingsRedirectCount.HasValue)
{
profiler.ClientTimings = new ClientTimings
{
RedirectCount = profiler.ClientTimingsRedirectCount ?? 0,
Timings = clientTimings
};
}
}
}
/// <summary>
/// Build the subtree of <see cref="Timing"/> objects with <paramref name="parent"/> at the top.
/// Used recursively.
/// </summary>
/// <param name="parent">Parent <see cref="Timing"/> to be evaluated.</param>
/// <param name="timingsLookupByParent">Key: parent timing Id; Value: collection of all <see cref="Timing"/> objects under the given parent.</param>
private void PopulateChildTimings(Timing parent, ILookup<Guid, Timing> timingsLookupByParent)
{
if (timingsLookupByParent.Contains(parent.Id))
{
foreach (var timing in timingsLookupByParent[parent.Id].OrderBy(x => x.StartMilliseconds))
{
parent.AddChild(timing);
PopulateChildTimings(timing, timingsLookupByParent);
}
}
}
/// <summary>
/// Flattens the timings down into a single list.
/// </summary>
/// <param name="timing">The <see cref="Timing"/> to flatten into <paramref name="timingsCollection"/>.</param>
/// <param name="timingsCollection">The collection to add all timings in the <paramref name="timing"/> tree to.</param>
protected void FlattenTimings(Timing timing, List<Timing> timingsCollection)
{
timingsCollection.Add(timing);
if (timing.HasChildren)
{
foreach (var child in timing.Children)
{
FlattenTimings(child, timingsCollection);
}
}
}
private List<string>? _tableCreationScripts;
/// <summary>
/// The table creation scripts for this database storage.
/// Generated by the <see cref="GetTableCreationScripts"/> implemented by the provider.
/// </summary>
public List<string> TableCreationScripts => _tableCreationScripts ??= GetTableCreationScripts().ToList();
/// <summary>
/// Creates needed tables. Run this once on your database.
/// </summary>
/// <remarks>
/// Works in SQL server and <c>sqlite</c> (with documented removals).
/// </remarks>
protected abstract IEnumerable<string> GetTableCreationScripts();
DbConnection IDatabaseStorageConnectable.GetConnection() => GetConnection();
}
/// <summary>
/// Interface for accessing the <see cref="DatabaseStorageBase"/>'s connection, for testing.
/// </summary>
public interface IDatabaseStorageConnectable
{
/// <summary>
/// Gets the connection for a <see cref="IDatabaseStorageConnectable"/> for testing.
/// </summary>
/// <returns>The connection for this storage.</returns>
DbConnection GetConnection();
}
}
| 48,847
|
https://github.com/rmjohn08/angular2-learning/blob/master/app/register/register-taker.component.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
angular2-learning
|
rmjohn08
|
TypeScript
|
Code
| 97
| 426
|
import {Component, Output, EventEmitter, OnInit} from 'angular2/core';
import {Router} from 'angular2/router';
import {UserService, RegisteredUser} from '../services/user.service';
import {FORM_DIRECTIVES, NgForm} from 'angular2/common';
@Component({
selector:'register-taker',
directives: [FORM_DIRECTIVES],
templateUrl: 'app/register/register-taker.html'
})
export class RegisterTakerComponent implements OnInit {
subscription: any;
regUser: RegisteredUser;
registrationComplete: boolean = false;
@Output() onRegistered = new EventEmitter<string>();
@Output() onSignedOut = new EventEmitter<string>();
constructor(private _userService: UserService,
private _routerService: Router) {
}
ngOnInit() {
this.regUser = this._userService.getEmptyRegisteredUser();
}
registerUser(registrationForm: NgForm) {
this.regUser.name = registrationForm.value.userName;
this.regUser.email = registrationForm.value.userEmail;
this._userService.registerUser(this.regUser);
this.registrationComplete=true;
this.onRegistered.emit(this.regUser.name);
}
signOut() {
let userSignedout : string = this.regUser.name;
this.regUser = this._userService.getEmptyRegisteredUser();
this.registrationComplete=false;
this._routerService.navigate(['Home']);
this.onSignedOut.emit(userSignedout);
return false;
}
}
| 568
|
https://github.com/shizhuoye/XREngine/blob/master/packages/server-core/src/types/WebRtcTransportParams.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
XREngine
|
shizhuoye
|
TypeScript
|
Code
| 58
| 148
|
// Types borrowed from Mediasoup
type NumSctpStreams = {
/**
* Initially requested number of outgoing SCTP streams.
*/
OS: number
/**
* Maximum number of incoming SCTP streams.
*/
MIS: number
}
type SctpCapabilities = {
numStreams: NumSctpStreams
}
export type WebRtcTransportParams = {
peerId?: string
direction: 'recv' | 'send'
sctpCapabilities: SctpCapabilities
channelType: string
channelId?: string
}
| 2,023
|
https://github.com/KimNeutral/SSSS/blob/master/resources/views/errors/notfound.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
SSSS
|
KimNeutral
|
PHP
|
Code
| 11
| 78
|
@extends('layouts.app')
@section('content')
<p style="font-size: 60px">404!</p>
<p style="font-size: 30px">존재하지 않는 페이지입니다!</p>
@endsection
| 28,341
|
https://github.com/knockdata/spark-highcharts/blob/master/src/main/scala/com/knockdata/spark/highcharts/CustomOutputMode.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
spark-highcharts
|
knockdata
|
Scala
|
Code
| 179
| 649
|
package com.knockdata.spark.highcharts
import com.knockdata.spark.highcharts.model.{Drilldown, Series}
import org.apache.spark.sql.streaming.OutputMode
import org.apache.zeppelin.spark.ZeppelinContext
import scala.collection.mutable
abstract class CustomOutputMode() extends OutputMode {
val values = mutable.Map[String, String]()
def put(key: String, value: String): Unit = values.put(key, value)
def get(key: String): Option[String] = values.get(key)
def apply(key: String): String = values(key)
def result(normalSeries: List[Series],
drilldownSeries: List[Series]): (List[Series], List[Series]) =
(normalSeries, drilldownSeries)
// def onFinish(result: String)
}
class AppendOutputMode(maxPoints: Int)
extends CustomOutputMode() {
var currentNormalSeries = mutable.Map[String, Series]()
var currentDrilldownSeries = mutable.Map[String, Series]()
def merge(previous: mutable.Map[String, Series],
currentSeriesList: List[Series]): mutable.Map[String, Series] = {
val current = mutable.Map[String, Series]()
for (series <- currentSeriesList) {
current += series.id -> series
}
// for the existing series, if there are more point need be added
for ((key, series) <- previous) {
if (current.contains(key)) {
// println("\nprevious")
// println(series.values.mkString("\n"))
// println("\ncurrent")
// println(current(key).values.mkString("\n"))
current(key).vs = (series.values ::: current(key).values).takeRight(maxPoints)
// println("\nvs")
// println(current(key).vs.mkString("\n"))
}
else {
current += key -> series
}
}
current
}
override def result(normalSeries: List[Series],
drilldownSeries: List[Series]): (List[Series], List[Series]) = {
currentNormalSeries = merge(currentNormalSeries, normalSeries)
currentDrilldownSeries = merge(currentDrilldownSeries, drilldownSeries)
(currentNormalSeries.values.toList, currentDrilldownSeries.values.toList)
}
}
class CompleteOutputMode()
extends CustomOutputMode() {
}
| 50,789
|
https://github.com/wya-team/wya-vc/blob/master/src/transition/transition-fade.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
wya-vc
|
wya-team
|
Vue
|
Code
| 127
| 549
|
<template>
<component
:is="componentType"
:tag="tag"
:enter-active-class="`${prefix} is-in`"
:move-class="`${prefix} is-move`"
:leave-active-class="`${prefix} is-out`"
v-bind="$attrs"
v-on="hooks"
>
<slot />
</component>
</template>
<script>
import basicMixin from './basic-mixin';
export default {
name: 'vc-transition-fade',
mixins: [basicMixin],
props: {
styles: {
type: Object,
default: () => ({
animationFillMode: 'both',
animationTimingFunction: undefined,
})
},
prefix: {
type: String,
default: 'vc-transition-fade'
}
}
};
</script>
<style lang="scss">
@import '../style/vars.scss';
$block: vc-transition-fade;
@include block($block) {
@include when(in) {
will-change: opacity;
animation-name: vc-fade-in;
animation-timing-function: linear;
}
@include when(out) {
will-change: opacity;
animation-name: vc-fade-out;
animation-timing-function: linear;
}
/**
* transition-group下删除元素, 其他元素位置变化动画
*/
@include when(move) {
transition: transform .3s $ease-out-quint;
}
}
@keyframes vc-fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes vc-fade-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
</style>
| 47,327
|
https://github.com/hvydya/kuma/blob/master/api/mesh/v1alpha1/dataplane_overview.pb.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
kuma
|
hvydya
|
Go
|
Code
| 487
| 1,801
|
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: mesh/v1alpha1/dataplane_overview.proto
package v1alpha1
import (
fmt "fmt"
_ "github.com/envoyproxy/protoc-gen-validate/validate"
proto "github.com/golang/protobuf/proto"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
// DataplaneOverview defines the projected state of a Dataplane.
type DataplaneOverview struct {
Dataplane *Dataplane `protobuf:"bytes,1,opt,name=dataplane,proto3" json:"dataplane,omitempty"`
DataplaneInsight *DataplaneInsight `protobuf:"bytes,2,opt,name=dataplane_insight,json=dataplaneInsight,proto3" json:"dataplane_insight,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *DataplaneOverview) Reset() { *m = DataplaneOverview{} }
func (m *DataplaneOverview) String() string { return proto.CompactTextString(m) }
func (*DataplaneOverview) ProtoMessage() {}
func (*DataplaneOverview) Descriptor() ([]byte, []int) {
return fileDescriptor_ea8390996584fcf0, []int{0}
}
func (m *DataplaneOverview) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_DataplaneOverview.Unmarshal(m, b)
}
func (m *DataplaneOverview) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_DataplaneOverview.Marshal(b, m, deterministic)
}
func (m *DataplaneOverview) XXX_Merge(src proto.Message) {
xxx_messageInfo_DataplaneOverview.Merge(m, src)
}
func (m *DataplaneOverview) XXX_Size() int {
return xxx_messageInfo_DataplaneOverview.Size(m)
}
func (m *DataplaneOverview) XXX_DiscardUnknown() {
xxx_messageInfo_DataplaneOverview.DiscardUnknown(m)
}
var xxx_messageInfo_DataplaneOverview proto.InternalMessageInfo
func (m *DataplaneOverview) GetDataplane() *Dataplane {
if m != nil {
return m.Dataplane
}
return nil
}
func (m *DataplaneOverview) GetDataplaneInsight() *DataplaneInsight {
if m != nil {
return m.DataplaneInsight
}
return nil
}
func init() {
proto.RegisterType((*DataplaneOverview)(nil), "kuma.mesh.v1alpha1.DataplaneOverview")
}
func init() {
proto.RegisterFile("mesh/v1alpha1/dataplane_overview.proto", fileDescriptor_ea8390996584fcf0)
}
var fileDescriptor_ea8390996584fcf0 = []byte{
// 210 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0xcb, 0x4d, 0x2d, 0xce,
0xd0, 0x2f, 0x33, 0x4c, 0xcc, 0x29, 0xc8, 0x48, 0x34, 0xd4, 0x4f, 0x49, 0x2c, 0x49, 0x2c, 0xc8,
0x49, 0xcc, 0x4b, 0x8d, 0xcf, 0x2f, 0x4b, 0x2d, 0x2a, 0xcb, 0x4c, 0x2d, 0xd7, 0x2b, 0x28, 0xca,
0x2f, 0xc9, 0x17, 0x12, 0xca, 0x2e, 0xcd, 0x4d, 0xd4, 0x03, 0x29, 0xd6, 0x83, 0x29, 0x96, 0x92,
0xc5, 0xa1, 0x17, 0xa2, 0x45, 0x4a, 0x15, 0x97, 0xd1, 0x99, 0x79, 0xc5, 0x99, 0xe9, 0x19, 0x25,
0x50, 0x65, 0xe2, 0x65, 0x89, 0x39, 0x99, 0x29, 0x89, 0x25, 0xa9, 0xfa, 0x30, 0x06, 0x44, 0x42,
0x69, 0x2d, 0x23, 0x97, 0xa0, 0x0b, 0x4c, 0x93, 0x3f, 0xd4, 0x39, 0x42, 0xae, 0x5c, 0x9c, 0x70,
0x93, 0x24, 0x18, 0x15, 0x18, 0x35, 0xb8, 0x8d, 0x64, 0xf5, 0x30, 0x1d, 0xa7, 0x07, 0xd7, 0xe9,
0xc4, 0xf1, 0xcb, 0x89, 0xb5, 0x8b, 0x91, 0x49, 0x80, 0x31, 0x08, 0xa1, 0x53, 0x28, 0x90, 0x4b,
0x10, 0xc3, 0x41, 0x12, 0x4c, 0x60, 0xe3, 0x54, 0xf0, 0x1a, 0xe7, 0x09, 0x51, 0x1b, 0x24, 0x90,
0x82, 0x26, 0xe2, 0xa4, 0x15, 0xa5, 0x91, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f,
0xab, 0x0f, 0x32, 0x23, 0xa3, 0x10, 0x4c, 0xe9, 0x27, 0x16, 0x64, 0xea, 0xa3, 0x04, 0x46, 0x12,
0x1b, 0xd8, 0x8b, 0xc6, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0x40, 0xdc, 0x30, 0x61, 0x7f, 0x01,
0x00, 0x00,
}
| 26,039
|
https://github.com/iotconnect-apps/AppConnect-SmartGreenHouse/blob/master/iot.solution.eventbus/CustomAttribute/ConfigureAttribute.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
AppConnect-SmartGreenHouse
|
iotconnect-apps
|
C#
|
Code
| 301
| 719
|
using System;
namespace component.eventbus.CustomAttribute
{
/// <summary>
/// ConfigureAttribute
/// </summary>
/// <seealso cref="System.Attribute" />
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class ConfigureAttribute : Attribute
{
/// <summary>
/// The connection
/// </summary>
private string _Connection;
/// <summary>
/// The topic name
/// </summary>
private string _TopicName;
/// <summary>
/// The queue name
/// </summary>
private string _QueueName;
/// <summary>
/// The event type
/// </summary>
private Int16 _EventType;
/// <summary>
/// The event type version
/// </summary>
private Int16 _EventTypeVersion;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigureAttribute"/> class.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="eventType">Type of the event.</param>
/// <param name="eventTypeVersion">The event type version.</param>
/// <param name="topicName">Name of the topic.</param>
/// <param name="queueName">Name of the queue.</param>
public ConfigureAttribute(string connection, Int16 eventType, Int16 eventTypeVersion, string topicName = "", string queueName = "")
{
this._TopicName = topicName;
this._Connection = connection;
this._EventType = eventType;
this._EventTypeVersion = eventTypeVersion;
this._QueueName = queueName;
}
/// <summary>
/// Gets the connection.
/// </summary>
/// <value>
/// The connection.
/// </value>
public string Connection { get { return _Connection; } }
/// <summary>
/// Gets the name of the topic.
/// </summary>
/// <value>
/// The name of the topic.
/// </value>
public string TopicName { get { return _TopicName; } }
/// <summary>
/// Gets the name of the queue.
/// </summary>
/// <value>
/// The name of the queue.
/// </value>
public string QueueName { get { return _QueueName; } }
/// <summary>
/// Gets the event identifier.
/// </summary>
/// <value>
/// The event identifier.
/// </value>
public Int16 EventId { get { return _EventType; } }
/// <summary>
/// Gets the event type version.
/// </summary>
/// <value>
/// The event type version.
/// </value>
public Int16 EventTypeVersion { get { return _EventTypeVersion; } }
}
}
| 22,659
|
https://github.com/nileshpatra/plast-library/blob/master/src/database/impl/BufferedCachedSequenceDatabase.cpp
|
Github Open Source
|
Open Source
|
Intel, DOC
| 2,020
|
plast-library
|
nileshpatra
|
C++
|
Code
| 308
| 832
|
/*****************************************************************************
* *
* PLAST : Parallel Local Alignment Search Tool *
* Version 2.3, released November 2015 *
* Copyright (c) 2009-2015 Inria-Cnrs-Ens *
* *
* PLAST is free software; you can redistribute it and/or modify it under *
* the Affero GPL ver 3 License, that is compatible with the GNU General *
* Public License *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* Affero GPL ver 3 License for more details. *
*****************************************************************************/
#include <database/impl/BufferedCachedSequenceDatabase.hpp>
#include <designpattern/impl/Property.hpp>
#include <misc/api/macros.hpp>
#include <stdlib.h>
#include <stdio.h>
#define DEBUG(a) //printf a
using namespace std;
using namespace dp;
using namespace dp::impl;
using namespace os;
using namespace os::impl;
/********************************************************************************/
namespace database { namespace impl {
/********************************************************************************/
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
BufferedCachedSequenceDatabase::BufferedCachedSequenceDatabase (ISequenceIterator* refIterator, int filterLowComplexity)
: BufferedSequenceDatabase (refIterator, filterLowComplexity), _isBuilt(false)
{
DEBUG (("BufferedCachedSequenceDatabase::BufferedCachedSequenceDatabase this=%p iter=%p\n", this, refIterator));
/** We force the building of the sequences cache. */
buildSequencesCache ();
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
BufferedCachedSequenceDatabase::~BufferedCachedSequenceDatabase ()
{
DEBUG (("BufferedCachedSequenceDatabase::~BufferedCachedSequenceDatabase this=%p _sequences.size=%ld\n",
this,
_sequences.size()
));
_sequences.clear ();
}
/*********************************************************************
** METHOD :
** PURPOSE :
** INPUT :
** OUTPUT :
** RETURN :
** REMARKS :
*********************************************************************/
void BufferedCachedSequenceDatabase::buildSequencesCache ()
{
DEBUG (("BufferedCachedSequenceDatabase::BufferedCachedSequenceDatabase this=%p _isBuilt=%d\n", this, _isBuilt));
if (_isBuilt == false)
{
/** Shortcut. */
size_t nbSeq = getSequencesNumber();
_sequences.resize (nbSeq);
for (size_t i=0; i<nbSeq; i++) { this->getSequenceByIndex (i, _sequences[i]); }
/** Note that we should have _sequences.size() == getSequencesNumber() */
_isBuilt = true;
}
}
/********************************************************************************/
} } /* end of namespaces. */
/********************************************************************************/
| 44,019
|
https://github.com/iangle/UKG-Ready-API/blob/master/venv/Lib/site-packages/pathy/gcs.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
UKG-Ready-API
|
iangle
|
Python
|
Code
| 631
| 2,232
|
from dataclasses import dataclass
from typing import Any, Dict, Generator, List, Optional
try:
from google.api_core.exceptions import BadRequest # type:ignore
from google.cloud.storage import Blob as GCSNativeBlob # type:ignore
from google.cloud.storage import Bucket as GCSNativeBucket # type:ignore
from google.cloud.storage import Client as GCSNativeClient # type:ignore
except (ImportError, ModuleNotFoundError):
raise ImportError(
"""You are using the GCS functionality of Pathy without
having the required dependencies installed.
Please try installing them:
pip install pathy[gcs]
"""
)
from . import (
Blob,
Bucket,
BucketClient,
BucketEntry,
PathyScanDir,
PurePathy,
register_client,
)
class BucketEntryGCS(BucketEntry):
bucket: "BucketGCS"
raw: GCSNativeBlob # type:ignore[override]
@dataclass
class BlobGCS(Blob):
def delete(self) -> None:
self.raw.delete() # type:ignore
def exists(self) -> bool:
return self.raw.exists() # type:ignore
@dataclass
class BucketGCS(Bucket):
name: str
bucket: GCSNativeBucket
def get_blob(self, blob_name: str) -> Optional[BlobGCS]:
assert isinstance(
blob_name, str
), f"expected str blob name, but found: {type(blob_name)}"
native_blob: Optional[Any] = self.bucket.get_blob(blob_name) # type:ignore
if native_blob is None:
return None
return BlobGCS(
bucket=self.bucket,
owner=native_blob.owner, # type:ignore
name=native_blob.name, # type:ignore
raw=native_blob,
size=native_blob.size,
updated=int(native_blob.updated.timestamp()), # type:ignore
)
def copy_blob( # type:ignore[override]
self, blob: BlobGCS, target: "BucketGCS", name: str
) -> Optional[BlobGCS]:
assert blob.raw is not None, "raw storage.Blob instance required"
native_blob: GCSNativeBlob = self.bucket.copy_blob( # type: ignore
blob.raw, target.bucket, name
)
return BlobGCS(
bucket=self.bucket,
owner=native_blob.owner, # type:ignore
name=native_blob.name, # type:ignore
raw=native_blob,
size=native_blob.size,
updated=int(native_blob.updated.timestamp()), # type:ignore
)
def delete_blob(self, blob: BlobGCS) -> None: # type:ignore[override]
return self.bucket.delete_blob(blob.name) # type:ignore
def delete_blobs(self, blobs: List[BlobGCS]) -> None: # type:ignore[override]
return self.bucket.delete_blobs(blobs) # type:ignore
def exists(self) -> bool:
return self.bucket.exists() # type:ignore
class BucketClientGCS(BucketClient):
client: GCSNativeClient
@property
def client_params(self) -> Any:
return dict(client=self.client)
def __init__(self, **kwargs: Any) -> None:
self.recreate(**kwargs)
def recreate(self, **kwargs: Any) -> None:
creds = kwargs["credentials"] if "credentials" in kwargs else None
if creds is not None:
kwargs["project"] = creds.project_id
self.client = GCSNativeClient(**kwargs)
def make_uri(self, path: PurePathy) -> str:
return str(path)
def create_bucket( # type:ignore[override]
self, path: PurePathy
) -> GCSNativeBucket:
return self.client.create_bucket(path.root) # type:ignore
def delete_bucket(self, path: PurePathy) -> None:
bucket = self.client.get_bucket(path.root) # type:ignore
bucket.delete() # type:ignore
def exists(self, path: PurePathy) -> bool:
# Because we want all the parents of a valid blob (e.g. "directory" in
# "directory/foo.file") to return True, we enumerate the blobs with a prefix
# and compare the object names to see if they match a substring of the path
key_name = str(path.key)
for obj in self.list_blobs(path):
if obj.name.startswith(key_name + path._flavour.sep): # type:ignore
return True
return False
def lookup_bucket(self, path: PurePathy) -> Optional[BucketGCS]:
try:
return self.get_bucket(path)
except FileNotFoundError:
return None
def get_bucket(self, path: PurePathy) -> BucketGCS:
native_bucket: Any = self.client.bucket(path.root) # type:ignore
try:
if native_bucket.exists():
return BucketGCS(str(path.root), bucket=native_bucket)
except BadRequest:
pass
raise FileNotFoundError(f"Bucket {path.root} does not exist!")
def list_buckets( # type:ignore[override]
self, **kwargs: Dict[str, Any]
) -> Generator[GCSNativeBucket, None, None]:
return self.client.list_buckets(**kwargs) # type:ignore
def scandir( # type:ignore[override]
self,
path: Optional[PurePathy] = None,
prefix: Optional[str] = None,
delimiter: Optional[str] = None,
) -> PathyScanDir:
return ScanDirGCS(client=self, path=path, prefix=prefix, delimiter=delimiter)
def list_blobs(
self,
path: PurePathy,
prefix: Optional[str] = None,
delimiter: Optional[str] = None,
) -> Generator[BlobGCS, None, None]:
bucket = self.lookup_bucket(path)
if bucket is None:
return
response: Any = self.client.list_blobs( # type:ignore
path.root, prefix=prefix, delimiter=delimiter
)
for page in response.pages: # type:ignore
for item in page:
yield BlobGCS(
bucket=bucket,
owner=item.owner,
name=item.name,
raw=item,
size=item.size,
updated=item.updated.timestamp(),
)
class ScanDirGCS(PathyScanDir):
_client: BucketClientGCS
def scandir(self) -> Generator[BucketEntryGCS, None, None]:
if self._path is None or not self._path.root:
gcs_bucket: GCSNativeBucket
for gcs_bucket in self._client.list_buckets():
yield BucketEntryGCS(
gcs_bucket.name, is_dir=True, raw=None # type:ignore
)
return
sep = self._path._flavour.sep # type:ignore
bucket = self._client.lookup_bucket(self._path)
if bucket is None:
return
response = self._client.client.list_blobs( # type:ignore
bucket.name, prefix=self._prefix, delimiter=sep
)
for page in response.pages: # type:ignore
folder: str
for folder in list(page.prefixes): # type:ignore
full_name = folder[:-1] if folder.endswith(sep) else folder
name = full_name.split(sep)[-1]
if name:
yield BucketEntryGCS(name, is_dir=True, raw=None)
item: Any
for item in page: # type:ignore
name = item.name.split(sep)[-1]
if name:
yield BucketEntryGCS(
name=name,
is_dir=False,
size=item.size,
last_modified=item.updated.timestamp(),
raw=item,
)
register_client("gs", BucketClientGCS)
| 2,359
|
https://github.com/YangYafei1998/main/blob/master/src/test/java/seedu/address/logic/commands/DeleteMedicalHistoryCommandTest.java
|
Github Open Source
|
Open Source
|
MIT
| null |
main
|
YangYafei1998
|
Java
|
Code
| 553
| 2,686
|
package seedu.address.logic.commands;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static seedu.address.logic.commands.CommandTestUtil.NON_EXIST_ALLERGY;
import static seedu.address.logic.commands.CommandTestUtil.NON_EXIST_CONDITION;
import static seedu.address.logic.commands.CommandTestUtil.NON_EXIST_NAME;
import static seedu.address.logic.commands.CommandTestUtil.VALID_ALLERGY_TO_DELETE;
import static seedu.address.logic.commands.CommandTestUtil.VALID_CONDITION_TO_DELETE;
import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_ALICE;
import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_BENSON;
import static seedu.address.logic.commands.CommandTestUtil.assertCommandFailure;
import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_PERSON;
import static seedu.address.testutil.TypicalPatientsAndDoctors.CARL_PATIENT;
import static seedu.address.testutil.TypicalPatientsAndDoctors.getTypicalAddressBookWithPatientAndDoctor;
import java.util.ArrayList;
import org.junit.Test;
import seedu.address.logic.CommandHistory;
import seedu.address.model.HealthBook;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.UserPrefs;
import seedu.address.model.patient.Allergy;
import seedu.address.model.patient.Condition;
import seedu.address.model.patient.Patient;
import seedu.address.model.person.Name;
import seedu.address.model.tag.TagContainsDoctorPredicate;
import seedu.address.model.tag.TagContainsPatientPredicate;
import seedu.address.testutil.PatientBuilder;
/**
* Contains integration tests and unit tests for DeleteMedicalHistoryCommand.
*/
public class DeleteMedicalHistoryCommandTest {
private ArrayList<Allergy> emptyAllergy = new ArrayList<>();
private ArrayList<Condition> emptyCondition = new ArrayList<>();
private Model model = new ModelManager(getTypicalAddressBookWithPatientAndDoctor(), new UserPrefs());
private CommandHistory commandHistory = new CommandHistory();
@Test
public void execute_deleteMedicalHistory_success() {
final TagContainsPatientPredicate predicate = new TagContainsPatientPredicate();
model.updateFilteredPersonList(predicate);
Patient firstPatient = (Patient) model.getFilteredPersonList().get(INDEX_FIRST_PERSON.getZeroBased());
Patient editedPatient = new PatientBuilder(firstPatient).build();
editedPatient.getMedicalHistory().getAllergies().remove(VALID_ALLERGY_TO_DELETE);
editedPatient.getMedicalHistory().getConditions().remove(VALID_CONDITION_TO_DELETE);
ArrayList<Allergy> allergies = new ArrayList<>();
ArrayList<Condition> conditions = new ArrayList<>();
allergies.add(new Allergy(VALID_ALLERGY_TO_DELETE));
conditions.add(new Condition(VALID_CONDITION_TO_DELETE));
DeleteMedicalHistoryCommand deleteMedicalHistoryCommand =
new DeleteMedicalHistoryCommand(
new Name(VALID_NAME_ALICE), null, allergies, conditions);
String expectedMessage = String.format(DeleteMedicalHistoryCommand.MESSAGE_DELETE_MEDICAL_HISTORY_SUCCESS,
editedPatient);
Model expectedModel = new ModelManager(new HealthBook(model.getAddressBook()), new UserPrefs());
expectedModel.updatePerson(firstPatient, editedPatient);
expectedModel.commitAddressBook();
assertCommandSuccess(deleteMedicalHistoryCommand, model, commandHistory, expectedMessage, expectedModel);
}
@Test
public void execute_invalidPersonName_failure() {
ArrayList<Allergy> allergies = new ArrayList<>();
ArrayList<Condition> conditions = new ArrayList<>();
allergies.add(new Allergy(VALID_ALLERGY_TO_DELETE));
conditions.add(new Condition(VALID_CONDITION_TO_DELETE));
DeleteMedicalHistoryCommand deleteMedicalHistoryCommand =
new DeleteMedicalHistoryCommand(new Name(NON_EXIST_NAME), null, allergies, conditions);
assertCommandFailure(deleteMedicalHistoryCommand,
model, commandHistory, DeleteMedicalHistoryCommand
.MESSAGE_INVALID_DELETE_MEDICAL_HISTORY_NO_MATCH_NAME);
}
@Test
public void execute_duplicatePatient_failure() {
ArrayList<Allergy> allergies = new ArrayList<>();
ArrayList<Condition> conditions = new ArrayList<>();
allergies.add(new Allergy(VALID_ALLERGY_TO_DELETE));
conditions.add(new Condition(VALID_CONDITION_TO_DELETE));
Patient similarPatientDifferentNumber = new PatientBuilder().withName(CARL_PATIENT.getName().toString())
.withPhone("12341234").build();
model.addPatient(similarPatientDifferentNumber);
AddMedicalHistoryCommand addMedicalHistoryCommand =
new AddMedicalHistoryCommand(new Name(CARL_PATIENT.getName().toString()),
null, allergies, conditions);
assertCommandFailure(addMedicalHistoryCommand,
model, commandHistory, AddMedicalHistoryCommand.MESSAGE_DUPLICATE_PATIENT);
}
@Test
public void execute_invalidAllergy_failure() {
final TagContainsPatientPredicate predicate = new TagContainsPatientPredicate();
model.updateFilteredPersonList(predicate);
ArrayList<Allergy> allergies = new ArrayList<>();
allergies.add(new Allergy(NON_EXIST_ALLERGY));
DeleteMedicalHistoryCommand deleteMedicalHistoryCommand =
new DeleteMedicalHistoryCommand(new Name(VALID_NAME_ALICE), null, allergies, emptyCondition);
assertCommandFailure(deleteMedicalHistoryCommand, model, commandHistory,
DeleteMedicalHistoryCommand.MESSAGE_INVALID_DELETE_MEDICAL_HISTORY_NO_ALLERGY
+ NON_EXIST_ALLERGY);
}
@Test
public void execute_invalidCondition_failure() {
final TagContainsPatientPredicate predicate = new TagContainsPatientPredicate();
model.updateFilteredPersonList(predicate);
ArrayList<Condition> conditions = new ArrayList<>();
conditions.add(new Condition(NON_EXIST_CONDITION));
DeleteMedicalHistoryCommand deleteMedicalHistoryCommand =
new DeleteMedicalHistoryCommand(new Name(VALID_NAME_ALICE), null, emptyAllergy, conditions);
assertCommandFailure(deleteMedicalHistoryCommand, model, commandHistory,
DeleteMedicalHistoryCommand.MESSAGE_INVALID_DELETE_MEDICAL_HISTORY_NO_CONDITION
+ NON_EXIST_CONDITION);
}
@Test
public void execute_invalidType_failure() {
final TagContainsDoctorPredicate predicate = new TagContainsDoctorPredicate();
model.updateFilteredPersonList(predicate);
ArrayList<Allergy> allergies = new ArrayList<>();
ArrayList<Condition> conditions = new ArrayList<>();
allergies.add(new Allergy(VALID_ALLERGY_TO_DELETE));
conditions.add(new Condition(VALID_CONDITION_TO_DELETE));
DeleteMedicalHistoryCommand deleteMedicalHistoryCommand =
new DeleteMedicalHistoryCommand(
model.getFilteredPersonList().get(INDEX_FIRST_PERSON.getZeroBased()).getName(),
null, allergies, conditions);
assertCommandFailure(deleteMedicalHistoryCommand, model, commandHistory,
DeleteMedicalHistoryCommand.MESSAGE_INVALID_DELETE_MEDICAL_HISTORY_WRONG_TYPE);
}
@Test
public void execute_blankInput_failure() {
final TagContainsPatientPredicate predicate = new TagContainsPatientPredicate();
model.updateFilteredPersonList(predicate);
DeleteMedicalHistoryCommand deleteMedicalHistoryCommand =
new DeleteMedicalHistoryCommand(new Name(VALID_NAME_ALICE), null, emptyAllergy, emptyCondition);
assertCommandFailure(deleteMedicalHistoryCommand, model, commandHistory,
DeleteMedicalHistoryCommand.MESSAGE_INVALID_DELETE_MEDICAL_HISTORY_NO_INFO);
}
@Test
public void execute_duplicateAllergyInput() {
ArrayList<Allergy> allergies = new ArrayList<>();
ArrayList<Condition> conditions = new ArrayList<>();
allergies.add(new Allergy(VALID_ALLERGY_TO_DELETE));
allergies.add(new Allergy(VALID_ALLERGY_TO_DELETE));
DeleteMedicalHistoryCommand deleteMedicalHistoryCommand =
new DeleteMedicalHistoryCommand(new Name(VALID_NAME_ALICE), null, allergies, conditions);
assertCommandFailure(deleteMedicalHistoryCommand,
model, commandHistory, AddMedicalHistoryCommand.MESSAGE_INVALID_ADD_MEDICAL_HISTORY_DUPLICATE_INPUT);
}
@Test
public void execute_duplicateConditionInput() {
ArrayList<Allergy> allergies = new ArrayList<>();
ArrayList<Condition> conditions = new ArrayList<>();
conditions.add(new Condition(VALID_CONDITION_TO_DELETE));
conditions.add(new Condition(VALID_CONDITION_TO_DELETE));
DeleteMedicalHistoryCommand deleteMedicalHistoryCommand =
new DeleteMedicalHistoryCommand(new Name(VALID_NAME_ALICE), null, allergies, conditions);
assertCommandFailure(deleteMedicalHistoryCommand,
model, commandHistory, AddMedicalHistoryCommand.MESSAGE_INVALID_ADD_MEDICAL_HISTORY_DUPLICATE_INPUT);
}
@Test
public void equals() {
ArrayList<Allergy> allergies = new ArrayList<>();
ArrayList<Condition> conditions = new ArrayList<>();
allergies.add(new Allergy(VALID_ALLERGY_TO_DELETE));
conditions.add(new Condition(VALID_CONDITION_TO_DELETE));
final DeleteMedicalHistoryCommand standardCommand =
new DeleteMedicalHistoryCommand(new Name(VALID_NAME_ALICE), null, allergies, conditions);
// same values -> returns true
DeleteMedicalHistoryCommand commandWithSameValues =
new DeleteMedicalHistoryCommand(new Name(VALID_NAME_ALICE), null, allergies, conditions);
assertTrue(standardCommand.equals(commandWithSameValues));
// same object -> returns true
assertTrue(standardCommand.equals(standardCommand));
// null -> returns false
assertFalse(standardCommand.equals(null));
// different types -> returns false
assertFalse(standardCommand.equals(new ClearCommand()));
// different index -> returns false
assertFalse(standardCommand.equals(
new DeleteMedicalHistoryCommand(new Name(VALID_NAME_BENSON), null, allergies, conditions)));
// different descriptor -> returns false
assertFalse(standardCommand.equals(
new DeleteMedicalHistoryCommand(new Name(VALID_NAME_ALICE), null, emptyAllergy, emptyCondition)));
}
}
| 3,514
|
https://github.com/MrCull/dtrace-utils/blob/master/test/unittest/sizeof/tst.SizeofString2.r
|
Github Open Source
|
Open Source
|
UPL-1.0
| 2,021
|
dtrace-utils
|
MrCull
|
R
|
Code
| 3
| 8
|
sizeof (var): 256
| 40,437
|
https://github.com/WillyWunderdog/More-Recipes-Gbenga/blob/master/server/routes/recipes.js
|
Github Open Source
|
Open Source
|
MIT
| null |
More-Recipes-Gbenga
|
WillyWunderdog
|
JavaScript
|
Code
| 94
| 406
|
import express from 'express';
import auth from '../middlewares/auth';
import controllers from '../controllers';
import validateRecipe from '../middlewares/recipeValidation';
import validateParams from '../middlewares/validateParams';
import validateOwnership from '../helpers/checkOwner';
const router = express.Router();
// route for creating a new recipe
router.post('/api/v1/recipe',
auth,
validateRecipe.validateFields,
controllers.Recipe.addRecipe);
// route for fetching all recipes
router.get('/api/v1/recipes',
controllers.Recipe.searchRecipes,
controllers.Recipe.fetchAllRecipes,
controllers.Recipe.fetchTopRecipes);
// route to get a users recipes
router.get('/api/v1/recipes/users',
auth,
controllers.Recipe.fetchUserRecipes);
// route to view recipe details
router.get('/api/v1/recipes/:recipeId',
validateParams,
validateRecipe.recipeExist,
controllers.Recipe.fetchARecipe);
// route for update recipe
router.put('/api/v1/recipes/:recipeId',
auth,
validateParams,
validateRecipe.recipeExist,
validateOwnership,
controllers.Recipe.updateARecipe);
// route for delete recipe
router.delete('/api/v1/recipes/:recipeId',
auth,
validateParams,
validateRecipe.recipeExist,
validateOwnership,
controllers.Recipe.destroyARecipe);
export default router;
| 8,830
|
https://github.com/utdcometsoccer/basiclandingpage/blob/master/starters/product-landing-page/index.d.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
basiclandingpage
|
utdcometsoccer
|
TypeScript
|
Code
| 36
| 188
|
import {
IDarkProductHeadlineProps,
IProductHeadlineContainerProps,
IProductHeadlineProps,
DarkProductHeadline,
LightProductHeadline,
ProductHeadline,
ProductHeadlineContainer,
} from "@idahoedokpayi/basic-landing-page-components";
import { IProductLayoutProps, ProductLayout } from "./src/components/productlayout";
import ProductExample from "./src/pages/productexample";
export {
DarkProductHeadline,
LightProductHeadline,
ProductHeadline,
ProductHeadlineContainer,
IProductLayoutProps,
IDarkProductHeadlineProps,
IProductHeadlineProps,
IProductHeadlineContainerProps,
ProductLayout,
ProductExample,
};
| 38,056
|
https://github.com/MILL5/yocto/blob/master/src/yocto/ContainerBuilder.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
yocto
|
MILL5
|
C#
|
Code
| 168
| 478
|
using System;
// ReSharper disable InconsistentNaming
namespace yocto
{
public class ContainerBuilder : IRegisterType, IDisposable
{
private readonly object _syncLock = new object();
private IContainer _container;
private bool _disposed;
public ContainerBuilder()
{
_container = Application.Current.GetChildContainer();
}
~ContainerBuilder()
{
InternalDispose();
}
public IRegistration Register<T>(T instance) where T : class
{
return GetContainer().Register(() => instance);
}
public IRegistration Register<T>(Func<T> factory) where T : class
{
return GetContainer().Register(factory);
}
public IRegistration Register<T, V>() where V : class, T where T : class
{
return GetContainer().Register<T, V>();
}
public IContainer Build()
{
IContainer container;
lock (_syncLock)
{
container = _container;
if (container == null)
throw new Exception("Container already built.");
_container = null;
}
return container;
}
private IContainer GetContainer()
{
IContainer container;
lock (_syncLock)
{
container = _container;
}
if (container == null)
throw new Exception("Container already built.");
return container;
}
protected virtual void InternalDispose()
{
if (!_disposed)
{
_disposed = true;
lock (_syncLock)
{
Cleanup.SafeMethod(() => (_container as IDisposable)?.Dispose());
}
}
}
public void Dispose()
{
InternalDispose();
GC.SuppressFinalize(this);
}
}
}
| 5,036
|
https://github.com/JoelRocaMartinez/immudb-webconsole/blob/master/src/components/the/Banner.vue
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
immudb-webconsole
|
JoelRocaMartinez
|
Vue
|
Code
| 237
| 924
|
<template>
<v-system-bar
v-if="value"
id="TheBanner"
class="ma-0 pa-0 d-flex justify-center align-center"
:height="32"
:color="color"
fixed
app
>
<v-spacer
v-if="!persistent"
class="ml-4"
/>
<slot>
<v-icon
class="ma-0 pa-0 white--text"
:size="18"
>
{{ icon }}
</v-icon>
<span
v-if="title === CHANGE_SYSADMIN_PASSWORD"
class="ma-0 ml-2 pa-0 subtitle-2 white--text text-center font-weight-bold"
>
immudb user has the default password: please
<span
class="white--text text-decoration-underline cursor-pointer"
@click="onSubmit"
>
change it to ensure proper security!
</span>
</span>
<span
v-else
class="ma-0 ml-2 pa-0 subtitle-2 white--text text-center font-weight-bold"
>
{{ title }}
</span>
</slot>
<v-spacer
v-if="!persistent"
/>
<v-btn
v-if="!persistent"
class="ma-0 mr-4 pa-0 text-center"
text
icon
dense
x-small
@click="onClose"
>
<v-icon
class="ma-0 pa-0"
:size="18"
>
{{ mdiClose }}
</v-icon>
</v-btn>
</v-system-bar>
</template>
<script>
import {
mdiAlert,
mdiStar,
mdiClose,
} from '@mdi/js';
const CHANGE_SYSADMIN_PASSWORD = 'immudb user has the default password: please change it to ensure proper security';
export default {
name: 'TheBanner',
props: {
value: { type: Boolean, default: false },
title: { type: String, default: '' },
subtitle: { type: String, default: '' },
color: { type: String, default: 'primary' },
persistent: { type: Boolean, default: false },
icon: { type: String, default: mdiAlert },
},
data () {
return {
mdiAlert,
mdiStar,
mdiClose,
CHANGE_SYSADMIN_PASSWORD,
height: 1,
};
},
methods: {
onClose () {
this.$emit('close');
},
onSubmit () {
this.$router.push(this.localePath({ name: 'users' }));
setTimeout(() => {
this.$eventbus && this.$eventbus
.$emit('EVENT_BUS==>updateSysadminPassword');
}, 300);
},
},
};
</script>
<style lang="scss">
#TheBanner {
a {
&:hover {
span {
text-decoration: underline !important;
}
}
}
}
</style>
| 9,196
|
https://github.com/daimoonis/ngx-color/blob/master/projects/ngx-color/src/lib/common/raised/raised.component.scss
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
ngx-color
|
daimoonis
|
SCSS
|
Code
| 33
| 133
|
.ngx-color-raised {
.ngx-color-raised-wrap {
position: relative;
display: inline-block;
.ngx-color-raised-bg {
position: absolute;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
.ngx-color-raised-content {
position: relative;
}
}
.zDepth-0 {
box-shadow: none;
}
}
| 32,952
|
https://github.com/sudhakar52621/cm/blob/master/modules/configuration/webSrc/ts/build/types/core/inputs/gwAutocomplete.d.ts
|
Github Open Source
|
Open Source
|
MIT, BSD-2-Clause, Apache-1.1, Apache-2.0
| null |
cm
|
sudhakar52621
|
TypeScript
|
Code
| 984
| 2,063
|
import { GwDomNode, GwEventType, GwKeyboardNavigation, GwMap, HTMLTextInputElement } from "../../types/gwTypes";
import { GwInitializableSystem } from "../util/GwInitializableSystem";
import { GwEventDescription } from "../events/GwEventDescription";
/**
* Guidewire's TypeScript APIs are an early-stage feature and are subject to change in a future release.
*
* System for providing the autocomplete entries drop down.
* Makes ajax requests on a delay to retrieve possible entries.
*
* Keymap:
* up: move up in entry selection dropdown
* down: move down in entry selection dropdown
* right: remove selection range, move cursor position to end, close autocomplete
* left: revert input value and close autocomplete
* escape: revert input value and close autocomplete
* enter: remove selection range, move cursor position to end, close autocomplete, possibly fire post on change
* click on entry in dropdown: same as enter key
*/
export declare class GwAutocomplete extends GwInitializableSystem implements GwKeyboardNavigation {
getSystemName(): string;
private timeoutKey;
/**
* The delay after the last keypress before the autocomplete will be refreshed and rendered
* @type {number}
*/
private readonly autocompleteDelay;
/**
* Caches the last value we sent a request to the server for, preventing a new
* autocomplete request on focus if the value hasn't changed and the autocomplete
* is still visible.
* @type {string}
*/
private autocompletedValueCache;
/**
* The current entry in the autocomplete dropdown when using arrow keys to navigate up and down
* @type {object}
*/
private currentAutocompleteEntry;
/**
* Keeps track of the current autocomplete input element
* @type {boolean}
*/
private autocompleteInput;
/**
* Keeps track of the current autocomplete div element
* @type {boolean}
*/
private autocompleteDiv;
init(isFullPageReload: boolean): void;
private cancelAnyPendingAutocomplete();
/**
* Called when an autocomplete input gets focus
* @param {HTMLTextInputElement} input autocomplete input that just got focus
* @param {GwEventDescription} eventDescription event description, from data-gw-focus attribute
* @param {FocusEvent} event focus event
*/
autocompleteOnFocus(input: HTMLTextInputElement, eventDescription: GwEventDescription, event: FocusEvent): void;
/**
* @public
* Fetches and Renders autocomplete information for the given node. Called when an autocomplete
* input first gets focus (via autocompleteOnFocus) and then whenever its value changes
* @param input the input node that needs to be autocompleted
*/
autocomplete(input: HTMLTextInputElement): void;
private inputTabbed();
private addTabListenerToInput();
private removeTabListenerFromInput();
/**
* @private
* Builds the request object to send a request for autocomplete results
* @param widgetId the renderId of the widget being autocompleted
*/
private fetchAutocompleteData(widgetId);
/**
* @private
* Handles a server response for autocomplete, creates the autocomplete elements under the input, or
* destroys them if they are visible but there's nothing to show
* @param widgetName the id of the autocomplete widget
* @param originalInputValue the autocomplete input's value at the time the server request was made
* @param data the data from the server
*/
private renderAutocompleteData(widgetName, originalInputValue, data);
/**
* @private
* Create autocomplete entries matching the given result list under the input widget with the given name.
* @param widgetName name of the autocomplete widget
* @param originalInputValue the autocomplete input's value at the time the server request was made
* @param results a non empty list of autocomplete results
*/
private createAutocompleteEntries(widgetName, originalInputValue, results);
private setInputBasedOnCurrentEntry();
private setInputValue(text);
/**
* Renders autocomplete using the input as a reference to position
* Attempts to align it to the left edge of the input it's displayed for.
* - If it's offscreen right, then aligns itself to the right of the input
* @link - gw.resizer.windowHeight, gw.resizer.windowWidth
* @private
*/
private renderAutocomplete();
/***
* @private
* Called if there is an error while calling the server to fetch autocomplete entries
* @param widgetName name of the autocomplete widget
*/
private handleAutocompleteError(widgetName);
/**
* @private
* Destroy any visible autocomplete entries under the widget with the given name.
* @param widgetName name of the autocomplete widget
*/
private destroyAutocompleteEntriesIfVisible(widgetName);
/**
* Replaces "markers" with a div containing a markup class plus the tag for styling
* @param displayText the display text to replace
* @returns the displayText with divs inserted
*/
private replaceStyles(displayText);
private setCurrentAutocompleteEntry(dir);
/**
* Autocomplete entries are problematic because we don't want them to be focusable (we want
* to leave focus in the input field, and not affect the tab order) but that means clicking on
* an entry causes a focus/blur event pair as we leave the input and go to the entry, quickly
* followed by another focus/blur event pair as we force focus back to the input. We have to
* watch out for these events and ignore them
* @param {FocusEvent} e focus event
* @returns {boolean} true if the focus event is caused by focusing on or returning focus from an entry
*/
private isFocusEventCausedByAutocompleteEntry(e);
revertAutocompleteInput(): void;
/**
* @public
* Called when the user clicks on an entry in the autocomplete dropdown
* @param entry the clicked autocomplete node
* @param info the event info
*/
clickAutocompleteEntry(entry: GwDomNode, info: GwMap): void;
enterKeyPressed(node: GwDomNode): void;
tabOrEnterKeyPressed(node: HTMLTextInputElement, args: any, e: KeyboardEvent): void;
autocompleteInputBlurred(node: GwDomNode, info: GwMap, e: FocusEvent): void;
/**
* Closes the autocomplete panel.
* removes the blur attribute from the container.
* restores the focus attribute to the child.
*/
closeAutocomplete(node?: GwDomNode, info?: GwMap, event?: GwEventType): void;
/**
* @private
* Should only be called by the navigation system, handles an "up" keystroke
* when in an autocomplete input
* @param input the dom node where "up" was pressed
* @param info the event method info
* @param event the key event
*/
up(input: HTMLTextInputElement, info: GwMap, event: GwEventType): boolean;
/**
* @private
* Should only be called by the navigation system, handles an "down" keystroke
* when in an autocomplete input
* @param input the dom node where "down" was pressed
* @param info the method info
* @param event the event
*/
down(input: HTMLTextInputElement, info: GwMap, event: GwEventType): boolean;
left(input: HTMLTextInputElement, info: GwMap, event: GwEventType): boolean;
right(input: HTMLTextInputElement, info: GwMap, event: GwEventType): boolean;
}
export declare const gwAutocomplete: GwAutocomplete;
| 17,607
|
https://github.com/Seongkyun-Yu/TIL/blob/master/algorithm-study/programers/level1/findKim.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
TIL
|
Seongkyun-Yu
|
JavaScript
|
Code
| 88
| 315
|
// 서울에서 김서방 찾기
// https://programmers.co.kr/learn/courses/30/lessons/12919
// 문제 설명
// String형 배열 seoul의 element중 Kim의 위치 x를 찾아, 김서방은 x에 있다는 String을 반환하는 함수, solution을 완성하세요. seoul에 Kim은 오직 한 번만 나타나며 잘못된 값이 입력되는 경우는 없습니다.
// 제한 사항
// seoul은 길이 1 이상, 1000 이하인 배열입니다.
// seoul의 원소는 길이 1 이상, 20 이하인 문자열입니다.
// Kim은 반드시 seoul 안에 포함되어 있습니다.
// 입출력 예
// seoul return
// [Jane, Kim] 김서방은 1에 있다
function solution(seoul) {
return `김서방은 ${seoul.findIndex((name) => name === 'Kim')}에 있다`;
}
| 47,958
|
https://github.com/grecosoft/NetFusion/blob/master/netfusion/src/Integration/IntegrationTests/RabbitMQ/PublisherModuleTests.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
NetFusion
|
grecosoft
|
C#
|
Code
| 543
| 2,162
|
using System;
using NetFusion.Bootstrap.Exceptions;
using NetFusion.Messaging.Plugin.Configs;
using NetFusion.Messaging.Types;
using NetFusion.RabbitMQ.Publisher;
using NetFusion.Test.Container;
using Xunit;
namespace IntegrationTests.RabbitMQ
{
/// <summary>
/// The publisher module contains the logic specific to creating exchanges/queues
/// defined by the publishing host.
/// </summary>
public class PublisherModuleTests
{
/// <summary>
/// The publishing application can determine if a given message has an assocated
/// exchange. The publishing application defines exchanges by declaring one or
/// more IExchangeRegistry or ExchangeRegistryBase classes. This information is
/// queried and cached when the NetFusion.RabbitMQ plugin is bootstrapped.
/// </summary>
[Fact]
public void CanDetermineIfMessage_HasAnAssociatedExchange()
{
ContainerFixture.Test(fixture =>
{
fixture.Arrange
.Configuration(TestSetup.AddValidBusConfig)
.Container(c => { c.WithRabbitMqHost(typeof(ValidExchangeRegistry)); })
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Assert.PluginModule<MockPublisherModule>(m =>
{
var isExchangeMsg = m.IsExchangeMessage(typeof(AutoSalesEvent));
Assert.True(isExchangeMsg);
});
});
}
/// <summary>
/// When publishing a message with an assocated exchange, the exchange definition
/// is retrieved and used to declare the exchange on the RabbitMQ message bus.
/// </summary>
[Fact]
public void CanLookupExchangeDefinition_ForMessageType()
{
ContainerFixture.Test(fixture =>
{
fixture.Arrange
.Configuration(TestSetup.AddValidBusConfig)
.Container(c => { c.WithRabbitMqHost(typeof(ValidExchangeRegistry)); })
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Assert.PluginModule<MockPublisherModule>(m =>
{
var definition = m.GetExchangeMeta(typeof(AutoSalesEvent));
Assert.NotNull(definition);
});
});
}
[Fact]
public void RequestingExchangeDefinition_ForNotExchangeMessageType_RaisesException()
{
ContainerFixture.Test(fixture =>
{
fixture.Arrange
.Configuration(TestSetup.AddValidBusConfig)
.Container(c => { c.WithRabbitMqHost(typeof(ValidExchangeRegistry)); })
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Assert.PluginModule<MockPublisherModule>(m =>
{
Assert.Throws<InvalidOperationException>(() => m.GetExchangeMeta(typeof(TestCommand1)));
});
});
}
/// <summary>
/// All exchange names defined a specific message bus must be unique for a given configured host.
/// </summary>
[Fact]
public void ExchangeName_MustBe_Unique_OnSameBus()
{
ContainerFixture.Test(fixture => {
fixture.Arrange
.Configuration(TestSetup.AddValidBusConfig)
.Container(c =>
{
c.WithRabbitMqHost(typeof(DuplicateExchangeRegistry));
})
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Act.RecordException().ComposeContainer()
.Assert.Exception<BootstrapException>(ex =>
{
});
});
}
/// <summary>
/// The same exchange names can be used across different configured hosts.
/// </summary>
[Fact]
public void ExchangeName_CanBeTheSame_OnDifferentBusses()
{
ContainerFixture.Test(fixture => {
fixture.Arrange
.Configuration(TestSetup.AddValidMultipleBusConfig)
.Container(c =>
{
c.WithRabbitMqHost(typeof(ValidDuplicateExchangeRegistry));
})
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Assert.PluginModule<MockPublisherModule>(m =>
{
Assert.NotNull(m.GetExchangeMeta(typeof(TestDomainEvent)));
Assert.NotNull(m.GetExchangeMeta(typeof(TestDomainEvent2)));
});
});
}
/// <summary>
/// All queue names defined a specific message bus must be unique.
/// </summary>
[Fact]
public void QueueName_MustBe_Unique_OnSameBus()
{
ContainerFixture.Test(fixture => {
fixture.Arrange
.Configuration(TestSetup.AddValidBusConfig)
.Container(c =>
{
c.WithRabbitMqHost(typeof(DuplicateQueueRegistry));
})
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Act.RecordException().ComposeContainer()
.Assert.Exception<BootstrapException>(ex =>
{
});
});
}
[Fact]
public void QueueName_CanBeTheSame_OnDifferentBusiness()
{
ContainerFixture.Test(fixture => {
fixture.Arrange
.Configuration(TestSetup.AddValidMultipleBusConfig)
.Container(c =>
{
c.WithRabbitMqHost(typeof(ValidDuplicateQueueRegistry));
})
.PluginConfig((MessageDispatchConfig c) =>
{
c.AddPublisher<RabbitMqPublisher>();
})
.Assert.PluginModule<MockPublisherModule>(m =>
{
Assert.NotNull(m.GetExchangeMeta(typeof(TestCommand1)));
Assert.NotNull(m.GetExchangeMeta(typeof(TestCommand2)));
});
});
}
public class ValidExchangeRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineTopicExchange<AutoSalesEvent>("AutoSales", "TestBus1");
}
}
public class DuplicateExchangeRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineTopicExchange<TestDomainEvent>("AutoSales", "TestBus1");
DefineTopicExchange<TestDomainEvent2>("AutoSales", "TestBus1");
}
}
public class ValidDuplicateExchangeRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineTopicExchange<TestDomainEvent>("AutoSales", "TestBus1");
DefineTopicExchange<TestDomainEvent2>("AutoSales", "TestBus2");
}
}
public class DuplicateQueueRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineWorkQueue<TestCommand1>("GenerateInvoice", "TestBus1");
DefineWorkQueue<TestCommand2>("GenerateInvoice", "TestBus1");
}
}
public class ValidDuplicateQueueRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineWorkQueue<TestCommand1>("GenerateInvoice", "TestBus1");
DefineWorkQueue<TestCommand2>("GenerateInvoice", "TestBus2");
}
}
public class RpcExchangeRegistry : ExchangeRegistryBase
{
protected override void OnRegister()
{
DefineRpcQueue<CalculatePropTax>("Calculations", "CalculatePropTax", "TestBus1");
DefineRpcQueue<CalculateAutoTax>("Calculations", "CalculateAutoTax", "TestBus1");
DefineRpcQueue<GetTaxRates>("LookupReferenceData", "GetTaxRates", "TestBus1");
}
}
public class AutoSalesEvent : DomainEvent
{
}
public class TestCommand1 : Command
{
}
public class TestCommand2 : Command
{
}
public class TestDomainEvent : DomainEvent
{
}
public class TestDomainEvent2 : DomainEvent
{
}
public class CalculatePropTax : Command
{
}
public class CalculateAutoTax : Command
{
}
public class GetTaxRates : Command
{
}
}
}
| 31,471
|
https://github.com/Matyrobbrt/MatyBot/blob/master/src/main/java/io/github/matyrobbrt/matybot/reimpl/BetterMember.java
|
Github Open Source
|
Open Source
|
MIT
| null |
MatyBot
|
Matyrobbrt
|
Java
|
Code
| 53
| 320
|
package io.github.matyrobbrt.matybot.reimpl;
import java.util.List;
import javax.annotation.Nonnull;
import io.github.matyrobbrt.matybot.MatyBot;
import io.github.matyrobbrt.matybot.managers.CustomPingManager.CustomPing;
import io.github.matyrobbrt.matybot.util.database.dao.nbt.LevelData;
import io.github.matyrobbrt.matybot.util.database.dao.nbt.UserSettings;
import net.dv8tion.jda.api.entities.Member;
public interface BetterMember extends Member {
default UserSettings getGlobalSettings() {
return MatyBot.nbtDatabase().getSettingsForUser(getIdLong());
}
default BetterGuild getBetterGuild() {
return new BetterGuildImpl(getGuild());
}
@Nonnull
default LevelData getLevelData() {
return getBetterGuild().getData().getLevelDataForUser(this);
}
default List<CustomPing> getCustomPings() {
return getBetterGuild().getData().getCustomPings(this);
}
}
| 5,031
|
https://github.com/wd1212/mip-extensions-platform/blob/master/mip-zlw/mip-zlw.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
mip-extensions-platform
|
wd1212
|
JavaScript
|
Code
| 13
| 45
|
/**
* @file mip-zlw 组件
* @author
*/
define(function (require) {
'alert("张良伟")';
});
| 4,685
|
https://github.com/elsa-workflows/elsa-core/blob/master/src/activities/Elsa.Activities.Telnyx/Models/ClientStatePayload.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
elsa-core
|
elsa-workflows
|
C#
|
Code
| 48
| 182
|
using System;
using System.Text;
using Newtonsoft.Json;
namespace Elsa.Activities.Telnyx.Models
{
public record ClientStatePayload(string CorrelationId)
{
public static ClientStatePayload FromBase64(string base64)
{
var bytes = Convert.FromBase64String(base64);
var json = Encoding.UTF8.GetString(bytes);
return JsonConvert.DeserializeObject<ClientStatePayload>(json)!;
}
public string ToBase64()
{
var json = JsonConvert.SerializeObject(this);
var bytes = Encoding.UTF8.GetBytes(json);
return Convert.ToBase64String(bytes);
}
}
}
| 9,648
|
https://github.com/Ekevin/kazi_app/blob/master/application/views/home_page.php
|
Github Open Source
|
Open Source
|
MIT
| null |
kazi_app
|
Ekevin
|
PHP
|
Code
| 95
| 465
|
<pre>
<?php //print_r($this->session->userdata); ?>
</pre>
<hr>
<pre>
<?php //var_dump($employee_tasks) ?>
</pre>
<div class="col-md-8 col-md-offset-2">
<div>
<h1>Tasks</h1> <a href="tasks/tasks" title=""><button class="btn btn-success pull-right" name="add task" value="Add Task">Add Task</button></a>
</div>
<table class="table" style="margin-bottom:50px;">
<thead>
<tr>
<th>Project Name</th>
<th>Date Done</th>
<th>Task</th>
<th>Time Taken</th>
<th>Comments</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($employee_tasks as $employee_task):?>
<tr>
<td><?php echo "to do"; ?></td>
<td><?php echo $employee_task["date_done"]; ?></td>
<td><?php echo $employee_task["task"]; ?></td>
<td><?php echo $employee_task["time_taken"]; ?></td>
<td><?php echo $employee_task["comments"]; ?></td>
<td><a href="controller/del/<?php echo $employee_task["eid"]; ?>" title="" class="btn btn-sm btn-primary">Edit</a> | <a href="#" title="" class="btn btn-sm btn-danger">Del</a></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
| 11,249
|
https://github.com/hiqdev/hipanel-module-client/blob/master/tests/acceptance/manager/AssignmentsCest.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
hipanel-module-client
|
hiqdev
|
PHP
|
Code
| 109
| 638
|
<?php
declare(strict_types=1);
namespace hipanel\modules\client\tests\acceptance\manager;
use hipanel\helpers\Url;
use hipanel\tests\_support\Page\IndexPage;
use hipanel\tests\_support\Page\Widget\Input\Input;
use hipanel\tests\_support\Page\Widget\Input\Select2;
use hipanel\tests\_support\Step\Acceptance\Manager;
class AssignmentsCest
{
public function ensureIndexPageWorks(Manager $I): void
{
$index = new IndexPage($I);
$I->login();
$I->needPage(Url::to('@client/assignments/index'));
$I->see('Assignments', 'h1');
$this->ensureICanSeeAdvancedSearchBox($I, $index);
$this->ensureICanSeeBulkSearchBox($I, $index);
$this->ensureICanAssignUser($I, $index);
}
private function ensureICanSeeAdvancedSearchBox(Manager $I, IndexPage $index): void
{
$index->containsFilters([
Input::asAdvancedSearch($I, 'Login'),
Select2::asAdvancedSearch($I, 'Client'),
Select2::asAdvancedSearch($I, 'Reseller'),
]);
}
private function ensureICanSeeBulkSearchBox(Manager $I, IndexPage $index): void
{
$index->containsBulkButtons([
'Set assignments',
]);
$index->containsColumns([
'Login',
'Reseller',
'Type',
'Assignments',
]);
}
private function ensureICanAssignUser(Manager $I, IndexPage $index): void
{
$I->needPage(Url::to('@client/assignments/index'));
$login = $I->grabTextFrom('//tbody//tr[1]//td[2]');
$row = $index->getRowNumberInColumnByValue('Login', $login);
$I->checkOption("//tbody/tr[$row]/td[1]/input");
$I->pressButton('Set assignments');
$I->waitForPageUpdate();
$I->see('Set assignments', 'h1');
$I->see($login, 'strong');
$I->pressButton('Assign');
$I->waitForPageUpdate();
$I->closeNotification('Assignments have been successfully applied.');
$I->seeInCurrentUrl('/assignments/index');
}
}
| 32,633
|
https://github.com/GauriChandaDattatray/Leetcode-June-Challenge/blob/master/Day_28.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Leetcode-June-Challenge
|
GauriChandaDattatray
|
C++
|
Code
| 71
| 292
|
// Time Complexity : O(E)
// Space Complexity : O(E)
// E = # of Edges in Graph
class Solution {
public:
void dfs(string s,unordered_map<string, priority_queue <string, vector<string>, greater<string>>> &m,vector<string> &ans){
if(m[s].empty())
return;
while(!m[s].empty()){
string v= m[s].top();
m[s].pop();
dfs(v,m,ans);
ans.push_back(v);
}
}
vector<string> findItinerary(vector<vector<string>>& tickets) {
vector<string> ans;
if(tickets.empty())
return ans;
unordered_map<string, priority_queue <string, vector<string>, greater<string>>> m;
for(auto i : tickets)
m[i[0]].push(i[1]);
dfs("JFK",m,ans);
ans.push_back("JFK");
reverse(ans.begin() , ans.end());
return ans;
}
};
| 15,422
|
https://github.com/Bagerian/gamebrary/blob/master/src/pages/Settings.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
gamebrary
|
Bagerian
|
Vue
|
Code
| 403
| 1,523
|
<template lang="html">
<modal title="Settings">
<gravatar :email="user.email" class="avatar" v-if="user && user.email" />
<div
slot="content"
class="settings"
>
<game-board-settings v-model="localSettings" @save="save" v-if="isGameBoard" />
<h3>Global</h3>
<tags-settings v-model="localSettings" />
<div class="setting">
<i class="fas fa-sign-out-alt" />
{{ $t('settings.signOut') }}
<button
class="secondary"
@click="signOut"
>
{{ $t('settings.signOut') }}
</button>
</div>
<modal
:message="$t('settings.deleteAccount.message')"
:title="$t('settings.deleteAccount.title')"
:action-text="$t('settings.deleteAccount.button')"
@action="deleteAccount"
>
<div class="setting">
<i class="fas fa-exclamation-triangle" />
{{ $t('settings.deleteAccount.button') }}
<button class="danger">
{{ $t('settings.deleteAccount.button') }}
</button>
</div>
</modal>
</div>
</modal>
</template>
<script>
import { mapState } from 'vuex';
import 'firebase/firestore';
import 'firebase/auth';
import Gravatar from 'vue-gravatar';
import GameBoardSettings from '@/components/Settings/GameBoardSettings';
import SettingsGlobal from '@/components/Settings/SettingsGlobal';
import AboutSettings from '@/components/Settings/AboutSettings';
import TagsSettings from '@/components/Settings/TagsSettings';
import Modal from '@/components/Modal';
import moment from 'moment';
import firebase from 'firebase/app';
import Releases from '@/components/Releases/Releases';
export default {
components: {
Modal,
Releases,
GameBoardSettings,
SettingsGlobal,
AboutSettings,
TagsSettings,
Gravatar,
},
data() {
return {
activeSection: null,
activeComponent: null,
language: null,
reloading: false,
localSettings: null,
moment,
defaultSettings: {
language: 'en',
theme: {
global: 'default',
},
position: {
global: 'top',
},
borderRadius: true,
showGameCount: false,
},
};
},
computed: {
...mapState(['user', 'gameLists', 'settings', 'platform']),
dateJoined() {
return moment(this.user.dateJoined).format('LL');
},
isGameBoard() {
return this.$route.name === 'game-board';
},
exitUrl() {
// TODO: move to getter and replace other instances
return process.env.NODE_ENV === 'development'
? 'http://localhost:3000'
: 'https://gamebrary.com';
},
},
mounted() {
this.localSettings = this.settings !== null
? JSON.parse(JSON.stringify(this.settings))
: JSON.parse(JSON.stringify(this.defaultSettings));
if (this.platform && !this.localSettings[this.platform.code]) {
this.localSettings[this.platform.code] = {
theme: 'default',
position: 'top',
borderRadius: true,
showGameCount: false,
};
}
},
methods: {
save() {
this.$store.dispatch('SAVE_SETTINGS', this.localSettings)
.then(() => {
this.$bus.$emit('TOAST', { message: 'Settings saved' });
})
.catch(() => {
this.$bus.$emit('TOAST', { message: 'There was an error saving your settings', type: 'error' });
this.$router.push({ name: 'sessionExpired' });
});
},
deleteAccount() {
const db = firebase.firestore();
// TODO: Add progress bar, delete tags, files, etc...
// TODO: move to actions
db.collection('settings').doc(this.user.uid).delete()
.then(() => {
// TODO: move to actions
db.collection('lists').doc(this.user.uid).delete()
.then(() => {
this.$bus.$emit('TOAST', { message: 'Account deleted' });
this.exit();
})
.catch(() => {
this.$bus.$emit('TOAST', { message: 'Authentication error', type: 'error' });
this.$router.push({ name: 'sessionExpired' });
});
})
.catch(() => {
this.$bus.$emit('TOAST', { message: 'Authentication error', type: 'error' });
this.$router.push({ name: 'sessionExpired' });
});
},
signOut() {
firebase.auth().signOut()
.then(() => {
this.exit();
})
.catch((error) => {
this.$bus.$emit('TOAST', { message: error, type: 'error' });
});
},
exit() {
this.$store.commit('CLEAR_SESSION');
window.location.href = this.exitUrl;
},
},
};
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
@import "~styles/styles";
$avatarSize: 30px;
.settings {
display: flex;
flex-direction: column;
}
.avatar {
width: $avatarSize;
height: $avatarSize;
border-radius: var(--border-radius);
overflow: hidden;
}
</style>
| 16,229
|
https://github.com/liftchampion/nativejson-benchmark/blob/master/thirdparty/ccan/web/staticmoduleinfo.php
|
Github Open Source
|
Open Source
|
MIT
| null |
nativejson-benchmark
|
liftchampion
|
PHP
|
Code
| 176
| 986
|
<?php
session_start();
include('logo.html');
include('menulist.html');
include('static-configuration');
$module_path=$argv[1];
$module=$argv[2];
$maintainer=extract_field('maintainer',$module_path);
$author=extract_field('author',$module_path);
$summary=extract_field('summary',$module_path);
$see_also=extract_field('see_also',$module_path);
$description=htmlize_field('description',$module_path);
$example=extract_field('example',$module_path);
$dependencies=htmlspecialchars(shell_exec('tools/ccan_depends --direct '.$module_path));
$extdepends=htmlspecialchars(shell_exec('tools/ccan_depends --compile --non-ccan '.$module_path));
$licence=extract_field('licence',$module_path);
$license=extract_field('license',$module_path);
$url_prefix = getenv("URLPREFIX");
?>
<div class='content moduleinfo'>
<p><a href="<?=$repo_base.$module?>">Browse Source</a> <a href="<?=$url_prefix?><?=$tar_dir?>/with-deps/<?=$module?>.tar.bz2">Download</a> <a href="<?=$url_prefix?><?=$tar_dir?>/<?=$module?>.tar.bz2">(without any required ccan dependencies)</a></p>
<h3>Module:</h3>
<p><?=$module?></p>
<h3>Summary:</h3>
<p><?=$summary?></p>
<?php
if ($maintainer) {
?>
<h3>Maintainer:</h3>
<p><?=$maintainer?></p>
<?php
}
if ($author) {
?>
<h3>Author:</h3>
<p><?=$author?></p>
<?php
}
if ($dependencies) {
?>
<h3>Dependencies:</h3>
<ul class='dependencies'>
<?php
foreach (preg_split("/\s+/", $dependencies) as $dep) {
if ($dep) {
echo '<li><a href="'.substr($dep, 5).'.html">'.$dep.'</a></li>';
}
}
?>
</ul>
<?php
}
if ($extdepends) {
?>
<h3>External dependencies:</h3>
<ul class='external-dependencies'>
<?php
foreach (split("\n", $extdepends) as $dep) {
$fields=preg_split("/\s+/", $dep);
echo "<li>" . $fields[0].' ';
if (count($fields) > 1)
echo '(version '.$fields[1].') ';
echo '</li>';
}
?>
</ul>
<?php
}
?>
<h3>Description:</h3>
<p><?=$description;?></p>
<?php
if ($see_also) {
?>
<h3>See Also:</h3>
<ul class='see-also'>
<?php
foreach (preg_split("/[\s,]+/", trim($see_also)) as $see) {
echo '<li><a href="'.substr($see, 5).'.html">'.$see.'</a></li>';
}
?>
</ul>
<?php
}
if ($example) {
?>
<h3>Example:</h3>
<pre class="prettyprint">
<code class="language-c"><?=$example?></code>
</pre>
<?php
}
if ($license) {
?>
<h3>License:</h3>
<p><?=$license?></p>
<?php
}
?>
</div>
</body></html>
| 48,280
|
https://github.com/amedama41/bulb/blob/master/include/canard/net/ofp/v10/flow_entry.hpp
|
Github Open Source
|
Open Source
|
BSL-1.0
| null |
bulb
|
amedama41
|
C++
|
Code
| 496
| 1,745
|
#ifndef CANARD_NET_OFP_V10_FLOW_ENTRY_HPP
#define CANARD_NET_OFP_V10_FLOW_ENTRY_HPP
#include <cstdint>
#include <utility>
#include <boost/operators.hpp>
#include <canard/net/ofp/v10/action_list.hpp>
#include <canard/net/ofp/v10/common/match.hpp>
namespace canard {
namespace net {
namespace ofp {
namespace v10 {
class flow_entry_id
: private boost::equality_comparable<flow_entry_id>
{
public:
flow_entry_id(
v10::match const& match, std::uint16_t const priority) noexcept
: match_(match)
, priority_(priority)
{
}
auto match() const noexcept
-> v10::match const&
{
return match_;
}
auto priority() const noexcept
-> std::uint16_t
{
return priority_;
}
static auto table_miss() noexcept
-> flow_entry_id
{
return flow_entry_id{v10::match{}, 0};
}
private:
v10::match match_;
std::uint16_t priority_;
};
inline auto operator==(
flow_entry_id const& lhs, flow_entry_id const& rhs) noexcept
-> bool
{
return lhs.priority() == rhs.priority()
&& equivalent(lhs.match(), rhs.match());
}
class flow_entry
: private boost::equality_comparable<flow_entry>
{
public:
flow_entry(
flow_entry_id const& identifer
, std::uint64_t const cookie
, action_list actions)
: identifier_(identifer)
, cookie_(cookie)
, actions_(std::move(actions))
{
}
flow_entry(
v10::match const& match
, std::uint16_t const priority
, std::uint64_t const cookie
, action_list actions)
: identifier_{match, priority}
, cookie_(cookie)
, actions_(std::move(actions))
{
}
auto id() const noexcept
-> flow_entry_id const&
{
return identifier_;
}
auto match() const noexcept
-> v10::match const&
{
return id().match();
}
auto priority() const noexcept
-> std::uint16_t
{
return id().priority();
}
auto cookie() const noexcept
-> std::uint64_t
{
return cookie_;
}
auto actions() const& noexcept
-> action_list const&
{
return actions_;
}
auto actions() && noexcept
-> action_list&&
{
return std::move(actions_);
}
void actions(action_list actions)
{
actions_ = std::move(actions);
}
private:
flow_entry_id identifier_;
std::uint64_t cookie_;
action_list actions_;
};
inline auto operator==(
flow_entry const& lhs, flow_entry const& rhs) noexcept
-> bool
{
return lhs.cookie() == rhs.cookie()
&& lhs.id() == rhs.id()
&& equivalent(lhs.actions(), rhs.actions());
}
class timeouts
: private boost::equality_comparable<timeouts>
{
public:
constexpr timeouts(
std::uint16_t const idle_timeout
, std::uint16_t const hard_timeout) noexcept
: idle_timeout_(idle_timeout)
, hard_timeout_(hard_timeout)
{
}
constexpr auto idle_timeout() const noexcept
-> std::uint16_t
{
return idle_timeout_;
}
constexpr auto hard_timeout() const noexcept
-> std::uint16_t
{
return hard_timeout_;
}
private:
std::uint16_t idle_timeout_;
std::uint16_t hard_timeout_;
};
constexpr auto operator==(timeouts const& lhs, timeouts const& rhs) noexcept
-> bool
{
return lhs.idle_timeout() == rhs.idle_timeout()
&& lhs.hard_timeout() == rhs.hard_timeout();
}
class counters
: private boost::equality_comparable<counters>
{
public:
constexpr counters(
std::uint64_t const packet_count
, std::uint64_t const byte_count) noexcept
: packet_count_(packet_count)
, byte_count_(byte_count)
{
}
constexpr auto packet_count() const noexcept
-> std::uint64_t
{
return packet_count_;
}
constexpr auto byte_count() const noexcept
-> std::uint64_t
{
return byte_count_;
}
private:
std::uint64_t packet_count_;
std::uint64_t byte_count_;
};
constexpr auto operator==(counters const& lhs, counters const& rhs) noexcept
-> bool
{
return lhs.packet_count() == rhs.packet_count()
&& lhs.byte_count() == rhs.byte_count();
}
class elapsed_time
: private boost::equality_comparable<elapsed_time>
{
public:
constexpr elapsed_time(
std::uint32_t const duration_sec
, std::uint32_t const duration_nsec) noexcept
: duration_sec_(duration_sec)
, duration_nsec_(duration_nsec)
{
}
constexpr auto duration_sec() const noexcept
-> std::uint32_t
{
return duration_sec_;
}
constexpr auto duration_nsec() const noexcept
-> std::uint32_t
{
return duration_nsec_;
}
private:
std::uint32_t duration_sec_;
std::uint32_t duration_nsec_;
};
constexpr auto operator==(
elapsed_time const& lhs, elapsed_time const& rhs) noexcept
-> bool
{
return lhs.duration_sec() == rhs.duration_sec()
&& lhs.duration_nsec() == rhs.duration_nsec();
}
} // namespace v10
} // namespace ofp
} // namespace net
} // namespace canard
#endif // CANARD_NET_OFP_V10_FLOW_ENTRY_HPP
| 18,222
|
https://github.com/arushanovanz/java_automation/blob/master/sandbox/src/test/java/ru/stqa/pft/sandbox/catalog/MobilePhonesPage.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
java_automation
|
arushanovanz
|
Java
|
Code
| 21
| 109
|
package ru.stqa.pft.sandbox.catalog;
import com.codeborne.selenide.SelenideElement;
import org.testng.annotations.Listeners;
import static com.codeborne.selenide.Selenide.$;
public class MobilePhonesPage {
public void addMobilePhoneToCompareList(SelenideElement locator) {
$(locator).click();
}
}
| 32,700
|
https://github.com/eclipse-ee4j/metro-jwsdp-samples/blob/master/jamazon/src/com/sun/jamazon/DetailsTableModel.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
metro-jwsdp-samples
|
eclipse-ee4j
|
Java
|
Code
| 1,119
| 3,368
|
/*
* Copyright (c) 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.jamazon;
import java.awt.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.table.*;
import myamazonclient.AmazonClientGenClient.Details;
import myamazonclient.AmazonClientGenClient.Reviews;
import myamazonclient.AmazonClientGenClient.CustomerReview;
/**
* A table model which encapsulates the details returned
* from the Amazon.com web service.
*
* @author Mark Davidson, Sun Microsystems, Inc.
*/
public class DetailsTableModel extends SortableTableModel {
private static final Float FLOAT_ZERO = new Float(0f);
private List details;
public DetailsTableModel() {
details = null;
}
public DetailsTableModel(Details[] details) {
setDetails(details);
}
public void setDetails(Details[] details) {
if (details == null) {
return;
}
this.details = new ArrayList();
this.details.addAll(Arrays.asList(details));
// Required for the SortableTableModel
setRowElements(this.details);
fireTableDataChanged();
}
public void addDetails(Details[] newDetails) {
if (newDetails == null) {
return;
}
int firstRow = details.size();
for (int i = 0; i < newDetails.length; i++) {
details.add(newDetails[i]);
}
fireTableRowsInserted(firstRow, firstRow + newDetails.length);
}
/**
* Returns the number of columns.
*/
public int getColumnCount() {
return DetailsColumnModel.NUM_COLUMNS;
}
public int getRowCount() {
return (details != null ? details.size() : 0);
}
/**
* Get text value for cell of table
* @param row table row
* @param col table column
*/
public Object getValueAt(int row, int col) {
return getValueForColumn(getDetails(row), col);
}
/**
* Overridden to sorting of the rows of details.
*/
public Object getValueForColumn(Object obj, int column) {
if (obj instanceof Details) {
Details details = (Details)obj;
switch (column) {
case DetailsColumnModel.IDX_TITLE:
return details.getProductName();
case DetailsColumnModel.IDX_AUTHOR:
String author = "[ no author ]";
String[] authors = details.getAuthors();
if (authors != null) {
author = authors[0];
if (authors.length > 1) {
// multiple authors
author += ", et al";
}
}
return author;
case DetailsColumnModel.IDX_LIST_PRICE:
return getFloatFromPrice(details.getListPrice());
case DetailsColumnModel.IDX_AMAZ_PRICE:
return getFloatFromPrice(details.getOurPrice());
case DetailsColumnModel.IDX_RATING:
Reviews reviews = details.getReviews();
return (reviews == null ? "" : reviews.getAvgCustomerRating());
}
}
return null;
}
public float getPrice(int row) {
Float f = (Float)getValueAt(row, DetailsColumnModel.IDX_AMAZ_PRICE);
if (f != null) {
return f.floatValue();
}
return 0f;
}
/**
* Create a page with the product details
* TODO: hand coding html in Java is tedious and unmainatinable. Should
* probably use a template and define tags which can be replaced.
*/
public String getProductDetails(int row) {
Details details = getDetails(row);
if (details == null) {
return "<html><body><i>No product details</i></body></html>";
}
// Html header
StringBuffer buffer = new StringBuffer("<html><head></head><body>");
buffer.append("<table><tr><td><img src=\"").append(details.getImageUrlMedium());
buffer.append("\"></td><td style=\"vertical-align: top;\"");
buffer.append("<h2>").append(details.getProductName()).append("</h2>");
buffer.append("<p><b>Publisher: </b>").append(details.getManufacturer());
buffer.append("; (").append(details.getReleaseDate());
buffer.append(")<br><b>ISBN: </b>").append(details.getIsbn());
buffer.append("<br><b>Sales Rank: </b>").append(details.getSalesRank());
buffer.append("</td></tr></table>");
Reviews reviews = details.getReviews();
if (reviews != null) {
buffer.append("<b>Average Customer Review: </b>");
buffer.append(reviews.getAvgCustomerRating());
buffer.append(" Based on ").append(reviews.getTotalCustomerReviews());
buffer.append(" reviews<p><hr>");
CustomerReview[] crevs = reviews.getCustomerReviews();
for (int i = 0; i < crevs.length; i++) {
CustomerReview rev = crevs[i];
buffer.append("<b>Rating: ").append(rev.getRating()).append(" ");
buffer.append(rev.getSummary()).append("</b><p>");
buffer.append(rev.getComment()).append("<p>");
}
}
buffer.append("</body></html>");
return buffer.toString();
}
public URL getProductURL(int row) {
Details details = getDetails(row);
URL url = null;
if (details != null) {
try {
url = new URL(details.getUrl());
} catch (MalformedURLException ex) {
// drop through
}
}
return url;
}
private Details getDetails(int row) {
if (details == null) {
return null;
}
if (row > details.size()) {
return null;
}
return (Details)details.get(row);
}
/**
* Converts the Amazon string representation of a price "$99.99"
* To a float type.
*/
public static Float getFloatFromPrice(String value) {
Float fval = FLOAT_ZERO;
if (value != null && !"".equals(value)) {
if (value.startsWith("$")) {
value = value.substring(1);
}
try {
Number nval = DecimalFormat.getInstance().parse(value);
fval = new Float(nval.floatValue());
} catch (ParseException ex) {
//
}
}
return fval;
}
/**
* The renderer component must be non-opaque and the selection is semi-transparant.
*/
public static class AmazonTableCellRenderer extends DefaultTableCellRenderer {
protected boolean isSelected = false;
protected Color selectionColor;
public AmazonTableCellRenderer() {
setOpaque(false);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
if (selectionColor == null) {
// we'll use a translucent version of the table's default
// selection color to paint selections
Color oldCol = table.getSelectionBackground();
selectionColor = new Color(oldCol.getRed(), oldCol.getGreen(),
oldCol.getBlue(), 128);
}
// save the selected state since we'll need it when painting
this.isSelected = isSelected;
return super.getTableCellRendererComponent(table, value,
isSelected, hasFocus,
row, column);
}
// since DefaultTableCellRenderer is really just a JLabel, we can override
// paintComponent to paint the translucent selection when necessary
public void paintComponent(Graphics g) {
if (isSelected) {
g.setColor(selectionColor);
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g);
}
}
public static class DetailsColumnModel extends DefaultTableColumnModel {
private final static String COL_LABEL_IMAGE = "Image";
private final static String COL_LABEL_TITLE = "Title";
private final static String COL_LABEL_AUTHOR = "Author";
private final static String COL_LABEL_LIST_PRICE = "List Price";
private final static String COL_LABEL_AMAZ_PRICE = "Amazon Price";
private final static String COL_LABEL_RATING = "Rating";
public static final int NUM_COLUMNS = 5;
// Column indexes
public final static int IDX_TITLE = 0;
public final static int IDX_AUTHOR = 1;
public final static int IDX_LIST_PRICE = 2;
public final static int IDX_AMAZ_PRICE = 3;
public final static int IDX_RATING = 4;
private static final int SMALL_WIDTH = 100;
private static final int MED_WIDTH = 200;
private static final int LARGE_WIDTH = 400;
public DetailsColumnModel() {
// Configure the columns and add them to the model
addColumn(IDX_TITLE, COL_LABEL_TITLE, LARGE_WIDTH, null);
addColumn(IDX_AUTHOR, COL_LABEL_AUTHOR, MED_WIDTH, null);
addColumn(IDX_LIST_PRICE, COL_LABEL_LIST_PRICE, SMALL_WIDTH, new PriceRenderer());
addColumn(IDX_AMAZ_PRICE, COL_LABEL_AMAZ_PRICE, SMALL_WIDTH, new PriceRenderer());
addColumn(IDX_RATING, COL_LABEL_RATING, SMALL_WIDTH, new RatingRenderer());
}
private void addColumn(int index, String header,
int width, TableCellRenderer renderer) {
TableColumn column = new TableColumn(index, width, renderer, null);
column.setHeaderValue(header);
addColumn(column);
}
/**
* A renderer which can correctly render prices
*/
class PriceRenderer extends AmazonTableCellRenderer {
protected void setValue(Object value) {
Float f = (Float)value;
NumberFormat nf = NumberFormat.getCurrencyInstance();
setText(nf.format(f.doubleValue()));
setHorizontalAlignment(SwingConstants.CENTER);
}
}
/**
* Renders the rating value as an ImageIcon of stars.
*/
class RatingRenderer extends AmazonTableCellRenderer {
private float mult;
private Image img0;
private Image img5;
private int width;
private int height;
public RatingRenderer() {
img0 = JAmazon.getImage("resources/stars-0-0.png", this);
img5 = JAmazon.getImage("resources/stars-5-0.png", this);
width = img5.getWidth(null);
height = img5.getHeight(null);
}
protected void setValue(Object value) {
setToolTipText((String)value);
// Calculate multiple;
try {
float fval = (new Float((String)value)).floatValue();
mult = fval/5f;
} catch (NumberFormatException ex) {
mult = 0f;
super.setValue(value);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w2 = (int)(width * mult);
// Calculate the starting position based on the alignment
int x = 0;
int y = 0;
// TODO: default is center, use the alignment attributes.
Dimension size = this.getSize();
x = (int)((size.width - width)/2);
y = (int)((size.height - height)/2);
g.translate(x, y);
g.drawImage(img0, 0, 0, this);
g.drawImage(img5, 0, 0, w2, height, 0, 0, w2, height, this);
g.translate(-x, -y);
}
}
}
}
| 9,705
|
https://github.com/yshalabi/VMExit-Delay/blob/master/timeExit.c
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
VMExit-Delay
|
yshalabi
|
C
|
Code
| 219
| 693
|
#include "stdio.h"
#include "unistd.h"
#include "assert.h"
#include "stdlib.h"
#include <sys/syscall.h>
#define __USE_GNU
#include "sched.h"
#include <inttypes.h>
void usage(){
printf("use -v to specify number of vm exits to cause\n");
}
__inline__ uint64_t
get_tsc(void) {
uint32_t lo, hi;
//if rdtscp is not available on your system, change to rdtsc
//and add a cpuid instruction before (for serialization)
//make sure its __volatile__ flagged or compiler will rudely
//move it around
__asm__ __volatile__ ("rdtscp" : "=a" (lo), "=d" (hi));
return (uint64_t)hi << 32 | lo;
}
//Code is written for readability..
int main(int argc, char ** argv){
if(argc < 2){
printf("pass in the number of trials\n");
return 0;
}
uint64_t ntimes_per_measurement, totalCycles, time_per_exit, numVMExits, exit_begin, exit_end, overhead_end, overhead_begin;
int numTrials = atoi(argv[1]);
ntimes_per_measurement = 10;
uint64_t results[numTrials];
int i = 0;
while(numTrials--){
numVMExits = ntimes_per_measurement;
exit_begin = get_tsc();
//time 1mil hypercalls to get vmexit cost
while(numVMExits--){
syscall(314,0);
}
exit_end = get_tsc();
numVMExits = ntimes_per_measurement;
//Time the overhead of making a syscall
//syscall 315 is basically a noop syscall
overhead_begin = get_tsc();
while(numVMExits--){
syscall(315,0);
}
overhead_end = get_tsc();
//total cycles is number of cycles for vmexits - number for noop syscall
totalCycles = (exit_end - exit_begin) - (overhead_end - overhead_begin);
time_per_exit = totalCycles / ntimes_per_measurement;
results[i++] = time_per_exit;
}
//dump output in csv format
while(i--){
printf("%" PRIu64 "",results[i]);
if(i) printf(",");
}
return 0;
}
| 25,764
|
https://github.com/dodolica/covernews-copil/blob/master/inc/hooks/hook-blocks.php
|
Github Open Source
|
Open Source
|
MIT
| null |
covernews-copil
|
dodolica
|
PHP
|
Code
| 39
| 159
|
<?php
if (!function_exists('covernews_page_layout_blocks')) :
/**
*
* @since CoverNews 1.0.0
*
* @param null
* @return null
*
*/
function covernews_page_layout_blocks( $archive_layout='full' ) {
$archive_layout = covernews_get_option('archive_layout');
switch ($archive_layout) {
case "archive-layout-grid":
covernews_get_block('grid');
break;
default:
covernews_get_block('full');
}
}
endif;
| 43,167
|
https://github.com/HITS-MBM/gromacs-developments/blob/master/src/programs/mdrun/tests/simulatorcomparison.cpp
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,022
|
gromacs-developments
|
HITS-MBM
|
C++
|
Code
| 528
| 1,284
|
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2019,2020, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
/*! \internal \file
* \brief
* Helper functions for tests that compare the results of equivalent
* simulation runs. Currently used for the rerun and the simulator
* tests
*
* \author Mark Abraham <mark.j.abraham@gmail.com>
* \author Pascal Merz <pascal.merz@me.com>
* \ingroup module_mdrun_integration_tests
*/
#include "gmxpre.h"
#include "simulatorcomparison.h"
#include "gromacs/trajectory/energyframe.h"
#include "energyreader.h"
#include "mdruncomparison.h"
#include "moduletest.h"
#include "trajectoryreader.h"
namespace gmx
{
namespace test
{
void runGrompp(SimulationRunner* runner, const std::vector<SimulationOptionTuple>& options)
{
CommandLine caller;
caller.append("grompp");
for (const std::tuple<std::string, std::string>& option : options)
{
caller.addOption(std::get<0>(option).c_str(), std::get<1>(option));
}
EXPECT_EQ(0, runner->callGrompp(caller));
}
void runMdrun(SimulationRunner* runner, const std::vector<SimulationOptionTuple>& options)
{
CommandLine caller;
caller.append("mdrun");
for (const std::tuple<std::string, std::string>& option : options)
{
caller.addOption(std::get<0>(option).c_str(), std::get<1>(option));
}
EXPECT_EQ(0, runner->callMdrun(caller));
}
void compareEnergies(const std::string& edr1Name,
const std::string& edr2Name,
const EnergyTermsToCompare& energyTermsToCompare,
const MaxNumFrames maxNumFrames)
{
// Build the functor that will compare energy frames on the chosen
// energy terms.
EnergyComparison energyComparison(energyTermsToCompare, maxNumFrames);
// Build the manager that will present matching pairs of frames to compare.
//
// TODO Here is an unnecessary copy of keys (ie. the energy term
// names), for convenience. In the future, use a range.
auto namesOfEnergiesToMatch = energyComparison.getEnergyNames();
FramePairManager<EnergyFrameReader> energyManager(
openEnergyFileToReadTerms(edr1Name, namesOfEnergiesToMatch),
openEnergyFileToReadTerms(edr2Name, namesOfEnergiesToMatch));
// Compare the energy frames.
energyManager.compareAllFramePairs<EnergyFrame>(energyComparison);
}
void compareTrajectories(const std::string& trajectory1Name,
const std::string& trajectory2Name,
const TrajectoryComparison& trajectoryComparison)
{
// Build the manager that will present matching pairs of frames to compare
FramePairManager<TrajectoryFrameReader> trajectoryManager(
std::make_unique<TrajectoryFrameReader>(trajectory1Name),
std::make_unique<TrajectoryFrameReader>(trajectory2Name));
// Compare the trajectory frames.
trajectoryManager.compareAllFramePairs<TrajectoryFrame>(trajectoryComparison);
}
} // namespace test
} // namespace gmx
| 14,756
|
https://github.com/lai-nam/NLP/blob/master/client/js/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
NLP
|
lai-nam
|
JavaScript
|
Code
| 32
| 119
|
function POST() {
var category = document.getElementById("nlp_category").value;
var content = document.getElementById("nlp_content").value;
$.ajax({
url: "/api/documents/",
dataType: "application/json",
data: JSON.stringify({
category: category,
content: content
}),
type: "POST",
complete: function(err, data){
alert("ok");
}
});
}
| 28,897
|
https://github.com/RepoCamp/Duke-B/blob/master/spec/forms/hyrax/image_form_spec.rb
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Duke-B
|
RepoCamp
|
Ruby
|
Code
| 47
| 143
|
# Generated via
# `rails generate hyrax:work Image`
require 'rails_helper'
RSpec.describe Hyrax::ImageForm do
subject { form }
let(:image) { Image.new }
let(:ability) { Ability.new(nil) }
let(:request) { nil }
let(:form) { described_class.new(image, ability, request) }
it "has the expected terms" do
expect(form.terms).to include(:title)
expect(form.terms).to include(:year)
end
end
| 29,493
|
https://github.com/ToastBuster/BlockQuest/blob/master/src/main/java/me/robifoxx/blockquest/command/sub/GuideCommand.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
BlockQuest
|
ToastBuster
|
Java
|
Code
| 189
| 563
|
package me.robifoxx.blockquest.command.sub;
import me.robifoxx.blockquest.BlockQuest;
import me.robifoxx.blockquest.api.BlockQuestAPI;
import me.robifoxx.blockquest.api.BlockQuestSeries;
import me.robifoxx.blockquest.command.SubCommand;
import org.bukkit.command.CommandSender;
public class GuideCommand extends SubCommand {
@Override
public String getBase() {
return "guide";
}
@Override
public void onCommand(BlockQuest plugin, CommandSender sender, String[] args) {
sender.sendMessage("§7§m----------------------------------------");
sender.sendMessage(" §2§l1) §aFirst, create a series using the following command:");
sender.sendMessage(" §7 /blockquest series §8myseries §7create");
sender.sendMessage(" §a You can change §8myseries §ato anything you want, such as §8christmas§a, §8halloween§a, etc.");
sender.sendMessage(" §2§l2) §aPlace down a block, or a player head, which you want to be a hidden block.");
sender.sendMessage(" §2§l3) §aType the following command:");
sender.sendMessage(" §7 /blockquest series §8myseries §7edit");
sender.sendMessage(" §a Don't forget to change §8myseries §ato whatever you named your series to.");
sender.sendMessage(" §2§l4) §aRepeat step 2 and 3 until you have enough blocks");
sender.sendMessage(" §2§l5) §aOpen BlockQuest's config.yml, find your series, and change the commands to fit your needs");
sender.sendMessage(" §2§l6) §aAfter making the changes, save the config, and restart the server");
sender.sendMessage(" §2§l7) §aDon't forget to enable your Series by running the following command:");
sender.sendMessage(" §7 /blockquest series §8myseries §7toggle");
sender.sendMessage(" §a Don't forget to change §8myseries §ato whatever you named your series to.");
sender.sendMessage("§7§m----------------------------------------");
}
}
| 25,370
|
https://github.com/Mikhail-Aoun/netcdf-java/blob/master/cdm-test/src/timing/java/ucar/nc2/util/xml/TimeJdomReading.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
netcdf-java
|
Mikhail-Aoun
|
Java
|
Code
| 189
| 547
|
/*
* Copyright (c) 1998-2018 University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
package ucar.nc2.internal.util.xml;
import org.jdom2.input.SAXBuilder;
import org.jdom2.*;
import ucar.unidata.util.Format;
import java.io.IOException;
import java.util.List;
public class TimeJdomReading {
TimeJdomReading(String filename) throws IOException {
long start = System.currentTimeMillis();
int count = 0;
org.jdom2.Document doc;
try {
SAXBuilder builder = new SAXBuilder();
doc = builder.build(filename);
} catch (JDOMException e) {
throw new IOException(e.getMessage());
}
Element root = doc.getRootElement();
List<Element> metars = root.getChildren("metar");
for (Element metar : metars) {
List<Element> data = metar.getChildren("data");
for (Element datum : data) {
String name = datum.getAttributeValue("name");
String val = datum.getText();
MetarField fld = MetarField.fields.get(name);
if (null == fld)
fld = new MetarField(name);
fld.sum(val);
}
count++;
}
System.out.println("Read from NetCDF; # metars= " + count);
double took = .001 * (System.currentTimeMillis() - start);
System.out.println(" that took = " + took + " sec; " + Format.d(count / took, 0) + " metars/sec");
System.out.println(" memory= " + Runtime.getRuntime().totalMemory());
for (MetarField f : MetarField.fields.values())
System.out.println(" " + f.name + " = " + f.sum);
}
public static void main(String args[]) throws IOException {
String dir = "C:/doc/metarEncoding/save/";
new TimeJdomReading(dir + "xmlC.xml");
}
}
| 34,005
|
https://github.com/jocimar-dev/orange-talents-01-template-casa-do-codigo/blob/master/src/main/java/com/br/zup/casadocodigo/compras/ItemPedido.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
orange-talents-01-template-casa-do-codigo
|
jocimar-dev
|
Java
|
Code
| 166
| 527
|
package com.br.zup.casadocodigo.compras;
import com.br.zup.casadocodigo.cadastrolivro.Livro;
import javax.persistence.Embeddable;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import java.math.BigDecimal;
@Embeddable
public class ItemPedido {
@ManyToOne
private @NotNull Livro livro;
private @Positive int quantidade;
@Positive
private BigDecimal precoMomento;
@Deprecated
public ItemPedido() {
}
public ItemPedido(@NotNull Livro livro, @Positive int quantidade) {
this.livro = livro;
this.quantidade = quantidade;
this.precoMomento = livro.getPreco();
}
@Override
public String toString() {
return "ItemPedido [livro=" + livro + ", quantidade=" + quantidade
+ ", precoMomento=" + precoMomento + "]";
}
public BigDecimal total() {
return precoMomento.multiply(new BigDecimal(quantidade));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((livro == null) ? 0 : livro.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ItemPedido other = (ItemPedido) obj;
if (livro == null) {
if (other.livro != null)
return false;
} else if (!livro.equals(other.livro))
return false;
return true;
}
}
| 38,530
|
https://github.com/toni-moreno/resistor/blob/master/src/app/core/http.service.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
resistor
|
toni-moreno
|
TypeScript
|
Code
| 363
| 1,261
|
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import {
Http,
RequestOptions,
RequestOptionsArgs,
Response,
Request,
Headers,
XHRBackend
} from '@angular/http';
import { Router } from '@angular/router';
import { DefaultRequestOptions } from './default-request.options';
import { LoaderService } from './loader/loader.service';
@Injectable()
export class HttpService extends Http {
public router : Router;
protected headersUpload: Headers;
constructor(
backend: XHRBackend,
defaultOptions: DefaultRequestOptions,
private loaderService: LoaderService,
public _router : Router
) {
super(backend, defaultOptions);
this.router = _router;
}
get(url: string, options?: RequestOptionsArgs ): Observable<any> {
return super.get(this.getFullUrl(url), this.requestOptions(options))
.catch(this.onCatch.bind(this))
.do((res: Response) => {
}, (error: any) => {
this.onError(error);
})
.finally(() => {
this.onEnd();
});
}
post(url: string, data:any, options?: RequestOptionsArgs, hideAlert? : boolean ): Observable<any> {
return super.post(this.getFullUrl(url), data, this.requestOptions(options))
.catch(this.onCatch.bind(this))
.do((res: Response) => {
if (!hideAlert) this.onSuccess(res);
}, (error: any) => {
this.onError(error);
})
.finally(() => {
this.onEnd();
});
}
postFile(url:string, data:any, options?: RequestOptionsArgs) : Observable<any> {
if (options == null) options = {};
options.headers = this.headersUpload;
return super.post(this.getFullUrl(url), data, options)
.catch(this.onCatch.bind(this))
.do((res: Response) => {
this.onSuccess(res);
}, (error: any) => {
this.onError(error);
})
.finally(() => {
this.onEnd();
});
}
put(url: string, data:any, options?: RequestOptionsArgs, hideAlert? : boolean ): Observable<any> {
return super.put(this.getFullUrl(url), data, this.requestOptions(options))
.catch(this.onCatch.bind(this))
.do((res: Response) => {
if (!hideAlert) this.onSuccess(res);
}, (error: any) => {
this.onError(error);
})
.finally(() => {
this.onEnd();
});
}
delete(url: string, options?: RequestOptionsArgs ): Observable<any> {
return super.delete(this.getFullUrl(url), this.requestOptions(options))
.catch(this.onCatch.bind(this))
.do((res: Response) => {
this.onSuccess(res);
}, (error: any) => {
this.onError(error);
})
.finally(() => {
this.onEnd();
});
}
private requestOptions(options?: RequestOptionsArgs): RequestOptionsArgs {
if (options == null) {
options = new DefaultRequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
return options;
}
private getFullUrl(url: string): string {
return encodeURI(url);
}
private onCatch(error: any, caught: Observable<any>): Observable<any> {
if (error['status'] == 403) {
this.router.navigate(['/sign-in']);
}else if (error['status'] == 0) {
//alert('Server seems not being running...');
this.loaderService.show('Server seems not being running...','danger');
} else if (error['status'] == 404 || error['status'] == 400 || error['status'] == 422) {
console.log(error);
this.loaderService.show(error,'danger');
//alert('CODE :'+error.status +'\n'+"ERROR: \t"+error['_body']);
}
return Observable.throw(error);
}
private onSuccess(res: Response): void {
console.log('Request successful',res);
this.loaderService.show(res,'success');
}
private onError(res: Response): void {
console.log('Error, status code: ' + res.status);
}
onEnd() {
console.log("finished");
}
}
| 26,255
|
https://github.com/urbanvas/GIPHY_API/blob/master/src/actions/userActions.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
GIPHY_API
|
urbanvas
|
JavaScript
|
Code
| 56
| 106
|
import userTypes from '../constants/userConstants';
// favroites are taken directly from the search results so they dont ahve to be reloaded/ refetched
// after users add favorites it is stored into the redux store and saved there even after new
// fetchs to the GIPHY API
export const addFavorite = (favorite) => ({
type: userTypes.ADD_TO_FAVORITES,
favorite
});
| 37,692
|
https://github.com/winfred958/kylin-operation/blob/master/kylin_cmd.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
kylin-operation
|
winfred958
|
Python
|
Code
| 57
| 221
|
# encoding: utf-8
"""
@author: kevin
@contact: kevin_678@126.com
@file: kylin_cmd.py
@time: 2018/3/23 15:28
@desc:
"""
from core import parameter_handle
from service import kylin_handler
from utils.logging_util import LogUtil
if __name__ == '__main__':
log = LogUtil()
parameter = parameter_handle.get_parse_args()
log.info("--operation {}".format(parameter.operation))
if parameter.operation is None:
log.info("--operation {}, is None exit -1".format(parameter.operation))
exit(-1)
else:
return_code = kylin_handler.operation_request(parameter)
log.info("exit {}".format(return_code))
exit(return_code)
| 47,239
|
https://github.com/sqf-ice/meshNetwork/blob/master/python/mesh/generic/serialComm.py
|
Github Open Source
|
Open Source
|
NASA-1.3
| null |
meshNetwork
|
sqf-ice
|
Python
|
Code
| 327
| 763
|
import time
import crcmod.predefined
class SerialComm(object):
"""Serial communication wrapper class that provides for serializing data to send over serial data links.
This class is the base class for serial communication and provides reading and writing functionality over the provided serial connection. Messages being sent and received are relayed using a SLIP message format which provides a CRC for data quality checking.
Attributes:
uartNumBytesToRead: Maximum number of bytes to attempt to read from the serial connection.
serialConn: Serial connection instance used by this class for communication.
serMsgParser: Serial message parser that parses raw serial data and looks for valid SLIP messages.
lastMsgSentTime: Time that the last serial message was sent over this connection.
msgCounter: Counter of the number of messages sent over this serial connection.
msgOut: SLIPmsg instance used for storing messages prior to sending over serial line.
rxBuffer: Raw serial data read from this connection.
msgEnd: Array location of end of raw serial message decoded from read serial bytes stored in rxBuffer.
"""
def __init__(self, commProcessor, radio, parser):
self.radio = radio
self.msgParser = parser
self.commProcessor = commProcessor
self.lastMsgSentTime = 0
self.msgCounter = 0
def readMsgs(self):
"""Reads and parses any received serial messages."""
# Read bytes
self.readBytes(False)
# Parse messages
self.parseMsgs()
def parseMsgs(self):
# Parse messages
self.msgParser.parseMsgs(self.radio.getRxBytes())
# Clear rx buffer
self.radio.clearRxBuffer()
def readBytes(self, bufferFlag=False):
"""Reads raw bytes from radio"""
self.radio.readBytes(bufferFlag)
def sendBytes(self, msgBytes): # DEPRECATED - duplicative and not used
"""Send raw bytes without further packaging."""
self.radio.sendMsg(msgBytes)
def sendMsg(self, msgBytes):
"""Wraps provided data into a SLIPmsg and then sends the message over the serial link
Args:
timestamp: Time of message.
cmdId: Command message type identifier.
msgBytes: Data bytes to be sent in serial message.
"""
if len(msgBytes) > 0:
self.lastMsgSentTime = time.time()
self.msgCounter += 1
self.msgCounter = self.msgCounter % 256
msgOut = self.msgParser.encodeMsg(msgBytes)
self.radio.sendMsg(msgOut)
def sendBuffer(self):
"""Send data in transmission buffer over serial connection."""
self.radio.sendBuffer()
def bufferTxMsg(self, msgBytes):
"""Add bytes to transmission buffer."""
if msgBytes:
msgOut = self.msgParser.encodeMsg(msgBytes)
self.radio.bufferTxMsg(msgOut)
def processMsg(self, msg, args):
if self.commProcessor:
self.commProcessor.processMsg(msg, args)
| 37,138
|
https://github.com/ccbabi/vue-component-toast/blob/master/src/toast.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
vue-component-toast
|
ccbabi
|
Vue
|
Code
| 117
| 418
|
<template>
<div :class="className">
<div v-if="mask" class="vc-toast-mask" @touchmove="touchmove" />
<transition name="vc-toast" @after-leave="afterLeave">
<div v-show="show" :class="['vc-toast', `is-${this.position}`]" :style="styles">
<i v-if="iconClass !== ''" class="vc-toast-icon" :class="iconClass" />
<span class="vc-toast-text">{{message}}</span>
</div>
</transition>
</div>
</template>
<script>
export default {
name: 'vc-toast',
props: {
message: String,
className: {
type: String,
default: ''
},
position: {
type: String,
default: 'middle'
},
iconClass: {
type: String,
default: ''
},
mask: {
type: Boolean,
default: false
}
},
data () {
return {
show: false
}
},
computed: {
styles () {
const padding = this.iconClass ? '.6em 2em' : '.4em .8em'
return { padding }
}
},
methods: {
afterLeave () {
if (this.__destroy) this.$destroy()
this.$el.parentNode.removeChild(this.$el)
},
touchmove (e) {
e.preventDefault()
e.stopPropagation()
}
}
}
</script>
| 49,588
|
https://github.com/retropipes/older-java-games/blob/master/LaserTank/src/com/puttysoftware/lasertank/utilities/IDGenerator.java
|
Github Open Source
|
Open Source
|
Unlicense
| 2,021
|
older-java-games
|
retropipes
|
Java
|
Code
| 52
| 148
|
/* LaserTank: An Arena-Solving Game
Copyright (C) 2008-2013 Eric Ahnell
Any questions should be directed to the author via email at: products@puttysoftware.com
*/
package com.puttysoftware.lasertank.utilities;
import com.puttysoftware.randomrange.RandomLongRange;
public class IDGenerator {
// Constructor
private IDGenerator() {
// Do nothing
}
// Methods
public static String generateRandomFilename() {
return Long.toString(RandomLongRange.generateRaw(), 36).toLowerCase();
}
}
| 17,327
|
https://github.com/RCCRAFT1/Scamming-Scammers/blob/master/devtools_java/commands/Intsakill.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Scamming-Scammers
|
RCCRAFT1
|
Java
|
Code
| 121
| 494
|
package devtools_java.commands;
import prodigy_hack.appendPacket.PacketSend;
import prodigy_hack.event.Event;
import prodigy_hack.packet.*;
public class Intsakill {
public static String killCommand;
public int killEntity;
public int killEntityStatement;
public void killCommand() {
return;
}
{
if (Event.event) {
do {
Event.eventPre(killEntity);
C01PacketPlayer.Game();
C03PacketInteractionEntity.setInteractionFailureEventCancelled(killCommand);
C03PacketInteractionEntity.getProdigyInteractionPacket();
C04PacketInteractionPlayer.getPacket2();
C01PacketPlayer.setPacketPlayer(killCommand);
Event.eventUpdate(1);
C02PacketInteraction.setPacketInteraction(killCommand);
Event.eventPre(killEntity);
C00Commons.getPacket0x00();
PacketSend.send();
Event.eventPost(killEntityStatement);
} while (null != null);
} else {
Event.eventUpdate(0);
}
}
public Intsakill(int killEntity, int killEntityStatement) {
this.killEntity = killEntity;
this.killEntityStatement = killEntityStatement;
}
public static String getKillCommand() {
return killCommand;
}
public static void setKillCommand(String killCommand) {
Intsakill.killCommand = killCommand;
}
public int getKillEntity() {
return killEntity;
}
public void setKillEntity(int killEntity) {
this.killEntity = killEntity;
}
public int getKillEntityStatement() {
return killEntityStatement;
}
public void setKillEntityStatement(int killEntityStatement) {
this.killEntityStatement = killEntityStatement;
}
}
| 48,911
|
https://github.com/kabartay/gammapy/blob/master/gammapy/modeling/models/tests/test_management.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
gammapy
|
kabartay
|
Python
|
Code
| 629
| 3,009
|
import pytest
import numpy as np
import astropy.units as u
from numpy.testing import assert_allclose
from gammapy.modeling import Covariance
from gammapy.modeling.models import (
BackgroundModel,
GaussianSpatialModel,
Models,
PointSpatialModel,
PowerLawSpectralModel,
SkyModel,
FoVBackgroundModel
)
from gammapy.maps import Map, MapAxis, WcsGeom
@pytest.fixture(scope="session")
def backgrounds():
axis = MapAxis.from_edges(np.logspace(-1, 1, 3), unit=u.TeV, name="energy")
geom = WcsGeom.create(skydir=(0, 0), npix=(5, 4), frame="galactic", axes=[axis])
m = Map.from_geom(geom)
m.quantity = np.ones(geom.data_shape) * 1e-7
background1 = BackgroundModel(m, name="bkg1", datasets_names="dataset-1")
background2 = BackgroundModel(m, name="bkg2", datasets_names=["dataset-2"])
backgrounds = [background1, background2]
return backgrounds
@pytest.fixture(scope="session")
def models(backgrounds):
spatial_model = GaussianSpatialModel(
lon_0="3 deg", lat_0="4 deg", sigma="3 deg", frame="galactic"
)
spectral_model = PowerLawSpectralModel(
index=2, amplitude="1e-11 cm-2 s-1 TeV-1", reference="1 TeV"
)
model1 = SkyModel(
spatial_model=spatial_model, spectral_model=spectral_model, name="source-1",
)
model2 = model1.copy(name="source-2")
model2.datasets_names = ["dataset-1"]
model3 = model1.copy(name="source-3")
model3.datasets_names = ["dataset-2"]
model3.spatial_model = PointSpatialModel()
model3.parameters.freeze_all()
models = Models([model1, model2, model3] + backgrounds)
return models
def test_select(models):
conditions = [
{"datasets_names": "dataset-1"},
{"datasets_names": "dataset-2"},
{"datasets_names": ["dataset-1", "dataset-2"]},
{"datasets_names": None},
{"tag": "BackgroundModel"},
{"tag": ["SkyModel", "BackgroundModel"]},
{"tag": "point", "model_type": "spatial"},
{"tag": ["point", "gauss"], "model_type": "spatial"},
{"tag": "pl", "model_type": "spectral"},
{"tag": ["pl", "pl-norm"], "model_type": "spectral"},
{"name_substring": "bkg"},
{"frozen": True},
{"frozen": False},
{"datasets_names": "dataset-1", "tag": "pl", "model_type": "spectral"},
]
expected = [
["source-1", "source-2", "bkg1"],
["source-1", "source-3", "bkg2"],
["source-1", "source-2", "source-3", "bkg1", "bkg2"],
["source-1", "source-2", "source-3", "bkg1", "bkg2"],
["bkg1", "bkg2"],
["source-1", "source-2", "source-3", "bkg1", "bkg2"],
["source-3"],
["source-1", "source-2", "source-3"],
["source-1", "source-2", "source-3"],
["source-1", "source-2", "source-3", "bkg1", "bkg2"],
["bkg1", "bkg2"],
["source-3"],
["source-1", "source-2", "bkg1", "bkg2"],
["source-1", "source-2"],
]
for cdt, xp in zip(conditions, expected):
selected = models.select(**cdt)
print(selected.names)
assert selected.names == xp
mask = models.selection_mask(**conditions[4]) | models.selection_mask(
**conditions[6]
)
selected = models[mask]
assert selected.names == ["source-3", "bkg1", "bkg2"]
def test_restore_status(models):
model = models[1].spectral_model
covariance_data = np.array([[1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 0.0]])
# the covariance is resest for frozen parameters
# because of from_factor_matrix (used by the optimizer)
# so if amplitude if frozen we get
covariance_frozen = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
model.covariance = Covariance.from_factor_matrix(model.parameters, np.ones((2, 2)))
assert_allclose(model.covariance.data, covariance_data)
with models.restore_status(restore_values=True):
model.amplitude.value = 0
model.amplitude.frozen = True
model.covariance = Covariance.from_factor_matrix(
model.parameters, np.ones((1, 1))
)
assert_allclose(model.covariance.data, covariance_frozen)
assert model.amplitude.value == 0
assert model.amplitude.error == 0
assert_allclose(model.amplitude.value, 1e-11)
assert model.amplitude.frozen == False
assert isinstance(models.covariance, Covariance)
assert_allclose(model.covariance.data, covariance_data)
assert model.amplitude.error == 1
with models.parameters.restore_status(restore_values=True):
model.amplitude.value = 0
model.amplitude.frozen = True
assert model.amplitude.value == 0
assert model.amplitude.frozen == True
assert_allclose(model.amplitude.value, 1e-11)
assert model.amplitude.frozen == False
with models.parameters.restore_status(restore_values=False):
model.amplitude.value = 0
model.amplitude.frozen = True
assert model.amplitude.value == 0
def test_bounds(models):
models.set_parameters_bounds(
tag="pl",
model_type="spectral",
parameters_names="index",
min=0,
max=5,
value=2.4,
)
pl_mask = models.selection_mask(tag="pl", model_type="spectral")
assert np.all([m.spectral_model.index.value == 2.4 for m in models[pl_mask]])
assert np.all([m.spectral_model.index.min == 0 for m in models[pl_mask]])
assert np.all([m.spectral_model.index.max == 5 for m in models[pl_mask]])
models.set_parameters_bounds(
tag=["pl", "pl-norm"],
model_type="spectral",
parameters_names=["norm", "amplitude"],
min=0,
max=None,
)
bkg_mask = models.selection_mask(tag="BackgroundModel")
assert np.all([m.spectral_model.amplitude.min == 0 for m in models[pl_mask]])
assert np.all([m._spectral_model.norm.min == 0 for m in models[bkg_mask]])
def test_freeze(models):
models.freeze()
assert np.all([p.frozen for p in models.parameters])
models.unfreeze()
assert not models["source-1"].spatial_model.lon_0.frozen
assert models["source-1"].spectral_model.reference.frozen
assert not models["source-3"].spatial_model.lon_0.frozen
assert models["bkg1"].spectral_model.tilt.frozen
assert not models["bkg1"].spectral_model.norm.frozen
models.freeze("spatial")
assert models["source-1"].spatial_model.lon_0.frozen
assert models["source-3"].spatial_model.lon_0.frozen
assert not models["bkg1"].spectral_model.norm.frozen
models.unfreeze("spatial")
assert not models["source-1"].spatial_model.lon_0.frozen
assert models["source-1"].spectral_model.reference.frozen
assert not models["source-3"].spatial_model.lon_0.frozen
models.freeze("spectral")
assert models["bkg1"].spectral_model.tilt.frozen
assert models["bkg1"].spectral_model.norm.frozen
assert models["source-1"].spectral_model.index.frozen
assert not models["source-3"].spatial_model.lon_0.frozen
models.unfreeze("spectral")
assert models["bkg1"].spectral_model.tilt.frozen
assert not models["bkg1"].spectral_model.norm.frozen
assert not models["source-1"].spectral_model.index.frozen
def test_parameters(models):
pars = models.parameters.select(frozen=False)
pars.freeze_all()
assert np.all([p.frozen for p in pars])
assert len(pars.select(frozen=True)) == len(pars)
pars.unfreeze_all()
assert np.all([not p.frozen for p in pars])
assert len(pars.min) == len(pars)
assert len(pars.max) == len(pars)
with pytest.raises(TypeError):
pars.min = 1
with pytest.raises(ValueError):
pars.min = [1]
with pytest.raises(ValueError):
pars.max = [2]
def test_fov_bkg_models():
models = Models([FoVBackgroundModel(dataset_name=name) for name in ["test-1", "test-2"]])
models.freeze()
assert models.frozen
models.parameters.select(name="tilt").unfreeze_all()
assert not models["test-1-bkg"].spectral_model.tilt.frozen
assert not models["test-2-bkg"].spectral_model.tilt.frozen
models.parameters.select(name=["tilt", "norm"]).freeze_all()
assert models["test-1-bkg"].spectral_model.tilt.frozen
assert models["test-1-bkg"].spectral_model.norm.frozen
def test_reassign_dataset(models):
ref = models.select(datasets_names="dataset-2")
models = models.reassign("dataset-2", "dataset-2-copy")
assert len(models.select(datasets_names="dataset-2")) == np.sum(
[m.datasets_names == None for m in models]
)
new = models.select(datasets_names="dataset-2-copy")
assert len(new) == len(ref)
assert new["source-1"].datasets_names == None
assert new["source-3"].datasets_names == ["dataset-2-copy"]
| 9,775
|
https://github.com/karlwnw/adventofcode2019/blob/master/python/day11.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
adventofcode2019
|
karlwnw
|
Python
|
Code
| 224
| 625
|
from day5 import parse
from intcode import IntCode
BLACK = 0
WHITE = 1
N = 1j
LEFT, RIGHT = -1j, 1j
def loop_run(program, current_color=BLACK):
heading = N
position = 0
painted_panels = {position: current_color}
intcode = IntCode(program)
while current_color is not None:
input_value = current_color
current_color = intcode.run(input_value)
direction_value = intcode.run(input_value)
if direction_value is None:
break
painted_panels[position] = current_color
if direction_value not in (0, 1):
raise RuntimeError("Invalid direction value: {}".format(direction_value))
heading = RIGHT * heading if direction_value else LEFT * heading
position = position + heading
current_color = painted_panels.get(position, BLACK)
# print(f"direction={direction_value} color={current_color}")
return painted_panels
def print_image(panel, color=WHITE):
values = list(panel.keys())
x_values = [c.real for c in values]
y_values = [c.imag for c in values]
max_width, min_width = max(x_values), min(x_values)
max_height, min_height = max(y_values), min(y_values)
width, height = int(max_width - min_width) + 1, int(max_height - min_height)
print(width, height)
# Reverse the axes
for y in range(height, -1, -1):
for x in range(width, 0, -1):
position = x + min_width + 1j * y + (min_height * 1j)
c = panel.get(position)
e = "##" if c == color else " "
end = "\n" if (x + 1) % width == 0 else ""
print(e, end=end)
if __name__ == "__main__":
with open("../inputs/day11.input") as f:
program = f.readline().strip()
# Part I
loop_run(parse(program), BLACK) # 2238
# Part II
panel = loop_run(parse(program), WHITE)
print_image(panel) # PKFPAZRP
| 16,469
|
https://github.com/FHedin/FittingWizard/blob/master/src/ch/unibas/fittingwizard/application/fitting/FitRepository.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,017
|
FittingWizard
|
FHedin
|
Java
|
Code
| 311
| 953
|
/*
* Copyright (c) 2015, Florent Hedin, Markus Meuwly, and the University of Basel
* All rights reserved.
*
* The 3-clause BSD license is applied to this software.
* see LICENSE.txt
*
*/
package ch.unibas.fittingwizard.application.fitting;
import ch.unibas.fittingwizard.application.base.MemoryRepository;
import ch.unibas.fittingwizard.application.molecule.*;
import java.util.ArrayList;
import java.util.List;
/**
* User: mhelmer
* Date: 03.12.13
* Time: 14:45
*/
public class FitRepository extends MemoryRepository<Fit> {
private final MoleculeRepository moleculeRepository;
public FitRepository(MoleculeRepository moleculeRepository) {
this.moleculeRepository = moleculeRepository;
}
public int getFitCount() {
return loadAll().size();
}
public int getNextFitId() {
return loadAll().size();
}
public void createFit(int fitId, double rmse, int rank, List<OutputAtomType> outputAtomTypes, InitialQ00 initialValues) {
Fit fit = new Fit(fitId, rmse, rank, createFitResults(outputAtomTypes, initialValues));
save(fit);
}
private ArrayList<FitResult> createFitResults(List<OutputAtomType> outputAtomTypes, InitialQ00 initialValues) {
ArrayList<FitResult> results = new ArrayList<>();
for (OutputAtomType outputAtomType : outputAtomTypes) {
AtomTypeId atomTypeId = outputAtomType.getId();
List<Molecule> molecules = moleculeRepository.findMoleculesWithAtomType(atomTypeId);
double initialQ = getInialQ00(initialValues, atomTypeId);
FitResult fitResult = new FitResult(atomTypeId,
getMoleculeIds(molecules),
initialQ,
outputAtomType);
results.add(fitResult);
}
return results;
}
private Double getInialQ00(InitialQ00 initialValues, AtomTypeId atomTypeId) {
for (ChargeValue initialValue : initialValues.getChargeValues()) {
if (initialValue.getAtomTypeId().equals(atomTypeId))
return initialValue.getValue();
}
throw new RuntimeException("Missing inital Q for atom type " + atomTypeId.getName());
}
private List<MoleculeId> getMoleculeIds(List<Molecule> molecules) {
ArrayList<MoleculeId> ids = new ArrayList<>();
for (Molecule molecule : molecules) {
ids.add(molecule.getId());
}
return ids;
}
private Double getVerifiedInitialQ(List<Molecule> molecules, AtomTypeId atomTypeId) {
boolean isReferenceValueInitialized = false;
Double referenceValue = 0.0;
for (int i = 0; i < molecules.size(); i++) {
Molecule molecule = molecules.get(i);
AtomType atomTypesInMolecule = molecule.findAtomTypeById(atomTypeId);
boolean moleculeIsCandidate = atomTypesInMolecule != null;
if (moleculeIsCandidate) {
Double userCharge = atomTypesInMolecule.getUserQ00();
if (!isReferenceValueInitialized) {
referenceValue = userCharge;
isReferenceValueInitialized = true;
} else if (userCharge == null) {
throw new RuntimeException("Atom types occuring in multiple molecules must have charge defined by user.");
} else if (userCharge != referenceValue) {
throw new RuntimeException("Atom types occuring in multiple molecules must have same charge defined by user.");
}
}
}
return referenceValue;
}
}
| 10,282
|
https://github.com/b2220333/pybind/blob/master/pybind/nos/v7_2_0/rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/listen_range/__init__.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
pybind
|
b2220333
|
Python
|
Code
| 945
| 5,253
|
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from decimal import Decimal
from bitarray import bitarray
import __builtin__
class listen_range(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module brocade-rbridge - based on the path /rbridge-id/router/router-bgp/address-family/ipv4/ipv4-unicast/af-vrf/listen-range. Each member element of
the container is represented as a class variable - with a specific
YANG type.
"""
__slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__listen_range_prefix','__peer_group','__limit',)
_yang_name = 'listen-range'
_rest_name = 'listen-range'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
path_helper_ = kwargs.pop("path_helper", None)
if path_helper_ is False:
self._path_helper = False
elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper):
self._path_helper = path_helper_
elif hasattr(self, "_parent"):
path_helper_ = getattr(self._parent, "_path_helper", False)
self._path_helper = path_helper_
else:
self._path_helper = False
extmethods = kwargs.pop("extmethods", None)
if extmethods is False:
self._extmethods = False
elif extmethods is not None and isinstance(extmethods, dict):
self._extmethods = extmethods
elif hasattr(self, "_parent"):
extmethods = getattr(self._parent, "_extmethods", None)
self._extmethods = extmethods
else:
self._extmethods = False
self.__listen_range_prefix = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="listen-range-prefix", rest_name="listen-range-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D/M IP address in dotted decimal/Mask'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='inet:ipv4-prefix', is_config=True)
self.__peer_group = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'[a-zA-Z]{1}([-a-zA-Z0-9\\\\\\\\@#\\+\\*\\(\\)=\\{~\\}%<>=$_\\[\\]\\|]{0,62})'}), is_leaf=True, yang_name="peer-group", rest_name="peer-group", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Peer group name', u'cli-expose-key-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='bgp-peergroup', is_config=True)
self.__limit = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..255']}), is_leaf=True, yang_name="limit", rest_name="limit", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Limit the neighbor'}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='listen-limit-type', is_config=True)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path()+[self._yang_name]
else:
return [u'rbridge-id', u'router', u'router-bgp', u'address-family', u'ipv4', u'ipv4-unicast', u'af-vrf', u'listen-range']
def _rest_path(self):
if hasattr(self, "_parent"):
if self._rest_name:
return self._parent._rest_path()+[self._rest_name]
else:
return self._parent._rest_path()
else:
return [u'rbridge-id', u'router', u'bgp', u'address-family', u'ipv4', u'unicast', u'vrf', u'listen-range']
def _get_listen_range_prefix(self):
"""
Getter method for listen_range_prefix, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/listen_range/listen_range_prefix (inet:ipv4-prefix)
"""
return self.__listen_range_prefix
def _set_listen_range_prefix(self, v, load=False):
"""
Setter method for listen_range_prefix, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/listen_range/listen_range_prefix (inet:ipv4-prefix)
If this variable is read-only (config: false) in the
source YANG file, then _set_listen_range_prefix is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_listen_range_prefix() directly.
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="listen-range-prefix", rest_name="listen-range-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D/M IP address in dotted decimal/Mask'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='inet:ipv4-prefix', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """listen_range_prefix must be of a type compatible with inet:ipv4-prefix""",
'defined-type': "inet:ipv4-prefix",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="listen-range-prefix", rest_name="listen-range-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D/M IP address in dotted decimal/Mask'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='inet:ipv4-prefix', is_config=True)""",
})
self.__listen_range_prefix = t
if hasattr(self, '_set'):
self._set()
def _unset_listen_range_prefix(self):
self.__listen_range_prefix = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="listen-range-prefix", rest_name="listen-range-prefix", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D/M IP address in dotted decimal/Mask'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='inet:ipv4-prefix', is_config=True)
def _get_peer_group(self):
"""
Getter method for peer_group, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/listen_range/peer_group (bgp-peergroup)
"""
return self.__peer_group
def _set_peer_group(self, v, load=False):
"""
Setter method for peer_group, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/listen_range/peer_group (bgp-peergroup)
If this variable is read-only (config: false) in the
source YANG file, then _set_peer_group is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_peer_group() directly.
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'[a-zA-Z]{1}([-a-zA-Z0-9\\\\\\\\@#\\+\\*\\(\\)=\\{~\\}%<>=$_\\[\\]\\|]{0,62})'}), is_leaf=True, yang_name="peer-group", rest_name="peer-group", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Peer group name', u'cli-expose-key-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='bgp-peergroup', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """peer_group must be of a type compatible with bgp-peergroup""",
'defined-type': "brocade-bgp:bgp-peergroup",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'[a-zA-Z]{1}([-a-zA-Z0-9\\\\\\\\@#\\+\\*\\(\\)=\\{~\\}%<>=$_\\[\\]\\|]{0,62})'}), is_leaf=True, yang_name="peer-group", rest_name="peer-group", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Peer group name', u'cli-expose-key-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='bgp-peergroup', is_config=True)""",
})
self.__peer_group = t
if hasattr(self, '_set'):
self._set()
def _unset_peer_group(self):
self.__peer_group = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'[a-zA-Z]{1}([-a-zA-Z0-9\\\\\\\\@#\\+\\*\\(\\)=\\{~\\}%<>=$_\\[\\]\\|]{0,62})'}), is_leaf=True, yang_name="peer-group", rest_name="peer-group", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Peer group name', u'cli-expose-key-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='bgp-peergroup', is_config=True)
def _get_limit(self):
"""
Getter method for limit, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/listen_range/limit (listen-limit-type)
"""
return self.__limit
def _set_limit(self, v, load=False):
"""
Setter method for limit, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/listen_range/limit (listen-limit-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_limit is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_limit() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..255']}), is_leaf=True, yang_name="limit", rest_name="limit", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Limit the neighbor'}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='listen-limit-type', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """limit must be of a type compatible with listen-limit-type""",
'defined-type': "brocade-bgp:listen-limit-type",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..255']}), is_leaf=True, yang_name="limit", rest_name="limit", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Limit the neighbor'}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='listen-limit-type', is_config=True)""",
})
self.__limit = t
if hasattr(self, '_set'):
self._set()
def _unset_limit(self):
self.__limit = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': [u'1..255']}), is_leaf=True, yang_name="limit", rest_name="limit", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Limit the neighbor'}}, namespace='urn:brocade.com:mgmt:brocade-bgp', defining_module='brocade-bgp', yang_type='listen-limit-type', is_config=True)
listen_range_prefix = __builtin__.property(_get_listen_range_prefix, _set_listen_range_prefix)
peer_group = __builtin__.property(_get_peer_group, _set_peer_group)
limit = __builtin__.property(_get_limit, _set_limit)
_pyangbind_elements = {'listen_range_prefix': listen_range_prefix, 'peer_group': peer_group, 'limit': limit, }
| 12,434
|
https://github.com/laoyigrace/files/blob/master/yibo/tempest/tempest/api/network/test_sf_router_update.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
files
|
laoyigrace
|
Python
|
Code
| 340
| 1,463
|
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest_lib.common.utils import data_utils
from tempest.api.network import sf_base
from tempest import config
from tempest import test
CONF = config.CONF
class RouterUpdateTestJSON(sf_base.SfBaseNetworkTest):
"""
Tests the following operations in the Quantum API using the REST client for
Neutron:
router_update
v2.0 of the Neutron API is assumed. It is also assumed that the following
options are defined in the [network] section of etc/tempest.conf:
public_network_id which is the id for the external network present
"""
@classmethod
def resource_setup(cls):
super(RouterUpdateTestJSON, cls).resource_setup()
if not test.is_extension_enabled('router', 'network'):
msg = "router extension not enabled."
raise cls.skipException(msg)
cls.ext_net_id = CONF.network.public_network_id
# Create network, subnet, router and add interface
cls.network = cls.create_network()
cls.subnet = cls.create_subnet(cls.network)
cls.router = cls.create_router(data_utils.rand_name('router-'),
external_network_id=cls.ext_net_id)
cls.sf_network_client.add_router_interface(router_id=cls.router['id'],\
subnet_id=cls.subnet['id'])
@test.attr(type='smoke')
@test.idempotent_id('a0bf10f0-49ba-479c-a0dd-aeaf90031c35')
def test_router_update_route(self):
# Create a route for a router
action = [{'destination':'192.168.66.0/24', 'nexthop':'10.100.0.5'}]
route_info = self.sf_network_client.router_update(
router_id=self.router['id'], action=action)
self.assertEqual(route_info['router']['routes'], action)
# Show the route
router_info = self.sf_network_client.router_show(\
router_id=self.router['id'])
self.assertEqual(router_info['router']['routes'], action)
# Update the route
action = [{'destination':'192.168.88.0/24', 'nexthop':'10.100.0.6'}]
route_info = self.sf_network_client.router_update(\
router_id=self.router['id'], action=action)
self.assertEqual(route_info['router']['routes'], action)
# Delete the route
router_update_info = self.sf_network_client.router_update(
router_id=self.router['id'], action=None)
self.assertEqual(router_update_info['router']['routes'], [])
#self.sf_network_client.remove_router_interface(router_id=self.router['id'],\
# subnet_id=self.subnet['id'])
@test.attr(type='smoke')
@test.idempotent_id('2322115f-fb32-4e80-a009-a3daf34ecf81')
def test_router_update_muti_route(self):
# Create a route for a router
action = [{'destination':'192.168.44.0/24', 'nexthop':'10.100.0.5'},
{'destination':'192.168.55.0/24', 'nexthop':'10.100.0.5'},
{'destination':'192.168.66.0/24', 'nexthop':'10.100.0.5'},
{'destination':'192.168.77.0/24', 'nexthop':'10.100.0.5'},
{'destination':'192.168.88.0/24', 'nexthop':'10.100.0.5'},]
route_info = self.sf_network_client.router_update(
router_id=self.router['id'], action=action)
self.assertEqual(route_info['router']['routes'], action)
# Show the route
router_info = self.sf_network_client.router_show(\
router_id=self.router['id'])
self.assertEqual(router_info['router']['routes'], action)
# Update the route
action = [{'destination':'192.168.88.0/24', 'nexthop':'10.100.0.6'}]
route_info = self.sf_network_client.router_update(\
router_id=self.router['id'], action=action)
self.assertEqual(route_info['router']['routes'], action)
# Delete the route
router_update_info = self.sf_network_client.router_update(
router_id=self.router['id'], action=None)
self.assertEqual(router_update_info['router']['routes'], [])
#self.sf_network_client.remove_router_interface(router_id=self.router['id'],\
# subnet_id=self.subnet['id'])
| 18,621
|
https://github.com/CapsicumCorp/iOmy/blob/master/watchinputs/watch_inputs/src/modules/tizigbeelib/tizigbeelibpriv.hpp
|
Github Open Source
|
Open Source
|
Apache-2.0, libpng-2.0
| 2,018
|
iOmy
|
CapsicumCorp
|
C++
|
Code
| 4,296
| 13,632
|
/*
Title: Texas Instruments Z-Stack Library Header for Watch Inputs
Author: Matthew Stapleton (Capsicum Corporation) <matthew@capsicumcorp.com>
Description: Header File for tizigbeelib.c
Copyright: Capsicum Corporation 2017
This file is part of Watch Inputs which is part of the iOmy project.
iOmy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
iOmy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with iOmy. If not, see <http://www.gnu.org/licenses/>.
Xbee info sourced from Digi docs
*/
#ifndef TIZIGBEELIB_HPP
#define TIZIGBEELIB_HPP
#include <stdint.h>
#include "modules/commonlib/commonlib.h"
namespace tizigbeelib {
/* TI Zigbee Commands and Responses */
//This command is used to check for a device
static const uint16_t SYS_PING=0x2101;
static const uint16_t SYS_PING_RESPONSE=0x6101;
//Ask for the device's version string
static const uint16_t SYS_VERSION=0x2102;
static const uint16_t SYS_VERSION_RESPONSE=0x6102;
//This command is sent by the tester to the target to reset it
static const uint16_t SYS_RESET=0x4100;
static const uint16_t SYS_RESET_RESPONSE=0x4180;
static const uint16_t AF_DATA_CONFIRM = 0x4480;
static const uint16_t AF_DATA_REQUEST = 0x2401;
static const uint16_t AF_DATA_REQUEST_EXT = 0x2402;
static const uint16_t AF_DATA_SRSP = 0x6401;
static const uint16_t AF_DATA_SRSP_EXT = 0x6402;
static const uint16_t AF_INCOMING_MSG = 0x4481;
static const uint16_t AF_REGISTER = 0x2400;
static const uint16_t AF_REGISTER_SRSP = 0x6400;
//Reads current device information
static const uint16_t ZB_GET_DEVICE_INFO=0x2606;
static const uint16_t ZB_GET_DEVICE_INFO_RESPONSE=0x6606;
//Reads a configuration property from nonvolatile memory
static const uint16_t ZB_READ_CONFIGURATION=0x2604;
static const uint16_t ZB_READ_CONFIGURATION_RESPONSE = 0x6604;
//Writes a configuration property to nonvolatile memory
static const uint16_t ZB_WRITE_CONFIGURATION=0x2605;
static const uint16_t ZB_WRITE_CONFIGURATION_RESPONSE=0x6605;
//This message will request the device to send a "Network Address Request"
static const uint16_t ZDO_NWK_ADDR_REQ = 0x2500;
static const uint16_t ZDO_NWK_ADDR_REQ_SRSP = 0x6500;
static const uint16_t ZDO_NWK_ADDR_RSP = 0x4580;
//This command will request a device's IEEE 64-bit address
static const uint16_t ZDO_IEEE_ADDR_REQ = 0x2501;
static const uint16_t ZDO_IEEE_ADDR_REQ_SRSP = 0x6501;
static const uint16_t ZDO_IEEE_ADDR_RSP = 0x4581;
//This command is generated to inquire as to the Node Descriptor of the destination device
static const uint16_t ZDO_NODE_DESC_REQ = 0x2502;
static const uint16_t ZDO_NODE_DESC_REQ_SRSP = 0x6502;
static const uint16_t ZDO_NODE_DESC_RSP = 0x4582;
//This command is generated to inquire as to the Power Descriptor of the destination
static const uint16_t ZDO_POWER_DESC_REQ = 0x2503;
static const uint16_t ZDO_POWER_DESC_REQ_SRSP = 0x6503;
static const uint16_t ZDO_POWER_DESC_RSP = 0x4583;
//This command is generated to inquire as to the Simple Descriptor of the destination device's Endpoint
static const uint16_t ZDO_SIMPLE_DESC_REQ = 0x2504;
static const uint16_t ZDO_SIMPLE_DESC_REQ_SRSP = 0x6504;
static const uint16_t ZDO_SIMPLE_DESC_RSP = 0x4584;
//This command is generated to request a list of active endpoint from the destination device
static const uint16_t ZDO_ACTIVE_EP_REQ = 0x2505;
static const uint16_t ZDO_ACTIVE_EP_REQ_SRSP = 0x6505;
static const uint16_t ZDO_ACTIVE_EP_RSP = 0x4585;
//This command is generated to request a list of active endpoint from the destination device
static const uint16_t ZDO_MATCH_DESC_REQ = 0x2506;
static const uint16_t ZDO_MATCH_DESC_REQ_SRSP = 0x6506;
static const uint16_t ZDO_MATCH_DESC_RSP = 0x4586;
//This command is generated to request for the destination device's complex descriptor
static const uint16_t ZDO_COMPLEX_DESC_REQ = 0x2507;
static const uint16_t ZDO_COMPLEX_DESC_REQ_SRSP = 0x6507;
static const uint16_t ZDO_COMPLEX_DESC_RSP = 0x4587;
//This command is generated to request for the destination device's user descriptor
static const uint16_t ZDO_USER_DESC_REQ = 0x2508;
static const uint16_t ZDO_USER_DESC_REQ_SRSP = 0x6508;
static const uint16_t ZDO_USER_DESC_RSP = 0x4588;
//This command is generated to request an End Device Announce
static const uint16_t ZDO_END_DEVICE_ANNCE = 0x250a;
static const uint16_t ZDO_END_DEVICE_ANNCE_SRSP = 0x650a;
static const uint16_t ZDO_END_DEVICE_ANNCE_IND = 0x45c1;
//This command is generated to request a User Descriptor Set Request
static const uint16_t ZDO_USER_DESC_SET = 0x250b;
static const uint16_t ZDO_USER_DESC_SET_SRSP = 0x650b;
static const uint16_t ZDO_SERVER_DISC_REQ = 0x250c;
static const uint16_t ZDO_SERVER_DISC_REQ_SRSP = 0x650c;
static const uint16_t ZDO_SERVER_DISC_RSP = 0x458a;
static const uint16_t ZDO_END_DEVICE_BIND_REQ = 0x2520;
static const uint16_t ZDO_END_DEVICE_BIND_REQ_SRSP = 0x6520;
static const uint16_t ZDO_END_DEVICE_BIND_RSP = 0x45a0;
static const uint16_t ZDO_BIND_REQ = 0x2521;
static const uint16_t ZDO_BIND_REQ_SRSP = 0x6521;
static const uint16_t ZDO_BIND_RSP = 0x45a1;
static const uint16_t ZDO_UNBIND_REQ = 0x2522;
static const uint16_t ZDO_UNBIND_REQ_SRSP = 0x6522;
static const uint16_t ZDO_UNBIND_RSP = 0x45a2;
static const uint16_t ZDO_SET_LINK_KEY = 0x2523;
static const uint16_t ZDO_SET_LINK_KEY_SRSP = 0x6523;
static const uint16_t ZDO_GET_LINK_KEY = 0x2525;
static const uint16_t ZDO_GET_LINK_KEY_SRSP = 0x6525;
static const uint16_t ZDO_SEND_DATA = 0x2528;
static const uint16_t ZDO_SEND_DATA_SRSP = 0x6528;
static const uint16_t ZDO_MGMT_NWK_DISC_REQ = 0x2530;
static const uint16_t ZDO_MGMT_NWK_DISC_REQ_SRSP = 0x6530;
static const uint16_t ZDO_MGMT_NWK_DISC_RSP = 0x45b0;
//This command is generated to request a Management LQI Request
static const uint16_t ZDO_MGMT_LQI_REQ = 0x2531;
static const uint16_t ZDO_MGMT_LQI_REQ_SRSP = 0x6531;
static const uint16_t ZDO_MGMT_LQI_RSP = 0x45b1;
static const uint16_t ZDO_MGMT_RTG_REQ = 0x2532;
static const uint16_t ZDO_MGMT_RTG_REQ_SRSP = 0x6532;
static const uint16_t ZDO_MGMT_RTG_RSP = 0x45b2;
static const uint16_t ZDO_MGMT_BIND_REQ = 0x2533;
static const uint16_t ZDO_MGMT_BIND_REQ_SRSP = 0x6533;
static const uint16_t ZDO_MGMT_BIND_RSP = 0x45b3;
static const uint16_t ZDO_MGMT_LEAVE_REQ = 0x2534;
static const uint16_t ZDO_MGMT_LEAVE_REQ_SRSP = 0x6534;
static const uint16_t ZDO_MGMT_LEAVE_RSP = 0x45b4;
static const uint16_t ZDO_MGMT_DIRECT_JOIN_REQ = 0x2535;
static const uint16_t ZDO_MGMT_DIRECT_JOIN_REQ_SRSP = 0x6535;
static const uint16_t ZDO_MGMT_DIRECT_JOIN_RSP = 0x45b5;
//This command is generated to request a Management Join Request
static const uint16_t ZDO_MGMT_PERMIT_JOIN_REQ = 0x2536;
static const uint16_t ZDO_MGMT_PERMIT_JOIN_REQ_SRSP = 0x6536;
static const uint16_t ZDO_MGMT_PERMIT_JOIN_RSP = 0x45b6;
static const uint16_t ZDO_MGMT_NWK_UPDATE_REQ = 0x2537;
static const uint16_t ZDO_MGMT_NWK_UPDATE_REQ_SRSP = 0x6537;
//This command registers for a ZDO callback
static const uint16_t ZDO_MSG_CB_REGISTER=0x253e;
static const uint16_t ZDO_MSG_CB_REGISTER_SRSP=0x653e;
// In the case where compiler flag HOLD_AUTO_START is defined by default;
// device will start from HOLD state. Issuing this command will trigger the
// device to leave HOLD state to form or join a network.
static const uint16_t ZDO_STARTUP_FROM_APP=0x2540;
static const uint16_t ZDO_STARTUP_FROM_APP_SRSP=0x6540;
//ZDO state change indication
static const uint16_t ZDO_STATE_CHANGE_IND = 0x45c0;
//ZDO Src Route indication
static const uint16_t ZDO_SRC_RTG_IND = 0x45c4;
//ZDO leave indication
static const uint16_t ZDO_LEAVE_IND = 0x45c9;
//ZDO Trust Center end device announce indication
static const uint16_t ZDO_TC_DEVICE_IND = 0x45ca;
//ZDO permit join indication
static const uint16_t ZDO_PERMIT_JOIN_IND = 0x45cb;
//This callback message contains a ZDO cluster response
static const uint16_t ZDO_MSG_CB_INCOMING = 0x45ff;
//TI Zigbee Waiting Definitions
enum class WAITING_FOR {
NOTHING=0,
ANYTHING, //Waiting for any valid packet
SYS_PING_RESPONSE,
SYS_VERSION_RESPONSE,
SYS_RESET_RESPONSE,
ZB_DEVICE_INFO_RESPONSE,
ZB_READ_CONFIG_RESPONSE,
ZB_WRITE_CONFIG_RESPONSE,
AF_REGISTER_SRESPONSE,
ZDO_MSG_CB_REGISTER_SRESPONSE,
ZDO_STARTUP_FROM_APP_SRESPONSE
};
// Dongle startup options
namespace STARTOPT {
static const uint8_t CLEAR_CONFIG = 0x01;
static const uint8_t CLEAR_STATE = 0x02;
}
//TI Zigbee Reset Types
namespace RESET_TYPE {
static const int SERIAL_BOOTLOADER=1;
static const int TARGET_DEVICE=0;
}
/// <name>TI.ZPI1.SYS_PING_RESPONSE.CAPABILITIES</name>
/// <summary>Capabilities bitfield</summary>
namespace CAPABILITIES {
/// <name>TI.ZPI2.SYS_PING_RESPONSE.CAPABILITIES.MT_CAP_AF</name>
/// <summary>Capabilities bitfield</summary>
static const uint16_t MT_CAP_AF = 8;
/// <name>TI.ZPI2.SYS_PING_RESPONSE.CAPABILITIES.MT_CAP_APP</name>
/// <summary>Capabilities bitfield</summary>
static const uint16_t MT_CAP_APP = 0x100;
/// <name>TI.ZPI2.SYS_PING_RESPONSE.CAPABILITIES.MT_CAP_DEBUG</name>
/// <summary>Capabilities bitfield</summary>
static const uint16_t MT_CAP_DEBUG = 0x80;
/// <name>TI.ZPI2.SYS_PING_RESPONSE.CAPABILITIES.MT_CAP_MAC</name>
/// <summary>Capabilities bitfield</summary>
static const uint16_t MT_CAP_MAC = 2;
/// <name>TI.ZPI2.SYS_PING_RESPONSE.CAPABILITIES.MT_CAP_NWK</name>
/// <summary>Capabilities bitfield</summary>
static const uint16_t MT_CAP_NWK = 4;
/// <name>TI.ZPI2.SYS_PING_RESPONSE.CAPABILITIES.MT_CAP_SAPI</name>
/// <summary>Capabilities bitfield</summary>
static const uint16_t MT_CAP_SAPI = 0x20;
/// <name>TI.ZPI2.SYS_PING_RESPONSE.CAPABILITIES.MT_CAP_SYS</name>
/// <summary>Capabilities bitfield</summary>
static const uint16_t MT_CAP_SYS = 1;
/// <name>TI.ZPI2.SYS_PING_RESPONSE.CAPABILITIES.MT_CAP_UTIL</name>
/// <summary>Capabilities bitfield</summary>
static const uint16_t MT_CAP_UTIL = 0x40;
/// <name>TI.ZPI2.SYS_PING_RESPONSE.CAPABILITIES.MT_CAP_ZDO</name>
/// <summary>Capabilities bitfield</summary>
static const uint16_t MT_CAP_ZDO = 0x10;
/// <name>TI.ZPI2.SYS_PING_RESPONSE.CAPABILITIES.NONE</name>
/// <summary>Capabilities bitfield</summary>
static const uint16_t NONE = 0;
}
/// <name>TI.ZPI2.ZB_GET_DEVICE_INFO.DEV_INFO_TYPE</name>
/// <summary>Reset type</summary>
namespace DEV_INFO_TYPE {
/// <name>TI.ZPI2.ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.CHANNEL</name>
/// <summary>Reset type</summary>
static const uint8_t CHANNEL = 5;
/// <name>TI.ZPI2.ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.EXT_PAN_ID</name>
/// <summary>Reset type</summary>
static const uint8_t EXT_PAN_ID = 7;
/// <name>TI.ZPI2.ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.IEEE_ADDR</name>
/// <summary>Reset type</summary>
static const uint8_t IEEE_ADDR = 1;
/// <name>TI.ZPI2.ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PAN_ID</name>
/// <summary>Reset type</summary>
static const uint8_t PAN_ID = 6;
/// <name>TI.ZPI2.ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PARENT_IEEE_ADDR</name>
/// <summary>Reset type</summary>
static const uint8_t PARENT_IEEE_ADDR = 4;
/// <name>TI.ZPI2.ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.PARENT_SHORT_ADDR</name>
/// <summary>Reset type</summary>
static const uint8_t PARENT_SHORT_ADDR = 3;
/// <name>TI.ZPI2.ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.SHORT_ADDR</name>
/// <summary>Reset type</summary>
static const uint8_t SHORT_ADDR = 2;
/// <name>TI.ZPI2.ZB_GET_DEVICE_INFO.DEV_INFO_TYPE.STATE</name>
/// <summary>Reset type</summary>
static const uint8_t STATE = 0;
}
//For ZB_READ and ZB_WRITE CONFIGURATION
namespace CONFIG_ID {
static const uint8_t ZCD_NV_STARTUP_OPTION = 0x03;
static const uint8_t ZCD_NV_LOGICAL_TYPE = 0x87; //Zigbee Node Mode
static const uint8_t ZCD_NV_POLL_RATE = 0x24;
static const uint8_t ZCD_NV_QUEUED_POLL_RATE = 0x25;
static const uint8_t ZCD_NV_RESPONSE_POLL_RATE = 0x26;
static const uint8_t ZCD_NV_POLL_FAILURE_RETRIES = 0x29;
static const uint8_t ZCD_NV_INDIRECT_MSG_TIMEOUT = 0x2B;
static const uint8_t ZCD_NV_APS_FRAME_RETRIES = 0x43;
static const uint8_t ZCD_NV_APS_ACK_WAIT_DURATION = 0x44;
static const uint8_t ZCD_NV_BINDING_TIME = 0x46;
static const uint8_t ZCD_NV_USERDESC = 0x81;
static const uint8_t ZCD_NV_PANID = 0x83;
static const uint8_t ZCD_NV_CHANLIST = 0x84;
static const uint8_t ZCD_NV_PRECFGKEY = 0x62; //Network Key
static const uint8_t ZCD_NV_PRECFGKEYS_ENABLE = 0x63; //Whether to distribute the network key in clear
static const uint8_t ZCD_NV_SECURITY_MODE = 0x64;
static const uint8_t ZCD_NV_BCAST_RETRIES = 0x2E;
static const uint8_t ZCD_NV_PASSIVE_ACK_TIMEOUT = 0x2F;
static const uint8_t ZCD_NV_BCAST_DELIVERY_TIME = 0x30;
static const uint8_t ZCD_NV_ROUTE_EXPIRY_TIME = 0x2C;
static const uint8_t ZCD_NV_EXTPANID = 0x2D;
}
namespace NetworkMode {
static const uint8_t Coordinator=0;
static const uint8_t Router=1;
static const uint8_t EndDevice=2;
}
namespace ZDO_STARTUP_STATUS {
static const uint8_t DEV_HOLD=0x00; // Initialized - not started automatically
static const uint8_t DEV_INIT=0x01; // Initialized - not connected to anything
static const uint8_t DEV_NWK_DISC=0x02; // Discovering PAN's to join
static const uint8_t DEV_NWK_JOINING=0x03; // Joining a PAN
static const uint8_t DEV_NWK_REJOINING=0x04; // ReJoining a PAN, only for end-devices
static const uint8_t DEV_END_DEVICE_UNAUTH=0x05; // Joined but not yet authenticated by trust center
static const uint8_t DEV_END_DEVICE=0x06; // Started as device after authentication
static const uint8_t DEV_ROUTER=0x07; // Device joined, authenticated and is a router
static const uint8_t DEV_COORD_STARTING=0x08; // Started as ZigBee Coordinator
static const uint8_t DEV_ZB_COORD=0x09; // Started as ZigBee Coordinator
static const uint8_t DEV_NWK_ORPHAN=0x0A; // Device has lost information about its parent
}
namespace JOIN_MODE_STATE {
static const uint8_t DISABLED=0; //Permanently disabled join mode
static const uint8_t TEMP_ENABLED=1; //Join mode enabled for a set number of seconds
static const uint8_t ENABLED=2; //Permanently enabled join mode
}
//TI Zigbee Other Definitions
static const uint8_t BOOTLOADER_MAGIC_BYTE1=0xFE;
static const uint8_t BOOTLOADER_MAGIC_BYTE2=0x07;
static const uint8_t BOOTLOADER_MAGIC_BYTE3=0xEF;
//Ported from TI Z-Stack: Components/osal/include/{comdef.h and ZComDef.h}
namespace STATUS {
/*** Generic Status Return Values ***/
#define SUCCESS 0x00
#define FAILURE 0x01
#define INVALIDPARAMETER 0x02
#define INVALID_TASK 0x03
#define MSG_BUFFER_NOT_AVAIL 0x04
#define INVALID_MSG_POINTER 0x05
#define INVALID_EVENT_ID 0x06
#define INVALID_INTERRUPT_ID 0x07
#define NO_TIMER_AVAIL 0x08
#define NV_ITEM_UNINIT 0x09
#define NV_OPER_FAILED 0x0A
#define INVALID_MEM_SIZE 0x0B
#define NV_BAD_ITEM_LEN 0x0C
#define NV_INVALID_DATA 0x0D
// ZStack status values must start at 0x10, after the generic status values (defined in comdef.h)
#define ZMemError 0x10
#define ZBufferFull 0x11
#define ZUnsupportedMode 0x12
#define ZMacMemError 0x13
#define ZSapiInProgress 0x20
#define ZSapiTimeout 0x21
#define ZSapiInit 0x22
#define ZNotAuthorized 0x7E
#define ZMalformedCmd 0x80
#define ZUnsupClusterCmd 0x81
// OTA Status values
#define ZOtaAbort 0x95
#define ZOtaImageInvalid 0x96
#define ZOtaWaitForData 0x97
#define ZOtaNoImageAvailable 0x98
#define ZOtaRequireMoreImage 0x99
// APS status values
#define ZApsFail 0xb1
#define ZApsTableFull 0xb2
#define ZApsIllegalRequest 0xb3
#define ZApsInvalidBinding 0xb4
#define ZApsUnsupportedAttrib 0xb5
#define ZApsNotSupported 0xb6
#define ZApsNoAck 0xb7
#define ZApsDuplicateEntry 0xb8
#define ZApsNoBoundDevice 0xb9
#define ZApsNotAllowed 0xba
#define ZApsNotAuthenticated 0xbb
// Security status values
#define ZSecNoKey 0xa1
#define ZSecOldFrmCount 0xa2
#define ZSecMaxFrmCount 0xa3
#define ZSecCcmFail 0xa4
#define ZSecFailure 0xad
// NWK status values
#define ZNwkInvalidParam 0xc1
#define ZNwkInvalidRequest 0xc2
#define ZNwkNotPermitted 0xc3
#define ZNwkStartupFailure 0xc4
#define ZNwkAlreadyPresent 0xc5
#define ZNwkSyncFailure 0xc6
#define ZNwkTableFull 0xc7
#define ZNwkUnknownDevice 0xc8
#define ZNwkUnsupportedAttribute 0xc9
#define ZNwkNoNetworks 0xca
#define ZNwkLeaveUnconfirmed 0xcb
#define ZNwkNoAck 0xcc // not in spec
#define ZNwkNoRoute 0xcd
// MAC status values
#define ZMacSuccess 0x00
#define ZMacBeaconLoss 0xe0
#define ZMacChannelAccessFailure 0xe1
#define ZMacDenied 0xe2
#define ZMacDisableTrxFailure 0xe3
#define ZMacFailedSecurityCheck 0xe4
#define ZMacFrameTooLong 0xe5
#define ZMacInvalidGTS 0xe6
#define ZMacInvalidHandle 0xe7
#define ZMacInvalidParameter 0xe8
#define ZMacNoACK 0xe9
#define ZMacNoBeacon 0xea
#define ZMacNoData 0xeb
#define ZMacNoShortAddr 0xec
#define ZMacOutOfCap 0xed
#define ZMacPANIDConflict 0xee
#define ZMacRealignment 0xef
#define ZMacTransactionExpired 0xf0
#define ZMacTransactionOverFlow 0xf1
#define ZMacTxActive 0xf2
#define ZMacUnAvailableKey 0xf3
#define ZMacUnsupportedAttribute 0xf4
#define ZMacUnsupported 0xf5
#define ZMacSrcMatchInvalidIndex 0xff
}
//TI Zigbee Structures
//---------------
//Request Packets
//---------------
//This header is present in every TI Zigbee api packet
//LSB 1-byte Checksum follows the payload and is the sum of all values from primary header to end of payload
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t payload; //Payload goes here: set by the caller, variable length
} __attribute__((packed)) tizigbee_api_header_t;
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t param1; //First parameter goes here
uint8_t checksum;
} __attribute__((packed)) tizigbee_api_header_with_8bit_param_t;
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t param1; //First parameter goes here
uint8_t checksum;
} __attribute__((packed)) tizigbee_api_header_with_16bit_param_t;
//SYS_RESET api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t reset_type; //RESET_TYPE type
uint8_t checksum;
} __attribute__((packed)) tizigbee_sys_reset_t;
//AF_REGISTER api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t endpoint;
uint16_t profileid; //LSB, MSB
uint16_t devid; //LSB, MSB
uint8_t devver;
uint8_t zero;
uint8_t clusterlist; //First zigbee_zdo_node_clusters_t is input clusters list then output clusters to match
uint8_t checksum;
} __attribute__((packed)) tizigbee_af_register_t;
//ZB_GET_DEVICE_INFO api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t devinfotype; //Type of device info to retrieve
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_get_device_info_t;
//ZB_WRITE_CONFIGURATION api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t configid;
uint8_t vallen; //Length of value
uint8_t value;
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_write_configuration_req_8bit_t;
//ZB_WRITE_CONFIGURATION api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t configid;
uint8_t vallen; //Length of value
uint16_t value; //LSB, MSB
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_write_configuration_req_16bit_t;
//ZB_WRITE_CONFIGURATION api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t configid;
uint8_t vallen; //Length of value
uint32_t value; //LSB, MSB
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_write_configuration_req_32bit_t;
//ZB_WRITE_CONFIGURATION api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t configid;
uint8_t vallen; //Length of value
uint64_t value; //LSB, MSB
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_write_configuration_req_64bit_t;
//ZB_WRITE_CONFIGURATION api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t configid;
uint8_t vallen; //Length of value
uint8_t value[8]; //LSB, MSB
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_write_configuration_req_8byte_t;
//ZDO_MSG_CB_REGISTER api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t cluster; //LSB, MSB: The cluster to listen for or 0xFFFF to listen for all clusters
uint8_t checksum;
} __attribute__((packed)) tizigbee_zdo_msg_cb_register_t;
//ZDO_STARTUP_FROM_APP api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t start_delay; //LSB, MSB: Specifies the time delay before the device starts in milliseconds
uint8_t checksum;
} __attribute__((packed)) tizigbee_zdo_startup_from_app_t;
//Generic Zigbee ZDO request with appropriate values for sending any type of ZDO Command
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Should be set to zigbeelib->zdocmd->zigbeelength+2 , structure size will be this length+5
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t destnetaddr; //LSB, MSB
uint8_t zigbeepayload; //Maps to the ZDO command structure
uint8_t checksum; //This goes after the zigbee payload
} __attribute__((packed)) tizigbee_zdo_general_request_t;
//Generic Zigbee ZDO request without destnetaddr with appropriate values for sending any type of ZDO Command
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Should be set to zigbeelib->zdocmd->zigbeelength+2 , structure size will be this length+5
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t zigbeepayload; //Maps to the ZDO command structure
uint8_t checksum; //This goes after the zigbee payload
} __attribute__((packed)) tizigbee_zdo_general_request_without_destnetaddr_t;
//ZDO_IEEE_ADDR_REQ api packet
typedef tizigbee_zdo_general_request_without_destnetaddr_t tizigbee_zdo_mgmt_ieee_addr_req_t;
//ZDO_MATCH_DESC_REQ api packet
typedef tizigbee_zdo_general_request_t tizigbee_zdo_match_desc_req_t;
//ZDO_MGMT_LQI_REQ api packet
typedef tizigbee_zdo_general_request_t tizigbee_zdo_mgmt_lqi_req_t;
//ZDO_MGMT_PERMIT_JOIN_REQ api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t addrmode; //0x02 - Address 16 bit, 0x0F - Broadcast
uint16_t netaddr; //LSB, MSB
uint8_t duration; //Specifies the time that joining should be enabled (in seconds), 0=Disabled, or 0xFF=Enabled permanently
uint8_t trust_center_significance; //If set to 1 and remote is a trust center, the command affects the trust center authentication policy, otherwise it has no effect
uint8_t checksum;
} __attribute__((packed)) tizigbee_zdo_mgmt_permit_join_req_t;
//ZDO_SEND_DATA api packet
//Can be used to send any ZDO packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t destnetaddr; //LSB, MSB
uint8_t seqnumber;
uint16_t clusterid; //LSB, MSB: Cluster ID
uint8_t zigbeelength;
uint8_t zigbeepayload; //Maps to the ZDO command structure
uint8_t checksum;
} __attribute__((packed)) tizigbee_zdo_send_data_t;
//AF_DATA_REQUEST api packet 16-bit address version
//Can be used to send any ZDO or ZCL packet
//NOTE: TI Zigbee Command: ZDO_SEND_DATA sets options to 0x0 and radius 0x1E
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length;
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t netaddr; //LSB, MSB
uint8_t destendpoint;
uint8_t srcendpoint;
uint16_t clusterid; //LSB: Cluster ID
uint8_t seqnumber; //Host must use 0-127, Module uses 128-255
uint8_t options; //0x02: AF_WILDCARD_PROFILEID: Will force the message to use Wildcard ProfileID
//0x04: AF_PREPROCESS: Will force APS to callback to preprocess before calling NWK layer
//0x08: AF_LIMIT_CONCENTRATOR: Check if route is available before sending data
//0x10: AF_ACK_REQUEST: Require a response to be returned
//0x20: AF_SUPRESS_ROUTE_DISC_NETWORK: Supress Route Discovery for intermediate routes
//0x40: AF_EN_SECURITY: Enable security
//0x80: AF_SKIP_ROUTING
uint8_t radius; //the number of hops allowed to deliver the message; usually use 7
uint8_t zigbeelength;
uint8_t zigbeepayload; //Maps to the command structure depending what cmdid was specified
uint8_t checksum;
} __attribute__((packed)) tizigbee_af_data_request_t;
typedef struct {
uint8_t frame_control; //bits 0-1: 0=ZCL General Command
// 1=Cluster-Specific Command
//bit 2: 1=Manufacturer-Specific Command
//bit 3: 0=Client to Server
// 1=Server to Client
//bit 4: 1=Disable Default Response
//bits 5-7: Reserved
uint8_t seqnumber;
uint8_t cmdid; //The Zigbee ZCL Command ID
uint8_t zigbeepayload; //Maps to the ZCL command structure depending what cmdid was specified
} __attribute__((packed)) tizigbee_zcl_general_request_t;
typedef struct {
uint8_t frame_control; //bits 0-1: 0=ZCL General Command
// 1=Cluster-Specific Command
//bit 2: 1=Manufacturer-Specific Command
//bit 3: 0=Client to Server
// 1=Server to Client
//bit 4: 1=Disable Default Response
//bits 5-7: Reserved
uint16_t manu; //LSB: Manufacturer code (Only used if Bit 2 of frame control is enabled but always included in packet)
uint8_t seqnumber;
uint8_t cmdid; //The Zigbee ZCL Command ID
uint8_t zigbeepayload; //Maps to the ZCL command structure depending what cmdid was specified
} __attribute__((packed)) tizigbee_zcl_general_request_with_manu_t;
//----------------
//Response Packets
//----------------
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t payload; //Payload goes here: set by the caller, variable length
} __attribute__((packed)) tizigbee_api_response_t;
typedef struct {
uint8_t frame_start;
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t capabilities; //First byte is LSB, second byte is MSB
uint8_t checksum;
} __attribute__((packed)) tizigbee_sys_ping_response_t;
typedef struct {
uint8_t frame_start;
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t transportrev; //Transport Revision
uint8_t product; //Product Type
uint8_t major_firmware_version;
uint8_t minor_firmware_version;
uint8_t hwrev; //Hardware Revision
uint8_t checksum;
} __attribute__((packed)) tizigbee_sys_version_response_t;
typedef struct {
uint8_t frame_start;
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t reason; //Reset Reason
uint8_t transportrev; //Transport Revision
uint8_t product; //Product Type
uint8_t major_firmware_version;
uint8_t minor_firmware_version;
uint8_t hwrev; //Hardware Revision
uint8_t checksum;
} __attribute__((packed)) tizigbee_sys_reset_response_t;
//ZB_GET_DEVICE_INFO_RESPONSE api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Length is always 8
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t devinfotype; //Type of device info in this response
multitypeval_t devinfo;
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_get_device_info_response_t;
//ZB_READ_CONFIGURATION_RESPONSE api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t status; //The result of the read operation (0=Success)
uint8_t configid; //The identifier of the property that was read
uint8_t proplen; //The length of the property
multitypeval_t value; //The value of the property
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_read_configuration_response_t;
//ZB_WRITE_CONFIGURATION_RESPONSE api packet
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t status; //The result of the write operation (0=Success)
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_write_configuration_response_t;
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t status; //The result of the read operation (0=Success)
uint8_t configid; //The identifier of the property that was read
uint8_t proplen; //The length of the property
uint8_t NetworkMode; //The current network mode of the TI Zigbee
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_read_configuration_response_nv_logical_type_t;
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t status; //The result of the read operation (0=Success)
uint8_t configid; //The identifier of the property that was read
uint8_t proplen; //The length of the property
uint8_t networkKey[16]; //LSB, MSB: The network key being used
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_read_configuration_response_nv_precfgkey_t;
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t status; //The result of the read operation (0=Success)
uint8_t configid; //The identifier of the property that was read
uint8_t proplen; //The length of the property
uint8_t distributeNetworkKey; //0 or 1: Whether to distribute the network key in clear
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_read_configuration_response_nv_precfgkeys_enable_t;
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t status; //The result of the read operation (0=Success)
uint8_t configid; //The identifier of the property that was read
uint8_t proplen; //The length of the property
uint8_t securityMode;
uint8_t checksum;
} __attribute__((packed)) tizigbee_zb_read_configuration_response_nv_security_mode_t;
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t status; //The result of the command (0=Success)
} __attribute__((packed)) tizigbee_zdo_generic_srsp_t;
//ZDO_STATE_CHANGE_IND
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t status; //The status: ZDO_STARTUP_STATUS
} __attribute__((packed)) tizigbee_zdo_state_change_ind_t;
//ZDO_SRC_RTG_IND
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t srcnetaddr; //LSB, MSB : Network Address of the remote Zigbee device
uint8_t numrelays;
uint16_t relaynetaddr[128]; //A network address in the relay list
uint8_t checksum; //This is after numrelays*sizeof(uint16_t)
} __attribute__((packed)) tizigbee_zdo_src_rtg_ind_t;
//ZDO_LEAVE_IND
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t srcnetaddr; //LSB, MSB : Network Address of the remote Zigbee device
uint64_t addr; //LSB, MSB : 64-bit IEEE Address of the remote Zigbee device
uint16_t netaddr; //LSB, MSB : IS this the Zigbee coordinator/router device that connected the end device?
uint8_t checksum;
} __attribute__((packed)) tizigbee_zdo_leave_ind_t;
//ZDO_TC_DEVICE_IND
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t srcnetaddr; //LSB, MSB : Network Address of the remote Zigbee device
uint64_t addr; //LSB, MSB : 64-bit IEEE Address of the remote Zigbee device
uint16_t netaddr; //LSB, MSB : IS this the Zigbee coordinator/router device that connected the end device?
uint8_t checksum;
} __attribute__((packed)) tizigbee_zdo_tc_device_ind_t;
//ZDO_PERMIT_JOIN_IND
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t value; //Unknown
} __attribute__((packed)) tizigbee_zdo_permit_join_ind_t;
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t srcnetaddr; //LSB, MSB
uint8_t wasBroadcast;
uint16_t clusterid; //LSB, MSB
uint8_t securityUse;
uint8_t seqnumber;
uint16_t destnetaddr; //LSB, MSB
uint8_t status; //status from remote Zigbee device
uint8_t zigbeepayload; //Rest of zigbee data
} __attribute__((packed)) tizigbee_zdo_msg_cb_incoming_t;
//AF_DATA_CONFIRM
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint8_t status; //The result of the command (0=Success)
uint8_t endpoint;
uint8_t seqnumber;
} __attribute__((packed)) tizigbee_af_data_confirm_t;
typedef tizigbee_zdo_generic_srsp_t tizigbee_af_data_srsp_t;
//AF_INCOMING_MSG
typedef struct {
uint8_t frame_start; //Always set to 0xFE
uint8_t length; //Number of bytes in the payload
uint16_t cmd; //TI Zigbee Command : First byte: MSB, Second byte: LSB
uint16_t groupid; //LSB, MSB: Message's group ID - 0 if not set
uint16_t clusterid; //LSB, MSB
uint16_t srcnetaddr; //LSB, MSB
uint8_t srcendpoint;
uint8_t destendpoint;
uint8_t wasbroadcast;
uint8_t linkquality;
uint8_t securityuse; //Not used
uint32_t timestamp;
uint8_t seqnumber; //Often seems to be 0
uint8_t zigbeelength; //Seems to be the length of the zcl zigbeepayload or +2 when manu specific command
uint8_t zigbeepayload;
} __attribute__((packed)) tizigbee_af_incoming_msg_t;
} //End of namespace
#endif
| 21,433
|
https://github.com/GitHubMaxwell/food_suite/blob/master/src/components/UHF/Header.js
|
Github Open Source
|
Open Source
|
MIT
| null |
food_suite
|
GitHubMaxwell
|
JavaScript
|
Code
| 5
| 7
|
// a simple navigation menu
| 4,555
|
https://github.com/chromium/chromium/blob/master/ash/calendar/DEPS
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,023
|
chromium
|
chromium
|
Python
|
Code
| 5
| 19
|
include_rules = [
"+google_apis/calendar",
]
| 42,244
|
https://github.com/mmagnuski/mne-python/blob/master/mne/io/cnt/__init__.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
mne-python
|
mmagnuski
|
Python
|
Code
| 4
| 11
|
from .cnt import read_raw_cnt
| 38,111
|
https://github.com/Trainmaster/Vision/blob/master/src/Form/Control/Text.php
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
Vision
|
Trainmaster
|
PHP
|
Code
| 21
| 56
|
<?php
declare(strict_types=1);
namespace Vision\Form\Control;
class Text extends AbstractInput
{
/** @var array $attributes */
protected $attributes = ['type' => 'text'];
}
| 8,493
|
https://github.com/FNSOIDATHQ/localization-tool-for-Men-of-War/blob/master/localization-tool-for-Men-of-War_v0_1/setting.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
localization-tool-for-Men-of-War
|
FNSOIDATHQ
|
C++
|
Code
| 77
| 509
|
#include "setting.h"
#include "ui_setting.h"
#include <QFileDialog>
Setting::Setting(QWidget *parent) :
QDialog(parent),
ui(new Ui::Setting)
{
ui->setupUi(this);
setWindowTitle("Setting");
}
Setting::~Setting()
{
delete ui;
}
void Setting::quick_type_local()
{
QString in=QFileDialog::getExistingDirectory(this,"open","/");
if(in.isEmpty()){
return ;
}
ui->localization->setText(in);
}
void Setting::quick_type_res()
{
QString in=QFileDialog::getExistingDirectory(this,"open","/");
if(in.isEmpty()){
return ;
}
ui->resource->setText(in);
}
void Setting::quick_type_unit_type()
{
QString in=QFileDialog::getOpenFileName(this,"open","/");
if(in.isEmpty()){
return ;
}
ui->link_set->setText(in);
}
void Setting::when_button_accepted()
{
pre_link=ui->link_set->text();
pre_type=ui->unit_link_set->currentText();
if(pre_type!="none"&&!pre_type.isEmpty()){
link_set.insert(pre_type,pre_link);
}
emit readpath(ui->localization->text(),ui->resource->text(),link_set);
//emit readpath("111","222");
this->close();
}
void Setting::change_link_set()
{
if(pre_type!="none"&&!pre_type.isEmpty()){
link_set.insert(pre_type,pre_link);
}
pre_link=ui->link_set->text();
pre_type=ui->unit_link_set->currentText();
}
| 25,617
|
https://github.com/seatonullberg/PyPPA/blob/master/Scripts/build_identity_profile.py
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,017
|
PyPPA
|
seatonullberg
|
Python
|
Code
| 237
| 738
|
import dlib
import pickle
import numpy as np
import os
import argparse
from utils import path_utils
from utils import identity_profile_utils
def main(path=None):
"""
Creates an IdentityProfile
:param path: (str) absolute path to a directory containing training images
- the end of the path should be a directory named after the person
- e.g. Seaton_Ullberg
- all images in the directory should contain only the face of the target
"""
# process args
parser = argparse.ArgumentParser()
parser.add_argument('--path',
default=None,
help="Path to directory containing face images")
args = parser.parse_args()
if path is None:
if args.path is None:
raise argparse.ArgumentError("--path is a required argument")
else:
path = args.path
# load the pretrained dlib models
local_paths = path_utils.LocalPaths()
detector = dlib.get_frontal_face_detector()
shape_predictor_path = os.path.join(local_paths.bin, "shape_predictor_5_face_landmarks.dat")
shape_predictor = dlib.shape_predictor(shape_predictor_path)
face_recognition_model_path = os.path.join(local_paths.bin, "dlib_face_recognition_resnet_model_v1.dat")
face_recognition_model = dlib.face_recognition_model_v1(face_recognition_model_path)
# iterate through a directory of images to calculate a 128D face description vector
descriptors = []
for fname in os.listdir(path):
img_path = os.path.join(path, fname)
img = dlib.load_rgb_image(img_path)
detections = detector(img, 1)
if len(detections) != 1: # only use single face images
continue
d = detections[0]
shape = shape_predictor(img, d)
face_descriptor = face_recognition_model.compute_face_descriptor(img, shape, 10)
descriptors.append(face_descriptor)
final_descriptor = np.mean(descriptors, axis=0)
# generate an IdentityProfile and save the descriptor alongside it
dir_name = os.path.basename(path)
pickle_path = os.path.join(local_paths.identity_profiles, dir_name, "{}")
# make the new profile dir and yaml file
identity_profile_utils.new_profile(dir_name)
# save face descriptor as a pickle
with open(pickle_path.format("face_descriptor.p"), 'wb') as stream:
pickle.dump(final_descriptor, stream)
if __name__ == "__main__":
main("/home/seaton/Pictures/Seaton_Ullberg")
| 2,181
|
https://github.com/Leeway213/BSP_AW1689_src/blob/master/src/drivers/Audio/VirtualI2S/I2SInterface.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
BSP_AW1689_src
|
Leeway213
|
C++
|
Code
| 802
| 2,936
|
/** @file
*
* Copyright (c) 2007-2016, Allwinner Technology Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**/
#include "I2SInterface.h"
#include "Device.h"
#include "DMA.h"
#include "Trace.h"
#include "I2SInterface.tmh"
void I2SInterfaceReference(
_In_ PVOID pContext)
{
PDEVICE_CONTEXT pDevExt = NULL;
FunctionEnter();
if (NULL == pContext)
{
DbgPrint_E("Invalid parameter.");
goto Exit;
}
pDevExt = DeviceGetContext((WDFDEVICE)pContext);
InterlockedIncrement((LONG *)&pDevExt->I2sInterfaceRef);
Exit:
FunctionExit(STATUS_SUCCESS);
return;
}
void I2SInterfaceDereference(
_In_ PVOID pContext)
{
PDEVICE_CONTEXT pDevExt = NULL;
FunctionEnter();
if (NULL == pContext)
{
DbgPrint_E("Invalid parameter.");
goto Exit;
}
pDevExt = DeviceGetContext((WDFDEVICE)pContext);
InterlockedDecrement((LONG *)&pDevExt->I2sInterfaceRef);
Exit:
FunctionExit(STATUS_SUCCESS);
return;
}
NTSTATUS I2SSetTransmitCallback(
_In_ PVOID pContext,
_In_ PI2S_TRANSMISSION_CALLBACK pTransmissionCallback)
{
NTSTATUS Status = STATUS_SUCCESS;
PDEVICE_CONTEXT pDevExt = NULL;
FunctionEnter();
if ((NULL == pContext)
|| (NULL == pTransmissionCallback))
{
DbgPrint_E("Invalid parameters.");
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
pDevExt = DeviceGetContext((WDFDEVICE)pContext);
pDevExt->DmaTransmitCallback.pCallbackContext = pTransmissionCallback->pCallbackContext;
pDevExt->DmaTransmitCallback.pCallbackRoutine = pTransmissionCallback->pCallbackRoutine;
Exit:
FunctionExit(Status);
return Status;
}
NTSTATUS I2SSetReceiveCallback(
_In_ PVOID pContext,
_In_ PI2S_TRANSMISSION_CALLBACK pTransmissionCallback)
{
NTSTATUS Status = STATUS_SUCCESS;
PDEVICE_CONTEXT pDevExt = NULL;
FunctionEnter();
if ((NULL == pContext)
|| (NULL == pTransmissionCallback))
{
DbgPrint_E("Invalid parameters.");
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
pDevExt = DeviceGetContext((WDFDEVICE)pContext);
pDevExt->DmaReceiveCallback.pCallbackContext = pTransmissionCallback->pCallbackContext;
pDevExt->DmaReceiveCallback.pCallbackRoutine = pTransmissionCallback->pCallbackRoutine;
Exit:
FunctionExit(Status);
return Status;
}
NTSTATUS I2STransmit(
_In_ PVOID pContext,
_In_ PMDL pTransferMdl,
_In_ ULONG TransferSize,
_In_ ULONG NotificationsPerBuffer)
{
NTSTATUS Status = STATUS_SUCCESS;
PDEVICE_CONTEXT pDevExt = NULL;
FunctionEnter();
if ((NULL == pContext)
|| (NULL == pTransferMdl))
{
DbgPrint_E("Invalid parameters.");
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
pDevExt = DeviceGetContext((WDFDEVICE)pContext);
Status = I2SDmaTransmit(pDevExt, pTransferMdl, TransferSize, NotificationsPerBuffer);
if (!NT_SUCCESS(Status))
{
DbgPrint_E("Failed to start transmit DMA with 0x%lx.", Status);
goto Exit;
}
//
// TODO: Start DMA HW TX here, if necessary
//
Exit:
FunctionExit(Status);
return Status;
}
NTSTATUS I2SReceive(
_In_ PVOID pContext,
_In_ PMDL pTransferMdl,
_In_ ULONG TransferSize,
_In_ ULONG NotificationsPerBuffer)
{
NTSTATUS Status = STATUS_SUCCESS;
PDEVICE_CONTEXT pDevExt = NULL;
FunctionEnter();
if ((NULL == pContext)
|| (NULL == pTransferMdl))
{
DbgPrint_E("Invalid parameters.");
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
pDevExt = DeviceGetContext((WDFDEVICE)pContext);
Status = I2SDmaReceive(pDevExt, pTransferMdl, TransferSize, NotificationsPerBuffer);
if (!NT_SUCCESS(Status))
{
DbgPrint_E("Failed to start receive DMA with 0x%lx.", Status);
goto Exit;
}
//
// TODO: Start DMA HW RX here, if necessary
//
Exit:
FunctionExit(Status);
return Status;
}
NTSTATUS I2SStopTransfer(
_In_ PVOID pContext,
_In_ BOOL IsCapture)
{
NTSTATUS Status = STATUS_SUCCESS;
PDEVICE_CONTEXT pDevExt = NULL;
FunctionEnter();
if (NULL == pContext)
{
DbgPrint_E("Invalid parameter.");
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
pDevExt = DeviceGetContext((WDFDEVICE)pContext);
Status = I2SDmaStop(pDevExt, IsCapture);
Exit:
FunctionExit(Status);
return Status;
}
NTSTATUS I2SSetStreamFormat(
_In_ PVOID pContext,
_In_ BOOL IsCapture,
_In_ PWAVEFORMATEXTENSIBLE pWaveFormatExt)
{
NTSTATUS Status = STATUS_SUCCESS;
PDEVICE_CONTEXT pDevExt = NULL;
FunctionEnter();
if ((NULL == pContext) || (NULL == pWaveFormatExt))
{
DbgPrint_E("Invalid parameters.");
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
pDevExt = DeviceGetContext((WDFDEVICE)pContext);
//
// TODO: Set the format to HW here
//
//
// TODO: Set the I2S clock here, if necessary
//
UNREFERENCED_PARAMETER(IsCapture);
Exit:
FunctionExit(Status);
return Status;
}
NTSTATUS I2SSetPowerState(
_In_ PVOID pContext,
_In_ DEVICE_POWER_STATE PowerState)
{
NTSTATUS Status = STATUS_SUCCESS;
PDEVICE_CONTEXT pDevExt = NULL;
UNREFERENCED_PARAMETER(PowerState);
FunctionEnter();
if (NULL == pContext)
{
DbgPrint_E("Invalid parameter.");
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
pDevExt = DeviceGetContext((WDFDEVICE)pContext);
DbgPrint_I("Set power state to [D %d].", PowerState - PowerDeviceD0);
if ((PowerState - PowerDeviceD0) == (pDevExt->PowerState - WdfPowerDeviceD0))
{
DbgPrint_I("The device is already in the state, do nothing.");
if (pDevExt->IdleState <= 0)
{
DbgPrint_E("FIXED : WdfDeviceStopIdle ...");
Status = WdfDeviceStopIdle(pDevExt->pDevice, TRUE);
pDevExt->IdleState++;
}
if (WdfPowerDeviceD3 == PowerState)
{
if ((NULL != pDevExt->PowerDownCompletionCallback.pCallbackContext)
&& (NULL != pDevExt->PowerDownCompletionCallback.pCallbackRoutine))
{
pDevExt->PowerDownCompletionCallback.pCallbackRoutine(pDevExt->PowerDownCompletionCallback.pCallbackContext);
}
}
goto Exit;
}
if (PowerDeviceD0 == PowerState)
{
// Wake up the device once the power state changed Dx->D0
Status = WdfDeviceStopIdle(pDevExt->pDevice, TRUE);
if (!NT_SUCCESS(Status))
{
DbgPrint_E("Failed to stop idle with 0x%lx.", Status);
goto Exit;
}
pDevExt->IdleState++;
}
else if (WdfPowerDeviceD0 == pDevExt->PowerState)
{
Status = I2SDmaStop(pDevExt, TRUE);
Status |= I2SDmaStop(pDevExt, FALSE);
if (!NT_SUCCESS(Status))
{
DbgPrint_E("Failed to stop DMA with 0x%lx.", Status);
goto Exit;
}
// Power down the device once the power state changed D0->Dx
ASSERT(pDevExt->IdleState > 0);
WdfDeviceResumeIdle(pDevExt->pDevice);
pDevExt->IdleState--;
}
else
{
// TODO :: Uncover state
DbgPrint_E("Uncovered !! Set power state to [D %d]. Current State is [D %d]",
PowerState - PowerDeviceD0, pDevExt->PowerState - WdfPowerDeviceD0);
}
Exit:
FunctionExit(Status);
return Status;
}
NTSTATUS I2SSetPowerDownCompletionCallback(
_In_ PVOID pContext,
_In_ PI2S_POWER_DOWN_COMPLETION_CALLBACK pPowerDownCompletionCallback)
{
NTSTATUS Status = STATUS_SUCCESS;
PDEVICE_CONTEXT pDevExt = NULL;
FunctionEnter();
if ((NULL == pContext)
|| (NULL == pPowerDownCompletionCallback))
{
DbgPrint_E("Invalid parameters.");
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
pDevExt = DeviceGetContext((WDFDEVICE)pContext);
pDevExt->PowerDownCompletionCallback.pCallbackContext = pPowerDownCompletionCallback->pCallbackContext;
pDevExt->PowerDownCompletionCallback.pCallbackRoutine = pPowerDownCompletionCallback->pCallbackRoutine;
Exit:
FunctionExit(Status);
return Status;
}
| 25,228
|
https://github.com/sardjv/murfin_method/blob/master/app/javascript/stylesheets/graph_tabs.scss
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
murfin_method
|
sardjv
|
SCSS
|
Code
| 35
| 120
|
.thin-tabs {
.nav {
.nav-item {
font-weight: bold;
.nav-link {
border: none;
color: $black;
font-size: 80%;
padding: 4px;
padding-right: 8px;
margin-right: 8px;
&.active {
color: $primary;
border-bottom: 4px solid $primary;
}
}
}
}
}
| 2,382
|
https://github.com/RustPython/RustPython/blob/master/wasm/demo/snippets/fetch.py
|
Github Open Source
|
Open Source
|
CC-BY-4.0, MIT
| 2,023
|
RustPython
|
RustPython
|
Python
|
Code
| 22
| 97
|
from browser import fetch
def fetch_handler(res):
print(f"headers: {res['headers']}")
fetch(
"https://httpbin.org/get",
response_format="json",
headers={
"X-Header-Thing": "rustpython is neat!"
},
).then(fetch_handler, lambda err: print(f"error: {err}"))
| 41,844
|
https://github.com/hashier/NewsBlur/blob/master/clients/android/NewsBlur/build.gradle
|
Github Open Source
|
Open Source
|
MIT, LicenseRef-scancode-unknown-license-reference
| 2,021
|
NewsBlur
|
hashier
|
Gradle
|
Code
| 142
| 749
|
buildscript {
ext.kotlin_version = '1.5.30'
repositories {
mavenCentral()
maven {
url 'https://maven.google.com'
}
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.0.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
repositories {
mavenCentral()
maven {
url 'https://maven.google.com'
}
jcenter()
google()
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.fragment:fragment-ktx:1.3.6'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.9.2'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.android.billingclient:billing:3.0.3'
implementation 'nl.dionsegijn:konfetti:1.2.2'
implementation 'com.google.android.play:core:1.10.0'
implementation "com.google.android.material:material:1.3.0"
implementation "androidx.preference:preference-ktx:1.1.1"
implementation "androidx.browser:browser:1.3.0"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.1"
}
android {
compileSdkVersion 30
defaultConfig {
applicationId "com.newsblur"
minSdkVersion 21
targetSdkVersion 30
versionCode 196
versionName "11.1.1"
}
compileOptions.with {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
android.buildFeatures.viewBinding = true
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
lintOptions {
abortOnError false
}
buildTypes {
debug {
minifyEnabled false
shrinkResources false
}
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
}
}
}
| 28,540
|
https://github.com/DJC-1984/DJC-1984.github.io/blob/master/widgets/Infographic/VersionManager.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
DJC-1984.github.io
|
DJC-1984
|
JavaScript
|
Code
| 827
| 2,691
|
define(['jimu/shared/BaseVersionManager'],
function(BaseVersionManager) {
function VersionManager() {
this.versions = [{
version: '1.0',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '1.1',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '1.2',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '1.3',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '1.4',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '2.0Beta',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '2.0',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '2.0.1',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '2.1',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '2.2',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '2.3',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '2.4',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '2.5',
upgrader: function(oldConfig) {
return oldConfig;
}
}, {
version: '2.6',
upgrader: function(oldConfig) {
var newConfig = oldConfig;
var dijits = newConfig.dijits;
var sortOrder;
for (var i = 0; i < dijits.length; i++) {
if (dijits[i].type === 'chart') {
//sortOrder
sortOrder = dijits[i].config.sortOrder;
dijits[i].config.sortOrder = {
isLabelAxis: true,
isAsc: sortOrder ? sortOrder === 'asc' : true
};
if (dijits[i].config.mode === 'feature') {
dijits[i].config.sortOrder.field = dijits[i].config.labelField;
}
//maxLabel
dijits[i].config.maxLabels = undefined;
//nullValue
if (dijits[i].config.mode === 'feature' || dijits[i].mode === 'count') {
dijits[i].config.nullValue = undefined;
} else {
dijits[i].config.nullValue = true;
}
//dateConfig
dijits[i].config.dateConfig = undefined;
//useLayerSymbology
dijits[i].config.useLayerSymbology = undefined;
}
}
return newConfig;
}
}, {
version: '2.7',
upgrader: function(oldConfig) {
var newConfig = oldConfig;
var dijits = newConfig.dijits;
var chartConfig;
for (var i = 0; i < dijits.length; i++) {
if (dijits[i].type === 'chart') {
chartConfig = dijits[i].config;
break;
}
}
if (!chartConfig || !chartConfig.mode) {
return newConfig;
}
var mode = chartConfig.mode;
var type = chartConfig.type;
var valueFields = chartConfig.valueFields;
/* color and useLayerSymbology upgrade to seriesStyle */
var colors = chartConfig.colors;
if (!colors) {
colors = ['#5d9cd3', '#eb7b3a', '#a5a5a5', '#febf29', '#4673c2', '#72ad4c'];
}
var seriesStyle = {};
//useLayerSymbology
if (typeof chartConfig.useLayerSymbology !== 'undefined') {
if (type === 'line') {
delete chartConfig.useLayerSymbology;
}
}
if (typeof chartConfig.useLayerSymbology !== 'undefined') {
seriesStyle.useLayerSymbology = chartConfig.useLayerSymbology;
}
var notAddedFields = [];
if (valueFields && valueFields.length > 0) {
notAddedFields = valueFields;
}
var colorAsArray = false;
if (type === 'column' || type === 'bar' || type === 'line') {
if (type === 'line' && mode === 'field') {
notAddedFields = ['line~field'];
} else {
if (mode === 'count') {
notAddedFields = ['count~count'];
}
}
} else if (type === 'pie') {
if (mode !== 'field') {
colorAsArray = true;
notAddedFields = ['pie~not-field'];
}
}
var newStyles = notAddedFields.map(function(item, i) {
return createSeriesStyle(item, i, colorAsArray, colors);
}.bind(this));
seriesStyle.styles = {};
if (newStyles) {
seriesStyle.styles = newStyles;
}
chartConfig.seriesStyle = seriesStyle;
if (typeof chartConfig.colors !== 'undefined') {
delete chartConfig.colors;
}
function createSeriesStyle(valueField, index, colorAsArray, colors) {
var style = {
name: valueField,
style: {
color: getRandomColor(colors, index)
}
};
if (colorAsArray) {
style.style.color = colors;
}
return style;
}
function getRandomColor(colors, i) {
var length = colors.length;
i = i % length;
return colors[i];
}
/* disable show legend for count and field mode(expect pie)*/
if (type !== 'pie') {
if (mode === 'count' || mode === 'field') {
chartConfig.showLegend = false;
}
}
/* force dateConfig.isNeedFilled is false for pie chart */
if (type === 'pie') {
if (chartConfig.dateConfig) {
chartConfig.dateConfig.isNeedFilled = false;
}
}
return newConfig;
}
}, {
version: '2.8',
upgrader: function(oldConfig) {
var newConfig = oldConfig;
//get chart dijit config
var dijits = newConfig.dijits;
var chartDijit = dijits.filter(function(d) {
return d.type === 'chart';
})[0];
if (!chartDijit) {
return newConfig;
}
var chartConfig = chartDijit && chartDijit.config;
if (!chartConfig || !chartConfig.mode) {
return newConfig;
}
var seriesStyle = chartConfig.seriesStyle;
if (!seriesStyle) {
return newConfig;
}
//upgrade seriesStyle.useLayerSymbology to seriesStyle.type
seriesStyle.type = seriesStyle.useLayerSymbology ? 'layerSymbol' : 'series';
if (typeof seriesStyle.useLayerSymbology !== 'undefined') {
delete seriesStyle.useLayerSymbology;
}
chartDijit.config = getCleanChartConfig(chartConfig);
function getCleanChartConfig(config) {
var cleanConfig = {
mode: config.mode,
type: config.type
};
var type = cleanConfig.type;
var mode = cleanConfig.mode;
var baseChartProperties = [];
if (mode === 'feature') {
baseChartProperties = baseChartProperties.concat(["labelField", "valueFields", "sortOrder", "maxLabels"]);
} else if (mode === 'category') {
baseChartProperties = baseChartProperties.concat(["categoryField", "dateConfig",
"valueFields", "sortOrder", "operation", "maxLabels", "nullValue"
]);
} else if (mode === 'count') {
baseChartProperties = baseChartProperties.concat(["categoryField", "dateConfig",
"sortOrder", "maxLabels"
]);
} else if (mode === 'field') {
baseChartProperties = baseChartProperties.concat(["valueFields", "operation",
"sortOrder", "maxLabels", "nullValue"
]);
}
var baseDisplayProperties = ["backgroundColor", "seriesStyle", "showLegend",
"legendTextColor", "legendTextSize", "highLightColor"
];
if (type === 'pie') {
baseDisplayProperties = baseDisplayProperties.concat(["showDataLabel", "dataLabelColor",
"dataLabelSize", "innerRadius"
]);
} else {
baseDisplayProperties = baseDisplayProperties.concat([
"showHorizontalAxis",
"horizontalAxisTextColor",
"horizontalAxisTextSize",
"showVerticalAxis",
"verticalAxisTextColor",
"verticalAxisTextSize",
"stack",
"area"
]);
}
baseChartProperties.forEach(function(chartProperty) {
cleanConfig[chartProperty] = config[chartProperty];
});
baseDisplayProperties.forEach(function(displayProperty) {
cleanConfig[displayProperty] = config[displayProperty];
});
//completed some option
if (!cleanConfig.hasOwnProperty("showLegend")) {
cleanConfig.showLegend = false;
}
if (type === 'pie') {
if (!cleanConfig.hasOwnProperty("showDataLabel")) {
cleanConfig.showDataLabel = true;
}
} else {
if (!cleanConfig.hasOwnProperty("showHorizontalAxis")) {
cleanConfig.showHorizontalAxis = true;
}
if (!cleanConfig.hasOwnProperty("showVerticalAxis")) {
cleanConfig.showVerticalAxis = true;
}
}
return cleanConfig;
}
return newConfig;
}
}];
}
VersionManager.prototype = new BaseVersionManager();
VersionManager.prototype.constructor = VersionManager;
return VersionManager;
});
| 37,523
|
https://github.com/samiz/engage-fork/blob/master/takmela-lexer/RExpr.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
engage-fork
|
samiz
|
C#
|
Code
| 524
| 1,775
|
using System;
using System.Collections.Generic;
namespace takmelalexer
{
public interface CharClassPart
{
}
public class CharPartRange : CharClassPart
{
public char From, To;
public CharPartRange(char _From, char _To)
{
From = _From;
To = _To;
}
public override string ToString()
{
return string.Format("CharRange({0}, {1})", From, To);
}
}
public class CharPartSingle : CharClassPart
{
public char Ch;
public CharPartSingle(char _Ch)
{
Ch = _Ch;
}
public override string ToString()
{
return string.Format("CharSingle({0})", Ch);
}
}
public interface RExpr
{
}
public class ByName : RExpr
{
public string Name;
ByName(string _Name)
{
Name = _Name;
}
public override string ToString()
{
return string.Format("ByName({0})", Name);
}
}
public class CharClass : RExpr
{
public List<CharClassPart> Parts;
public CharClass(List<CharClassPart> _Parts)
{
Parts = _Parts;
}
CharClass(params CharClassPart[] _Parts)
{
Parts = new List<CharClassPart> ();
Parts.AddRange(_Parts);
}
public override string ToString()
{
return string.Format("CharClass({0})",Utils.SurroundJoin(Parts, "[", "]", ", "));
}
}
public class NotCharClass : RExpr
{
public List<CharClassPart> Parts;
public NotCharClass(List<CharClassPart> _Parts)
{
Parts = _Parts;
}
public override string ToString()
{
return string.Format("NotCharClass({0})", Utils.SurroundJoin(Parts, "[", "]", ", "));
}
}
public class Oring : RExpr
{
public List<RExpr> Exprs;
public Oring(List<RExpr> _Exprs)
{
Exprs = _Exprs;
}
public override string ToString()
{
return string.Format("Oring({0})", Utils.SurroundJoin(Exprs, "[", "]", ", "));
}
}
public class RXSeq : RExpr
{
public List<RExpr> Exprs;
public RXSeq(List<RExpr> _Exprs)
{
Exprs = _Exprs;
}
public override string ToString()
{
return string.Format("RXSeq({0})", Utils.SurroundJoin(Exprs, "[", "]", ", "));
}
}
public class Plus : RExpr
{
public RExpr Expr;
public Plus(RExpr _Expr)
{
Expr = _Expr;
}
public override string ToString()
{
return string.Format("Plus({0})", Expr);
}
}
public class Question : RExpr
{
public RExpr Expr;
public Question(RExpr _Expr)
{
Expr = _Expr;
}
public override string ToString()
{
return string.Format("Question({0})", Expr);
}
}
public class Star : RExpr
{
public RExpr Expr;
public Star(RExpr _Expr)
{
Expr = _Expr;
}
public override string ToString()
{
return string.Format("Star({0})", Expr);
}
}
public class Str : RExpr
{
public string Value;
public Str(string _value)
{
Value = _value;
}
public override string ToString()
{
return string.Format("Str({0})", Value);
}
}
public class LexerRule
{
public string Name;
public List<string> Within = new List<string>();
public List<string> Pushes = new List<string>();
public List<string> Pops = new List<string>();
public string Class = "";
public bool Skip = false;
public RExpr Expr;
public LexerRule(string _Name,
List<string> _Within,
List<string> _Pushes,
List<string> _Pops,
string _Class,
bool _Skip,
RExpr _Expr)
{
Name = _Name;
Within = _Within;
Pushes = _Pushes;
Pops = _Pops;
Class = _Class;
Skip = _Skip;
Expr = _Expr;
}
LexerRule(string _Name, RExpr _Expr)
{
Name = _Name;
Expr = _Expr;
}
LexerRule(string _Name, RExpr _Expr, bool _Skip)
{
Name = _Name;
Expr = _Expr;
Skip = _Skip;
}
public override string ToString()
{
return string.Format("LexerRule({0}, {1}, {2}, {3}, {4}, {5}, {6})",
Name,
Utils.SurroundJoin(Within, "[", "]", ", "),
Utils.SurroundJoin(Pushes, "[", "]", ", "),
Utils.SurroundJoin(Pops, "[", "]", ", "),
Class,
Skip,
Expr);
}
}
public class LexerModule
{
public List<LexerRule> Rules;
public string ErrorRuleName;
public LexerModule(List<LexerRule> _Rules, string _ErrorRuleName)
{
Rules = _Rules;
ErrorRuleName = _ErrorRuleName;
}
public override string ToString()
{
return string.Format("Module({0})", Utils.SurroundJoin(Rules, "[", "]", ", "));
}
}
}
| 13,703
|
https://github.com/JacoboGallardo/builder/blob/master/packages/shopify/src/functions/fast-clone.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
builder
|
JacoboGallardo
|
TypeScript
|
Code
| 11
| 29
|
export const fastClone = <T extends object>(object: T): T => JSON.parse(JSON.stringify(object));
| 32,137
|
https://github.com/TUHH-ICS/2022-code-real-time-model-predictive-control-for-wind-farms-a-koopman-dynamic-mode-decomposition-app/blob/master/WFSimCode/bin/Kmpc/test run/testQuadProg.m
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
2022-code-real-time-model-predictive-control-for-wind-farms-a-koopman-dynamic-mode-decomposition-app
|
TUHH-ICS
|
MATLAB
|
Code
| 634
| 2,844
|
%% Toy example
clear; close all; clc;
addpath(genpath(pwd))
N = 9; Wp.turbine.N = N; % Number windturbines
Nh = 10; mpc.Nh = Nh; % Number time steps prediction trajectory
noRun = 10;
mpc.A = 0.1*eye(N); mpc.B = 0.9*eye(N); mpc.C = 1*eye(N); xinit = 0*ones(N,1);
mpc.MP = true(mpc.Nh,length(xinit));
sol.k = 1;
mpc.Pref = ones(100,1);
mpc.um = 0.2;
mpc.uM = 2;
mpc.Q = eye(mpc.Nh);
mpc.R = eye(mpc.Nh*N);
sol.turbine.CT_prime = mpc.um*ones(N,1)*4; %mpc.uM;
%% Calculate input U with optimize
% Build matrices horizon, define decision variables. prepare states,
% outputs, power output, tracking error
% build matrices horizon
mpc = matsys(Wp,mpc);
U = sdpvar(Wp.turbine.N*mpc.Nh,1); %define decision variables for windfarm
% prepare states, outputs, power output, tracking error
X = mpc.AA*xinit + mpc.BBt*U ;
Y = mpc.CC*X;
P = reshape(Y(mpc.MP),Wp.turbine.N,mpc.Nh) ;%Power output
E = sum(P,1)' - mpc.Pref(sol.k:sol.k+mpc.Nh-1);
cons = mpc.um <= U <= mpc.uM; % set constraints
% prepare vector with change in input and cost
dU = [ U(1:Wp.turbine.N)-sol.turbine.CT_prime ; U(Wp.turbine.N+1:end)-U(1:end-Wp.turbine.N)];%CT
cost = E'*mpc.Q*E + dU'*mpc.R*dU;
ops = sdpsettings('solver','','verbose',0,'cachesolvers',1);%sdpsettings('solver','cplex','verbose',0,'cachesolvers',1);
% run optimize
tic;
for idx = 1: noRun
optimize(cons,cost,ops);
end
toc_opt = toc;
anU = value(U);
E_num = value(E);
costValue = value(cost);
d_anU = [ anU(1:Wp.turbine.N)-sol.turbine.CT_prime ; ...
anU(Wp.turbine.N+1:end)-anU(1:end-Wp.turbine.N)];%CT
costValue01 = value(E)'*mpc.Q*value(E)+ d_anU'*mpc.R*d_anU;
% solution with optimize function
Xnum = mpc.AA*xinit + mpc.BBt*anU ;
Ynum = mpc.CC*Xnum;
%% Compute Hessian H, derivative g = dJk/dUk %%
% min Jk(Uk) s.t. h1(Uk) = 0, h1(Uk) < 0, at current estimate xl
% <=> min( xtilde'H(xl)xtilde + g(xl)xtilde
% s.t. dh1(xl)xtilde +h1(xl)=0, dh2(xl)x+h2(xl)< 0
% with
% Jk = E'Q E+(Uk-Uss)'R(Uk-Uss) + Psi
% dJk/dUk = 2S'Q (Lx+SUk-Xss) + 2R(Uk-Uss)
Isel = kron(eye(mpc.Nh),ones(1,Wp.turbine.N));
Csel = kron(eye(mpc.Nh*Wp.turbine.N),1);
C_tilde = Isel*Csel;
tic;
for idx = 1: noRun
L_tilde = C_tilde*mpc.AA;
S_tilde = C_tilde*mpc.BBt;
% cost function Jk =E'QE+(dUk)'R(dUk-Uss) with E = Qsum*Qsel*(Lx+SUk-Pref)
utemp = kron(ones(mpc.Nh,1),sol.turbine.CT_prime); %diag(mpc.Ct_ss));
E_approx = (L_tilde*xinit + S_tilde* utemp - mpc.Pref(sol.k:sol.k+mpc.Nh-1));
% calculate gradient of dU'dU: 2*[dU1-dU2, dU2-dU3,...dUN]
deltaUvec = utemp - [sol.turbine.CT_prime; utemp(1:(N*(mpc.Nh-1)))];
grad_dU = deltaUvec - [deltaUvec(N+1:end);zeros(N,1)];
% calculate gradient of dU'dU: 2*[dU1-dU2, dU2-dU3,...dUN]
R2 = [zeros(N*(Nh-1),N),- eye(N*(Nh-1)); zeros(N,N*Nh)];
RH = diag([2*ones(N*(Nh-1),1);ones(N,1)])+ R2 + R2';
% gradient :-
mpc.g = 2*(S_tilde'*mpc.Q*E_approx + mpc.R*grad_dU);
% Hessian:-
H = 2*(S_tilde'*mpc.Q*S_tilde + mpc.R*RH);
mpc.H = 1/2*(H + H'); % for symmetry
% Limits
Ulim_upper = mpc.uM*ones(Nh*N,1);
Ulim_lower = mpc.um*ones(Nh*N,1);
Ac_ = -[eye(Nh*N); -eye(Nh*N)];
bc_ = -[Ulim_lower; - Ulim_upper] - Ac_ * utemp;
end
toc_prepQuadprog = toc;
%% Quadprog
tic;
for idx = 1: noRun
[uval ,fval] = myquadprog(mpc.H,mpc.g,Ac_,bc_);
end
toc_quadprog = toc;
aValue_approx = uval + utemp;
X = mpc.AA*xinit + mpc.BBt*utemp;
Y = mpc.CC*X;
P = reshape(Y(mpc.MP),Wp.turbine.N,mpc.Nh) ;%Power output
Etemp = mpc.Pref(sol.k:sol.k+mpc.Nh-1) - sum(P,1)';
d_utemp = [utemp(1:Wp.turbine.N) - sol.turbine.CT_prime ; ...
utemp(Wp.turbine.N+1:end) - utemp(1:end-Wp.turbine.N)];%CT
% f(x1) = f(x0) + g(x0)*(x1-x0) + 0.5 H(x0) *(x1-x0)^2 = f(x0) +fval
costValue02 = Etemp'*mpc.Q*Etemp + d_utemp'*mpc.R*d_utemp + fval;
% f(aValue_approx)
X = mpc.AA*xinit + mpc.BBt*aValue_approx;
Y = mpc.CC*X;
P = reshape(Y(mpc.MP),Wp.turbine.N,mpc.Nh) ;%Power output
Etemp1 = mpc.Pref(sol.k:sol.k+mpc.Nh-1) - sum(P,1)';
d_utemp2 = [aValue_approx(1:Wp.turbine.N)-sol.turbine.CT_prime ; ...
aValue_approx(Wp.turbine.N+1:end) - aValue_approx(1:end-Wp.turbine.N)];%CT
costValue03 = Etemp1'*mpc.Q*Etemp1 + d_utemp2'*mpc.R*d_utemp2;
% LCP and Lemke's algorithm
Ac_ = [eye(Nh*N); -eye(Nh*N)];
bc_ = [Ulim_lower; - Ulim_upper] - Ac_ * utemp;
tic;
for idx = 1: noRun
Hi = eye(size(mpc.H,1))/mpc.H;
M = Ac_*Hi*Ac_';
q = - Ac_*Hi*mpc.g - bc_;
% n = length(q);
% mpc.mu_old = zeros(n,1);
temp1 = pinv(Ac_') *(mpc.H * utemp + mpc.g);
mpc.mu_old = temp1;
[mu,err] = lemke(M,q,mpc.mu_old);
end
toc_lemke = toc;
if err >0
error('Lemke did not converge');
end
aValue_approxLemke = Hi*(Ac_'*mu - mpc.g) + utemp;
X = mpc.AA*xinit + mpc.BBt*aValue_approxLemke;
Y = mpc.CC*X;
P = reshape(Y(mpc.MP),Wp.turbine.N,mpc.Nh) ;%Power output
Etemp_L = mpc.Pref(sol.k:sol.k+mpc.Nh-1) - sum(P,1)';
d_utemp3 = [aValue_approxLemke(1:Wp.turbine.N)-sol.turbine.CT_prime ; ...
aValue_approxLemke(Wp.turbine.N+1:end) - aValue_approxLemke(1:end-Wp.turbine.N)];%CT
costValue_Lemke = Etemp_L'*mpc.Q*Etemp_L + d_utemp3'*mpc.R*d_utemp3;
%% Diagnostic
fprintf('Cost optimize %2.3f, quadprog %2.3f, Lemke''s %2.3f\n',...
costValue, costValue03, costValue_Lemke);
fprintf('Runtime %d runs: optimize %2.3f, quadprog %2.3f, Lemke''s %2.3f\n',...
noRun, toc_opt, toc_quadprog + toc_prepQuadprog, toc_lemke + toc_prepQuadprog);
isSqrNo = mod(sqrt(N),1) == 0;
| 24,246
|
https://github.com/Peshino/futsal-hlinsko/blob/master/app/Player.php
|
Github Open Source
|
Open Source
|
MIT
| null |
futsal-hlinsko
|
Peshino
|
PHP
|
Code
| 64
| 237
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Player extends Model
{
protected $fillable = [
'firstname', 'lastname', 'history_code', 'jersey_number', 'birthdate', 'position', 'photo', 'futis_code', 'height', 'nationality', 'team_id', 'user_id', 'competition_id'
];
public function team()
{
return $this->belongsTo(Team::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function competition()
{
return $this->belongsTo(Competition::class);
}
public function goals()
{
return $this->hasMany(Goal::class);
}
public function cards()
{
return $this->hasMany(Card::class);
}
}
| 48,872
|
https://github.com/lalongooo/POSSpring/blob/master/src/main/java/com/puntodeventa/global/Entity/CredAmort.java
|
Github Open Source
|
Open Source
|
MIT
| null |
POSSpring
|
lalongooo
|
Java
|
Code
| 444
| 1,393
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.puntodeventa.global.Entity;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author jehernandez
*/
@Entity
@Table(name = "CRED_AMORT")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "CredAmort.findAll", query = "SELECT c FROM CredAmort c"),
@NamedQuery(name = "CredAmort.findByCveCliente", query = "SELECT c FROM CredAmort c WHERE c.credAmortPK.cveCliente = :cveCliente"),
@NamedQuery(name = "CredAmort.findByIdFolio", query = "SELECT c FROM CredAmort c WHERE c.credAmortPK.idFolio = :idFolio"),
@NamedQuery(name = "CredAmort.findByDebt", query = "SELECT c FROM CredAmort c WHERE c.debt = :debt"),
@NamedQuery(name = "CredAmort.findByDeposit", query = "SELECT c FROM CredAmort c WHERE c.deposit = :deposit"),
@NamedQuery(name = "CredAmort.findByDateMov", query = "SELECT c FROM CredAmort c WHERE c.dateMov = :dateMov")})
public class CredAmort implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected CredAmortPK credAmortPK;
@Basic(optional = false)
@Column(name = "DEBT")
private BigInteger debt;
@Column(name = "DEPOSIT")
private BigInteger deposit;
@Column(name = "DATE_MOV")
@Temporal(TemporalType.TIMESTAMP)
private Date dateMov;
@JoinColumn(name = "ID_FOLIO", referencedColumnName = "ID_FOLIO", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Venta ventas;
@JoinColumn(name = "CVE_CLIENTE", referencedColumnName = "CVE_CLIENTE", insertable = false, updatable = false)
@ManyToOne(optional = false)
private Cliente cliente;
public CredAmort() {
}
public CredAmort(CredAmortPK credAmortPK) {
this.credAmortPK = credAmortPK;
}
public CredAmort(CredAmortPK credAmortPK, BigInteger debt) {
this.credAmortPK = credAmortPK;
this.debt = debt;
}
public CredAmort(BigInteger cveCliente, BigInteger idFolio) {
this.credAmortPK = new CredAmortPK(cveCliente, idFolio);
}
public CredAmortPK getCredAmortPK() {
return credAmortPK;
}
public void setCredAmortPK(CredAmortPK credAmortPK) {
this.credAmortPK = credAmortPK;
}
public BigInteger getDebt() {
return debt;
}
public void setDebt(BigInteger debt) {
this.debt = debt;
}
public BigInteger getDeposit() {
return deposit;
}
public void setDeposit(BigInteger deposit) {
this.deposit = deposit;
}
public Date getDateMov() {
return dateMov;
}
public void setDateMov(Date dateMov) {
this.dateMov = dateMov;
}
public Venta getVentas() {
return ventas;
}
public void setVentas(Venta ventas) {
this.ventas = ventas;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
@Override
public int hashCode() {
int hash = 0;
hash += (credAmortPK != null ? credAmortPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof CredAmort)) {
return false;
}
CredAmort other = (CredAmort) object;
if ((this.credAmortPK == null && other.credAmortPK != null) || (this.credAmortPK != null && !this.credAmortPK.equals(other.credAmortPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.puntodeventa.persistence.Entity.CredAmort[ credAmortPK=" + credAmortPK + " ]";
}
}
| 29,715
|
https://github.com/2zqa/project-2.3/blob/master/src/main/java/project23/gui/model/GameLobbyModel.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
project-2.3
|
2zqa
|
Java
|
Code
| 402
| 1,136
|
package project23.gui.model;
import javafx.application.Platform;
import project23.framework.*;
import project23.gui.MainWindow;
import java.util.List;
public class GameLobbyModel extends Model implements ConnectedGameManagerObserver {
private List<String> currentlyShowingPlayers;
private ChallengeRequest lastChallengeRequest;
private boolean isAI;
private GameModel gameModel;
private MainWindow mainWindow;
private ConnectedGameManager cgm;
public GameLobbyModel(GameModel gameModel, MainWindow mainWindow) {
this.gameModel = gameModel;
this.mainWindow = mainWindow;
}
public void setAI(boolean AI) {
isAI = AI;
}
/**
* Requests a refresh of the playerlist. This, in turn, runs #onPlayerListReceive
*/
public void refreshPlayerList() {
cgm.getClient().sendGetPlayerlistMessage();
}
/**
* Returns the players in the lobby, and keeps a local copy (needed for {@link #challengePlayer(int)})
* @return players in lobby
*/
public List<String> getLobbyPlayers() {
this.currentlyShowingPlayers = cgm.getLobbyPlayers();
return currentlyShowingPlayers;
}
/**
* challenges a player, specified by index from the list items in the game lobby
* @param playerListIndex the selected index
*/
public void challengePlayer(int playerListIndex) {
String playername = currentlyShowingPlayers.get(playerListIndex);
cgm.challengePlayer(playername);
setInfoMessage("Challenged " + playername);
updateView();
}
/**
* Starts an online match, nothing to do with challenging
*/
public void prepareOnlineGame() {
gameModel.prepareNewGame();
cgm.requestStart();
}
public void logout() {
cgm.destroy();
}
/**
* Shows any server errors
* @param errorMessage the error message
*/
@Override
public void onServerError(String errorMessage) {
Platform.runLater(() -> {
setDialogMessageAndTitle(errorMessage, "Error");
updateView();
});
}
/**
* Updates the list of lobby players upon receiving playerlist update
*/
@Override
public void onPlayerListReceive() {
Platform.runLater(this::updateView);
}
/**
* Shows challenge messages, as long as player is not playing
* @param challengeRequest the challenge request
*/
@Override
public void onChallengeRequestReceive(ChallengeRequest challengeRequest) {
if (cgm.getBoard().getBoardState() != BoardState.PLAYING && challengeRequest.getGameType().equals(cgm.getGameType())) {
this.lastChallengeRequest = challengeRequest;
Platform.runLater(this::updateView); // zodat melding wordt weergegeven
}
}
/**
* Returns the latest challenge request, and then clears the variable so it cannot be requested again
* @return
*/
public ChallengeRequest getLastChallengeRequest() {
ChallengeRequest lastChallengeRequestTmp = lastChallengeRequest;
lastChallengeRequest = null;
return lastChallengeRequestTmp;
}
/**
* Accepts specified request
* @param request the challengerequest
*/
public void acceptMatch(ChallengeRequest request) {
cgm.acceptChallengeRequest(request);
}
/**
* Switches to game view when game has started
*/
@Override
public void onPostGameStart() {
Platform.runLater(() -> mainWindow.switchView(MainWindow.ViewEnum.GAME));
}
/**
* Sets whether AI or the user should play the match
*/
@Override
public void onPreGameStart() {
cgm.updateSelfPlayerSupplier(isAI ? ConfigData.getInstance().getCurrentGame().createAIPlayerFactory() :
ConfigData.getInstance().getCurrentGame().createLocalPlayerFactory());
}
/**
* Sets local gamemanager, so it does not need to be queried from ConfigData all the time
* Also registers this object as listener for {@link ConnectedGameManagerObserver}.
*/
public void prepareGameManager() {
this.cgm = (ConnectedGameManager) ConfigData.getInstance().getGameManager();
cgm.registerObserver(this);
}
}
| 50,484
|
https://github.com/Texera/texera/blob/master/core/amber/src/main/scala/edu/uci/ics/amber/engine/common/ambermessage/RecoveryPayload.scala
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-free-unknown, Apache-2.0
| 2,023
|
texera
|
Texera
|
Scala
|
Code
| 65
| 170
|
package edu.uci.ics.amber.engine.common.ambermessage
import akka.actor.{ActorRef, Address}
import edu.uci.ics.amber.engine.common.virtualidentity.ActorVirtualIdentity
sealed trait RecoveryPayload extends Serializable {}
// Notify controller on worker recovery starts/ends
final case class UpdateRecoveryStatus(isRecovering: Boolean) extends RecoveryPayload
// Notify upstream worker to resend output to another worker for recovery
final case class ResendOutputTo(vid: ActorVirtualIdentity, ref: ActorRef) extends RecoveryPayload
// Notify controller when the machine fails and triggers recovery
final case class NotifyFailedNode(addr: Address) extends RecoveryPayload
| 44,462
|
https://github.com/ting11222001/Weather-At-Where-You-Are/blob/master/find_nearest.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
Weather-At-Where-You-Are
|
ting11222001
|
Python
|
Code
| 293
| 787
|
# Libraries for below main construction block - index function.
# Allow users to make a request to a web page e.g. an external API to get data.
import requests
# Transform a description of a location into such as a pair of coordinates.
import geocoder
# Use math module to access different mathematical functions.
import math
# Read the API keys from the .env file and use them
import os
from dotenv import load_dotenv
load_dotenv()
def find_nearest():
# Insert government's API URL & parameters.
url = 'https://opendata.cwb.gov.tw/api/v1/rest/datastore/O-A0003-001?Authorization={}&format={}&elementName={}¶meterName={}'
# insert arguments according to its API document.
auth_arg = os.getenv('PROJECT_API_KEY')
format_arg = 'JSON'
ele_arg = 'TEMP,HUMD,24R'
para_arg = 'CITY,TOWN'
# Receive API data according to my specific arguments and it's in JSON format.
req = requests.get(url.format(auth_arg, format_arg, ele_arg, para_arg)).json()
# Next step is to find the nearest weather station in latitude and longitude versus my current location which is also in lat & lon.
# Find location data from the returned JSON.
data = req['records']['location']
# Find where I am with geocoder.
location = geocoder.ip('me').latlng
my_lat = location[0]
my_lon = location[1]
# Append distances of each weather station versus my current location.
result = []
for location in data:
any_lat = location['lat']
any_lon = location['lon']
p1 = [float(my_lat), float(my_lon)]
p2 = [float(any_lat), float(any_lon)]
distance = math.sqrt(((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2))
result.append(distance)
# Find the smallest values among all distances.
nearest = min(result)
# Get the index of the the smallest distance.
nearest_index = result.index(nearest)
# Get the data of the nearest weather station.
nearest_location = data[nearest_index]
# Pass this weather station's data as arguments from main.py to weather.html.
weather = {
'lat': nearest_location['lat'],
'lon': nearest_location['lon'],
'station_name': nearest_location['locationName'],
'station_city': nearest_location['parameter'][0]['parameterValue'],
'station_town': nearest_location['parameter'][1]['parameterValue'],
'time': nearest_location['time']['obsTime'],
'temperature': round(float(nearest_location['weatherElement'][0]['elementValue']), 0),
'humidity': round(float(nearest_location['weatherElement'][1]['elementValue']) * 100, 0),
'rainfall': nearest_location['weatherElement'][2]['elementValue'],
}
return weather, my_lat, my_lon
| 5,604
|
https://github.com/dsrour/DSX2/blob/master/Samples/UWP/D3D12PipelineStateCache/src/UberPixelShader.hlsl.h
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
DSX2
|
dsrour
|
C
|
Code
| 4,773
| 15,712
|
#if 0
//
// Generated by Microsoft (R) HLSL Shader Compiler 10.0.10011.0
//
//
// Buffer Definitions:
//
// cbuffer cb
// {
//
// uint shaderType; // Offset: 0 Size: 4
//
// }
//
//
// Resource Bindings:
//
// Name Type Format Dim HLSL Bind Count
// ------------------------------ ---------- ------- ----------- -------------- ------
// g_samp sampler NA NA s0 1
// g_tex texture float4 2d t0 1
// cb cbuffer NA NA cb0 1
//
//
//
// Input signature:
//
// Name Index Mask Register SysValue Format Used
// -------------------- ----- ------ -------- -------- ------- ------
// SV_POSITION 0 xyzw 0 POS float
// TEXCOORD 0 xy 1 NONE float xy
//
//
// Output signature:
//
// Name Index Mask Register SysValue Format Used
// -------------------- ----- ------ -------- -------- ------- ------
// SV_TARGET 0 xyzw 0 TARGET float xyzw
//
ps_5_0
dcl_globalFlags refactoringAllowed
dcl_immediateConstantBuffer { { 0, 0, 0.106115, 0},
{ 0.003750, 0.006250, 0.102851, 0},
{ -0.003750, -0.006250, 0.102851, 0},
{ 0.008750, 0.014583, 0.093647, 0},
{ -0.008750, -0.014583, 0.093647, 0},
{ 0.013750, 0.022917, 0.080100, 0},
{ -0.013750, -0.022917, 0.080100, 0},
{ 0.018750, 0.031250, 0.064362, 0},
{ -0.018750, -0.031250, 0.064362, 0},
{ 0.023750, 0.039583, 0.048583, 0},
{ -0.023750, -0.039583, 0.048583, 0},
{ 0.028750, 0.047917, 0.034451, 0},
{ -0.028750, -0.047917, 0.034451, 0},
{ 0.033750, 0.056250, 0.022949, 0},
{ -0.033750, -0.056250, 0.022949, 0} }
dcl_constantbuffer CB0[1], immediateIndexed
dcl_sampler s0, mode_default
dcl_resource_texture2d (float,float,float,float) t0
dcl_input_ps linear v1.xy
dcl_output o0.xyzw
dcl_temps 4
ieq r0.x, cb0[0].x, l(2)
if_nz r0.x
sample_indexable(texture2d)(float,float,float,float) r0.xyzw, v1.xyxx, t0.xyzw, s0
else
ieq r1.x, cb0[0].x, l(3)
if_nz r1.x
sample_indexable(texture2d)(float,float,float,float) r1.xyzw, v1.xyxx, t0.xyzw, s0
add r0.xyzw, -r1.xyzw, l(1.000000, 1.000000, 1.000000, 1.000000)
else
ieq r1.x, cb0[0].x, l(4)
if_nz r1.x
sample_indexable(texture2d)(float,float,float,float) r1.xyz, v1.xyxx, t0.xyzw, s0
dp3 r1.x, l(0.210000, 0.720000, 0.070000, 0.000000), r1.xyzx
mov r1.y, l(1.000000)
mov r0.xyzw, r1.xxxy
else
ieq r1.x, cb0[0].x, l(5)
if_nz r1.x
add r1.xyzw, v1.xyxy, l(-0.001000, 0.001000, 0.000000, 0.001000)
sample_indexable(texture2d)(float,float,float,float) r1.x, r1.xyxx, t0.xyzw, s0
sample_indexable(texture2d)(float,float,float,float) r1.y, r1.zwzz, t0.yxzw, s0
mad r1.y, r1.y, l(2.000000), r1.x
add r2.xyzw, v1.xyxy, l(0.001000, 0.001000, -0.001000, 0.000000)
sample_indexable(texture2d)(float,float,float,float) r1.z, r2.xyxx, t0.yzxw, s0
add r1.x, r1.z, -r1.x
add r1.y, r1.z, r1.y
sample_indexable(texture2d)(float,float,float,float) r1.w, r2.zwzz, t0.yzwx, s0
mad r1.x, r1.w, l(-2.000000), r1.x
mad r1.x, r1.z, l(2.000000), r1.x
add r2.xyzw, v1.xyxy, l(-0.001000, -0.001000, 0.000000, -0.001000)
sample_indexable(texture2d)(float,float,float,float) r1.z, r2.xyxx, t0.yzxw, s0
add r1.xy, -r1.zzzz, r1.xyxx
sample_indexable(texture2d)(float,float,float,float) r1.z, r2.zwzz, t0.yzxw, s0
mad r1.y, r1.z, l(-2.000000), r1.y
add r1.zw, v1.xxxy, l(0.000000, 0.000000, 0.001000, -0.001000)
sample_indexable(texture2d)(float,float,float,float) r1.z, r1.zwzz, t0.yzxw, s0
add r1.x, r1.z, r1.x
add r1.y, -r1.z, r1.y
mul r1.y, r1.y, r1.y
mad r1.x, r1.x, r1.x, r1.y
lt r1.x, r1.x, l(0.015000)
if_nz r1.x
sample_indexable(texture2d)(float,float,float,float) r0.xyzw, v1.xyxx, t0.xyzw, s0
else
mov r0.xyzw, l(1.000000,1.000000,1.000000,1.000000)
endif
else
ieq r1.x, cb0[0].x, l(6)
if_nz r1.x
mov r0.xyzw, l(0,0,0,0)
mov r1.x, l(0)
loop
ige r1.y, r1.x, l(15)
breakc_nz r1.y
add r1.yz, v1.xxyx, icb[r1.x + 0].xxyx
sample_indexable(texture2d)(float,float,float,float) r2.xyzw, r1.yzyy, t0.xyzw, s0
mad r0.xyzw, r2.xyzw, icb[r1.x + 0].zzzz, r0.xyzw
iadd r1.x, r1.x, l(1)
endloop
else
ieq r1.x, cb0[0].x, l(7)
if_nz r1.x
add r1.xy, v1.xyxx, l(-0.500000, -0.500000, 0.000000, 0.000000)
dp2 r1.z, r1.xyxx, r1.xyxx
sqrt r1.z, r1.z
mul r1.z, r1.z, l(6.000000)
exp r1.z, r1.z
sincos r1.z, null, r1.z
mad r1.xy, r1.xyxx, r1.zzzz, v1.xyxx
sample_indexable(texture2d)(float,float,float,float) r0.xyzw, r1.xyxx, t0.xyzw, s0
else
ieq r1.x, cb0[0].x, l(8)
if_nz r1.x
mul r1.xy, v1.xyxx, l(100.000000, 100.000000, 0.000000, 0.000000)
ftou r1.xy, r1.xyxx
utof r1.xy, r1.xyxx
mul r1.xy, r1.xyxx, l(0.010000, 0.010000, 0.000000, 0.000000)
sample_indexable(texture2d)(float,float,float,float) r0.xyzw, r1.xyxx, t0.xyzw, s0
else
ieq r1.x, cb0[0].x, l(9)
if_nz r1.x
add r1.xy, -v1.xyxx, l(0.500000, 0.500000, 0.000000, 0.000000)
dp2 r1.x, r1.xyxx, r1.xyxx
sqrt r1.x, r1.x
add r1.x, r1.x, l(1.000000)
log r1.yz, |v1.xxyx|
mul r1.xy, r1.yzyy, r1.xxxx
exp r1.xy, r1.xyxx
sample_indexable(texture2d)(float,float,float,float) r0.xyzw, r1.xyxx, t0.xyzw, s0
else
ieq r1.x, cb0[0].x, l(10)
if_nz r1.x
add r1.xy, -v1.xyxx, l(0.500000, 0.500000, 0.000000, 0.000000)
dp2 r1.x, r1.xyxx, r1.xyxx
sqrt r1.x, r1.x
mul r1.x, r1.x, l(50.000000)
add r1.yz, v1.xxyx, l(0.000000, -0.500000, -0.500000, 0.000000)
sincos r1.x, r2.x, r1.x
mad r1.y, r1.y, r2.x, l(0.500000)
mad r3.x, -r1.z, r1.x, r1.y
add r1.y, r3.x, l(-0.500000)
mad r1.x, r1.y, r1.x, l(0.500000)
mad r3.y, r1.z, r2.x, r1.x
sample_indexable(texture2d)(float,float,float,float) r0.xyzw, r3.xyxx, t0.xyzw, s0
else
mov r0.xyzw, l(0,0,0,1.000000)
endif
endif
endif
endif
endif
endif
endif
endif
endif
mul o0.xyzw, r0.xyzw, l(0.400000, 0.400000, 0.400000, 0.400000)
ret
// Approximately 117 instruction slots used
#endif
const BYTE g_UberPixelShader[] =
{
68, 88, 66, 67, 33, 43,
247, 184, 152, 181, 1, 48,
86, 228, 223, 101, 135, 51,
34, 201, 1, 0, 0, 0,
244, 15, 0, 0, 5, 0,
0, 0, 52, 0, 0, 0,
144, 1, 0, 0, 232, 1,
0, 0, 28, 2, 0, 0,
88, 15, 0, 0, 82, 68,
69, 70, 84, 1, 0, 0,
1, 0, 0, 0, 172, 0,
0, 0, 3, 0, 0, 0,
60, 0, 0, 0, 0, 5,
255, 255, 0, 1, 0, 0,
36, 1, 0, 0, 82, 68,
49, 49, 60, 0, 0, 0,
24, 0, 0, 0, 32, 0,
0, 0, 40, 0, 0, 0,
36, 0, 0, 0, 12, 0,
0, 0, 0, 0, 0, 0,
156, 0, 0, 0, 3, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 1, 0,
0, 0, 163, 0, 0, 0,
2, 0, 0, 0, 5, 0,
0, 0, 4, 0, 0, 0,
255, 255, 255, 255, 0, 0,
0, 0, 1, 0, 0, 0,
13, 0, 0, 0, 169, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0,
0, 0, 1, 0, 0, 0,
103, 95, 115, 97, 109, 112,
0, 103, 95, 116, 101, 120,
0, 99, 98, 0, 169, 0,
0, 0, 1, 0, 0, 0,
196, 0, 0, 0, 16, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 236, 0,
0, 0, 0, 0, 0, 0,
4, 0, 0, 0, 2, 0,
0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 255, 255,
255, 255, 0, 0, 0, 0,
255, 255, 255, 255, 0, 0,
0, 0, 115, 104, 97, 100,
101, 114, 84, 121, 112, 101,
0, 100, 119, 111, 114, 100,
0, 171, 171, 171, 0, 0,
19, 0, 1, 0, 1, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
247, 0, 0, 0, 77, 105,
99, 114, 111, 115, 111, 102,
116, 32, 40, 82, 41, 32,
72, 76, 83, 76, 32, 83,
104, 97, 100, 101, 114, 32,
67, 111, 109, 112, 105, 108,
101, 114, 32, 49, 48, 46,
48, 46, 49, 48, 48, 49,
49, 46, 48, 0, 73, 83,
71, 78, 80, 0, 0, 0,
2, 0, 0, 0, 8, 0,
0, 0, 56, 0, 0, 0,
0, 0, 0, 0, 1, 0,
0, 0, 3, 0, 0, 0,
0, 0, 0, 0, 15, 0,
0, 0, 68, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 3, 0, 0, 0,
1, 0, 0, 0, 3, 3,
0, 0, 83, 86, 95, 80,
79, 83, 73, 84, 73, 79,
78, 0, 84, 69, 88, 67,
79, 79, 82, 68, 0, 171,
171, 171, 79, 83, 71, 78,
44, 0, 0, 0, 1, 0,
0, 0, 8, 0, 0, 0,
32, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0,
0, 0, 15, 0, 0, 0,
83, 86, 95, 84, 65, 82,
71, 69, 84, 0, 171, 171,
83, 72, 69, 88, 52, 13,
0, 0, 80, 0, 0, 0,
77, 3, 0, 0, 106, 8,
0, 1, 53, 24, 0, 0,
62, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
8, 83, 217, 61, 0, 0,
0, 0, 143, 194, 117, 59,
207, 204, 204, 59, 82, 163,
210, 61, 0, 0, 0, 0,
143, 194, 117, 187, 207, 204,
204, 187, 82, 163, 210, 61,
0, 0, 0, 0, 41, 92,
15, 60, 235, 238, 110, 60,
190, 201, 191, 61, 0, 0,
0, 0, 41, 92, 15, 188,
235, 238, 110, 188, 190, 201,
191, 61, 0, 0, 0, 0,
174, 71, 97, 60, 190, 187,
187, 60, 133, 11, 164, 61,
0, 0, 0, 0, 174, 71,
97, 188, 190, 187, 187, 188,
133, 11, 164, 61, 0, 0,
0, 0, 154, 153, 153, 60,
0, 0, 0, 61, 90, 208,
131, 61, 0, 0, 0, 0,
154, 153, 153, 188, 0, 0,
0, 189, 90, 208, 131, 61,
0, 0, 0, 0, 92, 143,
194, 60, 36, 34, 34, 61,
38, 255, 70, 61, 0, 0,
0, 0, 92, 143, 194, 188,
36, 34, 34, 189, 38, 255,
70, 61, 0, 0, 0, 0,
31, 133, 235, 60, 69, 68,
68, 61, 26, 28, 13, 61,
0, 0, 0, 0, 31, 133,
235, 188, 69, 68, 68, 189,
26, 28, 13, 61, 0, 0,
0, 0, 113, 61, 10, 61,
102, 102, 102, 61, 173, 255,
187, 60, 0, 0, 0, 0,
113, 61, 10, 189, 102, 102,
102, 189, 173, 255, 187, 60,
0, 0, 0, 0, 89, 0,
0, 4, 70, 142, 32, 0,
0, 0, 0, 0, 1, 0,
0, 0, 90, 0, 0, 3,
0, 96, 16, 0, 0, 0,
0, 0, 88, 24, 0, 4,
0, 112, 16, 0, 0, 0,
0, 0, 85, 85, 0, 0,
98, 16, 0, 3, 50, 16,
16, 0, 1, 0, 0, 0,
101, 0, 0, 3, 242, 32,
16, 0, 0, 0, 0, 0,
104, 0, 0, 2, 4, 0,
0, 0, 32, 0, 0, 8,
18, 0, 16, 0, 0, 0,
0, 0, 10, 128, 32, 0,
0, 0, 0, 0, 0, 0,
0, 0, 1, 64, 0, 0,
2, 0, 0, 0, 31, 0,
4, 3, 10, 0, 16, 0,
0, 0, 0, 0, 69, 0,
0, 139, 194, 0, 0, 128,
67, 85, 21, 0, 242, 0,
16, 0, 0, 0, 0, 0,
70, 16, 16, 0, 1, 0,
0, 0, 70, 126, 16, 0,
0, 0, 0, 0, 0, 96,
16, 0, 0, 0, 0, 0,
18, 0, 0, 1, 32, 0,
0, 8, 18, 0, 16, 0,
1, 0, 0, 0, 10, 128,
32, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 64,
0, 0, 3, 0, 0, 0,
31, 0, 4, 3, 10, 0,
16, 0, 1, 0, 0, 0,
69, 0, 0, 139, 194, 0,
0, 128, 67, 85, 21, 0,
242, 0, 16, 0, 1, 0,
0, 0, 70, 16, 16, 0,
1, 0, 0, 0, 70, 126,
16, 0, 0, 0, 0, 0,
0, 96, 16, 0, 0, 0,
0, 0, 0, 0, 0, 11,
242, 0, 16, 0, 0, 0,
0, 0, 70, 14, 16, 128,
65, 0, 0, 0, 1, 0,
0, 0, 2, 64, 0, 0,
0, 0, 128, 63, 0, 0,
128, 63, 0, 0, 128, 63,
0, 0, 128, 63, 18, 0,
0, 1, 32, 0, 0, 8,
18, 0, 16, 0, 1, 0,
0, 0, 10, 128, 32, 0,
0, 0, 0, 0, 0, 0,
0, 0, 1, 64, 0, 0,
4, 0, 0, 0, 31, 0,
4, 3, 10, 0, 16, 0,
1, 0, 0, 0, 69, 0,
0, 139, 194, 0, 0, 128,
67, 85, 21, 0, 114, 0,
16, 0, 1, 0, 0, 0,
70, 16, 16, 0, 1, 0,
0, 0, 70, 126, 16, 0,
0, 0, 0, 0, 0, 96,
16, 0, 0, 0, 0, 0,
16, 0, 0, 10, 18, 0,
16, 0, 1, 0, 0, 0,
2, 64, 0, 0, 61, 10,
87, 62, 236, 81, 56, 63,
41, 92, 143, 61, 0, 0,
0, 0, 70, 2, 16, 0,
1, 0, 0, 0, 54, 0,
0, 5, 34, 0, 16, 0,
1, 0, 0, 0, 1, 64,
0, 0, 0, 0, 128, 63,
54, 0, 0, 5, 242, 0,
16, 0, 0, 0, 0, 0,
6, 4, 16, 0, 1, 0,
0, 0, 18, 0, 0, 1,
32, 0, 0, 8, 18, 0,
16, 0, 1, 0, 0, 0,
10, 128, 32, 0, 0, 0,
0, 0, 0, 0, 0, 0,
1, 64, 0, 0, 5, 0,
0, 0, 31, 0, 4, 3,
10, 0, 16, 0, 1, 0,
0, 0, 0, 0, 0, 10,
242, 0, 16, 0, 1, 0,
0, 0, 70, 20, 16, 0,
1, 0, 0, 0, 2, 64,
0, 0, 111, 18, 131, 186,
111, 18, 131, 58, 0, 0,
0, 0, 111, 18, 131, 58,
69, 0, 0, 139, 194, 0,
0, 128, 67, 85, 21, 0,
18, 0, 16, 0, 1, 0,
0, 0, 70, 0, 16, 0,
1, 0, 0, 0, 70, 126,
16, 0, 0, 0, 0, 0,
0, 96, 16, 0, 0, 0,
0, 0, 69, 0, 0, 139,
194, 0, 0, 128, 67, 85,
21, 0, 34, 0, 16, 0,
1, 0, 0, 0, 230, 10,
16, 0, 1, 0, 0, 0,
22, 126, 16, 0, 0, 0,
0, 0, 0, 96, 16, 0,
0, 0, 0, 0, 50, 0,
0, 9, 34, 0, 16, 0,
1, 0, 0, 0, 26, 0,
16, 0, 1, 0, 0, 0,
1, 64, 0, 0, 0, 0,
0, 64, 10, 0, 16, 0,
1, 0, 0, 0, 0, 0,
0, 10, 242, 0, 16, 0,
2, 0, 0, 0, 70, 20,
16, 0, 1, 0, 0, 0,
2, 64, 0, 0, 111, 18,
131, 58, 111, 18, 131, 58,
111, 18, 131, 186, 0, 0,
0, 0, 69, 0, 0, 139,
194, 0, 0, 128, 67, 85,
21, 0, 66, 0, 16, 0,
1, 0, 0, 0, 70, 0,
16, 0, 2, 0, 0, 0,
150, 124, 16, 0, 0, 0,
0, 0, 0, 96, 16, 0,
0, 0, 0, 0, 0, 0,
0, 8, 18, 0, 16, 0,
1, 0, 0, 0, 42, 0,
16, 0, 1, 0, 0, 0,
10, 0, 16, 128, 65, 0,
0, 0, 1, 0, 0, 0,
0, 0, 0, 7, 34, 0,
16, 0, 1, 0, 0, 0,
42, 0, 16, 0, 1, 0,
0, 0, 26, 0, 16, 0,
1, 0, 0, 0, 69, 0,
0, 139, 194, 0, 0, 128,
67, 85, 21, 0, 130, 0,
16, 0, 1, 0, 0, 0,
230, 10, 16, 0, 2, 0,
0, 0, 150, 115, 16, 0,
0, 0, 0, 0, 0, 96,
16, 0, 0, 0, 0, 0,
50, 0, 0, 9, 18, 0,
16, 0, 1, 0, 0, 0,
58, 0, 16, 0, 1, 0,
0, 0, 1, 64, 0, 0,
0, 0, 0, 192, 10, 0,
16, 0, 1, 0, 0, 0,
50, 0, 0, 9, 18, 0,
16, 0, 1, 0, 0, 0,
42, 0, 16, 0, 1, 0,
0, 0, 1, 64, 0, 0,
0, 0, 0, 64, 10, 0,
16, 0, 1, 0, 0, 0,
0, 0, 0, 10, 242, 0,
16, 0, 2, 0, 0, 0,
70, 20, 16, 0, 1, 0,
0, 0, 2, 64, 0, 0,
111, 18, 131, 186, 111, 18,
131, 186, 0, 0, 0, 0,
111, 18, 131, 186, 69, 0,
0, 139, 194, 0, 0, 128,
67, 85, 21, 0, 66, 0,
16, 0, 1, 0, 0, 0,
70, 0, 16, 0, 2, 0,
0, 0, 150, 124, 16, 0,
0, 0, 0, 0, 0, 96,
16, 0, 0, 0, 0, 0,
0, 0, 0, 8, 50, 0,
16, 0, 1, 0, 0, 0,
166, 10, 16, 128, 65, 0,
0, 0, 1, 0, 0, 0,
70, 0, 16, 0, 1, 0,
0, 0, 69, 0, 0, 139,
194, 0, 0, 128, 67, 85,
21, 0, 66, 0, 16, 0,
1, 0, 0, 0, 230, 10,
16, 0, 2, 0, 0, 0,
150, 124, 16, 0, 0, 0,
0, 0, 0, 96, 16, 0,
0, 0, 0, 0, 50, 0,
0, 9, 34, 0, 16, 0,
1, 0, 0, 0, 42, 0,
16, 0, 1, 0, 0, 0,
1, 64, 0, 0, 0, 0,
0, 192, 26, 0, 16, 0,
1, 0, 0, 0, 0, 0,
0, 10, 194, 0, 16, 0,
1, 0, 0, 0, 6, 20,
16, 0, 1, 0, 0, 0,
2, 64, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
111, 18, 131, 58, 111, 18,
131, 186, 69, 0, 0, 139,
194, 0, 0, 128, 67, 85,
21, 0, 66, 0, 16, 0,
1, 0, 0, 0, 230, 10,
16, 0, 1, 0, 0, 0,
150, 124, 16, 0, 0, 0,
0, 0, 0, 96, 16, 0,
0, 0, 0, 0, 0, 0,
0, 7, 18, 0, 16, 0,
1, 0, 0, 0, 42, 0,
16, 0, 1, 0, 0, 0,
10, 0, 16, 0, 1, 0,
0, 0, 0, 0, 0, 8,
34, 0, 16, 0, 1, 0,
0, 0, 42, 0, 16, 128,
65, 0, 0, 0, 1, 0,
0, 0, 26, 0, 16, 0,
1, 0, 0, 0, 56, 0,
0, 7, 34, 0, 16, 0,
1, 0, 0, 0, 26, 0,
16, 0, 1, 0, 0, 0,
26, 0, 16, 0, 1, 0,
0, 0, 50, 0, 0, 9,
18, 0, 16, 0, 1, 0,
0, 0, 10, 0, 16, 0,
1, 0, 0, 0, 10, 0,
16, 0, 1, 0, 0, 0,
26, 0, 16, 0, 1, 0,
0, 0, 49, 0, 0, 7,
18, 0, 16, 0, 1, 0,
0, 0, 10, 0, 16, 0,
1, 0, 0, 0, 1, 64,
0, 0, 143, 194, 117, 60,
31, 0, 4, 3, 10, 0,
16, 0, 1, 0, 0, 0,
69, 0, 0, 139, 194, 0,
0, 128, 67, 85, 21, 0,
242, 0, 16, 0, 0, 0,
0, 0, 70, 16, 16, 0,
1, 0, 0, 0, 70, 126,
16, 0, 0, 0, 0, 0,
0, 96, 16, 0, 0, 0,
0, 0, 18, 0, 0, 1,
54, 0, 0, 8, 242, 0,
16, 0, 0, 0, 0, 0,
2, 64, 0, 0, 0, 0,
128, 63, 0, 0, 128, 63,
0, 0, 128, 63, 0, 0,
128, 63, 21, 0, 0, 1,
18, 0, 0, 1, 32, 0,
0, 8, 18, 0, 16, 0,
1, 0, 0, 0, 10, 128,
32, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 64,
0, 0, 6, 0, 0, 0,
31, 0, 4, 3, 10, 0,
16, 0, 1, 0, 0, 0,
54, 0, 0, 8, 242, 0,
16, 0, 0, 0, 0, 0,
2, 64, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 54, 0, 0, 5,
18, 0, 16, 0, 1, 0,
0, 0, 1, 64, 0, 0,
0, 0, 0, 0, 48, 0,
0, 1, 33, 0, 0, 7,
34, 0, 16, 0, 1, 0,
0, 0, 10, 0, 16, 0,
1, 0, 0, 0, 1, 64,
0, 0, 15, 0, 0, 0,
3, 0, 4, 3, 26, 0,
16, 0, 1, 0, 0, 0,
0, 0, 0, 8, 98, 0,
16, 0, 1, 0, 0, 0,
6, 17, 16, 0, 1, 0,
0, 0, 6, 145, 144, 0,
10, 0, 16, 0, 1, 0,
0, 0, 69, 0, 0, 139,
194, 0, 0, 128, 67, 85,
21, 0, 242, 0, 16, 0,
2, 0, 0, 0, 150, 5,
16, 0, 1, 0, 0, 0,
70, 126, 16, 0, 0, 0,
0, 0, 0, 96, 16, 0,
0, 0, 0, 0, 50, 0,
0, 10, 242, 0, 16, 0,
0, 0, 0, 0, 70, 14,
16, 0, 2, 0, 0, 0,
166, 154, 144, 0, 10, 0,
16, 0, 1, 0, 0, 0,
70, 14, 16, 0, 0, 0,
0, 0, 30, 0, 0, 7,
18, 0, 16, 0, 1, 0,
0, 0, 10, 0, 16, 0,
1, 0, 0, 0, 1, 64,
0, 0, 1, 0, 0, 0,
22, 0, 0, 1, 18, 0,
0, 1, 32, 0, 0, 8,
18, 0, 16, 0, 1, 0,
0, 0, 10, 128, 32, 0,
0, 0, 0, 0, 0, 0,
0, 0, 1, 64, 0, 0,
7, 0, 0, 0, 31, 0,
4, 3, 10, 0, 16, 0,
1, 0, 0, 0, 0, 0,
0, 10, 50, 0, 16, 0,
1, 0, 0, 0, 70, 16,
16, 0, 1, 0, 0, 0,
2, 64, 0, 0, 0, 0,
0, 191, 0, 0, 0, 191,
0, 0, 0, 0, 0, 0,
0, 0, 15, 0, 0, 7,
66, 0, 16, 0, 1, 0,
0, 0, 70, 0, 16, 0,
1, 0, 0, 0, 70, 0,
16, 0, 1, 0, 0, 0,
75, 0, 0, 5, 66, 0,
16, 0, 1, 0, 0, 0,
42, 0, 16, 0, 1, 0,
0, 0, 56, 0, 0, 7,
66, 0, 16, 0, 1, 0,
0, 0, 42, 0, 16, 0,
1, 0, 0, 0, 1, 64,
0, 0, 0, 0, 192, 64,
25, 0, 0, 5, 66, 0,
16, 0, 1, 0, 0, 0,
42, 0, 16, 0, 1, 0,
0, 0, 77, 0, 0, 6,
66, 0, 16, 0, 1, 0,
0, 0, 0, 208, 0, 0,
42, 0, 16, 0, 1, 0,
0, 0, 50, 0, 0, 9,
50, 0, 16, 0, 1, 0,
0, 0, 70, 0, 16, 0,
1, 0, 0, 0, 166, 10,
16, 0, 1, 0, 0, 0,
70, 16, 16, 0, 1, 0,
0, 0, 69, 0, 0, 139,
194, 0, 0, 128, 67, 85,
21, 0, 242, 0, 16, 0,
0, 0, 0, 0, 70, 0,
16, 0, 1, 0, 0, 0,
70, 126, 16, 0, 0, 0,
0, 0, 0, 96, 16, 0,
0, 0, 0, 0, 18, 0,
0, 1, 32, 0, 0, 8,
18, 0, 16, 0, 1, 0,
0, 0, 10, 128, 32, 0,
0, 0, 0, 0, 0, 0,
0, 0, 1, 64, 0, 0,
8, 0, 0, 0, 31, 0,
4, 3, 10, 0, 16, 0,
1, 0, 0, 0, 56, 0,
0, 10, 50, 0, 16, 0,
1, 0, 0, 0, 70, 16,
16, 0, 1, 0, 0, 0,
2, 64, 0, 0, 0, 0,
200, 66, 0, 0, 200, 66,
0, 0, 0, 0, 0, 0,
0, 0, 28, 0, 0, 5,
50, 0, 16, 0, 1, 0,
0, 0, 70, 0, 16, 0,
1, 0, 0, 0, 86, 0,
0, 5, 50, 0, 16, 0,
1, 0, 0, 0, 70, 0,
16, 0, 1, 0, 0, 0,
56, 0, 0, 10, 50, 0,
16, 0, 1, 0, 0, 0,
70, 0, 16, 0, 1, 0,
0, 0, 2, 64, 0, 0,
10, 215, 35, 60, 10, 215,
35, 60, 0, 0, 0, 0,
0, 0, 0, 0, 69, 0,
0, 139, 194, 0, 0, 128,
67, 85, 21, 0, 242, 0,
16, 0, 0, 0, 0, 0,
70, 0, 16, 0, 1, 0,
0, 0, 70, 126, 16, 0,
0, 0, 0, 0, 0, 96,
16, 0, 0, 0, 0, 0,
18, 0, 0, 1, 32, 0,
0, 8, 18, 0, 16, 0,
1, 0, 0, 0, 10, 128,
32, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 64,
0, 0, 9, 0, 0, 0,
31, 0, 4, 3, 10, 0,
16, 0, 1, 0, 0, 0,
0, 0, 0, 11, 50, 0,
16, 0, 1, 0, 0, 0,
70, 16, 16, 128, 65, 0,
0, 0, 1, 0, 0, 0,
2, 64, 0, 0, 0, 0,
0, 63, 0, 0, 0, 63,
0, 0, 0, 0, 0, 0,
0, 0, 15, 0, 0, 7,
18, 0, 16, 0, 1, 0,
0, 0, 70, 0, 16, 0,
1, 0, 0, 0, 70, 0,
16, 0, 1, 0, 0, 0,
75, 0, 0, 5, 18, 0,
16, 0, 1, 0, 0, 0,
10, 0, 16, 0, 1, 0,
0, 0, 0, 0, 0, 7,
18, 0, 16, 0, 1, 0,
0, 0, 10, 0, 16, 0,
1, 0, 0, 0, 1, 64,
0, 0, 0, 0, 128, 63,
47, 0, 0, 6, 98, 0,
16, 0, 1, 0, 0, 0,
6, 17, 16, 128, 129, 0,
0, 0, 1, 0, 0, 0,
56, 0, 0, 7, 50, 0,
16, 0, 1, 0, 0, 0,
150, 5, 16, 0, 1, 0,
0, 0, 6, 0, 16, 0,
1, 0, 0, 0, 25, 0,
0, 5, 50, 0, 16, 0,
1, 0, 0, 0, 70, 0,
16, 0, 1, 0, 0, 0,
69, 0, 0, 139, 194, 0,
0, 128, 67, 85, 21, 0,
242, 0, 16, 0, 0, 0,
0, 0, 70, 0, 16, 0,
1, 0, 0, 0, 70, 126,
16, 0, 0, 0, 0, 0,
0, 96, 16, 0, 0, 0,
0, 0, 18, 0, 0, 1,
32, 0, 0, 8, 18, 0,
16, 0, 1, 0, 0, 0,
10, 128, 32, 0, 0, 0,
0, 0, 0, 0, 0, 0,
1, 64, 0, 0, 10, 0,
0, 0, 31, 0, 4, 3,
10, 0, 16, 0, 1, 0,
0, 0, 0, 0, 0, 11,
50, 0, 16, 0, 1, 0,
0, 0, 70, 16, 16, 128,
65, 0, 0, 0, 1, 0,
0, 0, 2, 64, 0, 0,
0, 0, 0, 63, 0, 0,
0, 63, 0, 0, 0, 0,
0, 0, 0, 0, 15, 0,
0, 7, 18, 0, 16, 0,
1, 0, 0, 0, 70, 0,
16, 0, 1, 0, 0, 0,
70, 0, 16, 0, 1, 0,
0, 0, 75, 0, 0, 5,
18, 0, 16, 0, 1, 0,
0, 0, 10, 0, 16, 0,
1, 0, 0, 0, 56, 0,
0, 7, 18, 0, 16, 0,
1, 0, 0, 0, 10, 0,
16, 0, 1, 0, 0, 0,
1, 64, 0, 0, 0, 0,
72, 66, 0, 0, 0, 10,
98, 0, 16, 0, 1, 0,
0, 0, 6, 17, 16, 0,
1, 0, 0, 0, 2, 64,
0, 0, 0, 0, 0, 0,
0, 0, 0, 191, 0, 0,
0, 191, 0, 0, 0, 0,
77, 0, 0, 7, 18, 0,
16, 0, 1, 0, 0, 0,
18, 0, 16, 0, 2, 0,
0, 0, 10, 0, 16, 0,
1, 0, 0, 0, 50, 0,
0, 9, 34, 0, 16, 0,
1, 0, 0, 0, 26, 0,
16, 0, 1, 0, 0, 0,
10, 0, 16, 0, 2, 0,
0, 0, 1, 64, 0, 0,
0, 0, 0, 63, 50, 0,
0, 10, 18, 0, 16, 0,
3, 0, 0, 0, 42, 0,
16, 128, 65, 0, 0, 0,
1, 0, 0, 0, 10, 0,
16, 0, 1, 0, 0, 0,
26, 0, 16, 0, 1, 0,
0, 0, 0, 0, 0, 7,
34, 0, 16, 0, 1, 0,
0, 0, 10, 0, 16, 0,
3, 0, 0, 0, 1, 64,
0, 0, 0, 0, 0, 191,
50, 0, 0, 9, 18, 0,
16, 0, 1, 0, 0, 0,
26, 0, 16, 0, 1, 0,
0, 0, 10, 0, 16, 0,
1, 0, 0, 0, 1, 64,
0, 0, 0, 0, 0, 63,
50, 0, 0, 9, 34, 0,
16, 0, 3, 0, 0, 0,
42, 0, 16, 0, 1, 0,
0, 0, 10, 0, 16, 0,
2, 0, 0, 0, 10, 0,
16, 0, 1, 0, 0, 0,
69, 0, 0, 139, 194, 0,
0, 128, 67, 85, 21, 0,
242, 0, 16, 0, 0, 0,
0, 0, 70, 0, 16, 0,
3, 0, 0, 0, 70, 126,
16, 0, 0, 0, 0, 0,
0, 96, 16, 0, 0, 0,
0, 0, 18, 0, 0, 1,
54, 0, 0, 8, 242, 0,
16, 0, 0, 0, 0, 0,
2, 64, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
128, 63, 21, 0, 0, 1,
21, 0, 0, 1, 21, 0,
0, 1, 21, 0, 0, 1,
21, 0, 0, 1, 21, 0,
0, 1, 21, 0, 0, 1,
21, 0, 0, 1, 21, 0,
0, 1, 56, 0, 0, 10,
242, 32, 16, 0, 0, 0,
0, 0, 70, 14, 16, 0,
0, 0, 0, 0, 2, 64,
0, 0, 205, 204, 204, 62,
205, 204, 204, 62, 205, 204,
204, 62, 205, 204, 204, 62,
62, 0, 0, 1, 83, 84,
65, 84, 148, 0, 0, 0,
117, 0, 0, 0, 4, 0,
0, 0, 15, 0, 0, 0,
2, 0, 0, 0, 47, 0,
0, 0, 11, 0, 0, 0,
0, 0, 0, 0, 11, 0,
0, 0, 11, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 16, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 6, 0,
0, 0, 0, 0, 0, 0,
2, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0,
0, 0, 0, 0
};
| 34,167
|
https://github.com/laionazeredo/econnessione/blob/master/services/admin-web/src/index.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
econnessione
|
laionazeredo
|
TSX
|
Code
| 81
| 323
|
import React from "react";
import ReactDOM from "react-dom";
import Helmet from "react-helmet";
import AdminPage from "./AdminPage";
import reportWebVitals from "./reportWebVitals";
import "ol/ol.css";
ReactDOM.render(
<React.StrictMode>
<Helmet
link={[
{
rel: "stylesheet",
type: "text/css",
href:
"https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick-theme.min.css",
},
{
rel: "stylesheet",
type: "text/css",
href:
"https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.min.css",
},
]}
/>
<AdminPage />
</React.StrictMode>,
document.getElementById("root")
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
| 3,851
|
https://github.com/don66/home-assistant/blob/master/homeassistant/components/sensor/version.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
home-assistant
|
don66
|
Python
|
Code
| 130
| 390
|
"""
Support for displaying the current version of Home Assistant.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.version/
"""
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import __version__, CONF_NAME
from homeassistant.helpers.entity import Entity
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "Current Version"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
async def async_setup_platform(
hass, config, async_add_devices, discovery_info=None):
"""Set up the Version sensor platform."""
name = config.get(CONF_NAME)
async_add_devices([VersionSensor(name)])
class VersionSensor(Entity):
"""Representation of a Home Assistant version sensor."""
def __init__(self, name):
"""Initialize the Version sensor."""
self._name = name
self._state = __version__
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def should_poll(self):
"""No polling needed."""
return False
@property
def state(self):
"""Return the state of the sensor."""
return self._state
| 12,370
|
https://github.com/SkewerSpot/ss-orders-app/blob/master/lib/models/unique_code_meta.dart
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
ss-orders-app
|
SkewerSpot
|
Dart
|
Code
| 140
| 352
|
import 'package:flutter/foundation.dart';
/// Metadata about a unique code.
class UniqueCodeMeta {
/// Firebase path for the code's associated order.
final String orderPath;
/// Whether the code has been redeemed.
final bool isRedeemed;
/// Timestamp of date and time when the code was redeemed.
/// Must be a valid ISO8601 string.
String redeemedTimestamp;
UniqueCodeMeta({
@required this.orderPath,
this.isRedeemed = false,
this.redeemedTimestamp,
});
/// Returns a deserialized instance of [UniqueCodeMeta] from a Map.
/// Useful for reading data from JSON or Firebase.
factory UniqueCodeMeta.fromMap(Map data) {
data = data ?? {};
return UniqueCodeMeta(
orderPath: data['orderPath'] ?? '',
isRedeemed: data['isRedeemed'] ?? false,
redeemedTimestamp: data['redeemedTimestamp'] ?? '',
);
}
/// Returns a [Map] representation of the object,
/// that can be used as a serialized form for sending to Firebase.
Map<String, dynamic> toMap() {
return {
'orderPath': this.orderPath,
'isRedeemed': this.isRedeemed,
'redeemedTimestamp': this.redeemedTimestamp,
};
}
}
| 39,435
|
https://github.com/cuihq/term/blob/master/examples/window_example.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
term
|
cuihq
|
Ruby
|
Code
| 20
| 73
|
# cording: utf-8
railties_path = File.expand_path('../../lib', __FILE__)
$:.unshift(railties_path)
require 'term/window'
IO.window_title = 'window title'
IO.icon_name = 'icon name'
sleep 3
| 23,838
|
https://github.com/rontech/Ribenyan/blob/master/client/dashBoard/second/template/contentLeft/adv_left_cell.js
|
Github Open Source
|
Open Source
|
MIT
| null |
Ribenyan
|
rontech
|
JavaScript
|
Code
| 57
| 252
|
// 广告集成cell
Template.advLeftCell.helpers({
"templateName" : function(){//显示模板
var advInfo = getAdvInfoById(this.advID);
var type = advInfo.showRule;
var templateName = "";
switch(type){
case "1" :
case "2" :
templateName = "advHouseLeftCell";//房屋广告显示模板
break;
case "3" :
templateName = "advCompanyJopLeftCell";//招聘信息显示模板
break;
default :
break;
}
return templateName;
},
"advInfo" : function(){
return getAdvInfoById(this.advID);
}
});
//获取广告信息
function getAdvInfoById(advID){
return AdInfo.findOne({"_id": advID});
}
| 16,206
|
https://github.com/johnnywang1994/axios-mock-shim/blob/master/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
axios-mock-shim
|
johnnywang1994
|
JavaScript
|
Code
| 3
| 19
|
module.exports = require('./dist/axios-mock-shim.min');
| 17,783
|
https://github.com/HaronK/aoc2019/blob/master/task23_2/src/network.rs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
aoc2019
|
HaronK
|
Rust
|
Code
| 263
| 837
|
use anyhow::{bail, ensure, Result};
use common::intcode_comp::*;
use common::log::*;
pub struct Network<'l> {
comps: Vec<IntcodeComp<'l>>,
is_running: bool,
nat: (DataType, DataType),
last_y: Option<DataType>,
}
impl<'l> Network<'l> {
pub fn new(prog: &str, count: usize, log: &'l Log) -> Result<Self> {
let mut comps = Vec::new();
for i in 0..count {
let mut comp = IntcodeComp::new(Vec::new(), log);
comp.load_prog(prog)?;
comp.add_input(i as DataType);
comp.add_input(-1);
comps.push(comp);
}
Ok(Self {
comps,
is_running: true,
nat: (-1, -1),
last_y: None,
})
}
fn run_iter(&mut self) -> Result<Option<DataType>> {
let mut nic = vec![Vec::new(); self.comps.len()];
let comps_count = self.comps.len();
self.is_running = false;
for comp in &mut self.comps {
if comp.is_halted() {
continue;
}
self.is_running = true;
comp.run()?;
let mut output = comp.get_output();
while !output.is_empty() {
let addr = output.remove(0) as usize;
let x = output.remove(0);
let y = output.remove(0);
if addr == 255 {
self.nat = (x, y);
} else {
ensure!(addr < comps_count, "Expected addr to be [0, {}] but was {}", self.comps.len() - 1, addr);
nic[addr].push(x);
nic[addr].push(y);
}
}
}
let mut i = 0;
let mut all_empty = true;
for mut input in &mut nic {
if !input.is_empty() {
self.comps[i].add_input_vec(&mut input);
all_empty = false;
} else {
self.comps[i].add_input(-1);
}
i += 1;
}
if all_empty {
if let Some(y) = self.last_y {
if y == self.nat.1 {
return Ok(Some(y));
}
} else {
self.comps[0].set_input(self.nat.0);
self.comps[0].add_input(self.nat.1);
}
self.last_y = Some(self.nat.1);
} else {
self.last_y = None;
}
Ok(None)
}
pub fn run(&mut self) -> Result<DataType> {
while self.is_running {
if let Some(y) = self.run_iter()? {
return Ok(y);
}
}
bail!("Didn't get idle twice in a row with the same y.");
}
}
| 31,882
|
https://github.com/idiocc/http/blob/master/example/src/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
http
|
idiocc
|
JavaScript
|
Code
| 71
| 196
|
const users = {
'secret-token': 'ExampleUser',
}
/**
* User Authentication Route.
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
*/
const middleware = (req, res) => {
const token = req.headers['x-auth']
if (!token) throw new Error('The authentication is required.')
const user = users[token]
if (!user) throw new Error('The user is not found.')
res.setHeader('set-cookie', `user=${user}`)
res.end(`Hello, ${user}`)
}
export default middleware
/**
* @typedef {import('http').IncomingMessage} http.IncomingMessage
* @typedef {import('http').ServerResponse} http.ServerResponse
*/
| 14,560
|
https://github.com/ts-upgrade-bot/gif-generator/blob/master/src/app/util/gif.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
gif-generator
|
ts-upgrade-bot
|
TypeScript
|
Code
| 280
| 863
|
import { TemplateContent } from '../models/template';
import { from } from 'rxjs';
declare var GIF: any;
export declare class GifReader {
width: number;
height: number;
numFrames: (() => number);
loopCount: (() => any);
frameInfo: ((frame_num: any) => any);
decodeAndBlitFrameBGRA: ((frame_num: any, pixels: any) => void);
decodeAndBlitFrameRGBA: ((frame_num: any, pixels: any) => void);
constructor(buf: Uint8Array)
}
const DEFAULT_FONT_SIZE = 20;
const DEFAULT_FONT_FAMILY = '"Microsoft YaHei", sans-serif';
const DEFAULT_FILL_STYLE = 'white';
const DEFAULT_STROKE_STYLE = 'black';
export const createCanvas = (width: number, height: number) => {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d') as CanvasRenderingContext2D;
context.font = `${DEFAULT_FONT_SIZE}px ${DEFAULT_FONT_FAMILY}`;
context.textAlign = 'center';
context.textBaseline = 'bottom';
context.fillStyle = DEFAULT_FILL_STYLE;
context.strokeStyle = DEFAULT_STROKE_STYLE;
context.lineWidth = 3;
context.lineJoin = 'round';
return context;
};
export const gifParser = (file: ArrayBuffer) =>
new GifReader(new Uint8Array(file));
export const gifEncoder = (gifReader: GifReader, context: CanvasRenderingContext2D, textInfo: TemplateContent[]) => {
const [width, height] = [gifReader.width, gifReader.height];
const gif = new GIF({
width: width,
height: height,
workerScript: './assets/js/gif.worker.js',
});
const pixelBuffer = new Uint8ClampedArray(width * height * 4);
for (let i = 0, textIndex = 0, time = 0; i < gifReader.numFrames(); i++) {
const frameInfo = gifReader.frameInfo(i);
gifReader.decodeAndBlitFrameRGBA(i, pixelBuffer);
const imageData = new ImageData(pixelBuffer, width, height);
context.putImageData(imageData, 0, 0);
if (textIndex < textInfo.length) {
const info = textInfo[textIndex];
if (info.startTime <= time && time < info.endTime) {
context.strokeText(info.text, width / 2, height - 8, width);
context.fillText(info.text, width / 2, height - 8, width);
}
time += frameInfo.delay / 100;
if (time >= info.endTime) {
textIndex++;
}
}
gif.addFrame(context, {
copy: true,
delay: frameInfo.delay * 10,
dispose: frameInfo.disposal,
});
}
return from(new Promise<string>(resolve => {
gif.on('finished', (blob: Blob) => {
resolve(window.URL.createObjectURL(blob));
});
gif.render();
}));
};
| 6,300
|
https://github.com/Fish-Roaly-D/JavaBase/blob/master/mybatisplus/mp-01/src/main/java/com/roily/codemake/codeMakeTest/controller/DepartmentController.java
|
Github Open Source
|
Open Source
|
MulanPSL-1.0
| 2,022
|
JavaBase
|
Fish-Roaly-D
|
Java
|
Code
| 28
| 115
|
package com.roily.codemake.codeMakeTest.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
/**
* <p>
* 前端控制器
* </p>
*
* @author roilyFish
* @since 2022-04-04
*/
@Controller
@RequestMapping("/codeMakeTest/department")
public class DepartmentController {
}
| 273
|
https://github.com/geekpius/NewOshelter/blob/master/app/Http/Controllers/UserProfileController.php
|
Github Open Source
|
Open Source
|
MIT
| null |
NewOshelter
|
geekpius
|
PHP
|
Code
| 507
| 2,140
|
<?php
namespace App\Http\Controllers;
use DB;
use Image;
use App\User;
use Illuminate\Http\Request;
use App\UserModel\UserProfile;
use App\UserModel\UserCurrency;
use App\Currency;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class UserProfileController extends Controller
{
public function __construct()
{
$this->middleware('verify-user');
$this->middleware('auth');
}
//view account
public function index()
{
$data['page_title'] = 'My account';
return view('user.account.index', $data);
}
public function accountInfo()
{
$data['page_title'] = current(explode(' ',Auth::user()->name)).' account info';
return view('user.account.account_info', $data);
}
public function updateAccountInfo(Request $request): string
{
$validator = \Validator::make($request->all(), [
'legal_name' => 'required|string',
'gender' => 'required|string',
'dob' => 'required|date',
'marital_status' => 'required|string',
'city' => 'required|string',
'profession' => 'required|string',
'emergency_contact' => 'required|string',
]);
if ($validator->fails()){
return 'fail';
}else{
$pro = User::FindorFail(Auth::user()->id);
$pro->name= $request->legal_name;
$pro->update();
UserProfile::updateOrCreate(
['user_id'=>Auth::user()->id],
[
'gender'=>$request->gender, 'dob'=>$request->dob, 'marital_status'=>$request->marital_status,
'city'=>$request->city, 'occupation'=>$request->profession, 'emergency'=>$request->emergency_contact
]
);
return "success";
}
}
public function uploadProfilePhoto(Request $request): string
{
$validator = \Validator::make($request->all(), [
'photo' => 'required|image|mimes:jpg,png,jpeg|max:1024',
]);
if ($validator->fails()){
$message = 'fail';
}else{
//upload image
if($request->hasFile('photo')){
try{
DB::beginTransaction();
$user = User::findorFail(Auth::user()->id);
$photo = $request->file('photo');
$name = sha1(date('YmdHis') . str_random(30));
$new_name = Auth::user()->id . $name . '.' . $photo->getClientOriginalExtension();
$location = 'assets/images/users/' . $new_name;
Image::make($photo)->resize(150, 150)->save($location);
//delete old photo
if(!empty($user->image)){
\File::delete("assets/images/users/".$user->image);
}
$user->image = $new_name;
$user->update();
DB::commit();
$message = $user->image;
}catch(\Exception $e){
DB::rollback();
$message = 'error';
}
}
else{
$message = 'nophoto';
}
}
return $message;
}
public function changePasswordView()
{
$data['page_title'] = 'Change password';
return view('user.account.change_password', $data);
}
public function updatePassword(Request $request)
{
$validator = \Validator::make($request->all(), [
'current_password' => 'required|string|min:6',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required|same:password',
]);
if ($validator->fails()){
return 'Wrong inputs(password mismatch). Try again.';
}
else{
if(auth()->check()){
if(Hash::check($request->current_password, Auth::user()->password))
{
$user = User::findorFail(Auth::user()->id);
$user->password = Hash::make($request->password);
$user->update();
return 'success';
}
else
{
return 'Incorrect current password.';
}
}
}
}
public function loginsView()
{
$data['page_title'] = 'Logins and security';
return view('user.account.login_details', $data);
}
public function paymentView()
{
$data['page_title'] = 'Payments';
$data['currencies'] = Currency::all();
return view('user.account.payments', $data);
}
public function changeCurrency(Request $request): string
{
$validator = \Validator::make($request->all(), [
'currency' => 'required|string',
]);
(string) $message = "";
if ($validator->fails()){
$message = 'fail';
}else{
$currency = UserCurrency::updateOrCreate(
['user_id'=>Auth::user()->id],
['currency'=>$request->currency]
);
$message = $currency->getCurrencyName();
}
return $message;
}
public function requestView()
{
$data['page_title'] = 'Requests and actions';
return view('user.account.request', $data);
}
public function notificationView()
{
$data['page_title'] = 'Notifications';
return view('user.account.notifications', $data);
}
public function uploadFrontCard(Request $request): string
{
$validator = \Validator::make($request->all(), [
'front_file' => 'required|image|mimes:jpg,png,jpeg|max:1024',
]);
(string) $message = "";
if ($validator->fails()){
$message = 'fail';
}else{
//upload image
if($request->hasFile('front_file')){
try{
DB::beginTransaction();
$user = UserProfile::whereUser_id(Auth::user()->id)->first();
$photo = $request->file('front_file');
$name = sha1(date('YmdHis') . str_random(30));
$new_name = Auth::user()->id . $name . '.' . $photo->getClientOriginalExtension();
$location = 'assets/images/cards/' . $new_name;
Image::make($photo)->resize(300, 200)->save($location);
//delete old photo
if(!empty($user)){
if(!empty($user->id_front)){
\File::delete("assets/images/cards/".$user->id_front);
}
}
$profile = UserProfile::updateOrCreate(
['user_id'=>Auth::user()->id],
['id_front'=>$new_name]
);
DB::commit();
$message = $profile->id_front;
}catch(\Exception $e){
DB::rollback();
$message = 'error';
}
}
else{
$message = 'nophoto';
}
}
return $message;
}
public function updateCardInfo(Request $request): string
{
$validator = \Validator::make($request->all(), [
'id_type' => 'required',
'id_number' => 'required',
]);
(string) $message = "";
if ($validator->fails()){
$message = 'Input required failed.';
}else{
try{
DB::beginTransaction();
$profile = UserProfile::whereUser_id(Auth::user()->id)->first();
$profile->id_number = $request->id_number;
$profile->id_type = $request->id_type;
$profile->update();
DB::commit();
$message = "success";
}catch(\Exception $e){
DB::rollback();
$message = 'Could not update card info.';
}
}
return $message;
}
}
| 24,008
|
https://github.com/Rume7/Data-Structures-and-Algorithms-in-Java/blob/master/src/main/java/com/packt/datastructuresandalg/lesson2/stack/StringReverse.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Data-Structures-and-Algorithms-in-Java
|
Rume7
|
Java
|
Code
| 57
| 189
|
package com.packt.datastructuresandalg.lesson2.stack;
import java.util.Optional;
public class StringReverse {
public String reverse(String str) {
StringBuilder result = new StringBuilder();
StackArray<Character> stack = new StackArray<>(100);
for (char c : str.toCharArray())
stack.push(c);
Optional<Character> optChar = stack.pop();
while (optChar.isPresent()) {
result.append(optChar.get());
optChar = stack.pop();
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(new StringReverse().reverse("This will be reversed"));
}
}
| 49,162
|
https://github.com/MDsolucoesTI/TesteIdoso/blob/master/BACI.Desk/BaseCadasView.Designer.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
TesteIdoso
|
MDsolucoesTI
|
C#
|
Code
| 770
| 3,764
|
//////////////////////////////////////////////////////////////////////////
// Criacao...........: 02/2018
// Sistema...........: Bateria de Avaliação Computadorizada para Idosos
// Analistas.........: Marilene Esquiavoni & Denny Paulista Azevedo Filho
// Desenvolvedores...: Marilene Esquiavoni & Denny Paulista Azevedo Filho
// Copyright.........: Marilene Esquiavoni & Denny Paulista Azevedo Filho
//////////////////////////////////////////////////////////////////////////
#region Copyright Syncfusion Inc. 2001-2017.
// Copyright Syncfusion Inc. 2001-2017. All rights reserved.
// Use of this code is subject to the terms of our license.
// A copy of the current license can be obtained at any time by e-mailing
// licensing@syncfusion.com. Any infringement will be prosecuted under
// applicable laws.
#endregion
namespace BACI.Desk
{
partial class BaseCadasView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnPrimeiro = new Syncfusion.Windows.Forms.ButtonAdv();
this.btnAnterior = new Syncfusion.Windows.Forms.ButtonAdv();
this.btnProximo = new Syncfusion.Windows.Forms.ButtonAdv();
this.btnUltimo = new Syncfusion.Windows.Forms.ButtonAdv();
this.btnNovo = new Syncfusion.Windows.Forms.ButtonAdv();
this.btnEditar = new Syncfusion.Windows.Forms.ButtonAdv();
this.btnOk = new Syncfusion.Windows.Forms.ButtonAdv();
this.btnCancela = new Syncfusion.Windows.Forms.ButtonAdv();
this.btnDeletar = new Syncfusion.Windows.Forms.ButtonAdv();
this.pnBotoes = new System.Windows.Forms.Panel();
this.pnCampos = new System.Windows.Forms.Panel();
this.btnSair = new Syncfusion.Windows.Forms.ButtonAdv();
((System.ComponentModel.ISupportInitialize)(this.statusBar)).BeginInit();
this.statusBar.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.statusBarUser)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarDate)).BeginInit();
this.pnBotoes.SuspendLayout();
this.SuspendLayout();
//
// btnPrimeiro
//
this.btnPrimeiro.BackgroundImage = global::BACI.Desk.Properties.Resources.Primeiro64;
this.btnPrimeiro.BeforeTouchSize = new System.Drawing.Size(64, 64);
this.btnPrimeiro.FlatAppearance.BorderSize = 0;
this.btnPrimeiro.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnPrimeiro.IsBackStageButton = false;
this.btnPrimeiro.Location = new System.Drawing.Point(85, 4);
this.btnPrimeiro.Name = "btnPrimeiro";
this.btnPrimeiro.Size = new System.Drawing.Size(64, 64);
this.btnPrimeiro.TabIndex = 1;
//
// btnAnterior
//
this.btnAnterior.BackgroundImage = global::BACI.Desk.Properties.Resources.Anterior64;
this.btnAnterior.BeforeTouchSize = new System.Drawing.Size(64, 64);
this.btnAnterior.FlatAppearance.BorderSize = 0;
this.btnAnterior.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnAnterior.IsBackStageButton = false;
this.btnAnterior.Location = new System.Drawing.Point(155, 4);
this.btnAnterior.Name = "btnAnterior";
this.btnAnterior.Size = new System.Drawing.Size(64, 64);
this.btnAnterior.TabIndex = 2;
//
// btnProximo
//
this.btnProximo.BackgroundImage = global::BACI.Desk.Properties.Resources.Proximo64;
this.btnProximo.BeforeTouchSize = new System.Drawing.Size(64, 64);
this.btnProximo.FlatAppearance.BorderSize = 0;
this.btnProximo.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnProximo.IsBackStageButton = false;
this.btnProximo.Location = new System.Drawing.Point(225, 4);
this.btnProximo.Name = "btnProximo";
this.btnProximo.Size = new System.Drawing.Size(64, 64);
this.btnProximo.TabIndex = 3;
//
// btnUltimo
//
this.btnUltimo.BackgroundImage = global::BACI.Desk.Properties.Resources.Ultimo64;
this.btnUltimo.BeforeTouchSize = new System.Drawing.Size(64, 64);
this.btnUltimo.FlatAppearance.BorderSize = 0;
this.btnUltimo.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnUltimo.IsBackStageButton = false;
this.btnUltimo.Location = new System.Drawing.Point(295, 4);
this.btnUltimo.Name = "btnUltimo";
this.btnUltimo.Size = new System.Drawing.Size(64, 64);
this.btnUltimo.TabIndex = 4;
//
// btnNovo
//
this.btnNovo.BackgroundImage = global::BACI.Desk.Properties.Resources.add164;
this.btnNovo.BeforeTouchSize = new System.Drawing.Size(64, 64);
this.btnNovo.FlatAppearance.BorderSize = 0;
this.btnNovo.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnNovo.IsBackStageButton = false;
this.btnNovo.Location = new System.Drawing.Point(394, 4);
this.btnNovo.Name = "btnNovo";
this.btnNovo.Size = new System.Drawing.Size(64, 64);
this.btnNovo.TabIndex = 5;
//
// btnEditar
//
this.btnEditar.BackgroundImage = global::BACI.Desk.Properties.Resources.edit64;
this.btnEditar.BeforeTouchSize = new System.Drawing.Size(64, 64);
this.btnEditar.FlatAppearance.BorderSize = 0;
this.btnEditar.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnEditar.IsBackStageButton = false;
this.btnEditar.Location = new System.Drawing.Point(464, 4);
this.btnEditar.Name = "btnEditar";
this.btnEditar.Size = new System.Drawing.Size(64, 64);
this.btnEditar.TabIndex = 6;
//
// btnOk
//
this.btnOk.BackgroundImage = global::BACI.Desk.Properties.Resources.Accept64;
this.btnOk.BeforeTouchSize = new System.Drawing.Size(64, 64);
this.btnOk.Enabled = false;
this.btnOk.FlatAppearance.BorderSize = 0;
this.btnOk.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnOk.IsBackStageButton = false;
this.btnOk.Location = new System.Drawing.Point(556, 4);
this.btnOk.Name = "btnOk";
this.btnOk.Size = new System.Drawing.Size(64, 64);
this.btnOk.TabIndex = 7;
//
// btnCancela
//
this.btnCancela.BackgroundImage = global::BACI.Desk.Properties.Resources.cancel64;
this.btnCancela.BeforeTouchSize = new System.Drawing.Size(64, 64);
this.btnCancela.Enabled = false;
this.btnCancela.FlatAppearance.BorderSize = 0;
this.btnCancela.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnCancela.IsBackStageButton = false;
this.btnCancela.Location = new System.Drawing.Point(626, 4);
this.btnCancela.Name = "btnCancela";
this.btnCancela.Size = new System.Drawing.Size(64, 64);
this.btnCancela.TabIndex = 8;
//
// btnDeletar
//
this.btnDeletar.BackgroundImage = global::BACI.Desk.Properties.Resources.Trash_can64;
this.btnDeletar.BeforeTouchSize = new System.Drawing.Size(64, 64);
this.btnDeletar.FlatAppearance.BorderSize = 0;
this.btnDeletar.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnDeletar.IsBackStageButton = false;
this.btnDeletar.Location = new System.Drawing.Point(730, 4);
this.btnDeletar.Name = "btnDeletar";
this.btnDeletar.Size = new System.Drawing.Size(64, 64);
this.btnDeletar.TabIndex = 9;
//
// pnBotoes
//
this.pnBotoes.BackColor = System.Drawing.Color.Honeydew;
this.pnBotoes.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pnBotoes.Controls.Add(this.btnSair);
this.pnBotoes.Controls.Add(this.btnPrimeiro);
this.pnBotoes.Controls.Add(this.btnDeletar);
this.pnBotoes.Controls.Add(this.btnAnterior);
this.pnBotoes.Controls.Add(this.btnCancela);
this.pnBotoes.Controls.Add(this.btnProximo);
this.pnBotoes.Controls.Add(this.btnOk);
this.pnBotoes.Controls.Add(this.btnUltimo);
this.pnBotoes.Controls.Add(this.btnEditar);
this.pnBotoes.Controls.Add(this.btnNovo);
this.pnBotoes.Dock = System.Windows.Forms.DockStyle.Bottom;
this.pnBotoes.Location = new System.Drawing.Point(0, 589);
this.pnBotoes.Name = "pnBotoes";
this.pnBotoes.Size = new System.Drawing.Size(988, 74);
this.pnBotoes.TabIndex = 10;
//
// pnCampos
//
this.pnCampos.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pnCampos.Dock = System.Windows.Forms.DockStyle.Fill;
this.pnCampos.Location = new System.Drawing.Point(0, 0);
this.pnCampos.Name = "pnCampos";
this.pnCampos.Size = new System.Drawing.Size(988, 589);
this.pnCampos.TabIndex = 11;
//
// btnSair
//
this.btnSair.BackgroundImage = global::BACI.Desk.Properties.Resources.Logout;
this.btnSair.BeforeTouchSize = new System.Drawing.Size(64, 64);
this.btnSair.FlatAppearance.BorderSize = 0;
this.btnSair.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnSair.IsBackStageButton = false;
this.btnSair.Location = new System.Drawing.Point(916, 5);
this.btnSair.Name = "btnSair";
this.btnSair.Size = new System.Drawing.Size(64, 64);
this.btnSair.TabIndex = 10;
this.btnSair.Click += new System.EventHandler(this.btnSair_Click);
//
// BaseCadasView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(988, 693);
this.Controls.Add(this.pnCampos);
this.Controls.Add(this.pnBotoes);
this.Name = "BaseCadasView";
this.Text = "Cadastro e Manuten��o - Dados";
this.Controls.SetChildIndex(this.statusBar, 0);
this.Controls.SetChildIndex(this.pnBotoes, 0);
this.Controls.SetChildIndex(this.pnCampos, 0);
((System.ComponentModel.ISupportInitialize)(this.statusBar)).EndInit();
this.statusBar.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.statusBarUser)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.statusBarDate)).EndInit();
this.pnBotoes.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public System.Windows.Forms.Panel pnCampos;
public Syncfusion.Windows.Forms.ButtonAdv btnPrimeiro;
public Syncfusion.Windows.Forms.ButtonAdv btnAnterior;
public Syncfusion.Windows.Forms.ButtonAdv btnProximo;
public Syncfusion.Windows.Forms.ButtonAdv btnUltimo;
public Syncfusion.Windows.Forms.ButtonAdv btnNovo;
public Syncfusion.Windows.Forms.ButtonAdv btnEditar;
public Syncfusion.Windows.Forms.ButtonAdv btnOk;
public Syncfusion.Windows.Forms.ButtonAdv btnCancela;
public Syncfusion.Windows.Forms.ButtonAdv btnDeletar;
public System.Windows.Forms.Panel pnBotoes;
public Syncfusion.Windows.Forms.ButtonAdv btnSair;
}
}
| 36,444
|
https://github.com/ThomasDre/TicTacToe-0.1-RL/blob/master/src/Server.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
TicTacToe-0.1-RL
|
ThomasDre
|
Python
|
Code
| 342
| 1,055
|
"""
A simple server that connects the reinforcement learning agent with a hosted (e.g. templates) representation of the
game.
A user can play the game in the browser and can
-) provide samples for learning (TRAIN MODE)
-) play a competitive game on the best level the agent is capable of (EVAL MODE)
-) control and observe offline training behaviour of agent (META-TEACHING MODE)
This server provides simple communication, to get user interactions, commands and to replay the own actions to the
interactive game during a game-session
"""
from flask import Flask, request, render_template, make_response
from custom_env.tictactoe.envs.tictactoe_env import TicTacToeEnv
from src.agents.base.SillyAgent import SillyAgent
from custom_env.tictactoe import strategy
app = Flask(__name__)
game_environment = TicTacToeEnv()
agent = SillyAgent()
first_move = True
response_text_template = '{{\"x\": {}, \"y\": {}, \"end\": \"{}\", \"won\": \"{}\"}}'
@app.route('/')
def output():
# serve index template
return render_template('index.html')
@app.route('/reset', methods=['GET'])
def reset():
game_environment.reset()
global first_move
first_move = True
return make_response('OK', 200)
@app.route('/move/user', methods=['POST'])
def get_user_move():
game_environment.set_opponent(strategy.human)
global first_move
first_move = False
data = request.get_json(force=True)
obs, reward, done, info = game_environment.take_a_move(tuple((data['x'], data['y'])))
if done:
response_text = response_text_template.format(-1, -1, True, True if reward == 1 else 'Undefined')
# debug(is_human=True, obs=obs, reward=reward, done=done, response=response_text)
else:
action, obs, reward, done, info = agent.action()
if done:
response_text = response_text_template.format(action[0], action[1], True, False if reward == 1 else 'Undefined')
else:
response_text = response_text_template.format(action[0], action[1], False, 'Undefined')
# debug(is_human=False, obs=obs, reward=reward, done=done,response=response_text)
if done:
game_environment.reset()
return make_response(response_text, 200)
@app.route('/move/agent', methods=['GET'])
def force_agent_move():
game_environment.set_opponent(strategy.human)
global first_move
if first_move:
first_move = False
action, obs, reward, done, info = agent.action()
# debug(False, obs=obs, reward=reward, done=done)
response_text = response_text_template.format(action[0], action[1], False, 'Undefined')
return make_response(response_text, 200)
return make_response('Failure', 400)
@app.route('/train', methods=['POST'])
def train_agent():
num_of_episodes = request.form['episodes']
print(num_of_episodes)
return make_response(200)
if __name__ == '__main__':
app.run()
def debug(is_human, obs=None, reward=None, done=None, info=None, response=None, additional=None):
if is_human:
print("AI move:")
else:
print("User move")
if obs is not None:
print("Obs: {}", obs)
if reward is not None and done is not None:
print("reward: {} ---- done: {}".format(reward, done))
if info is not None:
print("Info: " + info)
if response is not None:
print(response)
if additional is not None:
print(additional)
| 23,467
|
https://github.com/AutomotiveDevOps/mdf4-converters/blob/master/Library/Source/Blocks/DTBlock.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
mdf4-converters
|
AutomotiveDevOps
|
C++
|
Code
| 48
| 142
|
#include "DTBlock.h"
namespace mdf {
constexpr MdfHeader DTBlockHeader = {
.blockType = MdfBlockType_DT,
.blockSize = 24,
.linkCount = 0
};
DTBlock::DTBlock() {
header = DTBlockHeader;
dataPtr = nullptr;
}
bool DTBlock::load(uint8_t const* dataPtr_) {
bool result = false;
this->dataPtr = dataPtr_;
result = true;
return result;
}
}
| 23,239
|
https://github.com/bartnie/wormhole/blob/master/internal/tlsutil/tlsutil.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
wormhole
|
bartnie
|
Go
|
Code
| 159
| 425
|
// Copyright © 2018 The wormhole-connector authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
package tlsutil
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"github.com/cloudflare/cfssl/log"
)
func GenerateTLSConfig(trustCAFile string, insecure bool) (*tls.Config, error) {
tlsConfig := &tls.Config{
InsecureSkipVerify: insecure,
}
if insecure || trustCAFile == "" {
return tlsConfig, nil
}
rootCAs, _ := x509.SystemCertPool()
if rootCAs == nil {
rootCAs = x509.NewCertPool()
}
certs, err := ioutil.ReadFile(trustCAFile)
if err != nil {
return nil, fmt.Errorf("failed to append %q to RootCAs: %v", trustCAFile, err)
}
if ok := rootCAs.AppendCertsFromPEM(certs); !ok {
log.Infof("no certs appended, using system certs only")
}
tlsConfig.RootCAs = rootCAs
return tlsConfig, nil
}
| 42,753
|
https://github.com/v0idv0id/PerspectiveTexture/blob/master/shaders/point_fs.glsl
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
PerspectiveTexture
|
v0idv0id
|
GLSL
|
Code
| 35
| 104
|
#version 330 core
void main() {
// Very simple GL_POINTS (which are squares) to circle shader.
float diameter=0.8; //1.0 is max
if (length(gl_PointCoord - vec2(0.5)) > diameter/2)
discard;
gl_FragColor = vec4(1.0, 0.0, 1.0, 0.1);
}
| 30,545
|
https://github.com/guilleminio/paseoscaninos/blob/master/codigo/turnos.php
|
Github Open Source
|
Open Source
|
MIT
| null |
paseoscaninos
|
guilleminio
|
PHP
|
Code
| 260
| 1,480
|
<?php
session_start();
if ( !isset($_SESSION['cliente_actual'])){
header('Location:login.php');
exit();
}
include('backend/funcionesBD.php');
include('backend/config.php');
$conexion = conectarBD();
$turnos = null;
$totalTurnos = 0;
if ( $conexion['resultado']!=null){
$turnos = obtenerTurnos($conexion['resultado'],$_SESSION['perro_actual']['id_perro']);
$totalTurnos = count($turnos['resultado']);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo TITULO_SITIO?> - Turnos</title>
<?php include('librerias/librerias.php'); ?>
<!----------------- CSS BOOTSTAP --------------------------->
<link rel="stylesheet" type="text/css" href="css/sidebars.css">
<!--------------------------------------------------------->
<!----------------- CSS PROPIOS --------------------------->
<link rel="stylesheet" type="text/css" href="css/menu_lateral.css">
<!--------------------------------------------------------->
</head>
<body>
<main class="scrollarea">
<?php include('menu.php'); ?>
<section>
<div class="container">
<h1>Turnos para pasear</h1>
<?php
if ( $totalTurnos >0 ){
echo "<h3>Estos son los próximos paseos de ".$_SESSION['perro_actual']['nombre_perro']."</h3>";
echo "<table class=\"table table-striped table-hover \">
<thead>
<tr>
<th>Fecha</th>
<th>Hora</th>
<th>Paseador</th>
<th>Cancelar</th>
</tr>
</thead>
<tbody>";
for ( $i = 0; $i < $totalTurnos; $i++ ){
$paseador = obtenerPaseador($conexion['resultado'],$turnos['resultado'][$i]['id_paseador']);
echo "<tr>
<th scope=\"row\">".$turnos['resultado'][$i]['fecha_paseo']."</th>
<td>".$turnos['resultado'][$i]['hora_paseo']."</td>
<td>".$paseador['resultado']['nombre_paseador']."</td>
<td><button class=\"btn btn-outline-danger\" id=\"".$turnos['resultado'][$i]['id_paseo']."\"data-bs-toggle=\"modal\" data-bs-target=\"#exampleModal\">Cancelar</button></td>
</tr>";
}
echo "</tbody>
</table>";
}else
echo "<h3>".$_SESSION['perro_actual']['nombre_perro']." aún no tiene paseos resevados. ¿Reservamos uno? <a href=\"reservar_turno.php\">Click aquí</a></h3>";
?>
</div>
</section>
</main>
<!------------ Mensaje de confirmación ------------------------>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Atención</h5>
</div>
<div class="modal-body">
¿En verdad quierés cancelar el paseo?
</div>
<div class="modal-footer">
<button type="button" id="btnNo" class="btn btn-secondary">No</button>
<button type="button" id="btnSi" class="btn btn-primary botonActivo">Si</button>
</div>
</div>
</div>
</div>
<!----------- Fin mensaje de confirmación ---------------------->
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
var turno;
var modalAlerta = document.getElementById('exampleModal')
modalAlerta.addEventListener('shown.bs.modal', function (evento) {
var botonQueAbrioModal = evento.relatedTarget;
turno = botonQueAbrioModal.getAttribute('id');
modalAlerta.querySelector('.modal-body div').value = turno;
})
$('#btnSi').click(function() {
$.post('backend/procesar_cancelacion.php',{turno:turno},function(resultado){
console.log(resultado);
if ( resultado.error != null){
alert(resultado.error);
}else{
$('#exampleModal').modal('hide');
location.reload();
}
},'json')
})
$('#btnCerrarSesion').click(function () {
$.post('backend/cerrarsesion.php',function(){
location.href='index.php';
});
})
})
</script>
| 50,249
|
https://github.com/pablogalve/Edu-Game-Engine/blob/master/Source/Imgui/imgui_color_gradient.h
|
Github Open Source
|
Open Source
|
Unlicense
| null |
Edu-Game-Engine
|
pablogalve
|
C
|
Code
| 230
| 887
|
//
// imgui_color_gradient.h
// imgui extension
//
// Created by David Gallardo on 11/06/16.
/*
Usage:
::GRADIENT DATA::
ImGradient gradient;
::BUTTON::
if(ImGui::GradientButton(&gradient))
{
//set show editor flag to true/false
}
::EDITOR::
static ImGradientMark* draggingMark = nullptr;
static ImGradientMark* selectedMark = nullptr;
bool updated = ImGui::GradientEditor(&gradient, draggingMark, selectedMark);
::GET A COLOR::
float color[3];
gradient.getColorAt(0.3f, color); //position from 0 to 1
::MODIFY GRADIENT WITH CODE::
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(0.2f, 0.1f, 0.0f));
gradient.addMark(0.7f, ImColor(120, 200, 255));
::WOOD BROWNS PRESET::
gradient.getMarks().clear();
gradient.addMark(0.0f, ImColor(0xA0, 0x79, 0x3D));
gradient.addMark(0.2f, ImColor(0xAA, 0x83, 0x47));
gradient.addMark(0.3f, ImColor(0xB4, 0x8D, 0x51));
gradient.addMark(0.4f, ImColor(0xBE, 0x97, 0x5B));
gradient.addMark(0.6f, ImColor(0xC8, 0xA1, 0x65));
gradient.addMark(0.7f, ImColor(0xD2, 0xAB, 0x6F));
gradient.addMark(0.8f, ImColor(0xDC, 0xB5, 0x79));
gradient.addMark(1.0f, ImColor(0xE6, 0xBF, 0x83));
*/
#pragma once
#include "imgui.h"
#include <list>
struct ImGradientMark
{
float color[3] = {0.0f, 0.0f, 0.0f};
float position = 0.0f; //0 to 1
bool alpha = false;
};
class ImGradient
{
public:
ImGradient();
~ImGradient();
void getColorAt(float position, float* color) const;
ImGradientMark* addMark(float position, ImColor const color);
ImGradientMark* addAlphaMark(float position, float alpha);
void removeMark(ImGradientMark* mark);
void clearMarks();
void refreshCache();
std::list<ImGradientMark*> & getMarks(){ return m_marks; }
const std::list<ImGradientMark*> & getMarks() const { return m_marks; }
void computeColorAt(float position, float* color) const;
void setEditAlpha(bool edit) { edit_alpha = edit; }
bool getEditAlpha() const { return edit_alpha; }
private:
std::list<ImGradientMark*> m_marks;
float m_cachedValues[256 * 4];
bool edit_alpha = true;
};
namespace ImGui
{
bool GradientButton(ImGradient* gradient);
bool GradientEditor(ImGradient* gradient,
ImGradientMark* & draggingMark,
ImGradientMark* & selectedMark);
}
| 11,394
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.