hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
84c6389c90774bc9a27ef0182a3f1c8bbec25974 | 652 | h | C | orbicon/src/orbicon_app.h | FanatikPriest/orbicon | d598058430992ee06c1f74bebde5d4352c821e14 | [
"BSD-2-Clause"
] | null | null | null | orbicon/src/orbicon_app.h | FanatikPriest/orbicon | d598058430992ee06c1f74bebde5d4352c821e14 | [
"BSD-2-Clause"
] | 8 | 2015-01-24T18:05:59.000Z | 2015-03-08T07:38:04.000Z | orbicon/src/orbicon_app.h | FanatikPriest/orbicon | d598058430992ee06c1f74bebde5d4352c821e14 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <QtWidgets/QMainWindow>
#include "ui_orbicon_app.h"
#include "image.h"
using namespace cv;
using namespace gpu;
using namespace orbicon;
using namespace std;
class OrbiconApp : public QMainWindow
{
Q_OBJECT
public:
OrbiconApp(QWidget *parent = 0);
~OrbiconApp();
public slots:
void on_action_open_image_triggered();
void on_action_add_images_to_catalog_triggered();
void on_action_match_triggered();
void on_action_settings_triggered();
private:
Ui::OrbiconAppClass ui;
Image* subject;
Image* scene;
void setup_actions();
QString open_single_image();
void match();
}; | 16.717949 | 51 | 0.723926 |
56bba46a9a8b1703be0ece790c0d357f70a48361 | 710 | ts | TypeScript | src/app/modules/fileQuery/components/issue-detail/issue-detail-section/issue-detail-section.component.spec.ts | AdrianSalvador21/example | b1d1a7ef6468d2b96afc858dfb7e45ac25444b07 | [
"MIT"
] | null | null | null | src/app/modules/fileQuery/components/issue-detail/issue-detail-section/issue-detail-section.component.spec.ts | AdrianSalvador21/example | b1d1a7ef6468d2b96afc858dfb7e45ac25444b07 | [
"MIT"
] | null | null | null | src/app/modules/fileQuery/components/issue-detail/issue-detail-section/issue-detail-section.component.spec.ts | AdrianSalvador21/example | b1d1a7ef6468d2b96afc858dfb7e45ac25444b07 | [
"MIT"
] | null | null | null | import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {IssueDetailSectionComponent} from './issue-detail-section.component';
describe('IssueDetailSectionComponent', () => {
let component: IssueDetailSectionComponent;
let fixture: ComponentFixture<IssueDetailSectionComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [IssueDetailSectionComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(IssueDetailSectionComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 27.307692 | 77 | 0.711268 |
270719720f620d00c1503f27057709b329ab81f2 | 4,630 | c | C | smilelib/src/eval/compiler/compile_fn.c | seanofw/smile | 3bc8807513cdb54053134fe2c79c5bf077aa026d | [
"Apache-2.0"
] | 15 | 2016-05-27T14:30:28.000Z | 2020-12-09T09:14:18.000Z | smilelib/src/eval/compiler/compile_fn.c | seanofw/smile | 3bc8807513cdb54053134fe2c79c5bf077aa026d | [
"Apache-2.0"
] | null | null | null | smilelib/src/eval/compiler/compile_fn.c | seanofw/smile | 3bc8807513cdb54053134fe2c79c5bf077aa026d | [
"Apache-2.0"
] | 4 | 2016-01-17T03:52:21.000Z | 2019-02-06T19:24:33.000Z | //---------------------------------------------------------------------------------------
// Smile Programming Language Interpreter
// Copyright 2004-2019 Sean Werkema
//
// 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 <smile/eval/compiler.h>
#include <smile/eval/compiler_internal.h>
#include <smile/smiletypes/smilelist.h>
#include <smile/smiletypes/text/smilesymbol.h>
#include <smile/parsing/parsemessage.h>
#include <smile/parsing/internal/parsedecl.h>
#include <smile/parsing/internal/parsescope.h>
// Form: [$fn [args...] body]
CompiledBlock Compiler_CompileFn(Compiler compiler, SmileList args, CompileFlags compileFlags)
{
CompilerFunction compilerFunction;
CompileScope scope;
SmileList functionArgs;
SmileObject functionBody;
Int i;
ClosureInfo closureInfo;
UserFunctionInfo userFunctionInfo;
Int functionIndex;
String errorMessage;
CompiledBlock compiledBlock, childBlock;
IntermediateInstruction instr;
ByteCodeSegment byteCodeSegment;
Int oldSourceLocation = Compiler_SetAssignedSymbol(compiler, 0);
// The [$fn] expression must be of the form: [$fn [args...] body].
if (SMILE_KIND(args) != SMILE_KIND_LIST
|| (SMILE_KIND(args->a) != SMILE_KIND_LIST && SMILE_KIND(args->a) != SMILE_KIND_NULL)
|| SMILE_KIND(args->d) != SMILE_KIND_LIST || SMILE_KIND(((SmileList)args->d)->d) != SMILE_KIND_NULL) {
Compiler_AddMessage(compiler, ParseMessage_Create(PARSEMESSAGE_ERROR, SMILE_VCALL(args, getSourceLocation),
String_FromC("Cannot compile [$fn]: Expression is not well-formed.")));
return CompiledBlock_CreateError();
}
// Create the function.
functionArgs = (SmileList)args->a;
functionBody = ((SmileList)args->d)->a;
userFunctionInfo = UserFunctionInfo_Create(compiler->currentFunction->userFunctionInfo, SMILE_VCALL(args, getSourceLocation),
functionArgs, functionBody, &errorMessage);
if (userFunctionInfo == NULL) {
Compiler_AddMessage(compiler, ParseMessage_Create(PARSEMESSAGE_ERROR, SMILE_VCALL(functionArgs, getSourceLocation), errorMessage));
return CompiledBlock_CreateError();
}
functionIndex = Compiler_AddUserFunctionInfo(compiler, userFunctionInfo);
compilerFunction = Compiler_BeginFunction(compiler, functionArgs, functionBody);
compilerFunction->userFunctionInfo = userFunctionInfo;
compilerFunction->numArgs = userFunctionInfo->numArgs;
// Begin a new symbol scope for this function.
scope = Compiler_BeginScope(compiler, PARSESCOPE_FUNCTION);
compiledBlock = CompiledBlock_Create();
// Declare the argument symbols, so that they can be correctly resolved.
for (i = 0; i < userFunctionInfo->numArgs; i++) {
Symbol name = userFunctionInfo->args[i].name;
CompileScope_DefineSymbol(scope, name, PARSEDECL_ARGUMENT, i);
}
// Compile the body.
Compiler_SetSourceLocationFromList(compiler, (SmileList)args->d);
childBlock = Compiler_CompileExpr(compiler, functionBody, compileFlags & ~COMPILE_FLAG_NORESULT);
Compiler_EmitRequireResult(compiler, childBlock);
CompiledBlock_AppendChild(compiledBlock, childBlock);
// Emit a return instruction at the end.
Compiler_SetSourceLocationFromList(compiler, args);
EMIT0(Op_Ret, -1);
// We're done intermediate-compiling this function.
Compiler_EndScope(compiler);
byteCodeSegment = CompiledBlock_Finish(compiledBlock, compiler->compiledTables, False);
Compiler_EndFunction(compiler);
// Now transform it into finished bytecodes.
userFunctionInfo->byteCodeSegment = byteCodeSegment;
compilerFunction->stackSize = compiledBlock->maxStackDepth;
// Make a suitable closure decriptor for it, and an actual function object.
closureInfo = Compiler_SetupClosureInfoForCompilerFunction(compiler, compilerFunction);
MemCpy(&userFunctionInfo->closureInfo, closureInfo, sizeof(struct ClosureInfoStruct));
Compiler_RevertSourceLocation(compiler, oldSourceLocation);
compiledBlock = CompiledBlock_Create();
// Finally, emit an instruction to load a new instance of this function onto its parent's stack.
EMIT1(Op_NewFn, 1, index = functionIndex);
return compiledBlock;
}
| 42.477064 | 133 | 0.754428 |
b2a7bbf2b95210c04b5a4943b53d17bfd6bfd265 | 3,872 | rs | Rust | ion-c-sys/src/result.rs | therapon/ion-rust-1 | 19683123b1c95c4655bbc5ece8d4410e8d04729b | [
"Apache-2.0"
] | 1 | 2021-04-07T22:35:39.000Z | 2021-04-07T22:35:39.000Z | ion-c-sys/src/result.rs | Infinite-Blue-1042/ion-rust | b9e43eb985b3f0de177e3b00e722a68b94651000 | [
"Apache-2.0"
] | null | null | null | ion-c-sys/src/result.rs | Infinite-Blue-1042/ion-rust | b9e43eb985b3f0de177e3b00e722a68b94651000 | [
"Apache-2.0"
] | null | null | null | // Copyright Amazon.com, Inc. or its affiliates.
//! Provides convenient integration with `Error` and `Result` for Ion C.
use crate::*;
use std::error::Error;
use std::ffi::CStr;
use std::fmt;
use std::num::TryFromIntError;
/// IonC Error code and its associated error message.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct IonCError {
pub code: i32,
pub message: &'static str,
pub additional: &'static str,
}
impl IonCError {
/// Constructs an `IonCError` from an `iERR` error code.
pub fn from(code: i32) -> Self {
Self::with_additional(code, "iERR Result")
}
/// Constructs an `IonCError` from an `iERR` error code and its own message
pub fn with_additional(code: i32, additional: &'static str) -> Self {
match code {
ion_error_code_IERR_NOT_IMPL..=ion_error_code_IERR_INVALID_LOB_TERMINATOR => {
unsafe {
// this gives us static storage pointer so it doesn't violate lifetime
let c_str = CStr::from_ptr(ion_error_to_str(code));
// the error codes are all ASCII so a panic here is a bug
let message = c_str.to_str().unwrap();
Self {
code,
message,
additional,
}
}
}
_ => Self {
code,
message: "Unknown Ion C Error Code",
additional,
},
}
}
}
impl fmt::Display for IonCError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Error {}: {} ({})",
self.code, self.message, self.additional
)
}
}
impl Error for IonCError {}
impl From<TryFromIntError> for IonCError {
/// Due to the way Ion C works with sizes as i32, it is convenient to be able to coerce
/// a TryFromIntError to `IonCError`.
fn from(_: TryFromIntError) -> Self {
IonCError::from(ion_error_code_IERR_NUMERIC_OVERFLOW)
}
}
impl From<Utf8Error> for IonCError {
/// Due to the way Ion C works with raw UTF-8 byte sequences, it is convenient to be able
/// to coerce a `Utf8Error` to `IonCError`.
fn from(_: Utf8Error) -> Self {
IonCError::from(ion_error_code_IERR_INVALID_UTF8)
}
}
/// A type alias to results from Ion C API, the result value is generally `()` to signify
/// `ion_error_code_IERR_OK` since Ion C doesn't return results but generally takes
/// output parameters.
pub type IonCResult<T> = Result<T, IonCError>;
/// Macro to transform Ion C error code expressions into `Result<(), IonCError>`.
/// Higher-level facades over Ion C functions could map this to `Result<T, IonCError>`
/// or the like.
///
/// NB: `ionc!` implies `unsafe` code.
///
/// ## Usage
///
/// ```
/// # use std::ptr;
/// # use ion_c_sys::*;
/// # use ion_c_sys::result::*;
/// # fn main() -> IonCResult<()> {
/// let mut data = String::from("42");
/// let mut ion_reader: hREADER = ptr::null_mut();
/// let mut ion_type: ION_TYPE = ptr::null_mut();
/// ionc!(
/// ion_reader_open_buffer(
/// &mut ion_reader,
/// data.as_mut_ptr(),
/// data.len() as i32,
/// ptr::null_mut()
/// )
/// )?;
///
/// ionc!(ion_reader_next(ion_reader, &mut ion_type))?;
/// assert_eq!(ion_type as u32, tid_INT_INT);
///
/// let mut value = 0;
/// ionc!(ion_reader_read_int64(ion_reader, &mut value))?;
/// assert_eq!(value, 42);
///
/// ionc!(ion_reader_close(ion_reader))
/// # }
/// ```
#[macro_export]
macro_rules! ionc {
($e:expr) => {
unsafe {
let err: i32 = $e;
match err {
$crate::ion_error_code_IERR_OK => Ok(()),
code => Err($crate::result::IonCError::from(code)),
}
}
};
}
| 29.557252 | 93 | 0.569215 |
06e4a7380ed387ebdee6c9632020760e91fd31f2 | 201 | swift | Swift | PromiseKitAlamofire/PromiseKitAlamofire/Networking/Core/BaseResource.swift | manish-practo/PromiseKit-Alamofire-Manager | da213ab39081a7f9f4986b1779441380daea7751 | [
"MIT"
] | null | null | null | PromiseKitAlamofire/PromiseKitAlamofire/Networking/Core/BaseResource.swift | manish-practo/PromiseKit-Alamofire-Manager | da213ab39081a7f9f4986b1779441380daea7751 | [
"MIT"
] | null | null | null | PromiseKitAlamofire/PromiseKitAlamofire/Networking/Core/BaseResource.swift | manish-practo/PromiseKit-Alamofire-Manager | da213ab39081a7f9f4986b1779441380daea7751 | [
"MIT"
] | null | null | null | //
// BaseResource.swift
// PromiseKitAlamofire
//
// Created by Manish Pandey on 20/04/21.
//
import Alamofire
protocol BaseResource {
var route: (method: HTTPMethod, path: String) { get }
}
| 15.461538 | 57 | 0.681592 |
bd21dbef3c3e51bf60fc5777392ac5a00da683ac | 74 | rs | Rust | src/lib.rs | darosior/revaultd | c7bdb8abf4a4816f56f7d96619d663e90a74b513 | [
"BSD-3-Clause"
] | null | null | null | src/lib.rs | darosior/revaultd | c7bdb8abf4a4816f56f7d96619d663e90a74b513 | [
"BSD-3-Clause"
] | null | null | null | src/lib.rs | darosior/revaultd | c7bdb8abf4a4816f56f7d96619d663e90a74b513 | [
"BSD-3-Clause"
] | null | null | null | pub mod common;
pub mod daemon;
pub use revault_net;
pub use revault_tx;
| 12.333333 | 20 | 0.77027 |
95f0917f1017bd81c1ec7cd1a1c85c844eb94b0b | 318 | css | CSS | public/css/admin_login.css | watanabetomo/laradoc_cake | d665e780b41c1e8052ae0f3c17d33b93f366cf6a | [
"MIT"
] | null | null | null | public/css/admin_login.css | watanabetomo/laradoc_cake | d665e780b41c1e8052ae0f3c17d33b93f366cf6a | [
"MIT"
] | null | null | null | public/css/admin_login.css | watanabetomo/laradoc_cake | d665e780b41c1e8052ae0f3c17d33b93f366cf6a | [
"MIT"
] | null | null | null | body {
background-image: url("../img/contentback.jpg");
text-align: center;
}
main {
min-height: 500px;
}
table {
margin: 0 auto;
}
.card {
width: 50%;
margin: 30px auto;
background-color: #ffe;
}
h1 {
margin-bottom: 20px;
}
p {
margin-top: 20px;
}
.error {
color: red;
}
| 10.258065 | 52 | 0.553459 |
c7f9d80fb8be2dd9656f7497ef94c6dd6e8f3742 | 542 | java | Java | src/main/java/de/davelee/trams/operations/repository/RouteRepository.java | daveajlee/trams-operations | 0f9086370e85e8c768516831cc159df140ec1ec1 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/davelee/trams/operations/repository/RouteRepository.java | daveajlee/trams-operations | 0f9086370e85e8c768516831cc159df140ec1ec1 | [
"Apache-2.0"
] | null | null | null | src/main/java/de/davelee/trams/operations/repository/RouteRepository.java | daveajlee/trams-operations | 0f9086370e85e8c768516831cc159df140ec1ec1 | [
"Apache-2.0"
] | 2 | 2021-03-28T18:08:23.000Z | 2021-03-28T18:10:27.000Z | package de.davelee.trams.operations.repository;
import de.davelee.trams.operations.model.Route;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
/**
* This class enables as part of Spring Data access to the route objects stored in the Mongo DB.
* @author Dave Lee
*/
public interface RouteRepository extends MongoRepository<Route, String> {
List<Route> findByCompany (final String company);
List<Route> findByCompanyAndRouteNumber (final String company, final String routeNumber);
}
| 28.526316 | 96 | 0.785978 |
fb1cae7d3f19e9ae6496adf3bd289f908ba30000 | 211 | h | C | Example/APIKit1/GWViewController.h | a752538236/APIMode | 6d9eab768b8b8cfdd1415b519d32d2c27d969b3e | [
"MIT"
] | null | null | null | Example/APIKit1/GWViewController.h | a752538236/APIMode | 6d9eab768b8b8cfdd1415b519d32d2c27d969b3e | [
"MIT"
] | null | null | null | Example/APIKit1/GWViewController.h | a752538236/APIMode | 6d9eab768b8b8cfdd1415b519d32d2c27d969b3e | [
"MIT"
] | null | null | null | //
// GWViewController.h
// APIKit1
//
// Created by a752538236 on 04/06/2018.
// Copyright (c) 2018 a752538236. All rights reserved.
//
@import UIKit;
@interface GWViewController : UIViewController
@end
| 15.071429 | 55 | 0.706161 |
4cd3c0a9bf7356905919c5b6f35f5eb2ec41763f | 544 | swift | Swift | Tests/Foundation/Extensions/DispatchQueueExtensionsTests.swift | masmovil/swift-magic-pills | a53d280a97a5a75dfa7c68e5dfc1171b460c6bc7 | [
"Apache-2.0"
] | 11 | 2019-04-12T09:44:58.000Z | 2021-01-31T12:36:27.000Z | Tests/Foundation/Extensions/DispatchQueueExtensionsTests.swift | masmovil/swift-magic-pills | a53d280a97a5a75dfa7c68e5dfc1171b460c6bc7 | [
"Apache-2.0"
] | 46 | 2019-04-02T13:40:17.000Z | 2020-08-25T15:47:49.000Z | Tests/Foundation/Extensions/DispatchQueueExtensionsTests.swift | masmovil/swift-mas-magic-pills | 28202138fd23751a72d40022a54270cc34bbd5df | [
"Apache-2.0"
] | 3 | 2020-01-14T14:11:52.000Z | 2020-11-16T22:42:39.000Z | import Foundation
import XCTest
class DispatchQueueExtensionsTests: XCTestCase {
func test_ismain() {
let checks = expectation(description: "Check for async validations")
checks.expectedFulfillmentCount = 2
DispatchQueue.global(qos: .background).async {
XCTAssertFalse(DispatchQueue.isMain)
checks.fulfill()
}
DispatchQueue.main.async {
XCTAssertTrue(DispatchQueue.isMain)
checks.fulfill()
}
waitForExpectations(timeout: 5)
}
}
| 24.727273 | 76 | 0.641544 |
27befb4e8a9907df965064255ae59b61a4970611 | 2,155 | asm | Assembly | libsrc/_DEVELOPMENT/string/z80/asm_strrspn.asm | UnivEngineer/z88dk | 9047beba62595b1d88991bc934da75c0e2030d07 | [
"ClArtistic"
] | 1 | 2022-03-08T11:55:58.000Z | 2022-03-08T11:55:58.000Z | libsrc/_DEVELOPMENT/string/z80/asm_strrspn.asm | UnivEngineer/z88dk | 9047beba62595b1d88991bc934da75c0e2030d07 | [
"ClArtistic"
] | 2 | 2022-03-20T22:17:35.000Z | 2022-03-24T16:10:00.000Z | libsrc/_DEVELOPMENT/string/z80/asm_strrspn.asm | jorgegv/z88dk | 127130cf11f9ff268ba53e308138b12d2b9be90a | [
"ClArtistic"
] | null | null | null |
; ===============================================================
; Dec 2013
; ===============================================================
;
; size_t strrspn(const char *str, const char *cset)
;
; The reverse of strspn()
;
; Returns the number of leading chars in the input string up to
; and including the last occurrence of a char not in cset.
;
; If all chars of str are in cset, returns 0.
;
; If cset is empty, returns strlen(str).
;
; Example:
;
; char *s = "abcdee";
; int pos;
;
; // search from the end of s for the first char not in "e"
; pos = strrspn(s, "e"); // returns 4 = num leading chars not in "e"
;
; // remove the last two Es from s by truncating s
; s[pos] = '\0';
;
; ===============================================================
SECTION code_clib
SECTION code_string
PUBLIC asm_strrspn
EXTERN __str_locate_nul, l_neg_bc, asm_strchr, error_znc
asm_strrspn:
; enter : de = char *cset = matching set
; hl = char *str = string
;
; exit : hl = position of last char in str not in cset
; bc = char *str = string
;
; carry reset if all of str contains chars only from cset
;
; uses : af, bc, hl
push hl ; save str
call __str_locate_nul ; hl points at terminating 0 in str
call l_neg_bc ; bc = strlen(str) + 1
ld a,(de)
or a
jr Z,empty_cset
loop:
dec bc ; position of next char in str
ld a,b
or c
jr Z,all_in_cset
dec hl ; & next char in str to check
push bc
push hl
; see if current char from string is in cset
ld c,(hl)
ld hl,de ; hl = cset
call asm_strchr ; carry reset if in cset
pop hl
pop bc
jr NC,loop ; loop if char in cset
not_in_cset:
ld hl,bc ; hl = char position
pop bc ; bc = char *str
ret
all_in_cset:
pop bc ; bc = char *str
jp error_znc
empty_cset:
ld hl,bc
dec hl ; hl = strlen(str)
pop bc ; bc = char *str
ret
| 20.92233 | 69 | 0.49652 |
2a46759d6b8fbd0e0c6eb13ad2eccac79febe6b2 | 5,332 | java | Java | src/main/java/com/somlaser/Mp3Converter.java | feliperochadev/mp3-name-metadata-formatter | edb2c4bbde673bfec4dd348a76d1c7c61077503c | [
"MIT"
] | null | null | null | src/main/java/com/somlaser/Mp3Converter.java | feliperochadev/mp3-name-metadata-formatter | edb2c4bbde673bfec4dd348a76d1c7c61077503c | [
"MIT"
] | null | null | null | src/main/java/com/somlaser/Mp3Converter.java | feliperochadev/mp3-name-metadata-formatter | edb2c4bbde673bfec4dd348a76d1c7c61077503c | [
"MIT"
] | null | null | null | package com.somlaser;
import com.mpatric.mp3agic.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static com.google.common.io.Files.getFileExtension;
import static com.google.common.io.Files.getNameWithoutExtension;
public class Mp3Converter {
private static final List<String> CONVERSABLE_FILE_EXTENSIONS = Collections.singletonList("mp3");
private final ConverterFormat FORMAT;
private Integer filesConverted;
public Mp3Converter(ConverterFormat format) {
this.FORMAT = format;
this.filesConverted = 0;
}
public static String getPathType() {
return System.getProperty("os.name").toLowerCase().contains("win") ? "\\" : "/";
}
public void runConverterToDirectory(File currentDirectory, String rootPath, String outputPath, boolean isFirstCall) throws IOException {
File[] directoryListing = currentDirectory.listFiles();
if (isFirstCall)
Files.createDirectories(Paths.get(currentDirectory+outputPath));
for (File file : Objects.requireNonNull(directoryListing)) {
String[] rootSplitPath = file.isDirectory() ? file.getAbsolutePath().split(rootPath.replace("\\", "\\\\")) :
file.getParent().split(rootPath.replace("\\", "\\\\"));
String newPath = rootSplitPath.length > 1 ? rootPath + outputPath + rootSplitPath[1] :
rootPath + outputPath;
if (file.isDirectory()) {
if (Files.notExists(Paths.get(newPath))) {
Files.createDirectories(Paths.get(newPath));
runConverterToDirectory(file, rootPath, outputPath, false);
}
}
else {
try {
String fileExtension = getFileExtension(file.getName()).toLowerCase();
if (CONVERSABLE_FILE_EXTENSIONS.contains(fileExtension)) {
boolean result = convert(file.getAbsolutePath(), newPath);
if (result) {
this.filesConverted++;
System.out.println("Arquivo convertido: " + newPath + getPathType() +file.getName());
} else {
System.out.println("\u001B[31mFalha ao converter arquivo: " + file.getName());
}
}
} catch (Exception e) {
System.out.println("\u001B[31mErro " + e.getMessage() +" ao processar o arquivo: " + file.getName());
}
}
}
}
public Integer getFilesConverted() {
return this.filesConverted;
}
private boolean convert(String filePath, String outputPath) throws InvalidDataException, IOException,
UnsupportedTagException, NotSupportedException {
Mp3File mp3file = new Mp3File(filePath);
ID3v1 id3v1Tag;
if (mp3file.hasId3v1Tag()) {
id3v1Tag = mp3file.getId3v1Tag();
} else {
id3v1Tag = new ID3v1Tag();
mp3file.setId3v1Tag(id3v1Tag);
}
id3v1Tag.setTrack(format(id3v1Tag.getTrack()));
id3v1Tag.setArtist(format(id3v1Tag.getArtist()));
id3v1Tag.setTitle(format(id3v1Tag.getTitle()));
id3v1Tag.setAlbum(format(id3v1Tag.getAlbum()));
id3v1Tag.setYear(format(id3v1Tag.getYear()));
id3v1Tag.setGenre(id3v1Tag.getGenre());
id3v1Tag.setComment(format(id3v1Tag.getComment()));
ID3v2 id3v2Tag;
if (mp3file.hasId3v2Tag()) {
id3v2Tag = mp3file.getId3v2Tag();
} else {
id3v2Tag = new ID3v24Tag();
mp3file.setId3v2Tag(id3v2Tag);
}
id3v2Tag.setTrack(format(id3v2Tag.getTrack()));
id3v2Tag.setArtist(format(id3v2Tag.getArtist()));
id3v2Tag.setTitle(format(id3v2Tag.getTitle()));
id3v2Tag.setAlbum(format(id3v2Tag.getAlbum()));
id3v2Tag.setYear(format(id3v2Tag.getYear()));
id3v2Tag.setGenre(id3v2Tag.getGenre());
id3v2Tag.setComment(format(id3v2Tag.getComment()));
id3v2Tag.setComposer(format(id3v2Tag.getComposer()));
id3v2Tag.setPublisher(format(id3v2Tag.getPublisher()));
id3v2Tag.setOriginalArtist(format(id3v2Tag.getOriginalArtist()));
id3v2Tag.setAlbumArtist(format(id3v2Tag.getAlbumArtist()));
id3v2Tag.setCopyright(format(id3v2Tag.getCopyright()));
id3v2Tag.setUrl(format(id3v2Tag.getUrl()));
id3v2Tag.setEncoder(format(id3v2Tag.getEncoder()));
String fileExtension = getFileExtension(mp3file.getFilename());
String fileName = format(getNameWithoutExtension(mp3file.getFilename()));
mp3file.save(outputPath + getPathType() + fileName + "." + fileExtension);
return true;
}
private String format(String original) {
if (original != null) {
switch (FORMAT) {
case UPPER_CASE:
return original.toUpperCase();
case LOWER_CASE:
return original.toLowerCase();
default:
return original;
}
}
return original;
}
}
| 41.015385 | 140 | 0.608215 |
58061f41561745abd6eae9f3e09423ac550aea8b | 1,066 | c | C | src/cutscenes/scenes.c | timgates42/taisei | 6c792dc2be4c4ba2b4b6f43da9a9fdf76b7264de | [
"CC-BY-4.0"
] | 573 | 2017-10-12T17:48:57.000Z | 2022-03-28T05:44:43.000Z | src/cutscenes/scenes.c | timgates42/taisei | 6c792dc2be4c4ba2b4b6f43da9a9fdf76b7264de | [
"CC-BY-4.0"
] | 153 | 2017-10-18T19:51:33.000Z | 2022-03-31T11:06:40.000Z | src/cutscenes/scenes.c | timgates42/taisei | 6c792dc2be4c4ba2b4b6f43da9a9fdf76b7264de | [
"CC-BY-4.0"
] | 72 | 2017-11-17T17:32:46.000Z | 2022-03-23T11:36:33.000Z | /*
* This software is licensed under the terms of the MIT License.
* See COPYING for further information.
* ---
* Copyright (c) 2011-2019, Lukas Weber <laochailan@web.de>.
* Copyright (c) 2012-2019, Andrei Alexeyev <akari@taisei-project.org>.
*/
#include "taisei.h"
#include "scenes.h"
Cutscene const g_cutscenes[NUM_CUTSCENE_IDS] = {
[CUTSCENE_ID_INTRO] = {
#include "intro.inc.h"
},
[CUTSCENE_ID_REIMU_BAD_END] = {
#include "reimu_bad_end.inc.h"
},
[CUTSCENE_ID_REIMU_GOOD_END] = {
#include "reimu_good_end.inc.h"
},
[CUTSCENE_ID_REIMU_EXTRA_INTRO] = {
#include "reimu_extra_intro.inc.h"
},
[CUTSCENE_ID_MARISA_BAD_END] = {
#include "marisa_bad_end.inc.h"
},
[CUTSCENE_ID_MARISA_GOOD_END] = {
#include "marisa_good_end.inc.h"
},
[CUTSCENE_ID_MARISA_EXTRA_INTRO] = {
#include "marisa_extra_intro.inc.h"
},
[CUTSCENE_ID_YOUMU_BAD_END] = {
#include "youmu_bad_end.inc.h"
},
[CUTSCENE_ID_YOUMU_GOOD_END] = {
#include "youmu_good_end.inc.h"
},
[CUTSCENE_ID_YOUMU_EXTRA_INTRO] = {
#include "youmu_extra_intro.inc.h"
},
};
| 23.688889 | 71 | 0.708255 |
c8cce3b87507994fbbb70f12cd1a1a05c75c1150 | 482 | rs | Rust | elasticsearch/src/enrich/mod.rs | iostat/elasticsearch-rs | 47a58dde6aff0332005a37d15f1a3c1cf12dd745 | [
"Apache-2.0"
] | 25 | 2015-12-27T12:21:17.000Z | 2016-09-15T00:56:45.000Z | elasticsearch/src/enrich/mod.rs | iostat/elasticsearch-rs | 47a58dde6aff0332005a37d15f1a3c1cf12dd745 | [
"Apache-2.0"
] | 146 | 2015-12-12T09:47:49.000Z | 2016-09-19T10:21:54.000Z | elasticsearch/src/enrich/mod.rs | iostat/elasticsearch-rs | 47a58dde6aff0332005a37d15f1a3c1cf12dd745 | [
"Apache-2.0"
] | 3 | 2016-05-04T20:18:13.000Z | 2016-07-01T03:17:44.000Z | //! Enrich APIs
//!
//! Manage [enrich policies](https://www.elastic.co/guide/en/elasticsearch/reference/master/ingest-enriching-data.html#enrich-policy)
//! that can be used by the [enrich processor](https://www.elastic.co/guide/en/elasticsearch/reference/master/enrich-processor.html)
//! as part of an [ingest pipeline](../ingest/index.html), to add data from your existing indices
//! to incoming documents during ingest.
pub use super::generated::namespace_clients::enrich::*; | 60.25 | 133 | 0.759336 |
d9c050a11dcee8556644793d3015a320debc2a27 | 10,415 | rs | Rust | proc-macros/src/lib.rs | c410-f3r/jsonrpsee | cbd70eb80c323fed86d69df12592c40fdc9a00c0 | [
"MIT"
] | null | null | null | proc-macros/src/lib.rs | c410-f3r/jsonrpsee | cbd70eb80c323fed86d69df12592c40fdc9a00c0 | [
"MIT"
] | null | null | null | proc-macros/src/lib.rs | c410-f3r/jsonrpsee | cbd70eb80c323fed86d69df12592c40fdc9a00c0 | [
"MIT"
] | null | null | null | // Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any
// person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the
// Software without restriction, including without
// limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice
// shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
extern crate proc_macro;
use inflector::Inflector as _;
use proc_macro::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use std::collections::HashSet;
use syn::spanned::Spanned as _;
mod api_def;
/// Wraps around one or more API definitions and generates an enum.
///
/// The format within this macro must be:
///
/// ```ignore
/// jsonrpsee_proc_macros::rpc_client_api! {
/// Foo { ... }
/// pub(crate) Bar { ... }
/// }
/// ```
///
/// The `Foo` and `Bar` are identifiers, optionally prefixed with a visibility modifier
/// (e.g. `pub`).
///
/// The content of the blocks is the same as the content of a trait definition, except that
/// default implementations for methods are forbidden.
///
/// For each identifier (such as `Foo` and `Bar` in the example above), this macro will generate
/// an enum where each variant corresponds to a function of the definition. Function names are
/// turned into PascalCase to conform to the Rust style guide.
///
/// Additionally, each generated enum has one method per function definition that lets you perform
/// the method has a client.
///
// TODO(niklasad1): Generic type params for individual methods doesn't work
// because how the enum is generated, so for now type params must be declared on the entire enum.
// The reason is that all type params on the enum is bound as a separate variant but
// not generic params i.e, either params or return type.
// To handle that properly, all generic types has to be collected and applied to the enum, see example:
//
// ```rust
// jsonrpsee_rpc_client_api! {
// Api {
// // Doesn't work.
// fn generic_notif<T>(t: T);
// }
// ```
//
// Expands to which doesn't compile:
// ```rust
// enum Api {
// GenericNotif {
// t: T,
// },
// }
// ```
// The code should be expanded to (to compile):
// ```rust
// enum Api<T> {
// GenericNotif {
// t: T,
// },
// }
// ```
#[proc_macro]
pub fn rpc_client_api(input_token_stream: TokenStream) -> TokenStream {
// Start by parsing the input into what we expect.
let defs: api_def::ApiDefinitions = match syn::parse(input_token_stream) {
Ok(d) => d,
Err(err) => return err.to_compile_error().into(),
};
let mut out = Vec::with_capacity(defs.apis.len());
for api in defs.apis {
match build_client_api(api) {
Ok(a) => out.push(a),
Err(err) => return err.to_compile_error().into(),
};
}
TokenStream::from(quote! {
#(#out)*
})
}
/// Generates the macro output token stream corresponding to a single API.
fn build_client_api(api: api_def::ApiDefinition) -> Result<proc_macro2::TokenStream, syn::Error> {
let enum_name = &api.name;
let visibility = &api.visibility;
let generics = api.generics.clone();
let mut non_used_type_params = HashSet::new();
let mut variants = Vec::new();
for function in &api.definitions {
let variant_name = snake_case_to_camel_case(&function.signature.ident);
if let syn::ReturnType::Type(_, ty) = &function.signature.output {
non_used_type_params.insert(ty);
};
let mut params_list = Vec::new();
for input in function.signature.inputs.iter() {
let (ty, pat_span, param_variant_name) = match input {
syn::FnArg::Receiver(_) => {
return Err(syn::Error::new(
input.span(),
"Having `self` is not allowed in RPC queries definitions",
));
}
syn::FnArg::Typed(syn::PatType { ty, pat, .. }) => (ty, pat.span(), param_variant_name(&pat)?),
};
params_list.push(quote_spanned!(pat_span=> #param_variant_name: #ty));
}
variants.push(quote_spanned!(function.signature.ident.span()=>
#variant_name {
#(#params_list,)*
}
));
}
let client_impl_block = build_client_impl(&api)?;
let mut ret_variants = Vec::new();
for (idx, ty) in non_used_type_params.into_iter().enumerate() {
// NOTE(niklasad1): variant names are converted from `snake_case` to `CamelCase`
// It's impossible to have collisions between `_0, _1, ... _N`
// Because variant name `_0`, `__0` becomes `0` in `CamelCase`
// then `0` is not a valid identifier in Rust syntax and the error message is hard to understand.
// Perhaps document this in macro when it's ready.
let varname = format_ident!("_{}", idx);
ret_variants.push(quote_spanned!(ty.span()=> #varname (#ty)));
}
Ok(quote_spanned!(api.name.span()=>
#visibility enum #enum_name #generics {
#(#[allow(unused)] #variants,)* #(#[allow(unused)] #ret_variants,)*
}
#client_impl_block
))
}
/// Builds the impl block that allow performing outbound JSON-RPC queries.
///
/// Generates the `impl <enum> { }` block containing functions that perform RPC client calls.
fn build_client_impl(api: &api_def::ApiDefinition) -> Result<proc_macro2::TokenStream, syn::Error> {
let enum_name = &api.name;
let (impl_generics_org, type_generics, where_clause_org) = api.generics.split_for_impl();
let client_functions = build_client_functions(&api)?;
Ok(quote_spanned!(api.name.span() =>
impl #impl_generics_org #enum_name #type_generics #where_clause_org {
#(#client_functions)*
}
))
}
/// Builds the functions that allow performing outbound JSON-RPC queries.
///
/// Generates a list of functions that perform RPC client calls.
fn build_client_functions(api: &api_def::ApiDefinition) -> Result<Vec<proc_macro2::TokenStream>, syn::Error> {
let visibility = &api.visibility;
let mut client_functions = Vec::new();
for function in &api.definitions {
let f_name = &function.signature.ident;
let ret_ty = match function.signature.output {
syn::ReturnType::Default => quote!(()),
syn::ReturnType::Type(_, ref ty) => quote_spanned!(ty.span()=> #ty),
};
let rpc_method_name =
function.attributes.method.clone().unwrap_or_else(|| function.signature.ident.to_string());
let mut params_list = Vec::new();
let mut params_to_json = Vec::new();
let mut params_to_array = Vec::new();
let mut params_tys = Vec::new();
for (param_index, input) in function.signature.inputs.iter().enumerate() {
let (ty, pat_span, rpc_param_name) = match input {
syn::FnArg::Receiver(_) => {
return Err(syn::Error::new(
input.span(),
"Having `self` is not allowed in RPC queries definitions",
));
}
syn::FnArg::Typed(syn::PatType { ty, pat, attrs, .. }) => {
(ty, pat.span(), rpc_param_name(&pat, &attrs)?)
}
};
let generated_param_name =
syn::Ident::new(&format!("param{}", param_index), proc_macro2::Span::call_site());
params_tys.push(ty);
params_list.push(quote_spanned!(pat_span=> #generated_param_name: impl Into<#ty>));
params_to_json.push(quote_spanned!(pat_span=>
map.insert(
#rpc_param_name.to_string(),
jsonrpsee_types::jsonrpc::to_value(#generated_param_name.into()).map_err(|e| jsonrpsee_types::error::Error::Custom(format!("{:?}", e)))?
);
));
params_to_array.push(quote_spanned!(pat_span =>
jsonrpsee_types::jsonrpc::to_value(#generated_param_name.into()).map_err(|e| jsonrpsee_types::error::Error::Custom(format!("{:?}", e)))?
));
}
let params_building = if params_list.is_empty() {
quote! {jsonrpsee_types::jsonrpc::Params::None}
} else if function.attributes.positional_params {
quote_spanned!(function.signature.span()=>
jsonrpsee_types::jsonrpc::Params::Array(vec![
#(#params_to_array),*
])
)
} else {
let params_list_len = params_list.len();
quote_spanned!(function.signature.span()=>
jsonrpsee_types::jsonrpc::Params::Map({
let mut map = jsonrpsee_types::jsonrpc::JsonMap::with_capacity(#params_list_len);
#(#params_to_json)*
map
})
)
};
let is_notification = function.is_void_ret_type();
let function_body = if is_notification {
quote_spanned!(function.signature.span()=>
client.notification(#rpc_method_name, #params_building).await
)
} else {
quote_spanned!(function.signature.span()=>
client.request(#rpc_method_name, #params_building).await
)
};
client_functions.push(quote_spanned!(function.signature.span()=>
#visibility async fn #f_name (client: &impl jsonrpsee_types::traits::Client #(, #params_list)*) -> core::result::Result<#ret_ty, jsonrpsee_types::error::Error>
where
#ret_ty: jsonrpsee_types::jsonrpc::DeserializeOwned
#(, #params_tys: jsonrpsee_types::jsonrpc::Serialize)*
{
#function_body
}
));
}
Ok(client_functions)
}
/// Turns a snake case function name into an UpperCamelCase name suitable to be an enum variant.
fn snake_case_to_camel_case(snake_case: &syn::Ident) -> syn::Ident {
syn::Ident::new(&snake_case.to_string().to_pascal_case(), snake_case.span())
}
/// Determine the name of the variant in the enum based on the pattern of the function parameter.
fn param_variant_name(pat: &syn::Pat) -> syn::parse::Result<&syn::Ident> {
match pat {
// TODO: check other fields of the `PatIdent`
syn::Pat::Ident(ident) => Ok(&ident.ident),
_ => unimplemented!(),
}
}
/// Determine the name of the parameter based on the pattern.
fn rpc_param_name(pat: &syn::Pat, _attrs: &[syn::Attribute]) -> syn::parse::Result<String> {
// TODO: look in attributes if the user specified a param name
match pat {
// TODO: check other fields of the `PatIdent`
syn::Pat::Ident(ident) => Ok(ident.ident.to_string()),
_ => unimplemented!(),
}
}
| 34.372937 | 162 | 0.69035 |
b9d0489e749889b3978e17f1f89b26b786f6d14a | 2,903 | h | C | components/ping/ping_esp8266.h | viotemp1/esphome-component-ping | 3033e1eb3a8a78e69b1089ac88ed071cd2b81818 | [
"ISC"
] | 10 | 2021-07-24T07:46:07.000Z | 2022-03-26T09:18:36.000Z | components/ping/ping_esp8266.h | viotemp1/esphome-component-ping | 3033e1eb3a8a78e69b1089ac88ed071cd2b81818 | [
"ISC"
] | 12 | 2021-07-20T19:32:15.000Z | 2022-03-31T08:00:35.000Z | components/ping/ping_esp8266.h | viotemp1/esphome-component-ping | 3033e1eb3a8a78e69b1089ac88ed071cd2b81818 | [
"ISC"
] | 3 | 2021-09-23T13:34:49.000Z | 2022-02-12T09:40:12.000Z | /*
* Copyright (c) 2021 Tomoyuki Sakurai <y@trombik.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#pragma once
#ifdef ARDUINO_ARCH_ESP8266
#include "AsyncPing.h"
#include "esphome/components/sensor/sensor.h"
#define EACH_RESULT true
#define END false
#define TAG "ping"
namespace esphome {
namespace ping {
class PingSensorESP8266 : public PingSensor {
public:
void setup() override {
ping.on(EACH_RESULT, [this](const AsyncPingResponse &response) {
if (response.answer) {
ESP_LOGI(TAG, "%d bytes from %s: icmp_seq=%d ttl=%d time=%d ms", response.size, target.c_str(),
response.icmp_seq, response.ttl, response.time);
this->incr_total_success_time(response.time);
} else {
ESP_LOGI(TAG, "no reply from %s", target.c_str());
}
return false;
});
/* at the end, set the result */
ping.on(END, [this](const AsyncPingResponse &response) {
float loss = 0;
int total_failed_count = response.total_sent - response.total_recv;
if (response.total_sent != 0) {
loss = (float) total_failed_count / response.total_sent;
}
int mean = 0;
if (response.total_recv != 0) {
mean = total_success_time / response.total_recv;
}
this->set_latest_loss(loss * 100);
this->set_latest_latency(mean);
ESP_LOGI(TAG, "packet loss: %0.1f %% latency: %d ms", loss * 100, mean);
this->reset();
return true;
});
ping.begin(target.c_str(), n_packet, timeout);
}
void update() override {
float loss;
int latency_ms;
loss = this->get_latest_loss();
latency_ms = this->get_latest_latency();
if (loss >= 0 && this->packet_loss_sensor_ != nullptr) {
packet_loss_sensor_->publish_state(loss);
}
if (latency_ms >= 0 && this->latency_sensor_ != nullptr) {
latency_sensor_->publish_state((float) latency_ms / 1000);
}
ping.begin(target.c_str(), n_packet, timeout);
}
private:
protected:
int total_success_time;
void reset() { total_success_time = 0; }
void incr_total_success_time(int time) { total_success_time += time; }
AsyncPing ping;
};
} // namespace ping
} // namespace esphome
#endif
| 30.239583 | 103 | 0.676886 |
b87ffb34d071673151d11a7dfa2486421773f0b4 | 1,587 | kt | Kotlin | petal/src/main/kotlin/petal/common/value/NativeFunction.kt | NekoGoddessAlyx/Petal | bb1fee0549316ebbeae139745f29287f833e1d11 | [
"Apache-2.0"
] | null | null | null | petal/src/main/kotlin/petal/common/value/NativeFunction.kt | NekoGoddessAlyx/Petal | bb1fee0549316ebbeae139745f29287f833e1d11 | [
"Apache-2.0"
] | null | null | null | petal/src/main/kotlin/petal/common/value/NativeFunction.kt | NekoGoddessAlyx/Petal | bb1fee0549316ebbeae139745f29287f833e1d11 | [
"Apache-2.0"
] | null | null | null | package petal.common.value
/**
* A function that takes arguments from Petal code and returns a value back to Petal.
*
* The provided [Args] should be used only within the scope of execution.
* Any use outside the scope will result in undefined behavior.
*/
public typealias NativeFunction = (Args) -> Value
/**
* Represents arguments passed from Petal code to a [NativeFunction].
*
* The view represented by this object is only valid during execution of the function.
* Attempting to access any element of this object outside the scope of execution will result in undefined behavior.
*/
public class Args internal constructor(
private var stack: Array<Value>,
private var start: Int,
private var _size: Int
) : Iterable<Value> {
public val size: Int get() = _size
public val receiver: Value get() = stack[start - 1]
public operator fun get(index: Int): Value {
if (index !in 0 until _size) return Value.NULL
return stack[start + index]
}
public fun toArray(): Array<Value> = stack.copyOfRange(start, start + _size)
override fun iterator(): Iterator<Value> = object : Iterator<Value> {
var index = start
override fun hasNext(): Boolean = index < start + _size
override fun next(): Value = stack[index++]
}
/**
* Called after the [NativeFunction] has been invoked.
* This ensures that stack changes don't leak.
*/
internal fun close() {
stack = NULL_ARRAY
start = 1
_size = 0
}
}
private val NULL_ARRAY: Array<Value> = arrayOf(Value.NULL) | 30.519231 | 116 | 0.672338 |
5b34f72134ea100f6369e48e532bbcbe05eacd91 | 1,159 | c | C | src/Epsilon/uart.c | Xennis/Bluecontroller_BCA8_BTM | 65f51ae94b8b9943bb66b99685d85d084c916ef1 | [
"CC-BY-3.0"
] | null | null | null | src/Epsilon/uart.c | Xennis/Bluecontroller_BCA8_BTM | 65f51ae94b8b9943bb66b99685d85d084c916ef1 | [
"CC-BY-3.0"
] | null | null | null | src/Epsilon/uart.c | Xennis/Bluecontroller_BCA8_BTM | 65f51ae94b8b9943bb66b99685d85d084c916ef1 | [
"CC-BY-3.0"
] | null | null | null | /**
* @file uart.c
* @author Florian Thaeter, Fabi Rosenthal
* @version Epsilon
* @date 18.05.2013
*
* @section LICENSE
* Licence: CC BY 3.0 (http://creativecommons.org/licenses/by/3.0/)
*
* @section DESCRIPTION
* Code: http://github.com/Xennis/Bluecontroller_BCA8_BTM
*
* Documentation: http://xennis.org/wiki/Bluecontroller
*/
#include "uart.h"
/**
* @brief UART Initialization
*
* USART Initialization (datasheet page 178)
*/
void uart_init( unsigned int ubrr )
{
/* Set baud rate */
UBRRH = (unsigned char)(ubrr>>8);
UBRRL = (unsigned char)ubrr;
/* Enable double speed */
UCSRA = (0<<U2X0);
/* Enable receiver, transmitter and UART RX Complete Interrupt (activate global interrupt flag necessary) */
UCSRB |= (1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0);
/* Set frame format: 8data, 1stop bit */
UCSRC |= (1<<UCSZ01)|(1<<UCSZ00);
/* Dummy read to clear UDR */
UDR;
}
/**
* @brief Send char
*
* Sending Frames with 5 to 8 Data Bit (datasheet page 179)
*/
void uart_putc( unsigned char data )
{
/* Wait for empty transmit buffer */
while ( !( UCSRA & (1<<UDRE) ) );
/* Put data into buffer, sends the data */
UDR = data;
} | 23.18 | 109 | 0.654012 |
573cd93a5e3888d8cbe5ab4fbd2c0a43af9dc07c | 3,084 | c | C | src/graph.c | kkdwivedi/covid-sim | b8d1d42075b8998b02d7b09efac65b1eae205224 | [
"MIT"
] | null | null | null | src/graph.c | kkdwivedi/covid-sim | b8d1d42075b8998b02d7b09efac65b1eae205224 | [
"MIT"
] | null | null | null | src/graph.c | kkdwivedi/covid-sim | b8d1d42075b8998b02d7b09efac65b1eae205224 | [
"MIT"
] | null | null | null | #include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include "graph.h"
#include "config.h"
#define POOL_SIZE (SAMPLE_SIZE * (NR_EDGES + 1))
extern List ListS;
extern List ListI;
extern List ListR;
bool sir_list_add_item(Node *n, List *l)
{
static size_t iterator = 0;
static struct sir *pool = NULL;
if (!l && !n) {
free(pool);
pool = NULL;
iterator = 0;
return true;
}
if (!pool) {
pool = malloc(POOL_SIZE * sizeof *pool);
if (!pool) return false;
}
struct sir *s = NULL;
if (iterator < POOL_SIZE)
s = pool + iterator++;
if (!s) return false;
s->list.next = NULL;
list_append(l, &s->list);
s->item = n;
return true;
}
void sir_list_add_sir(struct sir *s, List *l)
{
assert(s);
list_append(l, &s->list);
}
struct sir* sir_list_del_item(Node *n, List *l)
{
/* l is assumed to be anchor, not an object embedded in entry */
struct sir *i;
list_for_each_entry(i, l->next, struct sir, list) {
if (i->item == n) {
struct sir *f = container_of(&i->list, struct sir, list);
/* updates l->next */
list_delete(&l->next, &i->list);
/* freeing individual elements is not possible
in pool based implementation */
// free(f);
f->list.next = NULL;
return f;
}
}
return NULL;
}
void sir_list_dump(List *l)
{
struct sir *i;
list_for_each_entry(i, l->next, struct sir, list)
fprintf(stderr, "%u ", i->item->id);
log_info("");
}
void sir_list_del_rec(List *l)
{
if (!l->next) return;
struct sir *i;
/* we cannot use list_for_each_entry here, since we need to
* advance the iterator and only then free the memory
*/
for (i = container_of(l->next, struct sir, list); i;) {
struct sir *f = i;
i = i->list.next ? container_of(i->list.next, struct sir, list) : NULL;
//sir_list_dump(&f->list, true);
free(f);
}
l->next = NULL;
}
size_t sir_list_len(List *l)
{
/* begin counting from next, as l is anchor */
size_t count = 0;
while (l->next) {
l = l->next;
count++;
}
return count;
}
Node* node_new(size_t sz)
{
Node *n = malloc(sz * sizeof(*n));
if (!n) return NULL;
for (size_t i = 0; i < sz; i++) {
n[i].id = i + 1;
n[i].state = SIR_SUSCEPTIBLE;
n[i].neigh.next = NULL;
n[i].tail = &n[i].neigh;
n[i].initial = false;
}
return n;
}
void node_connect(Node *a, Node *b)
{
assert(a);
assert(b);
static bool conn_cache[SAMPLE_SIZE][SAMPLE_SIZE] = {};
struct sir *i;
if (a == b) return;
//list_for_each_entry(i, a->neigh.next, struct sir, list)
// if (i->item == b) return;
if (!conn_cache[a->id-1][b->id-1] || !conn_cache[b->id-1][a->id-1]) {
assert(!conn_cache[a->id-1][b->id-1] && !conn_cache[b->id-1][a->id-1]);
conn_cache[a->id-1][b->id-1] = true;
conn_cache[b->id-1][a->id-1] = true;
} else return;
sir_list_add_item(a, b->tail);
b->tail = b->tail->next;
sir_list_add_item(b, a->tail);
a->tail = a->tail->next;
max_conn++;
}
void node_dump_adjacent_nodes(Node *n)
{
fprintf(stderr, "Node %u: ", n->id);
sir_list_dump(&n->neigh);
}
void node_delete(Node *n)
{
sir_list_del_rec(&n->neigh);
}
| 21.123288 | 73 | 0.626135 |
38062ba43e601feddcd4339deb9938491e2002d2 | 568 | swift | Swift | 2016-03-22-Handoff/HandoffHelper.swift | thiagotmb/BEPiD-Challenges-2016 | 9bddad98417c85eaeaf6469d02ceddeef6ee77f1 | [
"MIT"
] | 1 | 2016-04-13T21:48:03.000Z | 2016-04-13T21:48:03.000Z | 2016-03-22-Handoff/HandoffHelper.swift | thiagotmb/WatchOS-Samples | 9bddad98417c85eaeaf6469d02ceddeef6ee77f1 | [
"MIT"
] | null | null | null | 2016-03-22-Handoff/HandoffHelper.swift | thiagotmb/WatchOS-Samples | 9bddad98417c85eaeaf6469d02ceddeef6ee77f1 | [
"MIT"
] | null | null | null | //
// HandoffHelper.swift
// 2016-03-22-HapticChallenge
//
// Created by Thiago-Bernardes on 3/22/16.
// Copyright © 2016 TB. All rights reserved.
//
import UIKit
struct Handoff {
enum ActivityType : String {
case HapticDetail = "TB.-016-03-22-HapticChallenge.HapticDetail"
case HapticsTable = "TB.-016-03-22-HapticChallenge.HapticsTable"
}
static let ActivityValueKey = "ActivityValue"
static let version = Version(key: "", number: 1)
}
struct Version {
let key: String
let number: Int
}
| 17.75 | 72 | 0.637324 |
6151525fcce8991242b5e39e8c1c51805614debb | 1,472 | css | CSS | styles.css | spradha1/PixelMan | e148224a31478cbfa9fb8bc87854880c59da8b96 | [
"MIT"
] | null | null | null | styles.css | spradha1/PixelMan | e148224a31478cbfa9fb8bc87854880c59da8b96 | [
"MIT"
] | null | null | null | styles.css | spradha1/PixelMan | e148224a31478cbfa9fb8bc87854880c59da8b96 | [
"MIT"
] | null | null | null | body {
text-align: center;
background-color: #fcfafa;
}
header {
font-family: 'Marck Script', cursive;
font-size: 50px;
}
#subhead {
font-family: 'Anton';
font-size: 20px;
margin: 15px auto;
max-width: 650px;
max-height: 60px;
}
#subhead div {
display: inline;
margin: 0 10px;
}
.gameButton {
background-color: gold;
padding: 5px 10px;
}
.gameButton:hover, .endButton:hover{
cursor: pointer;
box-shadow: -3px 3px 5px rgb(38, 38, 38), 2px 3px 5px rgb(38, 38, 38);
}
table,
tr,
td {
border: 0.5px solid white;
}
table {
border-collapse: collapse;
margin: auto;
}
tr {
height: 13px;
}
td {
height: 13px;
width: 13px;
background-color: rgb(84, 160, 247);
}
/* color code */
.player {
background-color: rgb(235, 238, 51);
}
.goal {
background-color: rgb(10, 248, 10) !important;
}
.alive {
background-color: rgb(250, 64, 51) !important;
}
/* dialog box on end of each stage */
#stageEnd {
position: absolute;
text-align: center;
font-family: 'Marck Script', cursive;
font-size: 16px;
top: 40%;
left: 35%;
width: 30%;
height: 20%;
padding: 5px 0;
z-index: 2;
border-radius: 15px;
background-color: rgb(238, 223, 223);
}
.blurred {
filter: blur(3px);
}
.endButton {
font-family: 'Anton';
font-size: 18px;
display: block;
background-color: rgb(223, 190, 5);
margin-top: 15px;
margin-left: auto;
margin-right: auto;
min-height: 50px;
line-height: 50px;
max-width: 30%;
} | 14.868687 | 72 | 0.631793 |
b19c5c037150285d2ac19dab2b447f4a5086f5e4 | 197 | css | CSS | resources/css/app.css | extensionmedia/tealwallet-public | b968294a18d87153d52d7fd5c8a6a78d60b854c2 | [
"MIT"
] | null | null | null | resources/css/app.css | extensionmedia/tealwallet-public | b968294a18d87153d52d7fd5c8a6a78d60b854c2 | [
"MIT"
] | null | null | null | resources/css/app.css | extensionmedia/tealwallet-public | b968294a18d87153d52d7fd5c8a6a78d60b854c2 | [
"MIT"
] | null | null | null | @import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
@import '~@fortawesome/fontawesome-free/css/all.css';
#app{
font-family: 'Roboto', sans-serif;
} | 21.888889 | 53 | 0.725888 |
0a3aada0dd1ed8ab96f890e4f3c5169ccf88914b | 323 | c | C | AnalogComparator/main.c | nkieffer/AVR | 029b035020a1a9d7bfe5f843a5d7af7b705849d1 | [
"Unlicense"
] | null | null | null | AnalogComparator/main.c | nkieffer/AVR | 029b035020a1a9d7bfe5f843a5d7af7b705849d1 | [
"Unlicense"
] | null | null | null | AnalogComparator/main.c | nkieffer/AVR | 029b035020a1a9d7bfe5f843a5d7af7b705849d1 | [
"Unlicense"
] | null | null | null | #include <avr/io.h>
#include <util/delay.h>
#include <stdbool.h>
#include <avr/interrupt.h>
ISR(ANA_COMP_vect){
PORTB ^= _BV(PB4);
}
int main(void){
DDRB |=_BV(PB4);
PORTB = 0;
ACSR |= _BV(ACIS1);// | _BV(ACIS0); //set behavior of
ACSR |= _BV(ACIE);
DIDR0 |= _BV(AIN1D) | _BV(AIN0D);
sei();
while(1){
}
}
| 17.944444 | 55 | 0.597523 |
75ffea1d22321b30218f7adfa15c140da9bd12dc | 2,097 | php | PHP | 13. File System/Filesystem - fopen()l.php | munziru3/Mastering-PHP7 | 65c97c8f7b7916d48117f54467208b672b72cb76 | [
"Unlicense"
] | 60 | 2018-05-10T04:40:54.000Z | 2022-02-12T06:04:26.000Z | 13. File System/Filesystem - fopen()l.php | Rdx11/Mastering-PHP7 | 65c97c8f7b7916d48117f54467208b672b72cb76 | [
"Unlicense"
] | null | null | null | 13. File System/Filesystem - fopen()l.php | Rdx11/Mastering-PHP7 | 65c97c8f7b7916d48117f54467208b672b72cb76 | [
"Unlicense"
] | 47 | 2018-05-16T02:18:54.000Z | 2021-10-04T00:56:05.000Z | <!DOCTYPE html>
<html>
<body>
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
</body>
</html>
Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
PHP Read File - fread()
The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
PHP Close File - fclose()
The fclose() function is used to close an open file.
It's a good programming practice to close all files after you have finished with them. You don't want an open file running around on your server taking up resources!
The fclose() requires the name of the file (or a variable that holds the filename) we want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
| 45.586957 | 165 | 0.75155 |
7fd874a01ca9a73524521fafb5c03ba365046987 | 6,530 | go | Go | server/game/runner.go | jacobpatterson1549/selene-bananas | 6f8213ce8786c796f9272f403204c5869f9aa68b | [
"MIT"
] | 1 | 2021-06-22T12:40:21.000Z | 2021-06-22T12:40:21.000Z | server/game/runner.go | jacobpatterson1549/selene-bananas | 6f8213ce8786c796f9272f403204c5869f9aa68b | [
"MIT"
] | 1 | 2021-03-04T00:48:54.000Z | 2021-03-17T20:08:55.000Z | server/game/runner.go | jacobpatterson1549/selene-bananas | 6f8213ce8786c796f9272f403204c5869f9aa68b | [
"MIT"
] | null | null | null | package game
import (
"context"
"fmt"
"sync"
"github.com/jacobpatterson1549/selene-bananas/game"
"github.com/jacobpatterson1549/selene-bananas/game/message"
"github.com/jacobpatterson1549/selene-bananas/game/player"
"github.com/jacobpatterson1549/selene-bananas/server/log"
)
type (
// Runner runs games.
Runner struct {
// log is used to log errors and other information
log log.Logger
// games maps game ids to the channel each games listens to for incoming messages
// OutChannels are stored here because the Runner writes to the game, which in turn reads from the Runner's channel as an InChannel
games map[game.ID]chan<- message.Message
// lastID is the ID of themost recently created game. The next new game should get a larger ID.
lastID game.ID
// WordValidator is used to validate players' words when they try to finish the game.
WordValidator WordValidator
// UserDao increments user points when a game is finished.
userDao UserDao
// RunnerConfig contains configuration properties of the Runner.
RunnerConfig
}
// RunnerConfig is used to create a game Runner.
RunnerConfig struct {
// Debug is a flag that causes the game to log the types messages that are read.
Debug bool
// The maximum number of games.
MaxGames int
// The config for creating new games.
GameConfig Config
}
// WordValidator checks if words are valid.
WordValidator interface {
Validate(word string) bool
}
// UserDao makes changes to the stored state of users in the game
UserDao interface {
// UpdatePointsIncrement increments points for the specified usernames based on the userPointsIncrementFunc
UpdatePointsIncrement(ctx context.Context, userPoints map[string]int) error
}
)
// NewRunner creates a new game runner from the config.
func (cfg RunnerConfig) NewRunner(log log.Logger, WordValidator WordValidator, userDao UserDao) (*Runner, error) {
if err := cfg.validate(log, WordValidator, userDao); err != nil {
return nil, fmt.Errorf("creating game runner: validation: %w", err)
}
m := Runner{
log: log,
games: make(map[game.ID]chan<- message.Message, cfg.MaxGames),
RunnerConfig: cfg,
WordValidator: WordValidator,
userDao: userDao,
}
return &m, nil
}
// Run consumes messages from the "in" channel, processing them on a new goroutine until the "in" channel closes.
// The results of messages are sent on the "out" channel to be read by the subscriber.
func (r *Runner) Run(ctx context.Context, wg *sync.WaitGroup, in <-chan message.Message) <-chan message.Message {
ctx, cancelFunc := context.WithCancel(ctx)
out := make(chan message.Message)
wg.Add(1)
run := func() {
defer wg.Done()
defer r.log.Printf("game runner stopped")
defer close(out)
defer cancelFunc()
for { // BLOCKING
select {
case <-ctx.Done():
return
case m, ok := <-in:
if !ok {
return
}
r.handleMessage(ctx, wg, m, out)
}
}
}
go run()
return out
}
// validate ensures the configuration has no errors.
func (cfg RunnerConfig) validate(log log.Logger, WordValidator WordValidator, userDao UserDao) error {
switch {
case log == nil:
return fmt.Errorf("log required")
case WordValidator == nil:
return fmt.Errorf("word validator required")
case userDao == nil:
return fmt.Errorf("user dao required")
case cfg.MaxGames < 1:
return fmt.Errorf("must be able to create at least one game")
}
return nil
}
// handleMessage takes appropriate actions for different message types.
func (r *Runner) handleMessage(ctx context.Context, wg *sync.WaitGroup, m message.Message, out chan<- message.Message) {
switch m.Type {
case message.CreateGame:
r.createGame(ctx, wg, m, out)
case message.DeleteGame:
r.deleteGame(ctx, m, out)
default:
r.handleGameMessage(ctx, m, out)
}
}
// createGame allocates a new game, adding it to the open games.
func (r *Runner) createGame(ctx context.Context, wg *sync.WaitGroup, m message.Message, out chan<- message.Message) {
if err := r.validateCreateGame(m); err != nil {
r.sendError(err, m.PlayerName, out)
return
}
id := r.lastID + 1
gameCfg := r.GameConfig
gameCfg.Config = *m.Game.Config
g, err := gameCfg.NewGame(r.log, id, r.WordValidator, r.userDao)
if err != nil {
r.sendError(err, m.PlayerName, out)
return
}
r.lastID = id
gIn := make(chan message.Message)
g.Run(ctx, wg, gIn, out) // all games publish to the same "out" channel
r.games[id] = gIn
m.Type = message.JoinGame
message.Send(m, gIn, r.Debug, r.log)
}
// validateCreateGame returns an err if the runner cannot create a new game or the message to create one is invalid.
func (r *Runner) validateCreateGame(m message.Message) error {
switch {
case len(r.games) >= r.MaxGames:
return fmt.Errorf("the maximum number of games have already been created (%v)", r.MaxGames)
case m.Game == nil, m.Game.Board == nil:
return fmt.Errorf("board config required when creating game")
case m.Game.Config == nil:
return fmt.Errorf("missing config for game properties")
}
return nil
}
// deleteGame removes a game from the runner, notifying the game that it is being deleted so it can notify users.
func (r *Runner) deleteGame(ctx context.Context, m message.Message, out chan<- message.Message) {
gIn, err := r.getGame(m)
if err != nil {
r.sendError(err, m.PlayerName, out)
return
}
delete(r.games, m.Game.ID)
message.Send(m, gIn, r.Debug, r.log)
}
// handleGameMessage passes an error to the game the message is for.
func (r *Runner) handleGameMessage(ctx context.Context, m message.Message, out chan<- message.Message) {
gIn, err := r.getGame(m)
if err != nil {
r.sendError(err, m.PlayerName, out)
return
}
message.Send(m, gIn, r.Debug, r.log)
}
// getGame retrieves the game from the runner for the message, if the runner has a game for the message's game ID.
func (r *Runner) getGame(m message.Message) (chan<- message.Message, error) {
if m.Game == nil {
return nil, fmt.Errorf("no game for runner to handle in message: %v", m)
}
gIn, ok := r.games[m.Game.ID]
if !ok {
return nil, fmt.Errorf("no game ID for runner to handle in message: %v", m)
}
return gIn, nil
}
// sendError adds a message for the player on the channel
func (r *Runner) sendError(err error, pn player.Name, out chan<- message.Message) {
err = fmt.Errorf("player %v: %w", pn, err)
r.log.Printf("game runner error: %v", err)
m := message.Message{
Type: message.SocketError,
Info: err.Error(),
PlayerName: pn,
}
message.Send(m, out, r.Debug, r.log)
}
| 32.326733 | 133 | 0.711026 |
0cee3a5d83fc06ee8d80703cbf5bab61011eb8f9 | 7,039 | py | Python | repiko/module/calculator.py | liggest/RepiKoBot | 5a2aa511e747785ad341c60d809af2a2788963ab | [
"MIT"
] | 1 | 2021-07-29T13:23:58.000Z | 2021-07-29T13:23:58.000Z | repiko/module/calculator.py | liggest/RepiKoBot | 5a2aa511e747785ad341c60d809af2a2788963ab | [
"MIT"
] | null | null | null | repiko/module/calculator.py | liggest/RepiKoBot | 5a2aa511e747785ad341c60d809af2a2788963ab | [
"MIT"
] | null | null | null | import random
class Calculator():
symbol=["+","-","*","/","(",")"]
def __init__(self):
pass
def cal(self,s):
if self.isnumber(s[0]):
return s
elif s[0]=="error":
return ["error",s[1]]
elif "(" in s[0] or ")" in s[0]: #or "^" in s[0]:
el=self.analyze(s)
e=el[0]
log=el[1]
return self.cal([e,log])
else:
e=s[0]
log=s[1]
if "-" in e:
ex=e
for x in range(len(e)):
if e[x]=="-":
if x==0:
ex="–"+ex[1:]
elif e[x-1] in self.symbol:
ex=ex[:x]+"–"+ex[x+1:]
e=ex
if "*" in e or "/" in e:
length=len(e)
lastMark=-1
thisMark=0
nextMark=length
mark="*"
for x in range(length):
if e[x]=="*" or e[x]=="/":
thisMark=x
mark=e[x]
for y in range(thisMark+1,length):
if e[y] in self.symbol:
nextMark=y
break
for y in range(thisMark-1,-1,-1):
if e[y] in self.symbol:
lastMark=y
break
target_l=e[lastMark+1:thisMark].replace("–","-")
target_r=e[thisMark+1:nextMark].replace("–","-")
if not self.isnumber(target_l):
target=self.cal([target_l,log])
target_l=target[0]
log=target[1]
if not self.isnumber(target_r):
target=self.cal([target_r,log])
target_r=target[0]
log=target[1]
if target_r=="error" or target_l=="error":
return ["error",log]
if mark=="*":
result_temp=str(float(target_l)*float(target_r))
elif mark=="/" and target_r!="0":
result_temp=str(float(target_l)/float(target_r))
else:
return ["error",log]
e=e[:lastMark+1]+result_temp+e[nextMark:]
log=log+e+"\n"
break
elif "+" in e or "-" in e:
length=len(e)
lastMark=-1
thisMark=0
nextMark=length
mark="+"
for x in range(length):
if e[x]=="+" or e[x]=="-":
thisMark=x
mark=e[x]
for y in range(thisMark+1,length):
if e[y] in self.symbol:
nextMark=y
break
for y in range(thisMark-1,-1,-1):
if e[y] in self.symbol:
lastMark=y
break
target_l=e[lastMark+1:thisMark].replace("–","-")
target_r=e[thisMark+1:nextMark].replace("–","-")
if not self.isnumber(target_l):
target=self.cal([target_l,log])
target_l=target[0]
log=target[1]
if not self.isnumber(target_r):
target=self.cal([target_r,log])
target_r=target[0]
log=target[1]
if target_r=="error" or target_l=="error":
return ["error",log]
if mark=="+":
result_temp=str(float(target_l)+float(target_r))
elif mark=="-":
result_temp=str(float(target_l)-float(target_r))
else:
return ["error",log]
e=e[:lastMark+1]+result_temp+e[nextMark:]
log=log+e+"\n"
break
else:
return ["error",log]
return self.cal([e,log])
def analyze(self,s):
e=s[0]
log=s[1]
while "(" in e or ")" in e:
bracketL=0
bracketR=0
length=len(e)
for x in range(length-1,-1,-1):
if e[x]=="(":
bracketL=x
bracketR=e[x:].find(")")+x
break
rs=e[bracketL+1:bracketR]
log=log+rs+"\n"
result_temp=self.cal([rs,log])
if result_temp[0]=="error":
return ["error",result_temp[1]]
e=e[:bracketL]+result_temp[0]+e[bracketR+1:]
log=result_temp[1]+e+"\n"
return [e,log]
def isnumber(self,s):
try :
float(s)
return True
except:
return False
def dice(self,s):
e=s
while "d" in e:
length=len(e)
dn=e.find("d")
start=-1
end=length
for x in range(dn+1,length):
if not e[x].isdecimal():
end=x
break
for y in range(dn-1,-1,-1):
if not e[y].isdecimal():
start=y
break
startn=e[start+1:dn]
endn=e[dn+1:end]
if startn=="":
startn=1
else:
startn=abs(int(startn))
if endn=="":
endn=100
else:
endn=abs(int(endn))
if endn!=0 and startn<=100 and startn!=0:
result_temp="("
for z in range(startn):
result_temp+=str(random.randint(1,endn))
if z!=startn-1:
result_temp+="+"
result_temp+=")"
elif endn==0:
return "-丢了个卵子"
elif startn>100:
return "-丢了一群卵子"
elif startn==0:
return "-丢不出卵子,只能丢人了"
e=e[:start+1]+result_temp+e[end:]
return e
def dicetext(self,s,act):
text=self.dice(s)
if text[0:2]=="-丢":
return text[1:]
num=self.cal([text,text+"\n"])
if num[0]!="error":
return "投掷 "+act+" :"+s+" = "+text+" = "+num[0]
else:
return "呜…投个骰子都卡住了……"
#x=Calculator()
#a=input()
#r=x.cal([a,a+"\n"])
#print(r[1][:-1])
#if r[0]=="error":
# print("error")
#print(x.dicetext(a,""))
| 36.661458 | 76 | 0.356016 |
a17403fb100de0c39dec33a7ae5ea32cabe8fb81 | 7,435 | go | Go | golang-gatekeeper/helpers.go | vaibhavshu/examples | 88255dc77d69a4dd68399706e23bdacee950157d | [
"Apache-2.0"
] | 61 | 2018-04-16T23:37:23.000Z | 2022-02-27T18:24:33.000Z | golang-gatekeeper/helpers.go | vaibhavshu/examples | 88255dc77d69a4dd68399706e23bdacee950157d | [
"Apache-2.0"
] | 27 | 2018-06-08T19:46:16.000Z | 2022-01-13T22:39:19.000Z | golang-gatekeeper/helpers.go | vaibhavshu/examples | 88255dc77d69a4dd68399706e23bdacee950157d | [
"Apache-2.0"
] | 85 | 2018-04-16T23:49:26.000Z | 2021-06-12T03:46:17.000Z | package main
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"time"
beeline "github.com/honeycombio/beeline-go"
"github.com/honeycombio/beeline-go/timer"
libhoney "github.com/honeycombio/libhoney-go"
)
// addCommonLibhoneyFields adds a few fields we want in all events
func addCommonLibhoneyFields() {
// TODO what other fields should we add here for extra color?
libhoney.AddDynamicField("meta.num_goroutines",
func() interface{} { return runtime.NumGoroutine() })
getAlloc := func() interface{} {
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
return mem.Alloc
}
libhoney.AddDynamicField("meta.memory_inuse", getAlloc)
startTime := time.Now()
libhoney.AddDynamicField("meta.process_uptime_sec", func() interface{} {
return time.Now().Sub(startTime) / time.Second
})
}
// getHeaders pulls the three available headers out of the HTTP request and type
// asserts them to the right type. It does no additional validation.
func getHeaders(r *http.Request, ev *Event) error {
// add a timer around getting headers
defer func(t timer.Timer) {
dur := t.Finish()
beeline.AddField(r.Context(), "timer.get_headers_dur_ms", dur)
}(timer.Start())
// pull raw values from headers
wk := r.Header.Get(HeaderWriteKey)
beeline.AddField(r.Context(), HeaderWriteKey, wk)
ts := r.Header.Get(HeaderTimestamp)
beeline.AddField(r.Context(), HeaderTimestamp, ts)
sr := r.Header.Get(HeaderSampleRate)
beeline.AddField(r.Context(), HeaderSampleRate, sr)
// assert types
// writekeys are strings, so no assertion needed
ev.WriteKey = wk
// Timestamps should be RFC3339Nano. If we get the zero time that means
// parsing failed. Leave it at zero until we do real time stuff later
evTime, err := time.Parse(time.RFC3339Nano, ts)
if err != nil {
// it's fine if we can't parse the time (maybe it's missing!)
// but we should note that we failed and continue
beeline.AddField(r.Context(), "error_time_parsing", err)
}
ev.Timestamp = evTime
// sample rate should be a positive integer. Defaults to 1 if empty.
if sr == "" {
sr = "1"
}
sampleRate, err := strconv.Atoi(sr)
if err != nil {
return err
}
ev.SampleRate = sampleRate
beeline.AddField(r.Context(), "sample_rate", sampleRate)
return nil
}
// userFacingErr takes an error type and formats an appropriate HTTP response
// for that type of error.
func userFacingErr(ctx context.Context, err error, errType apierr, w http.ResponseWriter) {
beeline.AddField(ctx, "error", err.Error())
beeline.AddField(ctx, "error_desc", responses[errType].responseBody)
// if we got a user-safe error, use that. otherwise use errType
if err, ok := err.(*SafeError); ok {
w.WriteHeader(err.responseCode)
w.Write([]byte(err.responseBody))
return
}
w.WriteHeader(responses[errType].responseCode)
w.Write([]byte(responses[errType].responseBody))
}
func validateWritekey(ctx context.Context, wk string) (*Team, error) {
// add a timer around validation
defer func(t timer.Timer) {
dur := t.Finish()
beeline.AddField(ctx, "timer.validate_writekey_dur_ms", dur)
}(timer.Start())
// writekeys are only [a-zA-Z0-9]
for _, char := range wk {
if !strings.Contains(ValidWriteKeyCharset, string(char)) {
// send a user-safe error here to propagate the difference up
return nil, responses[apierrAuthMishapen]
}
}
// authenticate
// here we would call out to the database to validate the writekey
// but instead in the interests of simplicity
// we're just going to check that it's one of the few valid writekeys
// TODO add an in-memory cache and take a longer time to hit the "database"
for _, team := range knownTeams {
if team.WriteKey == wk {
return team, nil
}
}
return nil, responses[apierrAuthFailure]
}
func resolveDataset(ctx context.Context, datasetName string) (*Dataset, error) {
// add a timer around validation
defer func(t timer.Timer) {
dur := t.Finish()
beeline.AddField(ctx, "timer.resolve_dataset_dur_ms", dur)
}(timer.Start())
// here we would call out to the database to fetch the dataset object
// or create it if one didn't exist
// instead we're just going to take one from a known set of datasets
for _, ds := range knownDatasets {
if ds.Name == datasetName {
return ds, nil
}
}
return nil, errors.New("dataset not found")
}
func unmarshal(r *http.Request, ev *Event) error {
// add a timer around unmarshalling json
defer func(t timer.Timer) {
dur := t.Finish()
beeline.AddField(r.Context(), "timer.unmarshal_json_dur_ms", dur)
}(timer.Start())
// always close the body when done reading
defer r.Body.Close()
// include whether the content was gzipped in the event
var gzipped bool
defer beeline.AddField(r.Context(), "gzipped", gzipped)
// set up a plaintext reader to abstract out the gzipping
var reader io.Reader
switch r.Header.Get("Content-Encoding") {
case "gzip":
gzipped = true
buf := bytes.Buffer{}
var err error
if _, err = io.Copy(&buf, r.Body); err != nil {
return err
}
if reader, err = gzip.NewReader(&buf); err != nil {
return err
}
default:
reader = r.Body
}
body := make(map[string]interface{})
if err := json.NewDecoder(reader).Decode(&body); err != nil {
return err
}
ev.Data = body
return nil
}
// getPartition returns a random partition chosen from the available partition list
func getPartition(ctx context.Context, ds *Dataset) (int, error) {
// add a timer around getting the right partition
defer func(t timer.Timer) {
dur := t.Finish()
beeline.AddField(ctx, "timer.get_partition_dur_ms", dur)
}(timer.Start())
parts := ds.PartitionList
if len(parts) <= 0 {
return 0, errors.New("no partitions found")
}
partIndex := rand.Intn(len(parts))
return parts[partIndex], nil
}
// lastCacheTime lets us simulate having the schema cached in memory, and
// falling through to the database every so often (in this case every 10sec).
// The first call to getSchema will "fall through" (i.e. take 30-50ms longer),
// and the rest of the requests for the following 10 seconds will be fast.
var lastCacheTime time.Time
// getSchema pretends to fetch the schema from a database and cache it
func getSchema(ctx context.Context, dataset *Dataset) error {
// add a timer around getting the schema
defer func(t timer.Timer) {
dur := t.Finish()
beeline.AddField(ctx, "timer.get_schema_dur_ms", dur)
}(timer.Start())
hitCache := true
if time.Since(lastCacheTime) > CacheTimeout {
// we fall through the cache every 10 seconds. In production this might
// be closer to 5 minutes
hitCache = false
// pretend to hit a slow database that takes 30-50ms
time.Sleep(time.Duration((rand.Intn(20) + 30)) * time.Millisecond)
lastCacheTime = time.Now()
}
beeline.AddField(ctx, "hitSchemaCache", hitCache)
// let's just fail sometimes to pretend
if rand.Intn(60) == 0 {
return errors.New("failed to get dataset schema")
}
return nil
}
func writeEvent(ctx context.Context, ev *Event) error {
// TODO should probably add a timer here too, right?
fileNmae := fmt.Sprintf("/tmp/api%d.log", ev.ChosenPartition)
serialized, err := json.Marshal(ev)
if err != nil {
return err
}
fh, err := os.OpenFile(fileNmae, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
defer fh.Close()
fh.Write(serialized)
fh.Write([]byte("\n"))
return err
}
| 29.503968 | 91 | 0.712038 |
dea009a8a774eebaa4d0145172c7c1937334aae7 | 197 | rs | Rust | test_suite/tests/ui/conflict/flatten-skip-deserializing.rs | 0nkery/serde | 18b1604fc8598a1f8adcadb2fc0f832b584be24c | [
"Apache-2.0",
"MIT"
] | 1 | 2021-04-06T05:53:44.000Z | 2021-04-06T05:53:44.000Z | third_party/serde-rs/serde/test_suite/tests/ui/conflict/flatten-skip-deserializing.rs | CodeChain-io/rust-sgx-sdk | 3ee264bbddd04ee6d0f211135f6d6898edca722a | [
"Apache-2.0"
] | null | null | null | third_party/serde-rs/serde/test_suite/tests/ui/conflict/flatten-skip-deserializing.rs | CodeChain-io/rust-sgx-sdk | 3ee264bbddd04ee6d0f211135f6d6898edca722a | [
"Apache-2.0"
] | 5 | 2019-05-23T02:54:44.000Z | 2019-07-03T02:32:52.000Z | use serde_derive::Deserialize;
#[derive(Deserialize)]
struct Foo {
#[serde(flatten, skip_deserializing)]
other: Other,
}
#[derive(Deserialize)]
struct Other {
x: u32,
}
fn main() {}
| 13.133333 | 41 | 0.659898 |
fa82de916adac298052379e4e7e81b6c55191986 | 6,814 | sql | SQL | public/question4/Bookazon.sql | bryan-gilbert/assignments | ff5db009a8c324d73aedf07b6b3938a656f919be | [
"Unlicense"
] | 1 | 2020-07-28T21:48:49.000Z | 2020-07-28T21:48:49.000Z | public/question4/Bookazon.sql | bryan-gilbert/assignments | ff5db009a8c324d73aedf07b6b3938a656f919be | [
"Unlicense"
] | null | null | null | public/question4/Bookazon.sql | bryan-gilbert/assignments | ff5db009a8c324d73aedf07b6b3938a656f919be | [
"Unlicense"
] | null | null | null | -- MySQL Script generated by MySQL Workbench
-- Wed Aug 22 01:55:12 2018
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
-- -----------------------------------------------------
-- Schema bookazon
-- -----------------------------------------------------
-- source Bookazon.sql;
-- -----------------------------------------------------
-- Schema bookazon
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `bookazon` DEFAULT CHARACTER SET utf8 ;
USE `bookazon` ;
-- -----------------------------------------------------
-- Table `bookazon`.`Authors`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bookazon`.`Authors` ;
CREATE TABLE IF NOT EXISTS `bookazon`.`Authors` (
`id` INT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(100) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC) )
ENGINE = InnoDB;
LOAD DATA LOCAL INFILE 'Authors.csv' INTO TABLE Authors FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;
-- -----------------------------------------------------
-- Table `bookazon`.`Books`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bookazon`.`Books` ;
CREATE TABLE IF NOT EXISTS `bookazon`.`Books` (
`id` INT NOT NULL AUTO_INCREMENT,
`title` VARCHAR(200) NOT NULL,
`format` VARCHAR(45) NOT NULL,
`price` DOUBLE NULL default 0.0,
`authorId` INT NULL,
`category` INT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC)
)
ENGINE = InnoDB;
LOAD DATA LOCAL INFILE 'Books.csv' INTO TABLE Books FIELDS TERMINATED BY ',' ENCLOSED BY '"' IGNORE 1 LINES;
-- -----------------------------------------------------
-- Table `bookazon`.`Categories`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bookazon`.`Categories` ;
CREATE TABLE IF NOT EXISTS `bookazon`.`Categories` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`category` VARCHAR(200) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC) )
ENGINE = InnoDB;
LOAD DATA LOCAL INFILE 'Categories.csv' INTO TABLE Categories FIELDS TERMINATED BY ',' ENCLOSED BY '"' IGNORE 1 LINES;
-- -----------------------------------------------------
-- Table `bookazon`.`Customers`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bookazon`.`Customers` ;
CREATE TABLE IF NOT EXISTS `bookazon`.`Customers` (
`id` INT NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(100) NULL,
`City` VARCHAR(45) NULL,
`State` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC) )
ENGINE = InnoDB;
LOAD DATA LOCAL INFILE 'Customers.csv' INTO TABLE Customers FIELDS TERMINATED BY ',' ENCLOSED BY '"' IGNORE 1 LINES;
-- -----------------------------------------------------
-- Table `bookazon`.`LineItem`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bookazon`.`LineItems` ;
CREATE TABLE IF NOT EXISTS `bookazon`.`LineItems` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`bookId` INT NOT NULL,
`quantity` INT NOT NULL,
`cost` DOUBLE NULL DEFAULT 0.0,
`orderId` INT NOT NULL DEFAULT 0.0,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC)
)
ENGINE = InnoDB;
LOAD DATA LOCAL INFILE 'LineItems.csv' INTO TABLE LineItems FIELDS TERMINATED BY ',' ENCLOSED BY '"' IGNORE 1 LINES;
-- -----------------------------------------------------
-- Table `bookazon`.`Orders`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `bookazon`.`Orders` ;
CREATE TABLE IF NOT EXISTS `bookazon`.`Orders` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`date` DATETIME NOT NULL,
`custId` INT NULL,
PRIMARY KEY (`id`), UNIQUE INDEX `id_UNIQUE` (`id` ASC) ) ENGINE = InnoDB;
LOAD DATA LOCAL INFILE 'Orders.csv' INTO TABLE Orders FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES;
-- select * from salesByAuthor;
DROP VIEW IF EXISTS `bookazon`.`salesByAuthor` ;
CREATE VIEW `salesByAuthor` AS
SELECT
authors.Name, SUM(bookSales.totalBookUnits) AS totalAuthorUnits, SUM(bookSales.totalBookSales) AS totalAuthorSales, bookSales.yr
FROM Books bookAuthor
INNER JOIN Authors authors
ON authors.id = bookAuthor.authorId
INNER JOIN (
SELECT
book.id bookId, FORMAT(SUM(cmb.totalUnits), 2) AS totalBookUnits, FORMAT(SUM(cmb.totalSales), 2) AS totalBookSales, yr
FROM Books book
INNER JOIN (
SELECT bookId, yr, SUM(quantity * cost) AS totalSales, SUM(quantity ) AS totalUnits FROM LineItems item
INNER JOIN (
SELECT id, custId, YEAR(STR_TO_DATE(date, '%Y-%m-%d')) AS yr FROM Orders
) AS orders
ON orders.id = item.orderId
GROUP BY bookId, yr
ORDER BY SUM(quantity * cost), SUM(quantity)
) AS cmb
ON cmb.bookId = book.id
GROUP BY book.id, yr
ORDER BY SUM(book.price * cmb.totalUnits) DESC
) AS bookSales
ON bookSales.bookId = bookAuthor.id
GROUP BY bookSales.yr, bookAuthor.authorId
ORDER BY SUM(bookSales.totalBookUnits) DESC
;
-- select * from booksSoldByYear;
DROP VIEW IF EXISTS `bookazon`.`booksSoldByYear` ;
CREATE VIEW `booksSoldByYear` AS
SELECT bookId, yr, SUM(quantity * cost) AS totalSales, SUM(quantity ) AS totalUnits
FROM LineItems items
INNER JOIN (SELECT id, custId, YEAR(STR_TO_DATE(date, '%Y-%m-%d')) AS yr FROM Orders) orders ON orders.id = items.orderId
GROUP BY bookId, yr
ORDER BY SUM(quantity * cost), SUM(quantity)
;
-- select * from booksSold;
DROP VIEW IF EXISTS `bookazon`.`booksSold` ;
CREATE VIEW `booksSold` AS
select title as bookTitle, cat.category, auth.Name as Author, format, b2.yr, b2.totalSales, b2.totalUnits from books AS b1
INNER JOIN ( SELECT c.id, c.category from Categories c) as cat ON b1.category = cat.id
INNER JOIN ( SELECT a.id, a.Name from Authors a ) as auth ON auth.id = b1.authorId
INNER JOIN ( SELECT bookId, yr, totalSales, totalUnits from booksSoldByYear b2 ) as b2 ON b1.id = b2.bookId
;
DROP VIEW IF EXISTS `bookazon`.`customersOrders` ;
CREATE VIEW `customersOrders` AS
select Name, City, State, o.yr, li.bookId, li.quantity, li.cost, li.total FROM Customers AS c
INNER JOIN (SELECT o.id, custId, YEAR(STR_TO_DATE(date, '%Y-%m-%d')) AS yr from Orders as o) as o ON o.custId = c.id
INNER JOIN (SELECT bookId, quantity, cost, (quantity*cost ) total, orderId FROM LineItems li) as li ON li.orderId = o.id
;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
| 39.387283 | 159 | 0.623276 |
9554d36f5e676d537046beb16904e46b67fbc84d | 515 | css | CSS | src/containers/shared-assets/class-selection-wrapper/separator/separator-styles.css | vFujin/HearthLounge | c4c39e26d333c7a858cc0a646a80cd07e56113c5 | [
"Apache-2.0"
] | 28 | 2017-06-05T11:23:13.000Z | 2018-05-28T09:37:22.000Z | src/containers/shared-assets/class-selection-wrapper/separator/separator-styles.css | sbsrnt/HearthLounge | c4c39e26d333c7a858cc0a646a80cd07e56113c5 | [
"BSD-3-Clause"
] | 83 | 2017-05-20T14:29:00.000Z | 2018-05-09T20:59:38.000Z | src/containers/shared-assets/class-selection-wrapper/separator/separator-styles.css | xNehel/clownfiesta-collector-react | c4c39e26d333c7a858cc0a646a80cd07e56113c5 | [
"BSD-3-Clause"
] | 4 | 2017-08-28T14:41:24.000Z | 2018-03-04T13:10:49.000Z | .separator {
display: flex;
align-items: center;
background: #474143;
position: relative; }
.separator:before {
position: absolute;
content: '';
width: 1px;
height: 95%;
top: 2.5%;
left: calc(50% - .5px);
background-color: #A69E9D; }
.separator p {
background: #474143;
color: #A69E9D;
border: 1px solid #A69E9D;
padding: 15px;
position: relative;
text-transform: uppercase;
border-radius: 50%; }
/*# sourceMappingURL=separator-styles.css.map */
| 21.458333 | 48 | 0.617476 |
a18bf6d434cdc2194e1b8b2baa7376f921719b25 | 485 | h | C | Modules/ThirdParty/MINC/src/libminc/libsrc/minc_config.h | Crimson-MITK-ThirdParty/InsightToolkit-4.9.0 | 0b008f85216729cb9397576f690a685284683f4c | [
"Apache-2.0"
] | null | null | null | Modules/ThirdParty/MINC/src/libminc/libsrc/minc_config.h | Crimson-MITK-ThirdParty/InsightToolkit-4.9.0 | 0b008f85216729cb9397576f690a685284683f4c | [
"Apache-2.0"
] | null | null | null | Modules/ThirdParty/MINC/src/libminc/libsrc/minc_config.h | Crimson-MITK-ThirdParty/InsightToolkit-4.9.0 | 0b008f85216729cb9397576f690a685284683f4c | [
"Apache-2.0"
] | null | null | null | #ifndef MINC_CONFIG_H
#define MINC_CONFIG_H
#define MICFG_FORCE_V2 "MINC_FORCE_V2"
#define MICFG_COMPRESS "MINC_COMPRESS"
#define MICFG_CHUNKING "MINC_CHUNKING"
#define MICFG_LOGFILE "MINC_LOGFILE"
#define MICFG_LOGLEVEL "MINC_LOGLEVEL"
#define MICFG_MAXBUF "MINC_MAX_FILE_BUFFER_KB"
#define MICFG_MAXMEM "MINC_MAX_MEMORY_KB"
extern int miget_cfg_bool(const char *);
extern int miget_cfg_int(const char *);
extern char * miget_cfg_str(const char *);
#endif /* MINC_CONFIG_H */
| 28.529412 | 48 | 0.806186 |
596a34612ea13680b96c2fba452cdfed695bbd9f | 6,120 | h | C | Source/Core/Visualization/Renderer/ValueAxis.h | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 42 | 2015-07-24T23:05:07.000Z | 2022-03-16T01:31:04.000Z | Source/Core/Visualization/Renderer/ValueAxis.h | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 4 | 2015-03-17T05:42:49.000Z | 2020-08-09T15:21:45.000Z | Source/Core/Visualization/Renderer/ValueAxis.h | X1aoyueyue/KVS | ad47d62bef4fdd9ddd3412a26ee6557b63f0543b | [
"BSD-3-Clause"
] | 29 | 2015-01-03T05:56:32.000Z | 2021-10-05T15:28:33.000Z | /*****************************************************************************/
/**
* @file ValueAxis.h
* @author Naohisa Sakamoto
*/
/*****************************************************************************/
#pragma once
#include <kvs/Painter>
#include <kvs/Type>
#include <kvs/UIColor>
#include <kvs/Rectangle>
namespace kvs
{
/*===========================================================================*/
/**
* @brief Value axis class.
*/
/*===========================================================================*/
class ValueAxis
{
public:
enum Align
{
Bottom = 0,
Left,
Top,
Right
};
enum TickDirection
{
Inside = -1,
Outside = 1
};
private:
// Axis
bool m_visible; ///< visibility of the axis
Align m_align; ///< axis allign
float m_width; ///< axis width
kvs::RGBColor m_color; ///< axis and tick mark color
// Label
bool m_label_visible; ///< visibility of the label
std::string m_label; ///< axis label
kvs::Font m_label_font; ///< axis label font
int m_label_offset; ///< offset between the axis label and tick label
// Tick mark
bool m_tick_mark_visible; ///< visibility of the tick marks
float m_tick_mark_width; ///< tick mark width
float m_tick_mark_length; ///< tick mark length
// Tick label
bool m_tick_label_visible; ///< visibility of the tick labels
kvs::Font m_tick_label_font; ///< tick label font
int m_tick_label_offset; ///< offset between the tick label and the axis
TickDirection m_tick_direction; ///< tick mark direction
size_t m_nticks; ///< number of ticks
// Region
kvs::Rectangle m_rect; ///< drawing region (x0, x1, y0, y1 )
kvs::Real64 m_min; ///< min value
kvs::Real64 m_max; ///< max value
// Format
int m_precision; ///< decimal precision
bool m_scientific; ///< scientific notation
public:
ValueAxis( Align align = Bottom );
ValueAxis( const ValueAxis& axis );
virtual ~ValueAxis() {}
void setVisible( const bool visible = true ) { m_visible = visible; }
void setAlign( const Align align ) { m_align = align; }
void setAlignToBottom() { this->setAlign( Bottom ); }
void setAlignToLeft() { this->setAlign( Left ); }
void setWidth( const float width ) { m_width = width; }
void setColor( const kvs::RGBColor& color ) { m_color = color; }
void setLabelVisible( const bool visible = true ) { m_label_visible = visible; }
void setLabel( const std::string& label ) { m_label = label; }
void setLabelFont( const kvs::Font& font ) { m_label_font = font; }
void setLabelOffset( const int offset ) { m_label_offset = offset; }
void setTickMarkVisible( const bool visible = true ) { m_tick_mark_visible = visible; }
void setTickMarkWidth( const float width ) { m_tick_mark_width = width; }
void setTickMarkLength( const float length ) { m_tick_mark_length = length; }
void setTickLabelVisible( const bool visible = true ) { m_tick_label_visible = visible; }
void setTickLabelFont( const kvs::Font& font ) { m_tick_label_font = font; }
void setTickLabelOffset( const int offset ) { m_tick_label_offset = offset; }
void setTickDirection( const TickDirection dir ) { m_tick_direction = dir; }
void setTickDirectionToInside() { this->setTickDirection( Inside ); }
void setTickDirectionToOutside() { this->setTickDirection( Outside ); }
void setNumberOfTicks( const size_t nticks ) { m_nticks = nticks; }
void setRect( const kvs::Rectangle& rect ) { m_rect = rect; }
void setMin( const kvs::Real64 min ) { m_min = min; }
void setMax( const kvs::Real64 max ) { m_max = max; }
void setRange( const kvs::Real64 min, const kvs::Real64 max ) { this->setMin( min ); this->setMax( max ); }
void setPrecision( const int p, const bool s = false ) { m_precision = p; m_scientific = s; }
bool isVisible() const { return m_visible; }
Align align() const { return m_align; }
float width() const { return m_width; }
const kvs::RGBColor& color() const { return m_color; }
bool isLabelVisible() const { return m_label_visible; }
const std::string& label() const { return m_label; }
const kvs::Font& labelFont() const { return m_label_font; }
int labelOffset() const { return m_label_offset; }
bool isTickMarkVisible() const { return m_tick_mark_visible; }
float tickMarkWidth() const { return m_tick_mark_width; }
float tickMarkLength() const { return m_tick_mark_length; }
bool isTickLabelVisible() const { return m_tick_label_visible; }
const kvs::Font& tickLabelFont() const { return m_tick_label_font; }
int tickLabelOffset() const { return m_tick_label_offset; }
TickDirection tickDirection() const { return m_tick_direction; }
size_t numberOfTicks() const { return m_nticks; }
const kvs::Rectangle& rect() const { return m_rect; }
kvs::Real64 min() const { return m_min; }
kvs::Real64 max() const { return m_max; }
bool hasRange() const { return !kvs::Math::Equal( m_min, m_max ); }
virtual void draw( kvs::Painter& painter );
protected:
int drawTickLabelsOnTop( kvs::Painter& painter );
int drawTickLabelsOnBottom( kvs::Painter& painter );
int drawTickLabelsOnLeft( kvs::Painter& painter );
int drawTickLabelsOnRight( kvs::Painter& painter );
void drawTickMarksOnTop( kvs::Painter& painter );
void drawTickMarksOnBottom( kvs::Painter& painter );
void drawTickMarksOnLeft( kvs::Painter& painter );
void drawTickMarksOnRight( kvs::Painter& painter );
void drawAxisOnTop( kvs::Painter& painter );
void drawAxisOnBottom( kvs::Painter& painter );
void drawAxisOnLeft( kvs::Painter& painter );
void drawAxisOnRight( kvs::Painter& painter );
void drawLabelOnTop( kvs::Painter& painter, const int margin );
void drawLabelOnBottom( kvs::Painter& painter, const int margin );
void drawLabelOnLeft( kvs::Painter& painter, const int margin );
void drawLabelOnRight( kvs::Painter& painter, const int margin );
};
} // end of namespace kvs
| 40.8 | 111 | 0.641667 |
0b77f76b149075d4d3817aa9211f7115e499a12a | 273 | py | Python | tests/parser/rewriting.projection.4.test.py | veltri/DLV2 | 944aaef803aa75e7ec51d7e0c2b0d964687fdd0e | [
"Apache-2.0"
] | null | null | null | tests/parser/rewriting.projection.4.test.py | veltri/DLV2 | 944aaef803aa75e7ec51d7e0c2b0d964687fdd0e | [
"Apache-2.0"
] | null | null | null | tests/parser/rewriting.projection.4.test.py | veltri/DLV2 | 944aaef803aa75e7ec51d7e0c2b0d964687fdd0e | [
"Apache-2.0"
] | null | null | null | input = """
f(X,1) :- a(X,Y),
g(A,X),g(B,X),
not f(1,X).
a(X,Y) :- g(X,0),g(Y,0).
g(x1,0).
g(x2,0).
"""
output = """
f(X,1) :- a(X,Y),
g(A,X),g(B,X),
not f(1,X).
a(X,Y) :- g(X,0),g(Y,0).
g(x1,0).
g(x2,0).
"""
| 11.869565 | 25 | 0.296703 |
6cc990081ec1ca1f21d70e156a9e6926dde713af | 273 | sql | SQL | darth-vader/05_full_stack_sinatra/sql_examples/twitter_migrations.sql | ga-chicago/ga-chicago.github.io | 986e10405798014b28db94f1fd8421b204b78378 | [
"MIT"
] | null | null | null | darth-vader/05_full_stack_sinatra/sql_examples/twitter_migrations.sql | ga-chicago/ga-chicago.github.io | 986e10405798014b28db94f1fd8421b204b78378 | [
"MIT"
] | null | null | null | darth-vader/05_full_stack_sinatra/sql_examples/twitter_migrations.sql | ga-chicago/ga-chicago.github.io | 986e10405798014b28db94f1fd8421b204b78378 | [
"MIT"
] | null | null | null | #1 create db
CREATE DATABASE twitter;
#2 connect to db
\c twitter
#3 create tables
CREATE TABLE users (id SERIAL PRIMARY KEY, name varchar(255), password varchar(255), email varchar(255));
CREATE TABLE tweets(id SERIAL PRIMARY KEY, user_id integer, tweet varchar(140));
| 24.818182 | 105 | 0.761905 |
4a5bfd566f01020a6c28690cd9b9d299b8b9e9e6 | 627 | js | JavaScript | modules/compareUrls.js | robertrahardja/webscraper | 68eda069768c117eef08b7c14f0567433d101850 | [
"MIT"
] | null | null | null | modules/compareUrls.js | robertrahardja/webscraper | 68eda069768c117eef08b7c14f0567433d101850 | [
"MIT"
] | null | null | null | modules/compareUrls.js | robertrahardja/webscraper | 68eda069768c117eef08b7c14f0567433d101850 | [
"MIT"
] | null | null | null | const arrPop = require('./arrayPop.js')
const getPage = require('./get$.js')
const setArrayEquals = require('./setArrayEquals.js')
module.exports = async function compareUrls(url, url2) {
// info from first website
let firstArray = []
$ = await getPage(url).catch(err => console.error(`compareUrls: Error on getting first array url ${err}`))
arrPop($, firstArray)
// info from second website
let secondArray = []
$ = await getPage(url2).catch(err => console.error(`compareUrls: Error on getting second array url ${err}`))
arrPop($, secondArray)
setArrayEquals()
return firstArray.equals(secondArray)
}
| 29.857143 | 110 | 0.701754 |
126c6c7695a268e880abba932f60f2d1aacbaaa5 | 319 | h | C | UI/JKStockTableWidget.h | kenylerich/StockTool | 04da77d9be6633a66bef2d4f15c2b23f9ef522da | [
"Apache-2.0"
] | 3 | 2018-09-25T04:06:17.000Z | 2020-10-07T08:49:29.000Z | UI/JKStockTableWidget.h | kenylerich/StockTool | 04da77d9be6633a66bef2d4f15c2b23f9ef522da | [
"Apache-2.0"
] | null | null | null | UI/JKStockTableWidget.h | kenylerich/StockTool | 04da77d9be6633a66bef2d4f15c2b23f9ef522da | [
"Apache-2.0"
] | 1 | 2020-12-29T00:27:09.000Z | 2020-12-29T00:27:09.000Z | #pragma once
#include "JKVirtualTreeAdapter.h"
#include "JKTreeModelCustomItem.h"
#include "BLL/JKStockCodeTradeBLL.h"
#include "BLL/JKStockTradeUtil.h"
class StockBuyTableItem
: public JKTreeModelCustomItem<StockCodeTradeBLLPtr>
{
public:
StockBuyTableItem(StockCodeTradeBLLPtr data);
~StockBuyTableItem();
};
| 18.764706 | 53 | 0.805643 |
bb6af419b4cf285cffc88c1862db7c09d8809913 | 310 | rs | Rust | src/system/routes/index.rs | XNBlank/rusticity | 8cbd38f0724efc52ea53808bd2602a34b0c7975e | [
"MIT"
] | 1 | 2021-02-23T12:45:42.000Z | 2021-02-23T12:45:42.000Z | src/system/routes/index.rs | XNBlank/rusticity | 8cbd38f0724efc52ea53808bd2602a34b0c7975e | [
"MIT"
] | null | null | null | src/system/routes/index.rs | XNBlank/rusticity | 8cbd38f0724efc52ea53808bd2602a34b0c7975e | [
"MIT"
] | null | null | null | use actix_web::{web, get, post, put, delete, HttpResponse, Responder};
use sqlx::MySqlPool;
#[get("/")]
async fn index(db_pool: web::Data<MySqlPool>) -> impl Responder {
let result = "Hello World";
let response: HttpResponse = HttpResponse::Ok().content_type("text/html").body(result);
response
} | 31 | 91 | 0.687097 |
d4c256b0188c235a3e19a2077445fb261d413df0 | 1,819 | kt | Kotlin | app/src/main/java/info/moevm/se/weatheradvisor/ui/adapter/LocationAdapter.kt | moevm/adfmp19-weather-advisor | 1d2d3706163f0974c323a8a7c9d8af30ddf25e6f | [
"MIT"
] | null | null | null | app/src/main/java/info/moevm/se/weatheradvisor/ui/adapter/LocationAdapter.kt | moevm/adfmp19-weather-advisor | 1d2d3706163f0974c323a8a7c9d8af30ddf25e6f | [
"MIT"
] | null | null | null | app/src/main/java/info/moevm/se/weatheradvisor/ui/adapter/LocationAdapter.kt | moevm/adfmp19-weather-advisor | 1d2d3706163f0974c323a8a7c9d8af30ddf25e6f | [
"MIT"
] | 1 | 2019-02-17T23:20:44.000Z | 2019-02-17T23:20:44.000Z | package info.moevm.se.weatheradvisor.ui.adapter
import android.annotation.SuppressLint
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import info.moevm.se.domain.entities.Location
import info.moevm.se.ext.inflate
import info.moevm.se.weatheradvisor.R
import info.moevm.se.weatheradvisor.locationscreen.LocationActivity
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class LocationAdapter(val activity: LocationActivity) : RecyclerView.Adapter<LocationAdapter.LocationHolder>() {
var locations: List<Location> = listOf()
@SuppressLint("CheckResult")
fun fetchLocations(dataStream: Observable<List<Location>>) {
dataStream
.observeOn(Schedulers.io())
.flatMapIterable { it }
.toList()
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
list -> locations = list
notifyDataSetChanged()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
LocationHolder(parent.context.inflate(R.layout.location_city_item, parent))
override fun getItemCount() = locations.size
override fun onBindViewHolder(holder: LocationHolder, position: Int) = holder.bind(position)
inner class LocationHolder(val view: View) : RecyclerView.ViewHolder(view) {
fun bind(position: Int) {
view.findViewById<TextView>(R.id.location_city_item).apply {
text = locations[position].name
setOnClickListener {
activity.citySelected(locations[position])
}
}
}
}
} | 35.666667 | 112 | 0.694887 |
aa0f2b4b610691e2b60c7d028cff936bf3f46255 | 884 | asm | Assembly | boot/disk.asm | a-quelle/OSproject | 8afaaf87eef9a13fbca7819b751f8d4a7c13099f | [
"MIT"
] | null | null | null | boot/disk.asm | a-quelle/OSproject | 8afaaf87eef9a13fbca7819b751f8d4a7c13099f | [
"MIT"
] | null | null | null | boot/disk.asm | a-quelle/OSproject | 8afaaf87eef9a13fbca7819b751f8d4a7c13099f | [
"MIT"
] | null | null | null | ;params: bx is read buffer address
; dl is drive number to read from
; dh is number of sectors to read
;reads dh sectors, starting at sector 2 of cylinder 0 of drive dl
disk_load:
push ax
push bx
push cx
push dx
mov ah, 0x02 ;disk read with int 0x13
mov al, dh ;al is number of sectors to read
mov cl, 0x02 ;cl is start sector
mov ch, 0x00 ;ch is cylinder to read
mov dh, 0x00 ;dh is head number to use
int 0x13
jc disk_error
pop dx
cmp al, dh ;al contains number of sector read
jne sectors_error
pop cx
pop bx
pop ax
ret
disk_error:
mov bx, DISK_ERROR
call print
call print_nl
mov dh, ah ;ah contains error code
call print_hex ;will print error code and drive number
jmp disk_loop
sectors_error:
mov bx, SECTORS_ERROR
call print
disk_loop:
jmp $
DISK_ERROR: db "Disk read error", 0
SECTORS_ERROR: db "Incorrect number of sectors read", 0 | 20.55814 | 65 | 0.728507 |
0ba7c2583722cded680577d9143e475dac69688c | 2,258 | js | JavaScript | src/controllers/userController.js | AntonioCopete/node-develop-your-mvc-project | 680a52b22062f4e5c93e1549604a234dc19a1682 | [
"MIT"
] | 2 | 2021-12-22T16:43:08.000Z | 2021-12-26T11:31:21.000Z | src/controllers/userController.js | AntonioCopete/mern-back | e0f83eeba752095aad05c379ff68454e10283c5a | [
"MIT"
] | null | null | null | src/controllers/userController.js | AntonioCopete/mern-back | e0f83eeba752095aad05c379ff68454e10283c5a | [
"MIT"
] | null | null | null | const { errorMiddleware } = require('../middleware');
const db = require('../models');
async function login(req, res, next) {
const { uid, email } = req.user;
try {
const User = await db.User.findOne({ email: email }).select().lean().exec();
console.log(User);
if (User) {
res.status(200).send({
message: 'Logged successfully',
user: User,
});
}
} catch (err) {
next(err);
}
}
async function createUser(req, res, next) {
console.log(req.body);
const { email, password, fullName, userLink } = req.body;
try {
const user = await db.User.create({
fullName: fullName,
email: email,
password: password,
userLink: userLink,
});
res.status(201).send({
message: 'User created succeessfully',
data: user,
});
} catch (err) {
console.log('hello kitty');
next(err);
}
}
async function getUsers(req, res, next) {
try {
const users = await db.User.find().lean().exec();
res.status(200).send({
data: users,
});
} catch (err) {
next(err);
}
}
async function updateUser(req, res, next) {
const { userId } = req.params;
try {
const updateUser = await db.User.findByIdAndUpdate(userId, req.body, {
new: true,
});
res.status(200).send({
message: 'User updated successfully',
data: updateUser,
});
} catch (err) {
next(err);
}
}
async function deleteUser(req, res, next) {
const { userId } = req.params;
try {
const deleteUser = await db.User.deleteOne({ _id: userId });
if (deleteUser.deletedCount === 1) {
res.status(200).send({
message: 'User successfully deleted',
});
} else {
res.status(500).send({
message: 'User not removed',
});
}
} catch (err) {
next(err);
}
}
async function getSingleUser(req, res, next) {
try {
const { userId } = req.params;
const user = await db.User.findById({ _id: userId }).lean().exec();
res.status(200).send({
data: user,
});
} catch (err) {
next(err);
}
}
module.exports = {
createUser: createUser,
login: login,
getUsers: getUsers,
updateUser: updateUser,
deleteUser: deleteUser,
getSingleUser: getSingleUser,
};
| 20.160714 | 80 | 0.578831 |
417406a956c9b611f55d9da1cf3783f180090167 | 217 | h | C | SDK/AviUtl/edit_filter.h | totoki-kei/MyAviutlFilter | 6fcb6279319e933580a8a17aca6e6aabd1324055 | [
"MIT"
] | null | null | null | SDK/AviUtl/edit_filter.h | totoki-kei/MyAviutlFilter | 6fcb6279319e933580a8a17aca6e6aabd1324055 | [
"MIT"
] | null | null | null | SDK/AviUtl/edit_filter.h | totoki-kei/MyAviutlFilter | 6fcb6279319e933580a8a17aca6e6aabd1324055 | [
"MIT"
] | null | null | null | #define MID_EDIT_VIDEO_COPY 100
#define MID_EDIT_AUDIO_COPY 101
#define MID_EDIT_COPY 102
#define MID_EDIT_PASTE 103
#define MID_EDIT_DELETE 104
#define MID_EDIT_INSERT 105
#define MID_EDIT_FILE_INFO 106
| 21.7 | 32 | 0.81106 |
9e91e5850183a57e2b4340318a1c62552b62110c | 598 | asm | Assembly | oeis/003/A003261.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/003/A003261.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/003/A003261.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A003261: Woodall (or Riesel) numbers: n*2^n - 1.
; 1,7,23,63,159,383,895,2047,4607,10239,22527,49151,106495,229375,491519,1048575,2228223,4718591,9961471,20971519,44040191,92274687,192937983,402653183,838860799,1744830463,3623878655,7516192767,15569256447,32212254719,66571993087,137438953471,283467841535,584115552255,1202590842879,2473901162495,5085241278463,10445360463871,21440476741631,43980465111039,90159953477631,184717953466367,378231999954943,774056185954303,1583296743997439,3236962232172543,6614661952700415,13510798882111487
add $0,1
mov $1,2
pow $1,$0
mul $1,$0
sub $1,1
mov $0,$1
| 59.8 | 488 | 0.839465 |
0ad2a13bdbcf121ef1a736fdac3c09a1f15a1613 | 1,715 | kt | Kotlin | src/commonTest/kotlin/examples/qep/samples.kt | GameModsBR/quick-expression-parser | 91c286ad40e9ca345846a0f575edda5fcd3af40e | [
"Apache-2.0"
] | null | null | null | src/commonTest/kotlin/examples/qep/samples.kt | GameModsBR/quick-expression-parser | 91c286ad40e9ca345846a0f575edda5fcd3af40e | [
"Apache-2.0"
] | null | null | null | src/commonTest/kotlin/examples/qep/samples.kt | GameModsBR/quick-expression-parser | 91c286ad40e9ca345846a0f575edda5fcd3af40e | [
"Apache-2.0"
] | null | null | null | @file:Suppress("UndocumentedPublicClass", "unused")
package examples.qep
import br.com.gamemods.qep.ParameterProvider
import br.com.gamemods.qep.parseExpression
private fun parseExpressionMapSample()
= "Hello #{user.name}, today is #dayOfWeek. Will you go #{user.isAdult? 'work' : 'to school'} today?"
.parseExpression(mapOf(
"dayOfWeek" to "monday",
"user" to mapOf(
"name" to "Michael",
"isAdult" to true
)
))
private fun parseExpressionVarargSample()
= "Hello #{user.name}, today is #dayOfWeek. Will you go #{user.isAdult? 'work' : 'to school'} today?"
.parseExpression(
"dayOfWeek" to "monday",
"user" to mapOf(
"name" to "Michael",
"isAdult" to true
)
)
private fun parseExpressionParamProviderSample(): String {
data class UserBean(val name: String, val age: Int): ParameterProvider {
override fun getParameter(identifier: String): Any? = when (identifier) {
"name" -> name
"isAdult" -> age >= 18
else -> null
}
}
data class ExampleBean(val dayOfWeek: String, val user: UserBean): ParameterProvider {
override fun getParameter(identifier: String): Any? = when (identifier) {
"dayOfWeek" -> dayOfWeek
"user" -> user
else -> null
}
}
val bean = ExampleBean("monday", UserBean("Michael", 12))
return "Hello #{user.name}, today is #dayOfWeek. Will you go #{user.isAdult? 'work' : 'to school'} today?"
.parseExpression(bean)
}
| 35 | 110 | 0.561516 |
2a02c560298b28e3615935fc514fccffd58fa8f5 | 4,198 | java | Java | dap4/d4core/src/main/java/dap4/core/util/DapDump.java | joansmith3/thredds | ac321ce2a15f020f0cdef1ff9a2cf82261d8297c | [
"NetCDF"
] | 1 | 2018-04-24T13:53:46.000Z | 2018-04-24T13:53:46.000Z | dap4/d4core/src/main/java/dap4/core/util/DapDump.java | joansmith3/thredds | ac321ce2a15f020f0cdef1ff9a2cf82261d8297c | [
"NetCDF"
] | 16 | 2016-04-11T06:42:41.000Z | 2019-05-03T04:04:50.000Z | dap4/d4core/src/main/java/dap4/core/util/DapDump.java | joansmith3/thredds | ac321ce2a15f020f0cdef1ff9a2cf82261d8297c | [
"NetCDF"
] | 1 | 2019-07-22T19:57:26.000Z | 2019-07-22T19:57:26.000Z | /* Copyright 2012, UCAR/Unidata.
See the LICENSE file for more information.
*/
package dap4.core.util;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
abstract public class DapDump
{
//////////////////////////////////////////////////
// Provide a simple dump of binary data
// (Static method)
//////////////////////////////////////////////////
// Constants
static int MAXLIMIT = 20000;
//////////////////////////////////////////////////
// Provide a simple dump of binary data
static public void
dumpbytes(ByteBuffer buf0, boolean skipdmr)
{
int savepos = buf0.position();
int limit0 = buf0.limit();
int skipcount = 0;
if(limit0 > MAXLIMIT) limit0 = MAXLIMIT;
if(limit0 >= buf0.limit()) limit0 = buf0.limit();
if(skipdmr) {
skipcount = buf0.getInt(); //dmr count
skipcount &= 0xFFFFFF; // mask off the flags to get true count
skipcount += 4; // skip the count also
}
byte[] bytes = new byte[(limit0 + 8) - skipcount];
Arrays.fill(bytes, (byte) 0);
buf0.position(savepos + skipcount);
buf0.get(bytes, 0, limit0 - skipcount);
buf0.position(savepos);
ByteBuffer buf = ByteBuffer.wrap(bytes).order(buf0.order());
dumpbytes(buf);
}
/**
* Dump the contents of a buffer from 0 to position
*
* @param buf0 byte buffer to dump
*/
static public void
dumpbytes(ByteBuffer buf0)
{
int stop = buf0.limit();
int size = stop + 8;
ByteBuffer buf = ByteBuffer.allocate(size).order(buf0.order());
Arrays.fill(buf.array(), (byte) 0);
buf.put(buf0.array());
buf.position(0);
buf.limit(size);
int i = 0;
try {
for(i = 0; buf.position() < stop; i++) {
int savepos = buf.position();
int iv = buf.getInt();
buf.position(savepos);
long lv = buf.getLong();
buf.position(savepos);
short sv = buf.getShort();
buf.position(savepos);
byte b = buf.get();
long uiv = ((long) iv) & 0xFFFFFFFFL;
int usv = ((int) sv) & 0xFFFF;
int ib = (int) b;
int ub = (iv & 0xFF);
char c = (char) ub;
String s = Character.toString(c);
if(c == '\r') s = "\\r";
else if(c == '\n') s = "\\n";
else if(c < ' ') s = "?";
System.err.printf("[%03d] %02x %03d %4d '%s'", i, ub, ub, ib, s);
System.err.printf("\t%12d 0x%08x", iv, uiv);
System.err.printf("\t%5d\t0x%04x", sv, usv);
System.err.println();
System.err.flush();
}
} catch (Exception e) {
System.err.println("failure:" + e);
} finally {
System.err.flush();
//new Exception().printStackTrace(System.err);
System.err.flush();
}
}
static public void
dumpbytestream(OutputStream stream, ByteOrder order, String tag)
{
if(stream instanceof ByteArrayOutputStream) {
byte[] content = ((ByteArrayOutputStream) stream).toByteArray();
dumpbytestream(content, order, tag);
}
}
static public void
dumpbytestream(ByteBuffer buf, ByteOrder order, String tag)
{
dumpbytestream(buf.array(),0,buf.position(),order,tag);
}
static public void
dumpbytestream(byte[] content, ByteOrder order, String tag)
{
dumpbytestream(content,0,content.length,order,tag);
}
static public void
dumpbytestream(byte[] content, int start, int len, ByteOrder order, String tag)
{
System.err.println("++++++++++ " + tag + " ++++++++++ ");
ByteBuffer tmp = ByteBuffer.wrap(content).order(order);
tmp.position(start);
tmp.limit(len);
DapDump.dumpbytes(tmp);
System.err.println("++++++++++ " + tag + " ++++++++++ ");
System.err.flush();
}
}
| 31.328358 | 83 | 0.50667 |
2d096305889cff6cd77862bc4d963d9abcf76151 | 4,229 | rs | Rust | src/models/mapping_users_lookup_mapping_item_user.rs | cholcombe973/isilon | 928234ce6928a47e061c8afac4e4e589d3b22ea9 | [
"MIT"
] | 1 | 2018-11-26T17:37:36.000Z | 2018-11-26T17:37:36.000Z | src/models/mapping_users_lookup_mapping_item_user.rs | cholcombe973/isilon | 928234ce6928a47e061c8afac4e4e589d3b22ea9 | [
"MIT"
] | null | null | null | src/models/mapping_users_lookup_mapping_item_user.rs | cholcombe973/isilon | 928234ce6928a47e061c8afac4e4e589d3b22ea9 | [
"MIT"
] | null | null | null | #[allow(unused_imports)]
use serde_json::Value;
#[derive(Debug, Serialize, Deserialize)]
pub struct MappingUsersLookupMappingItemUser {
#[serde(rename = "dn")]
pub dn: Option<String>,
#[serde(rename = "dns_domain")]
pub dns_domain: Option<String>,
#[serde(rename = "domain")]
pub domain: Option<String>,
#[serde(rename = "email")]
pub email: Option<String>,
/// True, if the authenticated user is enabled.
#[serde(rename = "enabled")]
pub enabled: bool,
/// True, if the authenticated user has expired.
#[serde(rename = "expired")]
pub expired: bool,
#[serde(rename = "expiry")]
pub expiry: Option<i32>,
#[serde(rename = "gecos")]
pub gecos: Option<String>,
/// True, if the GID was generated.
#[serde(rename = "generated_gid")]
pub generated_gid: Option<bool>,
/// True, if the UID was generated.
#[serde(rename = "generated_uid")]
pub generated_uid: Option<bool>,
/// True, if the UPN was generated.
#[serde(rename = "generated_upn")]
pub generated_upn: Option<bool>,
/// Specifies properties for a persona, which consists of either a 'type' and a 'name' or an 'ID'.
#[serde(rename = "gid")]
pub gid: Option <crate::models::AuthAccessAccessItemFileGroup>,
#[serde(rename = "home_directory")]
pub home_directory: Option<String>,
/// Specifies the user or group ID.
#[serde(rename = "id")]
pub id: String,
/// If true, indicates that the account is locked.
#[serde(rename = "locked")]
pub locked: bool,
/// Specifies the maximum time in seconds allowed before the password expires.
#[serde(rename = "max_password_age")]
pub max_password_age: Option<i32>,
#[serde(rename = "member_of")]
pub member_of: Option<Vec <crate::models::AuthAccessAccessItemFileGroup>>,
/// Specifies a user or group name.
#[serde(rename = "name")]
pub name: String,
#[serde(rename = "object_history")]
pub object_history: Option<Vec <crate::models::AuthGroupObjectHistoryItem>>,
/// Specifies properties for a persona, which consists of either a 'type' and a 'name' or an 'ID'.
#[serde(rename = "on_disk_group_identity")]
pub on_disk_group_identity: Option <crate::models::AuthAccessAccessItemFileGroup>,
/// Specifies properties for a persona, which consists of either a 'type' and a 'name' or an 'ID'.
#[serde(rename = "on_disk_user_identity")]
pub on_disk_user_identity: Option <crate::models::AuthAccessAccessItemFileGroup>,
/// If true, the password has expired.
#[serde(rename = "password_expired")]
pub password_expired: bool,
/// If true, the password is allowed to expire.
#[serde(rename = "password_expires")]
pub password_expires: bool,
#[serde(rename = "password_expiry")]
pub password_expiry: Option<i32>,
#[serde(rename = "password_last_set")]
pub password_last_set: Option<i32>,
/// Specifies properties for a persona, which consists of either a 'type' and a 'name' or an 'ID'.
#[serde(rename = "primary_group_sid")]
pub primary_group_sid: Option <crate::models::AuthAccessAccessItemFileGroup>,
/// Prompts the user to change their password at the next login.
#[serde(rename = "prompt_password_change")]
pub prompt_password_change: bool,
#[serde(rename = "provider")]
pub provider: Option<String>,
#[serde(rename = "sam_account_name")]
pub sam_account_name: Option<String>,
#[serde(rename = "shell")]
pub shell: Option<String>,
/// Specifies properties for a persona, which consists of either a 'type' and a 'name' or an 'ID'.
#[serde(rename = "sid")]
pub sid: Option <crate::models::AuthAccessAccessItemFileGroup>,
/// Specifies the object type.
#[serde(rename = "type")]
pub _type: String,
/// Specifies properties for a persona, which consists of either a 'type' and a 'name' or an 'ID'.
#[serde(rename = "uid")]
pub uid: Option <crate::models::AuthAccessAccessItemFileGroup>,
#[serde(rename = "upn")]
pub upn: Option<String>,
/// Specifies whether the password for the user can be changed.
#[serde(rename = "user_can_change_password")]
pub user_can_change_password: bool,
}
| 43.597938 | 102 | 0.669662 |
50f419b4c75613cb0456330a78a759e2e79dea4d | 653 | go | Go | simulation/pkg/protos/inventory/actual.Helpers.go | Jim3Things/CloudChamber | 2d261aade139c21a8628978fe45af00c565c1e68 | [
"Apache-2.0"
] | 2 | 2019-11-10T11:14:18.000Z | 2022-02-18T22:26:11.000Z | simulation/pkg/protos/inventory/actual.Helpers.go | Jim3Things/CloudChamber | 2d261aade139c21a8628978fe45af00c565c1e68 | [
"Apache-2.0"
] | 107 | 2020-02-29T02:52:45.000Z | 2022-03-20T18:16:51.000Z | simulation/pkg/protos/inventory/actual.Helpers.go | Jim3Things/CloudChamber | 2d261aade139c21a8628978fe45af00c565c1e68 | [
"Apache-2.0"
] | 1 | 2019-11-10T11:12:37.000Z | 2019-11-10T11:12:37.000Z | // Assorted utility routines for types from the various protobuf definitions
package inventory
import (
"fmt"
)
func (x *Actual_Pdu) Describe() string {
cables := ""
join := ""
for i, cable := range x.Cables {
cables = fmt.Sprintf("%s%s%d: %s", cables, join, i, cable)
join = "; "
}
return fmt.Sprintf("PDU: %v, %v, %v, [%s]", x.Condition, x.SmState, x.Core, cables)
}
func (x *Actual_Tor) Describe() string {
cables := ""
join := ""
for i, cable := range x.Cables {
cables = fmt.Sprintf("%s%s%d: %s", cables, join, i, cable)
join = "; "
}
return fmt.Sprintf("TOR: %v, %v, %v, [%s]", x.Condition, x.SmState, x.Core, cables)
}
| 20.40625 | 84 | 0.601838 |
c4a3ca7ec69bb7a73dfa5c08e66290c17e3c4bf7 | 23,009 | c | C | src/modesel.c | msikma/allegrotest | 12ba94213768b7653eb1d667a0cbea02e04f62fe | [
"OLDAP-2.4"
] | 29 | 2016-08-18T18:03:55.000Z | 2022-01-13T15:55:42.000Z | src/modesel.c | msikma/allegrotest | 12ba94213768b7653eb1d667a0cbea02e04f62fe | [
"OLDAP-2.4"
] | 2 | 2021-09-15T19:45:50.000Z | 2021-09-16T12:39:48.000Z | src/modesel.c | msikma/allegrotest | 12ba94213768b7653eb1d667a0cbea02e04f62fe | [
"OLDAP-2.4"
] | 8 | 2017-08-16T06:49:27.000Z | 2022-01-15T04:44:32.000Z | /* ______ ___ ___
* /\ _ \ /\_ \ /\_ \
* \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___
* \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\
* \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \
* \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/
* \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/
* /\____/
* \_/__/
*
* GUI routines.
*
* The graphics mode selection dialog.
*
* By Shawn Hargreaves.
*
* Rewritten by Henrik Stokseth.
*
* Magnus Henoch modified it to keep the current selection
* across the changes as much as possible.
*
* gfx_mode_select_filter() added by Vincent Penquerc'h.
*
* See readme.txt for copyright information.
*/
#include <string.h>
#include <stdio.h>
#include "allegro.h"
#include "allegro/internal/aintern.h"
static AL_CONST char *gfx_mode_getter(int index, int *list_size);
static AL_CONST char *gfx_card_getter(int index, int *list_size);
static AL_CONST char *gfx_depth_getter(int index, int *list_size);
static int change_proc(int msg, DIALOG *d, int c);
#define ALL_BPP(w, h) { w, h, { TRUE, TRUE, TRUE, TRUE, TRUE }}
#define N_COLOR_DEPTH 5
static int bpp_value_list[N_COLOR_DEPTH] = {8, 15, 16, 24, 32};
typedef struct MODE_LIST {
int w, h;
char has_bpp[N_COLOR_DEPTH];
} MODE_LIST;
#define DRVNAME_SIZE 128
typedef struct DRIVER_LIST {
int id;
char name[DRVNAME_SIZE];
void *fetch_mode_list_ptr;
MODE_LIST *mode_list;
int mode_count;
} DRIVER_LIST;
static MODE_LIST default_mode_list[] =
{
ALL_BPP(320, 200 ),
ALL_BPP(320, 240 ),
ALL_BPP(640, 400 ),
ALL_BPP(640, 480 ),
ALL_BPP(800, 600 ),
ALL_BPP(1024, 768 ),
ALL_BPP(1280, 960 ),
ALL_BPP(1280, 1024),
ALL_BPP(1600, 1200),
ALL_BPP(80, 80 ),
ALL_BPP(160, 120 ),
ALL_BPP(256, 200 ),
ALL_BPP(256, 224 ),
ALL_BPP(256, 240 ),
ALL_BPP(256, 256 ),
ALL_BPP(320, 100 ),
ALL_BPP(320, 350 ),
ALL_BPP(320, 400 ),
ALL_BPP(320, 480 ),
ALL_BPP(320, 600 ),
ALL_BPP(360, 200 ),
ALL_BPP(360, 240 ),
ALL_BPP(360, 270 ),
ALL_BPP(360, 360 ),
ALL_BPP(360, 400 ),
ALL_BPP(360, 480 ),
ALL_BPP(360, 600 ),
ALL_BPP(376, 282 ),
ALL_BPP(376, 308 ),
ALL_BPP(376, 564 ),
ALL_BPP(400, 150 ),
ALL_BPP(400, 300 ),
ALL_BPP(400, 600 ),
ALL_BPP(0, 0 )
};
typedef int (*FILTER_FUNCTION)(int, int, int, int);
static DRIVER_LIST *driver_list;
static int driver_count;
static char mode_string[64];
static DIALOG *what_dialog;
static DIALOG gfx_mode_dialog[] =
{
/* (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) (dp2) (dp3) */
{ _gui_shadow_box_proc, 0, 0, 313, 159, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL },
{ change_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ _gui_ctext_proc, 156, 8, 1, 1, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL },
{ _gui_button_proc, 196, 105, 101, 17, 0, 0, 0, D_EXIT, 0, 0, NULL, NULL, NULL },
{ _gui_button_proc, 196, 127, 101, 17, 0, 0, 27, D_EXIT, 0, 0, NULL, NULL, NULL },
{ _gui_list_proc, 16, 28, 165, 116, 0, 0, 0, D_EXIT, 0, 0, (void*)gfx_card_getter, NULL, NULL },
{ _gui_list_proc, 196, 28, 101, 68, 0, 0, 0, D_EXIT, 3, 0, (void*)gfx_mode_getter, NULL, NULL },
{ d_yield_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL },
{ NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }
};
static DIALOG gfx_mode_ex_dialog[] =
{
/* (dialog proc) (x) (y) (w) (h) (fg) (bg) (key) (flags) (d1) (d2) (dp) (dp2) (dp3) */
{ _gui_shadow_box_proc, 0, 0, 313, 159, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL },
{ change_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ _gui_ctext_proc, 156, 8, 1, 1, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL },
{ _gui_button_proc, 196, 105, 101, 17, 0, 0, 0, D_EXIT, 0, 0, NULL, NULL, NULL },
{ _gui_button_proc, 196, 127, 101, 17, 0, 0, 27, D_EXIT, 0, 0, NULL, NULL, NULL },
{ _gui_list_proc, 16, 28, 165, 68, 0, 0, 0, D_EXIT, 0, 0, (void*)gfx_card_getter, NULL, NULL },
{ _gui_list_proc, 196, 28, 101, 68, 0, 0, 0, D_EXIT, 3, 0, (void*)gfx_mode_getter, NULL, NULL },
{ _gui_list_proc, 16, 105, 165, 44, 0, 0, 0, D_EXIT, 0, 0, (void*)gfx_depth_getter, NULL, NULL },
{ d_yield_proc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL },
{ NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL }
};
#define GFX_CHANGEPROC 1
#define GFX_TITLE 2
#define GFX_OK 3
#define GFX_CANCEL 4
#define GFX_DRIVERLIST 5
#define GFX_MODELIST 6
#define GFX_DEPTHLIST 7
/* bpp_value:
* Returns the bpp value of the color depth pointed to by INDEX.
*/
static INLINE int bpp_value(int index)
{
ASSERT(index < N_COLOR_DEPTH);
return bpp_value_list[index];
}
/* bpp_value_for_mode:
* Returns the bpp value of the color depth pointed to by INDEX
* for the specified MODE of the specified DRIVER or -1 if INDEX
* is out of bound.
*/
static int bpp_value_for_mode(int index, int driver, int mode)
{
int i, j = -1;
ASSERT(index < N_COLOR_DEPTH);
for (i=0; i < N_COLOR_DEPTH; i++) {
if (driver_list[driver].mode_list[mode].has_bpp[i]) {
if (++j == index)
return bpp_value(i);
}
}
return -1;
}
/* bpp_index:
* Returns the bpp index of the color depth given by DEPTH.
*/
static int bpp_index(int depth)
{
int i;
for (i=0; i < N_COLOR_DEPTH; i++) {
if (bpp_value_list[i] == depth)
return i;
}
ASSERT(FALSE);
return -1;
}
/* bpp_index_for_mode:
* Returns the bpp index of the color depth given by DEPTH for
* the specified MODE of the specified DRIVER or -1 if DEPTH
* is not supported.
*/
static int bpp_index_for_mode(int depth, int driver, int mode)
{
int i, index = -1;
for (i=0; i < N_COLOR_DEPTH; i++) {
if (driver_list[driver].mode_list[mode].has_bpp[i]) {
index++;
if (bpp_value_list[i] == depth)
return index;
}
}
return -1;
}
/* change_proc:
* Stores the current driver in d1 and graphics mode in d2; if a new
* driver is selected in the listbox, it updates the resolution and
* color depth listboxes so that they redraw; if a new resolution is
* selected in the listbox, it updates the color depth listbox. The
* current selection is kept across the changes as much as possible.
*/
static int change_proc(int msg, DIALOG *d, int c)
{
int width = driver_list[d->d1].mode_list[d->d2].w;
int height = driver_list[d->d1].mode_list[d->d2].h;
int depth = bpp_value_for_mode(what_dialog[GFX_DEPTHLIST].d1, d->d1, d->d2);
int i;
ASSERT(d);
if (msg != MSG_IDLE)
return D_O_K;
if (what_dialog[GFX_DRIVERLIST].d1 != d->d1) {
/* record the new setting */
d->d1 = what_dialog[GFX_DRIVERLIST].d1;
/* try to preserve the resolution */
what_dialog[GFX_MODELIST].d1 = 0;
for (i = 0; i < driver_list[d->d1].mode_count; i++) {
if (driver_list[d->d1].mode_list[i].w == width &&
driver_list[d->d1].mode_list[i].h == height) {
what_dialog[GFX_MODELIST].d1 = i;
break;
}
}
what_dialog[GFX_MODELIST].d2 = 0;
object_message(&what_dialog[GFX_MODELIST], MSG_DRAW, 0);
/* record the new setting */
d->d2 = what_dialog[GFX_MODELIST].d1;
if (what_dialog == gfx_mode_ex_dialog) {
/* try to preserve the color depth */
what_dialog[GFX_DEPTHLIST].d1 = bpp_index_for_mode(depth, d->d1, d->d2);
if (what_dialog[GFX_DEPTHLIST].d1 < 0)
what_dialog[GFX_DEPTHLIST].d1 = 0;
what_dialog[GFX_DEPTHLIST].d2 = 0;
object_message(&what_dialog[GFX_DEPTHLIST], MSG_DRAW, 0);
}
}
if (what_dialog[GFX_MODELIST].d1 != d->d2) {
/* record the new setting */
d->d2 = what_dialog[GFX_MODELIST].d1;
if (what_dialog == gfx_mode_ex_dialog) {
/* try to preserve the color depth */
what_dialog[GFX_DEPTHLIST].d1 = bpp_index_for_mode(depth, d->d1, d->d2);
if (what_dialog[GFX_DEPTHLIST].d1 < 0)
what_dialog[GFX_DEPTHLIST].d1 = 0;
what_dialog[GFX_DEPTHLIST].d2 = 0;
object_message(&what_dialog[GFX_DEPTHLIST], MSG_DRAW, 0);
}
}
return D_O_K;
}
/* add_mode:
* Helper function for adding a mode to a mode list.
* Returns 0 on success and -1 on failure.
*/
static int add_mode(MODE_LIST **list, int *size, int w, int h, int bpp)
{
int mode, n;
/* Resolution already there? */
for (mode = 0; mode < *size; mode++) {
if ((w == (*list)[mode].w) && (h == (*list)[mode].h)) {
(*list)[mode].has_bpp[bpp_index(bpp)] = TRUE;
return 0;
}
}
/* Add new resolution. */
*list = _al_sane_realloc(*list, sizeof(MODE_LIST) * ++(*size));
if (!list)
return -1;
mode = *size - 1;
(*list)[mode].w = w;
(*list)[mode].h = h;
for (n = 0; n < N_COLOR_DEPTH; n++)
(*list)[mode].has_bpp[n] = (bpp == bpp_value(n));
return 0;
}
/* terminate_list:
* Helper function for terminating a mode list.
*/
static int terminate_list(MODE_LIST **list, int size)
{
*list = _al_sane_realloc(*list, sizeof(MODE_LIST) * (size + 1));
if (!list)
return -1;
/* Add terminating marker. */
(*list)[size].w = 0;
(*list)[size].h = 0;
return 0;
}
/* create_mode_list:
* Creates a mode list table.
* Returns 0 on success and -1 on failure.
*/
static int create_mode_list(DRIVER_LIST *driver_list_entry, FILTER_FUNCTION filter)
{
MODE_LIST *temp_mode_list = NULL;
GFX_MODE_LIST *gfx_mode_list;
GFX_MODE *gfx_mode_entry;
int mode, n, w, h, bpp;
int is_autodetected = ((driver_list_entry->id == GFX_AUTODETECT)
|| (driver_list_entry->id == GFX_AUTODETECT_WINDOWED)
|| (driver_list_entry->id == GFX_AUTODETECT_FULLSCREEN));
/* Start with zero modes. */
driver_list_entry->mode_count = 0;
/* We use the default mode list in two cases:
* - the driver is GFX_AUTODETECT*,
* - the driver doesn't support get_gfx_mode_list().
*/
if (is_autodetected || !(gfx_mode_list = get_gfx_mode_list(driver_list_entry->id))) {
/* Simply return the default mode list if we can. */
if (!filter) {
driver_list_entry->mode_count = sizeof(default_mode_list) / sizeof(MODE_LIST) - 1;
driver_list_entry->mode_list = default_mode_list;
driver_list_entry->fetch_mode_list_ptr = NULL; /* static */
return 0;
}
/* Build mode list from the default list. */
for (mode = 0; default_mode_list[mode].w; mode++) {
w = default_mode_list[mode].w;
h = default_mode_list[mode].h;
for (n = 0; n < N_COLOR_DEPTH; n++) {
bpp = bpp_value(n);
if (filter(driver_list_entry->id, w, h, bpp) == 0) {
if (add_mode(&temp_mode_list, &driver_list_entry->mode_count, w, h, bpp) != 0)
return -1;
}
}
}
/* We should not terminate the list if the list is empty since the caller
* of this function will simply discard this driver_list entry in that
* case.
*/
if (driver_list_entry->mode_count > 0) {
if (terminate_list(&temp_mode_list, driver_list_entry->mode_count) != 0)
return -1;
}
driver_list_entry->mode_list = temp_mode_list;
driver_list_entry->fetch_mode_list_ptr = (void *)1L; /* private dynamic */
return 0;
}
/* Build mode list from the fetched list. */
for (gfx_mode_entry = gfx_mode_list->mode; gfx_mode_entry->width; gfx_mode_entry++) {
w = gfx_mode_entry->width;
h = gfx_mode_entry->height;
bpp = gfx_mode_entry->bpp;
if (!filter || filter(driver_list_entry->id, w, h, bpp) == 0) {
if (add_mode(&temp_mode_list, &driver_list_entry->mode_count, w, h, bpp) != 0) {
destroy_gfx_mode_list(gfx_mode_list);
return -1;
}
}
}
if (driver_list_entry->mode_count > 0) {
if (terminate_list(&temp_mode_list, driver_list_entry->mode_count) != 0) {
destroy_gfx_mode_list(gfx_mode_list);
return -1;
}
}
driver_list_entry->mode_list = temp_mode_list;
destroy_gfx_mode_list(gfx_mode_list);
return 0;
}
/* create_driver_list:
* Fills the list of video cards with info about the available drivers.
* Returns -1 on failure.
*/
static int create_driver_list(FILTER_FUNCTION filter)
{
_DRIVER_INFO *driver_info;
GFX_DRIVER *gfx_driver;
int i, j, used_prefetched;
int list_pos;
if (system_driver->gfx_drivers)
driver_info = system_driver->gfx_drivers();
else
driver_info = _gfx_driver_list;
driver_list = _AL_MALLOC(sizeof(DRIVER_LIST) * 3);
if (!driver_list) return -1;
list_pos = 0;
driver_list[list_pos].id = GFX_AUTODETECT;
ustrzcpy(driver_list[list_pos].name, DRVNAME_SIZE, get_config_text("Autodetect"));
create_mode_list(&driver_list[list_pos], filter);
if (driver_list[list_pos].mode_count > 0)
list_pos++;
driver_list[list_pos].id = GFX_AUTODETECT_FULLSCREEN;
ustrzcpy(driver_list[list_pos].name, DRVNAME_SIZE, get_config_text("Auto fullscreen"));
create_mode_list(&driver_list[list_pos], filter);
if (driver_list[list_pos].mode_count > 0)
list_pos++;
driver_list[list_pos].id = GFX_AUTODETECT_WINDOWED;
ustrzcpy(driver_list[list_pos].name, DRVNAME_SIZE, get_config_text("Auto windowed"));
create_mode_list(&driver_list[list_pos], filter);
if (driver_list[list_pos].mode_count > 0)
list_pos++;
for (i = 0; driver_info[i].driver; i++) {
driver_list = _al_sane_realloc(driver_list, sizeof(DRIVER_LIST) * (list_pos + 1));
if (!driver_list) return -1;
driver_list[list_pos].id = driver_info[i].id;
gfx_driver = driver_info[i].driver;
do_uconvert(gfx_driver->ascii_name, U_ASCII, driver_list[list_pos].name, U_CURRENT, DRVNAME_SIZE);
driver_list[list_pos].fetch_mode_list_ptr = gfx_driver->fetch_mode_list;
used_prefetched = FALSE;
/* use already fetched mode-list if possible */
for (j=0; j < list_pos; j++) {
if (driver_list[list_pos].fetch_mode_list_ptr == driver_list[j].fetch_mode_list_ptr) {
driver_list[list_pos].mode_list = driver_list[j].mode_list;
driver_list[list_pos].mode_count = driver_list[j].mode_count;
/* the following line prevents a mode-list from beeing free'd more than once */
driver_list[list_pos].fetch_mode_list_ptr = NULL;
used_prefetched = TRUE;
break;
}
}
/* didn't find an already fetched mode-list */
if (!used_prefetched) {
create_mode_list(&driver_list[list_pos], filter);
}
if (driver_list[list_pos].mode_count > 0) {
list_pos++;
}
else {
ASSERT(driver_list[list_pos].mode_list == NULL);
}
}
/* update global variable */
driver_count = list_pos;
return 0;
}
/* destroy_driver_list:
* Frees allocated memory used by driver lists and mode lists.
*/
static void destroy_driver_list(void)
{
int driver;
for (driver=0; driver < driver_count; driver++) {
if (driver_list[driver].fetch_mode_list_ptr)
_AL_FREE(driver_list[driver].mode_list);
}
_AL_FREE(driver_list);
}
/* gfx_card_getter:
* Listbox data getter routine for the graphics card list.
*/
static AL_CONST char *gfx_card_getter(int index, int *list_size)
{
if (index < 0) {
if (list_size)
*list_size = driver_count;
return NULL;
}
return driver_list[index].name;
}
/* gfx_mode_getter:
* Listbox data getter routine for the graphics mode list.
*/
static AL_CONST char *gfx_mode_getter(int index, int *list_size)
{
int entry;
char tmp[32];
entry = what_dialog[GFX_DRIVERLIST].d1;
if (index < 0) {
if (list_size) {
*list_size = driver_list[entry].mode_count;
return NULL;
}
}
uszprintf(mode_string, sizeof(mode_string), uconvert_ascii("%ix%i", tmp),
driver_list[entry].mode_list[index].w, driver_list[entry].mode_list[index].h);
return mode_string;
}
/* gfx_depth_getter:
* Listbox data getter routine for the color depth list.
*/
static AL_CONST char *gfx_depth_getter(int index, int *list_size)
{
static char *bpp_string_list[N_COLOR_DEPTH] = {"256", "32K", "64K", "16M", "16M"};
MODE_LIST *mode;
int card_entry, mode_entry, bpp_entry, bpp_count, bpp_index;
char tmp[128];
card_entry = what_dialog[GFX_DRIVERLIST].d1;
mode_entry = what_dialog[GFX_MODELIST].d1;
mode = &driver_list[card_entry].mode_list[mode_entry];
if (index < 0) {
if (list_size) {
/* Count the number of BPP entries for the mode. */
for (bpp_count = 0, bpp_entry = 0; bpp_entry < N_COLOR_DEPTH; bpp_entry++) {
if (mode->has_bpp[bpp_entry])
bpp_count++;
}
*list_size = bpp_count;
return NULL;
}
}
/* Find the BPP entry for the mode corresponding to the zero-based index. */
bpp_index = -1;
bpp_entry = -1;
while (bpp_index < index) {
if (mode->has_bpp[++bpp_entry])
bpp_index++;
}
uszprintf(mode_string, sizeof(mode_string), uconvert_ascii("%2d ", tmp), bpp_value(bpp_entry));
ustrzcat(mode_string, sizeof(mode_string), get_config_text("bpp"));
ustrzcat(mode_string, sizeof(mode_string), uconvert_ascii(" (", tmp));
ustrzcat(mode_string, sizeof(mode_string), uconvert_ascii(bpp_string_list[bpp_entry], tmp));
ustrzcat(mode_string, sizeof(mode_string), uconvert_ascii(" ", tmp));
ustrzcat(mode_string, sizeof(mode_string), get_config_text("colors"));
ustrzcat(mode_string, sizeof(mode_string), uconvert_ascii(")", tmp));
return mode_string;
}
/* gfx_mode_select_filter:
* Extended version of the graphics mode selection dialog, which allows the
* user to select the color depth as well as the resolution and hardware
* driver. This version of the function reads the initial values from the
* parameters when it activates, so you can specify the default values.
* An optional filter can be passed to check whether a particular entry
* should be displayed or not.
*/
int gfx_mode_select_filter(int *card, int *w, int *h, int *color_depth, FILTER_FUNCTION filter)
{
int i, ret, what_driver, what_mode, what_bpp, extd;
ASSERT(card);
ASSERT(w);
ASSERT(h);
clear_keybuf();
extd = color_depth ? TRUE : FALSE;
while (gui_mouse_b());
what_dialog = extd ? gfx_mode_ex_dialog : gfx_mode_dialog;
what_dialog[GFX_TITLE].dp = (void*)get_config_text("Graphics Mode");
what_dialog[GFX_OK].dp = (void*)get_config_text("OK");
what_dialog[GFX_CANCEL].dp = (void*)get_config_text("Cancel");
create_driver_list(filter);
/* We try to use the values passed through the argument pointers
* as initial settings for the dialog boxes, but only if we have
* been called from the extended function.
*/
if (extd) {
/* firstly the driver */
what_dialog[GFX_DRIVERLIST].d1 = 0; /* GFX_AUTODETECT */
for (i=0; i<driver_count; i++) {
if (driver_list[i].id == *card) {
what_dialog[GFX_DRIVERLIST].d1 = i;
break;
}
}
what_driver = what_dialog[GFX_DRIVERLIST].d1;
what_dialog[GFX_CHANGEPROC].d1 = what_dialog[GFX_DRIVERLIST].d1;
/* secondly the resolution */
what_dialog[GFX_MODELIST].d1 = 0;
for (i=0; driver_list[what_driver].mode_list[i].w; i++) {
if ((driver_list[what_driver].mode_list[i].w == *w)
&& (driver_list[what_driver].mode_list[i].h == *h)) {
what_dialog[GFX_MODELIST].d1 = i;
break;
}
}
what_mode = what_dialog[GFX_MODELIST].d1;
what_dialog[GFX_CHANGEPROC].d2 = what_dialog[GFX_MODELIST].d1; /* not d2 */
/* thirdly the color depth */
what_bpp = bpp_index_for_mode(*color_depth, what_driver, what_mode);
if (what_bpp < 0)
what_bpp = 0;
what_dialog[GFX_DEPTHLIST].d1 = what_bpp;
}
centre_dialog(what_dialog);
set_dialog_color(what_dialog, gui_fg_color, gui_bg_color);
ret = popup_dialog(what_dialog, GFX_DRIVERLIST);
what_driver = what_dialog[GFX_DRIVERLIST].d1;
what_mode = what_dialog[GFX_MODELIST].d1;
if (extd)
what_bpp = what_dialog[GFX_DEPTHLIST].d1;
else
what_bpp = 0;
*card = driver_list[what_driver].id;
*w = driver_list[what_driver].mode_list[what_mode].w;
*h = driver_list[what_driver].mode_list[what_mode].h;
if (extd)
*color_depth = bpp_value_for_mode(what_bpp, what_driver, what_mode);
destroy_driver_list();
if (ret == GFX_CANCEL)
return FALSE;
else
return TRUE;
}
/* gfx_mode_select_ex:
* Extended version of the graphics mode selection dialog, which allows the
* user to select the color depth as well as the resolution and hardware
* driver. This version of the function reads the initial values from the
* parameters when it activates, so you can specify the default values.
*/
int gfx_mode_select_ex(int *card, int *w, int *h, int *color_depth)
{
ASSERT(card);
ASSERT(w);
ASSERT(h);
ASSERT(color_depth);
return gfx_mode_select_filter(card, w, h, color_depth, NULL);
}
/* gfx_mode_select:
* Displays the Allegro graphics mode selection dialog, which allows the
* user to select a screen mode and graphics card. Stores the selection
* in the three variables, and returns zero if it was closed with the
* Cancel button, or non-zero if it was OK'd.
*/
int gfx_mode_select(int *card, int *w, int *h)
{
ASSERT(card);
ASSERT(w);
ASSERT(h);
/* Make sure these values are not used uninitialised.
* This is different to the other gfx_mode_select_* functions.
*/
*card = GFX_AUTODETECT;
*w = 0;
*h = 0;
return gfx_mode_select_filter(card, w, h, NULL, NULL);
}
| 30.195538 | 129 | 0.60372 |
2f2aad78bef0c197ba909b3b5248edfc918124b0 | 2,337 | php | PHP | src/Cinema/BoBundle/Repository/MoviesRepository.php | soz3w/cinema | 0290b6b31a1ed2b7a676a183c94e5d1250e19ae8 | [
"MIT"
] | null | null | null | src/Cinema/BoBundle/Repository/MoviesRepository.php | soz3w/cinema | 0290b6b31a1ed2b7a676a183c94e5d1250e19ae8 | [
"MIT"
] | null | null | null | src/Cinema/BoBundle/Repository/MoviesRepository.php | soz3w/cinema | 0290b6b31a1ed2b7a676a183c94e5d1250e19ae8 | [
"MIT"
] | null | null | null | <?php
namespace Cinema\BoBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Mapping as ORM;
class MoviesRepository extends EntityRepository
{
public function getMoviesCovered($limit)
{
$query=$this->getEntityManager()->createQuery(
"SELECT m
FROM CinemaBoBundle:Movies m
WHERE m.visible =1
AND m.cover=1
AND m.dateRelease <= :today"
)
->setParameter("today", new \DateTime("now"))
->setMaxResults($limit); //limit
//setFirstResult for offset
try {
$movies = $query->getResult();
} catch (\Doctrine\Orm\NoResultException $e) {
$movies = null;
}
return $movies;
}
public function getBestMovies($limit)
{
$query=$this->getEntityManager()->createQuery(
"SELECT m
FROM CinemaBoBundle:Movies m
WHERE m.visible =1
AND m.cover=1
AND m.dateRelease <= :today"
)
->setParameter("today", new \DateTime("now"))
->setMaxResults($limit); //limit
//setFirstResult for offset
try {
$movies = $query->getResult();
} catch (\Doctrine\Orm\NoResultException $e) {
$actors = null;
}
return $movies;
}
public function getBestExpectedMovies($limit)
{
$query=$this->getEntityManager()->createQuery(
"SELECT m
FROM CinemaBoBundle:Movies m
WHERE m.notePresse >0
AND m.dateRelease > :today
ORDER BY m.notePresse desc "
)
->setParameter("today", new \DateTime("now"))
->setMaxResults($limit); //limit
//setFirstResult for offset
try {
$movies = $query->getResult();
} catch (\Doctrine\Orm\NoResultException $e) {
$actors = null;
}
return $movies;
}
public function countMovies()
{
$query=$this->getEntityManager()->createQuery(
"SELECT count(m.id) as nbMovies
FROM CinemaBoBundle:Movies m
"
);
return $query->getSingleScalarResult();
}
}
| 27.174419 | 58 | 0.51519 |
e75f0fb76d22be4155f6047a1fe0c9ce8cfe6ac7 | 233 | js | JavaScript | examples/CompWithSass/CompWithSass.js | Jay-A-McBee/create-react-component-folder | ae2e537d6bbefc1a08bd681597a8edb97578ca1d | [
"MIT"
] | 159 | 2018-02-07T11:30:21.000Z | 2022-02-23T12:33:00.000Z | examples/CompWithSass/CompWithSass.js | donovantc/create-react-component-folder | b6bb2d007914c67b4d0df17c5adcfe14a73c14eb | [
"MIT"
] | 44 | 2018-03-11T10:02:28.000Z | 2021-12-02T22:46:57.000Z | examples/CompWithSass/CompWithSass.js | donovantc/create-react-component-folder | b6bb2d007914c67b4d0df17c5adcfe14a73c14eb | [
"MIT"
] | 59 | 2018-03-10T23:35:45.000Z | 2022-03-10T13:03:12.000Z | import React, { Component } from 'react';
import PropTypes from 'prop-types';
class CompWithSass extends Component {
render() {
return <div>CompWithSass</div>;
}
}
CompWithSass.propTypes = {};
export default CompWithSass;
| 17.923077 | 41 | 0.712446 |
77787f90d594707d7cb1509c6c682e55205734a6 | 4,786 | kt | Kotlin | agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/cxx/model/JsonUtil.kt | jomof/CppBuildCacheWorkInProgress | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | [
"Apache-2.0"
] | null | null | null | agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/cxx/model/JsonUtil.kt | jomof/CppBuildCacheWorkInProgress | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | [
"Apache-2.0"
] | null | null | null | agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/cxx/model/JsonUtil.kt | jomof/CppBuildCacheWorkInProgress | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.internal.cxx.model
import com.android.build.gradle.internal.cxx.json.PlainFileGsonTypeAdaptor
import com.android.repository.Revision
import com.google.gson.GsonBuilder
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import org.gradle.api.file.FileCollection
import java.io.File
import java.io.IOException
import java.io.StringWriter
/**
* Write the [CxxAbiModel] to Json string.
*/
fun CxxAbiModel.toJsonString(): String {
return StringWriter()
.also { writer -> GSON.toJson(this, writer) }
.toString()
}
/**
* Write the [CxxCmakeAbiModel] to Json string.
*/
fun CxxCmakeAbiModel.toJsonString(): String {
return StringWriter()
.also { writer -> GSON.toJson(this, writer) }
.toString()
}
/**
* Write the [CxxVariantModel] to Json string.
*/
fun CxxVariantModel.toJsonString(): String {
return StringWriter()
.also { writer -> GSON.toJson(this, writer) }
.toString()
}
/**
* Write the [CxxModuleModel] to Json string.
*/
fun CxxModuleModel.toJsonString(): String {
return StringWriter()
.also { writer -> GSON.toJson(this, writer) }
.toString()
}
/**
* Create a [CxxModuleModel] from Json string.
*/
fun createCxxModuleModelFromJson(json: String): CxxModuleModel {
return GSON.fromJson(json, CxxModuleModel::class.java)
}
/**
* Create a [CxxAbiModel] from Json string.
*/
fun createCxxAbiModelFromJson(json: String): CxxAbiModel {
return GSON.fromJson(json, CxxAbiModel::class.java)
}
/**
* Write model to JSON file.
*/
fun CxxAbiModel.writeJsonToFile() {
modelOutputFile.parentFile.mkdirs()
modelOutputFile.writeText(toJsonString())
}
/**
* GSon TypeAdapter that will convert between File and String.
*/
class PlainFileGsonTypeAdaptor : TypeAdapter<File?>() {
@Throws(IOException::class)
override fun write(jsonWriter: JsonWriter, file: File?) {
if (file == null) {
jsonWriter.nullValue()
return
}
jsonWriter.value(file.path)
}
@Throws(IOException::class)
override fun read(jsonReader: JsonReader): File? {
val path = jsonReader.nextString()
return File(path)
}
}
class FileCollectionTypeAdaptor : TypeAdapter<FileCollection?>() {
override fun write(jsonWriter: JsonWriter, fileCollection: FileCollection?) {
jsonWriter.beginArray()
fileCollection?.onEach { jsonWriter.value(it.path) }
jsonWriter.endArray()
}
override fun read(jsonReader: JsonReader): FileCollection? {
// FileCollection is read but ignored
jsonReader.beginArray()
while(jsonReader.hasNext()) jsonReader.nextString()
jsonReader.endArray()
return null
}
}
private val GSON = GsonBuilder()
.registerTypeAdapter(File::class.java, PlainFileGsonTypeAdaptor())
.registerTypeAdapter(Revision::class.java, RevisionTypeAdapter())
.registerTypeAdapter(FileCollection::class.java, FileCollectionTypeAdaptor())
.setPrettyPrinting()
.create()
/**
* [TypeAdapter] that converts between [Revision] and Json string.
*/
private class RevisionTypeAdapter : TypeAdapter<Revision>() {
override fun write(writer: JsonWriter, revision: Revision) {
writer.value(revision.toString())
}
override fun read(reader: JsonReader): Revision {
return Revision.parseRevision(reader.nextString())
}
}
/**
* Prefab configuration state to be persisted to disk.
*
* Prefab configuration state needs to be persisted to disk because changes in configuration
* require model regeneration.
*/
data class PrefabConfigurationState(
val enabled: Boolean,
val prefabPath: File?,
val packages: List<File>
) {
fun toJsonString(): String {
return StringWriter()
.also { writer -> GSON.toJson(this, writer) }
.toString()
}
companion object {
@JvmStatic
fun fromJson(json: String): PrefabConfigurationState {
return GSON.fromJson(json, PrefabConfigurationState::class.java)
}
}
}
| 28.152941 | 92 | 0.690765 |
26a03c18ef82af69a934196fb97aba1729cb504a | 4,276 | java | Java | studio/plugins/text.editor/src/main/java/com/andcreations/ae/studio/plugins/text/editor/autocomplete/TECompletionProvider.java | mikolajgucki/ae-engine | c4953feb74853b01b39b45b3bce23c10f6f74db0 | [
"MIT"
] | 1 | 2021-02-23T09:36:42.000Z | 2021-02-23T09:36:42.000Z | studio/plugins/text.editor/src/main/java/com/andcreations/ae/studio/plugins/text/editor/autocomplete/TECompletionProvider.java | mikolajgucki/ae-engine | c4953feb74853b01b39b45b3bce23c10f6f74db0 | [
"MIT"
] | null | null | null | studio/plugins/text.editor/src/main/java/com/andcreations/ae/studio/plugins/text/editor/autocomplete/TECompletionProvider.java | mikolajgucki/ae-engine | c4953feb74853b01b39b45b3bce23c10f6f74db0 | [
"MIT"
] | null | null | null | package com.andcreations.ae.studio.plugins.text.editor.autocomplete;
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.JTextComponent;
import org.fife.ui.autocomplete.Completion;
import org.fife.ui.autocomplete.DefaultCompletionProvider;
/**
* @author Mikolaj Gucki
*/
public class TECompletionProvider extends DefaultCompletionProvider {
/** */
@Override
public boolean isValidChar(char ch) {
return super.isValidChar(ch) || ch == '.' || ch == '?' || ch == '@';
}
/** */
private boolean matchName(Autocompl autocompl,String text) {
return autocompl.getLowerCaseName().startsWith(text);
}
/** */
private boolean matchFullName(Autocompl autocompl,String text) {
return autocompl.getLowerCaseFullName().startsWith(text);
}
/** */
private boolean matchPrefix(Autocompl autocompl,String text,
String dotText) {
//
return autocompl.getLowerCasePrefix().startsWith(text) ||
autocompl.getLowerCasePrefix().contains(dotText);
}
/** */
@Override
protected List<Completion> getCompletionsImpl(JTextComponent comp) {
String text = getAlreadyEnteredText(comp).toLowerCase();
if (text == null || text.length() == 0) {
return completions;
}
String name = null;
String prefix = null;
// check if to match name, prefix or both
int indexOf = text.indexOf('?');
if (indexOf < 0) {
name = text;
}
else {
name = text.substring(indexOf + 1,text.length());
prefix = text.substring(0,indexOf);
if (name.length() == 0) {
name = null;
}
if (prefix.length() == 0) {
prefix = null;
}
}
String dotName = null;
if (name != null) {
dotName = "." + name;
}
String dotPrefix = null;
if (prefix != null) {
dotPrefix = "." + prefix;
}
// matched completions
List<Completion> matched = new ArrayList<>();
// ? -> match all
if (name == null && prefix == null) {
return completions;
}
// ... or ?...
if (name != null && prefix == null) {
if (indexOf < 0) {
// ... -> match by name, prefix or full name
for (Completion compl:completions) {
Autocompl autocompl = (Autocompl)compl;
if (matchName(autocompl,name) == true ||
matchPrefix(autocompl,name,dotName) == true ||
matchFullName(autocompl,name) == true) {
//
matched.add(compl);
}
}
}
else {
// ?... -> match by name
for (Completion compl:completions) {
Autocompl autocompl = (Autocompl)compl;
if (matchName(autocompl,name) == true) {
matched.add(compl);
}
}
}
}
// ...? -> match by prefix
if (name == null && prefix != null) {
for (Completion compl:completions) {
Autocompl autocompl = (Autocompl)compl;
if (matchPrefix(autocompl,prefix,dotPrefix) == true) {
matched.add(compl);
}
}
}
// ...?... -> match by name and prefix
if (name != null && prefix != null) {
for (Completion compl:completions) {
Autocompl autocompl = (Autocompl)compl;
if (matchName(autocompl,name) == true &&
matchPrefix(autocompl,prefix,dotPrefix) == true) {
//
matched.add(compl);
}
}
}
return matched;
}
} | 32.393939 | 77 | 0.45884 |
90238070b4dc6cc427c6cd8a8293f07bfd65a221 | 808 | swift | Swift | DouYUZB/DouYUZB/Classes/Home/ViewModel/GameViewModel.swift | BreankingBad/DouYuZB | 8e9c5d8bcd01edf02bed6a96646e83487c6e0925 | [
"MIT"
] | 2 | 2018-06-07T06:50:31.000Z | 2018-07-08T10:50:01.000Z | DouYUZB/DouYUZB/Classes/Home/ViewModel/GameViewModel.swift | BreankingBad/DouYuZB | 8e9c5d8bcd01edf02bed6a96646e83487c6e0925 | [
"MIT"
] | 1 | 2018-07-08T10:49:13.000Z | 2018-07-09T03:10:33.000Z | DouYUZB/DouYUZB/Classes/Home/ViewModel/GameViewModel.swift | BreankingBad/DouYuZB | 8e9c5d8bcd01edf02bed6a96646e83487c6e0925 | [
"MIT"
] | null | null | null | //
// GameViewModel.swift
// DouYUZB
//
// Created by mxm on 2018/7/8.
// Copyright © 2018年 mxm. All rights reserved.
//
import Foundation
class GameViewModel {
lazy var gameModels: [BaseGameModel] = [BaseGameModel]()
}
extension GameViewModel {
func loadGameData(finishedCallback: @escaping () -> Void) {
NetworkUtils.request(type: .Get, url: "http://capi.douyucdn.cn/api/v1/getColumnDetail?shortName:game", params: [:]) { result in
guard let result = result as? [String : Any] else { return }
guard let dataArray = result["data"] as? [[String : Any]] else { return }
for data in dataArray {
self.gameModels.append(GameModel(dict: data))
}
finishedCallback()
}
}
}
| 26.933333 | 135 | 0.589109 |
11416b090ceec38b1532e567ef41ce6539631c37 | 749 | asm | Assembly | oeis/126/A126986.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/126/A126986.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/126/A126986.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A126986: Expansion of 1/(1+4*x*c(x)), c(x) the g.f. of Catalan numbers A000108.
; Submitted by Christian Krause
; 1,-4,12,-40,124,-408,1272,-4176,13020,-42808,133096,-439344,1358872,-4514800,13853040,-46469280,140945820,-479312760,1430085000,-4958382960,14453014920,-51500944080,145230007440,-537922074720,1446902948184,-5662012752048,14228883685392,-60226310250976,137097352070320,-649709888025312,1277277868359904,-7139278380425536,11209981985980188,-80299194256775160,87088517291886024,-929038489053819888,479894769046382632,-11103501969636787216,-1229437156859674800,-137452891327654401760
mov $4,$0
add $0,1
lpb $0
sub $0,1
mov $3,$4
bin $3,$1
add $1,1
add $3,$2
mul $2,2
mul $3,6
sub $2,$3
add $4,1
lpe
mov $0,$3
div $0,6
| 37.45 | 481 | 0.76235 |
1f2e8a17e3eef51cb643dc015e53aee082bc6848 | 125 | css | CSS | src/components/Side/side.css | FredBrock/gatsby-fredbrock-blog | cd97a777eb5480a4cd7be5cdf3e0adfbb29a8018 | [
"MIT"
] | null | null | null | src/components/Side/side.css | FredBrock/gatsby-fredbrock-blog | cd97a777eb5480a4cd7be5cdf3e0adfbb29a8018 | [
"MIT"
] | 7 | 2021-05-09T21:42:04.000Z | 2022-02-26T14:30:17.000Z | src/components/Side/side.css | FredBrock/gatsby-fredbrock-blog | cd97a777eb5480a4cd7be5cdf3e0adfbb29a8018 | [
"MIT"
] | null | null | null | .box-shadow {
box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.15);
}
.transition-fast {
transition: all 0.2s ease !important;
}
| 15.625 | 46 | 0.632 |
fbcb6d9fe250614319e6ef49db2ede858cd1f740 | 708 | h | C | code/Modules/Gfx/Resource/drawState.h | waywardmonkeys/oryol | 6b496fa9f5fd7acbae3363e0617cb13d333aa6bf | [
"MIT"
] | null | null | null | code/Modules/Gfx/Resource/drawState.h | waywardmonkeys/oryol | 6b496fa9f5fd7acbae3363e0617cb13d333aa6bf | [
"MIT"
] | null | null | null | code/Modules/Gfx/Resource/drawState.h | waywardmonkeys/oryol | 6b496fa9f5fd7acbae3363e0617cb13d333aa6bf | [
"MIT"
] | null | null | null | #pragma once
//------------------------------------------------------------------------------
/**
@class Oryol::_priv::drawState
@ingroup _priv
@brief bundles pre-compiled state for drawing operations
*/
#if ORYOL_OPENGL
#include "Gfx/gl/glDrawState.h"
namespace Oryol {
namespace _priv {
class drawState : public glDrawState { };
} }
#elif ORYOL_D3D11
#include "Gfx/d3d11/d3d11DrawState.h"
namespace Oryol {
namespace _priv {
class drawState : public d3d11DrawState { };
} }
#elif ORYOL_METAL
#include "Gfx/mtl/mtlDrawState.h"
namespace Oryol {
namespace _priv {
class drawState : public mtlDrawState { };
} }
#else
#error "Target platform not yet supported!"
#endif
| 24.413793 | 81 | 0.624294 |
28b3f1c40fd5db6b96bf013396f1b4009d1db49d | 393 | rb | Ruby | db/migrate/20090405172532_create_team_filters.rb | mikehelmick/CascadeLMS | 50475a619665dad921efb01fd1265f5ebbc3653c | [
"BSD-3-Clause"
] | 16 | 2015-01-20T06:03:46.000Z | 2022-01-16T00:07:18.000Z | db/migrate/20090405172532_create_team_filters.rb | ybakos/CascadeLMS | ff5c0e0f51fda8dedccfdf36ec9a929267bf5141 | [
"BSD-3-Clause"
] | 38 | 2020-02-06T05:13:54.000Z | 2020-02-06T05:14:35.000Z | db/migrate/20090405172532_create_team_filters.rb | ybakos/CascadeLMS | ff5c0e0f51fda8dedccfdf36ec9a929267bf5141 | [
"BSD-3-Clause"
] | 5 | 2015-07-04T12:47:07.000Z | 2019-03-23T00:51:47.000Z | class CreateTeamFilters < ActiveRecord::Migration
def self.up
create_table :team_filters do |t|
t.column :assignment_id, :integer, :null => false
t.column :project_team_id, :integer, :null => false
t.timestamps
end
add_index(:team_filters, [:assignment_id, :project_team_id], :unique => true)
end
def self.down
drop_table :team_filters
end
end
| 23.117647 | 81 | 0.681934 |
cd9ce6496d864d155e4ef7acb145a95a69629557 | 3,603 | kt | Kotlin | demo/src/main/java/com/github/ai/fprovider/demo/MainViewModel.kt | aivanovski/internal-storage-file-provider | 1ddc05dc4f6439966872386a03f4ec85cce5c9e3 | [
"Apache-2.0"
] | null | null | null | demo/src/main/java/com/github/ai/fprovider/demo/MainViewModel.kt | aivanovski/internal-storage-file-provider | 1ddc05dc4f6439966872386a03f4ec85cce5c9e3 | [
"Apache-2.0"
] | null | null | null | demo/src/main/java/com/github/ai/fprovider/demo/MainViewModel.kt | aivanovski/internal-storage-file-provider | 1ddc05dc4f6439966872386a03f4ec85cce5c9e3 | [
"Apache-2.0"
] | null | null | null | package com.github.ai.fprovider.demo
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.github.ai.fprovider.demo.utils.Event
import com.github.ai.fprovider.demo.utils.ResourceProvider
import com.github.ai.isfprovider.InternalStorageTokenManager
import kotlinx.coroutines.launch
import kotlin.random.Random
class MainViewModel(
private val interactor: FileSystemInteractor,
private val tokenManager: InternalStorageTokenManager,
private val resourceProvider: ResourceProvider
) : ViewModel() {
private val _isProgressVisible = MutableLiveData(false)
val isProgressVisible: LiveData<Boolean> = _isProgressVisible
private val _isOpenButtonEnabled = MutableLiveData(false)
val isOpenButtonEnabled: LiveData<Boolean> = _isOpenButtonEnabled
private val _accessTokenMessage = MutableLiveData("")
val accessTokenMessage: LiveData<String> = _accessTokenMessage
private val _showViewerEvent = MutableLiveData<Event<AccessData>>()
val showViewerEvent: LiveData<Event<AccessData>> = _showViewerEvent
private var token: String? = null
fun loadCurrentToken() {
viewModelScope.launch {
val currentToken = tokenManager.getAllTokens().firstOrNull()
token = currentToken
_isOpenButtonEnabled.value = (token != null)
if (currentToken != null) {
_accessTokenMessage.value = "Current token is: $currentToken"
} else {
_accessTokenMessage.value = "Access token is not set"
}
}
}
fun createFileStructure() {
_isProgressVisible.value = true
viewModelScope.launch {
interactor.createFilesInsideInternalStorage()
_isProgressVisible.value = false
}
}
fun generateAccessToken() {
_isProgressVisible.value = true
viewModelScope.launch {
tokenManager.removeAllTokens()
val newToken = newToken()
tokenManager.addToken(newToken, DEFAULT_PATH_TO_FILES)
token = newToken
_isOpenButtonEnabled.value = (token != null)
_accessTokenMessage.value = "Generated new token: $newToken"
_isProgressVisible.value = false
}
}
fun showViewer() {
val token = token ?: return
_showViewerEvent.value = Event(
AccessData(
contentProviderAuthority = resourceProvider.getString(R.string.content_provider_authority),
path = "$DEFAULT_PATH_TO_FILES/*",
token = token
)
)
}
private fun newToken(): String {
val value = Random(System.currentTimeMillis()).nextInt(10)
val token = StringBuilder()
for (idx in 0 until 4) {
token.append(value)
}
return token.toString()
}
data class AccessData(
val contentProviderAuthority: String,
val path: String,
val token: String
)
companion object {
private const val DEFAULT_PATH_TO_FILES = "/files/home"
}
}
class MainViewModelFactory(
private val interactor: FileSystemInteractor,
private val tokenManager: InternalStorageTokenManager,
private val resourceProvider: ResourceProvider
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return MainViewModel(interactor, tokenManager, resourceProvider) as T
}
} | 31.060345 | 107 | 0.677491 |
92d91df9851f8f5d230f0ecd1a7bea41e8ae3e30 | 11,980 | h | C | include/ups/upscaledb_uqi.h | romz-pl/upscaledb | 781206f75a9f49b67dc0cd2c0e191435e60f4693 | [
"Apache-2.0"
] | null | null | null | include/ups/upscaledb_uqi.h | romz-pl/upscaledb | 781206f75a9f49b67dc0cd2c0e191435e60f4693 | [
"Apache-2.0"
] | 9 | 2018-05-05T08:01:58.000Z | 2018-05-07T19:10:01.000Z | include/ups/upscaledb_uqi.h | romz-pl/upscaledb | 781206f75a9f49b67dc0cd2c0e191435e60f4693 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2005-2017 Christoph Rupp (chris@crupp.de).
*
* 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.
*
* See the file COPYING for License information.
*/
/**
* @file upscaledb_uqi.h
* @brief Include file for upscaledb Query Interface
* @author Christoph Rupp, chris@crupp.de
* @version 2.2.1
*
* This API is EXPERIMENTAL!! The interface is not yet stable.
*/
#ifndef UPS_UPSCALEDB_UQI_H
#define UPS_UPSCALEDB_UQI_H
#include <ups/upscaledb.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* A structure which stores the results of a query.
*/
struct uqi_result_t;
typedef struct uqi_result_t uqi_result_t;
/**
* Returns the number of rows stored in a query result
*/
uint32_t
uqi_result_get_row_count(uqi_result_t *result);
/**
* Returns the key type
*/
uint32_t
uqi_result_get_key_type(uqi_result_t *result);
/**
* Returns the record type
*/
uint32_t
uqi_result_get_record_type(uqi_result_t *result);
/**
* Returns a key for the specified row
*/
void
uqi_result_get_key(uqi_result_t *result, uint32_t row, ups_key_t *key);
/**
* Returns a record for the specified row
*/
void
uqi_result_get_record(uqi_result_t *result, uint32_t row, ups_record_t *record);
/**
* Returns a pointer to the serialized key data
*
* If the keys have a fixed-length type (i.e. UPS_TYPE_UINT32) then this
* corresponds to an array of this type (here: uint32_t).
*/
void *
uqi_result_get_key_data(uqi_result_t *result, uint32_t *size);
/**
* Returns a pointer to the serialized record data
*
* If the record have a fixed-length type (i.e. UPS_TYPE_UINT32) then this
* corresponds to an array of this type (here: uint32_t).
*/
void *
uqi_result_get_record_data(uqi_result_t *result, uint32_t *size);
/**
* Releases the resources allocated by an uqi_result_t type.
*
* Call this to avoid memory leaks.
*
* @parameter result Pointer to the uqi_result_t object.
*/
void
uqi_result_close(uqi_result_t *result);
/**
* Initializes an uqi_result_t object.
*
* @parameter result Pointer to the uqi_result_t object.
* @parameter key_type The key type (i.e. UPS_TYPE_BINARY)
* @parameter record_type The record type (i.e. UPS_TYPE_UINT64)
*/
void
uqi_result_initialize(uqi_result_t *result, int key_type, int record_type);
/**
* Adds a new key/value pair to a result set.
*
* This can be used by plugin implementors to assign the results of an
* aggregation query.
*
* @parameter result Pointer to the uqi_result_t object.
* @parameter key_data The data of the new key
* @parameter key_size The size of the new key (in bytes)
* @parameter record_data The data of the new record
* @parameter record_size The size of the new record (in bytes)
*/
void
uqi_result_add_row(uqi_result_t *result,
const void *key_data, uint32_t key_size,
const void *record_data, uint32_t record_size);
/**
* Efficiently moves a result set's data to another one.
*/
void
uqi_result_move(uqi_result_t *destination, uqi_result_t *source);
/**
* The plugins are stateless and threadsafe. However, the "init" function is
* called prior to the actual usage, and it can allocate (and return) a
* state variable.
*
* |flags| specify whether this plugin will work on keys, records or both
* (@ref UQI_STREAM_KEY, UQI_STREAM_RECORD)
* |key_type| is the key type specified by the user (i.e. @a UPS_TYPE_UINT32),
* |key_size| is the specified key size
* |record_type| is the record type specified by the user
* |record_size| is the specified record size
*/
typedef void *(*uqi_plugin_init_function)(int flags, int key_type,
uint32_t key_size, int record_type, uint32_t record_size,
const char *reserved);
/** Plugin initialization flag */
#define UQI_STREAM_KEY 1
/** Plugin initialization flag */
#define UQI_STREAM_RECORD 2
/** Cleans up the state variable and can release resources */
typedef void (*uqi_plugin_cleanup_function)(void *state);
/** Performs the actual aggregation on a single value */
typedef void (*uqi_plugin_aggregate_single_function)(void *state,
const void *key_data, uint32_t key_size,
const void *record_data, uint32_t record_size);
/** Performs the actual aggregation on a list of values */
typedef void (*uqi_plugin_aggregate_many_function)(void *state,
const void *key_data_list, const void *record_data_list,
size_t list_length);
/**
* Predicate function; returns true if the value matches the predicate,
* otherwise false
*/
typedef int (*uqi_plugin_predicate_function)(void *state,
const void *key_data, uint32_t key_size,
const void *record_data, uint32_t record_size);
/** Assigns the results to an @a uqi_result_t structure */
typedef void (*uqi_plugin_result_function)(void *state, uqi_result_t *result);
/** Describes a plugin for predicates */
#define UQI_PLUGIN_PREDICATE 1
/** Describes a plugin for aggregation */
#define UQI_PLUGIN_AGGREGATE 2
/** Describes a plugin which requires keys AND records */
#define UQI_PLUGIN_REQUIRE_BOTH_STREAMS 1
/**
* A plugin descriptor. Describes the implementation of a user-supplied
* aggregation or predicate function and can be loaded dynamically from
* an external library.
*
* Plugins can be loaded dynamically from a library (.DLL/.SO etc) by
* specifying a function name in a query string, i.e.
*
* foo@path/to/library.dll
*
* or
*
* foo@library.so
*
* The library name can be either an absolute path or a (relative) file name,
* in the latter case the system's library directories will be searched
* for the file. The library can be ommitted if the plugin was registered
* with @a uqi_register_plugin.
*
* After the file is loaded, a function with the following interface is
* invoked:
*
* uqi_plugin_t *plugin_descriptor(const char *name);
*
* The parameter |name| is "foo" in our example. The function
* |plugin_descriptor| must be an exported symbol with the "C"
* calling convention.
*
*/
struct uqi_plugin_t {
uqi_plugin_t()
: name( nullptr )
, type( 0 )
, flags( 0 )
, plugin_version( 0 )
, init( nullptr )
, cleanup( nullptr )
, agg_single( nullptr )
, agg_many( nullptr )
, pred( nullptr )
, results( nullptr )
{
}
/** The name of this plugin */
const char *name;
/**
* The type of this plugin - either @a UQI_PLUGIN_PREDICATE or
* @a UQI_PLUGIN_AGGREGATE
*/
uint32_t type;
/**
* The plugin flags - either 0, or
* @UQI_PLUGIN_REQUIRE_BOTH_STREAMS: if set, then key AND record stream
* will be passed to the predicate. Otherwise, the query engine
* will only pass keys (or records), not both.
*/
uint32_t flags;
/** The version of the plugin's interface; always set to 0 */
uint32_t plugin_version;
/** The initialization function; can be null */
uqi_plugin_init_function init;
/** The de-initialization function; can be null */
uqi_plugin_cleanup_function cleanup;
/**
* The aggregation function; must be implemented if
* @a type is @a UQI_PLUGIN_AGGREGATE, otherwise set to null
*/
uqi_plugin_aggregate_single_function agg_single;
/**
* The aggregation function; must be implemented if
* @a type is @a UQI_PLUGIN_AGGREGATE, otherwise set to null
*/
uqi_plugin_aggregate_many_function agg_many;
/**
* The predicate function; must be implemented if
* @a type is @a UQI_PLUGIN_PREDICATE, otherwise set to null
*/
uqi_plugin_predicate_function pred;
/** Assigns the result to a @a uqi_result_t structure; must not be null */
uqi_plugin_result_function results;
};
/**
* Manually registers a UQI plugiRegisters a UQI plugin
*
* This is the pro-active alternative to exporting a plugin descriptor
* from a dynamic library. Use this if your plugin is linked statically
* into your application.
*
* @return @ref UPS_SUCCESS upon success
* @return @ref UPS_PLUGIN_ALREADY_EXISTS if a plugin with this name already
* exists
* @return @ref UPS_INV_PARAMETER if any of the pointers is null
*/
ups_status_t
uqi_register_plugin(uqi_plugin_t *descriptor);
/**
* Performs a "UQI Select" query.
*
* See below for a description of the query syntax. In short, this function
* can execute aggregation functions like SUM, AVERAGE or COUNT over a
* database. The result is returned in @a result, which is allocated
* by this function and has to be released with @a uqi_result_close.
*
* @return UPS_PLUGIN_NOT_FOUND The specified function is not available
* @return UPS_PARSER_ERROR Failed to parse the @a query string
*
* @sa uqi_result_close
* @sa uqi_select_range
*/
ups_status_t
uqi_select(ups_env_t *env, const char *query, uqi_result_t **result);
/**
* Performs a paginated "UQI Select" query.
*
* This function is similar to @a uqi_db_select, but uses two cursors for
* specifying the range of the data. Make sure that both cursors are
* operating on the same database as the query. Both cursors are optional;
* if @a begin is null then the query will start at the first element (with
* the lowest key) in the database. If @a end is null then it will run till
* the last element of the database.
*
* If @a begin is not null then it will be moved to the first key behind the
* processed range.
*
* If the specified Database is not yet opened, it will be reopened in
* background and immediately closed again after the query. Closing the
* Database can hurt performance. To avoid this, manually open the
* Database (see @a ups_env_open_db) prior to the query. The
* @a uqi_select_range method will then re-use the existing Database handle.
*
* The supplied @ref query string has a syntax similar to SQL:
*
* [DISTINCT] <FUNCTION>(<STREAM>) FROM DATABASE <DB>
* [WHERE <PREDICATE>(<STREAM>)]
* [LIMIT <LIMIT>]
*
* DISTINCT: an optional key word which strips the query input from all
* duplicate keys. (This is different from SQL where duplicate results
* are removed.)
*
* FUNCTION: an identifier for a built-in or an external aggregation function.
* Built-in functions are SUM, COUNT, AVERAGE, TOP, BOTTOM,
* MIN and MAX. External identifiers are names of registered plugins
* (with @a uqi_register_plugin) or loaded from external libraries.
*
* DB: the numerical id of the database
*
* PREDICATE: an identifier for a predicate function.
*
* STREAM: a literal "$key" or "$record"; decides whether keys or
* records are aggregated
*
* LIMIT: a limit for the result. Currently ONLY allowed for the built-in
* functions "TOP" and "BOTTOM"! When used with other functions then
* an error is returned.
*
* The @a result object is allocated automatically and has to be released
* with @a uqi_result_close by the caller.
*
* @return UPS_PLUGIN_NOT_FOUND The specified function is not available
* @return UPS_PARSER_ERROR Failed to parse the @a query string
*
* @sa uqi_result_close
*/
ups_status_t
uqi_select_range(ups_env_t *env, const char *query, ups_cursor_t *begin,
const ups_cursor_t *end, uqi_result_t **result);
/**
* @}
*/
#ifdef __cplusplus
} // extern "C"
#endif
#endif /* UPS_UPSCALEDB_UQI_H */
| 31.197917 | 80 | 0.705175 |
270f2fbdf0ccb6a65807e6304456c8748eaaea48 | 8,659 | c | C | machine/qemu/sources/u-boot/drivers/clk/ti/clk-divider.c | muddessir/framework | 5b802b2dd7ec9778794b078e748dd1f989547265 | [
"MIT"
] | 1 | 2021-11-21T19:56:29.000Z | 2021-11-21T19:56:29.000Z | machine/qemu/sources/u-boot/drivers/clk/ti/clk-divider.c | muddessir/framework | 5b802b2dd7ec9778794b078e748dd1f989547265 | [
"MIT"
] | null | null | null | machine/qemu/sources/u-boot/drivers/clk/ti/clk-divider.c | muddessir/framework | 5b802b2dd7ec9778794b078e748dd1f989547265 | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: GPL-2.0+
/*
* TI divider clock support
*
* Copyright (C) 2020 Dario Binacchi <dariobin@libero.it>
*
* Loosely based on Linux kernel drivers/clk/ti/divider.c
*/
#include <common.h>
#include <clk.h>
#include <clk-uclass.h>
#include <div64.h>
#include <dm.h>
#include <dm/device_compat.h>
#include <asm/io.h>
#include <linux/clk-provider.h>
#include <linux/kernel.h>
#include <linux/log2.h>
#include "clk.h"
/*
* The reverse of DIV_ROUND_UP: The maximum number which
* divided by m is r
*/
#define MULT_ROUND_UP(r, m) ((r) * (m) + (m) - 1)
struct clk_ti_divider_priv {
struct clk parent;
fdt_addr_t reg;
const struct clk_div_table *table;
u8 shift;
u8 flags;
u8 div_flags;
s8 latch;
u16 min;
u16 max;
u16 mask;
};
static unsigned int _get_div(const struct clk_div_table *table, ulong flags,
unsigned int val)
{
if (flags & CLK_DIVIDER_ONE_BASED)
return val;
if (flags & CLK_DIVIDER_POWER_OF_TWO)
return 1 << val;
if (table)
return clk_divider_get_table_div(table, val);
return val + 1;
}
static unsigned int _get_val(const struct clk_div_table *table, ulong flags,
unsigned int div)
{
if (flags & CLK_DIVIDER_ONE_BASED)
return div;
if (flags & CLK_DIVIDER_POWER_OF_TWO)
return __ffs(div);
if (table)
return clk_divider_get_table_val(table, div);
return div - 1;
}
static int _div_round_up(const struct clk_div_table *table, ulong parent_rate,
ulong rate)
{
const struct clk_div_table *clkt;
int up = INT_MAX;
int div = DIV_ROUND_UP_ULL((u64)parent_rate, rate);
for (clkt = table; clkt->div; clkt++) {
if (clkt->div == div)
return clkt->div;
else if (clkt->div < div)
continue;
if ((clkt->div - div) < (up - div))
up = clkt->div;
}
return up;
}
static int _div_round(const struct clk_div_table *table, ulong parent_rate,
ulong rate)
{
if (table)
return _div_round_up(table, parent_rate, rate);
return DIV_ROUND_UP(parent_rate, rate);
}
static int clk_ti_divider_best_div(struct clk *clk, ulong rate,
ulong *best_parent_rate)
{
struct clk_ti_divider_priv *priv = dev_get_priv(clk->dev);
ulong parent_rate, parent_round_rate, max_div;
ulong best_rate, r;
int i, best_div = 0;
parent_rate = clk_get_rate(&priv->parent);
if (IS_ERR_VALUE(parent_rate))
return parent_rate;
if (!rate)
rate = 1;
if (!(clk->flags & CLK_SET_RATE_PARENT)) {
best_div = _div_round(priv->table, parent_rate, rate);
if (best_div == 0)
best_div = 1;
if (best_div > priv->max)
best_div = priv->max;
*best_parent_rate = parent_rate;
return best_div;
}
max_div = min(ULONG_MAX / rate, (ulong)priv->max);
for (best_rate = 0, i = 1; i <= max_div; i++) {
if (!clk_divider_is_valid_div(priv->table, priv->div_flags, i))
continue;
/*
* It's the most ideal case if the requested rate can be
* divided from parent clock without needing to change
* parent rate, so return the divider immediately.
*/
if ((rate * i) == parent_rate) {
*best_parent_rate = parent_rate;
dev_dbg(clk->dev, "rate=%ld, best_rate=%ld, div=%d\n",
rate, rate, i);
return i;
}
parent_round_rate = clk_round_rate(&priv->parent,
MULT_ROUND_UP(rate, i));
if (IS_ERR_VALUE(parent_round_rate))
continue;
r = DIV_ROUND_UP(parent_round_rate, i);
if (r <= rate && r > best_rate) {
best_div = i;
best_rate = r;
*best_parent_rate = parent_round_rate;
if (best_rate == rate)
break;
}
}
if (best_div == 0) {
best_div = priv->max;
parent_round_rate = clk_round_rate(&priv->parent, 1);
if (IS_ERR_VALUE(parent_round_rate))
return parent_round_rate;
}
dev_dbg(clk->dev, "rate=%ld, best_rate=%ld, div=%d\n", rate, best_rate,
best_div);
return best_div;
}
static ulong clk_ti_divider_round_rate(struct clk *clk, ulong rate)
{
ulong parent_rate;
int div;
div = clk_ti_divider_best_div(clk, rate, &parent_rate);
if (div < 0)
return div;
return DIV_ROUND_UP(parent_rate, div);
}
static ulong clk_ti_divider_set_rate(struct clk *clk, ulong rate)
{
struct clk_ti_divider_priv *priv = dev_get_priv(clk->dev);
ulong parent_rate;
int div;
u32 val, v;
div = clk_ti_divider_best_div(clk, rate, &parent_rate);
if (div < 0)
return div;
if (clk->flags & CLK_SET_RATE_PARENT) {
parent_rate = clk_set_rate(&priv->parent, parent_rate);
if (IS_ERR_VALUE(parent_rate))
return parent_rate;
}
val = _get_val(priv->table, priv->div_flags, div);
v = readl(priv->reg);
v &= ~(priv->mask << priv->shift);
v |= val << priv->shift;
writel(v, priv->reg);
clk_ti_latch(priv->reg, priv->latch);
return clk_get_rate(clk);
}
static ulong clk_ti_divider_get_rate(struct clk *clk)
{
struct clk_ti_divider_priv *priv = dev_get_priv(clk->dev);
ulong rate, parent_rate;
unsigned int div;
u32 v;
parent_rate = clk_get_rate(&priv->parent);
if (IS_ERR_VALUE(parent_rate))
return parent_rate;
v = readl(priv->reg) >> priv->shift;
v &= priv->mask;
div = _get_div(priv->table, priv->div_flags, v);
if (!div) {
if (!(priv->div_flags & CLK_DIVIDER_ALLOW_ZERO))
dev_warn(clk->dev,
"zero divisor and CLK_DIVIDER_ALLOW_ZERO not set\n");
return parent_rate;
}
rate = DIV_ROUND_UP(parent_rate, div);
dev_dbg(clk->dev, "rate=%ld\n", rate);
return rate;
}
static int clk_ti_divider_request(struct clk *clk)
{
struct clk_ti_divider_priv *priv = dev_get_priv(clk->dev);
clk->flags = priv->flags;
return 0;
}
const struct clk_ops clk_ti_divider_ops = {
.request = clk_ti_divider_request,
.round_rate = clk_ti_divider_round_rate,
.get_rate = clk_ti_divider_get_rate,
.set_rate = clk_ti_divider_set_rate
};
static int clk_ti_divider_remove(struct udevice *dev)
{
struct clk_ti_divider_priv *priv = dev_get_priv(dev);
int err;
err = clk_release_all(&priv->parent, 1);
if (err) {
dev_err(dev, "failed to release parent clock\n");
return err;
}
return 0;
}
static int clk_ti_divider_probe(struct udevice *dev)
{
struct clk_ti_divider_priv *priv = dev_get_priv(dev);
int err;
err = clk_get_by_index(dev, 0, &priv->parent);
if (err) {
dev_err(dev, "failed to get parent clock\n");
return err;
}
return 0;
}
static int clk_ti_divider_of_to_plat(struct udevice *dev)
{
struct clk_ti_divider_priv *priv = dev_get_priv(dev);
struct clk_div_table *table = NULL;
u32 val, valid_div;
u32 min_div = 0;
u32 max_val, max_div = 0;
u16 mask;
int i, div_num;
priv->reg = dev_read_addr(dev);
dev_dbg(dev, "reg=0x%08lx\n", priv->reg);
priv->shift = dev_read_u32_default(dev, "ti,bit-shift", 0);
priv->latch = dev_read_s32_default(dev, "ti,latch-bit", -EINVAL);
if (dev_read_bool(dev, "ti,index-starts-at-one"))
priv->div_flags |= CLK_DIVIDER_ONE_BASED;
if (dev_read_bool(dev, "ti,index-power-of-two"))
priv->div_flags |= CLK_DIVIDER_POWER_OF_TWO;
if (dev_read_bool(dev, "ti,set-rate-parent"))
priv->flags |= CLK_SET_RATE_PARENT;
if (dev_read_prop(dev, "ti,dividers", &div_num)) {
div_num /= sizeof(u32);
/* Determine required size for divider table */
for (i = 0, valid_div = 0; i < div_num; i++) {
dev_read_u32_index(dev, "ti,dividers", i, &val);
if (val)
valid_div++;
}
if (!valid_div) {
dev_err(dev, "no valid dividers\n");
return -EINVAL;
}
table = calloc(valid_div + 1, sizeof(*table));
if (!table)
return -ENOMEM;
for (i = 0, valid_div = 0; i < div_num; i++) {
dev_read_u32_index(dev, "ti,dividers", i, &val);
if (!val)
continue;
table[valid_div].div = val;
table[valid_div].val = i;
valid_div++;
if (val > max_div)
max_div = val;
if (!min_div || val < min_div)
min_div = val;
}
max_val = max_div;
} else {
/* Divider table not provided, determine min/max divs */
min_div = dev_read_u32_default(dev, "ti,min-div", 1);
if (dev_read_u32(dev, "ti,max-div", &max_div)) {
dev_err(dev, "missing 'max-div' property\n");
return -EFAULT;
}
max_val = max_div;
if (!(priv->div_flags & CLK_DIVIDER_ONE_BASED) &&
!(priv->div_flags & CLK_DIVIDER_POWER_OF_TWO))
max_val--;
}
priv->table = table;
priv->min = min_div;
priv->max = max_div;
if (priv->div_flags & CLK_DIVIDER_POWER_OF_TWO)
mask = fls(max_val) - 1;
else
mask = max_val;
priv->mask = (1 << fls(mask)) - 1;
return 0;
}
static const struct udevice_id clk_ti_divider_of_match[] = {
{.compatible = "ti,divider-clock"},
{}
};
U_BOOT_DRIVER(clk_ti_divider) = {
.name = "ti_divider_clock",
.id = UCLASS_CLK,
.of_match = clk_ti_divider_of_match,
.of_to_plat = clk_ti_divider_of_to_plat,
.probe = clk_ti_divider_probe,
.remove = clk_ti_divider_remove,
.priv_auto = sizeof(struct clk_ti_divider_priv),
.ops = &clk_ti_divider_ops,
};
| 22.667539 | 78 | 0.685414 |
8951dce431453c1f9dd38d08bb27dc6d0559c684 | 406 | asm | Assembly | oeis/036/A036716.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/036/A036716.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/036/A036716.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A036716: a(n)=number of Gaussian integers z=a+bi satisfying n-1/2<|z|<=n+1/2, a>=0, 0<=b<=a.
; Submitted by Jamie Morken(w4)
; 1,2,2,3,5,4,6,6,7,9,8,10,9,12,12,11,15,15,15,15,15,19,18,19,19,22,21,21,24,22,26,25,24,27,29,29,29,29,32,30,34,32,34,35,34,37,35,39,39,40,40,41,44,40,43,45,43,48,43,50,48
seq $0,36705 ; Number of Gaussian integers z=a+bi satisfying n - 1/2 < |z| <= n + 1/2.
div $0,8
add $0,1
| 50.75 | 172 | 0.633005 |
263be644f442d276d4bc2fad57fea2a68f018190 | 3,510 | java | Java | workflow/commons/src/test/java/com/datastax/oss/dsbulk/workflow/commons/settings/ConnectorSettingsTest.java | tarzanek/dsbulk | 28eec419fc8548a739095176e7b7f6fc98aff58a | [
"Apache-2.0"
] | 37 | 2020-07-21T15:20:42.000Z | 2022-03-07T10:12:25.000Z | workflow/commons/src/test/java/com/datastax/oss/dsbulk/workflow/commons/settings/ConnectorSettingsTest.java | tarzanek/dsbulk | 28eec419fc8548a739095176e7b7f6fc98aff58a | [
"Apache-2.0"
] | 30 | 2020-07-21T15:23:37.000Z | 2022-03-28T08:03:26.000Z | workflow/commons/src/test/java/com/datastax/oss/dsbulk/workflow/commons/settings/ConnectorSettingsTest.java | tarzanek/dsbulk | 28eec419fc8548a739095176e7b7f6fc98aff58a | [
"Apache-2.0"
] | 18 | 2020-07-21T21:53:39.000Z | 2022-03-22T09:53:18.000Z | /*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.oss.dsbulk.workflow.commons.settings;
import static com.datastax.oss.dsbulk.tests.assertions.TestAssertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.datastax.oss.dsbulk.connectors.api.Connector;
import com.datastax.oss.dsbulk.connectors.csv.CSVConnector;
import com.datastax.oss.dsbulk.connectors.json.JsonConnector;
import com.datastax.oss.dsbulk.tests.utils.TestConfigUtils;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.junit.jupiter.api.Test;
class ConnectorSettingsTest {
private static final Config CONNECTOR_DEFAULT_SETTINGS =
TestConfigUtils.createTestConfig("dsbulk.connector");
@Test
void should_find_csv_connector_short_name() {
Config config =
ConfigFactory.parseString("name: csv, csv{url:\"file:///a/b.csv\"}")
.withFallback(CONNECTOR_DEFAULT_SETTINGS);
ConnectorSettings connectorSettings = new ConnectorSettings(config, true);
connectorSettings.init(true);
Connector connector = connectorSettings.getConnector();
assertThat(connector).isNotNull().isInstanceOf(CSVConnector.class);
assertThat(config.getConfig("csv"))
.hasPaths(
"url",
"fileNamePattern",
"recursive",
"maxConcurrentFiles",
"encoding",
"header",
"delimiter",
"quote",
"escape",
"comment",
"skipRecords",
"maxRecords")
.doesNotHavePath("csv");
}
@Test
void should_find_json_connector_short_name() {
Config config =
ConfigFactory.parseString("name: json, json{ url:\"file:///a/b.json\"}")
.withFallback(CONNECTOR_DEFAULT_SETTINGS);
ConnectorSettings connectorSettings = new ConnectorSettings(config, true);
connectorSettings.init(true);
Connector connector = connectorSettings.getConnector();
assertThat(connector).isNotNull().isInstanceOf(JsonConnector.class);
assertThat(config.getConfig("json"))
.hasPaths(
"url",
"fileNamePattern",
"recursive",
"maxConcurrentFiles",
"encoding",
"skipRecords",
"maxRecords",
"parserFeatures",
"generatorFeatures",
"prettyPrint")
.doesNotHavePath("json");
}
@Test
void should_fail_for_nonexistent_connector() {
assertThrows(
IllegalArgumentException.class,
() -> {
Config config = ConfigFactory.parseString("name: foo, foo {url:\"file:///a/b.txt\"}");
ConnectorSettings connectorSettings = new ConnectorSettings(config, true);
connectorSettings.init(true);
//noinspection ResultOfMethodCallIgnored
connectorSettings.getConnector();
},
"Cannot find connector 'foo'; available connectors are");
}
}
| 35.816327 | 96 | 0.676353 |
f07e0ced31d9f3b5a75c59dd3ef793ba14212ab0 | 2,831 | py | Python | tests/base.py | octue/octue-sdk-python | 31c6e9358d3401ca708f5b3da702bfe3be3e52ce | [
"MIT"
] | 5 | 2020-10-01T12:43:10.000Z | 2022-03-14T17:26:25.000Z | tests/base.py | octue/octue-sdk-python | 31c6e9358d3401ca708f5b3da702bfe3be3e52ce | [
"MIT"
] | 322 | 2020-06-24T15:55:22.000Z | 2022-03-30T11:49:28.000Z | tests/base.py | octue/octue-sdk-python | 31c6e9358d3401ca708f5b3da702bfe3be3e52ce | [
"MIT"
] | null | null | null | import os
import subprocess
import unittest
import uuid
import warnings
from tempfile import TemporaryDirectory, gettempdir
from octue.cloud.emulators import GoogleCloudStorageEmulatorTestResultModifier
from octue.mixins import MixinBase, Pathable
from octue.resources import Datafile, Dataset, Manifest
from tests import TEST_BUCKET_NAME
class MyPathable(Pathable, MixinBase):
pass
class BaseTestCase(unittest.TestCase):
"""Base test case for twined:
- sets a path to the test data directory
"""
test_result_modifier = GoogleCloudStorageEmulatorTestResultModifier(default_bucket_name=TEST_BUCKET_NAME)
setattr(unittest.TestResult, "startTestRun", test_result_modifier.startTestRun)
setattr(unittest.TestResult, "stopTestRun", test_result_modifier.stopTestRun)
def setUp(self):
# Set up paths to the test data directory and to the app templates directory
root_dir = os.path.dirname(os.path.abspath(__file__))
self.data_path = os.path.join(root_dir, "data")
self.templates_path = os.path.join(os.path.dirname(root_dir), "octue", "templates")
# Make unittest ignore excess ResourceWarnings so tests' console outputs are clearer. This has to be done even
# if these warnings are ignored elsewhere as unittest forces warnings to be displayed by default.
warnings.simplefilter("ignore", category=ResourceWarning)
super().setUp()
def callCli(self, args):
"""Utility to call the octue CLI (eg for a templated example) in a separate subprocess
Enables testing that multiple processes aren't using the same memory space, or for running multiple apps in
parallel to ensure they don't conflict
"""
call_id = str(uuid.uuid4())
tmp_dir_name = os.path.join(gettempdir(), "octue-sdk-python", f"test-{call_id}")
with TemporaryDirectory(dir=tmp_dir_name):
subprocess.call(args, cwd=tmp_dir_name)
def create_valid_dataset(self):
""" Create a valid dataset with two valid datafiles (they're the same file in this case). """
path_from = MyPathable(path=os.path.join(self.data_path, "basic_files", "configuration", "test-dataset"))
path = os.path.join("path-within-dataset", "a_test_file.csv")
files = [
Datafile(path_from=path_from, path=path, skip_checks=False),
Datafile(path_from=path_from, path=path, skip_checks=False),
]
return Dataset(files=files)
def create_valid_manifest(self):
""" Create a valid manifest with two valid datasets (they're the same dataset in this case). """
datasets = [self.create_valid_dataset(), self.create_valid_dataset()]
manifest = Manifest(datasets=datasets, keys={"my_dataset": 0, "another_dataset": 1})
return manifest
| 42.253731 | 118 | 0.716001 |
62059c4821c3317ae25a1c871edbbbd255141a28 | 852 | asm | Assembly | src/test/resources/library/io.asm | xCubeArrow/Cubelang | 602376489c0acbbb1f88fd97ee71d143e30cfd53 | [
"MIT"
] | null | null | null | src/test/resources/library/io.asm | xCubeArrow/Cubelang | 602376489c0acbbb1f88fd97ee71d143e30cfd53 | [
"MIT"
] | 1 | 2021-11-13T22:49:01.000Z | 2021-11-13T22:49:01.000Z | src/test/resources/library/io.asm | xCubeArrow/Cubelang | 602376489c0acbbb1f88fd97ee71d143e30cfd53 | [
"MIT"
] | null | null | null | extern putchar
extern printf
intPrintFormat db "%d", 10, 0
charPrintFormat db "%c", 10, 0
pointerPrintFormat db "%p", 10, 0
printI8:
sub rsp, 8
mov esi, edi
mov edi, intPrintFormat
xor al, al
call printf
add rsp, 8
ret
printI16:
sub rsp, 8
mov esi, edi
mov edi, intPrintFormat
xor al, al
call printf
add rsp, 8
ret
printI64:
sub rsp, 8
mov rsi, rdi
mov edi, intPrintFormat
xor al, al
call printf
add rsp, 8
ret
printChar:
sub rsp, 8
call putchar
mov rdi, 10
call putchar
add rsp, 8
ret
printI32:
sub rsp, 8
mov esi, edi
mov edi, intPrintFormat
xor al, al
call printf
add rsp, 8
ret
printPointer:
sub rsp, 8
mov esi, edi
mov edi, pointerPrintFormat
xor al, al
call printf
add rsp, 8
ret | 15.490909 | 33 | 0.596244 |
3ef445bc1f7ede22930eaefa6bfa2bc582e2bef0 | 2,467 | h | C | sodor/emulator/common/tracer.h | haojunliu/OpenFPGA | b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1 | [
"BSD-2-Clause"
] | 31 | 2016-02-15T02:57:28.000Z | 2021-06-02T10:40:25.000Z | archipelago/emulator/common/tracer.h | haojunliu/OpenFPGA | b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1 | [
"BSD-2-Clause"
] | null | null | null | archipelago/emulator/common/tracer.h | haojunliu/OpenFPGA | b0c4f27077f698aae59bbcbd3ca002f22ba2a5a1 | [
"BSD-2-Clause"
] | 6 | 2017-02-08T21:51:51.000Z | 2021-06-02T10:40:40.000Z | //************************************************************
// CS152 Lab 1: Tracer class for analyzing instruction mixes
//************************************************************
// TA : Christopher Celio
// Date : 2012 Spring
// Student :
// ****INSTRUCTIONS*****:
//
// Your job is to add new features to Tracer_t to provide more detailed
// information on some of the instructions being executed. Here are the
// following steps required to add a new "counter":
//
// Step 1. Add your counters to tracer.h
// Step 2. Initialize your counters to 0 in Tracer_t::start()
// Step 3. Increment your counters as appropriate in Tracer_t::tick()
// Step 4. Print out your counters in Tracer_t::print()
//
// You can grep for "Step" or "HERE" in tracer.h and tracer.cpp to find where
// your code goes.
#include <stdint.h>
#include <stdio.h>
#include "emulator.h"
class Tracer_t {
public:
// Tracer_t(dat_t<32>* _inst_ptr, dat_t<1>* _stats_reg, FILE* log);
Tracer_t(dat_t<32>* _inst_ptr, FILE* log);
void start();
void tick(bool inc_inst_count);
void stop();
void print();
private:
dat_t<32>* inst_ptr; // pointer to the Instruction Register in the processor
// dat_t<1>* stats_reg; // pointer to the StatsEnable co-processor register cr10.
// Allows the software to set when to start tracking stats
// by calling "li x1, 1; mtpcr cr10, x1".
FILE* logfile;
int paused;
struct
{
uint64_t cycles;
uint64_t inst_count;
uint64_t nop_count;
uint64_t bubble_count;
uint64_t ldst_count;
uint64_t arith_count;
uint64_t br_count;
uint64_t misc_count;
/* XXX Step 1: ADD MORE COUNTS HERE */
uint64_t load_count;
uint64_t store_count;
// etc.
} trace_data;
};
| 37.378788 | 94 | 0.452371 |
b5e3e70ce3c2cabc6efe3a52d7d5849f03f1310b | 4,186 | kt | Kotlin | Module/DebugTools/src/main/java/com/lwh/debugtools/ui/activity/home/DTHomeActivity.kt | l-w-h/DebugTools | cd9ccb97577f17d77884643942a0c642be03dae8 | [
"Apache-2.0"
] | 1 | 2019-11-29T04:10:32.000Z | 2019-11-29T04:10:32.000Z | Module/DebugTools/src/main/java/com/lwh/debugtools/ui/activity/home/DTHomeActivity.kt | l-w-h/DebugTools | cd9ccb97577f17d77884643942a0c642be03dae8 | [
"Apache-2.0"
] | null | null | null | Module/DebugTools/src/main/java/com/lwh/debugtools/ui/activity/home/DTHomeActivity.kt | l-w-h/DebugTools | cd9ccb97577f17d77884643942a0c642be03dae8 | [
"Apache-2.0"
] | null | null | null | package com.lwh.debugtools.ui.activity.home
import android.content.Context
import android.content.Intent
import android.view.View
import androidx.appcompat.app.AlertDialog
import com.lwh.debugtools.R
import com.lwh.debugtools.base.adapter.ViewPagerAdapter
import com.lwh.debugtools.base.listener.OnPageChangeListenerImpl
import com.lwh.debugtools.base.ui.HeaderFooterActivity
import com.lwh.debugtools.base.ui.RefreshFragment
import com.lwh.debugtools.db.DatabaseUtils
import com.lwh.debugtools.ui.fragment.error.ErrorFragment
import com.lwh.debugtools.ui.fragment.log.LogFragment
import com.lwh.debugtools.ui.fragment.request.RequestFragment
import kotlinx.android.synthetic.main.l_activity_home.*
/**
* @author lwh
* @Date 2019/10/21 9:41
* @description Debug Tools 首页(请求,日志,错误)
*/
class DTHomeActivity : HeaderFooterActivity(), OnPageChangeListenerImpl, View.OnClickListener {
private val fragments = ArrayList<RefreshFragment<*>>()
companion object {
fun startActivity(context: Context) {
val intent = Intent(context, DTHomeActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
context.startActivity(intent)
}
}
override fun initBefore() {
bodyLayout = R.layout.l_activity_home
}
override fun init() {
headerManager?.let {
it.setFuncAText(R.string.icon_delete)
it.setFuncAVisible(View.VISIBLE)
}
fragments.add(RequestFragment.newInstance())
fragments.add(LogFragment.newInstance())
fragments.add(ErrorFragment.newInstance())
view_pager.adapter = ViewPagerAdapter(supportFragmentManager, null, fragments)
view_pager.addOnPageChangeListener(this)
headerManager?.title = "Debug Tools"
ll_request.setOnClickListener(this)
ll_log.setOnClickListener(this)
ll_error.setOnClickListener(this)
selectorPage(0)
}
/**
* 重置选中按钮
*/
private fun resetNavView() {
icon_request.isChecked = false
tv_request.isChecked = false
icon_log.isChecked = false
tv_log.isChecked = false
icon_error.isChecked = false
tv_error.isChecked = false
}
/**
* 根据下标选中按钮
*/
private fun selectorPage(position: Int) {
resetNavView()
when (position) {
0 -> {
icon_request.isChecked = true
tv_request.isChecked = true
}
1 -> {
icon_log.isChecked = true
tv_log.isChecked = true
}
2 -> {
icon_error.isChecked = true
tv_error.isChecked = true
}
else -> {
}
}
}
override fun onClick(view: View?) {
resetNavView()
val position: Int = when (view?.id) {
R.id.ll_request -> {
0
}
R.id.ll_log -> {
1
}
R.id.ll_error -> {
2
}
else -> {
0
}
}
selectorPage(position)
view_pager.currentItem = position
}
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
selectorPage(position)
}
override fun funcAClick(v: View) {
val alertDialog: AlertDialog = AlertDialog.Builder(this)
.setTitle("删除数据")
.setMessage("确定要永久删除全部数据吗?")
.setCancelable(false)
.setPositiveButton("确定") { _, _ ->
val currentItem = view_pager.currentItem
when (currentItem) {
0 -> {
DatabaseUtils.deleteRequestTableData()
}
1 -> {
DatabaseUtils.deleteLogTableData()
}
2 -> {
DatabaseUtils.deleteErrorTableData()
}
}
fragments[currentItem].reLoadData()
}.setNegativeButton("取消", null)
.create()
alertDialog.show()
}
}
| 28.671233 | 95 | 0.573817 |
cf24b76e346ce013e3adc6823eb0afebb714f752 | 18,972 | css | CSS | img/portfolio/BayAreaWeddingFairs _ home_files/Or_NMPGe-t-.css | IrakozeLadouce/wedds-connector | 6247e2eda6f0f314f1b6b80317db4739ed0dd6db | [
"MIT"
] | null | null | null | img/portfolio/BayAreaWeddingFairs _ home_files/Or_NMPGe-t-.css | IrakozeLadouce/wedds-connector | 6247e2eda6f0f314f1b6b80317db4739ed0dd6db | [
"MIT"
] | null | null | null | img/portfolio/BayAreaWeddingFairs _ home_files/Or_NMPGe-t-.css | IrakozeLadouce/wedds-connector | 6247e2eda6f0f314f1b6b80317db4739ed0dd6db | [
"MIT"
] | null | null | null | ._3u55{display:inline-block;vertical-align:middle}._3qh2{animation:rotateSpinner 1.2s linear infinite}@keyframes rotateSpinner{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}
._51l0 ._1r_9{-webkit-font-smoothing:antialiased;z-index:202}._3v5f ._1r_9{-webkit-font-smoothing:antialiased;z-index:202}._1r_9 ._53ij{border:0;border-radius:6px;box-shadow:0 0 0 1px rgba(0, 0, 0, .1), 0 1px 10px rgba(0, 0, 0, .35)}.safari ._1r_9 ._53ij{-webkit-backdrop-filter:blur(5px);background:rgba(255, 255, 255, .95)}._1r_9 ._5v-0{padding-bottom:14px}._1r_9 ._53il{padding-top:14px}._1r_9 ._53im{padding-right:14px}._1r_9 ._53ik{padding-bottom:14px}._1r_9 ._53in{padding-left:14px}._1r_9 ._53il ._53io{background-image:url(/rsrc.php/v3/yH/r/ymaruJl2Pjp.png);background-repeat:no-repeat;background-size:auto;background-position:0 -635px;height:8px;top:7px;width:16px}._1r_9 ._53im ._53io{background-image:url(/rsrc.php/v3/yH/r/ymaruJl2Pjp.png);background-repeat:no-repeat;background-size:auto;background-position:-51px -431px;height:16px;right:7px;width:8px}._1r_9 ._53ik ._53io{background-image:url(/rsrc.php/v3/yH/r/ymaruJl2Pjp.png);background-repeat:no-repeat;background-size:auto;background-position:-40px -359px;bottom:7px;height:8px;width:16px}._1r_9 ._53in ._53io{background-image:url(/rsrc.php/v3/yH/r/ymaruJl2Pjp.png);background-repeat:no-repeat;background-size:auto;background-position:-51px -414px;height:16px;left:7px;width:8px}
._30ss{bottom:0;display:flex;flex-direction:column;height:100%;justify-content:flex-end;position:absolute;-webkit-tap-highlight-color:transparent;width:100%}._6atm{background-color:#fff;border-radius:12px;bottom:0;position:absolute}._6atk{transition:height 200ms linear}._6atl{height:480px !important;width:360px}._6atr{height:100%;width:100%}._6atn{opacity:0}._6ato{bottom:0;opacity:1;position:absolute;transition:opacity 200ms cubic-bezier(1, .16, .92, -0.06)}._6atp{opacity:1}._6atq{bottom:0;opacity:0;position:absolute;transition:opacity 200ms cubic-bezier(.03, .95, 0, 1)}._3gog{background-color:#fff;box-shadow:0 1pt 12pt rgba(0, 0, 0, .15);display:flex;flex-direction:column;font-family:'Helvetica Neue', 'HelveticaNeue', Helvetica, Arial, sans-serif;overflow:hidden;-webkit-overflow-scrolling:touch;position:relative}._6ati{height:100%;width:360px}._6atj{height:100%;width:100%}._2t-5{align-items:center;background-color:rgba(0, 0, 0, .1);border-radius:50%;cursor:pointer;display:flex;height:18pt;justify-content:center;outline:none;width:18pt}._4bqf{cursor:pointer;transition:opacity .2s}._4bqf:active{opacity:.2;transition-duration:0s}._6i-7{background-color:#fff;border-radius:18px;box-shadow:0 1pt 12pt rgba(0, 0, 0, .15);font-family:'Helvetica Neue', 'HelveticaNeue', Helvetica, Arial, sans-serif;font-size:16px;left:0;padding:12px;position:absolute;right:24px;top:auto;width:auto}._6i-8{position:relative}._6i-9{font-weight:bold}._6lg-{align-items:center;display:flex;height:16px;justify-content:center;left:-12px;position:absolute;top:-12px;width:16px}._6k7_{background-color:#fff;bottom:0;display:flex;flex-direction:column;font-family:'Helvetica Neue', 'HelveticaNeue', Helvetica, Arial, sans-serif;height:100%;justify-content:center;left:0;position:fixed;width:100%}._6k80{left:12px;position:absolute;top:12px}._6k81{align-items:center;display:flex;flex-direction:column;justify-content:center}._6k82{margin-bottom:32px}._6k83{color:rgba(0, 0, 0, .6);font-size:14px;line-height:20px;text-align:center}._6k84{background-color:#0084ff;border-radius:12px;color:#fff;display:flex;font-size:17px;justify-content:center;line-height:20px;margin:16px 0;padding:12px;width:80%}._6k85{height:20px;margin-right:6px;width:20px}._6k86{color:rgba(0, 0, 0, .3);font-size:14px;line-height:18px}._6taj{background-color:#fff;border-radius:18px;box-shadow:0 1pt 12pt rgba(0, 0, 0, .15);font-family:'Helvetica Neue', 'HelveticaNeue', Helvetica, Arial, sans-serif;font-size:16px;left:0;margin:auto;max-width:65%;padding:16px;position:absolute;right:0;top:48px;width:fit-content}
._j68{background-color:#fff;border-radius:12px;bottom:0;box-shadow:0 1pt 12pt rgba(0, 0, 0, .15);display:flex;flex-direction:column;font-family:HelveticaNeue-Medium, 'Helvetica Neue', 'HelveticaNeue', Helvetica, Arial, sans-serif;height:100%;word-wrap:break-word;position:absolute;text-align:center;width:360px}._j68 .fillerDiv{flex-grow:1}._j68 .promptHeaderContainer{display:flex;justify-content:flex-end;padding:12px 12px;position:relative}._j68 .promptHeaderContainer .closeButtonContainer{left:9pt;position:absolute;top:9pt}._j68 .promptHeaderContainer .profilePicture{border-radius:50%;height:48px;width:48px}._j68 .promptHeaderContainer .promptTextContainer{margin-right:12px;text-align:left;width:236px}._j68 .promptHeaderContainer .promptHeader{font-size:16px;line-height:18px;margin-bottom:10px}._j68 .promptHeaderContainer .promptSubheader{font-family:'Helvetica Neue', 'HelveticaNeue', Helvetica, Arial, sans-serif;font-size:12px;line-height:14px}._j68 .promptSubheader .profilePictureContainer{float:left}._j68 .promptSubheader .profilePicture{border-radius:50%;height:20px;width:20px}._j68 .promptSubheader .username{color:rgba(0, 0, 0, .3);display:inline-block;line-height:20px;margin:0 6px;max-width:140px;overflow:hidden;text-overflow:ellipsis;vertical-align:middle;white-space:nowrap}._j68 .promptSubheader .notYouLink{color:rgba(0, 0, 0, .3);cursor:pointer;display:inline-block;line-height:20px;text-decoration:underline;vertical-align:middle}._j68 .notYouLink a:visited{color:rgba(0, 0, 0, .3)}._j68 .promptButton{cursor:pointer;font-size:18px;line-height:21px;outline:none;padding-bottom:13px;padding-top:14px}._j68 .promptButtonContainer{border-top:.75pt solid rgba(0, 0, 0, .1)}._7acu{background-color:#fff;border-radius:12px;bottom:0;box-shadow:0 1pt 12pt rgba(0, 0, 0, .15);display:flex;flex-direction:column;font-family:SF Pro Text, Helvetica Neue, Segoe UI, Helvetica, Arial, sans-serif;height:100%;position:absolute;width:360px}._7acu .fillerDiv{flex-grow:1}._7acu .promptHeaderContainer{border-bottom:rgba(0, 0, 0, .03);border-radius:12px 12px 0 0;box-shadow:0 -5px 20px 1px rgba(0, 0, 0, .03) inset;display:flex;flex-direction:row;padding:20px 10px;position:relative}._7acu .profilePictureContainer{bottom:18px;position:absolute}._7acu .promptHeaderAndBubbleContainer{display:flex;flex-direction:column;justify-content:left;margin-left:40px;margin-right:10px}._7acu .promptHeaderContainer .profilePicture{border:.5pt solid rgba(0, 0, 0, .10);border-radius:50%;height:20pt;width:20pt}._7acu .promptHeaderAndBubbleContainer .promptHeaderText{color:rgba(0, 0, 0, .50);font-size:8pt;margin-bottom:4px;margin-left:12px}._7acu .promptHeaderAndBubbleContainer .promptTextBubble{background-color:#f1f0f0;border-radius:1.3em;color:rgba(0, 0, 0, 1);font-size:11pt;max-width:270px;padding:8px 12px;text-align:left;width:fit-content}._7acu .promptFooterContainer{display:flex;flex-direction:column;padding:12px}._7acu .promptFooterContainer .promptButton{border-radius:10px;color:#fff;display:flex;font-size:11pt;justify-content:center;margin:auto;max-width:336px;outline:none;padding:8px 30px}._7acu .promptFooterContainer .promptButton .messengerIcon{margin-right:6px}._7acu .promptFooterContainer .notYouLink{color:rgba(0, 0, 0, .40);cursor:pointer;line-height:20px;padding-top:4px;text-align:center;text-decoration:underline}._7acu .promptFooterContainer .subButtonText{color:rgba(0, 0, 0, .40);line-height:20px;padding-top:4px;text-align:center}
._f_0{align-items:center;border-bottom:1pt solid rgba(0, 0, 0, .1);display:flex;flex-basis:10%;height:10%;justify-content:space-between;max-height:48pt;min-height:36pt;text-align:center;width:100%}._1qd1{margin-left:9pt;order:1}._hov{display:flex;flex-direction:column;flex-grow:1;height:100%;justify-content:center;margin-left:3pt;margin-right:3pt;order:2}._how{font-family:HelveticaNeue-Medium, 'Helvetica Neue', 'HelveticaNeue', Helvetica, Arial, sans-serif;font-size:12pt;line-height:16.5pt}._hox{color:rgba(0, 0, 0, .5);font-size:9pt;line-height:10.5pt}._424s{flex:1 1 auto;height:80%;overflow-y:auto;position:relative;word-wrap:break-word}._424s .preventScrollOverflow{overflow:hidden}._424s .conversationContainer{margin:7.5pt}._424s .datebreak{margin:10px 0}._424s .logMessage{color:rgba(0, 0, 0, .40);font-size:9pt;margin:9pt 1.5pt;text-align:center}._424s .spinner{position:relative;text-align:center;top:50%}._7982{border-bottom:1pt solid rgba(0, 0, 0, .1);display:block}._7983{display:block;height:55px;margin:0 10px 10px 15px;position:relative}._7983 .iconContainer{background-color:rgba(0, 0, 0, .04);border-radius:30px;float:left;height:50px;margin:8px 10px 5px 0;width:50px}._7983 .icon{margin:auto;padding:6.5px}._7983 .text{float:right;font-size:14px;margin:16px 0 12px;position:absolute;text-align:left;vertical-align:middle;width:75%}._7983 .isIpad.text{margin-top:25px}._796l{background-color:rgba(0, 0, 0, .07);border-radius:5px;display:block;margin:0 12px 10px 12px;padding:10px;text-align:center}._796l .text{font-size:14px;padding-top:3px}._4xkn{margin-bottom:7.5pt;position:relative}._4xkn .profilePictureColumn{bottom:0;position:absolute}._4xkn .profilePicture{border-radius:50%;height:22.5pt;width:22.5pt}._4xkn .messages{margin-left:27pt;margin-right:3.75pt}._2a0-{position:relative}._21c3 .datebreak{margin:2px 30px 2px 0}._4xko{border-radius:3pt;clear:both;display:block;font-size:12pt;line-height:15pt;margin:1pt 0;max-width:88%;outline:none;padding:6pt 9pt}._4xkr{border-bottom-right-radius:1.3em;border-top-right-radius:1.3em;color:rgba(0, 0, 0, 1);float:left}._4xkr a,._4xkr a:visited{color:rgba(0, 0, 0, 1);text-decoration:underline}._21c3:first-of-type ._2a0-:first-of-type ._4xkr:first-of-type,._21c3:first-of-type ._2a0-:first-of-type ._4xkr:first-of-type ._2k7x:first-child{border-top-left-radius:1.3em}._21c3:last-of-type ._2a0-:last-of-type ._4xkr:last-of-type,._21c3:last-of-type ._2a0-:last-of-type ._4xkr:last-of-type ._2k7x:last-child{border-bottom-left-radius:1.3em}._4xks{border-bottom-left-radius:1.3em;border-top-left-radius:1.3em;color:#fff;float:right;position:relative;right:8px}._4xks a,._4xks a:visited{color:#fff;text-decoration:underline}._21c3:first-of-type ._2a0-:first-of-type ._4xks:first-of-type,._2a0-:first-of-type ._4xks:first-of-type ._2k7x:first-child{border-top-right-radius:1.3em}._21c3:last-of-type ._2a0-:last-of-type ._4xks:last-of-type,._21c3:last-of-type ._2a0-:last-of-type ._4xks:last-of-type ._2k7x:last-child{border-bottom-right-radius:1.3em}._4xks._2k7w{right:8px}._2k7x{border:.75px solid rgba(0, 0, 0, .10);overflow:hidden}._4xks ._2k7x{border-bottom-left-radius:1.3em;border-top-left-radius:1.3em;margin-bottom:3px}._4xkr ._2k7x{border-bottom-right-radius:1.3em;border-top-right-radius:1.3em;margin-bottom:3px}._4xks ._2k7x:nth-last-child(1),._4xkr ._2k7x:nth-last-child(1){margin-bottom:0}._4xko._2k7w{background:none;max-width:97%;padding:0}._2k7y{max-width:100%;vertical-align:middle}._46jp{font-size:12pt;line-height:15pt;max-width:100%;padding:6pt 9pt}._4xko._gb1{background:none;padding-left:0;padding-right:0}._4xko div[role='img'],._4xko div[tabIndex='0']{outline:none !important}._21c4{bottom:-1px;clear:both;float:right;position:absolute;right:-9px}._21c5{border-radius:50%;display:inline-block;height:15px;vertical-align:middle;width:15px}._21c6{background:none;border:1px solid currentColor;border-radius:50%;bottom:-1px;box-sizing:border-box;color:currentColor;display:inline-block;height:10px;position:absolute;right:-4px;vertical-align:middle;width:10px}._21c6 ._21c7{border:1px solid currentColor;border-width:0 0 1px 1px;display:block;height:1px;margin-left:3px;margin-top:4px;transform:rotate(-45deg);transform-origin:0% 100%;width:4px}._21c8{background-color:currentColor}._6934{clear:both;color:#f03d25;float:right;font-size:10px;margin-bottom:5px;opacity:1}._6934 .error{background-image:url(/rsrc.php/v3/y4/r/wULFWkmGcxL.png);background-repeat:no-repeat;background-size:auto;background-position:-34px -198px;border:none;bottom:1px;cursor:pointer;position:relative}._6934.noDisplay{opacity:0;position:fixed}._21c8 ._21c7{color:#fff}@keyframes fadeIn{0%{opacity:0}100%{opacity:1}}._1qd3{margin-right:9pt;order:3}._17l7{border-radius:50%;cursor:pointer;outline:none}._4fsi{background-color:#fff;position:absolute;width:100%;z-index:100}._4fsj{flex-grow:1;outline:none;text-align:left}._2jjx{align-items:center;background-color:#fff;border-bottom:1pt solid rgba(0, 0, 0, .1);cursor:pointer;display:flex;font-size:12pt;height:36pt;line-height:14.25pt;outline:none;padding-left:12pt;padding-right:12pt}._2jjx a:hover{text-decoration:none}._13y8{background-color:#f1f0f0;border-radius:1.3em;float:left}._13y8 ._5pd7{animation-name:messengerTypingAnimation;background-color:rgba(0, 0, 0, .60);border-radius:50%;height:6px;margin-right:4px;vertical-align:middle;width:6px}._13y8 ._5pd7:last-child{margin-right:0}@keyframes messengerTypingAnimation{0%{transform:translateY(0px)}28%{transform:translateY(-6px)}44%{transform:translateY(0px)}}._2oap{color:#fff;font-family:'Helvetica Neue', 'HelveticaNeue', Helvetica, Arial, sans-serif;font-size:12px;height:35px;line-height:35px;text-align:center}._2oap .connected{background-color:#4bcc1f;height:100%}._2oap .connecting{background-color:#fc0;height:100%}._2oap .connecting .connectingSpinner{margin-right:6px}._2oap .disconnected{background-color:#f03d25;height:100%}._6b7s{width:260px}._6bxn{width:260px}._6bxo{color:rgba(0, 0, 0, 1);display:inline-block;font-weight:bold}._6bxp{color:rgba(0, 0, 0, .40);display:inline-block}._6bxp a,._6bxp a:visited{color:rgba(0, 0, 0, .40)}._6bxq{color:rgba(0, 0, 0, .40);display:inline-block;font-size:9pt}._6bxq a,._6bxq a:visited{color:rgba(0, 0, 0, .40)}._6biu{margin-left:13px;margin-right:13px;padding-bottom:10px;text-align:center}._6biq{background:#fff;border-radius:1.3em;cursor:pointer;display:inline-block;font-size:12pt;line-height:15pt;margin-right:10px;outline:none;padding:6px}._6bir{border:1px solid}._6bit{border:1px solid rgba(0, 0, 0, .40);color:rgba(0, 0, 0, .40)}._6bm0{border-radius:50%;height:20px;margin-right:5px;vertical-align:middle;width:20px}._6bis{padding-right:12px}._6d42{display:flex;flex-direction:column}._6d45{align-self:center;font-size:16px;height:44px;line-height:44px;outline:none;text-align:center;width:100%}._6d44{font-weight:bold}._6d46{border-top:1px solid rgba(0, 0, 0, .10);cursor:pointer;position:relative}._6d46 a,._6d46 a:visited{text-decoration:none}._6d43{left:0;margin:7px 6px;position:absolute;top:0}._6d4a{margin:7px;position:absolute;right:0;top:0}._6d49{outline:none}._6d48{display:block}._6d47{color:rgba(0, 0, 0, .40);cursor:pointer}._6d5w{display:block}._6d5w._6d5x{text-decoration:none}._6d5y{display:inline-block;height:16px;margin-right:6px;vertical-align:text-bottom;width:16px}._6d5z{background-image:url(/rsrc.php/v3/y4/r/wULFWkmGcxL.png);background-repeat:no-repeat;background-size:auto;background-position:-17px -334px}._6d5-{background-image:url(/rsrc.php/v3/y4/r/wULFWkmGcxL.png);background-repeat:no-repeat;background-size:auto;background-position:0 -351px}._6ir3{display:block;font-size:12pt;line-height:15pt;text-align:center;width:260px}._6ir3 a{text-decoration:none}._6ir3 a:hover{text-decoration:none}._6ir5{border-top:1px solid rgba(0, 0, 0, .10)}._6isd{border-top:none}._6ir6{color:rgba(0, 0, 0, .40);cursor:pointer}._6ir4{display:inline-block;height:100%;padding-bottom:6pt;padding-top:6pt;width:100%}._6j2i{width:260px}._6j0s{background-size:cover;border-top-left-radius:1.3em;border-top-right-radius:1.3em;display:block}._6j0r{background-size:cover;display:block}._6j2g{border-top:1px solid rgba(0, 0, 0, .10);padding:8px 12px;text-overflow:ellipsis}._6j0t{font-weight:bold}._6j0u{color:rgba(0, 0, 0, .40);padding-top:4px}._6j0y{font-size:10.5pt;padding-top:4px}._6j0y a,._6j0y a:visited{color:rgba(0, 0, 0, .40)}._6j0z{visibility:hidden}._6j0v{position:relative}._6j0w{max-height:39px;overflow:hidden;visibility:hidden}._6j0x{position:absolute;top:0}._6j2h{border:.75px solid rgba(0, 0, 0, .10);border-radius:1.3em;margin-right:10px;overflow:hidden;white-space:normal}
._336a{border-radius:0 0 12px 12px;border-top:1px solid rgba(0, 0, 0, .10);width:100%}._4zbw{display:flex}._kmd{align-items:center;display:flex;flex:0 0 auto;font-size:12pt;height:48px;line-height:24pt;margin-right:6px}._64mk{align-items:center;cursor:pointer;display:flex;justify-content:center;margin:3px 0 3px 6px;outline:none;-webkit-user-select:none;width:32px}._68t0{margin-top:3px}._64ml{margin-top:2px}._2ez5{background-image:url(/rsrc.php/v3/y4/r/wULFWkmGcxL.png);background-repeat:no-repeat;background-size:auto;background-position:0 -127px;height:24px;overflow:hidden;position:relative;width:24px}._2ez6{bottom:0;cursor:inherit;font-size:1000px !important;height:300px;margin:0;opacity:0;padding:0;position:absolute;right:0}._4fwe{flex:1 0 auto}._4fwe ._58ak{border-style:none;padding:12pt 0 12pt 9pt;width:100%}._4fwe ._58al{font-size:12pt}._4fwe ._58al::-webkit-input-placeholder{color:#90949c}._661n{cursor:pointer;margin-left:12px;margin-top:13px;outline:none;-webkit-user-select:none}._664i{background-color:#f9faf9}._664k{color:#90949c;flex:1 1 auto;font-size:12pt;overflow:hidden;padding:10pt 9pt;text-overflow:ellipsis;white-space:nowrap}
._1i69{display:flex;flex-direction:column}._2l9v{color:#f03d25;font-size:12px;margin:12px 12px 0 12px}._2l9u{display:flex;flex-direction:row;flex-wrap:wrap;padding:0 12px}._1i5v{margin-right:10px;margin-top:12px;position:relative}._3l_i{background-position:50% 50%;background-repeat:no-repeat;background-size:cover;border-radius:4px;min-height:54px;min-width:54px}._3l_m{border:1px solid #dadcde;border-radius:12px;display:flex;max-width:154px;min-height:54px;overflow:hidden}._3l_l{align-items:center;display:flex;height:54px;justify-content:center;width:48px}._3l_n{display:flex;flex-direction:column;flex-grow:1;font-size:14px;justify-content:center;max-width:100px;padding-left:6px;width:100px}._3l_o{font-weight:600}._3l_p{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}._1i63{bottom:0;left:0;margin:auto;position:absolute;right:0;top:0}._3l_j{background-color:#fff;border:1px solid #fff;border-radius:50% 50%;cursor:pointer;outline:none;position:absolute;right:4px;top:4px}._3l_k{background-image:url(/rsrc.php/v3/y4/r/wULFWkmGcxL.png);background-repeat:no-repeat;background-size:auto;background-position:-25px -163px;height:12px;width:12px}._3l_q{background-image:url(/rsrc.php/v3/y4/r/wULFWkmGcxL.png);background-repeat:no-repeat;background-size:auto;background-position:0 -198px;height:16px;width:16px}
._1ift{display:inline-block;pointer-events:none;vertical-align:middle}._2560{height:16px;margin:0 1px 0 1px;width:16px}._19_s{height:128px;margin:0 1px 0 1px;width:128px}._1ifu{height:32px;margin:0 1px 0 1px;width:32px}._19_r{height:64px;margin:0 1px 0 1px;width:64px}._5m3a{height:1em;margin:0 1px 0 1px}
#bootloader_XI0Yw{height:42px;}.bootloader_XI0Yw{display:block!important;} | 1,897.2 | 8,631 | 0.793591 |
9d725982bd52176029ce6e59d58617f6c33a1135 | 1,061 | asm | Assembly | _build/dispatcher/jmp_ippsSHA256Unpack_cb89815c.asm | zyktrcn/ippcp | b0bbe9bbb750a7cf4af5914dd8e6776a8d544466 | [
"Apache-2.0"
] | 1 | 2021-10-04T10:21:54.000Z | 2021-10-04T10:21:54.000Z | _build/dispatcher/jmp_ippsSHA256Unpack_cb89815c.asm | zyktrcn/ippcp | b0bbe9bbb750a7cf4af5914dd8e6776a8d544466 | [
"Apache-2.0"
] | null | null | null | _build/dispatcher/jmp_ippsSHA256Unpack_cb89815c.asm | zyktrcn/ippcp | b0bbe9bbb750a7cf4af5914dd8e6776a8d544466 | [
"Apache-2.0"
] | null | null | null | extern m7_ippsSHA256Unpack:function
extern n8_ippsSHA256Unpack:function
extern y8_ippsSHA256Unpack:function
extern e9_ippsSHA256Unpack:function
extern l9_ippsSHA256Unpack:function
extern n0_ippsSHA256Unpack:function
extern k0_ippsSHA256Unpack:function
extern ippcpJumpIndexForMergedLibs
extern ippcpSafeInit:function
segment .data
align 8
dq .Lin_ippsSHA256Unpack
.Larraddr_ippsSHA256Unpack:
dq m7_ippsSHA256Unpack
dq n8_ippsSHA256Unpack
dq y8_ippsSHA256Unpack
dq e9_ippsSHA256Unpack
dq l9_ippsSHA256Unpack
dq n0_ippsSHA256Unpack
dq k0_ippsSHA256Unpack
segment .text
global ippsSHA256Unpack:function (ippsSHA256Unpack.LEndippsSHA256Unpack - ippsSHA256Unpack)
.Lin_ippsSHA256Unpack:
db 0xf3, 0x0f, 0x1e, 0xfa
call ippcpSafeInit wrt ..plt
align 16
ippsSHA256Unpack:
db 0xf3, 0x0f, 0x1e, 0xfa
mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc]
movsxd rax, dword [rax]
lea r11, [rel .Larraddr_ippsSHA256Unpack]
mov r11, qword [r11+rax*8]
jmp r11
.LEndippsSHA256Unpack:
| 27.205128 | 91 | 0.792648 |
04067c3bed680e8d2d619338541549a5e5fdba5c | 274 | js | JavaScript | index.js | buschtoens/fix-ember-component-css | 4eddc4b5e04175fa23c77f17d260fbcac39364ad | [
"MIT"
] | null | null | null | index.js | buschtoens/fix-ember-component-css | 4eddc4b5e04175fa23c77f17d260fbcac39364ad | [
"MIT"
] | null | null | null | index.js | buschtoens/fix-ember-component-css | 4eddc4b5e04175fa23c77f17d260fbcac39364ad | [
"MIT"
] | null | null | null | /* jshint node: true */
'use strict';
module.exports = {
name: 'fix-ember-component-css',
setupPreprocessorRegistry: function(type, registry) {
registry.add('css', {
ext: ['dummy'],
toTree: function(tree) {
return tree;
}
})
}
};
| 17.125 | 55 | 0.565693 |
2f1eac3682e91c44b5663ae8dec7fbd370c029d5 | 3,949 | php | PHP | views/renewal/renewalstatus.php | jaredespineli/bpls | 2060e00367c77f0a04ed957bcd67160d75a67fba | [
"BSD-3-Clause"
] | null | null | null | views/renewal/renewalstatus.php | jaredespineli/bpls | 2060e00367c77f0a04ed957bcd67160d75a67fba | [
"BSD-3-Clause"
] | null | null | null | views/renewal/renewalstatus.php | jaredespineli/bpls | 2060e00367c77f0a04ed957bcd67160d75a67fba | [
"BSD-3-Clause"
] | null | null | null | <style type="text/css">
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: center;
padding: 2px;
}
</style>
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;
use app\models\Business;
use app\models\Document;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $searchModel app\models\PaymentSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Business Renewal Status';
$this->params['breadcrumbs'][] = $this->title;
// $modelBusiness = Business::find()
// ->where(['business_id' => $modelBusiness->business_id])
// ->one();
?>
<div class="renewal-status">
<div>
<h3><?= Html::encode('Business Name: ' . $this->title) ?></h3>
</div>
<br/>
<br/>
<br/>
<div>
<?php
//echo "Assessed Real Property Number: <strong>" . $model->arp_no . "</strong><br>";
echo "Property Owner: <strong>" . $modelBusiness->president_name . "</strong><br>";
echo "<table>
<tr>
<th>Requirements</th>
<th>Status</th>
</tr>
<tr>
<td>Payment</td>";
if(trim($modelPayment->payment_status, " ") == 'Paid'){
echo "<td>". $modelPayment->payment_status ."</td>";
}else{
echo "<td>" . Html::a('Pending', ['payment/paytable', 'id' => $modelPayment->payment_id], ['class' => 'btn btn-primary']) . "</td>";
}
echo "</tr>
<tr>
<td>Documents</td>";
if(trim($modelDoc->document_status, " ") == 'Approved'){
echo "<td>". $modelDoc->document_status ."</td>";
}else{
echo "<td>" . Html::a('Pending', ['business/verifydoc', 'id' => $modelDoc->document_id], ['class' => 'btn btn-primary']) . "</td>";
}
echo "</tr>
<tr>
<td>Business Status</td>";
echo "<td>" . $model->business_status . "</td>";
// date_default_timezone_set('Asia/Manila');
// $yearnow = date('Y');
// if($modelApproval->next_renewal_date > $yearnow){
// $modelBusiness->isActive = 0;
// $modelBusiness->business_status = "Inactive";
// echo "<td>". $modelBusiness->business_status ."</td>";
// }else{
// $modelBusiness->isActive = 1;
// $modelBusiness->business_status = "Active";
// echo "<td>". $modelBusiness->business_status ."</td>";
// }
echo "</tr>
</table>";
echo "<br>";
echo "<br>";
if((trim($modelPayment->payment_status, " ") == 'Paid') && trim($modelDoc->document_status, " ") == 'Approved' && (trim($model->business_status, " ") == 'Inactive')){?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'received_by')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Renew Business Permit',['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php } ?>
</div>
| 33.752137 | 203 | 0.416814 |
74124b701266cb4c3daecc1aafcaba7719efe366 | 2,971 | h | C | simd_sys_core/include/simd_sig_dmeu_data.h | timurkelin/simsimd | 79431b70cca50a995f2a1f12b3f5abe26e574096 | [
"MIT"
] | 14 | 2019-07-16T22:14:21.000Z | 2021-09-26T10:20:48.000Z | simd_sys_core/include/simd_sig_dmeu_data.h | timurkelin/simsimd | 79431b70cca50a995f2a1f12b3f5abe26e574096 | [
"MIT"
] | null | null | null | simd_sys_core/include/simd_sig_dmeu_data.h | timurkelin/simsimd | 79431b70cca50a995f2a1f12b3f5abe26e574096 | [
"MIT"
] | 3 | 2020-03-20T02:34:39.000Z | 2020-06-28T19:55:28.000Z | /*
* simd_sig_dmeu_data.h
*
* Description:
* Declaration of the DM/EU data type and signal
*
*/
#ifndef SIMD_SYS_CORE_INCLUDE_SIMD_SIG_DMEU_DATA_H_
#define SIMD_SYS_CORE_INCLUDE_SIMD_SIG_DMEU_DATA_H_
#include <string>
#include <iostream>
#include <complex>
#include <systemc>
#include "simd_report.h"
namespace simd {
class simd_sig_dmeu_data_c; // Forward declaration
} // namespace simd
namespace sc_core {
void sc_trace(
sc_core::sc_trace_file* tf,
const simd::simd_sig_dmeu_data_c& sig,
const std::string& name );
} // namespace sc_core
namespace simd {
typedef std::complex<double> simd_dmeu_smp_t;
class simd_dmeu_slot_t {
public:
bool ena = false;
simd_dmeu_smp_t smp = simd_dmeu_smp_t( 0.0, 0.0 );
};
class simd_dmeu_data_c {
public:
const static std::size_t dim = 4;
simd_dmeu_data_c() {
for( std::size_t idx = 0; idx < dim; idx ++ ) {
slot[idx].smp = simd_dmeu_smp_t( 0.0, 0.0 );
slot[idx].ena = false;
}
}
simd_dmeu_slot_t& operator [](const std::size_t idx) {
if(( idx < 0 ) || ( idx >= dim )) {
SIMD_REPORT_ERROR( "simd::chn_dmeu_data" ) << "Index is out of bounds";
}
return slot[idx];
}
simd_dmeu_slot_t operator [](const std::size_t idx) const {
if(( idx < 0 ) || ( idx >= dim )) {
SIMD_REPORT_ERROR( "simd::chn_dmeu_data" ) << "Index is out of bounds";
}
return slot[idx];
}
simd_dmeu_data_c& operator = (
const simd_dmeu_data_c& rhs );
bool operator == (
const simd_dmeu_data_c& rhs) const;
private:
simd_dmeu_slot_t slot[dim];
};
std::ostream& operator << (
std::ostream& os,
const simd_sig_dmeu_data_c& sig );
class simd_sig_dmeu_data_c {
private:
simd_dmeu_data_c data;
bool tr_data0_en, tr_data1_en, tr_data2_en, tr_data3_en;
double tr_data0_re, tr_data1_re, tr_data2_re, tr_data3_re;
double tr_data0_im, tr_data1_im, tr_data2_im, tr_data3_im;
public:
// Required for the assignment operations
simd_sig_dmeu_data_c& set(
const simd_dmeu_data_c& rhs );
const simd_dmeu_data_c& get(
void ) const;
// Required by sc_signal<> and sc_fifo<>
simd_sig_dmeu_data_c& operator = (
const simd_sig_dmeu_data_c& rhs );
// Required by sc_signal<>
bool operator == (
const simd_sig_dmeu_data_c& rhs) const;
friend void sc_core::sc_trace(
sc_core::sc_trace_file* tf,
const simd::simd_sig_dmeu_data_c& sig,
const std::string& name );
friend std::ostream& operator << (
std::ostream& os,
const simd_sig_dmeu_data_c& sig );
}; // class simd_sig_dmeu_data_c
} // namespace simd
#endif /* SIMD_SYS_CORE_INCLUDE_SIMD_SIG_DMEU_DATA_H_ */
| 24.966387 | 83 | 0.613262 |
74c78f62a2baebe1eefdb1530ca542f84e8082b4 | 2,186 | js | JavaScript | react-production-center/src/components/controls.component.js | HypeUFO/react-production-center | 6be7ab8ba029f7df2824eed183428afe4f1474e2 | [
"MIT"
] | null | null | null | react-production-center/src/components/controls.component.js | HypeUFO/react-production-center | 6be7ab8ba029f7df2824eed183428afe4f1474e2 | [
"MIT"
] | null | null | null | react-production-center/src/components/controls.component.js | HypeUFO/react-production-center | 6be7ab8ba029f7df2824eed183428afe4f1474e2 | [
"MIT"
] | null | null | null | import React from 'react';
import classnames from 'classnames';
import RaisedButton from 'material-ui/RaisedButton';
const styles = {
rBtn: {
margin: 0,
minWidth: 20,
width: '40%',
//minHeight: 65,
border: '2px solid black',
margin: '2%'
},
misc: {
minHeight: 40
}
}
class Controls extends React.Component {
render() {
// let startStopClass = classnames('startStopButton2', {'active': this.props.play});
return (
<div className="pad-grid col-xs-3" style={{backgroundColor: 'white', marginTop: 35, marginLeft: '4%'}}>
<div style={{height: 243}}></div>
<RaisedButton label="Play" rippleStyle={styles.misc} buttonStyle={styles.misc} style={styles.rBtn} labelStyle={{fontSize: '0.5em'}}/>
<RaisedButton label="Stop" rippleStyle={styles.misc} buttonStyle={styles.misc} style={styles.rBtn} labelStyle={{fontSize: '0.5em'}}/>
{/*<RaisedButton label="<<" rippleStyle={styles.misc} buttonStyle={styles.misc} style={styles.rBtn} labelStyle={{fontSize: '0.5em'}}/>
<RaisedButton label=">>" rippleStyle={styles.misc} buttonStyle={styles.misc} style={styles.rBtn} labelStyle={{fontSize: '0.5em'}}/>*/}
</div>
)
}
}
// function mapStateToProps(state) {
// return {
// // buffering: state.decksReducer.deck1.buffering,
// // song: state.decksReducer.deck1.activeSong,
// // play: state.decksReducer.deck1.play,
// // speed: state.decksReducer.deck1.speed,
// // volume: state.decksReducer.deck1.volume,
// };
// }
// function mapDispatchToProps(dispatch) {
// return bindActionCreators({
// handleBufferStart: actions.handleBufferStart,
// handleBufferEnd: actions.handleBufferEnd,
// // handlePlaybackSpeed: actions.handlePlaybackSpeed,
// // startStopSong: actions.startStopSong,
// // handleVolumeChange: actions.handleVolumeChange,
// },
// dispatch);
// }
// export default connect(mapStateToProps, mapDispatchToProps)(Turntable);
export default Controls;
| 31.681159 | 161 | 0.610247 |
70cf86fb9639da93308965b48b62b99ad48b9e75 | 3,662 | h | C | prebuildevent_demo/display/ssd1306_commands.h | AterLux/prebuildevent_demo | 9e34c9fa55c2d899641b16ec0c8a6cc355241686 | [
"Apache-2.0"
] | null | null | null | prebuildevent_demo/display/ssd1306_commands.h | AterLux/prebuildevent_demo | 9e34c9fa55c2d899641b16ec0c8a6cc355241686 | [
"Apache-2.0"
] | null | null | null | prebuildevent_demo/display/ssd1306_commands.h | AterLux/prebuildevent_demo | 9e34c9fa55c2d899641b16ec0c8a6cc355241686 | [
"Apache-2.0"
] | null | null | null | /*
* ssd13061_commands.h
*
* Author: Погребняк Дмитрий (Pogrebnyak Dmitry, http://aterlux.ru/)
*/
#ifndef SSD1306_COMMANDS_H_
#define SSD1306_COMMANDS_H_
// Устанавливает контраст, значение - в следующем байте
#define CMD_SET_CONTRAST_CONTROL 0x81
#define CMD_ENTIRE_DISPLAY_ON(enabled) ((enabled) ? 0xA5 : 0xA4)
#define CMD_SET_INVERSE_DISPLAY(enabled) ((enabled) ? 0xA7 : 0xA6)
#define CMD_SET_DISPLAY_ON 0xAF
#define CMD_SET_DISPLAY_OFF 0xAE
// Настройка скроллинга, далее следуют 6 байт с параметрами
#define CMD_SCROLL_HORIZONTAL_RIGHT 0x26
#define CMD_SCROLL_HORIZONTAL_LEFT 0x27
// Настройка скроллинга, далее следуют 5 байт с параметрами
#define CMD_SCROLL_VERTICAL_AND_HORIZONTAL_RIGHT 0x29
#define CMD_SCROLL_VERTICAL_AND_HORIZONTAL_LEFT 0x2A
#define CMD_SCROLL_DISABLE 0x2E
#define CMD_SCROLL_ENABLE 0x2F
#define CMD_SCROLL_SET_VERTICAL_AREA 0xA3
#define CMD_SET_COLUMN 0xA3
// Команды установки адреса в режиме страничной адресации
#define CMD_SET_COLUMN_LO(x) ((x) & 0x0F)
#define CMD_SET_COLUMN_HI(x) (0x10 | ((x) & 0x0F))
// Выбор режима адресации, далее следует 1 байт с параметрами (один из MEMORY_ADDRESSING_MODE_...)
#define CMD_SET_MEMORY_ADDRESSING_MODE 0x20
#define MEMORY_ADDRESSING_MODE_HORIZONTAL 0x20
#define MEMORY_ADDRESSING_MODE_VERTICAL 0x21
#define MEMORY_ADDRESSING_MODE_PAGE 0x22
// Команда установки горизонтального диапазона в горизонтальном и вертикальном режиме, далее следуют 2 байта с параметрами
#define CMD_SET_COULUMN_START_END_ADDRESS 0x21
// Команда установки вертикального диапазона в горизонтальном и вертикальном режиме, далее следуют 2 байта с параметрами
#define CMD_SET_PAGE_START_END_ADDRESS 0x22
// Команды установки страницы в режиме страничной адресации
#define CMD_SET_PAGE(x) (0xB0 | ((x) & 0x07))
// Устанавливает адрес верхней строки дисплея
#define CMD_SET_DISPLAY_START_LINE(x) (0x40 | ((x) & 0x3F))
// Устанавливает горизонтальное отражение изображения
#define CMD_SET_SEGMENT_REMAP(remapped) ((remapped) ? 0xA1 : 0xA0)
// Установка мультиплекора генератора изображения (количество используемых выводов), далее следует 1 байт с параметром
#define CMD_SET_MUX_RATIO 0xA8
// Устанавливает вертикальное отражение изображения
#define CMD_SET_SCAN_DIRECTION(remapped) ((remapped) ? 0xC8 : 0xC0)
// Установка позиции вертикального прокручивания, далее следует 1 байт с параметром
#define CMD_SET_DISPLAY_OFFSET 0xD3
// Установка переназначения общих выводов, далее следует 1 байт с параметром COM_PINS_CONFIGURATION
#define CMD_SET_COM_PINS_CONFIGURATION 0xDA
#define COM_PINS_CONFIGURATION(alternative, left_right_remap) (((alternative) ? 0x10 : 0x00) | ((left_right_remap) ? 0x20 : 0x00) | 0x02)
// Установка частоты и делителя осциллятора, далее следует 1 байт с параметрами CLOCK_RATIO_FREQUENCY
#define CMD_SET_CLOCK_RATIO_FREQUENCY 0xD5
#define CLOCK_RATIO_FREQUENCY(ratio, freq) ((((ratio) - 1) & 0x0F) | (((freq) & 0x0F) << 4))
// Установка периода предзаряда, далее следует 1 байт с параметрами PRECHARGE_PERIOD
#define CMD_SET_PRECHARGE_PERIOD 0xD9
#define PRECHARGE_PERIOD(phase1, phase2) (((phase1) & 0x0F) | (((phase2) & 0x0F) << 4))
// Установка периода отпускания VCOMMH, далее следует 1 байт с параметром, один из VCOMH_DESELECT_...
#define CMD_SET_VCOMH_DESELECT 0xDB
#define VCOMH_DESELECT_0_65_VCC 0x00
#define VCOMH_DESELECT_0_77_VCC 0x20
#define VCOMH_DESELECT_0_83_VCC 0x30
// Включение/отключение повышающего преобразователя, далее следует 1 байт с параметром, один из CHARGE_PUMP_..
#define CMD_CHARGE_PUMP_CONTROL 0x8D
#define CHARGE_PUMP_ENABLE 0x14
#define CHARGE_PUMP_DISABLE 0x10
#define CMD_NOP 0xE3
#endif /* SSD1306_COMMANDS_H_ */ | 36.62 | 137 | 0.808301 |
8bd7390178d919e10842af3e6f9416270e92a8f7 | 4,268 | swift | Swift | Shared/SlidersView.swift | paulrbarnard/WHRDisplay | 99817462670ff378a7635f262db86513edf5e1e8 | [
"BSD-2-Clause"
] | null | null | null | Shared/SlidersView.swift | paulrbarnard/WHRDisplay | 99817462670ff378a7635f262db86513edf5e1e8 | [
"BSD-2-Clause"
] | null | null | null | Shared/SlidersView.swift | paulrbarnard/WHRDisplay | 99817462670ff378a7635f262db86513edf5e1e8 | [
"BSD-2-Clause"
] | null | null | null | //
// SlidersView.swift
// WHRDisplay
//
// Created by pbarnard on 01/03/2022.
//
import SwiftUI
import Network
struct slidersView: View {
@ObservedObject var setSize: mySize
@ObservedObject var udpListener: UdpListener
var udpSender: UdpSender
@State var minDistance: Double = 0.0
@State var spanDistance: Double = 0.0
var body: some View {
ZStack {
VStack {
Text("\(minDistance, specifier: "%.2f") meters")
Slider(value: $minDistance, in: 0.5...3.0, onEditingChanged: { data in
sendMin()
})
.frame(width: setSize.mySize.width * 0.465, height: .infinity)
.disabled(!udpListener.remoteSetting[udpListener.selectedLight])
}
.offset(x: setSize.mySize.width * 0.065, y: setSize.mySize.height * 0.45)
HStack {
VStack {
Text("\(spanDistance, specifier: "%.2f") meters")
Slider(value: $spanDistance, in: 0.01...2.5, onEditingChanged: { data in
sendSpan()
})
.frame(width: setSize.mySize.width * 0.26, height: .infinity)
.disabled(!udpListener.remoteSetting[udpListener.selectedLight])
}
.offset(x: setSize.mySize.width * 0.46, y: setSize.mySize.height * 0.00)
}
}.onReceive(udpListener.$selectedLight) { (newLight) in
initMinDistance(light: newLight);
initSpanDistance(light: newLight)
}
.onReceive(udpListener.$remoteSetting) { (newSetting) in
initMinDistance(light: udpListener.selectedLight);
initSpanDistance(light: udpListener.selectedLight)
}
.onReceive(udpListener.$minDistance) { (newDistance) in
initMinDistance(light: udpListener.selectedLight);
initSpanDistance(light: udpListener.selectedLight)
}
.onReceive(udpListener.$spanDistance) { (newSpan) in
initMinDistance(light: udpListener.selectedLight);
initSpanDistance(light: udpListener.selectedLight)
}
}
private func minDistanceValue(value: Double) -> UInt8 {
let uValue: UInt8 = UInt8((value - 0.50) * 100)
return uValue
}
private func spanDistanceValue(value: Double) -> UInt8{
let uValue: UInt8 = UInt8((value) * 100)
return uValue
}
func initMinDistance(light: Int) -> Void{
if minDistance != udpListener.getMinDistance(forLight: light) {
DispatchQueue.main.async {
self.minDistance = udpListener.getMinDistance(forLight: light)
//print("initMinDistance minDistance:\(self.minDistance) meters")
}
}
}
func initSpanDistance(light: Int) -> Void{
if spanDistance != udpListener.getSpanDistance(forLight: light) {
DispatchQueue.main.async {
self.spanDistance = udpListener.getSpanDistance(forLight: light)
//print("initMinDistance spanDistance:\(self.spanDistance) meters")
}
}
}
private func sendMin() -> Void {
DispatchQueue.main.async {
// send message to signal box to change the minDistance
var buf: Data = "Contrl:0000".data(using: .utf8)!
buf[7] = UInt8(udpListener.selectedLight) + 48 // make it ASCII
buf[8] = minDistanceValue(value: self.minDistance)
buf[9] = 255 // indicate value not changed
buf[10] = udpSender.checksum(data: buf)
buf.append(0)
//print("minDistance:\(buf[8])")
//print("spanDistance:\(buf[9])")
//print("checkSum:\(buf[10])")
udpSender.connect(host: NWEndpoint.Host(udpListener.signalboxAddress),port: 44444)
udpSender.send(buf)
}
}
private func sendSpan() -> Void {
DispatchQueue.main.async {
// send message to signal box to change the minDistance
var buf: Data = "Contrl:0000".data(using: .utf8)!
buf[7] = UInt8(udpListener.selectedLight) + 48 // make it ASCII
buf[9] = spanDistanceValue(value: self.spanDistance)
buf[8] = 255 // indicate value not changed
buf[10] = udpSender.checksum(data: buf)
buf.append(0)
//print("minDistance:\(buf[8])")
//print("spanDistance:\(buf[9])")
//print("checkSum:\(buf[10])")
udpSender.connect(host: NWEndpoint.Host(udpListener.signalboxAddress),port: 44444)
udpSender.send(buf)
}
}
private func showSize(att: mySize) -> some View {
att.showSize()
return AnyView(Rectangle().fill(Color.clear))
}
}
struct SlidersView_Previews: PreviewProvider {
static var previews: some View {
slidersView(setSize: mySize(), udpListener: UdpListener(), udpSender: UdpSender())
}
}
| 30.056338 | 85 | 0.684161 |
965f0c972752de1332f29c3f62b2b7ecccc1fa23 | 896 | php | PHP | examples/generate_csr.php | jpcandioti/phpWsAfip | 865e1c2287b17a85ec37d066fba8aba2c2e8c548 | [
"Apache-2.0"
] | 8 | 2018-06-27T12:10:47.000Z | 2019-10-31T20:44:06.000Z | examples/generate_csr.php | jpcandioti/phpWsAfip | 865e1c2287b17a85ec37d066fba8aba2c2e8c548 | [
"Apache-2.0"
] | 1 | 2020-09-20T19:11:35.000Z | 2020-09-20T19:11:35.000Z | examples/generate_csr.php | jpcandioti/phpWsAfip | 865e1c2287b17a85ec37d066fba8aba2c2e8c548 | [
"Apache-2.0"
] | 1 | 2019-08-13T02:08:10.000Z | 2019-08-13T02:08:10.000Z | <?php
include 'vendor/autoload.php';
use phpWsAfip\WS\WSASS;
// Nombre y ubicación del archivo .key y el archivos .csr a generar.
$alias = 'jgutierrez';
$key_file = 'credentials/' . $alias . '.key';
$csr_file = 'credentials/' . $alias . '.csr';
// Distinguished Name (DN) para el Certificate Signing Request (CSR).
// Los siguientes datos son de ejemplo y no concuerdan con una persona real.
$dn = array(
'countryName' => 'AR',
'stateOrProvinceName' => 'Santa Fe',
'localityName' => 'Rosario',
'organizationName' => 'Juan Gutiérrez',
'commonName' => 'jgutierrez',
'serialNumber' => 'CUIT 20260795326'
);
// CUIDADO con reescribir el CSR.
if (!file_exists($csr_file)) {
// Genera un CSR en formato PKCS#10 con la clave privada y el DN.
file_put_contents($csr_file, WSASS::generateCsr($key_file, $dn));
}
| 30.896552 | 76 | 0.63058 |
227bd457908ad0eaa0028bfded4b5dfcb0883ca3 | 684 | html | HTML | Angular Sakan/src/app/layout/user/show-post/show-post.component.html | alaanaeim125/Project-Sakan-For-Student | e3f1a5ee3f9533f14a4ca94ab7b21b3b2287990b | [
"MIT"
] | 2 | 2019-10-03T19:58:26.000Z | 2019-10-04T10:42:21.000Z | Angular Sakan/src/app/layout/user/show-post/show-post.component.html | alaanaeim125/Project-Sakan-For-Student | e3f1a5ee3f9533f14a4ca94ab7b21b3b2287990b | [
"MIT"
] | null | null | null | Angular Sakan/src/app/layout/user/show-post/show-post.component.html | alaanaeim125/Project-Sakan-For-Student | e3f1a5ee3f9533f14a4ca94ab7b21b3b2287990b | [
"MIT"
] | null | null | null | <h2 class="headDetails">تفاصيـــــل العقـــار</h2>
<br>
<div class="card">
<img src="{{post.ImageUrl}}" alt="no image" style="width:100%" class="marginTop">
<h1 class="marginTop headDetails">شـــقه للإيجـــار</h1>
<h3 class="marginTop "> تاريخ النشر : {{post.Date}}</h3>
<h3 class="marginTop"> السعر : {{post.Price}} جنية</h3>
<h3 class="marginTop"> المساحه : {{post.Area}} متر </h3>
<h3 class="marginTop"> عدد الاسره : {{post.NumberOfBeds}} </h3>
<h3 class="marginTop"> عدد المتاح من الاسره : {{post.Available_NumberOfBeds}} </h3>
<h3 class="marginTop "> تفاصيل العقار : {{post.Details}}</h3>
<h3 class="marginTop "> رقم موبايل : {{ownerOfPost.phone}}</h3>
</div> | 52.615385 | 86 | 0.662281 |
4c2cc88b83a4c17f887565245f1732750eea05aa | 143 | php | PHP | www/html/bitrix/modules/bizproc/install/activities/bitrix/codecondition/lang/en/codecondition.php | Evil1991/bitrixdock | 306734e0f6641c9118c0129a49d9a266124cdc9c | [
"MIT"
] | 1 | 2020-10-05T04:28:40.000Z | 2020-10-05T04:28:40.000Z | www/html/bitrix/modules/bizproc/install/activities/bitrix/codecondition/lang/en/codecondition.php | Evil1991/bitrixdock | 306734e0f6641c9118c0129a49d9a266124cdc9c | [
"MIT"
] | null | null | null | www/html/bitrix/modules/bizproc/install/activities/bitrix/codecondition/lang/en/codecondition.php | Evil1991/bitrixdock | 306734e0f6641c9118c0129a49d9a266124cdc9c | [
"MIT"
] | null | null | null | <?
$MESS ['BPCC_EMPTY_CODE'] = "PHP condition is missing.";
$MESS ['BPCC_NO_PERMS'] = "You do not have permission to change the condition.";
?> | 35.75 | 80 | 0.692308 |
043094d9206c065a97a3907d6eb62492c2b7b18d | 10,261 | swift | Swift | Controller/Authentication/SignUpController.swift | AgrinobleAGN/Agrinoble-Mobile-App-iOS | 9c28c53b8f3b74afcf5ba1e280c2f7ac36de2403 | [
"MIT"
] | 1 | 2021-09-29T03:08:51.000Z | 2021-09-29T03:08:51.000Z | Controller/Authentication/SignUpController.swift | AgrinobleAGN/Agrinoble-Mobile-App-iOS | 9c28c53b8f3b74afcf5ba1e280c2f7ac36de2403 | [
"MIT"
] | null | null | null | Controller/Authentication/SignUpController.swift | AgrinobleAGN/Agrinoble-Mobile-App-iOS | 9c28c53b8f3b74afcf5ba1e280c2f7ac36de2403 | [
"MIT"
] | null | null | null |
import UIKit
import WoWonderTimelineSDK
import ZKProgressHUD
class SignUpController: BaseVC {
@IBOutlet weak var userNameField: RoundTextField!
@IBOutlet weak var firstName: RoundTextField!
@IBOutlet weak var lastName: RoundTextField!
@IBOutlet weak var email: RoundTextField!
@IBOutlet weak var passwordField: RoundTextField!
@IBOutlet weak var confirmPassword: RoundTextField!
@IBOutlet weak var genderField: RoundTextField!
@IBOutlet weak var checkBtn: UIButton!
@IBOutlet weak var iAgreeLabel: UILabel!
@IBOutlet weak var termsOfServiceBtn: UIButton!
@IBOutlet weak var privacyPolicyBtn: UIButton!
@IBOutlet weak var registerBtn: RoundButton!
@IBOutlet weak var haveAnAccountBtn: UIButton!
var error = ""
override func viewDidLoad() {
super.viewDidLoad()
print("OneSignal device id = \(self.oneSignalID ?? "")")
NotificationCenter.default.addObserver(self, selector: #selector(SignUpController.networkStatusChanged(_:)), name: Notification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil)
Reach().monitorReachabilityChanges()
self.userNameField.placeholder = NSLocalizedString("User Name", comment: "User Name")
self.firstName.placeholder = NSLocalizedString("First Name", comment: "First Name")
self.lastName.placeholder = NSLocalizedString("Last Name", comment: "Last Name")
self.email.placeholder = NSLocalizedString("Email", comment: "Email")
self.passwordField.placeholder = NSLocalizedString("Password", comment: "Password")
self.confirmPassword.placeholder = NSLocalizedString("Confirm Password", comment: "Confirm Password")
self.genderField.placeholder = NSLocalizedString("Gender", comment: "Gender")
self.iAgreeLabel.text = NSLocalizedString("I Agree to", comment: "I Agree to")
self.termsOfServiceBtn.setTitle(NSLocalizedString("Terms of Service", comment: "Terms of Service"), for: .normal)
self.privacyPolicyBtn.setTitle(NSLocalizedString("Privacy Policy", comment: "Privacy Policy"), for: .normal)
self.registerBtn.setTitle(NSLocalizedString("Register", comment: "Register"), for: .normal)
self.haveAnAccountBtn.setTitle(NSLocalizedString("Already have an Account ?", comment: "Already have an Account ?"), for: .normal)
}
@objc func networkStatusChanged(_ notification: Notification) {
if let userInfo = notification.userInfo {
let status = userInfo["Status"] as! String
print(status)
}
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.navigationBar.isHidden = true
}
var check = 0
@IBAction func Check(_ sender: Any) {
if check == 0 {
self.checkBtn.setImage(UIImage(named: "ic_check"), for: .normal)
check = 1
}
else{
self.checkBtn.setImage(UIImage(named: "ic_uncheck"), for: .normal)
check = 0
}
}
@IBAction func Register(_ sender: Any) {
if self.userNameField.text?.isEmpty == true {
self.error = NSLocalizedString("Error, Required Username", comment: "Error, Required Username")
self.performSegue(withIdentifier: "ErrorVC", sender: self)
}
else if self.firstName.text?.isEmpty == true{
self.error = NSLocalizedString("Error, Required FirstName", comment: "Error, Required FirstName")
self.performSegue(withIdentifier: "ErrorVC", sender: self)
}
else if self.lastName.text?.isEmpty == true{
self.error = NSLocalizedString("Error, Required LastName", comment: "Error, Required LastName")
self.performSegue(withIdentifier: "ErrorVC", sender: self)
}
else if self.email.text?.isEmpty == true{
self.error = NSLocalizedString("Error, Required Email", comment: "Error, Required Email")
self.performSegue(withIdentifier: "ErrorVC", sender: self)
}
else if self.passwordField.text?.isEmpty == true{
self.error = NSLocalizedString("Error, Required Password", comment: "Error, Required Password")
self.performSegue(withIdentifier: "ErrorVC", sender: self)
}
else if self.confirmPassword.text?.isEmpty == true{
self.error = NSLocalizedString("Error, Required ConfirmPassword", comment: "Error, Required ConfirmPassword")
self.performSegue(withIdentifier: "ErrorVC", sender: self)
}
else if self.genderField.text?.isEmpty == true{
self.error = NSLocalizedString("Error, Please select gender", comment: "Error, Please select gender")
self.performSegue(withIdentifier: "ErrorVC", sender: self)
}
else if self.check == 0{
self.error = NSLocalizedString("Please read terms of services", comment: "Please read terms of services")
self.performSegue(withIdentifier: "ErrorVC", sender: self)
}
else {
ZKProgressHUD.show(NSLocalizedString("Loading", comment: "Loading"))
self.signUPAuthentication(userName: self.userNameField.text!, email: self.email.text!, password:self.passwordField.text!, confirmPassword: self.confirmPassword.text!, deviceID: self.oneSignalID ?? "")
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ErrorVC"{
let destinationVc = segue.destination as! SecurityController
destinationVc.error = error
}
}
private func updateUserData(){
UpdateUserDataManager.sharedInstance.updateUserData(firstName: self.firstName.text!, lastName: self.lastName.text!, phoneNumber: "", website: "", address: "", workPlace: "", school: "", gender: self.genderField.text!) { (success,authError , error) in
if success != nil{
print(success?.message)
}
else if authError != nil {
print(authError?.errors.errorText)
}
else if error != nil{
print(error?.localizedDescription)
}
}
}
private func signUPAuthentication(userName : String,email : String, password : String,confirmPassword : String,deviceID:String) {
let status = Reach().connectionStatus()
switch status {
case .unknown, .offline:
ZKProgressHUD.dismiss()
self.error = NSLocalizedString("Internet Connection Failed", comment: "Internet Connection Failed")
self.performSegue(withIdentifier: "ErrorVC", sender: self)
case .online(.wwan), .online(.wiFi):
AuthenticationManager.sharedInstance.signUPAuthentication(userName: userName, password: password, email: email, confirmPassword: confirmPassword,deviceId:deviceID) { (success, authError, error) in
if success != nil {
UserData.setUSER_ID(success?.userID)
UserData.setaccess_token(success?.accessToken)
self.updateUserData()
ZKProgressHUD.dismiss()
AppInstance.instance.getProfile()
self.performSegue(withIdentifier: "imageSlider", sender: self)
print("SignUp Succesfull")
}
else if authError != nil {
ZKProgressHUD.dismiss()
self.error = authError?.errors.errorText ?? ""
self.performSegue(withIdentifier: "ErrorVC", sender: self)
print(authError?.errors.errorText)
}
else if error != nil {
ZKProgressHUD.dismiss()
print("error")
}
}
}
}
@IBAction func Gender(_ sender: Any) {
self.genderField.inputView = UIView()
self.genderField.resignFirstResponder()
let alert = UIAlertController(title: "", message: NSLocalizedString("Gender", comment: "Gender"), preferredStyle: .actionSheet)
alert.setValue(NSAttributedString(string: alert.message ?? "", attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.medium), NSAttributedString.Key.foregroundColor : UIColor.black]), forKey: "attributedMessage")
alert.addAction(UIAlertAction(title: NSLocalizedString("Male", comment: "Male"), style: .default, handler: { (_) in
self.genderField.text = NSLocalizedString("Male", comment: "Male")
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("Female", comment: "Female"), style: .default, handler: { (_) in
self.genderField.text = NSLocalizedString("Female", comment: "Female")
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("Close", comment: "Close"), style: .cancel, handler: { (_) in
print("User click Dismiss button")
self.genderField.resignFirstResponder()
}))
if let popoverController = alert.popoverPresentationController {
popoverController.sourceView = self.view
popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popoverController.permittedArrowDirections = []
}
self.present(alert, animated: true, completion: {
print("completion block")
})
}
@IBAction func PopView(_ sender: Any) {
self.navigationController?.popViewController(animated: true)
}
@IBAction func TermsofService(_ sender: Any) {
if let url = URL(string: "\(APIClient.baseURl)/terms/terms") {
UIApplication.shared.open(url)
}
}
@IBAction func PrivacyPolicy(_ sender: Any) {
if let url = URL(string: "\(APIClient.baseURl)/terms/privacy-policy") {
UIApplication.shared.open(url)
}
}
}
| 44.80786 | 261 | 0.62567 |
39c20b5333b6e43bd4fb9b976104f021d0684e57 | 157,167 | js | JavaScript | example/main.js | LeeeeeeM/mobx | 67540a4e5a6cae3a65e12f74a5a0bf7258cb1f83 | [
"MIT"
] | null | null | null | example/main.js | LeeeeeeM/mobx | 67540a4e5a6cae3a65e12f74a5a0bf7258cb1f83 | [
"MIT"
] | null | null | null | example/main.js | LeeeeeeM/mobx | 67540a4e5a6cae3a65e12f74a5a0bf7258cb1f83 | [
"MIT"
] | null | null | null | !(function(e) {
var t = {}
function n(r) {
if (t[r]) return t[r].exports
var i = (t[r] = { i: r, l: !1, exports: {} })
return e[r].call(i.exports, i, i.exports, n), (i.l = !0), i.exports
}
;(n.m = e),
(n.c = t),
(n.d = function(e, t, r) {
n.o(e, t) || Object.defineProperty(e, t, { enumerable: !0, get: r })
}),
(n.r = function(e) {
"undefined" != typeof Symbol &&
Symbol.toStringTag &&
Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }),
Object.defineProperty(e, "__esModule", { value: !0 })
}),
(n.t = function(e, t) {
if ((1 & t && (e = n(e)), 8 & t)) return e
if (4 & t && "object" == typeof e && e && e.__esModule) return e
var r = Object.create(null)
if (
(n.r(r),
Object.defineProperty(r, "default", { enumerable: !0, value: e }),
2 & t && "string" != typeof e)
)
for (var i in e)
n.d(
r,
i,
function(t) {
return e[t]
}.bind(null, i)
)
return r
}),
(n.n = function(e) {
var t =
e && e.__esModule
? function() {
return e.default
}
: function() {
return e
}
return n.d(t, "a", t), t
}),
(n.o = function(e, t) {
return Object.prototype.hasOwnProperty.call(e, t)
}),
(n.p = ""),
n((n.s = 6))
})([
function(e, t, n) {
"use strict"
function r(e, t) {
return (
(function(e) {
if (Array.isArray(e)) return e
})(e) ||
(function(e, t) {
var n = [],
r = !0,
i = !1,
o = void 0
try {
for (
var a, u = e[Symbol.iterator]();
!(r = (a = u.next()).done) && (n.push(a.value), !t || n.length !== t);
r = !0
);
} catch (e) {
;(i = !0), (o = e)
} finally {
try {
r || null == u.return || u.return()
} finally {
if (i) throw o
}
}
return n
})(e, t) ||
(function() {
throw new TypeError("Invalid attempt to destructure non-iterable instance")
})()
)
}
function i(e) {
return (i =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function(e) {
return typeof e
}
: function(e) {
return e &&
"function" == typeof Symbol &&
e.constructor === Symbol &&
e !== Symbol.prototype
? "symbol"
: typeof e
})(e)
}
var o =
"An invariant failed, however the error is obfuscated because this is an production build.",
a = []
Object.freeze(a)
var u = {}
function c() {
return ++Pe.a.mobxGuid
}
function s(e) {
throw (l(!1, e), "X")
}
function l(e, t) {
if (!e) throw new Error("[mobx] " + (t || o))
}
Object.freeze(u)
function f(e, t) {
return !1
}
function h(e) {
var t = !1
return function() {
if (!t) return (t = !0), e.apply(this, arguments)
}
}
var d = function() {}
function v(e) {
var t = []
return (
e.forEach(function(e) {
;-1 === t.indexOf(e) && t.push(e)
}),
t
)
}
function y(e) {
return null !== e && "object" === i(e)
}
function p(e) {
if (null === e || "object" !== i(e)) return !1
var t = Object.getPrototypeOf(e)
return t === Object.prototype || null === t
}
function b(e, t, n) {
Object.defineProperty(e, t, {
enumerable: !1,
writable: !0,
configurable: !0,
value: n
})
}
function m(e, t, n) {
Object.defineProperty(e, t, {
enumerable: !1,
writable: !1,
configurable: !0,
value: n
})
}
function g(e, t) {
var n = Object.getOwnPropertyDescriptor(e, t)
return !n || (!1 !== n.configurable && !1 !== n.writable)
}
function w(e, t) {
0
}
function O(e, t) {
var n = "isMobX" + e
return (
(t.prototype[n] = !0),
function(e) {
return y(e) && !0 === e[n]
}
)
}
function S(e) {
return e instanceof Map
}
function k(e) {
return e instanceof Set
}
function _(e) {
var t = new Set()
for (var n in e) t.add(n)
return (
Object.getOwnPropertySymbols(e).forEach(function(n) {
Object.getOwnPropertyDescriptor(e, n).enumerable && t.add(n)
}),
Array.from(t)
)
}
function A(e) {
return e && e.toString ? e.toString() : new String(e).toString()
}
function E(e) {
return p(e)
? Object.keys(e)
: Array.isArray(e)
? e.map(function(e) {
return r(e, 1)[0]
})
: S(e) || $t(e)
? Array.from(e.keys())
: s("Cannot get keys from '".concat(e, "'"))
}
function j(e) {
return null === e ? null : "object" === i(e) ? "" + e : e
}
function T(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n]
;(r.enumerable = r.enumerable || !1),
(r.configurable = !0),
"value" in r && (r.writable = !0),
Object.defineProperty(e, r.key, r)
}
}
var x = Symbol("mobx administration"),
C = (function() {
function e() {
var t =
arguments.length > 0 && void 0 !== arguments[0]
? arguments[0]
: "Atom@" + c()
!(function(e, t) {
if (!(e instanceof t))
throw new TypeError("Cannot call a class as a function")
})(this, e),
(this.name = t),
(this.isPendingUnobservation = !1),
(this.isBeingObserved = !1),
(this.observers = new Set()),
(this.diffValue = 0),
(this.lastAccessedBy = 0),
(this.lowestObserverState = be.NOT_TRACKING)
}
var t, n, r
return (
(t = e),
(n = [
{
key: "onBecomeObserved",
value: function() {
this.onBecomeObservedListeners &&
this.onBecomeObservedListeners.forEach(function(e) {
return e()
})
}
},
{
key: "onBecomeUnobserved",
value: function() {
this.onBecomeUnobservedListeners &&
this.onBecomeUnobservedListeners.forEach(function(e) {
return e()
})
}
},
{
key: "reportObserved",
value: function() {
return Me(this)
}
},
{
key: "reportChanged",
value: function() {
Re(), Ue(this), Ie()
}
},
{
key: "toString",
value: function() {
return this.name
}
}
]) && T(t.prototype, n),
r && T(t, r),
e
)
})(),
P = O("Atom", C)
function V(e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : d,
n = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : d,
r = new C(e)
return t !== d && ht(r, t), n !== d && dt(r, n), r
}
var D = {
identity: function(e, t) {
return e === t
},
structural: function(e, t) {
return On(e, t)
},
default: function(e, t) {
return Object.is(e, t)
}
},
N = Symbol("mobx did run lazy initializers"),
L = Symbol("mobx pending decorators"),
B = {},
R = {}
function I(e, t) {
var n = t ? B : R
return (
n[e] ||
(n[e] = {
configurable: !0,
enumerable: t,
get: function() {
return M(this), this[e]
},
set: function(t) {
M(this), (this[e] = t)
}
})
)
}
function M(e) {
if (!0 !== e[N]) {
var t = e[L]
if (t)
for (var n in (b(e, N, !0), t)) {
var r = t[n]
r.propertyCreator(
e,
r.prop,
r.descriptor,
r.decoratorTarget,
r.decoratorArguments
)
}
}
}
function U(e, t) {
return function() {
var n,
r = function(r, i, o, a) {
if (!0 === a) return t(r, i, o, r, n), null
if (!Object.prototype.hasOwnProperty.call(r, L)) {
var u = r[L]
b(r, L, Object.assign({}, u))
}
return (
(r[L][i] = {
prop: i,
propertyCreator: t,
descriptor: o,
decoratorTarget: r,
decoratorArguments: n
}),
I(i, e)
)
}
return G(arguments)
? ((n = a), r.apply(null, arguments))
: ((n = Array.prototype.slice.call(arguments)), r)
}
}
function G(e) {
return (
((2 === e.length || 3 === e.length) && "string" == typeof e[1]) ||
(4 === e.length && !0 === e[3])
)
}
function K(e, t, n) {
return Ot(e)
? e
: Array.isArray(e)
? te.array(e, { name: n })
: p(e)
? te.object(e, void 0, { name: n })
: S(e)
? te.map(e, { name: n })
: k(e)
? te.set(e, { name: n })
: e
}
function z(e, t, n) {
return null == e
? e
: vn(e) || qt(e) || $t(e) || rn(e)
? e
: Array.isArray(e)
? te.array(e, { name: n, deep: !1 })
: p(e)
? te.object(e, void 0, { name: n, deep: !1 })
: S(e)
? te.map(e, { name: n, deep: !1 })
: k(e)
? te.set(e, { name: n, deep: !1 })
: s(!1)
}
function H(e) {
return e
}
function J(e, t, n) {
return On(e, t) ? t : e
}
var q = n(4)
var W = { deep: !0, name: void 0, defaultDecorator: void 0, proxy: !0 }
function X(e) {
return null == e ? W : "string" == typeof e ? { name: e, deep: !0, proxy: !0 } : e
}
Object.freeze(W)
var Y = Object(q.a)(K),
F = Object(q.a)(z),
Q = Object(q.a)(H),
Z = Object(q.a)(J)
function $(e) {
return e.defaultDecorator ? e.defaultDecorator.enhancer : !1 === e.deep ? H : K
}
var ee = {
box: function(e, t) {
arguments.length > 2 && ne("box")
var n = X(t)
return new ve(e, $(n), n.name, !0, n.equals)
},
array: function(e, t) {
arguments.length > 2 && ne("array")
var n = X(t)
return Gt(e, $(n), n.name)
},
map: function(e, t) {
arguments.length > 2 && ne("map")
var n = X(t)
return new Zt(e, $(n), n.name)
},
set: function(e, t) {
arguments.length > 2 && ne("set")
var n = X(t)
return new nn(e, $(n), n.name)
},
object: function(e, t, n) {
"string" == typeof arguments[1] && ne("object")
var r = X(n)
if (!1 === r.proxy) return yt({}, e, t, r)
var i = pt(r),
o = yt({}, void 0, void 0, r),
a = Ct(o)
return bt(a, e, t, i), a
},
ref: Q,
shallow: F,
deep: Y,
struct: Z
},
te = function(e, t, n) {
if ("string" == typeof arguments[1]) return Y.apply(null, arguments)
if (Ot(e)) return e
var r = p(e)
? te.object(e, t, n)
: Array.isArray(e)
? te.array(e, t)
: S(e)
? te.map(e, t)
: k(e)
? te.set(e, t)
: e
if (r !== e) return r
s(!1)
}
function ne(e) {
s(
"Expected one or two arguments to observable."
.concat(e, ". Did you accidentally try to use observable.")
.concat(e, " as decorator?")
)
}
Object.keys(ee).forEach(function(e) {
return (te[e] = ee[e])
})
var re = U(!1, function(e, t, n, r, i) {
var o = n.get,
a = n.set,
u = i[0] || {}
cn(e).addComputedProp(e, t, Object.assign({ get: o, set: a, context: e }, u))
})
re({ equals: D.structural })
function ie(e, t, n) {
var r = function() {
return oe(e, t, n || this, arguments)
}
return (r.isMobxAction = !0), r
}
function oe(e, t, n, r) {
var i = (function(e, t, n, r) {
var i = 0
var o = Te()
Re()
var a = ue(!0)
return {
prevDerivation: o,
prevAllowStateChanges: a,
notifySpy: !1,
startTime: i
}
})(),
o = !0
try {
var a = t.apply(n, r)
return (o = !1), a
} finally {
o
? ((Pe.a.suppressReactionErrors = o), ae(i), (Pe.a.suppressReactionErrors = !1))
: ae(i)
}
}
function ae(e) {
ce(e.prevAllowStateChanges), Ie(), xe(e.prevDerivation), e.notifySpy
}
function ue(e) {
var t = Pe.a.allowStateChanges
return (Pe.a.allowStateChanges = e), t
}
function ce(e) {
Pe.a.allowStateChanges = e
}
function se(e) {
return (se =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function(e) {
return typeof e
}
: function(e) {
return e &&
"function" == typeof Symbol &&
e.constructor === Symbol &&
e !== Symbol.prototype
? "symbol"
: typeof e
})(e)
}
function le(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n]
;(r.enumerable = r.enumerable || !1),
(r.configurable = !0),
"value" in r && (r.writable = !0),
Object.defineProperty(e, r.key, r)
}
}
function fe(e, t) {
return !t || ("object" !== se(t) && "function" != typeof t)
? (function(e) {
if (void 0 === e)
throw new ReferenceError(
"this hasn't been initialised - super() hasn't been called"
)
return e
})(e)
: t
}
function he(e) {
return (he = Object.setPrototypeOf
? Object.getPrototypeOf
: function(e) {
return e.__proto__ || Object.getPrototypeOf(e)
})(e)
}
function de(e, t) {
return (de =
Object.setPrototypeOf ||
function(e, t) {
return (e.__proto__ = t), e
})(e, t)
}
var ve = (function(e) {
function t(e, n) {
var r,
i =
arguments.length > 2 && void 0 !== arguments[2]
? arguments[2]
: "ObservableValue@" + c(),
o =
(!(arguments.length > 3 && void 0 !== arguments[3]) || arguments[3],
arguments.length > 4 && void 0 !== arguments[4]
? arguments[4]
: D.default)
return (
(function(e, t) {
if (!(e instanceof t))
throw new TypeError("Cannot call a class as a function")
})(this, t),
((r = fe(this, he(t).call(this, i))).enhancer = n),
(r.name = i),
(r.equals = o),
(r.hasUnreportedChange = !1),
(r.value = n(e, void 0, i)),
r
)
}
var n, r, i
return (
(function(e, t) {
if ("function" != typeof t && null !== t)
throw new TypeError(
"Super expression must either be null or a function"
)
;(e.prototype = Object.create(t && t.prototype, {
constructor: { value: e, writable: !0, configurable: !0 }
})),
t && de(e, t)
})(t, C),
(n = t),
(r = [
{
key: "dehanceValue",
value: function(e) {
return void 0 !== this.dehancer ? this.dehancer(e) : e
}
},
{
key: "set",
value: function(e) {
this.value,
(e = this.prepareNewValue(e)) !== Pe.a.UNCHANGED &&
this.setNewValue(e)
}
},
{
key: "prepareNewValue",
value: function(e) {
if ((_e(this), Pt(this))) {
var t = Dt(this, { object: this, type: "update", newValue: e })
if (!t) return Pe.a.UNCHANGED
e = t.newValue
}
return (
(e = this.enhancer(e, this.value, this.name)),
this.equals(this.value, e) ? Pe.a.UNCHANGED : e
)
}
},
{
key: "setNewValue",
value: function(e) {
var t = this.value
;(this.value = e),
this.reportChanged(),
Nt(this) &&
Bt(this, {
type: "update",
object: this,
newValue: e,
oldValue: t
})
}
},
{
key: "get",
value: function() {
return this.reportObserved(), this.dehanceValue(this.value)
}
},
{
key: "intercept",
value: function(e) {
return Vt(this, e)
}
},
{
key: "observe",
value: function(e, t) {
return (
t &&
e({
object: this,
type: "update",
newValue: this.value,
oldValue: void 0
}),
Lt(this, e)
)
}
},
{
key: "toJSON",
value: function() {
return this.get()
}
},
{
key: "toString",
value: function() {
return "".concat(this.name, "[").concat(this.value, "]")
}
},
{
key: "valueOf",
value: function() {
return j(this.get())
}
},
{
key: Symbol.toPrimitive,
value: function() {
return this.valueOf()
}
}
]) && le(n.prototype, r),
i && le(n, i),
t
)
})(),
ye = O("ObservableValue", ve)
function pe(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n]
;(r.enumerable = r.enumerable || !1),
(r.configurable = !0),
"value" in r && (r.writable = !0),
Object.defineProperty(e, r.key, r)
}
}
var be,
me,
ge = (function() {
function e(t) {
!(function(e, t) {
if (!(e instanceof t))
throw new TypeError("Cannot call a class as a function")
})(this, e),
(this.dependenciesState = be.NOT_TRACKING),
(this.observing = []),
(this.newObserving = null),
(this.isBeingObserved = !1),
(this.isPendingUnobservation = !1),
(this.observers = new Set()),
(this.diffValue = 0),
(this.runId = 0),
(this.lastAccessedBy = 0),
(this.lowestObserverState = be.UP_TO_DATE),
(this.unboundDepsCount = 0),
(this.__mapid = "#" + c()),
(this.value = new Oe(null)),
(this.isComputing = !1),
(this.isRunningSetter = !1),
(this.isTracing = me.NONE),
(this.derivation = t.get),
(this.name = t.name || "ComputedValue@" + c()),
t.set && (this.setter = ie(this.name + "-setter", t.set)),
(this.equals =
t.equals ||
(t.compareStructural || t.struct ? D.structural : D.default)),
(this.scope = t.context),
(this.requiresReaction = !!t.requiresReaction),
(this.keepAlive = !!t.keepAlive)
}
var t, n, r
return (
(t = e),
(n = [
{
key: "onBecomeStale",
value: function() {
Ke(this)
}
},
{
key: "onBecomeObserved",
value: function() {
this.onBecomeObservedListeners &&
this.onBecomeObservedListeners.forEach(function(e) {
return e()
})
}
},
{
key: "onBecomeUnobserved",
value: function() {
this.onBecomeUnobservedListeners &&
this.onBecomeUnobservedListeners.forEach(function(e) {
return e()
})
}
},
{
key: "get",
value: function() {
this.isComputing &&
s(
"Cycle detected in computation "
.concat(this.name, ": ")
.concat(this.derivation)
),
0 !== Pe.a.inBatch ||
0 !== this.observers.size ||
this.keepAlive
? (Me(this), ke(this) && this.trackAndCompute() && Ge(this))
: ke(this) &&
(this.warnAboutUntrackedRead(),
Re(),
(this.value = this.computeValue(!1)),
Ie())
var e = this.value
if (Se(e)) throw e.cause
return e
}
},
{
key: "peek",
value: function() {
var e = this.computeValue(!1)
if (Se(e)) throw e.cause
return e
}
},
{
key: "set",
value: function(e) {
if (this.setter) {
l(
!this.isRunningSetter,
"The setter of computed value '".concat(
this.name,
"' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?"
)
),
(this.isRunningSetter = !0)
try {
this.setter.call(this.scope, e)
} finally {
this.isRunningSetter = !1
}
} else l(!1, !1)
}
},
{
key: "trackAndCompute",
value: function() {
var e = this.value,
t = this.dependenciesState === be.NOT_TRACKING,
n = this.computeValue(!0),
r = t || Se(e) || Se(n) || !this.equals(e, n)
return r && (this.value = n), r
}
},
{
key: "computeValue",
value: function(e) {
var t
if (((this.isComputing = !0), Pe.a.computationDepth++, e))
t = Ae(this, this.derivation, this.scope)
else if (!0 === Pe.a.disableErrorBoundaries)
t = this.derivation.call(this.scope)
else
try {
t = this.derivation.call(this.scope)
} catch (e) {
t = new Oe(e)
}
return Pe.a.computationDepth--, (this.isComputing = !1), t
}
},
{
key: "suspend",
value: function() {
this.keepAlive || (Ee(this), (this.value = void 0))
}
},
{
key: "observe",
value: function(e, t) {
var n = this,
r = !0,
i = void 0
return st(function() {
var o = n.get()
if (!r || t) {
var a = Te()
e({ type: "update", object: n, newValue: o, oldValue: i }),
xe(a)
}
;(r = !1), (i = o)
})
}
},
{ key: "warnAboutUntrackedRead", value: function() {} },
{
key: "toJSON",
value: function() {
return this.get()
}
},
{
key: "toString",
value: function() {
return ""
.concat(this.name, "[")
.concat(this.derivation.toString(), "]")
}
},
{
key: "valueOf",
value: function() {
return j(this.get())
}
},
{
key: Symbol.toPrimitive,
value: function() {
return this.valueOf()
}
}
]) && pe(t.prototype, n),
r && pe(t, r),
e
)
})(),
we = O("ComputedValue", ge)
!(function(e) {
;(e[(e.NOT_TRACKING = -1)] = "NOT_TRACKING"),
(e[(e.UP_TO_DATE = 0)] = "UP_TO_DATE"),
(e[(e.POSSIBLY_STALE = 1)] = "POSSIBLY_STALE"),
(e[(e.STALE = 2)] = "STALE")
})(be || (be = {})),
(function(e) {
;(e[(e.NONE = 0)] = "NONE"), (e[(e.LOG = 1)] = "LOG"), (e[(e.BREAK = 2)] = "BREAK")
})(me || (me = {}))
var Oe = function e(t) {
!(function(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
})(this, e),
(this.cause = t)
}
function Se(e) {
return e instanceof Oe
}
function ke(e) {
switch (e.dependenciesState) {
case be.UP_TO_DATE:
return !1
case be.NOT_TRACKING:
case be.STALE:
return !0
case be.POSSIBLY_STALE:
for (var t = Te(), n = e.observing, r = n.length, i = 0; i < r; i++) {
var o = n[i]
if (we(o)) {
if (Pe.a.disableErrorBoundaries) o.get()
else
try {
o.get()
} catch (e) {
return xe(t), !0
}
if (e.dependenciesState === be.STALE) return xe(t), !0
}
}
return Ce(e), xe(t), !1
}
}
function _e(e) {
var t = e.observers.size > 0
Pe.a.computationDepth > 0 && t && s(!1),
Pe.a.allowStateChanges || (!t && "strict" !== Pe.a.enforceActions) || s(!1)
}
function Ae(e, t, n) {
Ce(e),
(e.newObserving = new Array(e.observing.length + 100)),
(e.unboundDepsCount = 0),
(e.runId = ++Pe.a.runId)
var r,
i = Pe.a.trackingDerivation
if (((Pe.a.trackingDerivation = e), !0 === Pe.a.disableErrorBoundaries)) r = t.call(n)
else
try {
r = t.call(n)
} catch (e) {
r = new Oe(e)
}
return (
(Pe.a.trackingDerivation = i),
(function(e) {
for (
var t = e.observing,
n = (e.observing = e.newObserving),
r = be.UP_TO_DATE,
i = 0,
o = e.unboundDepsCount,
a = 0;
a < o;
a++
) {
var u = n[a]
0 === u.diffValue && ((u.diffValue = 1), i !== a && (n[i] = u), i++),
u.dependenciesState > r && (r = u.dependenciesState)
}
;(n.length = i), (e.newObserving = null), (o = t.length)
for (; o--; ) {
var c = t[o]
0 === c.diffValue && Le(c, e), (c.diffValue = 0)
}
for (; i--; ) {
var s = n[i]
1 === s.diffValue && ((s.diffValue = 0), Ne(s, e))
}
r !== be.UP_TO_DATE && ((e.dependenciesState = r), e.onBecomeStale())
})(e),
r
)
}
function Ee(e) {
var t = e.observing
e.observing = []
for (var n = t.length; n--; ) Le(t[n], e)
e.dependenciesState = be.NOT_TRACKING
}
function je(e) {
var t = Te()
try {
return e()
} finally {
xe(t)
}
}
function Te() {
var e = Pe.a.trackingDerivation
return (Pe.a.trackingDerivation = null), e
}
function xe(e) {
Pe.a.trackingDerivation = e
}
function Ce(e) {
if (e.dependenciesState !== be.UP_TO_DATE) {
e.dependenciesState = be.UP_TO_DATE
for (var t = e.observing, n = t.length; n--; )
t[n].lowestObserverState = be.UP_TO_DATE
}
}
var Pe = n(5)
function Ve(e) {
return e.observers && e.observers.size > 0
}
function De(e) {
return e.observers
}
function Ne(e, t) {
e.observers.add(t),
e.lowestObserverState > t.dependenciesState &&
(e.lowestObserverState = t.dependenciesState)
}
function Le(e, t) {
e.observers.delete(t), 0 === e.observers.size && Be(e)
}
function Be(e) {
!1 === e.isPendingUnobservation &&
((e.isPendingUnobservation = !0), Pe.a.pendingUnobservations.push(e))
}
function Re() {
Pe.a.inBatch++
}
function Ie() {
if (0 == --Pe.a.inBatch) {
Xe()
for (var e = Pe.a.pendingUnobservations, t = 0; t < e.length; t++) {
var n = e[t]
;(n.isPendingUnobservation = !1),
0 === n.observers.size &&
(n.isBeingObserved &&
((n.isBeingObserved = !1), n.onBecomeUnobserved()),
n instanceof ge && n.suspend())
}
Pe.a.pendingUnobservations = []
}
}
function Me(e) {
var t = Pe.a.trackingDerivation
return null !== t
? (t.runId !== e.lastAccessedBy &&
((e.lastAccessedBy = t.runId),
(t.newObserving[t.unboundDepsCount++] = e),
e.isBeingObserved || ((e.isBeingObserved = !0), e.onBecomeObserved())),
!0)
: (0 === e.observers.size && Pe.a.inBatch > 0 && Be(e), !1)
}
function Ue(e) {
e.lowestObserverState !== be.STALE &&
((e.lowestObserverState = be.STALE),
e.observers.forEach(function(t) {
t.dependenciesState === be.UP_TO_DATE &&
(t.isTracing !== me.NONE && ze(t, e), t.onBecomeStale()),
(t.dependenciesState = be.STALE)
}))
}
function Ge(e) {
e.lowestObserverState !== be.STALE &&
((e.lowestObserverState = be.STALE),
e.observers.forEach(function(t) {
t.dependenciesState === be.POSSIBLY_STALE
? (t.dependenciesState = be.STALE)
: t.dependenciesState === be.UP_TO_DATE &&
(e.lowestObserverState = be.UP_TO_DATE)
}))
}
function Ke(e) {
e.lowestObserverState === be.UP_TO_DATE &&
((e.lowestObserverState = be.POSSIBLY_STALE),
e.observers.forEach(function(t) {
t.dependenciesState === be.UP_TO_DATE &&
((t.dependenciesState = be.POSSIBLY_STALE),
t.isTracing !== me.NONE && ze(t, e),
t.onBecomeStale())
}))
}
function ze(e, t) {
if (
(console.log(
"[mobx.trace] '"
.concat(e.name, "' is invalidated due to a change in: '")
.concat(t.name, "'")
),
e.isTracing === me.BREAK)
) {
var n = []
!(function e(t, n, r) {
if (n.length >= 1e3) return void n.push("(and many more)")
n.push("".concat(new Array(r).join("\t")).concat(t.name))
t.dependencies &&
t.dependencies.forEach(function(t) {
return e(t, n, r + 1)
})
})(mt(e), n, 1),
new Function(
"debugger;\n/*\nTracing '"
.concat(
e.name,
"'\n\nYou are entering this break point because derivation '"
)
.concat(e.name, "' is being traced and '")
.concat(
t.name,
"' is now forcing it to update.\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\n\n"
)
.concat(
e instanceof ge
? e.derivation.toString().replace(/[*]\//g, "/")
: "",
"\n\nThe dependencies for this derivation are:\n\n"
)
.concat(n.join("\n"), "\n*/\n ")
)()
}
}
function He(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n]
;(r.enumerable = r.enumerable || !1),
(r.configurable = !0),
"value" in r && (r.writable = !0),
Object.defineProperty(e, r.key, r)
}
}
var Je = (function() {
function e() {
var t =
arguments.length > 0 && void 0 !== arguments[0]
? arguments[0]
: "Reaction@" + c(),
n = arguments.length > 1 ? arguments[1] : void 0,
r = arguments.length > 2 ? arguments[2] : void 0
!(function(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
})(this, e),
(this.name = t),
(this.onInvalidate = n),
(this.errorHandler = r),
(this.observing = []),
(this.newObserving = []),
(this.dependenciesState = be.NOT_TRACKING),
(this.diffValue = 0),
(this.runId = 0),
(this.unboundDepsCount = 0),
(this.__mapid = "#" + c()),
(this.isDisposed = !1),
(this._isScheduled = !1),
(this._isTrackPending = !1),
(this._isRunning = !1),
(this.isTracing = me.NONE)
}
var t, n, r
return (
(t = e),
(n = [
{
key: "onBecomeStale",
value: function() {
this.schedule()
}
},
{
key: "schedule",
value: function() {
this._isScheduled ||
((this._isScheduled = !0), Pe.a.pendingReactions.push(this), Xe())
}
},
{
key: "isScheduled",
value: function() {
return this._isScheduled
}
},
{
key: "runReaction",
value: function() {
if (!this.isDisposed) {
if ((Re(), (this._isScheduled = !1), ke(this))) {
this._isTrackPending = !0
try {
this.onInvalidate(), this._isTrackPending
} catch (e) {
this.reportExceptionInDerivation(e)
}
}
Ie()
}
}
},
{
key: "track",
value: function(e) {
if (!this.isDisposed) {
Re(), (this._isRunning = !0)
var t = Ae(this, e, void 0)
;(this._isRunning = !1),
(this._isTrackPending = !1),
this.isDisposed && Ee(this),
Se(t) && this.reportExceptionInDerivation(t.cause),
Ie()
}
}
},
{
key: "reportExceptionInDerivation",
value: function(e) {
var t = this
if (this.errorHandler) this.errorHandler(e, this)
else {
if (Pe.a.disableErrorBoundaries) throw e
var n = "[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '".concat(
this,
"'"
)
Pe.a.suppressReactionErrors
? console.warn(
"[mobx] (error in reaction '".concat(
this.name,
"' suppressed, fix error of causing action below)"
)
)
: console.error(n, e),
Pe.a.globalReactionErrorHandlers.forEach(function(n) {
return n(e, t)
})
}
}
},
{
key: "dispose",
value: function() {
this.isDisposed ||
((this.isDisposed = !0), this._isRunning || (Re(), Ee(this), Ie()))
}
},
{
key: "getDisposer",
value: function() {
var e = this.dispose.bind(this)
return (e[x] = this), e
}
},
{
key: "toString",
value: function() {
return "Reaction[".concat(this.name, "]")
}
},
{
key: "trace",
value: function() {
var e = arguments.length > 0 && void 0 !== arguments[0] && arguments[0]
_t(this, e)
}
}
]) && He(t.prototype, n),
r && He(t, r),
e
)
})()
var qe = 100,
We = function(e) {
return e()
}
function Xe() {
Pe.a.inBatch > 0 || Pe.a.isRunningReactions || We(Ye)
}
function Ye() {
Pe.a.isRunningReactions = !0
for (var e = Pe.a.pendingReactions, t = 0; e.length > 0; ) {
++t === qe &&
(console.error(
"Reaction doesn't converge to a stable state after ".concat(
qe,
" iterations."
) + " Probably there is a cycle in the reactive function: ".concat(e[0])
),
e.splice(0))
for (var n = e.splice(0), r = 0, i = n.length; r < i; r++) n[r].runReaction()
}
Pe.a.isRunningReactions = !1
}
var Fe = O("Reaction", Je)
function Qe(e) {
var t = We
We = function(n) {
return e(function() {
return t(n)
})
}
}
function Ze() {
return !1
}
function $e(e) {}
function et(e) {}
function tt(e) {}
function nt(e) {
return console.warn("[mobx.spy] Is a no-op in production builds"), function() {}
}
function rt() {
s(!1)
}
function it(e) {
return function(t, n, r) {
if (r) {
if (r.value)
return {
value: ie(e, r.value),
enumerable: !1,
configurable: !0,
writable: !0
}
var i = r.initializer
return {
enumerable: !1,
configurable: !0,
writable: !0,
initializer: function() {
return ie(e, i.call(this))
}
}
}
return ot(e).apply(this, arguments)
}
}
function ot(e) {
return function(t, n, r) {
Object.defineProperty(t, n, {
configurable: !0,
enumerable: !1,
get: function() {},
set: function(t) {
b(this, n, ut(e, t))
}
})
}
}
function at(e, t, n, r) {
return !0 === r
? (ct(e, t, n.value), null)
: n
? {
configurable: !0,
enumerable: !1,
get: function() {
return ct(this, t, n.value || n.initializer.call(this)), this[t]
},
set: rt
}
: {
enumerable: !1,
configurable: !0,
set: function(e) {
ct(this, t, e)
},
get: function() {}
}
}
var ut = function(e, t, n, r) {
return 1 === arguments.length && "function" == typeof e
? ie(e.name || "<unnamed action>", e)
: 2 === arguments.length && "function" == typeof t
? ie(e, t)
: 1 === arguments.length && "string" == typeof e
? it(e)
: !0 !== r
? it(t).apply(null, arguments)
: void b(e, t, ie(e.name || t, n.value, this))
}
function ct(e, t, n) {
b(e, t, ie(t, n.bind(e)))
}
function st(e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : u
var n,
r = (t && t.name) || e.name || "Autorun@" + c()
if (!t.scheduler && !t.delay)
n = new Je(
r,
function() {
this.track(a)
},
t.onError
)
else {
var i = ft(t),
o = !1
n = new Je(
r,
function() {
o ||
((o = !0),
i(function() {
;(o = !1), n.isDisposed || n.track(a)
}))
},
t.onError
)
}
function a() {
e(n)
}
return n.schedule(), n.getDisposer()
}
ut.bound = at
var lt = function(e) {
return e()
}
function ft(e) {
return e.scheduler
? e.scheduler
: e.delay
? function(t) {
return setTimeout(t, e.delay)
}
: lt
}
function ht(e, t, n) {
return vt("onBecomeObserved", e, t, n)
}
function dt(e, t, n) {
return vt("onBecomeUnobserved", e, t, n)
}
function vt(e, t, n, r) {
var i = "function" == typeof r ? pn(t, n) : pn(t),
o = "function" == typeof r ? r : n,
a = "".concat(e, "Listeners")
return (
i[a] ? i[a].add(o) : (i[a] = new Set([o])),
"function" != typeof i[e]
? s(!1)
: function() {
var e = i[a]
e && (e.delete(o), 0 === e.size && delete i[a])
}
)
}
function yt(e, t, n, r) {
var i = pt((r = X(r)))
return M(e), cn(e, r.name, i.enhancer), t && bt(e, t, n, i), e
}
function pt(e) {
return e.defaultDecorator || (!1 === e.deep ? Q : Y)
}
function bt(e, t, n, r) {
Re()
try {
var i = _(t),
o = !0,
a = !1,
u = void 0
try {
for (var c, s = i[Symbol.iterator](); !(o = (c = s.next()).done); o = !0) {
var l = c.value,
f = Object.getOwnPropertyDescriptor(t, l)
0
var h = (n && l in n ? n[l] : f.get ? re : r)(e, l, f, !0)
h && Object.defineProperty(e, l, h)
}
} catch (e) {
;(a = !0), (u = e)
} finally {
try {
o || null == s.return || s.return()
} finally {
if (a) throw u
}
}
} finally {
Ie()
}
}
function mt(e, t) {
return gt(pn(e, t))
}
function gt(e) {
var t = { name: e.name }
return (
e.observing && e.observing.length > 0 && (t.dependencies = v(e.observing).map(gt)),
t
)
}
function wt(e, t) {
return (
null != e &&
(void 0 !== t
? !!vn(e) && e[x].values.has(t)
: vn(e) || !!e[x] || P(e) || Fe(e) || we(e))
)
}
function Ot(e) {
return 1 !== arguments.length && s(!1), wt(e)
}
function St(e) {
return vn(e)
? e[x].getKeys()
: $t(e)
? Array.from(e.keys())
: rn(e)
? Array.from(e.keys())
: qt(e)
? e.map(function(e, t) {
return t
})
: s(!1)
}
function kt(e, t, n) {
if (2 !== arguments.length || rn(e))
if (vn(e)) {
var r = e[x]
r.values.get(t) ? r.write(t, n) : r.addObservableProp(t, n, r.defaultEnhancer)
} else if ($t(e)) e.set(t, n)
else if (rn(e)) e.add(t)
else {
if (!qt(e)) return s(!1)
"number" != typeof t && (t = parseInt(t, 10)),
l(t >= 0, "Not a valid index: '".concat(t, "'")),
Re(),
t >= e.length && (e.length = t + 1),
(e[t] = n),
Ie()
}
else {
Re()
var i = t
try {
for (var o in i) kt(e, o, i[o])
} finally {
Ie()
}
}
}
function _t() {
for (var e = !1, t = arguments.length, n = new Array(t), r = 0; r < t; r++)
n[r] = arguments[r]
"boolean" == typeof n[n.length - 1] && (e = n.pop())
var i = (function(e) {
switch (e.length) {
case 0:
return Pe.a.trackingDerivation
case 1:
return pn(e[0])
case 2:
return pn(e[0], e[1])
}
})(n)
if (!i) return s(!1)
i.isTracing === me.NONE &&
console.log("[mobx.trace] '".concat(i.name, "' tracing enabled")),
(i.isTracing = e ? me.BREAK : me.LOG)
}
function At(e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : void 0
Re()
try {
return e.apply(t)
} finally {
Ie()
}
}
function Et(e) {
return (Et =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function(e) {
return typeof e
}
: function(e) {
return e &&
"function" == typeof Symbol &&
e.constructor === Symbol &&
e !== Symbol.prototype
? "symbol"
: typeof e
})(e)
}
function jt(e) {
return e[x]
}
function Tt(e) {
return "string" == typeof e || "number" == typeof e || "symbol" === Et(e)
}
var xt = {
has: function(e, t) {
if (t === x || "constructor" === t || t === N) return !0
var n = jt(e)
return Tt(t) ? n.has(t) : t in e
},
get: function(e, t) {
if (t === x || "constructor" === t || t === N) return e[t]
var n = jt(e),
r = n.values.get(t)
if (r instanceof C) {
var i = r.get()
return void 0 === i && n.has(t), i
}
return Tt(t) && n.has(t), e[t]
},
set: function(e, t, n) {
return !!Tt(t) && (kt(e, t, n), !0)
},
deleteProperty: function(e, t) {
return !!Tt(t) && (jt(e).remove(t), !0)
},
ownKeys: function(e) {
return jt(e).keysAtom.reportObserved(), Reflect.ownKeys(e)
},
preventExtensions: function(e) {
return s("Dynamic observable objects cannot be frozen"), !1
}
}
function Ct(e) {
var t = new Proxy(e, xt)
return (e[x].proxy = t), t
}
function Pt(e) {
return void 0 !== e.interceptors && e.interceptors.length > 0
}
function Vt(e, t) {
var n = e.interceptors || (e.interceptors = [])
return (
n.push(t),
h(function() {
var e = n.indexOf(t)
;-1 !== e && n.splice(e, 1)
})
)
}
function Dt(e, t) {
var n = Te()
try {
var r = e.interceptors
if (r)
for (
var i = 0, o = r.length;
i < o &&
(l(
!(t = r[i](t)) || t.type,
"Intercept handlers should return nothing or a change object"
),
t);
i++
);
return t
} finally {
xe(n)
}
}
function Nt(e) {
return void 0 !== e.changeListeners && e.changeListeners.length > 0
}
function Lt(e, t) {
var n = e.changeListeners || (e.changeListeners = [])
return (
n.push(t),
h(function() {
var e = n.indexOf(t)
;-1 !== e && n.splice(e, 1)
})
)
}
function Bt(e, t) {
var n = Te(),
r = e.changeListeners
if (r) {
for (var i = 0, o = (r = r.slice()).length; i < o; i++) r[i](t)
xe(n)
}
}
function Rt(e) {
return (
(function(e) {
if (Array.isArray(e)) {
for (var t = 0, n = new Array(e.length); t < e.length; t++) n[t] = e[t]
return n
}
})(e) ||
(function(e) {
if (
Symbol.iterator in Object(e) ||
"[object Arguments]" === Object.prototype.toString.call(e)
)
return Array.from(e)
})(e) ||
(function() {
throw new TypeError("Invalid attempt to spread non-iterable instance")
})()
)
}
function It(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n]
;(r.enumerable = r.enumerable || !1),
(r.configurable = !0),
"value" in r && (r.writable = !0),
Object.defineProperty(e, r.key, r)
}
}
function Mt(e) {
return (Mt =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function(e) {
return typeof e
}
: function(e) {
return e &&
"function" == typeof Symbol &&
e.constructor === Symbol &&
e !== Symbol.prototype
? "symbol"
: typeof e
})(e)
}
var Ut = {
get: function(e, t) {
return t === x
? e[x]
: "length" === t
? e[x].getArrayLength()
: "number" == typeof t
? zt.get.call(e, t)
: "string" != typeof t || isNaN(t)
? zt.hasOwnProperty(t)
? zt[t]
: e[t]
: zt.get.call(e, parseInt(t))
},
set: function(e, t, n) {
return (
"length" === t && e[x].setArrayLength(n),
"number" == typeof t && zt.set.call(e, t, n),
"symbol" === Mt(t) || isNaN(t) ? (e[t] = n) : zt.set.call(e, parseInt(t), n),
!0
)
},
preventExtensions: function(e) {
return s("Observable arrays cannot be frozen"), !1
}
}
function Gt(e, t) {
var n =
arguments.length > 2 && void 0 !== arguments[2]
? arguments[2]
: "ObservableArray@" + c(),
r = arguments.length > 3 && void 0 !== arguments[3] && arguments[3],
i = new Kt(n, t, r)
m(i.values, x, i)
var o = new Proxy(i.values, Ut)
if (((i.proxy = o), e && e.length)) {
var a = ue(!0)
i.spliceWithArray(0, 0, e), ce(a)
}
return o
}
var Kt = (function() {
function e(t, n, r) {
!(function(e, t) {
if (!(e instanceof t))
throw new TypeError("Cannot call a class as a function")
})(this, e),
(this.owned = r),
(this.values = []),
(this.proxy = void 0),
(this.lastKnownLength = 0),
(this.atom = new C(t || "ObservableArray@" + c())),
(this.enhancer = function(e, r) {
return n(e, r, t + "[..]")
})
}
var t, n, r
return (
(t = e),
(n = [
{
key: "dehanceValue",
value: function(e) {
return void 0 !== this.dehancer ? this.dehancer(e) : e
}
},
{
key: "dehanceValues",
value: function(e) {
return void 0 !== this.dehancer && e.length > 0
? e.map(this.dehancer)
: e
}
},
{
key: "intercept",
value: function(e) {
return Vt(this, e)
}
},
{
key: "observe",
value: function(e) {
var t =
arguments.length > 1 && void 0 !== arguments[1] && arguments[1]
return (
t &&
e({
object: this.proxy,
type: "splice",
index: 0,
added: this.values.slice(),
addedCount: this.values.length,
removed: [],
removedCount: 0
}),
Lt(this, e)
)
}
},
{
key: "getArrayLength",
value: function() {
return this.atom.reportObserved(), this.values.length
}
},
{
key: "setArrayLength",
value: function(e) {
if ("number" != typeof e || e < 0)
throw new Error("[mobx.array] Out of range: " + e)
var t = this.values.length
if (e !== t)
if (e > t) {
for (var n = new Array(e - t), r = 0; r < e - t; r++)
n[r] = void 0
this.spliceWithArray(t, 0, n)
} else this.spliceWithArray(e, t - e)
}
},
{
key: "updateArrayLength",
value: function(e, t) {
if (e !== this.lastKnownLength)
throw new Error(
"[mobx] Modification exception: the internal structure of an observable array was changed."
)
this.lastKnownLength += t
}
},
{
key: "spliceWithArray",
value: function(e, t, n) {
var r = this
_e(this.atom)
var i = this.values.length
if (
(void 0 === e
? (e = 0)
: e > i
? (e = i)
: e < 0 && (e = Math.max(0, i + e)),
(t =
1 === arguments.length
? i - e
: null == t
? 0
: Math.max(0, Math.min(t, i - e))),
void 0 === n && (n = a),
Pt(this))
) {
var o = Dt(this, {
object: this.proxy,
type: "splice",
index: e,
removedCount: t,
added: n
})
if (!o) return a
;(t = o.removedCount), (n = o.added)
}
n =
0 === n.length
? n
: n.map(function(e) {
return r.enhancer(e, void 0)
})
var u = this.spliceItemsIntoValues(e, t, n)
return (
(0 === t && 0 === n.length) || this.notifyArraySplice(e, n, u),
this.dehanceValues(u)
)
}
},
{
key: "spliceItemsIntoValues",
value: function(e, t, n) {
var r
if (n.length < 1e4)
return (r = this.values).splice.apply(r, [e, t].concat(Rt(n)))
var i = this.values.slice(e, e + t)
return (
(this.values = this.values
.slice(0, e)
.concat(n, this.values.slice(e + t))),
i
)
}
},
{
key: "notifyArrayChildUpdate",
value: function(e, t, n) {
var r = !this.owned && !1,
i = Nt(this),
o =
i || r
? {
object: this.proxy,
type: "update",
index: e,
newValue: t,
oldValue: n
}
: null
this.atom.reportChanged(), i && Bt(this, o)
}
},
{
key: "notifyArraySplice",
value: function(e, t, n) {
var r = !this.owned && !1,
i = Nt(this),
o =
i || r
? {
object: this.proxy,
type: "splice",
index: e,
removed: n,
added: t,
removedCount: n.length,
addedCount: t.length
}
: null
this.atom.reportChanged(), i && Bt(this, o)
}
}
]) && It(t.prototype, n),
r && It(t, r),
e
)
})(),
zt = {
intercept: function(e) {
return this[x].intercept(e)
},
observe: function(e) {
var t = arguments.length > 1 && void 0 !== arguments[1] && arguments[1],
n = this[x]
return n.observe(e, t)
},
clear: function() {
return this.splice(0)
},
replace: function(e) {
var t = this[x]
return t.spliceWithArray(0, t.values.length, e)
},
toJS: function() {
return this.slice()
},
toJSON: function() {
return this.toJS()
},
splice: function(e, t) {
for (
var n = arguments.length, r = new Array(n > 2 ? n - 2 : 0), i = 2;
i < n;
i++
)
r[i - 2] = arguments[i]
var o = this[x]
switch (arguments.length) {
case 0:
return []
case 1:
return o.spliceWithArray(e)
case 2:
return o.spliceWithArray(e, t)
}
return o.spliceWithArray(e, t, r)
},
spliceWithArray: function(e, t, n) {
return this[x].spliceWithArray(e, t, n)
},
push: function() {
for (var e = this[x], t = arguments.length, n = new Array(t), r = 0; r < t; r++)
n[r] = arguments[r]
return e.spliceWithArray(e.values.length, 0, n), e.values.length
},
pop: function() {
return this.splice(Math.max(this[x].values.length - 1, 0), 1)[0]
},
shift: function() {
return this.splice(0, 1)[0]
},
unshift: function() {
for (var e = this[x], t = arguments.length, n = new Array(t), r = 0; r < t; r++)
n[r] = arguments[r]
return e.spliceWithArray(0, 0, n), e.values.length
},
reverse: function() {
var e = this.slice()
return e.reverse.apply(e, arguments)
},
sort: function(e) {
var t = this.slice()
return t.sort.apply(t, arguments)
},
remove: function(e) {
var t = this[x],
n = t.dehanceValues(t.values).indexOf(e)
return n > -1 && (this.splice(n, 1), !0)
},
get: function(e) {
var t = this[x]
if (t) {
if (e < t.values.length)
return t.atom.reportObserved(), t.dehanceValue(t.values[e])
console.warn(
"[mobx.array] Attempt to read an array index ("
.concat(e, ") that is out of bounds (")
.concat(
t.values.length,
"). Please check length first. Out of bound indices will not be tracked by MobX"
)
)
}
},
set: function(e, t) {
var n = this[x],
r = n.values
if (e < r.length) {
_e(n.atom)
var i = r[e]
if (Pt(n)) {
var o = Dt(n, {
type: "update",
object: n.proxy,
index: e,
newValue: t
})
if (!o) return
t = o.newValue
}
;(t = n.enhancer(t, i)) !== i &&
((r[e] = t), n.notifyArrayChildUpdate(e, t, i))
} else {
if (e !== r.length)
throw new Error(
"[mobx.array] Index out of bounds, "
.concat(e, " is larger than ")
.concat(r.length)
)
n.spliceWithArray(e, 0, [t])
}
}
}
;[
"concat",
"every",
"filter",
"forEach",
"indexOf",
"join",
"lastIndexOf",
"map",
"reduce",
"reduceRight",
"slice",
"some",
"toString",
"toLocaleString"
].forEach(function(e) {
zt[e] = function() {
var t = this[x]
t.atom.reportObserved()
var n = t.dehanceValues(t.values)
return n[e].apply(n, arguments)
}
})
var Ht,
Jt = O("ObservableArrayAdministration", Kt)
function qt(e) {
return y(e) && Jt(e[x])
}
function Wt(e) {
return (Wt =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function(e) {
return typeof e
}
: function(e) {
return e &&
"function" == typeof Symbol &&
e.constructor === Symbol &&
e !== Symbol.prototype
? "symbol"
: typeof e
})(e)
}
function Xt(e, t) {
return (
(function(e) {
if (Array.isArray(e)) return e
})(e) ||
(function(e, t) {
var n = [],
r = !0,
i = !1,
o = void 0
try {
for (
var a, u = e[Symbol.iterator]();
!(r = (a = u.next()).done) && (n.push(a.value), !t || n.length !== t);
r = !0
);
} catch (e) {
;(i = !0), (o = e)
} finally {
try {
r || null == u.return || u.return()
} finally {
if (i) throw o
}
}
return n
})(e, t) ||
(function() {
throw new TypeError("Invalid attempt to destructure non-iterable instance")
})()
)
}
function Yt(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n]
;(r.enumerable = r.enumerable || !1),
(r.configurable = !0),
"value" in r && (r.writable = !0),
Object.defineProperty(e, r.key, r)
}
}
var Ft,
Qt = {},
Zt = (function() {
function e(t) {
var n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : K,
r =
arguments.length > 2 && void 0 !== arguments[2]
? arguments[2]
: "ObservableMap@" + c()
if (
((function(e, t) {
if (!(e instanceof t))
throw new TypeError("Cannot call a class as a function")
})(this, e),
(this.enhancer = n),
(this.name = r),
(this[Ht] = Qt),
(this._keysAtom = V("".concat(this.name, ".keys()"))),
(this[Symbol.toStringTag] = "Map"),
"function" != typeof Map)
)
throw new Error(
"mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js"
)
;(this._data = new Map()), (this._hasMap = new Map()), this.merge(t)
}
var t, n, r
return (
(t = e),
(n = [
{
key: "_has",
value: function(e) {
return this._data.has(e)
}
},
{
key: "has",
value: function(e) {
var t = this
if (!Pe.a.trackingDerivation) return this._has(e)
var n = this._hasMap.get(e)
if (!n) {
var r = (n = new ve(
this._has(e),
H,
"".concat(this.name, ".").concat(A(e), "?"),
!1
))
this._hasMap.set(e, r),
dt(r, function() {
return t._hasMap.delete(e)
})
}
return n.get()
}
},
{
key: "set",
value: function(e, t) {
var n = this._has(e)
if (Pt(this)) {
var r = Dt(this, {
type: n ? "update" : "add",
object: this,
newValue: t,
name: e
})
if (!r) return this
t = r.newValue
}
return n ? this._updateValue(e, t) : this._addValue(e, t), this
}
},
{
key: "delete",
value: function(e) {
var t = this
if (
Pt(this) &&
!Dt(this, { type: "delete", object: this, name: e })
)
return !1
if (this._has(e)) {
var n = Nt(this),
r = n
? {
type: "delete",
object: this,
oldValue: this._data.get(e).value,
name: e
}
: null
return (
At(function() {
t._keysAtom.reportChanged(),
t._updateHasMapEntry(e, !1),
t._data.get(e).setNewValue(void 0),
t._data.delete(e)
}),
n && Bt(this, r),
!0
)
}
return !1
}
},
{
key: "_updateHasMapEntry",
value: function(e, t) {
var n = this._hasMap.get(e)
n && n.setNewValue(t)
}
},
{
key: "_updateValue",
value: function(e, t) {
var n = this._data.get(e)
if ((t = n.prepareNewValue(t)) !== Pe.a.UNCHANGED) {
var r = Nt(this),
i = r
? {
type: "update",
object: this,
oldValue: n.value,
name: e,
newValue: t
}
: null
n.setNewValue(t), r && Bt(this, i)
}
}
},
{
key: "_addValue",
value: function(e, t) {
var n = this
_e(this._keysAtom),
At(function() {
var r = new ve(
t,
n.enhancer,
"".concat(n.name, ".").concat(A(e)),
!1
)
n._data.set(e, r),
(t = r.value),
n._updateHasMapEntry(e, !0),
n._keysAtom.reportChanged()
})
var r = Nt(this),
i = r
? { type: "add", object: this, name: e, newValue: t }
: null
r && Bt(this, i)
}
},
{
key: "get",
value: function(e) {
return this.has(e)
? this.dehanceValue(this._data.get(e).get())
: this.dehanceValue(void 0)
}
},
{
key: "dehanceValue",
value: function(e) {
return void 0 !== this.dehancer ? this.dehancer(e) : e
}
},
{
key: "keys",
value: function() {
return this._keysAtom.reportObserved(), this._data.keys()
}
},
{
key: "values",
value: function() {
var e = this,
t = 0,
n = Array.from(this.keys())
return An({
next: function() {
return t < n.length
? { value: e.get(n[t++]), done: !1 }
: { done: !0 }
}
})
}
},
{
key: "entries",
value: function() {
var e = this,
t = 0,
n = Array.from(this.keys())
return An({
next: function() {
if (t < n.length) {
var r = n[t++]
return { value: [r, e.get(r)], done: !1 }
}
return { done: !0 }
}
})
}
},
{
key: ((Ht = x), Symbol.iterator),
value: function() {
return this.entries()
}
},
{
key: "forEach",
value: function(e, t) {
var n = !0,
r = !1,
i = void 0
try {
for (
var o, a = this[Symbol.iterator]();
!(n = (o = a.next()).done);
n = !0
) {
var u = Xt(o.value, 2),
c = u[0],
s = u[1]
e.call(t, s, c, this)
}
} catch (e) {
;(r = !0), (i = e)
} finally {
try {
n || null == a.return || a.return()
} finally {
if (r) throw i
}
}
}
},
{
key: "merge",
value: function(e) {
var t = this
return (
$t(e) && (e = e.toJS()),
At(function() {
p(e)
? _(e).forEach(function(n) {
return t.set(n, e[n])
})
: Array.isArray(e)
? e.forEach(function(e) {
var n = Xt(e, 2),
r = n[0],
i = n[1]
return t.set(r, i)
})
: S(e)
? (e.constructor !== Map &&
s(
"Cannot initialize from classes that inherit from Map: " +
e.constructor.name
),
e.forEach(function(e, n) {
return t.set(n, e)
}))
: null != e && s("Cannot initialize map from " + e)
}),
this
)
}
},
{
key: "clear",
value: function() {
var e = this
At(function() {
je(function() {
var t = !0,
n = !1,
r = void 0
try {
for (
var i, o = e.keys()[Symbol.iterator]();
!(t = (i = o.next()).done);
t = !0
) {
var a = i.value
e.delete(a)
}
} catch (e) {
;(n = !0), (r = e)
} finally {
try {
t || null == o.return || o.return()
} finally {
if (n) throw r
}
}
})
})
}
},
{
key: "replace",
value: function(e) {
var t = this
return (
At(function() {
var n = E(e)
Array.from(t.keys())
.filter(function(e) {
return -1 === n.indexOf(e)
})
.forEach(function(e) {
return t.delete(e)
}),
t.merge(e)
}),
this
)
}
},
{
key: "toPOJO",
value: function() {
var e = {},
t = !0,
n = !1,
r = void 0
try {
for (
var i, o = this[Symbol.iterator]();
!(t = (i = o.next()).done);
t = !0
) {
var a = Xt(i.value, 2),
u = a[0],
c = a[1]
e["symbol" === Wt(u) ? u : A(u)] = c
}
} catch (e) {
;(n = !0), (r = e)
} finally {
try {
t || null == o.return || o.return()
} finally {
if (n) throw r
}
}
return e
}
},
{
key: "toJS",
value: function() {
return new Map(this)
}
},
{
key: "toJSON",
value: function() {
return this.toPOJO()
}
},
{
key: "toString",
value: function() {
var e = this
return (
this.name +
"[{ " +
Array.from(this.keys())
.map(function(t) {
return "".concat(A(t), ": ").concat("" + e.get(t))
})
.join(", ") +
" }]"
)
}
},
{
key: "observe",
value: function(e, t) {
return Lt(this, e)
}
},
{
key: "intercept",
value: function(e) {
return Vt(this, e)
}
},
{
key: "size",
get: function() {
return this._keysAtom.reportObserved(), this._data.size
}
}
]) && Yt(t.prototype, n),
r && Yt(t, r),
e
)
})(),
$t = O("ObservableMap", Zt)
function en(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n]
;(r.enumerable = r.enumerable || !1),
(r.configurable = !0),
"value" in r && (r.writable = !0),
Object.defineProperty(e, r.key, r)
}
}
var tn = {},
nn = (function() {
function e(t) {
var n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : K,
r =
arguments.length > 2 && void 0 !== arguments[2]
? arguments[2]
: "ObservableSet@" + c()
if (
((function(e, t) {
if (!(e instanceof t))
throw new TypeError("Cannot call a class as a function")
})(this, e),
(this.name = r),
(this[Ft] = tn),
(this._data = new Set()),
(this._atom = V(this.name)),
(this[Symbol.toStringTag] = "Set"),
"function" != typeof Set)
)
throw new Error(
"mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js"
)
;(this.enhancer = function(e, t) {
return n(e, t, r)
}),
t && this.replace(t)
}
var t, n, r
return (
(t = e),
(n = [
{
key: "dehanceValue",
value: function(e) {
return void 0 !== this.dehancer ? this.dehancer(e) : e
}
},
{
key: "clear",
value: function() {
var e = this
At(function() {
je(function() {
var t = !0,
n = !1,
r = void 0
try {
for (
var i, o = e._data.values()[Symbol.iterator]();
!(t = (i = o.next()).done);
t = !0
) {
var a = i.value
e.delete(a)
}
} catch (e) {
;(n = !0), (r = e)
} finally {
try {
t || null == o.return || o.return()
} finally {
if (n) throw r
}
}
})
})
}
},
{
key: "forEach",
value: function(e, t) {
var n = !0,
r = !1,
i = void 0
try {
for (
var o, a = this[Symbol.iterator]();
!(n = (o = a.next()).done);
n = !0
) {
var u = o.value
e.call(t, u, u, this)
}
} catch (e) {
;(r = !0), (i = e)
} finally {
try {
n || null == a.return || a.return()
} finally {
if (r) throw i
}
}
}
},
{
key: "add",
value: function(e) {
var t = this
if (
(_e(this._atom),
Pt(this) &&
!Dt(this, { type: "add", object: this, newValue: e }))
)
return this
if (!this.has(e)) {
At(function() {
t._data.add(t.enhancer(e, void 0)), t._atom.reportChanged()
})
var n = Nt(this),
r = n ? { type: "add", object: this, newValue: e } : null
n && Bt(this, r)
}
return this
}
},
{
key: "delete",
value: function(e) {
var t = this
if (
Pt(this) &&
!Dt(this, { type: "delete", object: this, oldValue: e })
)
return !1
if (this.has(e)) {
var n = Nt(this),
r = n ? { type: "delete", object: this, oldValue: e } : null
return (
At(function() {
t._atom.reportChanged(), t._data.delete(e)
}),
n && Bt(this, r),
!0
)
}
return !1
}
},
{
key: "has",
value: function(e) {
return (
this._atom.reportObserved(),
this._data.has(this.dehanceValue(e))
)
}
},
{
key: "entries",
value: function() {
var e = 0,
t = Array.from(this.keys()),
n = Array.from(this.values())
return An({
next: function() {
var r = e
return (
(e += 1),
r < n.length
? { value: [t[r], n[r]], done: !1 }
: { done: !0 }
)
}
})
}
},
{
key: "keys",
value: function() {
return this.values()
}
},
{
key: "values",
value: function() {
this._atom.reportObserved()
var e = this,
t = 0,
n = Array.from(this._data.values())
return An({
next: function() {
return t < n.length
? { value: e.dehanceValue(n[t++]), done: !1 }
: { done: !0 }
}
})
}
},
{
key: "replace",
value: function(e) {
var t = this
return (
rn(e) && (e = e.toJS()),
At(function() {
Array.isArray(e)
? (t.clear(),
e.forEach(function(e) {
return t.add(e)
}))
: k(e)
? (t.clear(),
e.forEach(function(e) {
return t.add(e)
}))
: null != e && s("Cannot initialize set from " + e)
}),
this
)
}
},
{
key: "observe",
value: function(e, t) {
return Lt(this, e)
}
},
{
key: "intercept",
value: function(e) {
return Vt(this, e)
}
},
{
key: "toJS",
value: function() {
return new Set(this)
}
},
{
key: "toString",
value: function() {
return this.name + "[ " + Array.from(this).join(", ") + " ]"
}
},
{
key: ((Ft = x), Symbol.iterator),
value: function() {
return this.values()
}
},
{
key: "size",
get: function() {
return this._atom.reportObserved(), this._data.size
}
}
]) && en(t.prototype, n),
r && en(t, r),
e
)
})(),
rn = O("ObservableSet", nn)
function on(e, t) {
return (
(function(e) {
if (Array.isArray(e)) return e
})(e) ||
(function(e, t) {
var n = [],
r = !0,
i = !1,
o = void 0
try {
for (
var a, u = e[Symbol.iterator]();
!(r = (a = u.next()).done) && (n.push(a.value), !t || n.length !== t);
r = !0
);
} catch (e) {
;(i = !0), (o = e)
} finally {
try {
r || null == u.return || u.return()
} finally {
if (i) throw o
}
}
return n
})(e, t) ||
(function() {
throw new TypeError("Invalid attempt to destructure non-iterable instance")
})()
)
}
function an(e, t) {
for (var n = 0; n < t.length; n++) {
var r = t[n]
;(r.enumerable = r.enumerable || !1),
(r.configurable = !0),
"value" in r && (r.writable = !0),
Object.defineProperty(e, r.key, r)
}
}
var un = (function() {
function e(t) {
var n = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : new Map(),
r = arguments.length > 2 ? arguments[2] : void 0,
i = arguments.length > 3 ? arguments[3] : void 0
!(function(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function")
})(this, e),
(this.target = t),
(this.values = n),
(this.name = r),
(this.defaultEnhancer = i),
(this.keysAtom = new C(r + ".keys"))
}
var t, n, r
return (
(t = e),
(n = [
{
key: "read",
value: function(e) {
return this.values.get(e).get()
}
},
{
key: "write",
value: function(e, t) {
var n = this.target,
r = this.values.get(e)
if (r instanceof ge) r.set(t)
else {
if (Pt(this)) {
var i = Dt(this, {
type: "update",
object: this.proxy || n,
name: e,
newValue: t
})
if (!i) return
t = i.newValue
}
if ((t = r.prepareNewValue(t)) !== Pe.a.UNCHANGED) {
var o = Nt(this),
a = o
? {
type: "update",
object: this.proxy || n,
oldValue: r.value,
name: e,
newValue: t
}
: null
r.setNewValue(t), o && Bt(this, a)
}
}
}
},
{
key: "has",
value: function(e) {
var t = this.pendingKeys || (this.pendingKeys = new Map()),
n = t.get(e)
if (n) return n.get()
var r = !!this.values.get(e)
return (
(n = new ve(r, H, "".concat(this.name, ".").concat(A(e), "?"), !1)),
t.set(e, n),
n.get()
)
}
},
{
key: "addObservableProp",
value: function(e, t) {
var n =
arguments.length > 2 && void 0 !== arguments[2]
? arguments[2]
: this.defaultEnhancer,
r = this.target
if ((w(), Pt(this))) {
var i = Dt(this, {
object: this.proxy || r,
name: e,
type: "add",
newValue: t
})
if (!i) return
t = i.newValue
}
var o = new ve(t, n, "".concat(this.name, ".").concat(A(e)), !1)
this.values.set(e, o),
(t = o.value),
Object.defineProperty(r, e, fn(e)),
this.notifyPropertyAddition(e, t)
}
},
{
key: "addComputedProp",
value: function(e, t, n) {
var r = this.target
;(n.name = n.name || "".concat(this.name, ".").concat(A(t))),
this.values.set(t, new ge(n)),
(e === r || g(e, t)) &&
Object.defineProperty(
e,
t,
(function(e) {
return (
ln[e] ||
(ln[e] = {
configurable: Pe.a.computedConfigurable,
enumerable: !1,
get: function() {
return hn(this).read(e)
},
set: function(t) {
hn(this).write(e, t)
}
})
)
})(t)
)
}
},
{
key: "remove",
value: function(e) {
if (this.values.has(e)) {
var t = this.target
if (
Pt(this) &&
!Dt(this, { object: this.proxy || t, name: e, type: "remove" })
)
return
try {
Re()
var n = Nt(this),
r = this.values.get(e),
i = r && r.get()
if (
(r && r.set(void 0),
this.keysAtom.reportChanged(),
this.values.delete(e),
this.pendingKeys)
) {
var o = this.pendingKeys.get(e)
o && o.set(!1)
}
delete this.target[e]
var a = n
? {
type: "remove",
object: this.proxy || t,
oldValue: i,
name: e
}
: null
n && Bt(this, a)
} finally {
Ie()
}
}
}
},
{
key: "illegalAccess",
value: function(e, t) {
console.warn(
"Property '"
.concat(t, "' of '")
.concat(
e,
"' was accessed through the prototype chain. Use 'decorate' instead to declare the prop or access it statically through it's owner"
)
)
}
},
{
key: "observe",
value: function(e, t) {
return Lt(this, e)
}
},
{
key: "intercept",
value: function(e) {
return Vt(this, e)
}
},
{
key: "notifyPropertyAddition",
value: function(e, t) {
var n = Nt(this),
r = n
? {
type: "add",
object: this.proxy || this.target,
name: e,
newValue: t
}
: null
if ((n && Bt(this, r), this.pendingKeys)) {
var i = this.pendingKeys.get(e)
i && i.set(!0)
}
this.keysAtom.reportChanged()
}
},
{
key: "getKeys",
value: function() {
this.keysAtom.reportObserved()
var e = [],
t = !0,
n = !1,
r = void 0
try {
for (
var i, o = this.values[Symbol.iterator]();
!(t = (i = o.next()).done);
t = !0
) {
var a = on(i.value, 2),
u = a[0]
a[1] instanceof ve && e.push(u)
}
} catch (e) {
;(n = !0), (r = e)
} finally {
try {
t || null == o.return || o.return()
} finally {
if (n) throw r
}
}
return e
}
}
]) && an(t.prototype, n),
r && an(t, r),
e
)
})()
function cn(e) {
var t = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : "",
n = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : K
if (Object.prototype.hasOwnProperty.call(e, x)) return e[x]
p(e) || (t = (e.constructor.name || "ObservableObject") + "@" + c()),
t || (t = "ObservableObject@" + c())
var r = new un(e, new Map(), A(t), n)
return b(e, x, r), r
}
var sn = Object.create(null),
ln = Object.create(null)
function fn(e) {
return (
sn[e] ||
(sn[e] = {
configurable: !0,
enumerable: !0,
get: function() {
return this[x].read(e)
},
set: function(t) {
this[x].write(e, t)
}
})
)
}
function hn(e) {
var t = e[x]
return t || (M(e), e[x])
}
var dn = O("ObservableObjectAdministration", un)
function vn(e) {
return !!y(e) && (M(e), dn(e[x]))
}
function yn(e) {
return (yn =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function(e) {
return typeof e
}
: function(e) {
return e &&
"function" == typeof Symbol &&
e.constructor === Symbol &&
e !== Symbol.prototype
? "symbol"
: typeof e
})(e)
}
function pn(e, t) {
if ("object" === yn(e) && null !== e) {
if (qt(e)) return void 0 !== t && s(!1), e[x].atom
if (rn(e)) return e[x]
if ($t(e)) {
var n = e
if (void 0 === t) return n._keysAtom
var r = n._data.get(t) || n._hasMap.get(t)
return r || s(!1), r
}
if ((M(e), t && !e[x] && e[t], vn(e))) {
if (!t) return s(!1)
var i = e[x].values.get(t)
return i || s(!1), i
}
if (P(e) || we(e) || Fe(e)) return e
} else if ("function" == typeof e && Fe(e[x])) return e[x]
return s(!1)
}
function bn(e, t) {
return (
e || s("Expecting some object"),
void 0 !== t
? bn(pn(e, t))
: P(e) || we(e) || Fe(e)
? e
: $t(e) || rn(e)
? e
: (M(e), e[x] ? e[x] : void s(!1))
)
}
function mn(e, t) {
return (void 0 !== t ? pn(e, t) : vn(e) || $t(e) || rn(e) ? bn(e) : pn(e)).name
}
function gn(e) {
return (gn =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function(e) {
return typeof e
}
: function(e) {
return e &&
"function" == typeof Symbol &&
e.constructor === Symbol &&
e !== Symbol.prototype
? "symbol"
: typeof e
})(e)
}
var wn = Object.prototype.toString
function On(e, t) {
return Sn(e, t)
}
function Sn(e, t, n, r) {
if (e === t) return 0 !== e || 1 / e == 1 / t
if (null == e || null == t) return !1
if (e != e) return t != t
var i = gn(e)
return (
("function" === i || "object" === i || "object" == gn(t)) &&
(function(e, t, n, r) {
;(e = kn(e)), (t = kn(t))
var i = wn.call(e)
if (i !== wn.call(t)) return !1
switch (i) {
case "[object RegExp]":
case "[object String]":
return "" + e == "" + t
case "[object Number]":
return +e != +e ? +t != +t : 0 == +e ? 1 / +e == 1 / t : +e == +t
case "[object Date]":
case "[object Boolean]":
return +e == +t
case "[object Symbol]":
return (
"undefined" != typeof Symbol &&
Symbol.valueOf.call(e) === Symbol.valueOf.call(t)
)
}
var o = "[object Array]" === i
if (!o) {
if ("object" != gn(e) || "object" != gn(t)) return !1
var a = e.constructor,
u = t.constructor
if (
a !== u &&
!(
"function" == typeof a &&
a instanceof a &&
"function" == typeof u &&
u instanceof u
) &&
"constructor" in e &&
"constructor" in t
)
return !1
}
r = r || []
var c = (n = n || []).length
for (; c--; ) if (n[c] === e) return r[c] === t
if ((n.push(e), r.push(t), o)) {
if ((c = e.length) !== t.length) return !1
for (; c--; ) if (!Sn(e[c], t[c], n, r)) return !1
} else {
var s,
l = Object.keys(e)
if (((c = l.length), Object.keys(t).length !== c)) return !1
for (; c--; )
if (((s = l[c]), !_n(t, s) || !Sn(e[s], t[s], n, r))) return !1
}
return n.pop(), r.pop(), !0
})(e, t, n, r)
)
}
function kn(e) {
return qt(e)
? e.slice()
: S(e) || $t(e)
? Array.from(e.entries())
: k(e) || rn(e)
? Array.from(e.entries())
: e
}
function _n(e, t) {
return Object.prototype.hasOwnProperty.call(e, t)
}
function An(e) {
return (e[Symbol.iterator] = En), e
}
function En() {
return this
}
n.d(t, "e", function() {
return a
}),
n.d(t, "f", function() {
return u
}),
n.d(t, "Y", function() {
return c
}),
n.d(t, "R", function() {
return s
}),
n.d(t, "hb", function() {
return l
}),
n.d(t, "M", function() {
return f
}),
n.d(t, "Ib", function() {
return h
}),
n.d(t, "Db", function() {
return d
}),
n.d(t, "ic", function() {
return v
}),
n.d(t, "nb", function() {
return y
}),
n.d(t, "ub", function() {
return p
}),
n.d(t, "o", function() {
return b
}),
n.d(t, "n", function() {
return m
}),
n.d(t, "vb", function() {
return g
}),
n.d(t, "u", function() {
return w
}),
n.d(t, "F", function() {
return O
}),
n.d(t, "lb", function() {
return S
}),
n.d(t, "mb", function() {
return k
}),
n.d(t, "ab", function() {
return _
}),
n.d(t, "dc", function() {
return A
}),
n.d(t, "X", function() {
return E
}),
n.d(t, "ec", function() {
return j
}),
n.d(t, "a", function() {
return x
}),
n.d(t, "b", function() {
return C
}),
n.d(t, "ib", function() {
return P
}),
n.d(t, "C", function() {
return V
}),
n.d(t, "z", function() {
return D
}),
n.d(t, "Bb", function() {
return N
}),
n.d(t, "fb", function() {
return M
}),
n.d(t, "H", function() {
return U
}),
n.d(t, "J", function() {
return K
}),
n.d(t, "Wb", function() {
return z
}),
n.d(t, "Ob", function() {
return H
}),
n.d(t, "Nb", function() {
return J
}),
n.d(t, "D", function() {
return q.a
}),
n.d(t, "s", function() {
return X
}),
n.d(t, "I", function() {
return Y
}),
n.d(t, "Mb", function() {
return Q
}),
n.d(t, "Fb", function() {
return te
}),
n.d(t, "A", function() {
return re
}),
n.d(t, "B", function() {
return ie
}),
n.d(t, "O", function() {
return oe
}),
n.d(t, "r", function() {
return ue
}),
n.d(t, "q", function() {
return ce
}),
n.d(t, "j", function() {
return ve
}),
n.d(t, "tb", function() {
return ye
}),
n.d(t, "d", function() {
return ge
}),
n.d(t, "kb", function() {
return we
}),
n.d(t, "g", function() {
return be
}),
n.d(t, "l", function() {
return me
}),
n.d(t, "c", function() {
return Oe
}),
n.d(t, "jb", function() {
return Se
}),
n.d(t, "Xb", function() {
return ke
}),
n.d(t, "x", function() {
return _e
}),
n.d(t, "gc", function() {
return Ae
}),
n.d(t, "y", function() {
return Ee
}),
n.d(t, "jc", function() {
return je
}),
n.d(t, "lc", function() {
return Te
}),
n.d(t, "kc", function() {
return xe
}),
n.d(t, "bb", function() {
return Pe.a
}),
n.d(t, "yb", function() {
return Pe.b
}),
n.d(t, "eb", function() {
return Ve
}),
n.d(t, "Z", function() {
return De
}),
n.d(t, "p", function() {
return Ne
}),
n.d(t, "Rb", function() {
return Le
}),
n.d(t, "cc", function() {
return Re
}),
n.d(t, "N", function() {
return Ie
}),
n.d(t, "Sb", function() {
return Me
}),
n.d(t, "Kb", function() {
return Ue
}),
n.d(t, "Jb", function() {
return Ge
}),
n.d(t, "Lb", function() {
return Ke
}),
n.d(t, "k", function() {
return Je
}),
n.d(t, "Tb", function() {
return Xe
}),
n.d(t, "wb", function() {
return Fe
}),
n.d(t, "Vb", function() {
return Qe
}),
n.d(t, "xb", function() {
return Ze
}),
n.d(t, "Zb", function() {
return $e
}),
n.d(t, "bc", function() {
return et
}),
n.d(t, "ac", function() {
return tt
}),
n.d(t, "Yb", function() {
return nt
}),
n.d(t, "Cb", function() {
return it
}),
n.d(t, "w", function() {
return at
}),
n.d(t, "m", function() {
return ut
}),
n.d(t, "L", function() {
return ct
}),
n.d(t, "v", function() {
return st
}),
n.d(t, "Gb", function() {
return ht
}),
n.d(t, "Hb", function() {
return dt
}),
n.d(t, "P", function() {
return yt
}),
n.d(t, "V", function() {
return pt
}),
n.d(t, "Q", function() {
return bt
}),
n.d(t, "W", function() {
return mt
}),
n.d(t, "ob", function() {
return Ot
}),
n.d(t, "zb", function() {
return St
}),
n.d(t, "Ub", function() {
return kt
}),
n.d(t, "fc", function() {
return _t
}),
n.d(t, "hc", function() {
return At
}),
n.d(t, "E", function() {
return Ct
}),
n.d(t, "cb", function() {
return Pt
}),
n.d(t, "Pb", function() {
return Vt
}),
n.d(t, "gb", function() {
return Dt
}),
n.d(t, "db", function() {
return Nt
}),
n.d(t, "Qb", function() {
return Lt
}),
n.d(t, "Eb", function() {
return Bt
}),
n.d(t, "G", function() {
return Gt
}),
n.d(t, "pb", function() {
return qt
}),
n.d(t, "h", function() {
return Zt
}),
n.d(t, "qb", function() {
return $t
}),
n.d(t, "i", function() {
return nn
}),
n.d(t, "sb", function() {
return rn
}),
n.d(t, "t", function() {
return cn
}),
n.d(t, "rb", function() {
return vn
}),
n.d(t, "T", function() {
return pn
}),
n.d(t, "S", function() {
return bn
}),
n.d(t, "U", function() {
return mn
}),
n.d(t, "K", function() {
return On
}),
n.d(t, "Ab", function() {
return An
})
},
function(e, t, n) {
"use strict"
;(function(e, t) {
var r = n(0)
function i(e) {
return (i =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function(e) {
return typeof e
}
: function(e) {
return e &&
"function" == typeof Symbol &&
e.constructor === Symbol &&
e !== Symbol.prototype
? "symbol"
: typeof e
})(e)
}
if ("undefined" == typeof Proxy || "undefined" == typeof Symbol)
throw new Error(
"[mobx] MobX 5+ requires Proxy and Symbol objects. If your environment doesn't support Symbol or Proxy objects, please downgrade to MobX 4. For React Native Android, consider upgrading JSCore."
)
"object" ===
("undefined" == typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__
? "undefined"
: i(__MOBX_DEVTOOLS_GLOBAL_HOOK__)) &&
__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({
spy: r.Yb,
extras: { getDebugName: r.U },
$mobx: r.a
})
}.call(this, n(2), n(3)))
},
function(e, t) {
var n
n = (function() {
return this
})()
try {
n = n || new Function("return this")()
} catch (e) {
"object" == typeof window && (n = window)
}
e.exports = n
},
function(e, t) {
var n,
r,
i = (e.exports = {})
function o() {
throw new Error("setTimeout has not been defined")
}
function a() {
throw new Error("clearTimeout has not been defined")
}
function u(e) {
if (n === setTimeout) return setTimeout(e, 0)
if ((n === o || !n) && setTimeout) return (n = setTimeout), setTimeout(e, 0)
try {
return n(e, 0)
} catch (t) {
try {
return n.call(null, e, 0)
} catch (t) {
return n.call(this, e, 0)
}
}
}
!(function() {
try {
n = "function" == typeof setTimeout ? setTimeout : o
} catch (e) {
n = o
}
try {
r = "function" == typeof clearTimeout ? clearTimeout : a
} catch (e) {
r = a
}
})()
var c,
s = [],
l = !1,
f = -1
function h() {
l && c && ((l = !1), c.length ? (s = c.concat(s)) : (f = -1), s.length && d())
}
function d() {
if (!l) {
var e = u(h)
l = !0
for (var t = s.length; t; ) {
for (c = s, s = []; ++f < t; ) c && c[f].run()
;(f = -1), (t = s.length)
}
;(c = null),
(l = !1),
(function(e) {
if (r === clearTimeout) return clearTimeout(e)
if ((r === a || !r) && clearTimeout)
return (r = clearTimeout), clearTimeout(e)
try {
r(e)
} catch (t) {
try {
return r.call(null, e)
} catch (t) {
return r.call(this, e)
}
}
})(e)
}
}
function v(e, t) {
;(this.fun = e), (this.array = t)
}
function y() {}
;(i.nextTick = function(e) {
var t = new Array(arguments.length - 1)
if (arguments.length > 1)
for (var n = 1; n < arguments.length; n++) t[n - 1] = arguments[n]
s.push(new v(e, t)), 1 !== s.length || l || u(d)
}),
(v.prototype.run = function() {
this.fun.apply(null, this.array)
}),
(i.title = "browser"),
(i.browser = !0),
(i.env = {}),
(i.argv = []),
(i.version = ""),
(i.versions = {}),
(i.on = y),
(i.addListener = y),
(i.once = y),
(i.off = y),
(i.removeListener = y),
(i.removeAllListeners = y),
(i.emit = y),
(i.prependListener = y),
(i.prependOnceListener = y),
(i.listeners = function(e) {
return []
}),
(i.binding = function(e) {
throw new Error("process.binding is not supported")
}),
(i.cwd = function() {
return "/"
}),
(i.chdir = function(e) {
throw new Error("process.chdir is not supported")
}),
(i.umask = function() {
return 0
})
},
function(e, t, n) {
"use strict"
;(function(e) {
n.d(t, "a", function() {
return i
})
var r = n(0)
function i(t) {
Object(r.hb)(t)
var n = Object(r.H)(!0, function(e, n, i, o, a) {
var u = i ? (i.initializer ? i.initializer.call(e) : i.value) : void 0
Object(r.t)(e).addObservableProp(n, u, t)
}),
i = (void 0 !== e && e.env, n)
return (i.enhancer = t), i
}
}.call(this, n(3)))
},
function(e, t, n) {
"use strict"
;(function(e) {
n.d(t, "a", function() {
return u
}),
n.d(t, "b", function() {
return c
})
var r = n(0)
var i = function e() {
!(function(e, t) {
if (!(e instanceof t))
throw new TypeError("Cannot call a class as a function")
})(this, e),
(this.version = 5),
(this.UNCHANGED = {}),
(this.trackingDerivation = null),
(this.computationDepth = 0),
(this.runId = 0),
(this.mobxGuid = 0),
(this.inBatch = 0),
(this.pendingUnobservations = []),
(this.pendingReactions = []),
(this.isRunningReactions = !1),
(this.allowStateChanges = !0),
(this.enforceActions = !1),
(this.spyListeners = []),
(this.globalReactionErrorHandlers = []),
(this.computedRequiresReaction = !1),
(this.computedConfigurable = !1),
(this.disableErrorBoundaries = !1),
(this.suppressReactionErrors = !1)
},
o = !0,
a = !1,
u = (function() {
var e = l()
return (
e.__mobxInstanceCount > 0 && !e.__mobxGlobals && (o = !1),
e.__mobxGlobals && e.__mobxGlobals.version !== new i().version && (o = !1),
o
? e.__mobxGlobals
? ((e.__mobxInstanceCount += 1),
e.__mobxGlobals.UNCHANGED || (e.__mobxGlobals.UNCHANGED = {}),
e.__mobxGlobals)
: ((e.__mobxInstanceCount = 1), (e.__mobxGlobals = new i()))
: (setTimeout(function() {
a ||
Object(r.R)(
"There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`"
)
}, 1),
new i())
)
})()
function c() {
;(u.pendingReactions.length || u.inBatch || u.isRunningReactions) &&
Object(r.R)(
"isolateGlobalState should be called before MobX is running any reactions"
),
(a = !0),
o &&
(0 == --l().__mobxInstanceCount && (l().__mobxGlobals = void 0),
(u = new i()))
}
var s = {}
function l() {
return "undefined" != typeof window ? window : void 0 !== e ? e : s
}
}.call(this, n(2)))
},
function(e, t, n) {
"use strict"
n.r(t)
var r = n(1),
i = document.getElementById("add"),
o = document.getElementById("minus"),
a = document.getElementById("display"),
u = r.default.observable({ name: "Ivan Fan", income: 3, debit: 2 })
r.default.autorun(function() {
a.innerHTML = "i'm the content ".concat(u.income)
}),
i.addEventListener("click", function() {
u.income++
}),
o.addEventListener("click", function() {
u.income--
})
}
])
| 39.961098 | 265 | 0.261467 |
875ecab8413de848c2d090ea27b7dc04879371d7 | 6,365 | rs | Rust | src/problem/rank.rs | hvy/kurobako | 35b24596cea73148a9fa942c283e88238a313ef4 | [
"MIT"
] | 31 | 2019-05-06T14:36:07.000Z | 2021-01-30T14:18:27.000Z | src/problem/rank.rs | hvy/kurobako | 35b24596cea73148a9fa942c283e88238a313ef4 | [
"MIT"
] | 31 | 2020-01-23T05:52:56.000Z | 2021-02-28T10:16:49.000Z | src/problem/rank.rs | hvy/kurobako | 35b24596cea73148a9fa942c283e88238a313ef4 | [
"MIT"
] | 3 | 2021-03-24T01:46:57.000Z | 2022-03-11T11:33:17.000Z | use crate::record::{ProblemRecord, StudyRecord};
use kurobako_core::domain;
use kurobako_core::json::{self, JsonRecipe};
use kurobako_core::problem::{
BoxEvaluator, BoxProblem, BoxProblemFactory, Evaluator, Problem, ProblemFactory, ProblemRecipe,
ProblemSpec, ProblemSpecBuilder,
};
use kurobako_core::registry::FactoryRegistry;
use kurobako_core::rng::ArcRng;
use kurobako_core::trial::{Params, Values};
use kurobako_core::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
use std::sync::Arc;
use structopt::StructOpt;
/// Recipe for normalizing a problem's evaluation result by calculating ranking within the given baseline results.
#[derive(Debug, Clone, StructOpt, Serialize, Deserialize)]
#[structopt(rename_all = "kebab-case")]
pub struct RankProblemRecipe {
/// Problem recipe JSON.
pub problem: JsonRecipe,
/// Baseline results that are used to calculate ranking.
pub baselines: Vec<PathBuf>,
}
impl RankProblemRecipe {
fn inner_problem_id(&self, factory: &BoxProblemFactory) -> Result<String> {
let recipe = track!(serde_json::from_value(self.problem.clone()).map_err(Error::from))?;
let spec = track!(factory.specification())?;
let record = ProblemRecord { recipe, spec };
track!(record.id())
}
fn load_baseline_studies(&self, inner_problem_id: &str) -> Result<Vec<StudyRecord>> {
let mut studies = Vec::new();
for path in &self.baselines {
let file = track!(File::open(path).map_err(Error::from); path)?;
let temp_studies: Vec<StudyRecord> = track!(json::load(BufReader::new(file)); path)?;
for study in temp_studies {
if track!(study.problem.id())? == inner_problem_id {
studies.push(study);
}
}
}
Ok(studies)
}
}
impl ProblemRecipe for RankProblemRecipe {
type Factory = RankProblemFactory;
fn create_factory(&self, registry: &FactoryRegistry) -> Result<Self::Factory> {
let inner_factory = track!(registry.create_problem_factory_from_json(&self.problem))?;
let inner_problem_id = track!(self.inner_problem_id(&inner_factory))?;
let studies = track!(self.load_baseline_studies(&inner_problem_id))?;
let baseline = Arc::new(Baseline::new(&studies));
Ok(RankProblemFactory {
inner_factory,
baseline,
baseline_studies: studies.len(),
})
}
}
#[derive(Debug)]
pub struct RankProblemFactory {
inner_factory: BoxProblemFactory,
baseline: Arc<Baseline>,
baseline_studies: usize,
}
impl ProblemFactory for RankProblemFactory {
type Problem = RankProblem;
fn specification(&self) -> Result<ProblemSpec> {
let inner_spec = track!(self.inner_factory.specification())?;
let mut spec = ProblemSpecBuilder::new(&inner_spec.name)
.attr(
"version",
&format!("kurobako_solvers={}", env!("CARGO_PKG_VERSION")),
)
.attr("baseline_study_count", &self.baseline_studies.to_string())
.params(
inner_spec
.params_domain
.variables()
.iter()
.map(|p| p.clone().into())
.collect(),
)
.steps(inner_spec.steps.iter());
for (k, v) in &inner_spec.attrs {
spec = spec.attr(&format!("inner.{}", k), v);
}
for v in inner_spec.values_domain.variables().iter() {
spec = spec.value(
domain::var(&format!("1 - percentile_rank({}) / 100", v.name()))
.continuous(0.0, 1.0),
);
}
track!(spec.finish())
}
fn create_problem(&self, rng: ArcRng) -> Result<Self::Problem> {
let inner_problem = track!(self.inner_factory.create_problem(rng))?;
Ok(RankProblem {
inner_problem,
baseline: Arc::clone(&self.baseline),
})
}
}
#[derive(Debug)]
pub struct RankProblem {
inner_problem: BoxProblem,
baseline: Arc<Baseline>,
}
impl Problem for RankProblem {
type Evaluator = StudyEvaluator;
fn create_evaluator(&self, params: Params) -> Result<Self::Evaluator> {
let inner_evaluator = track!(self.inner_problem.create_evaluator(params))?;
Ok(StudyEvaluator {
inner_evaluator,
baseline: Arc::clone(&self.baseline),
})
}
}
#[derive(Debug)]
pub struct StudyEvaluator {
inner_evaluator: BoxEvaluator,
baseline: Arc<Baseline>,
}
impl Evaluator for StudyEvaluator {
fn evaluate(&mut self, next_step: u64) -> Result<(u64, Values)> {
let (current_step, values) = track!(self.inner_evaluator.evaluate(next_step))?;
let ranks = self.baseline.rank_values(current_step, &values);
Ok((current_step, ranks))
}
}
#[derive(Debug)]
struct Baseline {
step_to_values: HashMap<u64, Vec<Values>>,
}
impl Baseline {
fn new(studies: &[StudyRecord]) -> Self {
let mut step_to_values: HashMap<_, Vec<_>> = HashMap::new();
for study in studies {
for trial in &study.trials {
let mut step = 0;
for eval in &trial.evaluations {
step += eval.elapsed_steps();
step_to_values
.entry(step)
.or_default()
.push(eval.values.clone());
}
}
}
Self { step_to_values }
}
fn rank_values(&self, step: u64, values: &Values) -> Values {
let count = self.step_to_values.get(&step).map_or(0, |vs| vs.len()) + 1;
let mut ranks = vec![0; values.len()];
for vs in self
.step_to_values
.get(&step)
.iter()
.flat_map(|vs| vs.iter())
{
for ((rank, a), b) in ranks.iter_mut().zip(vs.iter()).zip(values.iter()) {
if a < b {
*rank += 1;
}
}
}
Values::new(
ranks
.into_iter()
.map(|rank| rank as f64 / count as f64)
.collect(),
)
}
}
| 32.809278 | 114 | 0.580047 |
e5027656ee990fb6039cc6594914cdcf968dde66 | 4,588 | ts | TypeScript | src/app/app.component.ts | Kesavan2013/OnDVay_latest | 4e33e44f9bbe0bd72782056206ca4342cd23e58e | [
"Apache-2.0"
] | null | null | null | src/app/app.component.ts | Kesavan2013/OnDVay_latest | 4e33e44f9bbe0bd72782056206ca4342cd23e58e | [
"Apache-2.0"
] | null | null | null | src/app/app.component.ts | Kesavan2013/OnDVay_latest | 4e33e44f9bbe0bd72782056206ca4342cd23e58e | [
"Apache-2.0"
] | null | null | null | import { Component, OnInit, ViewChild,NgZone } from "@angular/core";
import { NavigationEnd, Router } from "@angular/router";
import { RouterExtensions } from "nativescript-angular/router";
import { DrawerTransitionBase, RadSideDrawer, SlideInOnTopTransition } from "nativescript-ui-sidedrawer";
import { filter } from "rxjs/operators";
import * as app from "tns-core-modules/application";
import * as ApplicationSettings from "application-settings";
const firebase = require("nativescript-plugin-firebase");
import { connectionType, getConnectionType, startMonitoring, stopMonitoring }from "tns-core-modules/connectivity";
import { BikePoolService} from "./shared/bikepoolservice";
import { ServiceURL } from "./shared/services";
import * as Connectivity from "tns-core-modules/connectivity";
import * as Toast from "nativescript-toast";
import { alert, prompt } from "tns-core-modules/ui/dialogs";
import { RadSideDrawerComponent } from "nativescript-ui-sidedrawer/angular";
@Component({
moduleId: module.id,
selector: "ns-app",
templateUrl: "app.component.html"
})
export class AppComponent implements OnInit {
private _activatedUrl: string;
private _sideDrawerTransition: DrawerTransitionBase;
private appLoggedIn: boolean = false;
public connectionType: string;
private profileImage : any;
private username : string;
private email : string;
private loggedIn : boolean;
constructor(private router: Router, private routerExtensions: RouterExtensions,
private bikepoolservice:BikePoolService,private zone: NgZone) {
// Use the component constructor to inject services.
}
ngOnInit(): void {
this._activatedUrl = "/home";
this._sideDrawerTransition = new SlideInOnTopTransition();
//this.CheckInternetConnection();
this.router.events
.pipe(filter((event: any) => event instanceof NavigationEnd))
.subscribe((event: NavigationEnd) => this.ActivateURL(event));
this.connectionType = this.connectionToString(Connectivity.getConnectionType());
Connectivity.startMonitoring(connectionType => {
this.zone.run(() => {
this.connectionType = this.connectionToString(connectionType);
//Toast.makeText(this.connectionType,"20000");
if(this.connectionType != '')
{
alert({
title: "On d Vay",
message: this.connectionType,
okButtonText: "Ok"
})
}
});
});
}
ActivateURL(event:NavigationEnd)
{
this._activatedUrl = event.urlAfterRedirects;
}
get sideDrawerTransition(): DrawerTransitionBase {
return this._sideDrawerTransition;
}
isComponentSelected(url: string): boolean {
if(ApplicationSettings.getString("userid") != null){
this.profileImage = ApplicationSettings.getString("profileImageURL");
this.email = ApplicationSettings.getString("email");
this.username = ApplicationSettings.getString("username");
}
return this._activatedUrl === url;
}
onNavItemTap(navItemRoute: string): void {
this.routerExtensions.navigate([navItemRoute], {
transition: {
name: "fade"
}
});
this.closeDrawer();
}
LogoutSuccess(success)
{
this.closeDrawer();
this.loggedIn = false;
this.username = "";
this.email = "";
ApplicationSettings.remove("userid");
firebase.logout();
this.routerExtensions.navigate(["signin"], {
transition: {
name: "push"
}
});
}
LogoutError(error) { }
Logout() {
var objUser = { userid : ApplicationSettings.getString("userid"),deviceToken : "Logged Out" };
this.bikepoolservice.PostService(ServiceURL.DeleteDeviceToken,objUser).subscribe(
success => this.LogoutSuccess(success),
error => this.LogoutError(error)
)
}
closeDrawer(){
const sideDrawer = <RadSideDrawer>app.getRootView();
sideDrawer.closeDrawer();
}
public connectionToString(connectionType: number): string {
switch(connectionType) {
case Connectivity.connectionType.none:
return "Please Check Your Internet Connection";
default:
return "";
}
}
}
| 35.022901 | 114 | 0.625981 |
4da271b52a67bbc7632d8dce5ac38562712072a8 | 665 | html | HTML | manuscript/page-1335/body.html | marvindanig/the-idiot | 1492fc48bfea73fc306ed7bf934cd5643f7e6739 | [
"CECILL-B"
] | null | null | null | manuscript/page-1335/body.html | marvindanig/the-idiot | 1492fc48bfea73fc306ed7bf934cd5643f7e6739 | [
"CECILL-B"
] | null | null | null | manuscript/page-1335/body.html | marvindanig/the-idiot | 1492fc48bfea73fc306ed7bf934cd5643f7e6739 | [
"CECILL-B"
] | null | null | null | <div class="leaf flex"><div class="inner justify"><p> If I have once been given to understand and realize that I am—what does it matter to me that the world is organized on a system full of errors and that otherwise it cannot be organized at all? Who will or can judge me after this? Say what you like—the thing is impossible and unjust!</p><p>“And meanwhile I have never been able, in spite of my great desire to do so, to persuade myself that there is no future existence, and no Providence.</p><p>“The fact of the matter is that all this does exist, but that we know absolutely nothing about the future life and its laws!</p></div> </div> | 665 | 665 | 0.762406 |
33140a733282fc3cda89ba29d9d792c5e98ffc31 | 365 | asm | Assembly | oeis/152/A152456.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/152/A152456.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/152/A152456.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A152456: a(n)=1*(n+2)!-2*(n+1)!-3*n!.
; Submitted by Jamie Morken(s3.)
; -3,-1,6,54,408,3240,28080,267120,2782080,31570560,388281600,5149267200,73287244800,1114636723200,18045906278400,309918825216000,5628230479872000,107773290713088000,2170404686241792000
add $0,2
mov $2,4
mov $3,-4
lpb $0
dif $2,2
add $3,$0
mul $3,$0
sub $0,$2
lpe
mov $0,$3
add $0,1
| 22.8125 | 185 | 0.70137 |
0bb20a1cdedfbffd4e7982cebb075a87cca615b2 | 3,731 | js | JavaScript | src/js/service/keyboard/ShortcutService.js | stayqrious/piskel | a7d43f63b4dc263550e4be2add920f52b11913ee | [
"Apache-2.0"
] | 2,039 | 2015-01-01T16:28:53.000Z | 2022-01-14T01:03:19.000Z | src/js/service/keyboard/ShortcutService.js | stayqrious/piskel | a7d43f63b4dc263550e4be2add920f52b11913ee | [
"Apache-2.0"
] | 319 | 2015-01-04T17:01:48.000Z | 2017-05-13T00:37:29.000Z | src/js/service/keyboard/ShortcutService.js | stayqrious/piskel | a7d43f63b4dc263550e4be2add920f52b11913ee | [
"Apache-2.0"
] | 209 | 2015-01-17T01:37:33.000Z | 2021-09-17T00:39:33.000Z | (function () {
var ns = $.namespace('pskl.service.keyboard');
ns.ShortcutService = function () {
this.shortcuts_ = [];
};
/**
* @public
*/
ns.ShortcutService.prototype.init = function() {
$(document.body).keydown($.proxy(this.onKeyDown_, this));
};
/**
* Add a keyboard shortcut
* @param {pskl.service.keyboard.Shortcut} shortcut
* @param {Function} callback should return true to let the original event perform its default action
*/
ns.ShortcutService.prototype.registerShortcut = function (shortcut, callback) {
if (!(shortcut instanceof ns.Shortcut)) {
throw 'Invalid shortcut argument, please use instances of pskl.service.keyboard.Shortcut';
}
if (typeof callback != 'function') {
throw 'Invalid callback argument, please provide a function';
}
this.shortcuts_.push({
shortcut : shortcut,
callback : callback
});
};
ns.ShortcutService.prototype.unregisterShortcut = function (shortcut) {
var index = -1;
this.shortcuts_.forEach(function (s, i) {
if (s.shortcut === shortcut) {
index = i;
}
});
if (index != -1) {
this.shortcuts_.splice(index, 1);
}
};
/**
* @private
*/
ns.ShortcutService.prototype.onKeyDown_ = function(evt) {
var eventKey = ns.KeyUtils.createKeyFromEvent(evt);
if (this.isInInput_(evt) || !eventKey) {
return;
}
this.shortcuts_.forEach(function (shortcutInfo) {
shortcutInfo.shortcut.getKeys().forEach(function (shortcutKey) {
if (!ns.KeyUtils.equals(shortcutKey, eventKey)) {
return;
}
var bubble = shortcutInfo.callback(eventKey.key);
if (bubble !== true) {
evt.preventDefault();
}
$.publish(Events.KEYBOARD_EVENT, [evt]);
}.bind(this));
}.bind(this));
};
ns.ShortcutService.prototype.isInInput_ = function (evt) {
var targetTagName = evt.target.nodeName.toUpperCase();
return targetTagName === 'INPUT' || targetTagName === 'TEXTAREA';
};
ns.ShortcutService.prototype.getShortcutById = function (id) {
return pskl.utils.Array.find(this.getShortcuts(), function (shortcut) {
return shortcut.getId() === id;
});
};
ns.ShortcutService.prototype.getShortcuts = function () {
var shortcuts = [];
ns.Shortcuts.CATEGORIES.forEach(function (category) {
var shortcutMap = ns.Shortcuts[category];
Object.keys(shortcutMap).forEach(function (shortcutKey) {
shortcuts.push(shortcutMap[shortcutKey]);
});
});
return shortcuts;
};
ns.ShortcutService.prototype.updateShortcut = function (shortcut, keyAsString) {
var key = keyAsString.replace(/\s/g, '');
var isForbiddenKey = ns.Shortcuts.FORBIDDEN_KEYS.indexOf(key) != -1;
if (isForbiddenKey) {
$.publish(Events.SHOW_NOTIFICATION, [{
'content': 'Key cannot be remapped (' + keyAsString + ')',
'hideDelay' : 5000
}]);
} else {
this.removeKeyFromAllShortcuts_(key);
shortcut.updateKeys([key]);
$.publish(Events.SHORTCUTS_CHANGED);
}
};
ns.ShortcutService.prototype.removeKeyFromAllShortcuts_ = function (key) {
this.getShortcuts().forEach(function (s) {
if (s.removeKeys([key])) {
$.publish(Events.SHOW_NOTIFICATION, [{
'content': 'Shortcut key removed for ' + s.getId(),
'hideDelay' : 5000
}]);
}
});
};
/**
* Restore the default piskel key for all shortcuts
*/
ns.ShortcutService.prototype.restoreDefaultShortcuts = function () {
this.getShortcuts().forEach(function (shortcut) {
shortcut.restoreDefault();
});
$.publish(Events.SHORTCUTS_CHANGED);
};
})();
| 28.480916 | 103 | 0.628518 |
0e4d1ae1c9e123251a3c47b47b23f407087af6ee | 1,008 | html | HTML | docs/layouts/_default/baseof.html | stefb965/containerd | a1affdb4ff38395ee6d7590a7b11d18f2333c0da | [
"Apache-2.0"
] | 9 | 2018-10-10T04:52:28.000Z | 2020-02-14T19:50:40.000Z | docs/layouts/_default/baseof.html | stefb965/containerd | a1affdb4ff38395ee6d7590a7b11d18f2333c0da | [
"Apache-2.0"
] | 1 | 2021-03-16T11:16:32.000Z | 2021-03-16T11:16:32.000Z | docs/layouts/_default/baseof.html | stefb965/containerd | a1affdb4ff38395ee6d7590a7b11d18f2333c0da | [
"Apache-2.0"
] | 2 | 2018-10-18T15:59:50.000Z | 2021-03-16T11:14:01.000Z | {{- $prodSite := not .Site.IsServer -}}
{{- $faviconUrl := .Site.Params.favicon | absURL -}}
{{- $fontImport := .Site.Params.fontImport -}}
<!DOCTYPE html>
<html lang="{{ default "en" .Site.LanguageCode }}">
<head>
{{ .Hugo.Generator }}
{{- partial "meta.html" . }}
<title>{{ block "title" . }}{{ .Site.Title }}{{ end }}</title>
{{- partial "css.html" . }}
<link rel="icon" type="image/png" href="{{ $faviconUrl }}" sizes="16x16">
<link href="{{ $fontImport }}" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="hero">
{{- partial "navbar.html" . }}
{{- partial "definition.html" . }}
</div>
<div class="content">
<div class="wrapper-details">
{{ block "main" . }}
{{ end }}
</div>
</div>
</div>
{{- partial "footer.html" . }}
{{- partial "javascript.html" . }}
{{- if $prodSite }}
{{- partial "google-analytics.html" . }}
{{- end }}
</body>
</html> | 28.8 | 77 | 0.502976 |
16b05ceb1a784cb4c0a06eff629cae9185c3fb51 | 1,079 | h | C | code/include/swoc/swoc_version.h | bneradt/libswoc | 58719322a17fe020ed2340592abb30bbfba26f2f | [
"Apache-2.0"
] | null | null | null | code/include/swoc/swoc_version.h | bneradt/libswoc | 58719322a17fe020ed2340592abb30bbfba26f2f | [
"Apache-2.0"
] | null | null | null | code/include/swoc/swoc_version.h | bneradt/libswoc | 58719322a17fe020ed2340592abb30bbfba26f2f | [
"Apache-2.0"
] | null | null | null | // SPDX-License-Identifier: Apache-2.0
// Copyright Verizon Media 2020
/** @file
Solid Wall of C++ Library
@mainpage
A collection of basic utilities derived from Apache Traffic Server code.
Much of the focus is on low level text manipulation, in particular
- @c TextView, an extension of @c std::string_view with a collection od
methods to make working with the text in the view fast and convenient.
- @c BufferWriter, a safe mechanism for writing to fixed sized buffers. As
an optional extension this supports python like output formatting along
with the ability to extend the formatting to arbitrary types, bind names
in to the formatting context, and substitute alternate parsers for
custom format styles.
*/
#pragma once
#if !defined(SWOC_VERSION_NS)
# define SWOC_VERSION_NS _1_2_18
#endif
namespace swoc { inline namespace SWOC_VERSION_NS {
static constexpr unsigned MAJOR_VERSION = 1;
static constexpr unsigned MINOR_VERSION = 2;
static constexpr unsigned POINT_VERSION = 18;
}} // namespace SWOC_VERSION_NS
| 32.69697 | 78 | 0.751622 |
b241727d7bcf4f6a1979d161e61088ed7bab1bc9 | 1,298 | swift | Swift | BBMetalImage/BBMetalImage/BBMetalBoxBlurFilter.swift | carat-im/BBMetalImage | 6edd7287c9a5e702bce7fc7b6a4953b6197601cf | [
"MIT"
] | 815 | 2019-04-20T09:24:12.000Z | 2022-03-23T15:11:43.000Z | BBMetalImage/BBMetalImage/BBMetalBoxBlurFilter.swift | carat-im/BBMetalImage | 6edd7287c9a5e702bce7fc7b6a4953b6197601cf | [
"MIT"
] | 100 | 2019-04-25T04:06:37.000Z | 2021-12-15T02:41:32.000Z | BBMetalImage/BBMetalImage/BBMetalBoxBlurFilter.swift | carat-im/BBMetalImage | 6edd7287c9a5e702bce7fc7b6a4953b6197601cf | [
"MIT"
] | 109 | 2019-04-20T09:24:14.000Z | 2022-03-08T07:40:26.000Z | //
// BBMetalBoxBlurFilter.swift
// BBMetalImage
//
// Created by Kaibo Lu on 4/6/19.
// Copyright © 2019 Kaibo Lu. All rights reserved.
//
import MetalPerformanceShaders
/// A filter that convolves an image with a given kernel of odd width and height
public class BBMetalBoxBlurFilter: BBMetalBaseFilter {
/// The width of the kernel. Must be an odd number
public var kernelWidth: Int { didSet { _kernel = nil } }
/// The height of the kernel. Must be an odd number
public var kernelHeight: Int { didSet { _kernel = nil } }
private var kernel: MPSImageBox {
if let k = _kernel { return k }
let k = MPSImageBox(device: BBMetalDevice.sharedDevice, kernelWidth: kernelWidth, kernelHeight: kernelHeight)
k.edgeMode = .clamp
_kernel = k
return k
}
private var _kernel: MPSImageBox!
public init(kernelWidth: Int = 1, kernelHeight: Int = 1) {
self.kernelWidth = kernelWidth
self.kernelHeight = kernelHeight
super.init(kernelFunctionName: "", useMPSKernel: true)
}
public override func encodeMPSKernel(into commandBuffer: MTLCommandBuffer) {
kernel.encode(commandBuffer: commandBuffer, sourceTexture: _sources.first!.texture!, destinationTexture: _outputTexture!)
}
}
| 35.081081 | 129 | 0.68567 |
f77b55e4448027ac27952a64d042c30e6350915b | 1,923 | c | C | libkieker/monitoring/probes/aspect/controlflow.c | kieker-monitoring/kieker-lang-pack-c | a8aa001f02781bda34a655e6b62b7ed369759142 | [
"Apache-2.0"
] | null | null | null | libkieker/monitoring/probes/aspect/controlflow.c | kieker-monitoring/kieker-lang-pack-c | a8aa001f02781bda34a655e6b62b7ed369759142 | [
"Apache-2.0"
] | null | null | null | libkieker/monitoring/probes/aspect/controlflow.c | kieker-monitoring/kieker-lang-pack-c | a8aa001f02781bda34a655e6b62b7ed369759142 | [
"Apache-2.0"
] | null | null | null | #include "controlflow.h"
#include <pthread.h>
#include <unistd.h>
#include "../../utilities/kieker_error.h"
#include "../../../include/kieker_controller.h"
#include "../../controller/kieker_trace.h"
void kieker_probe_aspect_controlflow_initialize() {
kieker_controller_initialize();
}
kieker_trace_t* kieker_probe_aspect_controlflow_before(kieker_common_record_controlflow_operation_execution_record* record) {
/* get thread unique identifier */
int thread_id = (int) pthread_self();
kieker_trace_t* trace = kieker_trace_get(thread_id);
/* increment indexes */
trace->order_index++;
trace->stack++;
/* set record data */
record->hostname = kieker_controller_get_hostname();;
record->sessionId = "<no session>";
record->traceId = trace->trace_id;
record->eoi = trace->order_index;
record->ess = trace->stack;
/* measure entry time */
record->tin = kieker_controller_get_time_ms();
return trace;
}
void kieker_probe_aspect_controlflow_after(kieker_trace_t *trace, kieker_common_record_controlflow_operation_execution_record *record) {
/* measure exit time */
record->tout = kieker_controller_get_time_ms();
/* decrement execution stack index */
trace->stack--;
}
void kieker_probe_aspect_controlflow_after2(kieker_trace_t *trace, kieker_common_record_controlflow_operation_execution_record *record) {
kieker_probe_aspect_controlflow_send(record, trace->buffer);
/* detect end of trace */
if (trace->stack == -1) {
kieker_trace_remove(trace);
}
}
void kieker_probe_aspect_controlflow_finalize() {
kieker_controller_finalize();
}
void kieker_probe_aspect_controlflow_send(const kieker_common_record_controlflow_operation_execution_record *record, char* buffer) {
int length = kieker_common_record_controlflow_operation_execution_record_serialize(buffer, 0, *record);
kieker_controller_send(length);
}
| 30.52381 | 137 | 0.74987 |
e57f424d659b7aa09863f70a11eb59d19c978f11 | 885 | ts | TypeScript | FronEnd/FrontComentario/src/app/Services/comentario.service.ts | walase01/APPCometarios | 474db6f78f97b2ce883e899506916bc60f668198 | [
"MIT"
] | null | null | null | FronEnd/FrontComentario/src/app/Services/comentario.service.ts | walase01/APPCometarios | 474db6f78f97b2ce883e899506916bc60f668198 | [
"MIT"
] | null | null | null | FronEnd/FrontComentario/src/app/Services/comentario.service.ts | walase01/APPCometarios | 474db6f78f97b2ce883e899506916bc60f668198 | [
"MIT"
] | null | null | null | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { comentario } from '../Interfaces/comentario';
@Injectable({
providedIn: 'root'
})
export class ComentarioService {
private myAppUrl = "https://localhost:44355/";
private myApiUrl = "api/comentario/";
constructor( private _http : HttpClient) { }
getListComentarios() : Observable<any>{
return this._http.get(this.myAppUrl + this.myApiUrl);
}
deleteComentario(id : number) : Observable<any>{
return this._http.delete(this.myAppUrl + this.myApiUrl + id);
}
getListComentario(id : number) : Observable<any>{
return this._http.get(this.myAppUrl + this.myApiUrl + id);
}
saveComentario(comentario : comentario) : Observable<any>{
return this._http.post(this.myAppUrl + this.myApiUrl, comentario);
}
}
| 31.607143 | 72 | 0.698305 |
56ae110666731b2e708d678e9021908bd696d4e7 | 47 | ts | TypeScript | src/Components/Admin/index.ts | sh-fes/sh-fes | a9e0cae9ea9c50497ab6af944f156479052addca | [
"MIT"
] | null | null | null | src/Components/Admin/index.ts | sh-fes/sh-fes | a9e0cae9ea9c50497ab6af944f156479052addca | [
"MIT"
] | null | null | null | src/Components/Admin/index.ts | sh-fes/sh-fes | a9e0cae9ea9c50497ab6af944f156479052addca | [
"MIT"
] | null | null | null | export { default as AdminUI } from './AdminUI'; | 47 | 47 | 0.702128 |
ae3dd5b891b276ae7dbf5edcf5e7bcbcb084e2c8 | 651 | lua | Lua | example/clients/lua/model/example_hat.lua | titpetric/protoc-gen-twirp_swagger | f21ef47d69e37c1602a7fb26146de05c092d30b6 | [
"BSD-3-Clause"
] | 58 | 2018-01-30T21:57:01.000Z | 2021-12-28T11:12:02.000Z | example/clients/lua/model/example_hat.lua | titpetric/protoc-gen-twirp_swagger | f21ef47d69e37c1602a7fb26146de05c092d30b6 | [
"BSD-3-Clause"
] | 21 | 2018-03-12T22:32:57.000Z | 2021-05-06T06:31:22.000Z | example/clients/lua/model/example_hat.lua | titpetric/protoc-gen-twirp_swagger | f21ef47d69e37c1602a7fb26146de05c092d30b6 | [
"BSD-3-Clause"
] | 14 | 2018-06-06T07:45:24.000Z | 2022-02-15T11:31:37.000Z | --[[
service.proto
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: version not set
Generated by: https://github.com/swagger-api/swagger-codegen.git
]]
-- example_hat class
local example_hat = {}
local example_hat_mt = {
__name = "example_hat";
__index = example_hat;
}
local function cast_example_hat(t)
return setmetatable(t, example_hat_mt)
end
local function new_example_hat(size, color, name)
return cast_example_hat({
["size"] = size;
["color"] = color;
["name"] = name;
})
end
return {
cast = cast_example_hat;
new = new_example_hat;
}
| 19.147059 | 103 | 0.717358 |
9c7b95b7285bed90d2edd1c8d62770c7c759ff92 | 339 | js | JavaScript | WebContent/app/contents/01ma/ma04MrkOpt/services/ma.MrkOpt.svc.js | edentns/MarketManagerWeb | 4397dcf437f74bdd14ce4d8ce65fddf196d4780b | [
"BSD-3-Clause"
] | 1 | 2020-07-23T13:52:08.000Z | 2020-07-23T13:52:08.000Z | WebContent/app/contents/01ma/ma04MrkOpt/services/ma.MrkOpt.svc.js | edentns/MarketManagerWeb | 4397dcf437f74bdd14ce4d8ce65fddf196d4780b | [
"BSD-3-Clause"
] | null | null | null | WebContent/app/contents/01ma/ma04MrkOpt/services/ma.MrkOpt.svc.js | edentns/MarketManagerWeb | 4397dcf437f74bdd14ce4d8ce65fddf196d4780b | [
"BSD-3-Clause"
] | null | null | null | (function () {
"use strict";
/**
* @ngdoc function
* @name ma.MrkOpt.service : ma.MrkOptSvc
* MrkOpt에 ""를 관리한다.
*/
angular.module("ma.MrkOpt.service")
.factory("ma.MrkOptSvc", ["APP_CONFIG", "$http", function (APP_CONFIG, $http) {
return {
};
}]);
}()); | 24.214286 | 88 | 0.471976 |
c644b25b0dfa630e1d5fbb1ab32ef2b21f006ae8 | 45 | sql | SQL | beeline-utils/hql/chicago/createDatabase.sql | zhuwbigdata/hadoop-admin-utils | bc0f3ca13d75c7e0e2e849102da7abfdf0771419 | [
"Apache-2.0"
] | 7 | 2016-10-11T14:58:48.000Z | 2021-01-04T08:43:40.000Z | beeline-utils/hql/chicago/createDatabase.sql | zhuwbigdata/hadoop-admin-utils | bc0f3ca13d75c7e0e2e849102da7abfdf0771419 | [
"Apache-2.0"
] | 1 | 2019-09-19T19:46:53.000Z | 2019-09-19T19:46:53.000Z | beeline-utils/hql/chicago/createDatabase.sql | zhuwbigdata/hadoop-admin-utils | bc0f3ca13d75c7e0e2e849102da7abfdf0771419 | [
"Apache-2.0"
] | 3 | 2016-10-16T16:08:17.000Z | 2019-04-30T02:26:07.000Z | CREATE DATABASE IF NOT EXISTS chicago;
!quit
| 15 | 38 | 0.8 |
e76ae0a55c4c5aa9b8e98fc87c0a9ce5d8b8efbb | 232 | js | JavaScript | migrations/2_erc20_migration.js | ethtective/contracts | 7e437e446904cd8599f707e1e7e0f4ea89191289 | [
"MIT"
] | null | null | null | migrations/2_erc20_migration.js | ethtective/contracts | 7e437e446904cd8599f707e1e7e0f4ea89191289 | [
"MIT"
] | null | null | null | migrations/2_erc20_migration.js | ethtective/contracts | 7e437e446904cd8599f707e1e7e0f4ea89191289 | [
"MIT"
] | null | null | null | const Ethtective20 = artifacts.require("./Ethtective20.sol");
module.exports = async function(deployer) {
await deployer.deploy(Ethtective20, "Ethtective20", "Ethtective20");
const eth20 = await Ethtective20.deployed();
};
| 33.142857 | 72 | 0.741379 |
c330ae7d44ce390ea2d213dc57eada5f0a26b8aa | 145 | go | Go | leetcode/classical_01_03.go | Zchary-Ma/go101 | c37866bda126c749860b8e149544f884993dccd6 | [
"MIT"
] | 1 | 2021-11-10T10:02:24.000Z | 2021-11-10T10:02:24.000Z | leetcode/classical_01_03.go | Zchary-Ma/go101 | c37866bda126c749860b8e149544f884993dccd6 | [
"MIT"
] | null | null | null | leetcode/classical_01_03.go | Zchary-Ma/go101 | c37866bda126c749860b8e149544f884993dccd6 | [
"MIT"
] | null | null | null | package leetcode
import (
"strings"
)
func replaceSpaces(S string, length int) string {
return strings.Replace(S[:length], " ", "%20", -1)
}
| 14.5 | 51 | 0.668966 |
26b8e83a390acdd0635b17f6280fc7f23e8afc0f | 16,523 | java | Java | src/main/java/org/jlab/jaws/ActivationRule.java | JeffersonLab/shelved-timer | 90a286d796ac0d48d0c8a9258ff69bd9251f5a3f | [
"MIT"
] | null | null | null | src/main/java/org/jlab/jaws/ActivationRule.java | JeffersonLab/shelved-timer | 90a286d796ac0d48d0c8a9258ff69bd9251f5a3f | [
"MIT"
] | 1 | 2021-03-25T13:33:39.000Z | 2021-03-25T13:33:39.000Z | src/main/java/org/jlab/jaws/ActivationRule.java | JeffersonLab/shelved-timer | 90a286d796ac0d48d0c8a9258ff69bd9251f5a3f | [
"MIT"
] | null | null | null | package org.jlab.jaws;
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.*;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.state.KeyValueStore;
import org.apache.kafka.streams.state.StoreBuilder;
import org.apache.kafka.streams.state.Stores;
import org.jlab.jaws.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static io.confluent.kafka.serializers.AbstractKafkaSchemaSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG;
/**
* Streams rule to join the activation and override topics into a single topic that is ordered (single partition)
* such that processing can be done.
*
* A store of the previous active record for each alarm is used to determine
* transitions from active to normal and back.
*/
public class ActivationRule extends ProcessingRule {
private static final Logger log = LoggerFactory.getLogger(ActivationRule.class);
String inputTopicRegisteredMonolog;
String inputTopicActive;
String inputTopicOverridden;
public static final Serdes.StringSerde ACTIVE_KEY_SERDE = new Serdes.StringSerde();
public static final SpecificAvroSerde<AlarmActivationUnion> ACTIVE_VALUE_SERDE = new SpecificAvroSerde<>();
public static final SpecificAvroSerde<OverriddenAlarmKey> OVERRIDE_KEY_SERDE = new SpecificAvroSerde<>();
public static final SpecificAvroSerde<AlarmOverrideUnion> OVERRIDE_VALUE_SERDE = new SpecificAvroSerde<>();
public static final Serdes.StringSerde MONOLOG_KEY_SERDE = new Serdes.StringSerde();
public static final SpecificAvroSerde<IntermediateMonolog> MONOLOG_VALUE_SERDE = new SpecificAvroSerde<>();
public static final SpecificAvroSerde<OverrideList> OVERRIDE_LIST_VALUE_SERDE = new SpecificAvroSerde<>();
public ActivationRule(String inputTopicRegisteredMonolog, String inputTopicActive, String inputTopicOverridden, String outputTopic) {
super(null, outputTopic);
this.inputTopicRegisteredMonolog = inputTopicRegisteredMonolog;
this.inputTopicActive = inputTopicActive;
this.inputTopicOverridden = inputTopicOverridden;
}
@Override
public Properties constructProperties() {
final Properties props = super.constructProperties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "jaws-alarm-processor-activation");
return props;
}
@Override
public Topology constructTopology(Properties props) {
final StreamsBuilder builder = new StreamsBuilder();
// If you get an unhelpful NullPointerException in the depths of the AVRO deserializer it's likely because you didn't set registry config
Map<String, String> config = new HashMap<>();
config.put(SCHEMA_REGISTRY_URL_CONFIG, props.getProperty(SCHEMA_REGISTRY_URL_CONFIG));
ACTIVE_VALUE_SERDE.configure(config, false);
OVERRIDE_KEY_SERDE.configure(config, true);
OVERRIDE_VALUE_SERDE.configure(config, false);
MONOLOG_VALUE_SERDE.configure(config, false);
OVERRIDE_LIST_VALUE_SERDE.configure(config, false);
final KTable<String, IntermediateMonolog> registeredMonologTable = builder.table(inputTopicRegisteredMonolog,
Consumed.as("Registered-Table").with(MONOLOG_KEY_SERDE, MONOLOG_VALUE_SERDE));
final KTable<String, AlarmActivationUnion> activeTable = builder.table(inputTopicActive,
Consumed.as("Active-Table").with(ACTIVE_KEY_SERDE, ACTIVE_VALUE_SERDE));
KTable<String, IntermediateMonolog> registeredAndActive = registeredMonologTable.outerJoin(activeTable,
new RegisteredAndActiveJoiner(), Materialized.with(Serdes.String(), MONOLOG_VALUE_SERDE))
.filter(new Predicate<String, IntermediateMonolog>() {
@Override
public boolean test(String key, IntermediateMonolog value) {
log.debug("CLASS-ACTIVE JOIN RESULT: key: " + key + "\n\tregistered: " + value.getRegistration() + ", \n\tactive: " + value.getActivation());
return true;
}
});
KTable<String, OverrideList> overriddenItems = getOverriddenViaGroupBy(builder);
KTable<String, IntermediateMonolog> plusOverrides = registeredAndActive.outerJoin(overriddenItems, new OverrideJoiner())
.filter(new Predicate<String, IntermediateMonolog>() {
@Override
public boolean test(String key, IntermediateMonolog value) {
log.debug("ACTIVE-OVERRIDE JOIN RESULT: key: " + key + "\n\tregistered: " + value.getRegistration() + ", \n\tactive: " + value.getActivation());
return true;
}
});
final StoreBuilder<KeyValueStore<String, AlarmActivationUnion>> storeBuilder = Stores.keyValueStoreBuilder(
Stores.persistentKeyValueStore("PreviousActiveStateStore"),
ACTIVE_KEY_SERDE,
ACTIVE_VALUE_SERDE
).withCachingEnabled();
builder.addStateStore(storeBuilder);
// Ensure we always return non-null Alarm record and populate it with transition state
final KStream<String, IntermediateMonolog> withTransitionState = plusOverrides.toStream()
.transform(new ActivationRule.MsgTransformerFactory(storeBuilder.name()),
Named.as("ActiveTransitionStateProcessor"),
storeBuilder.name());
final KStream<String, IntermediateMonolog> withHeaders = withTransitionState
.transform(new MonologAddHeadersFactory());
withHeaders.to(outputTopic, Produced.as("Monolog")
.with(MONOLOG_KEY_SERDE, MONOLOG_VALUE_SERDE));
return builder.build();
}
private final class RegisteredAndActiveJoiner implements ValueJoiner<IntermediateMonolog, AlarmActivationUnion, IntermediateMonolog> {
public IntermediateMonolog apply(IntermediateMonolog registered, AlarmActivationUnion active) {
//System.err.println("active joiner: " + active + ", registered: " + registered);
EffectiveRegistration effectiveReg = EffectiveRegistration.newBuilder()
.setClass$(null)
.setActual(null)
.setCalculated(null)
.build();
EffectiveActivation effectiveAct = EffectiveActivation.newBuilder()
.setActual(active)
.setOverrides(new AlarmOverrideSet())
.setState(AlarmState.Normal)
.build();
IntermediateMonolog result = IntermediateMonolog.newBuilder()
.setRegistration(effectiveReg)
.setActivation(effectiveAct)
.setTransitions(new ProcessorTransitions())
.build();
if(registered != null) {
result.getRegistration().setActual(registered.getRegistration().getActual());
result.getRegistration().setClass$(registered.getRegistration().getClass$());
result.getRegistration().setCalculated(registered.getRegistration().getCalculated());
}
return result;
}
}
private final class OverrideJoiner implements ValueJoiner<IntermediateMonolog, OverrideList, IntermediateMonolog> {
public IntermediateMonolog apply(IntermediateMonolog registeredAndActive, OverrideList overrideList) {
//System.err.println("override joiner: " + registeredAndActive);
AlarmOverrideSet overrides = AlarmOverrideSet.newBuilder()
.setDisabled(null)
.setFiltered(null)
.setLatched(null)
.setMasked(null)
.setOffdelayed(null)
.setOndelayed(null)
.setShelved(null)
.build();
if(overrideList != null) {
for(AlarmOverrideUnion over: overrideList.getOverrides()) {
if(over.getMsg() instanceof DisabledOverride) {
overrides.setDisabled((DisabledOverride) over.getMsg());
}
if(over.getMsg() instanceof FilteredOverride) {
overrides.setFiltered((FilteredOverride) over.getMsg());
}
if(over.getMsg() instanceof LatchedOverride) {
overrides.setLatched((LatchedOverride) over.getMsg());
}
if(over.getMsg() instanceof MaskedOverride) {
overrides.setMasked((MaskedOverride) over.getMsg());
}
if(over.getMsg() instanceof OnDelayedOverride) {
overrides.setOndelayed((OnDelayedOverride) over.getMsg());
}
if(over.getMsg() instanceof OffDelayedOverride) {
overrides.setOffdelayed((OffDelayedOverride) over.getMsg());
}
if(over.getMsg() instanceof ShelvedOverride) {
overrides.setShelved((ShelvedOverride) over.getMsg());
}
}
}
IntermediateMonolog result;
if(registeredAndActive != null) {
result = IntermediateMonolog.newBuilder(registeredAndActive)
.build();
result.getActivation().setOverrides(overrides);
} else {
EffectiveRegistration effectiveReg = EffectiveRegistration.newBuilder()
.build();
EffectiveActivation effectiveAct = EffectiveActivation.newBuilder()
.setOverrides(overrides)
.setState(AlarmState.Normal)
.build();
result = IntermediateMonolog.newBuilder()
.setRegistration(effectiveReg)
.setActivation(effectiveAct)
.setTransitions(new ProcessorTransitions())
.build();
}
return result;
}
}
private KTable<String, OverrideList> getOverriddenViaGroupBy(StreamsBuilder builder) {
final KTable<OverriddenAlarmKey, AlarmOverrideUnion> overriddenTable = builder.table(inputTopicOverridden,
Consumed.as("Overridden-Table").with(OVERRIDE_KEY_SERDE, OVERRIDE_VALUE_SERDE));
final KTable<String, OverrideList> groupTable = overriddenTable
.groupBy((key, value) -> groupOverride(key, value), Grouped.as("Grouped-Overrides")
.with(Serdes.String(), OVERRIDE_LIST_VALUE_SERDE))
.aggregate(
() -> new OverrideList(new ArrayList<>()),
(key, newValue, aggregate) -> {
//System.err.println("add: " + key + ", " + newValue + ", " + aggregate);
if(newValue.getOverrides() != null && aggregate != null && aggregate.getOverrides() != null) {
aggregate.getOverrides().addAll(newValue.getOverrides());
}
return aggregate;
},
(key, oldValue, aggregate) -> {
//System.err.println("subtract: " + key + ", " + oldValue + ", " + aggregate);
ArrayList<AlarmOverrideUnion> tmp = new ArrayList<>(aggregate.getOverrides());
for(AlarmOverrideUnion oav: oldValue.getOverrides()) {
tmp.remove(oav);
}
return new OverrideList(tmp);
},
Materialized.as("Override-Criteria-Table").with(Serdes.String(), OVERRIDE_LIST_VALUE_SERDE));
return groupTable;
}
private static KeyValue<String, OverrideList> groupOverride(OverriddenAlarmKey key, AlarmOverrideUnion value) {
List<AlarmOverrideUnion> list = new ArrayList<>();
list.add(value);
return new KeyValue<>(key.getName(), new OverrideList(list));
}
private static final class MsgTransformerFactory implements TransformerSupplier<String, IntermediateMonolog, KeyValue<String, IntermediateMonolog>> {
private final String storeName;
/**
* Create a new MsgTransformerFactory.
*
* @param storeName The state store name
*/
public MsgTransformerFactory(String storeName) {
this.storeName = storeName;
}
/**
* Return a new {@link Transformer} instance.
*
* @return a new {@link Transformer} instance
*/
@Override
public Transformer<String, IntermediateMonolog, KeyValue<String, IntermediateMonolog>> get() {
return new Transformer<String, IntermediateMonolog, KeyValue<String, IntermediateMonolog>>() {
private KeyValueStore<String, AlarmActivationUnion> store;
private ProcessorContext context;
@Override
@SuppressWarnings("unchecked") // https://cwiki.apache.org/confluence/display/KAFKA/KIP-478+-+Strongly+typed+Processor+API
public void init(ProcessorContext context) {
this.context = context;
this.store = (KeyValueStore<String, AlarmActivationUnion>) context.getStateStore(storeName);
}
@Override
public KeyValue<String, IntermediateMonolog> transform(String key, IntermediateMonolog value) {
AlarmActivationUnion previous = store.get(key);
AlarmActivationUnion next = null;
//System.err.println("previous: " + previous);
//System.err.println("next: " + (value == null ? null : value.getActive()));
boolean transitionToActive = false;
boolean transitionToNormal = false;
// Handle Scenario where only one of Registration or Activation and it just got tombstoned!
// Instead of forwarding IntermediateMonolog = null we always forward non-null IntermediateMonolog,
// but fields inside may be null
if(value == null) {
EffectiveRegistration effectiveReg = EffectiveRegistration.newBuilder().build();
EffectiveActivation effectiveAct = EffectiveActivation.newBuilder()
.setOverrides(new AlarmOverrideSet())
.setState(AlarmState.Normal)
.build();
value = IntermediateMonolog.newBuilder()
.setRegistration(effectiveReg)
.setActivation(effectiveAct)
.setTransitions(new ProcessorTransitions())
.build();
}
next = value.getActivation().getActual();
if (previous == null && next != null) {
//System.err.println("TRANSITION TO ACTIVE!");
transitionToActive = true;
} else if(previous != null && next == null) {
//System.err.println("TRANSITION TO NORMAL!");
transitionToNormal = true;
}
store.put(key, next);
value.getTransitions().setTransitionToActive(transitionToActive);
value.getTransitions().setTransitionToNormal(transitionToNormal);
log.trace("Transformed: {}={}", key, value);
return new KeyValue<>(key, value);
}
@Override
public void close() {
// Nothing to do
}
};
}
}
}
| 45.268493 | 168 | 0.60092 |
7140212d0ad023a39b34c17cbec3576c4f1d368c | 4,626 | ts | TypeScript | user/src/service/controller.ts | aufacicenta/rapydbot | 84413fb882b73d4dd89c4f7c645d8a2fe39bdcff | [
"MIT"
] | 1 | 2021-07-17T16:20:07.000Z | 2021-07-17T16:20:07.000Z | user/src/service/controller.ts | aufacicenta/rapydbot | 84413fb882b73d4dd89c4f7c645d8a2fe39bdcff | [
"MIT"
] | 19 | 2021-05-27T21:29:04.000Z | 2021-07-19T17:28:43.000Z | user/src/service/controller.ts | aufacicenta/rapydbot | 84413fb882b73d4dd89c4f7c645d8a2fe39bdcff | [
"MIT"
] | 1 | 2021-05-28T01:25:49.000Z | 2021-05-28T01:25:49.000Z | import grpc from "grpc";
import { injectable } from "inversify";
import "reflect-metadata";
import { IContext } from "../server/interface/IContext";
import {
CreateUserReply,
CreateUserRequest,
FindUserByTelegramUserIdReply,
FindUserByTelegramUserIdRequest,
GetUserIdByTelegramUsernameReply,
GetUserIdByTelegramUsernameRequest,
GetUserReply,
GetUserRequest,
GetUsersRequest,
GetUserTelegramChatIdReply,
GetUserTelegramChatIdRequest,
} from "../server/protos/schema_pb";
type GRPCUnaryCall<Request, Reply> = {
call: grpc.ServerUnaryCall<Request>;
callback: grpc.sendUnaryData<Reply>;
};
type gRPCServerStreamingCall<Request, Reply> = {
call: grpc.ServerWritableStream<Request>;
};
@injectable()
export class Controller {
public static type: string = "Controller";
async findUserByTelegramUserIdOrCreateUser(
{ call, callback }: GRPCUnaryCall<CreateUserRequest, CreateUserReply>,
{ dao }: IContext
) {
try {
const telegram_from_user_id = call.request.getTelegramFromUserId();
const telegram_username = call.request.getTelegramUsername();
const telegram_private_chat_id = call.request.getTelegramPrivateChatId();
const result = await dao.UserDAO.findUserByTelegramUserIdOrCreateUser({
telegram_from_user_id,
telegram_username,
telegram_private_chat_id,
});
const reply = new CreateUserReply();
reply.setUserId(result.userId);
reply.setTelegramFromUserId(result.telegramFromUserId);
reply.setTelegramUsername(result.telegramUsername);
reply.setTelegramPrivateChatId(result.telegramPrivateChatId);
callback(null, reply);
} catch (error) {
callback(error, null);
}
}
async getUser(
{ call, callback }: GRPCUnaryCall<GetUserRequest, GetUserReply>,
{ dao }: IContext
) {
try {
const user_id = call.request.getUserId();
const result = await dao.UserDAO.getUser({
user_id,
});
const reply = new GetUserReply();
reply.setUserId(result.userId);
reply.setTelegramFromUserId(result.telegramFromUserId);
reply.setTelegramUsername(result.telegramUsername);
reply.setTelegramPrivateChatId(result.telegramPrivateChatId);
callback(null, reply);
} catch (error) {
callback(error, null);
}
}
async getUsers(
{ call }: gRPCServerStreamingCall<GetUsersRequest, GetUserReply>,
{ dao }: IContext
) {
const user_ids = call.request.getUserIdList();
const result = await dao.UserDAO.getUsers({
user_ids,
});
for (const user of result) {
const reply = new GetUserReply();
reply.setUserId(user.userId);
reply.setTelegramFromUserId(user.telegramFromUserId);
reply.setTelegramUsername(user.telegramUsername);
reply.setTelegramPrivateChatId(user.telegramPrivateChatId);
call.write(reply, (err) => {
if (err) {
console.error(err);
}
});
}
call.end();
}
async findUserByTelegramUserId(
{
call,
callback,
}: GRPCUnaryCall<FindUserByTelegramUserIdRequest, FindUserByTelegramUserIdReply>,
{ dao }: IContext
) {
try {
const telegram_from_user_id = call.request.getTelegramFromUserId();
const result = await dao.UserDAO.findUserByTelegramUserId({
telegram_from_user_id,
});
const reply = new FindUserByTelegramUserIdReply();
reply.setUserId(result.userId);
callback(null, reply);
} catch (error) {
callback(error, null);
}
}
async getUserIdByTelegramUsername(
{
call,
callback,
}: GRPCUnaryCall<GetUserIdByTelegramUsernameRequest, GetUserIdByTelegramUsernameReply>,
{ dao }: IContext
) {
try {
const username = call.request.getTelegramUsername();
const result = await dao.UserDAO.findUserByTelegramUsername({
username,
});
const reply = new GetUserIdByTelegramUsernameReply();
reply.setUserId(result.userId);
callback(null, reply);
} catch (error) {
callback(error, null);
}
}
async getUserTelegramChatId(
{ call, callback }: GRPCUnaryCall<GetUserTelegramChatIdRequest, GetUserTelegramChatIdReply>,
{ dao }: IContext
) {
try {
const user_id = call.request.getUserId();
const private_chat_id = await dao.UserDAO.getUserTelegramChatId({
userId: user_id,
});
const reply = new GetUserTelegramChatIdReply();
reply.setPrivateChatId(private_chat_id);
callback(null, reply);
} catch (error) {
callback(error, null);
}
}
}
| 25.7 | 96 | 0.681799 |
6f9e0c0ab79bcfaf9c2ba93c03b527b993224b23 | 633 | rs | Rust | updater-bin/src/version.rs | AmionSky/updater | 7f9220b487d8ba42733dae93b3d3ff1f96e5b5ae | [
"MIT"
] | 1 | 2020-05-12T06:46:39.000Z | 2020-05-12T06:46:39.000Z | updater-bin/src/version.rs | AmionSky/updater | 7f9220b487d8ba42733dae93b3d3ff1f96e5b5ae | [
"MIT"
] | null | null | null | updater-bin/src/version.rs | AmionSky/updater | 7f9220b487d8ba42733dae93b3d3ff1f96e5b5ae | [
"MIT"
] | null | null | null | use semver::Version;
use std::error::Error;
use std::path::{Path, PathBuf};
pub const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
pub fn app_file<P: AsRef<Path>>(wd: P) -> PathBuf {
wd.as_ref().join("version.txt")
}
pub fn read_file<P: AsRef<Path>>(version_file: P) -> Option<Version> {
if version_file.as_ref().exists() {
let text = std::fs::read_to_string(version_file).ok()?;
Some(Version::parse(&text).ok()?)
} else {
None
}
}
pub fn write_file<P: AsRef<Path>>(file: P, version: &Version) -> Result<(), Box<dyn Error>> {
std::fs::write(file, version.to_string())?;
Ok(())
}
| 26.375 | 93 | 0.614534 |
47651a9d21bd0aa522af677e5058cf89d99b4967 | 1,225 | html | HTML | web/index.html | 1548162311/test | 0aa7faaf81626aa1efd16284fcef8b75ce9004dd | [
"Apache-2.0"
] | null | null | null | web/index.html | 1548162311/test | 0aa7faaf81626aa1efd16284fcef8b75ce9004dd | [
"Apache-2.0"
] | null | null | null | web/index.html | 1548162311/test | 0aa7faaf81626aa1efd16284fcef8b75ce9004dd | [
"Apache-2.0"
] | null | null | null | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0;" name="viweport">
<title>first html</title>
</head>
<body>
<div>测试第一阶段</div>
<div>测试第二阶段</div>
<img src="https://www.baidu.com/img/bd_logo1.png" width="270" height="129">
<dl>
<dt>测试</dt>
<dd>this is a test</dd>
</dl>
<b>我是加粗</b>
<u>我是U</u> 
<i>我是i</i> 
<s>我是殺殺殺</s>
<ul>
<li>hheheh</li>
<li>
<a href="">好聲音内幕</a>
</li>
<li>wwwwwww</li>
<li>eeeeeee</li>
<li>adsadsadsa</li>
<li>egdfdasdsadsafkk/li>
</ul>
<table width="200" border="1">
<thead>
<tr>
<th>姓名</th>
<th>名次</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2">郑珊珊第三</td>
</tr>
<tr>
<td rowspan="2">张三网只</td>
<td>第二</td>
</tr>
<tr>
<td>第一</td>
</tr>
</tbody>
</table>
<iframe src="https://www.baidu.com" width="500" height="500"></iframe>
</body>
</html>
| 20.762712 | 92 | 0.42449 |
f076d7596035ea99f16b2ee688410ac4e2c0be9a | 2,292 | py | Python | tests/coro.py | dshean/sliderule-python | 3cf9a6c65987705354cb536d71f85a32fbb24d15 | [
"BSD-3-Clause"
] | 1 | 2021-04-09T22:01:33.000Z | 2021-04-09T22:01:33.000Z | tests/coro.py | dshean/sliderule-python | 3cf9a6c65987705354cb536d71f85a32fbb24d15 | [
"BSD-3-Clause"
] | null | null | null | tests/coro.py | dshean/sliderule-python | 3cf9a6c65987705354cb536d71f85a32fbb24d15 | [
"BSD-3-Clause"
] | null | null | null | # python
import sys
import h5coro
###############################################################################
# DATA
###############################################################################
# set resource
resource = "file:///data/ATLAS/ATL06_20200714160647_02950802_003_01.h5"
# expected single read
h_li_exp_1 = [3432.17578125, 3438.776611328125, 3451.01123046875, 3462.688232421875, 3473.559326171875]
# expected parallel read
h_li_exp_2 = { '/gt1l/land_ice_segments/h_li': [3432.17578125, 3438.776611328125, 3451.01123046875, 3462.688232421875, 3473.559326171875],
'/gt2l/land_ice_segments/h_li': [3263.659912109375, 3258.362548828125, 3.4028234663852886e+38, 3233.031494140625, 3235.200927734375],
'/gt3l/land_ice_segments/h_li': [3043.489013671875, 3187.576171875, 3.4028234663852886e+38, 4205.04248046875, 2924.724365234375]}
###############################################################################
# UTILITY FUNCTIONS
###############################################################################
def check_results(act, exp):
if type(exp) == dict:
for dataset in exp:
for i in range(len(exp[dataset])):
if exp[dataset][i] != act[dataset][i]:
print("Failed parallel read test")
return False
print("Passed parallel read test")
return True
else:
for i in range(len(exp)):
if exp[i] != act[i]:
print("Failed single read test")
return False
print("Passed single read test")
return True
###############################################################################
# MAIN
###############################################################################
if __name__ == '__main__':
# Open H5Coro File #
h5file = h5coro.file(resource)
# Perform Single Read #
h_li_1 = h5file.read("/gt1l/land_ice_segments/h_li", 0, 19, 5)
check_results(h_li_1, h_li_exp_1)
# Perform Parallel Read #
datasets = [["/gt1l/land_ice_segments/h_li", 0, 19, 5],
["/gt2l/land_ice_segments/h_li", 0, 19, 5],
["/gt3l/land_ice_segments/h_li", 0, 19, 5]]
h_li_2 = h5file.readp(datasets)
check_results(h_li_2, h_li_exp_2)
| 38.2 | 149 | 0.505236 |
4a5aa620ff9ed592919f5f987eba7f9cf4bdcb44 | 1,228 | js | JavaScript | src/components/Landing.js | Dragoris/people-and-projects | f773fce6db936763723e6081a93eff728894ccee | [
"MIT"
] | null | null | null | src/components/Landing.js | Dragoris/people-and-projects | f773fce6db936763723e6081a93eff728894ccee | [
"MIT"
] | null | null | null | src/components/Landing.js | Dragoris/people-and-projects | f773fce6db936763723e6081a93eff728894ccee | [
"MIT"
] | null | null | null | import React from "react"
import Form from 'react-bootstrap/Form'
import Row from 'react-bootstrap/Row'
import Button from 'react-bootstrap/Button'
import Col from 'react-bootstrap/Col'
import { Link } from "gatsby"
import UseButtons from './UseButtons'
const containerStyle = {
position: 'absolute',
top: '0',
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
height: '100vh',
width: '100vw',
alignItems: 'center',
}
const title = {
fontWeight: 700,
textAlign: 'center'
}
const Landing = () => (
<div style={containerStyle}>
<div className="px-4">
<h1 style={title}> Find Your Entitlement Risk</h1>
<UseButtons />
<Form className="pt-2">
<Form.Group controlId="search" className="d-flex align-items-center">
<Col sm={9}>
<Form.Control as="select" placeholder="Enter City Here">
<option>Select a City</option>
<option>San Jose, CA</option>
</Form.Control>
</Col>
<Col sm={3}>
<Button className="w-100">
<Link style={{color: '#fff', textDecoration: 'none'}} to="/people">Search</Link>
</Button>
</Col>
</Form.Group>
</Form>
</div>
</div>
)
export default Landing
| 22.327273 | 89 | 0.619707 |