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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8b364961b1a2dc1e766af3840583a746bd49680c | 222 | swift | Swift | JPHacks_Hackamon_Brothers/JPHacks_Hackamon_Brothers/NotificationWithTool.swift | en-i/FK_1909 | 228d51074f5eceadae59a863d7e46f2e9e84fc63 | [
"MIT"
] | null | null | null | JPHacks_Hackamon_Brothers/JPHacks_Hackamon_Brothers/NotificationWithTool.swift | en-i/FK_1909 | 228d51074f5eceadae59a863d7e46f2e9e84fc63 | [
"MIT"
] | null | null | null | JPHacks_Hackamon_Brothers/JPHacks_Hackamon_Brothers/NotificationWithTool.swift | en-i/FK_1909 | 228d51074f5eceadae59a863d7e46f2e9e84fc63 | [
"MIT"
] | 1 | 2020-11-05T10:06:13.000Z | 2020-11-05T10:06:13.000Z | //
// NotificationWithTool.swift
// JPHacks_Hackamon_Brothers
//
// Created by 鈴木俊亮 on 2019/10/19.
// Copyright © 2019 藤山裕輝. All rights reserved.
//
import Foundation
class NotificationWithTool
{
// TODO Suzuki
}
| 14.8 | 47 | 0.711712 |
b53930e00b8e30d1a30458d8ec17684e16e3dbf7 | 1,507 | rs | Rust | cross-checks/rust-checks/backends/fakechecks-zstd/src/bin/printer.rs | sjvs/c2rust | 0eb7359b35f9159c446074748d9dbd09fb212ce9 | [
"BSD-3-Clause"
] | null | null | null | cross-checks/rust-checks/backends/fakechecks-zstd/src/bin/printer.rs | sjvs/c2rust | 0eb7359b35f9159c446074748d9dbd09fb212ce9 | [
"BSD-3-Clause"
] | null | null | null | cross-checks/rust-checks/backends/fakechecks-zstd/src/bin/printer.rs | sjvs/c2rust | 0eb7359b35f9159c446074748d9dbd09fb212ce9 | [
"BSD-3-Clause"
] | null | null | null | #![feature(int_to_from_bytes)]
extern crate zstd;
use std::fmt;
use std::fs::File;
use std::io;
use std::io::{Read, Write};
use std::env;
const BUF_SIZE: usize = 4 * 1024 * 1024; // 4MB buffer
const MAX_XCHECK_LEN: usize = 52;
pub fn main() -> Result<(), std::io::Error> {
let mut out = String::with_capacity(BUF_SIZE);
for arg in env::args() {
let file = File::open(arg)?;
let mut reader = zstd::stream::Decoder::new(file)?;
loop {
let mut buf = [0u8; 9];
if reader.read_exact(&mut buf).is_err() {
break;
}
let mut val_buf = [0u8; 8];
val_buf.copy_from_slice(&buf[1..]);
let val = u64::from_le(u64::from_bytes(val_buf));
if out.len() >= BUF_SIZE - MAX_XCHECK_LEN {
io::stdout().write_all(out.as_bytes())?;
out.clear();
}
let old_len = out.len();
let tag_name = match buf[0] {
0 => "Unk",
1 => "Ent",
2 => "Exi",
3 => "Arg",
4 => "Ret",
_ => panic!("Unknown cross-check tag: {}", buf[0])
};
fmt::write(&mut out, format_args!("XCHECK({0}):{1:}/0x{1:08x}\n", tag_name, val))
.expect("Error formatting xcheck");
assert!(out.len() <= old_len + MAX_XCHECK_LEN);
}
}
// Flush the buffer
io::stdout().write_all(out.as_bytes())?;
Ok(())
}
| 30.755102 | 93 | 0.480425 |
8567f6d7d465f74f2b389ee1a3af3783e28d85f5 | 1,729 | js | JavaScript | src/store/modules/dependencies/models.js | altest-com/siice-spa | 579b5711886367755d8fae44da24e7bda15a9406 | [
"MIT"
] | null | null | null | src/store/modules/dependencies/models.js | altest-com/siice-spa | 579b5711886367755d8fae44da24e7bda15a9406 | [
"MIT"
] | null | null | null | src/store/modules/dependencies/models.js | altest-com/siice-spa | 579b5711886367755d8fae44da24e7bda15a9406 | [
"MIT"
] | null | null | null | import { Model } from 'vrudex';
class DependencyModel extends Model {
props = {
id: {
writable: false,
api: 'id',
type: Number
},
name: {
writable: true,
api: 'name',
type: String
},
corporation: {
writable: true,
api: 'corporation',
type: Number
},
createdAt: {
writable: false,
api: 'created_at',
type: Date
},
updatedAt: {
writable: false,
api: 'updated_at',
type: Date
}
}
}
const dependencyModel = new DependencyModel();
Object.freeze(dependencyModel);
class DependencyFilter extends Model {
ORDER_CHOICES = {
'name': 'Nombre',
'created_at': 'Fecha de creación',
'corporation__name': 'Corporación'
}
props = {
orderBy: {
writable: true,
api: 'order_by',
type: String,
default: '-created_at'
},
name: {
writable: true,
api: 'name__icontains',
type: String
},
corporations: {
writable: true,
api: 'corporation_id__in',
type: Number,
many: true
},
minCreatedAt: {
writable: false,
api: 'created_at__gte',
type: Date
},
maxCreatedAt: {
writable: false,
api: 'created_at__gte',
type: Date
}
}
}
const dependencyFilter = new DependencyFilter();
Object.freeze(dependencyFilter);
export {
dependencyModel,
dependencyFilter
};
| 21.345679 | 48 | 0.465009 |
1aedc086e927d6435e3304442fbc059ae3f14c95 | 306 | kt | Kotlin | libraries/server/src/main/java/com/chesire/nekome/server/api/UserApi.kt | mvvm-android/Nekome | a434618e0a27a16a4f292e34bb21465cf8895b9f | [
"Apache-2.0"
] | null | null | null | libraries/server/src/main/java/com/chesire/nekome/server/api/UserApi.kt | mvvm-android/Nekome | a434618e0a27a16a4f292e34bb21465cf8895b9f | [
"Apache-2.0"
] | null | null | null | libraries/server/src/main/java/com/chesire/nekome/server/api/UserApi.kt | mvvm-android/Nekome | a434618e0a27a16a4f292e34bb21465cf8895b9f | [
"Apache-2.0"
] | null | null | null | package com.chesire.nekome.server.api
import com.chesire.nekome.core.models.UserModel
import com.chesire.nekome.server.Resource
/**
* Methods relating to a users profile.
*/
interface UserApi {
/**
* Get all of the user details.
*/
suspend fun getUserDetails(): Resource<UserModel>
}
| 20.4 | 53 | 0.712418 |
166994c716ace56c40dd8932f12c7873b8921edf | 4,651 | c | C | mc/model/com.mentor.nucleus.bp.core/src416/ooaofooa_R_SUB_class.c | NDGuthrie/bposs | 2c47abf74a3e6fadb174b08e57aa66a209400606 | [
"Apache-2.0"
] | 1 | 2018-01-24T16:28:01.000Z | 2018-01-24T16:28:01.000Z | mc/model/com.mentor.nucleus.bp.core/src418/ooaofooa_R_SUB_class.c | NDGuthrie/bposs | 2c47abf74a3e6fadb174b08e57aa66a209400606 | [
"Apache-2.0"
] | null | null | null | mc/model/com.mentor.nucleus.bp.core/src418/ooaofooa_R_SUB_class.c | NDGuthrie/bposs | 2c47abf74a3e6fadb174b08e57aa66a209400606 | [
"Apache-2.0"
] | null | null | null | /*----------------------------------------------------------------------------
* File: ooaofooa_R_SUB_class.c
*
* Class: Class As Subtype (R_SUB)
* Component: ooaofooa
*
* your copyright statement can go here (from te_copyright.body)
*--------------------------------------------------------------------------*/
#include "sys_sys_types.h"
#include "LOG_bridge.h"
#include "POP_bridge.h"
#include "T_bridge.h"
#include "ooaofooa_classes.h"
/*
* Instance Loader (from string data).
*/
Escher_iHandle_t
ooaofooa_R_SUB_instanceloader( Escher_iHandle_t instance, const c_t * avlstring[] )
{
Escher_iHandle_t return_identifier = 0;
ooaofooa_R_SUB * self = (ooaofooa_R_SUB *) instance;
/* Initialize application analysis class attributes. */
self->Obj_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 1 ] );
self->Rel_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 2 ] );
self->OIR_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 3 ] );
return return_identifier;
}
/*
* Select any where using referential/identifying attribute set.
* If not_empty, relate this instance to the selected instance.
*/
void ooaofooa_R_SUB_batch_relate( Escher_iHandle_t instance )
{
ooaofooa_R_SUB * ooaofooa_R_SUB_instance = (ooaofooa_R_SUB *) instance;
ooaofooa_R_SUBSUP * ooaofooa_R_SUBSUPrelated_instance1 = ooaofooa_R_SUBSUP_AnyWhere1( ooaofooa_R_SUB_instance->Rel_ID );
if ( ooaofooa_R_SUBSUPrelated_instance1 ) {
ooaofooa_R_SUB_R213_Link_relates( ooaofooa_R_SUBSUPrelated_instance1, ooaofooa_R_SUB_instance );
}
{
ooaofooa_R_RGO * ooaofooa_R_RGOrelated_instance1 = ooaofooa_R_RGO_AnyWhere1( ooaofooa_R_SUB_instance->Obj_ID, ooaofooa_R_SUB_instance->Rel_ID, ooaofooa_R_SUB_instance->OIR_ID );
if ( ooaofooa_R_RGOrelated_instance1 ) {
ooaofooa_R_SUB_R205_Link( ooaofooa_R_RGOrelated_instance1, ooaofooa_R_SUB_instance );
}
}
}
/*
* RELATE R_RGO TO R_SUB ACROSS R205
*/
void
ooaofooa_R_SUB_R205_Link( ooaofooa_R_RGO * supertype, ooaofooa_R_SUB * subtype )
{
/* Use TagEmptyHandleDetectionOn() to detect empty handle references. */
subtype->OIR_ID = supertype->OIR_ID;
subtype->Obj_ID = supertype->Obj_ID;
subtype->Rel_ID = supertype->Rel_ID;
/* Optimized linkage for R_SUB->R_RGO[R205] */
subtype->R_RGO_R205 = supertype;
/* Optimized linkage for R_RGO->R_SUB[R205] */
supertype->R205_subtype = subtype;
supertype->R205_object_id = ooaofooa_R_SUB_CLASS_NUMBER;
}
/*
* UNRELATE R_RGO FROM R_SUB ACROSS R205
*/
void
ooaofooa_R_SUB_R205_Unlink( ooaofooa_R_RGO * supertype, ooaofooa_R_SUB * subtype )
{
/* Use TagEmptyHandleDetectionOn() to detect empty handle references. */
subtype->R_RGO_R205 = 0;
supertype->R205_subtype = 0;
supertype->R205_object_id = 0;
}
/*
* RELATE R_SUBSUP TO R_SUB ACROSS R213
*/
void
ooaofooa_R_SUB_R213_Link_relates( ooaofooa_R_SUBSUP * part, ooaofooa_R_SUB * form )
{
/* Use TagEmptyHandleDetectionOn() to detect empty handle references. */
form->Rel_ID = part->Rel_ID;
form->R_SUBSUP_R213_is_related_to_supertype_via = part;
Escher_SetInsertElement( &part->R_SUB_R213_relates, (Escher_ObjectSet_s *) form );
}
/*
* UNRELATE R_SUBSUP FROM R_SUB ACROSS R213
*/
void
ooaofooa_R_SUB_R213_Unlink_relates( ooaofooa_R_SUBSUP * part, ooaofooa_R_SUB * form )
{
/* Use TagEmptyHandleDetectionOn() to detect empty handle references. */
form->R_SUBSUP_R213_is_related_to_supertype_via = 0;
Escher_SetRemoveElement( &part->R_SUB_R213_relates, (Escher_ObjectSet_s *) form );
}
/*
* Dump instances in SQL format.
*/
void
ooaofooa_R_SUB_instancedumper( Escher_iHandle_t instance )
{
ooaofooa_R_SUB * self = (ooaofooa_R_SUB *) instance;
printf( "INSERT INTO R_SUB VALUES ( %ld,%ld,%ld );\n",
((long)self->Obj_ID & ESCHER_IDDUMP_MASK),
((long)self->Rel_ID & ESCHER_IDDUMP_MASK),
((long)self->OIR_ID & ESCHER_IDDUMP_MASK) );
}
/*
* Statically allocate space for the instance population for this class.
* Allocate space for the class instance and its attribute values.
* Depending upon the collection scheme, allocate containoids (collection
* nodes) for gathering instances into free and active extents.
*/
static Escher_SetElement_s ooaofooa_R_SUB_container[ ooaofooa_R_SUB_MAX_EXTENT_SIZE ];
static ooaofooa_R_SUB ooaofooa_R_SUB_instances[ ooaofooa_R_SUB_MAX_EXTENT_SIZE ];
Escher_Extent_t pG_ooaofooa_R_SUB_extent = {
{0,0}, {0,0}, &ooaofooa_R_SUB_container[ 0 ],
(Escher_iHandle_t) &ooaofooa_R_SUB_instances,
sizeof( ooaofooa_R_SUB ), 0, ooaofooa_R_SUB_MAX_EXTENT_SIZE
};
| 35.234848 | 180 | 0.71619 |
5f4cb6230c0a1bac52abb17c079a743c0d0f1a18 | 950 | ts | TypeScript | src/events/guildCreate.ts | alloha228/YellowBR | fff0570956ab58d18781e73a470b8d6a6657b3cc | [
"MIT"
] | null | null | null | src/events/guildCreate.ts | alloha228/YellowBR | fff0570956ab58d18781e73a470b8d6a6657b3cc | [
"MIT"
] | 1 | 2022-01-22T12:11:20.000Z | 2022-01-22T12:11:20.000Z | src/events/guildCreate.ts | alloha228/YellowBR | fff0570956ab58d18781e73a470b8d6a6657b3cc | [
"MIT"
] | null | null | null | import getEnv from '../utils/getEnv';
import Eris from 'eris';
import GuildService from '../services/GuildService';
const { PREMIUM_BOT_ID, PREMIUM_BOT, FOSS_MODE } = getEnv();
const regionRelation = {
brazil: 'pt_BR',
russia: 'ru_RU',
india: 'hi_IN',
};
const guildCreate = async (guild: Eris.Guild) => {
// Self kick when premium bot is present and the guild is premium
if (!PREMIUM_BOT && !FOSS_MODE) {
const guildSettings = await GuildService.init(guild.id);
const premiumBotMember = await guild
.getRESTMember(PREMIUM_BOT_ID)
.catch(() => {});
if (guildSettings.premium && premiumBotMember) {
guild.leave().catch(console.error);
}
}
// set language for the guild based on its voice region
if (regionRelation[guild.region]) {
const guildSettings = await GuildService.init(guild.id);
await guildSettings.setLanguage(regionRelation[guild.region]);
}
};
export default guildCreate;
| 27.142857 | 67 | 0.693684 |
3b4a8b22b5682fd7a99b77a7e3f4e2efa974fca8 | 221 | lua | Lua | MMOCoreORB/bin/scripts/object/custom_content/mobile/vf_Done/exar_kun_intro_magnus_grenz.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/bin/scripts/object/custom_content/mobile/vf_Done/exar_kun_intro_magnus_grenz.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/bin/scripts/object/custom_content/mobile/vf_Done/exar_kun_intro_magnus_grenz.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | object_mobile_exar_kun_intro_magnus_grenz = object_mobile_shared_exar_kun_intro_magnus_grenz:new {
}
ObjectTemplates:addTemplate(object_mobile_exar_kun_intro_magnus_grenz, "object/mobile/exar_kun_intro_magnus_grenz.iff")
| 221 | 221 | 0.909502 |
710629fb5d41a0ef8d607f10b9a0244deac46ce4 | 725 | swift | Swift | Uncoolness/Uncoolness/AppDelegate.swift | AboutObjectsTraining/swift-comp-reston-2018-12 | a2ea22e61f31fbd09ff5b4bb882bedd8d92f7397 | [
"MIT"
] | null | null | null | Uncoolness/Uncoolness/AppDelegate.swift | AboutObjectsTraining/swift-comp-reston-2018-12 | a2ea22e61f31fbd09ff5b4bb882bedd8d92f7397 | [
"MIT"
] | null | null | null | Uncoolness/Uncoolness/AppDelegate.swift | AboutObjectsTraining/swift-comp-reston-2018-12 | a2ea22e61f31fbd09ff5b4bb882bedd8d92f7397 | [
"MIT"
] | 1 | 2019-03-05T18:18:32.000Z | 2019-03-05T18:18:32.000Z | // Created by Jonathan Lehr on 12/11/18.
// Copyright © 2018 About Objects. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func applicationDidFinishLaunching(_ application: UIApplication) {
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.yellow
window?.rootViewController = UncoolController()
window?.makeKeyAndVisible()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
UIApplication.shared.sendAction(#selector(resignFirstResponder), to: nil, from: nil, for: nil)
print("In \(#function)")
}
}
| 30.208333 | 102 | 0.695172 |
65373505df666d8a906bfd1acd7f0539541bd3a0 | 940 | py | Python | model_agreement.py | ntunlp/coherence-paradigm | 7219fe5b57f5a44e780ca8ba5632194a68e07528 | [
"MIT"
] | null | null | null | model_agreement.py | ntunlp/coherence-paradigm | 7219fe5b57f5a44e780ca8ba5632194a68e07528 | [
"MIT"
] | null | null | null | model_agreement.py | ntunlp/coherence-paradigm | 7219fe5b57f5a44e780ca8ba5632194a68e07528 | [
"MIT"
] | null | null | null | import sys
import pickle
from krips_alpha import krippendorff_alpha, nominal_metric
def get_model_labels(model_output):
model_labels = []
for x in model_output:
try:
if x['pos_score'] > x['neg_score']:
model_labels.append('0')
elif x['neg_score'] > x['pos_score']:
model_labels.append('1')
else:
print(x, "error")
except KeyError:
if x['pos'] > x['neg']:
model_labels.append('0')
elif x['neg'] > x['pos']:
model_labels.append('1')
else:
print(x, "error")
return model_labels
annotations = pickle.load(open(sys.argv[1], 'rb'))
#print(len(annotations[0]))
alpha = krippendorff_alpha(annotations, nominal_metric)
#print(alpha)
model_output = pickle.load(open(sys.argv[2], 'rb'))
print(len(model_output))
model_labels = get_model_labels(model_output)
annotations.append(model_labels)
print(len(annotations))
model_alpha = krippendorff_alpha(annotations, nominal_metric)
print(model_alpha)
| 24.102564 | 61 | 0.71383 |
7702543adac5ec672ebee6edafcfa2a0bad395e9 | 2,991 | rs | Rust | src/day_04_password.rs | lucis-fluxum/advent-of-code | 9b69119ae875525423076369ae8b4b8a578ef43e | [
"MIT"
] | null | null | null | src/day_04_password.rs | lucis-fluxum/advent-of-code | 9b69119ae875525423076369ae8b4b8a578ef43e | [
"MIT"
] | null | null | null | src/day_04_password.rs | lucis-fluxum/advent-of-code | 9b69119ae875525423076369ae8b4b8a578ef43e | [
"MIT"
] | null | null | null | use std::fs::read_to_string;
use itertools::Itertools;
use rayon::prelude::*;
fn get_input() -> Vec<u32> {
let contents = read_to_string("src/day_04_password/input.txt").unwrap();
let bounds: Vec<&str> = contents.trim().split('-').collect();
let lower_bound = bounds[0].parse::<u32>().unwrap();
let upper_bound = bounds[1].parse::<u32>().unwrap();
(lower_bound..upper_bound).collect()
}
fn get_digits(num: u32) -> Vec<u32> {
num.to_string()
.chars()
.map(|c| c.to_digit(10).unwrap())
.collect()
}
fn is_possible_password(candidate: u32) -> bool {
let mut adjacent_digit_condition = false;
let mut non_decreasing_condition = true;
for (a, b) in get_digits(candidate).into_iter().tuple_windows() {
if a == b {
adjacent_digit_condition = true;
} else if a > b {
non_decreasing_condition = false;
break;
}
}
adjacent_digit_condition && non_decreasing_condition
}
fn is_possible_password_no_triples(candidate: u32) -> bool {
let mut valid_pair_exists = false;
let mut iterator = get_digits(candidate).into_iter();
// Have to find at least one isolated pair
let mut current_num = iterator.next().unwrap();
let mut current_freq = 1;
for n in iterator {
if n == current_num {
current_freq += 1;
} else if current_freq == 2 {
// We have an isolated pair!
valid_pair_exists = true;
break;
} else {
current_num = n;
current_freq = 1;
}
}
// Check if the last two elements formed a pair
if current_freq == 2 {
valid_pair_exists = true;
}
is_possible_password(candidate) && valid_pair_exists
}
pub fn find_num_possible_passwords() -> usize {
let candidates: Vec<u32> = get_input()
.into_par_iter()
.filter(|&p| is_possible_password(p))
.collect();
candidates.len()
}
pub fn find_num_possible_passwords_no_triples() -> usize {
let candidates: Vec<u32> = get_input()
.into_par_iter()
.filter(|&p| is_possible_password_no_triples(p))
.collect();
candidates.len()
}
#[cfg(test)]
mod tests {
use crate::day_04_password::{
find_num_possible_passwords, find_num_possible_passwords_no_triples, is_possible_password,
is_possible_password_no_triples,
};
#[test]
fn example_passwords() {
assert!(is_possible_password(111111));
assert!(!is_possible_password(223450));
assert!(!is_possible_password(123789));
assert!(is_possible_password_no_triples(112233));
assert!(!is_possible_password_no_triples(123444));
assert!(is_possible_password_no_triples(111122));
}
#[test]
fn part_1_valid() {
assert_eq!(find_num_possible_passwords(), 921);
}
#[test]
fn part_2_valid() {
assert_eq!(find_num_possible_passwords_no_triples(), 603);
}
}
| 28.216981 | 98 | 0.626881 |
70fdd07df75b9a255968faad5157576fa458e398 | 255 | sql | SQL | store/postgres/migrations/2020-04-10-111111_add_deployment_errors/down.sql | Tumble17/graph-node | a4315a33652391f453031a5412b6c51ba4ce084c | [
"Apache-2.0",
"MIT"
] | 1,811 | 2018-08-01T00:52:11.000Z | 2022-03-31T17:56:57.000Z | store/postgres/migrations/2020-04-10-111111_add_deployment_errors/down.sql | Tumble17/graph-node | a4315a33652391f453031a5412b6c51ba4ce084c | [
"Apache-2.0",
"MIT"
] | 1,978 | 2018-08-01T17:00:43.000Z | 2022-03-31T23:59:29.000Z | store/postgres/migrations/2020-04-10-111111_add_deployment_errors/down.sql | Tumble17/graph-node | a4315a33652391f453031a5412b6c51ba4ce084c | [
"Apache-2.0",
"MIT"
] | 516 | 2018-08-01T05:26:27.000Z | 2022-03-31T14:04:19.000Z | alter table subgraphs.subgraph_deployment drop column health;
alter table subgraphs.subgraph_deployment drop column fatal_error;
alter table subgraphs.subgraph_deployment drop column non_fatal_errors;
drop type subgraph_health;
drop table subgraph_error;
| 42.5 | 71 | 0.87451 |
abbd538fe573a91a33925977e72eabe2a26dea93 | 9,658 | rb | Ruby | WindowSize.rb | cacao-soft/RMVX | 2bded361ea45faf8a60420377e3271ab753c2315 | [
"MIT"
] | null | null | null | WindowSize.rb | cacao-soft/RMVX | 2bded361ea45faf8a60420377e3271ab753c2315 | [
"MIT"
] | null | null | null | WindowSize.rb | cacao-soft/RMVX | 2bded361ea45faf8a60420377e3271ab753c2315 | [
"MIT"
] | null | null | null | #=============================================================================
# [RGSS2] エセフルスクリーン - v1.0.0
# ---------------------------------------------------------------------------
# Copyright (c) 2021 CACAO
# Released under the MIT License.
# https://opensource.org/licenses/mit-license.php
# ---------------------------------------------------------------------------
# [Twitter] https://twitter.com/cacao_soft/
# [GitHub] https://github.com/cacao-soft/
#=============================================================================
=begin
-- 概 要 ----------------------------------------------------------------
ウィンドウのサイズを変更する機能を追加します。
ゲーム解像度 -> 800x600 -> フルサイズ の順に変更を行います。
-- 注意事項 ----------------------------------------------------------------
※ 設定によっては、「初期化ファイルの操作」スクリプトが必要です。
-- 使用方法 ----------------------------------------------------------------
★ WLIB::SetGameWindowSize(width, height)
ウィンドウを中央に移動し、指定されたサイズに変更します。
引数が負数、もしくはデスクトップより大きい場合はフルサイズで表示されます。
処理が失敗すると false を返します。
=end
#==============================================================================
# ◆ ユーザー設定
#==============================================================================
module WND_SIZE
#--------------------------------------------------------------------------
# ◇ サイズ変更キー
#--------------------------------------------------------------------------
# 0 .. サイズ変更を行わない
#--------------------------------------------------------------------------
INPUT_KEY = Input::F5
#--------------------------------------------------------------------------
# ◇ 初期サイズ
#--------------------------------------------------------------------------
# 0 .. 初期サイズ変更を行わない。
# 1 .. 初期化ファイル (Game.ini) の設定を使用する。
# セクション : Window キー : WIDTH, HEIGHT
# 2 .. データファイル (Game.rvdata) の設定を使用する。
# 内容は、クライアント領域の Rect オブジェクトです。
# 配列 .. [width, height] の値で変更する。
#--------------------------------------------------------------------------
INIT_SIZE = 0
end
#/////////////////////////////////////////////////////////////////////////////#
# #
# 下記のスクリプトを変更する必要はありません。 #
# #
#/////////////////////////////////////////////////////////////////////////////#
module WLIB
#--------------------------------------------------------------------------
# ● 定数
#--------------------------------------------------------------------------
# SystemMetrics
SM_CYCAPTION = 0x04 # タイトルバーの高さ
SM_CXDLGFRAME = 0x07 # 枠の幅
SM_CYDLGFRAME = 0x08 # 枠の高さ
# SetWindowPos
SWP_NOSIZE = 0x01 # サイズ変更なし
SWP_NOMOVE = 0x02 # 位置変更なし
SWP_NOZORDER = 0x04 # 並び変更なし
#--------------------------------------------------------------------------
# ● Win32API
#--------------------------------------------------------------------------
@@FindWindow =
Win32API.new('user32', 'FindWindow', 'pp', 'l')
@@GetDesktopWindow =
Win32API.new('user32', 'GetDesktopWindow', 'v', 'l')
@@SetWindowPos =
Win32API.new('user32', 'SetWindowPos', 'lliiiii', 'i')
@@GetClientRect =
Win32API.new('user32', 'GetClientRect', 'lp', 'i')
@@GetWindowRect =
Win32API.new('user32', 'GetWindowRect', 'lp', 'i')
@@GetWindowLong =
Win32API.new('user32', 'GetWindowLong', 'li', 'l')
@@GetSystemMetrics =
Win32API.new('user32', 'GetSystemMetrics', 'i', 'i')
@@SystemParametersInfo =
Win32API.new('user32', 'SystemParametersInfo', 'iipi', 'i')
#--------------------------------------------------------------------------
# ● ウィンドウの情報
#--------------------------------------------------------------------------
unless $!
GAME_TITLE = NKF.nkf("-sxm0", load_data("Data/System.rvdata").game_title)
GAME_HANDLE = @@FindWindow.call("RGSS Player", GAME_TITLE)
end
GAME_STYLE = @@GetWindowLong.call(GAME_HANDLE, -16)
GAME_EXSTYLE = @@GetWindowLong.call(GAME_HANDLE, -20)
HDSK = @@GetDesktopWindow.call
module_function
#--------------------------------------------------------------------------
# ● GetWindowRect
#--------------------------------------------------------------------------
def GetWindowRect(hwnd)
r = [0,0,0,0].pack('l4')
if @@GetWindowRect.call(hwnd, r) != 0
result = Rect.new(*r.unpack('l4'))
result.width -= result.x
result.height -= result.y
else
result = nil
end
return result
end
#--------------------------------------------------------------------------
# ● GetClientRect
#--------------------------------------------------------------------------
def GetClientRect(hwnd)
r = [0,0,0,0].pack('l4')
if @@GetClientRect.call(hwnd, r) != 0
result = Rect.new(*r.unpack('l4'))
else
result = nil
end
return result
end
#--------------------------------------------------------------------------
# ● GetSystemMetrics
#--------------------------------------------------------------------------
def GetSystemMetrics(index)
@@GetSystemMetrics.call(index)
end
#--------------------------------------------------------------------------
# ● SetWindowPos
#--------------------------------------------------------------------------
def SetWindowPos(hwnd, x, y, width, height, z, flag)
@@SetWindowPos.call(hwnd, z, x, y, width, height, flag) != 0
end
#--------------------------------------------------------------------------
# ● ウィンドウのサイズを取得
#--------------------------------------------------------------------------
def GetGameWindowRect
GetWindowRect(GAME_HANDLE)
end
#--------------------------------------------------------------------------
# ● ウィンドウのクライアントサイズを取得
#--------------------------------------------------------------------------
def GetGameClientRect
GetClientRect(GAME_HANDLE)
end
#--------------------------------------------------------------------------
# ● デスクトップのサイズを取得
#--------------------------------------------------------------------------
def GetDesktopRect
r = [0,0,0,0].pack('l4')
if @@SystemParametersInfo.call(0x30, 0, r, 0) != 0
result = Rect.new(*r.unpack('l4'))
result.width -= result.x
result.height -= result.y
else
result = nil
end
return result
end
#--------------------------------------------------------------------------
# ● ウィンドウのフレームサイズを取得
#--------------------------------------------------------------------------
def GetFrameSize
return [
GetSystemMetrics(SM_CYCAPTION), # タイトルバー
GetSystemMetrics(SM_CXDLGFRAME), # 左右フレーム
GetSystemMetrics(SM_CYDLGFRAME) # 上下フレーム
]
end
#--------------------------------------------------------------------------
# ● ウィンドウの位置を変更
#--------------------------------------------------------------------------
def MoveGameWindow(x, y)
SetWindowPos(GAME_HANDLE, x, y, 0, 0, 0, SWP_NOSIZE|SWP_NOZORDER)
end
#--------------------------------------------------------------------------
# ● ウィンドウの位置を中央へ
#--------------------------------------------------------------------------
def MoveGameWindowCenter
dr = GetDesktopRect()
wr = GetGameWindowRect()
x = (dr.width - wr.width) / 2
y = (dr.height - wr.height) / 2
SetWindowPos(GAME_HANDLE, x, y, 0, 0, 0, SWP_NOSIZE|SWP_NOZORDER)
end
#--------------------------------------------------------------------------
# ● ウィンドウのサイズを変更
#--------------------------------------------------------------------------
def SetGameWindowSize(width, height)
# 各領域の取得
dr = GetDesktopRect() # Rect デスクトップ
wr = GetGameWindowRect() # Rect ウィンドウ
cr = GetGameClientRect() # Rect クライアント
return false unless dr && wr && cr
# フレームサイズの取得
frame = GetFrameSize()
ft = frame[0] + frame[2] # タイトルバーの縦幅
fl = frame[1] # 左フレームの横幅
fs = frame[1] * 2 # 左右フレームの横幅
fb = frame[2] # 下フレームの縦幅
if width < 0 || height < 0 || width >= dr.width || height >= dr.height
w = dr.width + fs
h = dr.height + ft + fb
SetWindowPos(GAME_HANDLE, -fl, -ft, w, h, 0, SWP_NOZORDER)
else
w = width + fs
h = height + ft + fb
SetWindowPos(GAME_HANDLE, 0, 0, w, h, 0, SWP_NOMOVE|SWP_NOZORDER)
MoveGameWindowCenter()
end
end
end
class Scene_Base
#--------------------------------------------------------------------------
# ○ フレーム更新
#--------------------------------------------------------------------------
alias _cao_update_wndsize update
def update
_cao_update_wndsize
if Input.trigger?(WND_SIZE::INPUT_KEY)
case WLIB::GetGameClientRect().width
when Graphics.width
width, height = 800, 600
when 800
width, height = -1, -1
else
width, height = Graphics.width, Graphics.height
end
unless WLIB::SetGameWindowSize(width, height)
Sound.play_buzzer
end
end
end
end
# 初期サイズの設定
case WND_SIZE::INIT_SIZE
when 1
width = IniFile.read("Game", "Window", "WIDTH", Graphics.width).to_i
height = IniFile.read("Game", "Window", "HEIGHT", Graphics.height).to_i
WLIB::SetGameWindowSize(width, height)
when 2
if FileTest.exist?("Game.rvdata")
r = load_data("Game.rvdata")
WLIB::SetGameWindowSize(r.width, r.height)
end
when Array
WLIB::SetGameWindowSize(WND_SIZE::INIT_SIZE[0], WND_SIZE::INIT_SIZE[1])
end
| 36.445283 | 79 | 0.372437 |
d9296165627e20e922d4f63833ab99afa8f2dc0e | 13,635 | rs | Rust | tests/guard.rs | TotalKrill/rocket_cors | bf4f91abec0e3fb38b78cf57b93c657071384135 | [
"Apache-2.0",
"MIT"
] | null | null | null | tests/guard.rs | TotalKrill/rocket_cors | bf4f91abec0e3fb38b78cf57b93c657071384135 | [
"Apache-2.0",
"MIT"
] | null | null | null | tests/guard.rs | TotalKrill/rocket_cors | bf4f91abec0e3fb38b78cf57b93c657071384135 | [
"Apache-2.0",
"MIT"
] | 1 | 2020-08-29T14:47:53.000Z | 2020-08-29T14:47:53.000Z | //! This crate tests using `rocket_cors` using the per-route handling with request guard
#![feature(proc_macro_hygiene, decl_macro)]
use hyper;
use rocket_cors as cors;
use std::str::FromStr;
use rocket::http::Method;
use rocket::http::{Header, Status};
use rocket::local::Client;
use rocket::response::Body;
use rocket::{get, options, routes};
use rocket::{Response, State};
#[get("/")]
fn cors(cors: cors::Guard<'_>) -> cors::Responder<'_, &str> {
cors.responder("Hello CORS")
}
#[get("/panic")]
fn panicking_route(_cors: cors::Guard<'_>) {
panic!("This route will panic");
}
/// Manually specify our own OPTIONS route
#[options("/manual")]
fn cors_manual_options(cors: cors::Guard<'_>) -> cors::Responder<'_, &str> {
cors.responder("Manual CORS Preflight")
}
/// Manually specify our own OPTIONS route
#[get("/manual")]
fn cors_manual(cors: cors::Guard<'_>) -> cors::Responder<'_, &str> {
cors.responder("Hello CORS")
}
/// Using a `Response` instead of a `Responder`
#[get("/response")]
fn response(cors: cors::Guard<'_>) -> Response<'_> {
cors.response(Response::new())
}
/// `Responder` with String
#[get("/responder/string")]
fn responder_string(cors: cors::Guard<'_>) -> cors::Responder<'_, String> {
cors.responder("Hello CORS".to_string())
}
/// `Responder` with 'static ()
#[get("/responder/unit")]
fn responder_unit(cors: cors::Guard<'_>) -> cors::Responder<'_, ()> {
cors.responder(())
}
struct SomeState;
/// Borrow `SomeState` from Rocket
#[get("/state")]
fn state<'r>(cors: cors::Guard<'r>, _state: State<'r, SomeState>) -> cors::Responder<'r, &'r str> {
cors.responder("hmm")
}
fn make_cors() -> cors::Cors {
let allowed_origins = cors::AllowedOrigins::some_exact(&["https://www.acme.com"]);
cors::CorsOptions {
allowed_origins,
allowed_methods: vec![Method::Get].into_iter().map(From::from).collect(),
allowed_headers: cors::AllowedHeaders::some(&["Authorization", "Accept"]),
allow_credentials: true,
..Default::default()
}
.to_cors()
.expect("To not fail")
}
fn make_rocket() -> rocket::Rocket {
rocket::ignite()
.mount("/", routes![cors, panicking_route])
.mount(
"/",
routes![response, responder_string, responder_unit, state],
)
.mount("/", cors::catch_all_options_routes()) // mount the catch all routes
.mount("/", routes![cors_manual, cors_manual_options]) // manual OPTIOONS routes
.manage(make_cors())
.manage(SomeState)
}
#[test]
fn smoke_test() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
// `Options` pre-flight checks
let origin_header =
Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
let method_header = Header::from(hyper::header::AccessControlRequestMethod(
hyper::method::Method::Get,
));
let request_headers =
hyper::header::AccessControlRequestHeaders(vec![
FromStr::from_str("Authorization").unwrap()
]);
let request_headers = Header::from(request_headers);
let req = client
.options("/")
.header(origin_header)
.header(method_header)
.header(request_headers);
let response = req.dispatch();
assert!(response.status().class().is_success());
// "Actual" request
let origin_header =
Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
let authorization = Header::new("Authorization", "let me in");
let req = client.get("/").header(origin_header).header(authorization);
let mut response = req.dispatch();
assert!(response.status().class().is_success());
let body_str = response.body().and_then(Body::into_string);
assert_eq!(body_str, Some("Hello CORS".to_string()));
let origin_header = response
.headers()
.get_one("Access-Control-Allow-Origin")
.expect("to exist");
assert_eq!("https://www.acme.com", origin_header);
}
/// Check the "catch all" OPTIONS route works for `/`
#[test]
fn cors_options_catch_all_check() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
let origin_header =
Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
let method_header = Header::from(hyper::header::AccessControlRequestMethod(
hyper::method::Method::Get,
));
let request_headers =
hyper::header::AccessControlRequestHeaders(vec![
FromStr::from_str("Authorization").unwrap()
]);
let request_headers = Header::from(request_headers);
let req = client
.options("/")
.header(origin_header)
.header(method_header)
.header(request_headers);
let response = req.dispatch();
assert!(response.status().class().is_success());
let origin_header = response
.headers()
.get_one("Access-Control-Allow-Origin")
.expect("to exist");
assert_eq!("https://www.acme.com", origin_header);
}
/// Check the "catch all" OPTIONS route works for other routes
#[test]
fn cors_options_catch_all_check_other_routes() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
let origin_header =
Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
let method_header = Header::from(hyper::header::AccessControlRequestMethod(
hyper::method::Method::Get,
));
let request_headers =
hyper::header::AccessControlRequestHeaders(vec![
FromStr::from_str("Authorization").unwrap()
]);
let request_headers = Header::from(request_headers);
let req = client
.options("/response/unit")
.header(origin_header)
.header(method_header)
.header(request_headers);
let response = req.dispatch();
assert!(response.status().class().is_success());
let origin_header = response
.headers()
.get_one("Access-Control-Allow-Origin")
.expect("to exist");
assert_eq!("https://www.acme.com", origin_header);
}
#[test]
fn cors_get_check() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
let origin_header =
Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
let authorization = Header::new("Authorization", "let me in");
let req = client.get("/").header(origin_header).header(authorization);
let mut response = req.dispatch();
assert!(response.status().class().is_success());
let body_str = response.body().and_then(Body::into_string);
assert_eq!(body_str, Some("Hello CORS".to_string()));
let origin_header = response
.headers()
.get_one("Access-Control-Allow-Origin")
.expect("to exist");
assert_eq!("https://www.acme.com", origin_header);
}
/// This test is to check that non CORS compliant requests to GET should still work. (i.e. curl)
#[test]
fn cors_get_no_origin() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
let authorization = Header::new("Authorization", "let me in");
let req = client.get("/").header(authorization);
let mut response = req.dispatch();
assert!(response.status().class().is_success());
let body_str = response.body().and_then(Body::into_string);
assert_eq!(body_str, Some("Hello CORS".to_string()));
assert!(response
.headers()
.get_one("Access-Control-Allow-Origin")
.is_none());
}
#[test]
fn cors_options_bad_origin() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
let origin_header =
Header::from(hyper::header::Origin::from_str("https://www.bad-origin.com").unwrap());
let method_header = Header::from(hyper::header::AccessControlRequestMethod(
hyper::method::Method::Get,
));
let request_headers =
hyper::header::AccessControlRequestHeaders(vec![
FromStr::from_str("Authorization").unwrap()
]);
let request_headers = Header::from(request_headers);
let req = client
.options("/")
.header(origin_header)
.header(method_header)
.header(request_headers);
let response = req.dispatch();
assert_eq!(response.status(), Status::Forbidden);
assert!(response
.headers()
.get_one("Access-Control-Allow-Origin")
.is_none());
}
#[test]
fn cors_options_missing_origin() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
let method_header = Header::from(hyper::header::AccessControlRequestMethod(
hyper::method::Method::Get,
));
let request_headers =
hyper::header::AccessControlRequestHeaders(vec![
FromStr::from_str("Authorization").unwrap()
]);
let request_headers = Header::from(request_headers);
let req = client
.options("/")
.header(method_header)
.header(request_headers);
let response = req.dispatch();
assert!(response.status().class().is_success());
assert!(response
.headers()
.get_one("Access-Control-Allow-Origin")
.is_none());
}
#[test]
fn cors_options_bad_request_method() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
let origin_header =
Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
let method_header = Header::from(hyper::header::AccessControlRequestMethod(
hyper::method::Method::Post,
));
let request_headers =
hyper::header::AccessControlRequestHeaders(vec![
FromStr::from_str("Authorization").unwrap()
]);
let request_headers = Header::from(request_headers);
let req = client
.options("/")
.header(origin_header)
.header(method_header)
.header(request_headers);
let response = req.dispatch();
assert_eq!(response.status(), Status::Forbidden);
assert!(response
.headers()
.get_one("Access-Control-Allow-Origin")
.is_none());
}
#[test]
fn cors_options_bad_request_header() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
let origin_header =
Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
let method_header = Header::from(hyper::header::AccessControlRequestMethod(
hyper::method::Method::Get,
));
let request_headers =
hyper::header::AccessControlRequestHeaders(vec![FromStr::from_str("Foobar").unwrap()]);
let request_headers = Header::from(request_headers);
let req = client
.options("/")
.header(origin_header)
.header(method_header)
.header(request_headers);
let response = req.dispatch();
assert_eq!(response.status(), Status::Forbidden);
assert!(response
.headers()
.get_one("Access-Control-Allow-Origin")
.is_none());
}
#[test]
fn cors_get_bad_origin() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
let origin_header =
Header::from(hyper::header::Origin::from_str("https://www.bad-origin.com").unwrap());
let authorization = Header::new("Authorization", "let me in");
let req = client.get("/").header(origin_header).header(authorization);
let response = req.dispatch();
assert_eq!(response.status(), Status::Forbidden);
assert!(response
.headers()
.get_one("Access-Control-Allow-Origin")
.is_none());
}
/// This test ensures that on a failing CORS request, the route (along with its side effects)
/// should never be executed.
/// The route used will panic if executed
#[test]
fn routes_failing_checks_are_not_executed() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
let origin_header =
Header::from(hyper::header::Origin::from_str("https://www.bad-origin.com").unwrap());
let authorization = Header::new("Authorization", "let me in");
let req = client.get("/").header(origin_header).header(authorization);
let response = req.dispatch();
assert_eq!(response.status(), Status::Forbidden);
assert!(response
.headers()
.get_one("Access-Control-Allow-Origin")
.is_none());
}
/// This test ensures that manually mounted CORS OPTIONS routes are used even in the presence of
/// a "catch all" route.
#[test]
fn overridden_options_routes_are_used() {
let rocket = make_rocket();
let client = Client::new(rocket).unwrap();
let origin_header =
Header::from(hyper::header::Origin::from_str("https://www.acme.com").unwrap());
let method_header = Header::from(hyper::header::AccessControlRequestMethod(
hyper::method::Method::Get,
));
let request_headers =
hyper::header::AccessControlRequestHeaders(vec![
FromStr::from_str("Authorization").unwrap()
]);
let request_headers = Header::from(request_headers);
let req = client
.options("/manual")
.header(origin_header)
.header(method_header)
.header(request_headers);
let mut response = req.dispatch();
let body_str = response.body().and_then(Body::into_string);
assert!(response.status().class().is_success());
assert_eq!(body_str, Some("Manual CORS Preflight".to_string()));
let origin_header = response
.headers()
.get_one("Access-Control-Allow-Origin")
.expect("to exist");
assert_eq!("https://www.acme.com", origin_header);
}
| 32.387173 | 99 | 0.641878 |
76fb0cd0d2904dc2670f89b3b4989732242d5be7 | 7,939 | h | C | ble-mesh-model/include/mmdl_gen_powonoff_cl_api.h | lonesomebyte537/cordio | c0db6dc27d1931feafa7f8db018cd9095416f978 | [
"Apache-2.0"
] | 1 | 2022-02-15T03:51:14.000Z | 2022-02-15T03:51:14.000Z | ble-mesh-model/include/mmdl_gen_powonoff_cl_api.h | lonesomebyte537/cordio | c0db6dc27d1931feafa7f8db018cd9095416f978 | [
"Apache-2.0"
] | null | null | null | ble-mesh-model/include/mmdl_gen_powonoff_cl_api.h | lonesomebyte537/cordio | c0db6dc27d1931feafa7f8db018cd9095416f978 | [
"Apache-2.0"
] | 2 | 2022-01-21T08:00:37.000Z | 2022-02-15T03:51:23.000Z | /*************************************************************************************************/
/*!
* \file
*
* \brief Generic Power On Off Client Model API.
*
* Copyright (c) 2010-2019 Arm Ltd.
*
* Copyright (c) 2019 Packetcraft, 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.
*/
/*************************************************************************************************/
/*! ***********************************************************************************************
* \addtogroup ModelGenPowOnOffCl Generic Power OnOff Client Model API
* @{
*************************************************************************************************/
#ifndef MMDL_GEN_POWER_ONOFF_CL_API_H
#define MMDL_GEN_POWER_ONOFF_CL_API_H
#ifdef __cplusplus
extern "C"
{
#endif
#include "mmdl_defs.h"
/**************************************************************************************************
Data Types
**************************************************************************************************/
/*! \brief Model Power OnOff Client Set parameters structure */
typedef struct mmdlGenPowOnOffSetParam_tag
{
mmdlGenOnPowerUpState_t state; /*!< New OnPowerUp State */
} mmdlGenPowOnOffSetParam_t;
/*! \brief Generic Power OnOff Client Model Status event structure */
typedef struct mmdlGenPowOnOffClStatusEvent_tag
{
wsfMsgHdr_t hdr; /*!< WSF message header */
meshElementId_t elementId; /*!< Element ID */
meshAddress_t serverAddr; /*!< Server Address */
mmdlGenOnPowerUpState_t state; /*!< Received published state */
mmdlGenOnPowerUpState_t targetState; /*!< Received published target state */
} mmdlGenPowOnOffClStatusEvent_t;
/*! \brief Generic Power OnOff Client Model event callback parameters structure */
typedef union mmdlGenPowOnOffClEvent_tag
{
wsfMsgHdr_t hdr; /*!< WSF message header */
mmdlGenPowOnOffClStatusEvent_t statusEvent; /*!< State updated event. Used for
* ::MMDL_GEN_POWER_ONOFF_CL_STATUS_EVENT.
*/
} mmdlGenPowOnOffClEvent_t;
/*************************************************************************************************/
/*!
* \brief Model Generic Power OnOff Client received callback.
*
* \param[in] pEvent Pointer model event. See ::mmdlGenPowOnOffClEvent_t.
*
* \return None.
*/
/*************************************************************************************************/
typedef void (*mmdlGenPowOnOffClRecvCback_t)(const mmdlGenPowOnOffClEvent_t *pEvent);
/**************************************************************************************************
Variables Declarations
**************************************************************************************************/
/*! \brief WSF handler id */
extern wsfHandlerId_t mmdlGenPowOnOffClHandlerId;
/*! \brief Supported opcodes */
extern const meshMsgOpcode_t mmdlGenPowOnOffClRcvdOpcodes[];
/**************************************************************************************************
Function Declarations
**************************************************************************************************/
/*************************************************************************************************/
/*!
* \brief Initializes the Mesh WSF handler.
*
* \param[in] handlerId WSF handler ID for Power OnOff Client Model.
*
* \return None.
*/
/*************************************************************************************************/
void MmdlGenPowOnOffClHandlerInit(wsfHandlerId_t handlerId);
/*************************************************************************************************/
/*!
*
* \brief WSF message handler for Power OnOff Client Model.
*
* \param[in] pMsg WSF message.
*
* \return None.
*/
/*************************************************************************************************/
void MmdlGenPowOnOffClHandler(wsfMsgHdr_t *pMsg);
/*************************************************************************************************/
/*!
* \brief Send a GenOnPowerUpGet message to the destination address.
*
* \param[in] elementId Identifier of the Element implementing the model.
* \param[in] serverAddr Element address of the server or ::MMDL_USE_PUBLICATION_ADDR.
* \param[in] ttl TTL value as defined by the specification.
* \param[in] appKeyIndex Application Key Index.
*
* \return None.
*/
/*************************************************************************************************/
void MmdlGenPowOnOffClGet(meshElementId_t elementId, meshAddress_t serverAddr, uint8_t ttl,
uint16_t appKeyIndex);
/*************************************************************************************************/
/*!
* \brief Send a GenOnPowerUpSet message to the destination address.
*
* \param[in] elementId Identifier of the Element implementing the model.
* \param[in] serverAddr Element address of the server or ::MMDL_USE_PUBLICATION_ADDR.
* \param[in] ttl TTL value as defined by the specification.
* \param[in] pSetParam Pointer to structure containing the set parameters.
* \param[in] appKeyIndex Application Key Index.
*
* \return None.
*/
/*************************************************************************************************/
void MmdlGenPowOnOffClSet(meshElementId_t elementId, meshAddress_t serverAddr, uint8_t ttl,
const mmdlGenPowOnOffSetParam_t *pSetParam, uint16_t appKeyIndex);
/*************************************************************************************************/
/*!
* \brief Send a GenOnPowerUpSetUnacknowledged message to the destination address.
*
* \param[in] elementId Identifier of the Element implementing the model
* \param[in] serverAddr Element address of the server or ::MMDL_USE_PUBLICATION_ADDR.
* \param[in] ttl TTL value as defined by the specification
* \param[in] pSetParam Pointer to structure containing the set parameters.
* \param[in] appKeyIndex Application Key Index.
*
* \return None.
*/
/*************************************************************************************************/
void MmdlGenPowOnOffClSetNoAck(meshElementId_t elementId, meshAddress_t serverAddr, uint8_t ttl,
const mmdlGenPowOnOffSetParam_t *pSetParam, uint16_t appKeyIndex);
/*************************************************************************************************/
/*!
* \brief Install the callback that is triggered when a message is received for this model.
*
* \param[in] recvCback Callback installed by the upper layer to receive messages from the model.
*
* \return None.
*/
/*************************************************************************************************/
void MmdlGenPowOnOffClRegister(mmdlEventCback_t recvCback);
#ifdef __cplusplus
}
#endif
#endif /* MMDL_GEN_POWER_ONOFF_CL_API_H */
/*! ***********************************************************************************************
* @}
*************************************************************************************************/
| 43.146739 | 99 | 0.465046 |
8a89a9fa9d50956448e776c26c4774d3e6d335f0 | 4,396 | rs | Rust | src/ports.rs | DmitryAstafyev/clibri.transport.rust.server | 3b86c86c19aa62bab504a3d2c31a3ee6a5362500 | [
"Apache-2.0"
] | null | null | null | src/ports.rs | DmitryAstafyev/clibri.transport.rust.server | 3b86c86c19aa62bab504a3d2c31a3ee6a5362500 | [
"Apache-2.0"
] | null | null | null | src/ports.rs | DmitryAstafyev/clibri.transport.rust.server | 3b86c86c19aa62bab504a3d2c31a3ee6a5362500 | [
"Apache-2.0"
] | null | null | null | use crate::{errors::Error, options::Ports as PortsSource};
use clibri::env::logs;
use log::info;
use std::{collections::HashMap, time::Instant};
use tokio_util::sync::CancellationToken;
const VALID_KEEP_OPEN_DURATION_MS: u128 = 3 * 1000;
pub struct Ports {
source: Option<PortsSource>,
per_port: Option<u32>,
reserved: HashMap<u16, (u32, CancellationToken, Instant)>,
used: HashMap<u16, u32>,
}
impl Ports {
pub fn new(per_port: Option<u32>, source: Option<PortsSource>) -> Self {
Self {
source,
per_port,
reserved: HashMap::new(),
used: HashMap::new(),
}
}
pub fn add(&mut self, port: u16, cancel: tokio_util::sync::CancellationToken) {
self.reserved.insert(port, (0, cancel, Instant::now()));
}
pub fn reserve(&mut self) -> Result<Option<u16>, Error> {
if let Some(per_port) = self.per_port.as_ref() {
let port = self
.reserved
.iter()
.find_map(|(port, (count, _cancel, _instant))| {
if count < per_port {
Some(port.to_owned())
} else {
None
}
});
if let Some(port) = port {
if let Some((count, _cancel, _instant)) = self.reserved.get_mut(&port) {
*count += 1;
}
}
Ok(port)
} else {
Err(Error::NoOptions(String::from(
"option connections_per_port is required",
)))
}
}
pub fn delegate(&mut self) -> Result<Option<u16>, Error> {
let port = self.get_port()?;
if port.is_some() {
Ok(port)
} else {
self.drop_reserved();
self.get_port()
}
}
pub fn confirm(&mut self, port: u16) {
*self.used.entry(port).or_insert(0) += 1;
}
pub fn free(&mut self, port: u16) {
if let Some((count, cancel, _instant)) = self.reserved.get_mut(&port) {
*count -= 1;
if count == &0 {
cancel.cancel();
self.reserved.remove(&port);
}
}
if let Some(count) = self.used.get_mut(&port) {
*count -= 1;
if count == &0 {
self.used.remove(&port);
}
}
}
fn get_port(&mut self) -> Result<Option<u16>, Error> {
if let Some(ref mut source) = self.source {
match source {
PortsSource::List(ports) => {
info!(
target: logs::targets::SERVER,
"looking for port from a list"
);
let mut free: Option<u16> = None;
for port in ports.iter() {
if !self.reserved.contains_key(port) {
free = Some(port.to_owned());
break;
}
}
Ok(free)
}
PortsSource::Range(range) => {
info!(
target: logs::targets::SERVER,
"looking for port from a range"
);
let mut free: Option<u16> = None;
for port in range {
if !self.reserved.contains_key(&port) {
free = Some(port);
break;
}
}
Ok(free)
}
}
} else {
Err(Error::NoOptions(String::from("option ports is required")))
}
}
/// This method will drop all reserved ports to amount of real connections
fn drop_reserved(&mut self) {
let mut to_free: Vec<u16> = vec![];
for (port, (reserved_connections, _cancel, instant)) in self.reserved.iter_mut() {
if let Some(real_connections) = self.used.get(port) {
*reserved_connections = *real_connections;
} else if instant.elapsed().as_millis() >= VALID_KEEP_OPEN_DURATION_MS {
to_free.push(*port);
}
}
for port in to_free.iter() {
self.free(*port);
}
}
}
| 32.087591 | 90 | 0.451092 |
1fce6f409a9e1481dd75d96b3e54fec034b1d283 | 3,562 | css | CSS | public/FrontEnd/Css/cart_arithmeticPatternsAndProblemSolving.css | imgauravsharma4/Alba_educations | 6b4177cd48e2f69ac929145ad8eb51ba2493496a | [
"MIT"
] | null | null | null | public/FrontEnd/Css/cart_arithmeticPatternsAndProblemSolving.css | imgauravsharma4/Alba_educations | 6b4177cd48e2f69ac929145ad8eb51ba2493496a | [
"MIT"
] | null | null | null | public/FrontEnd/Css/cart_arithmeticPatternsAndProblemSolving.css | imgauravsharma4/Alba_educations | 6b4177cd48e2f69ac929145ad8eb51ba2493496a | [
"MIT"
] | 1 | 2022-02-27T17:51:01.000Z | 2022-02-27T17:51:01.000Z | .gallery-images{
border: 1px solid #f2f2f2;
}
.gallery-images img{
width: 100%;
}
.product-summary{
padding-left: 40px;
}
.product-summary h3 {
display: block;
font-size: 24px;
font-weight: 800;
position: relative;
margin-bottom: 15px;
}
.product-meta {
margin-top: 20px;
}
.product-meta .posted-in{
margin-top: 5px;
display: block;
color: #221638;
margin-bottom: 10px;
font-size: 16px;
font-weight: 700;
}
.posted-in a{
font-size: 16px;
color: #606060;
margin-left: 5px;
font-weight: 600;
display: inline-block;
text-transform: capitalize;
}
.product-share {
margin-top: 30px;
}
.product-share .social {
padding-left: 0;
list-style-type: none;
margin-bottom: 0;
}
.products-share ul{
padding-left: 0px !important;
}
.social li {
display: inline-block;
}
.social li a.facebook {
background-color: #3b5998;
border-color: #3b5998;
color: #ffffff;
}
.social li a.twitter {
background-color: #1da1f2;
border-color: #1da1f2;
color: #ffffff;
}
.social li a.linkedin {
background-color: #007bb5;
border-color: #007bb5;
color: #ffffff;
}
.social li a.whatsapp {
background-color: #44c153;
border-color: #44c153;
color: #ffffff;
}
.product-share .social li a {
display: block;
width: 32px;
height: 32px;
line-height: 34px;
border-radius: 50%;
color: #ffffff;
border: 1px solid;
text-align: center;
font-size: 17px;
margin-left: 2px;
}
.products-details-tabs {
margin-top: 50px;
}
ul#tabs {
text-align: center;
padding-left: 0;
margin-bottom: 40px;
list-style-type: none;
border-bottom: 1px solid #dee2e6;
display: block;
overflow: unset;
}
ul#tabs .tabs-item {
display: inline-block;
margin-left: 15px;
margin-right: 15px;
padding: 0;
border: none;
background-color: transparent;
margin-bottom: 6px;
margin-top: 0;
border-radius: 0;
}
ul#tabs .tabs-item .tabs-link {
color: #221638;
border: none;
border-bottom: none;
padding: 0;
background-color: transparent;
position: relative;
padding-bottom: 8px;
font-size: 20px;
font-weight: 800;
}
ul#tabs .tabs-item .tabs-link::before {
content: '';
position: absolute;
left: 0;
width: 100%;
height: 3px;
transition: 0.5s;
bottom: -2px;
background-color: var(--mainColor);
}
.products-review-comments h3{
text-transform: capitalize;
margin-bottom: 10px;
font-size: 24px;
font-weight: 800;
color: #221638;
}
.products-review-comments p{
font-size: 15px;
margin-bottom: 10px;
}
.comment-respond span{
font-size: 15px;
font-weight: normal;
border-bottom: none;
padding-bottom: 0;
margin-bottom: 10px;
}
.comment-respond p{
margin-bottom: 10px;
}
.comment-form-rating p span i{
color: rgb(255, 167, 2);
}
.comment-form-comment textarea{
width: 100%;
border-color: rgb(211, 205, 194);
padding: 10px;
}
.comment-form-nameEmail-wrapper{
display: flex;
}
.comment-form-author{
width: 48%;
}
.comment-form-author input::placeholder, .comment-form-email input::placeholder, .comment-form-comment textarea::placeholder {
color: #b9b2b2;
}
.comment-form-email{
width: 48%;
margin-left: 4%;
}
.comment-respond form button.form-button{
padding: 9px 20px !important;
}
@media (max-width:767px) {
.product-summary {
padding-left: 0px;
padding-top: 30px;
}
} | 16.961905 | 126 | 0.621842 |
5763cc910b00263a9f9ccdfc17c453e071ceecf0 | 371 | h | C | drivers/Trace.h | nscooling/cpp_arm_test | aa6473ad0f4537faa8ef49bd03f85a85739de28f | [
"MIT"
] | null | null | null | drivers/Trace.h | nscooling/cpp_arm_test | aa6473ad0f4537faa8ef49bd03f85a85739de28f | [
"MIT"
] | null | null | null | drivers/Trace.h | nscooling/cpp_arm_test | aa6473ad0f4537faa8ef49bd03f85a85739de28f | [
"MIT"
] | null | null | null | #ifndef TRACE_H_
#define TRACE_H_
#ifdef TRACE_ENABLED
#include <iostream>
#define TRACE_MSG(msg) std::clog << "DEBUG: " << msg << std::endl
#define TRACE_VALUE(variable) \
std::clog << "DEBUG: " << #variable << " : " << variable << std::endl
#else
#define TRACE_MSG(msg)
#define TRACE_VALUE(variable)
#endif
#endif | 21.823529 | 80 | 0.587601 |
78c450799eabc868cec917f6440969f1fb896a4a | 405 | asm | Assembly | src/drivers/keyboard/keyboard.asm | DreamPearl/FuzzyOS | e287bf139511b59abe9e2a0e7ce49444c6a5299e | [
"Apache-2.0"
] | 10 | 2021-03-04T18:48:29.000Z | 2022-03-10T19:07:54.000Z | src/drivers/keyboard/keyboard.asm | DreamPearl/FuzzyOS | e287bf139511b59abe9e2a0e7ce49444c6a5299e | [
"Apache-2.0"
] | 7 | 2020-06-27T13:13:08.000Z | 2021-10-17T17:09:40.000Z | src/drivers/keyboard/keyboard.asm | DreamPearl/FuzzyOS | e287bf139511b59abe9e2a0e7ce49444c6a5299e | [
"Apache-2.0"
] | 1 | 2022-02-10T20:09:01.000Z | 2022-02-10T20:09:01.000Z | [BITS 32]
global port_write
global port_read
[SECTION .text]
port_write:
push ebp
mov ebp, esp
mov al, [ebp + 0xc] ; value
mov dx, [ebp + 0x8] ; port
out dx, al
pop ebp
ret
port_read:
push ebp
mov ebp, esp
mov dx, [ebp + 0x8] ; port
in al, dx
and eax, 0xFF
pop ebp
ret
| 14.464286 | 38 | 0.459259 |
afeb0c820e9ecdade109cddffa659a1c404e6e73 | 5,010 | rb | Ruby | examples/rlgl_compute_shader.rb | vaiorabbit/raylib-bindings | 36396b932e3444ab03f242e400ed77cc2c4dfcd4 | [
"Zlib"
] | 1 | 2022-01-16T07:16:16.000Z | 2022-01-16T07:16:16.000Z | examples/rlgl_compute_shader.rb | vaiorabbit/raylib-bindings | 36396b932e3444ab03f242e400ed77cc2c4dfcd4 | [
"Zlib"
] | 2 | 2022-01-14T07:48:18.000Z | 2022-01-20T21:08:33.000Z | examples/rlgl_compute_shader.rb | vaiorabbit/raylib-bindings | 36396b932e3444ab03f242e400ed77cc2c4dfcd4 | [
"Zlib"
] | null | null | null | require_relative 'util/setup_dll'
require_relative 'util/resource_path'
# [NOTE] This sample requires:
# - Windows OS
# - OpenGL 4.3 capable GPU
# - libraylib.dll built with 'GRAPHICS=GRAPHICS_API_OPENGL_43'
if __FILE__ == $PROGRAM_NAME
# IMPORTANT: This must match gol*.glsl GOL_WIDTH constant.
# This must be a multiple of 16 (check golLogic compute dispatch).
GOL_WIDTH = 768
# Maximum amount of queued draw commands (squares draw from mouse down events).
MAX_BUFFERED_TRANSFERTS = 48
# Game Of Life Update Command
class GolUpdateCmd < FFI::Struct
layout(
:x, :uint, # x coordinate of the gol command
:y, :uint, # y coordinate of the gol command
:w, :uint, # width of the filled zone
:enabled, :uint, # whether to enable or disable zone
)
end
# Game Of Life Update Commands SSBO
class GolUpdateSSBO < FFI::Struct
layout(
:count, :uint,
:commands, [GolUpdateCmd, MAX_BUFFERED_TRANSFERTS],
)
end
InitWindow(GOL_WIDTH, GOL_WIDTH, "Yet Another Ruby-raylib bindings - compute shader - game of life")
resolution = Vector2.create(GOL_WIDTH, GOL_WIDTH)
brushSize = 8
# Game of Life logic compute shader
golLogicCode = LoadFileText(RAYLIB_OTHERS_PATH + "resources/shaders/glsl430/gol.glsl")
golLogicShader = rlCompileShader(golLogicCode, RL_COMPUTE_SHADER)
golLogicProgram = rlLoadComputeShaderProgram(golLogicShader)
UnloadFileText(golLogicCode)
# Game of Life logic compute shader
golRenderShader = LoadShader(nil, RAYLIB_OTHERS_PATH + "resources/shaders/glsl430/gol_render.glsl")
resUniformLoc = GetShaderLocation(golRenderShader, "resolution")
# Game of Life transfert shader
golTransfertCode = LoadFileText( RAYLIB_OTHERS_PATH + "resources/shaders/glsl430/gol_transfert.glsl")
golTransfertShader = rlCompileShader(golTransfertCode, RL_COMPUTE_SHADER)
golTransfertProgram = rlLoadComputeShaderProgram(golTransfertShader)
UnloadFileText(golTransfertCode)
# SSBOs
ssboA = rlLoadShaderBuffer(GOL_WIDTH*GOL_WIDTH*FFI::type_size(:uint), nil, RL_DYNAMIC_COPY)
ssboB = rlLoadShaderBuffer(GOL_WIDTH*GOL_WIDTH*FFI::type_size(:uint), nil, RL_DYNAMIC_COPY)
transfertBuffer = GolUpdateSSBO.new
transfertBuffer[:count] = 0
transfertSSBO = rlLoadShaderBuffer(GolUpdateSSBO.size, nil, RL_DYNAMIC_COPY)
# Create a white texture of the size of the window to update
# each pixel of the window using the fragment shader
whiteImage = GenImageColor(GOL_WIDTH, GOL_WIDTH, WHITE)
whiteTex = LoadTextureFromImage(whiteImage)
UnloadImage(whiteImage)
until WindowShouldClose()
brushSize += GetMouseWheelMove().to_f
if (IsMouseButtonDown(MOUSE_BUTTON_LEFT) || IsMouseButtonDown(MOUSE_BUTTON_RIGHT)) && (transfertBuffer[:count] < MAX_BUFFERED_TRANSFERTS)
# Buffer a new command
transfertBuffer[:commands][transfertBuffer[:count]][:x] = GetMouseX() - brushSize/2
transfertBuffer[:commands][transfertBuffer[:count]][:y] = GetMouseY() - brushSize/2
transfertBuffer[:commands][transfertBuffer[:count]][:w] = brushSize
transfertBuffer[:commands][transfertBuffer[:count]][:enabled] = IsMouseButtonDown(MOUSE_BUTTON_LEFT) ? 1 : 0
transfertBuffer[:count] += 1
elsif transfertBuffer[:count] > 0
# Process transfert buffer
# Send SSBO buffer to GPU
rlUpdateShaderBufferElements(transfertSSBO, transfertBuffer, GolUpdateSSBO.size, 0)
# Process ssbo command
rlEnableShader(golTransfertProgram)
rlBindShaderBuffer(ssboA, 1)
rlBindShaderBuffer(transfertSSBO, 3)
rlComputeShaderDispatch(transfertBuffer[:count], 1, 1) # each GPU unit will process a command
rlDisableShader()
transfertBuffer[:count] = 0
else # elsif IsKeyDown(KEY_SPACE)
# Process game of life logic
rlEnableShader(golLogicProgram)
rlBindShaderBuffer(ssboA, 1)
rlBindShaderBuffer(ssboB, 2)
rlComputeShaderDispatch(GOL_WIDTH/16, GOL_WIDTH/16, 1)
rlDisableShader()
# ssboA <-> ssboB
ssboA, ssboB = ssboB, ssboA
end
rlBindShaderBuffer(ssboA, 1)
SetShaderValue(golRenderShader, resUniformLoc, resolution, SHADER_UNIFORM_VEC2)
BeginDrawing()
ClearBackground(BLANK)
BeginShaderMode(golRenderShader)
DrawTexture(whiteTex, 0, 0, WHITE)
EndShaderMode()
DrawRectangleLines(GetMouseX() - brushSize/2, GetMouseY() - brushSize/2, brushSize, brushSize, RED)
DrawText("Use Mouse wheel to increase/decrease brush size", 10, 10, 20, WHITE)
DrawFPS(GetScreenWidth() - 100, 10)
EndDrawing()
end
# Unload shader buffers objects.
rlUnloadShaderBuffer(ssboA)
rlUnloadShaderBuffer(ssboB)
rlUnloadShaderBuffer(transfertSSBO)
# Unload compute shader programs
rlUnloadShaderProgram(golTransfertProgram)
rlUnloadShaderProgram(golLogicProgram)
UnloadTexture(whiteTex) # Unload white texture
UnloadShader(golRenderShader) # Unload rendering fragment shader
CloseWindow()
end
| 35.034965 | 141 | 0.737126 |
ace18e3c15bd25f101a3da56301db0f5af5a5ff6 | 1,241 | kt | Kotlin | livingdoc-converters/src/main/kotlin/org/livingdoc/converters/collection/MapConverter.kt | pkleimann/livingdoc | 02be0744f2f7c0cdb9ab01dec0413280124d5fe3 | [
"Apache-2.0"
] | 9 | 2018-06-19T03:42:02.000Z | 2021-06-24T14:15:11.000Z | livingdoc-converters/src/main/kotlin/org/livingdoc/converters/collection/MapConverter.kt | pkleimann/livingdoc | 02be0744f2f7c0cdb9ab01dec0413280124d5fe3 | [
"Apache-2.0"
] | 53 | 2017-04-12T14:43:09.000Z | 2017-08-18T14:24:57.000Z | livingdoc-converters/src/main/kotlin/org/livingdoc/converters/collection/MapConverter.kt | pkleimann/livingdoc | 02be0744f2f7c0cdb9ab01dec0413280124d5fe3 | [
"Apache-2.0"
] | 9 | 2017-04-11T19:37:53.000Z | 2017-08-11T12:39:53.000Z | package org.livingdoc.converters.collection
import java.lang.reflect.AnnotatedElement
import org.livingdoc.api.conversion.ConversionException
import org.livingdoc.api.conversion.TypeConverter
import org.livingdoc.converters.TypeConverters.findTypeConverterForGenericElement
import org.livingdoc.converters.collection.Tokenizer.tokenizeToMap
open class MapConverter : TypeConverter<Map<Any, Any>> {
private val keyParameter: Int = 0
private val valueParameter: Int = 1
@Throws(ConversionException::class)
override fun convert(value: String, element: AnnotatedElement, documentClass: Class<*>?): Map<Any, Any> {
val keyConverter = findTypeConverterForGenericElement(element, keyParameter, documentClass)
val valueConverter = findTypeConverterForGenericElement(element, valueParameter, documentClass)
val pairs = tokenizeToMap(value)
return pairs.map { (key, value) ->
val convertedKey = keyConverter.convert(key, element, documentClass)
val convertedValue = valueConverter.convert(value, element, documentClass)
convertedKey to convertedValue
}.toMap()
}
override fun canConvertTo(targetType: Class<*>?) = Map::class.java == targetType
}
| 44.321429 | 109 | 0.756648 |
5826b23b1035ff033291d28e37ec5f6ccf7c2e48 | 6,467 | c | C | pyscf/lib/ri/r_df_incore.c | nmardirossian/pyscf | 57c8912dcfcc1157a822feede63df54ed1067115 | [
"BSD-2-Clause"
] | 1 | 2018-05-02T19:55:30.000Z | 2018-05-02T19:55:30.000Z | pyscf/lib/ri/r_df_incore.c | nmardirossian/pyscf | 57c8912dcfcc1157a822feede63df54ed1067115 | [
"BSD-2-Clause"
] | null | null | null | pyscf/lib/ri/r_df_incore.c | nmardirossian/pyscf | 57c8912dcfcc1157a822feede63df54ed1067115 | [
"BSD-2-Clause"
] | 1 | 2018-12-06T03:10:50.000Z | 2018-12-06T03:10:50.000Z | /*
* Author: Qiming Sun <osirpt.sun@gmail.com>
*/
#include <stdlib.h>
#include <assert.h>
#include <complex.h>
//#include <omp.h>
#include "config.h"
#include "cint.h"
#include "vhf/fblas.h"
#include "vhf/nr_direct.h"
#include "np_helper/np_helper.h"
#include "ao2mo/r_ao2mo.h"
void zhemm_(const char*, const char*,
const int*, const int*,
const double complex*, const double complex*, const int*,
const double complex*, const int*,
const double complex*, double complex*, const int*);
/*
* transform bra (without doing conj(mo)), v_{iq} = C_{pi} v_{pq}
* s1 to label AO symmetry
*/
int RIhalfmmm_r_s1_bra_noconj(double complex *vout, double complex *vin,
struct _AO2MOEnvs *envs, int seekdim)
{
switch (seekdim) {
case 1: return envs->bra_count * envs->nao;
case 2: return envs->nao * envs->nao;
}
const double complex Z0 = 0;
const double complex Z1 = 1;
const char TRANS_N = 'N';
int n2c = envs->nao;
int i_start = envs->bra_start;
int i_count = envs->bra_count;
double complex *mo_coeff = envs->mo_coeff;
zgemm_(&TRANS_N, &TRANS_N, &n2c, &i_count, &n2c,
&Z1, vin, &n2c, mo_coeff+i_start*n2c, &n2c,
&Z0, vout, &n2c);
return 0;
}
/*
* transform ket, s1 to label AO symmetry
*/
int RIhalfmmm_r_s1_ket(double complex *vout, double complex *vin,
struct _AO2MOEnvs *envs, int seekdim)
{
switch (seekdim) {
case 1: return envs->nao * envs->ket_count;
case 2: return envs->nao * envs->nao;
}
const double complex Z0 = 0;
const double complex Z1 = 1;
const char TRANS_T = 'T';
const char TRANS_N = 'N';
int n2c = envs->nao;
int j_start = envs->ket_start;
int j_count = envs->ket_count;
double complex *mo_coeff = envs->mo_coeff;
zgemm_(&TRANS_T, &TRANS_N, &j_count, &n2c, &n2c,
&Z1, mo_coeff+j_start*n2c, &n2c, vin, &n2c,
&Z0, vout, &j_count);
return 0;
}
/*
* transform bra (without doing conj(mo)), v_{iq} = C_{pi} v_{pq}
* s2 to label AO symmetry
*/
int RIhalfmmm_r_s2_bra_noconj(double complex *vout, double complex *vin,
struct _AO2MOEnvs *envs, int seekdim)
{
switch (seekdim) {
case 1: return envs->bra_count * envs->nao;
case 2: return envs->nao * (envs->nao+1) / 2;
}
const double complex Z0 = 0;
const double complex Z1 = 1;
const char SIDE_L = 'L';
const char UPLO_U = 'U';
int n2c = envs->nao;
int i_start = envs->bra_start;
int i_count = envs->bra_count;
double complex *mo_coeff = envs->mo_coeff;
zhemm_(&SIDE_L, &UPLO_U, &n2c, &i_count,
&Z1, vin, &n2c, mo_coeff+i_start*n2c, &n2c,
&Z0, vout, &n2c);
return 0;
}
/*
* transform ket, s2 to label AO symmetry
*/
int RIhalfmmm_r_s2_ket(double complex *vout, double complex *vin,
struct _AO2MOEnvs *envs, int seekdim)
{
switch (seekdim) {
case 1: return envs->nao * envs->ket_count;
case 2: return envs->nao * (envs->nao+1) / 2;
}
const double complex Z0 = 0;
const double complex Z1 = 1;
const char SIDE_L = 'L';
const char UPLO_U = 'U';
int n2c = envs->nao;
int j_start = envs->ket_start;
int j_count = envs->ket_count;
double complex *mo_coeff = envs->mo_coeff;
double complex *buf = malloc(sizeof(double complex)*n2c*j_count);
int i, j;
zhemm_(&SIDE_L, &UPLO_U, &n2c, &j_count,
&Z1, vin, &n2c, mo_coeff+j_start*n2c, &n2c,
&Z0, buf, &n2c);
for (j = 0; j < n2c; j++) {
for (i = 0; i < j_count; i++) {
vout[i] = buf[i*n2c+j];
}
vout += j_count;
}
free(buf);
return 0;
}
/*
* unpack the AO integrals and copy to vout, s2 to label AO symmetry
*/
int RImmm_r_s2_copy(double complex *vout, double complex *vin,
struct _AO2MOEnvs *envs, int seekdim)
{
switch (seekdim) {
case 1: return envs->nao * envs->nao;
case 2: return envs->nao * (envs->nao+1) / 2;
}
int n2c = envs->nao;
int i, j;
for (i = 0; i < n2c; i++) {
for (j = 0; j < i; j++) {
vout[i*n2c+j] = vin[j];
vout[j*n2c+i] = conj(vin[j]);
}
vout[i*n2c+i] = vin[i];
vin += n2c;
}
return 0;
}
/*
* transpose (no conj) the AO integrals and copy to vout, s2 to label AO symmetry
*/
int RImmm_r_s2_transpose(double complex *vout, double complex *vin,
struct _AO2MOEnvs *envs, int seekdim)
{
switch (seekdim) {
case 1: return envs->nao * envs->nao;
case 2: return envs->nao * (envs->nao+1) / 2;
}
int n2c = envs->nao;
int i, j;
for (i = 0; i < n2c; i++) {
for (j = 0; j < i; j++) {
vout[j*n2c+i] = vin[j];
vout[i*n2c+j] = conj(vin[j]);
}
vout[i*n2c+i] = vin[i];
vin += n2c;
}
return 0;
}
/*
* ************************************************
* s1, s2ij, s2kl, s4 here to label the AO symmetry
*/
void RItranse2_r_s1(int (*fmmm)(),
double complex *vout, double complex *vin, int row_id,
struct _AO2MOEnvs *envs)
{
size_t ij_pair = (*fmmm)(NULL, NULL, envs, 1);
size_t nao2 = envs->nao * envs->nao;
(*fmmm)(vout+ij_pair*row_id, vin+nao2*row_id, envs, 0);
}
void RItranse2_r_s2(int (*fmmm)(),
double complex *vout, double complex *vin, int row_id,
struct _AO2MOEnvs *envs)
{
int nao = envs->nao;
size_t ij_pair = (*fmmm)(NULL, NULL, envs, 1);
size_t nao2 = nao*(nao+1)/2;
double complex *buf = malloc(sizeof(double complex) * nao*nao);
NPzunpack_tril(nao, vin+nao2*row_id, buf, 0);
(*fmmm)(vout+ij_pair*row_id, buf, envs, 0);
free(buf);
}
| 31.546341 | 81 | 0.510747 |
743529292c3b7a8af2546f8aeaa9e794e692c7eb | 838 | h | C | ComputeGraphModule/inputframestream.h | Rubius/Caboodle | 75b267208a124a7e372b1d704fcae3699cf4ed43 | [
"MIT"
] | null | null | null | ComputeGraphModule/inputframestream.h | Rubius/Caboodle | 75b267208a124a7e372b1d704fcae3699cf4ed43 | [
"MIT"
] | null | null | null | ComputeGraphModule/inputframestream.h | Rubius/Caboodle | 75b267208a124a7e372b1d704fcae3699cf4ed43 | [
"MIT"
] | 1 | 2020-07-27T02:23:38.000Z | 2020-07-27T02:23:38.000Z | #ifndef INPUTFRAMESTREAM_H
#define INPUTFRAMESTREAM_H
#include <SharedModule/internal.hpp>
class QFile;
namespace cv {
class Mat;
}
class InputFrameStream
{
public:
InputFrameStream(quint32 outputsCount);
~InputFrameStream();
void MoveToThread(QThread* thread);
void SetFileName(const QString& name);
void SetPause(bool flag) { _paused = flag; }
bool IsPaused() const { return _paused; }
bool ReadFrame();
void Repeat();
bool IsFinished() const;
bool IsValid() const;
const cv::Mat& GetOutput() const;
static QStringList GetAvailableInputs();
private:
ScopedPointer<cv::Mat> _output;
ScopedPointer<QFile> _inputFile;
ScopedPointer<QDataStream> _inputStream;
quint32 _outputsCount;
quint32 _readingCounter;
bool _paused;
};
#endif // INPUTFRAMESTREAM_H
| 19.952381 | 48 | 0.710024 |
c3629ad070876a3613e0f791655cf8212e27f6ce | 1,508 | go | Go | tracker.go | die-net/dhtproxy | 0e13123cfdd963f0e6121401d1d00de24efbdaed | [
"Apache-2.0"
] | 14 | 2016-06-01T03:08:00.000Z | 2021-03-16T06:46:48.000Z | tracker.go | die-net/dhtproxy | 0e13123cfdd963f0e6121401d1d00de24efbdaed | [
"Apache-2.0"
] | 3 | 2016-11-17T13:28:13.000Z | 2021-09-07T16:35:53.000Z | tracker.go | die-net/dhtproxy | 0e13123cfdd963f0e6121401d1d00de24efbdaed | [
"Apache-2.0"
] | 6 | 2017-02-13T20:21:22.000Z | 2021-09-20T06:36:37.000Z | package main
import (
"net/http"
"strings"
"time"
bencode "github.com/jackpal/bencode-go"
"github.com/nictuku/dht"
)
type TrackerResponse struct {
Interval int64 "interval" //nolint:govet // Bencode-go uses non-comformant struct tags
MinInterval int64 "min interval" //nolint:govet // Bencode-go uses non-comformant struct tags
Complete int "complete" //nolint:govet // Bencode-go uses non-comformant struct tags
Incomplete int "incomplete" //nolint:govet // Bencode-go uses non-comformant struct tags
Peers string "peers" //nolint:govet // Bencode-go uses non-comformant struct tags
}
func trackerHandler(w http.ResponseWriter, r *http.Request) {
if r.FormValue("compact") != "1" {
http.Error(w, "Only compact protocol supported.", 400)
return
}
infoHash := dht.InfoHash(r.FormValue("info_hash"))
if len(infoHash) != 20 {
http.Error(w, "Bad info_hash.", 400)
return
}
response := TrackerResponse{
Interval: 300,
MinInterval: 60,
}
peers, ok := peerCache.Get(string(infoHash))
dhtNode.Find(infoHash)
if !ok || len(peers) == 0 {
response.Interval = 30
response.MinInterval = 10
time.Sleep(5 * time.Second)
peers, ok = peerCache.Get(string(infoHash))
}
if ok && len(peers) > 0 {
response.Incomplete = len(peers)
response.Peers = strings.Join(peers, "")
}
w.Header().Set("Content-Type", "application/octet-stream")
if err := bencode.Marshal(w, response); err != nil {
http.Error(w, err.Error(), 500)
}
}
| 24.721311 | 95 | 0.677719 |
20c65af76cedbb281df66ca1601591f20436faeb | 1,130 | css | CSS | desafio_01/src/css/pesquisa.css | edniltonmatos/desafios-codelandia | 105d8196c174536ff380688a750a1cd2c61f9219 | [
"MIT"
] | 1 | 2022-03-26T20:32:49.000Z | 2022-03-26T20:32:49.000Z | desafio_01/src/css/pesquisa.css | edniltonmatos/desafios-codelandia | 105d8196c174536ff380688a750a1cd2c61f9219 | [
"MIT"
] | null | null | null | desafio_01/src/css/pesquisa.css | edniltonmatos/desafios-codelandia | 105d8196c174536ff380688a750a1cd2c61f9219 | [
"MIT"
] | null | null | null | @import url(./global.css);
header{
background: var(--gradient-default);
padding: 2.5rem 0;
}
header > section div:nth-child(1){
display: flex;
justify-content: space-between;
margin-bottom: 5rem;
}
header > section div:nth-child(2){
background-color: var(--light-tranparent);
display: flex;
align-items: center;
border-radius: 5px;
}
header > section div:nth-child(2) > label > svg{
padding: 1rem;
}
header > section div:nth-child(2) > input{
width: 100%;
}
input{
font-size: 1.1rem;
line-height: 120%;
color: var(--light);
padding: 1.25rem 0;
border: none;
outline: none;
background: none;
font-family: 'Inter', sans-serif;
font-weight: 500;
}
input::placeholder{
color: var(--light-tranparent);
}
@media screen and (max-width:920px) {
header{
padding: 2.5rem 1.25rem;
}
}
@media screen and (max-width:480px) {
header > section div:nth-child(2) > label > svg{
padding: .7rem;
}
header > section div:nth-child(1){
margin-bottom: 2.5rem;
}
input,input::placeholder{
font-size: .9rem;
}
} | 21.730769 | 52 | 0.611504 |
33920841ba8c1c09bc215e9848f8c8f5fe4c4dd4 | 136 | sql | SQL | sql/get_char_items.sql | Tym17/SymbiozUtils | ba77b9e7fbfa1623fa754f499d6a6eb5d31582b5 | [
"MIT"
] | null | null | null | sql/get_char_items.sql | Tym17/SymbiozUtils | ba77b9e7fbfa1623fa754f499d6a6eb5d31582b5 | [
"MIT"
] | null | null | null | sql/get_char_items.sql | Tym17/SymbiozUtils | ba77b9e7fbfa1623fa754f499d6a6eb5d31582b5 | [
"MIT"
] | null | null | null | SELECT ci.UId,
i.Name
FROM charactersitems ci
LEFT JOIN items i
ON ci.Gid = i.Id
WHERE ci.CharacterId = ?
AND i.TypeId in (?); | 19.428571 | 24 | 0.669118 |
dfbae014c6d4de859a9f81ff98144fa95f62c03e | 5,677 | tsx | TypeScript | src/views/modals/ExampleFormModal.tsx | codeBelt/typescript-hapi-react-hot-loader-example | c9910c58efc4885de56e2e4dbfbc4674eeca6cdc | [
"MIT"
] | 50 | 2017-08-28T17:48:05.000Z | 2020-02-14T13:10:35.000Z | src/views/modals/ExampleFormModal.tsx | codeBelt/typescript-hapi-react-hot-loader-example | c9910c58efc4885de56e2e4dbfbc4674eeca6cdc | [
"MIT"
] | 16 | 2017-08-28T18:57:03.000Z | 2021-10-05T20:44:25.000Z | src/views/modals/ExampleFormModal.tsx | codeBelt/typescript-hapi-react-hot-loader-example | c9910c58efc4885de56e2e4dbfbc4674eeca6cdc | [
"MIT"
] | 7 | 2017-09-18T14:45:06.000Z | 2020-09-25T12:05:54.000Z | import * as React from 'react';
import {form2js} from 'form2js';
import InputField from '../components/InputField';
import {connect} from 'react-redux';
import IAction from '../../stores/IAction';
import IStore from '../../stores/IStore';
import {Dispatch} from 'redux';
import ModalAction from '../../stores/modal/ModalAction';
import BaseModal from './BaseModal';
export interface IProps {
isRequired: boolean;
data: any;
}
interface IState {}
interface IStateToProps {}
interface IDispatchToProps {
dispatch: (action: IAction<any>) => void;
}
const mapStateToProps = (state: IStore) => ({});
const mapDispatchToProps = (dispatch: Dispatch<IAction<any>>): IDispatchToProps => ({
dispatch,
});
type PropsUnion = IStateToProps & IDispatchToProps & IProps;
class ExampleFormModal extends React.Component<PropsUnion, IState> {
public static defaultProps: Partial<PropsUnion> = {
isRequired: false,
};
private _formElement: HTMLFormElement = null;
public render(): JSX.Element {
return (
<BaseModal isRequired={this.props.isRequired}>
<section className="modal-content">
<h2 className="modal-header modal-header_left">{'Modal Form Title'}</h2>
<div className="modal-body">
{this._buildFormJsx()}
</div>
<div className="modal-footer modal-footer_stack">
<button onClick={this._onClickClose}>
{'Cancel'}
</button>
<button onClick={this._onClickAccept}>
{'Accept'}
</button>
</div>
</section>
</BaseModal>
);
}
private _buildFormJsx(): JSX.Element {
return (
<form
autoComplete="off"
className="modalForm u-validate"
noValidate={true}
ref={(element: HTMLFormElement) => {
this._formElement = element;
}}
>
<p className="modalForm-warning">
{'This is an example of a custom modal. The "isRequired" attribute is set to "true" which prevents the user from clicking the esc key or click outside of the modal to close it. It also has form validation.'}
</p>
<div className="modalForm-item">
<label
htmlFor="modal-form-name"
className="modalForm-item-label"
>
{'Name'}<sup>{'*'}</sup>
</label>
<div className="modalForm-item-input">
<InputField
id={'modal-form-name'}
name="name"
isRequired={true}
/>
</div>
</div>
<div className="modalForm-item">
<label
htmlFor="modal-form-exposure-limit"
className="modalForm-item-label"
>
{'Age'}<sup>{'*'}</sup>
</label>
<div className="modalForm-item-input">
<InputField
id={'example-form-age'}
name="age"
step={'1'}
type={'number'}
isRequired={true}
/>
</div>
</div>
<div className="modalForm-item">
<label
htmlFor="modal-form-molecular-weight"
className="modalForm-item-label"
>
{'Email'}<sup>{'*'}</sup>
</label>
<div className="modalForm-item-input">
<InputField
id={'example-form-modal-email'}
name="email"
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$"
isRequired={true}
/>
</div>
</div>
<div className="modalForm-item">
<label
htmlFor="example-form-modal"
className="modalForm-item-label"
>
{'Address'}
</label>
<div className="modalForm-item-input">
<InputField
id={'example-form-modal-address'}
name="address"
/>
</div>
</div>
</form>
);
}
private _onClickAccept = (event: React.MouseEvent<HTMLButtonElement>): void => {
event.preventDefault();
if (this._formElement.checkValidity()) {
const formData: any = form2js(this._formElement, '.', false);
console.info(formData);
this._onClickClose();
} else {
this._formElement.classList.remove('u-validate');
}
}
private _onClickClose = (event: React.MouseEvent<HTMLButtonElement> = null): void => {
this.props.dispatch(ModalAction.closeModal());
}
}
export default connect<IStateToProps, IDispatchToProps, IProps>(mapStateToProps, mapDispatchToProps)(ExampleFormModal);
| 36.159236 | 227 | 0.454113 |
0a26c7ce3503f4d70492e0ffefe75e53f5a03acd | 880 | ts | TypeScript | src/common/components/cart-item-addition/cart-item-addition.component.ts | hungtruongquoc/udacity-store-front | d722bfce51d0fb594ac96dc2ddd98d84e67cff41 | [
"MIT"
] | null | null | null | src/common/components/cart-item-addition/cart-item-addition.component.ts | hungtruongquoc/udacity-store-front | d722bfce51d0fb594ac96dc2ddd98d84e67cff41 | [
"MIT"
] | null | null | null | src/common/components/cart-item-addition/cart-item-addition.component.ts | hungtruongquoc/udacity-store-front | d722bfce51d0fb594ac96dc2ddd98d84e67cff41 | [
"MIT"
] | null | null | null | import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
@Component({
selector: 'app-cart-item-addition',
templateUrl: './cart-item-addition.component.html',
styleUrls: ['./cart-item-addition.component.scss']
})
export class CartItemAdditionComponent implements OnInit {
@Input()
showButton = true;
@Input()
initialQty: number | null = 0;
@Output()
quantityChanged: EventEmitter<number | null> = new EventEmitter<number | null>();
@Output()
addCartButtonClicked: EventEmitter<void> = new EventEmitter<void>();
private _selection: number | null = null;
set selection(value: number | null) {
this._selection = value;
this.quantityChanged.emit(this._selection)
}
get selection(): number | null {
return this._selection;
}
constructor() { }
ngOnInit(): void {
this._selection = this.initialQty;
}
}
| 22.564103 | 83 | 0.688636 |
b99351bfeeb42e8d1436c3da5d04cfcea700438c | 3,216 | h | C | ivan_original/include/find_oc_adapt.h | stevenglasford/Seminar_NDSU_2020 | 3bc778185ac40a92913c091e2e717434cbf17b31 | [
"Apache-2.0"
] | null | null | null | ivan_original/include/find_oc_adapt.h | stevenglasford/Seminar_NDSU_2020 | 3bc778185ac40a92913c091e2e717434cbf17b31 | [
"Apache-2.0"
] | null | null | null | ivan_original/include/find_oc_adapt.h | stevenglasford/Seminar_NDSU_2020 | 3bc778185ac40a92913c091e2e717434cbf17b31 | [
"Apache-2.0"
] | null | null | null | /*
* Fichier utilisateur associe a la fonction de calcul de la trajectoire optimale avec un pas adaptatif
*
* Ce fichier contient deux fonctions :
* -une implementation de la fontion de recherche de contrôle optimal, find_optimal_control_adapt()
* -une adaptation de l'integrateur de Heun pour plusieurs pas
*/
/*!
*
* \brief fonction de recherche du controle optimal
*
* @param[in] y : l'état en cours
* @param[in] h : pas de progression unitaire
* @param[in] t : temps en cours
* @param[out] val: la valeur optimale trouvée
* @param[in] nbSteps : nombre de pas unitaires utilisé pour l'intégration à partir de y avec un contrôle donné
* @param[in] vtab : la fonction valeur utilisée pour le calcul de la valeur optimale
* @return le numéro du contrôle optimal trouvé
*/
int HJB::find_optimal_control_adapt(const double* y, double h, double t, double& val, int nbSteps, double *vtab)
{
double val_star,vect[ncall];
bool inTheBounds;
int c;
int u_star;
double rc;
double dvect[dim];
double currentVal;
//int dimc=u->dimC;
val_star=INF; u_star=-1;
for(c=0;c<ncall;c++)
{
/*
* pour tous les controles possibles
* calcul de la positions suivante correspondante avec RK2
*/
heunIntegrator(y, nbSteps, c, t, h, dvect, &inTheBounds);
rc = (!inTheBounds) ? INF : (*this.*interpolation)(dvect,topt);
if(rc<=2.0*T)
vect[c]=rc;
else
vect[c]=INF;
}
for(c=0;c<ncall;c++)
{
if(vect[c]<INF)
{
currentVal=vect[c];
if(currentVal<val_star)
{
val_star=currentVal;
u_star=c;
}
}
}
val=val_star;
return(u_star);
}
/*!
*
* \brief Cette fonction réalise le calcul d'une intégration de numérique de Heune sur un nombre donné de pas
*
* @param[in] yInit : l'état de début
* @param[in] h : pas de progression unitaire
* @param[in] tau : temps initial
* @param[out] inTheBounds: indicateur booléen de non dépassement des limites du domaine de calcul
* @param[in] nbSteps : nombre de pas unitaires utilisé pour l'intégration à partir de yInit avec un contrôle donné
* @param[in] c : le numéro du contrôle à appliquer le long de tout le chemin
* @param[out] res: l'état final (successeur de yInit pour le contrôle c )
*
*/
void HJB::heunIntegrator(const double* yInit,int nbSteps, int c, double tau, double h, double *res, bool *inTheBounds)
{
double ff2[dim], ff[dim],y[dim]; // tableaux pour le stockage temporaire des images intermediaires calculees
// pour le schema de Heun
int d;
double tt=tau; // temps en cours pour le chemin a calculer
int k=0;
*inTheBounds=true;
for(d=0;d<dim;d++)
y[d]=yInit[d];
while ((k<nbSteps )& (*inTheBounds))
{
(*dynamics)(y,(*u)[c],tt,ff2);
for(d=0;d<dim;d++)
res[d]=y[d]+h*ff2[d];
(*dynamics)(res,(*u)[c],tt+h,ff);
for(d=0;d<dim;d++)
{
res[d]=y[d]+0.5*h*(ff[d]+ff2[d]);
y[d]=res[d];
}
if(periodic_mesh)
periodizePoint(res);
for(d=0; d<dim; d++)
{
if(res[d]< mesh->lowBounds[d] || res[d]>mesh->highBounds[d])
{
(*inTheBounds)=false;
break;
}
}
k++;
tt+=h;
}
}
| 24.363636 | 118 | 0.631219 |
cd23516969e53cf4e332b54349522ea68f72041e | 2,884 | kt | Kotlin | app/src/main/java/org/panta/misskey_for_android_v2/adapter/NotificationViewHolder.kt | Kinoshita0623/Misskey_for_Android_v2 | 7d387d90ac0d4b4e44d8792710b9a0394b6128aa | [
"Apache-2.0"
] | 3 | 2019-05-01T15:34:17.000Z | 2019-05-06T15:28:14.000Z | app/src/main/java/org/panta/misskey_for_android_v2/adapter/NotificationViewHolder.kt | Kinoshita0623/Misskey-for-Android | 7d387d90ac0d4b4e44d8792710b9a0394b6128aa | [
"Apache-2.0"
] | null | null | null | app/src/main/java/org/panta/misskey_for_android_v2/adapter/NotificationViewHolder.kt | Kinoshita0623/Misskey-for-Android | 7d387d90ac0d4b4e44d8792710b9a0394b6128aa | [
"Apache-2.0"
] | null | null | null | package org.panta.misskey_for_android_v2.adapter
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.item_notification.view.*
import org.panta.misskey_for_android_v2.R
import org.panta.misskey_for_android_v2.constant.NotificationType
import org.panta.misskey_for_android_v2.constant.ReactionConstData
import org.panta.misskey_for_android_v2.entity.NotificationProperty
class NotificationViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
private val userIcon = itemView.notification_user_icon
private val typeIcon = itemView.notification_status_icon
private val userName = itemView.notification_user_name
private val content = itemView.notification_content
fun setNotification(property: NotificationProperty){
picasso(userIcon, property.user.avatarUrl!!)
when(NotificationType.getEnumFromString(property.type)){
NotificationType.FOLLOW ->{
typeIcon.setImageResource(R.drawable.human_icon)
content.visibility = View.INVISIBLE
}
NotificationType.RENOTE ->{
typeIcon.setImageResource(R.drawable.re_note_icon)
content.text = property.note?.text
}
NotificationType.REACTION ->{
setReactionTypeIcon(property.reaction)
content.text = property.note?.text
}
else -> throw IllegalArgumentException("follow, renote, reactionしか対応していません。${property.type}")
}
userName.text = property.user.name
}
private fun setReactionTypeIcon(type: String?){
when(type){
ReactionConstData.RIP -> typeIcon.setImageResource(R.drawable.reaction_icon_rip)
ReactionConstData.PUDDING -> typeIcon.setImageResource(R.drawable.reaction_icon_pudding)
ReactionConstData.LOVE -> typeIcon.setImageResource(R.drawable.reaction_icon_love)
ReactionConstData.LAUGH -> typeIcon.setImageResource(R.drawable.reaction_icon_laugh)
ReactionConstData.ANGRY -> typeIcon.setImageResource(R.drawable.reaction_icon_angry)
ReactionConstData.CONFUSED -> typeIcon.setImageResource(R.drawable.reaction_icon_confused)
ReactionConstData.CONGRATS -> typeIcon.setImageResource(R.drawable.reaction_icon_congrats)
ReactionConstData.HMM -> typeIcon.setImageResource(R.drawable.reaction_icon_hmm)
ReactionConstData.LIKE -> typeIcon.setImageResource(R.drawable.reaction_icon_like)
ReactionConstData.SURPRISE -> typeIcon.setImageResource(R.drawable.reaction_icon_surprise)
}
}
private fun picasso(imageView: ImageView, url: String){
Picasso
.get()
.load(url)
.into(imageView)
}
} | 47.278689 | 105 | 0.720527 |
21e2f1b5fd5a7a52aa6ff4996210bbc8214c01e4 | 1,014 | html | HTML | manuscript/page-810/body.html | marvindanig/the-beautiful-and-the-damned | fb6b53f735cb001c480264823c215688fb9ceb11 | [
"CECILL-B"
] | null | null | null | manuscript/page-810/body.html | marvindanig/the-beautiful-and-the-damned | fb6b53f735cb001c480264823c215688fb9ceb11 | [
"CECILL-B"
] | null | null | null | manuscript/page-810/body.html | marvindanig/the-beautiful-and-the-damned | fb6b53f735cb001c480264823c215688fb9ceb11 | [
"CECILL-B"
] | null | null | null | <div class="leaf flex"><div class="inner justify"><p> At high school she had enjoyed a rather unsavory reputation. As a matter of fact her behavior at the class picnic, where the rumors started, had been merely indiscreet—she had retained her technical purity until over a year later. The boy had been a clerk in a store on Jackson Street, and on the day after the incident he departed unexpectedly to New York. He had been intending to leave for some time, but had tarried for the consummation of his amorous enterprise.</p><p>After a while she confided the adventure to a girl friend, and later, as she watched her friend disappear down the sleepy street of dusty sunshine she knew in a flash of intuition that her story was going out into the world. Yet after telling it she felt much better, and a little bitter, and made as near an approach to character as she was capable of by walking in another direction and meeting another man with the honest intention of gratifying herself again.</p></div> </div> | 1,014 | 1,014 | 0.789941 |
39c67ae9679a204f343ccb7842ad1eaa51df6fa1 | 6,531 | js | JavaScript | src/rss.js | hebcal/hebcal-rest-api | 4eb07050c7f252c294fd611567bfac33b59673ab | [
"BSD-2-Clause"
] | 5 | 2020-08-28T22:33:07.000Z | 2022-03-31T18:59:45.000Z | src/rss.js | hebcal/hebcal-rest-api | 4eb07050c7f252c294fd611567bfac33b59673ab | [
"BSD-2-Clause"
] | 105 | 2021-07-15T19:19:00.000Z | 2022-03-24T20:01:56.000Z | src/rss.js | hebcal/hebcal-rest-api | 4eb07050c7f252c294fd611567bfac33b59673ab | [
"BSD-2-Clause"
] | null | null | null | import {getEventCategories, makeAnchor, appendIsraelAndTracking,
makeTorahMemoText, getCalendarTitle} from './common';
import {Locale, HebrewCalendar, Zmanim, flags} from '@hebcal/core';
import holidayDescription from './holidays.json';
/**
* @private
* @param {Event} ev
* @param {boolean} il
* @param {string} tzid
* @param {string} mainUrl
* @param {string} utmSource
* @param {string} utmMedium
* @return {string[]}
*/
function getLinkAndGuid(ev, il, tzid, mainUrl, utmSource, utmMedium) {
let link;
let guid;
const dt = ev.eventTime || ev.getDate().greg();
const isoDateTime = Zmanim.formatISOWithTimeZone(tzid, dt);
const dtStr = isoDateTime.substring(0, isoDateTime.indexOf('T'));
const dtAnchor = dtStr.replace(/-/g, '');
const descAnchor = makeAnchor(ev.getDesc());
const anchor = `${dtAnchor}-${descAnchor}`;
const url0 = ev.url();
if (url0) {
link = appendIsraelAndTracking(url0, il, utmSource, utmMedium).replace(/&/g, '&');
guid = `${url0}#${anchor}`;
} else {
const url1 = `${mainUrl}&dt=${dtStr}`;
const url = appendIsraelAndTracking(url1, il, utmSource, utmMedium).replace(/&/g, '&');
guid = url1.replace(/&/g, '&') + `#${anchor}`;
link = `${url}#${anchor}`;
}
return [link, guid];
}
/**
* @param {Event[]} events
* @param {Location} location
* @param {string} mainUrl
* @param {string} selfUrl
* @param {string} [lang] language such as 'he' (default 'en-US')
* @param {boolean} [evPubDate] if true, use event time as pubDate (false uses lastBuildDate)
* @return {string}
*/
export function eventsToRss(events, location, mainUrl, selfUrl, lang='en-US', evPubDate=true) {
const cityDescr = location.getName();
const options = {
location,
mainUrl,
selfUrl,
lang,
evPubDate,
title: Locale.gettext('Shabbat') + ` Times for ${cityDescr}`,
description: `Weekly Shabbat candle lighting times for ${cityDescr}`,
utmSource: 'shabbat1c',
utmMedium: 'rss',
};
return eventsToRss2(events, options);
}
const localeToLg = {
's': 'en',
'a': 'en',
'he-x-NoNikud': 'he',
'h': 'he',
'ah': 'en',
'sh': 'en',
};
/**
* @param {Event[]} events
* @param {HebrewCalendar.Options} options
* @return {string}
*/
export function eventsToRss2(events, options) {
options.dayFormat = new Intl.DateTimeFormat('en-US', {
weekday: 'long',
day: '2-digit',
month: 'long',
year: 'numeric',
});
const location = options.location;
const mainUrl = options.mainUrl;
const buildDate = options.buildDate = options.buildDate || new Date();
const thisYear = buildDate.getFullYear();
const lastBuildDate = options.lastBuildDate = buildDate.toUTCString();
const title = options.title || getCalendarTitle(events, options);
const description = options.description || title;
const utmSource = options.utmSource || 'shabbat1c';
const utmMedium = options.utmMedium || 'rss';
const mainUrlEsc = appendIsraelAndTracking(mainUrl,
location && location.getIsrael(),
utmSource, utmMedium, options.utmCampaign).replace(/&/g, '&');
const selfUrlEsc = options.selfUrl.replace(/&/g, '&');
const lang = options.lang || localeToLg[options.locale] || options.locale || 'en-US';
let str = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>${title}</title>
<link>${mainUrlEsc}</link>
<atom:link href="${selfUrlEsc}" rel="self" type="application/rss+xml" />
<description>${description}</description>
<language>${lang}</language>
<copyright>Copyright (c) ${thisYear} Michael J. Radwin. All rights reserved.</copyright>
<lastBuildDate>${lastBuildDate}</lastBuildDate>
`;
events.forEach((ev) => {
str += eventToRssItem2(ev, options);
});
str += '</channel>\n</rss>\n';
return str;
}
/**
* @private
* @param {Event} ev
* @param {boolean} evPubDate
* @param {Date} evDate
* @param {string} lastBuildDate
* @return {string}
*/
function getPubDate(ev, evPubDate, evDate, lastBuildDate) {
if (evPubDate) {
const dt = ev.eventTime;
if (dt) {
return dt.toUTCString();
}
return evDate.toUTCString().replace(/ \S+ GMT$/, ' 00:00:00 GMT');
}
return lastBuildDate;
}
/**
* @param {Event} ev
* @param {HebrewCalendar.Options} options
* @return {string}
*/
export function eventToRssItem2(ev, options) {
return eventToRssItem(
ev,
options.evPubDate,
options.lastBuildDate,
options.dayFormat,
options.location,
options.mainUrl,
options);
}
/**
* @param {Event} ev
* @param {boolean} evPubDate
* @param {string} lastBuildDate
* @param {Intl.DateTimeFormat} dayFormat
* @param {Location} location
* @param {string} mainUrl
* @param {HebrewCalendar.Options} [options]
* @return {string}
*/
export function eventToRssItem(ev, evPubDate, lastBuildDate, dayFormat, location, mainUrl, options) {
let subj = ev.render();
const evDate = ev.getDate().greg();
const pubDate = getPubDate(ev, evPubDate, evDate, lastBuildDate);
const il = location ? location.getIsrael() : false;
const tzid = location ? location.getTzid() : 'UTC';
const utmSource = (options && options.utmSource) || 'shabbat1c';
const utmMedium = (options && options.utmMedium) || 'rss';
const linkGuid = getLinkAndGuid(ev, il, tzid, mainUrl, utmSource, utmMedium);
const link = linkGuid[0];
const guid = linkGuid[1];
const categories = getEventCategories(ev);
const cat0 = categories[0];
const desc = ev.getDesc();
const candles = desc === 'Havdalah' || desc === 'Candle lighting';
let memo;
if (candles) {
const colon = subj.indexOf(': ');
if (colon != -1) {
const options = {location, il, locale: Locale.getLocaleName()};
const time = HebrewCalendar.reformatTimeStr(ev.eventTimeStr, 'pm', options);
subj = subj.substring(0, colon) + ': ' + time;
}
} else {
memo = (ev.getFlags() & flags.PARSHA_HASHAVUA) ?
makeTorahMemoText(ev, il) :
ev.memo || holidayDescription[ev.basename()];
}
const description = memo || dayFormat.format(evDate);
const geoTags = (cat0 == 'candles') ?
`<geo:lat>${location.getLatitude()}</geo:lat>\n<geo:long>${location.getLongitude()}</geo:long>\n` :
'';
return `<item>
<title>${subj}</title>
<link>${link}</link>
<guid isPermaLink="false">${guid}</guid>
<description>${description}</description>
<category>${cat0}</category>
<pubDate>${pubDate}</pubDate>
${geoTags}</item>
`;
}
| 32.172414 | 113 | 0.657786 |
7076d42073e61e2752b2a3cda34fa6297ecf2d1a | 1,165 | c | C | voxen/stream.c | mafiosso/voxen | d0368bbfe3cf2134253480c362a313e258cf4fec | [
"MIT"
] | 2 | 2018-06-24T09:28:00.000Z | 2020-11-24T12:09:28.000Z | voxen/stream.c | mafiosso/voxen | d0368bbfe3cf2134253480c362a313e258cf4fec | [
"MIT"
] | null | null | null | voxen/stream.c | mafiosso/voxen | d0368bbfe3cf2134253480c362a313e258cf4fec | [
"MIT"
] | 1 | 2021-06-30T10:27:56.000Z | 2021-06-30T10:27:56.000Z | #include "VX_lib.h"
#include "stream.h"
VX_promise * VX_promise_new( void (*func) , void * user_args )
{
VX_promise * out = malloc(sizeof(VX_promise));
*out = (VX_promise){ func , user_args };
return out;
}
static void s_call( VX_stream * self , void * shared_args , void * ret )
{
int i = self->stack_top;
while( i >= 0 )
{
VX_promise * p = self->stack_promises[i];
p->func_call( shared_args , p->args , ret );
i--;
}
}
static void s_promise( VX_stream * self , VX_promise * p )
{
self->stack_promises[ self->stack_top++ ] = p;
if( self->stack_max_size >= self->stack_top )
{
self->stack_max_size *= 2;
self->stack_promises = realloc( self->stack_promises ,
sizeof(void*) * self->stack_max_size );
}
}
VX_stream * VX_stream_new( VX_uint32 default_stack_size )
{
VX_stream * out = calloc(sizeof(VX_stream) , 0);
out->stack_promises = malloc( sizeof( void* ) * default_stack_size );
out->stack_max_size = default_stack_size;
out->stack_top = 0;
out->call = s_call;
out->promise = s_promise;
return out;
}
| 24.270833 | 79 | 0.6 |
e9091bdeeaa1bacb84752b67f3ed1bbd23ec20dc | 931 | rb | Ruby | app/models/user.rb | victorzottmann/steamdeck | a925baf82517bc8e6d67571c5a363925a8ddfb15 | [
"Ruby"
] | null | null | null | app/models/user.rb | victorzottmann/steamdeck | a925baf82517bc8e6d67571c5a363925a8ddfb15 | [
"Ruby"
] | null | null | null | app/models/user.rb | victorzottmann/steamdeck | a925baf82517bc8e6d67571c5a363925a8ddfb15 | [
"Ruby"
] | null | null | null | class User < ApplicationRecord
rolify
has_many :books, dependent: :destroy
has_many :rentals
has_one_attached :profile_picture
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
# validates :first_name, length: { within: 1..20, too_long: "%{count} characters is the maximum allowed" }
# validates :last_name, length: { within: 1..20, too_long: "%{count} characters is the maximum allowed" }
# validates :username, uniqueness: true,
# validates :email, presence: true, uniqueness: true
# validates :bio, length: { maximum: 200, too_long: "200 characters is the maximum allowed" }
# validates :password, length: { in: 6..20, too_long: "%{count} characters is the maximum allowed" }
end
| 46.55 | 115 | 0.692803 |
6e329968836730959d3b28a544f45dfc551c44d7 | 14,894 | html | HTML | talks.html | eholmbeck/eholmbeck.github.io | 08e6a2b761240add3aa93ec7a6596dd20e26ef43 | [
"CC-BY-3.0"
] | null | null | null | talks.html | eholmbeck/eholmbeck.github.io | 08e6a2b761240add3aa93ec7a6596dd20e26ef43 | [
"CC-BY-3.0"
] | null | null | null | talks.html | eholmbeck/eholmbeck.github.io | 08e6a2b761240add3aa93ec7a6596dd20e26ef43 | [
"CC-BY-3.0"
] | null | null | null | <!DOCTYPE HTML>
<!--
Massively by HTML5 UP
html5up.net | @ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Talks</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<a href="index.html" class="logo">Home</a>
</header>
<!-- Nav -->
<nav id="nav">
<ul class="links">
<li><a href="index.html">About</a></li>
<li><a href="research.html">Research</a></li>
<li><a href="publications.html">Publications</a></li>
<li class="active"><a href="talks.html">Talks</a></li>
<!--<li><a href="elements.html">Elements Reference</a></li>-->
</ul>
<!--
<ul class="icons">
<li><a href="#" class="icon fa-twitter"><span class="label">Twitter</span></a></li>
<li><a href="#" class="icon fa-facebook"><span class="label">Facebook</span></a></li>
<li><a href="#" class="icon fa-instagram"><span class="label">Instagram</span></a></li>
<li><a href="#" class="icon fa-github"><span class="label">GitHub</span></a></li>
</ul>
-->
</nav>
<!-- Main -->
<div id="main">
<!-- Post -->
<section class="post">
<h2>Seminars, Colloquia, and Conference Talks</h2>
<p>Click on the talk title to view or watch (<span style="color: red">►</span>) presentation! (Slides work best in Safari)</p>
<div class="table-wrapper">
<table style="font-size:10pt">
<thead>
<tr>
<th style="width:13%">Date</th>
<th style="width:35%">Event</th>
<th>Talk Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>28 Oct 2021</td>
<td><a href="https://www.stsci.edu/contents/events/stsci/2021/october/2021-nasa-hubble-fellowship-program-nhfp-symposium" target="_blank">2021 NASA Hubble Fellowship Program (NHFP) Symposium (Contributed)</a></td>
<td>Reconstructing Neutron Star Masses from Metal-poor Stars</td>
</tr>
<tr>
<td>13 Oct 2021</td>
<td><a href="https://meetings.aps.org/Meeting/DNP21/Session/MA.2" target="_blank">2021 Fall Meeting of the APS Division of Nuclear Physics (Invited)</a></td>
<td>Dissertation Award in Nuclear Physics Talk: Constraining the <i>r</i>-process with Observation and Theory</td>
</tr>
<tr>
<td>13 Oct 2021</td>
<td><a href="https://meetings.aps.org/Meeting/DNP21/Session/LD.3" target="_blank">2021 Fall Meeting of the APS Division of Nuclear Physics (Contributed)</a></td>
<td>A Nuclear Equation of State Inferred from Stellar <i>r</i>-process Abundances</td>
</tr>
<tr>
<td>5 Oct 2021</td>
<td><a href="https://inpp.ohio.edu/~inpp/seminars.html" target="_blank">Institute for Nuclear and Particle Physics Seminar (Invited)</a></td>
<td>Stellar Actinides as Tracers of Heavy-Element Nucleosynthesis</td>
</tr>
<tr>
<td>30 Sep 2021</td>
<td><a href="https://indico.frib.msu.edu/event/49/" target="_blank">IReNA Origin of the Isotopes Workshop (Invited)</a></td>
<td><a href="https://indico.frib.msu.edu/event/49/contributions/500/" target="_blank">The Production of the Heaviest Elements through the Nuclear Lens</a></td>
</tr>
<tr>
<td>16 Sep 2021</td>
<td><a href="https://astronomy.yale.edu/event/yale-astronomy-virtual-colloquium-erika-holmbeck" target="_blank">Yale Astronomy Seminar (Invited)</a></td>
<td>Heavy-Element Nucleosynthesis in the Era of Multi-messenger Astronomy</td>
</tr>
<tr>
<td>29 Jul 2021</td>
<td>LANL Astrophysics Seminar (Invited)</td>
<td>Stellar Actinides as Tracers of Heavy-Element Nucleosynthesis</td>
</tr>
<tr>
<td>28 Jul 2021</td>
<td><a href="http://www2.yukawa.kyoto-u.ac.jp/~nuc2021/index.php" target="_blank">Nuclear Burning in Massive Stars</a> (Contributed)</td>
<td><a href="http://www2.yukawa.kyoto-u.ac.jp/~nuc2021/slides/holmbeck_e.pdf" targer="_blank">Reconstructing Neutron Star Masses from Metal-Poor Stars</a></td>
</tr>
<tr>
<td>13 Jul 2021</td>
<td><a href="https://compact-binaries.org/content/presentations/2021-07-13/erika.holmbeck/tcan2021-erika-holmbeck" target="_blank">TCAN Meeting 2021: BNS/BH-NS Merger Workshop</a> (Invited)</td>
<td><a href="https://youtu.be/ObZV4xJQuNw" target="_blank"><span style="color: red">►</span> Observational Signatures of Heavy-Element Nucleosynthesis</a></td>
</tr>
<tr>
<td>29 Mar 2021</td>
<td><a href="http://csa.phys.uvic.ca/star-talks/the-origin-of-the-heavy-elements-what-we-can-learn-from-metal-poor-stars" target="_blank">University of Victoria Physics and Astronomy Seminar</a> (Invited)</td>
<td><a href="https://stellarhydro1.ppmstar.org/StarTalks/EHolmbeck_StellarSeminar.mp4" target="_blank"><span style="color: red">►</span> The Origin of the Heavy Elements: What We Can Learn from Metal-Poor Stars</a></td>
</tr>
<tr>
<td>26 Mar 2021</td>
<td>Texas AMU Nuclear Astrophysics Seminar Series (Invited)</td>
<td>Heavy Element Nucleosynthesis in the Era of Multi-messenger Astronomy</td>
</tr>
<tr>
<td>19 Mar 2021</td>
<td>Center for Computational Relativity and Gravitation, Rochester Institute of Technology (Invited)</td>
<td>The Astrophysical Production of the Heaviest Elements</td>
</tr>
<tr>
<td>22 Jan 2021</td>
<td><a href="https://www.astro.ucsc.edu/news-events/Seminars/index.html" target="_blank">University of California Santa Cruz</a> (Invited)</td>
<td>The Astrophysical Production of the Heaviest Elements</td>
</tr>
<tr>
<td>9 Nov 2020</td>
<td><a href="http://www.physics.sfsu.edu/Colloquia.html" target="_blank">San Francisco State University Physics Colloquium</a> (Invited)</td>
<td><a href="https://drive.google.com/file/d/1bBL06npK8FBI5QSPMYYlQgb21Th9iPpR/view?usp=sharing" target="_blank">The Astrophysical Production of the Heaviest Elements</a></td>
</tr>
<tr>
<td>31 Oct 2020</td>
<td><a href="https://meetings.aps.org/Meeting/DNP20/Session/LD" target="_blank">2020 Fall Meeting of the APS Division of Nuclear Physics</a> (Contributed)</td>
<td><a href="https://drive.google.com/file/d/1RsIehEg_t-90Jnsj5G8FG-V8Xb_r7JJq/view?usp=sharing" target="_blank">Which Neutron Star Mergers Synthesized the <em>r</em>-Process Elements?</a></td>
</tr>
<tr>
<td>23 Oct 2020</td>
<td>Gonzaga University Physics Colloquium (Invited)</td>
<td>The Astrophysical Production of the Heaviest Elements</td>
</tr>
<tr>
<td>6 Oct 2020</td>
<td><a href="https://n3as.berkeley.edu/p/event/properties-of-r-process-producing-neutron-star-mergers/" target="_blank">N3AS Seminar</a> (Invited)</td>
<td><a href="https://n3as.berkeley.edu/wp-content/uploads/2020/09/n3as_6oct20_holmbeck_file.pdf" target="_blank">Properties of <em>r</em>-Process-Producing Neutron Star Mergers: What We Can Learn from Metal-Poor Stars</a></td>
</tr>
<tr>
<td>12 May 2020</td>
<td><a href="https://events.nd.edu/events/2020/05/12/our-universe-revealed-cosmic-alchemy-how-the-universe-made-the-heaviest-elements/" target="_blank">Our Universe Revealed</a> (Invited)</td>
<td><a href="https://www.youtube.com/watch?v=TxH74RTseTg" target="_blank"><span style="color: red">►</span> Cosmic Alchemy: How the Universe Made the Heaviest Elements</a></td>
</tr>
<tr>
<td>24 Apr 2020</td>
<td>Ph.D. Thesis Defense</td>
<td><a href="https://youtu.be/bGEmNrLnaic" target="_blank"><span style="color: red">►</span> The Looking Glass and Beyond: Using Observations and Modeling of Stellar Actinide Abundances as a Window into <em>r</em>-Process Events</a></td>
</tr>
<tr>
<td>14 Feb 2020</td>
<td><a href="https://www.andrews.edu/cas/math/about/eigen-.html" target="_blank">Andrews University eigen* Colloquium</a> (Invited)</td>
<td><a href="https://docs.google.com/presentation/d/1EsAum8K5IX5t7dLVCgvwz4IQTFkWbzkBT2W8hPuc-vM/edit?usp=sharing" target="_blank">Investigating the Production of the Heavy Elements with Stellar Uranium</a></td>
</tr>
<tr>
<td>8 Jan 2020</td>
<td><a href="https://aas.org/meetings/aas235/program" target="_blank">235th Meeting of the AAS</a> (Contributed)</td>
<td><a href="https://docs.google.com/presentation/d/1NLsxtZpDfhIhD19ai-3BNLQf14lsFTzXK3fLQnSUj00/edit?usp=sharing" target="_blank">The Actinide Boost and its <em>r</em>-Process Implications</a></td>
</tr>
<tr>
<td>2 Dec 2019</td>
<td><a href="https://physics.nd.edu/events/2019/12/02/nuclear-physics-seminar-ms-erika-holmbeck-university-of-notre-dame/" target="_blank">Notre Dame Nuclear Physics Seminar</a> (Invited)</td>
<td><a href="https://eholmbeck.github.io/slides/ND_Nuclear_Seminar.html#" target="_blank">Constraining the <em>r</em>-Process with Actinide Production Studies</a></td>
</tr>
<tr>
<td>20 Nov 2019</td>
<td><a href="https://indico.frib.msu.edu/event/23/overview" target="_blank">R-Process Alliance Workshop: Pushing toward the Next Project Phases</a> (Invited)</td>
<td><a href="https://eholmbeck.github.io/slides/RPA_Workshop.html#" target="_blank">Constraining the <em>r</em>-Process with Actinide Production Studies</a></td>
</tr>
<tr>
<td>16 Oct 2019</td>
<td><a href="http://meetings.aps.org/Meeting/DNP19/Session/LG.8" target="_blank">2019 Fall Meeting of the APS Division of Nuclear Physics</a> (Contributed)</td>
<td><a href="https://eholmbeck.github.io/slides/DNP2019.html#" target="_blank">Actinide-Rich or Actinide-Poor, Same <em>r</em>-Process Progenitor</a></td>
</tr>
<tr>
<td>1 Oct 2019</td>
<td><a href="https://physics.nd.edu/events/2019/10/01/astrophysics-seminar-erika-holmbeck-university-of-nottre-dame/" target="_blank">Notre Dame Astrophysics Seminar</a> (Invited)</td>
<td><a href="https://eholmbeck.github.io/slides/ND_Seminar.html#" target="_blank">The Stellar Actinide Boost and its <em>r</em>-Process Implications</a></td>
</tr>
<tr>
<td>23 May 2019</td>
<td><a href="https://indico.frib.msu.edu/event/1/page/6-program" target="_blank">2019 JINA-CEE Frontiers in Nuclear Astrophysics</a> (Contributed)</td>
<td><a href="https://eholmbeck.github.io/slides/Frontiers2019_Holmbeck.html#" target="_blank">Actinide-Rich or Actinide-Poor, Same <em>r</em>-Process Progenitor</a></td>
</tr>
<tr>
<td>17 May 2019</td>
<td><a href="https://sites.google.com/view/ffss2019/home" target="_blank">First Frontiers Summer School</a> (Invited)</td>
<td>The <em>r</em>-Process</td>
</tr>
<tr>
<td>15 May 2019</td>
<td><a href="https://sites.google.com/view/ffss2019/home" target="_blank">First Frontiers Summer School</a> (Invited)</td>
<td>General Astronomy: Terminology and Observing Tools Relevant for JINA-CEE</td>
</tr>
<tr>
<td>17 Apr 2019</td>
<td><a href="https://physics.nd.edu/events/calendar/colloquia/" target="_blank">Notre Dame GPS Annual Conference</a> (Contributed)</td>
<td><a href="https://eholmbeck.github.io/slides/GPS2019.html#/" target="_blank">Actinide-Boost Stars Might Not Suggest a Separate <em>r</em>-Process Site</a></td>
</tr>
<tr>
<td>28 Mar 2019</td>
<td><a href="https://r-process-sources.weebly.com/" target="_blank"><em>R-</em>Process Sources in the Universe</a> (Contributed)</td>
<td><a href="https://eholmbeck.github.io/slides/R-Process_Sources_2019.slides.html" target="_blank">Actinide-Boost Stars may not Suggest a Separate <em>r</em>-Process Site</a></td>
</tr>
<tr>
<td>25 Oct 2018</td>
<td><a href="http://meetings.aps.org/Meeting/HAW18/Session/EP.11" target="_blank">Fifth Joint Meeting of the Nuclear Physics Divisions of the APS and JPS</a> (Contributed)</td>
<td><a href="https://eholmbeck.github.io/slides/DNP2018#/" target="_blank">Actinide Production in Neutron Star Mergers</a></td>
</tr>
<tr>
<td>12 Oct 2018</td>
<td><a href="https://www.jinaweb.org/events/actinide-production-neutron-star-mergers-observation-and-theory" target="_blank">JINA-CEE Online Seminar</a> (Invited)</td>
<td><a href="https://www.youtube.com/watch?v=3HJ_NsZXyTw&feature=youtu.be" target="_blank"><span style="color: red">►</span> Actinide Production in Neutron Star Mergers: Observation and Theory</a></td>
</tr>
</tbody>
</table>
</div>
<article>
<div class="image fit">
<img src="images/Frontiers2018.jpg">
</div>
<p>As you can see, I am passionate about my work.
</p>
</article>
</section>
</div>
<!-- Footer -->
<footer id="footer">
<section>
<!--
<h3>Social</h3>
<ul class="icons alt">
<li><a href="#" class="icon alt fa-twitter"><span class="label">Twitter</span></a></li>
<li><a href="#" class="icon alt fa-facebook"><span class="label">Facebook</span></a></li>
<li><a href="#" class="icon alt fa-instagram"><span class="label">Instagram</span></a></li>
<li><a href="#" class="icon alt fa-github"><span class="label">GitHub</span></a></li>
</ul>
-->
</section>
</footer>
<!-- Copyright -->
<div id="copyright">
<ul><li>© Untitled</li><li>Design: <a href="https://html5up.net">HTML5 UP</a></li></ul>
</div>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
| 55.36803 | 249 | 0.623204 |
4747823f49474dae697dc821577de021add98227 | 4,240 | html | HTML | client/index.html | adamsteinert/remoteHaven | 95bdfc4f5179e5973eac97a88ba53520da041d69 | [
"MIT"
] | 1 | 2020-05-22T06:03:44.000Z | 2020-05-22T06:03:44.000Z | client/index.html | adamsteinert/remoteHaven | 95bdfc4f5179e5973eac97a88ba53520da041d69 | [
"MIT"
] | 2 | 2020-04-09T18:27:09.000Z | 2020-04-15T22:51:34.000Z | client/index.html | adamsteinert/remoteHaven | 95bdfc4f5179e5973eac97a88ba53520da041d69 | [
"MIT"
] | null | null | null | <!-- ./client/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<style>
canvas {
background: cornflowerblue;
margin: 1px solid gray;
padding: 0;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
width: 3000;
height: 3000;
font-family: sans-serif;
overflow: scroll;
}
a {
display: block;
text-align: center;
margin: 10px auto;
width: 100%;
color: #2c3e50;
}
.container {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
}
.left {
width: 300px;
padding: 8px;
}
.right {
max-width: 1800px;
}
</style>
<body onload="init();initItemLists();">
<div class="container">
<div class="left">
<fieldset>
<div>Map Tiles</div>
<br />
<select id="tileSelect"></select>
<button onClick="addMapTile(ibFromSrc(document.getElementById('tileSelect').value), true)">Add Tiles</button>
<br />
<!-- <button onClick="">Lock Tiles</button>
<hr /> -->
</fieldset>
<fieldset>
<div>Player Characters</div>
<br />
<select id="pcs">
<option value="Brute">Brute</option>
<option value="Mindthief">Mindthief</option>
<option value="Spellweaver">Spellweaver</option>
</select>
<button onClick="">Add PC</button>
</fieldset>
<fieldset>
<div>Tile Adorners</div>
<br />
<select id="adorners">
<option value="Door">Door</option>
</select>
<button onClick="">Add Adorner</button>
</fieldset>
<fieldset>
<div>Monsters</div>
<br />
<select id="monsterSelect"></select>
<br />
<!-- TODO: call a server method to get monster number. Use global increment as a cheap identity -->
<select id="monsterNumber">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
<input type="checkbox" name="elite" id="elite" /><label for="elite">Elite</label>
<br />
<button onClick="addMonster(document.getElementById('monsterSelect').value,
document.getElementById('monsterNumber').value,
document.getElementById('elite').checked)">Add Monster</button>
</fieldset>
<fieldset>
<div>Map Tiles</div>
<br />
<!-- <button onClick="sendMsg()">Ping</button> -->
<fieldset>
</div>
<div class="right">
<div style="max-height: 90vh; overflow: auto;">
<canvas id="canvas"></canvas>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
<script type="text/javascript" src="/js/rendering.js"></script>
<script type="text/javascript" src="/js/restApi.js"></script>
<script type="text/javascript" src="/js/socketApi.js"></script>
</body>
</html> | 31.176471 | 126 | 0.461557 |
c01702a17ea0bac6932175aa1b78bf507ba018df | 759 | asm | Assembly | programs/oeis/302/A302588.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/302/A302588.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/302/A302588.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | ; A302588: a(n) = a(n-3) + 7*(n-2), a(0)=1, a(1)=2, a(2)=4.
; 1,2,4,8,16,25,36,51,67,85,107,130,155,184,214,246,282,319,358,401,445,491,541,592,645,702,760,820,884,949,1016,1087,1159,1233,1311,1390,1471,1556,1642,1730,1822,1915,2010
mov $12,$0
mov $14,$0
add $14,1
lpb $14,1
clr $0,12
mov $0,$12
sub $14,1
sub $0,$14
mov $9,$0
mov $11,$0
add $11,1
lpb $11,1
mov $0,$9
sub $11,1
sub $0,$11
sub $1,$1
mov $6,2
mov $8,2
lpb $0,1
sub $0,1
mov $5,$0
trn $0,2
mov $2,1
trn $8,$1
trn $1,8
add $5,1
add $8,$1
mov $1,$5
add $1,$0
trn $2,$8
add $0,$2
mov $6,$1
lpe
mov $1,$6
sub $1,1
add $10,$1
lpe
add $13,$10
lpe
mov $1,$13
| 17.25 | 172 | 0.478261 |
0cbd7b1b3648a635297e6eb2447f59f26aa10163 | 49,924 | py | Python | pyUSID/io/hdf_utils/model.py | rajgiriUW/pyUSID | 064dcd81d9c42f4eb4782f0a41fd437b3f56f50c | [
"MIT"
] | 25 | 2018-07-11T21:43:56.000Z | 2021-11-17T11:40:00.000Z | pyUSID/io/hdf_utils/model.py | rajgiriUW/pyUSID | 064dcd81d9c42f4eb4782f0a41fd437b3f56f50c | [
"MIT"
] | 62 | 2018-07-05T20:28:52.000Z | 2021-12-14T09:49:35.000Z | pyUSID/io/hdf_utils/model.py | rajgiriUW/pyUSID | 064dcd81d9c42f4eb4782f0a41fd437b3f56f50c | [
"MIT"
] | 15 | 2019-03-27T22:28:47.000Z | 2021-01-03T20:23:42.000Z | # -*- coding: utf-8 -*-
"""
Utilities for reading and writing USID datasets that are highly model-dependent (with or without N-dimensional form)
Created on Tue Nov 3 21:14:25 2015
@author: Suhas Somnath, Chris Smith
"""
from __future__ import division, print_function, absolute_import, unicode_literals
from warnings import warn
import sys
import h5py
import numpy as np
from dask import array as da
from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, \
copy_dataset, lazy_load_array
from sidpy.base.num_utils import contains_integers
from sidpy.base.dict_utils import flatten_dict
from sidpy.base.string_utils import validate_single_string_arg, \
validate_list_of_strings, validate_string_args
from sidpy.hdf.dtype_utils import validate_dtype
from sidpy import sid
from .base import write_book_keeping_attrs
from .simple import link_as_main, check_if_main, write_ind_val_dsets, validate_dims_against_main, validate_anc_h5_dsets
from ..dimension import Dimension, validate_dimensions
from ..anc_build_utils import INDICES_DTYPE, make_indices_matrix
if sys.version_info.major == 3:
unicode = str
def reshape_to_n_dims(h5_main, h5_pos=None, h5_spec=None, get_labels=False, verbose=False, sort_dims=False,
lazy=False):
"""
Reshape the input 2D matrix to be N-dimensions based on the
position and spectroscopic datasets.
Parameters
----------
h5_main : HDF5 Dataset
2D data to be reshaped
h5_pos : HDF5 Dataset, optional
Position indices corresponding to rows in `h5_main`
h5_spec : HDF5 Dataset, optional
Spectroscopic indices corresponding to columns in `h5_main`
get_labels : bool, optional
Whether or not to return the dimension labels. Default False
verbose : bool, optional
Whether or not to print debugging statements
sort_dims : bool
If True, the data is sorted so that the dimensions are in order from slowest to fastest
If False, the data is kept in the original order
If `get_labels` is also True, the labels are sorted as well.
lazy : bool, optional. Default = False
If False, ds_Nd will be a numpy.ndarray object - this is suitable if the HDF5 dataset fits into memory
If True, ds_Nd will be a dask.array object - This is suitable if the HDF5 dataset is too large to fit into
memory. Note that this will bea lazy computation meaning that the returned object just contains the instructions
. In order to get the actual value or content in numpy arrays, call ds_Nd.compute()
Returns
-------
ds_Nd : N-D numpy array or dask.array object
N dimensional array arranged as [positions slowest to fastest, spectroscopic slowest to fastest]
success : boolean or string
True if full reshape was successful
"Positions" if it was only possible to reshape by
the position dimensions
False if no reshape was possible
ds_labels : list of str
List of the labels of each dimension of `ds_Nd`
Notes
-----
If either `h5_pos` or `h5_spec` are not provided, the function will first
attempt to find them as attributes of `h5_main`. If that fails, it will
generate dummy values for them.
"""
# TODO: automatically switch on lazy if the data is larger than memory
# TODO: sort_dims does not appear to do much. Functions as though it was always True
if h5_pos is None and h5_spec is None:
if not check_if_main(h5_main):
raise ValueError('if h5_main is a h5py.Dataset it should be a Main dataset')
else:
if not isinstance(h5_main, (h5py.Dataset, np.ndarray, da.core.Array)):
raise TypeError('h5_main should either be a h5py.Dataset or numpy array')
if h5_pos is not None:
if not isinstance(h5_pos, (h5py.Dataset, np.ndarray, da.core.Array)):
raise TypeError('h5_pos should either be a h5py.Dataset or numpy array')
if h5_pos.shape[0] != h5_main.shape[0]:
raise ValueError('The size of h5_pos: {} does not match with h5_main: {}'.format(h5_pos.shape,
h5_main.shape))
if h5_spec is not None:
if not isinstance(h5_spec, (h5py.Dataset, np.ndarray, da.core.Array)):
raise TypeError('h5_spec should either be a h5py.Dataset or numpy array')
if h5_spec.shape[1] != h5_main.shape[1]:
raise ValueError('The size of h5_spec: {} does not match with h5_main: {}'.format(h5_spec.shape,
h5_main.shape))
pos_labs = np.array(['Positions'])
spec_labs = np.array(['Spectral_Step'])
if h5_pos is None:
"""
Get the Position datasets from the references if possible
"""
if isinstance(h5_main, h5py.Dataset):
try:
h5_pos = h5_main.file[h5_main.attrs['Position_Indices']]
ds_pos = h5_pos[()]
pos_labs = get_attr(h5_pos, 'labels')
except KeyError:
print('No position datasets found as attributes of {}'.format(h5_main.name))
if len(h5_main.shape) > 1:
ds_pos = np.arange(h5_main.shape[0], dtype=INDICES_DTYPE).reshape(-1, 1)
pos_labs = np.array(['Position Dimension {}'.format(ipos) for ipos in range(ds_pos.shape[1])])
else:
ds_pos = np.array(0, dtype=INDICES_DTYPE).reshape(-1, 1)
else:
ds_pos = np.arange(h5_main.shape[0], dtype=INDICES_DTYPE).reshape(-1, 1)
pos_labs = np.array(['Position Dimension {}'.format(ipos) for ipos in range(ds_pos.shape[1])])
elif isinstance(h5_pos, h5py.Dataset):
"""
Position Indices dataset was provided
"""
ds_pos = h5_pos[()]
pos_labs = get_attr(h5_pos, 'labels')
elif isinstance(h5_pos, (np.ndarray, da.core.Array)):
ds_pos = np.atleast_2d(h5_pos)
pos_labs = np.array(['Position Dimension {}'.format(ipos) for ipos in range(ds_pos.shape[1])])
else:
raise TypeError('Position Indices must be either h5py.Dataset or None')
if h5_spec is None:
"""
Get the Spectroscopic datasets from the references if possible
"""
if isinstance(h5_main, h5py.Dataset):
try:
h5_spec = h5_main.file[h5_main.attrs['Spectroscopic_Indices']]
ds_spec = h5_spec[()]
spec_labs = get_attr(h5_spec, 'labels')
except KeyError:
print('No spectroscopic datasets found as attributes of {}'.format(h5_main.name))
if len(h5_main.shape) > 1:
ds_spec = np.arange(h5_main.shape[1], dtype=INDICES_DTYPE).reshape([1, -1])
spec_labs = np.array(['Spectral Dimension {}'.format(ispec) for ispec in range(ds_spec.shape[0])])
else:
ds_spec = np.array(0, dtype=INDICES_DTYPE).reshape([1, 1])
else:
ds_spec = np.arange(h5_main.shape[1], dtype=INDICES_DTYPE).reshape([1, -1])
spec_labs = np.array(['Spectral Dimension {}'.format(ispec) for ispec in range(ds_spec.shape[0])])
elif isinstance(h5_spec, h5py.Dataset):
"""
Spectroscopic Indices dataset was provided
"""
ds_spec = h5_spec[()]
spec_labs = get_attr(h5_spec, 'labels')
elif isinstance(h5_spec, (np.ndarray, da.core.Array)):
ds_spec = h5_spec
spec_labs = np.array(['Spectral Dimension {}'.format(ispec) for ispec in range(ds_spec.shape[0])])
else:
raise TypeError('Spectroscopic Indices must be either h5py.Dataset or None')
'''
Sort the indices from fastest to slowest
'''
pos_sort = get_sort_order(np.transpose(ds_pos))
spec_sort = get_sort_order(ds_spec)
if verbose:
print('Position dimensions:', pos_labs)
print('Position sort order:', pos_sort)
print('Spectroscopic Dimensions:', spec_labs)
print('Spectroscopic sort order:', spec_sort)
'''
Get the size of each dimension in the sorted order
'''
pos_dims = get_dimensionality(np.transpose(ds_pos), pos_sort)
spec_dims = get_dimensionality(ds_spec, spec_sort)
if np.prod(pos_dims) != h5_main.shape[0]:
mesg = 'Product of position dimension sizes: {} = {} not matching ' \
'with size of first axis of main dataset: {}. One or more ' \
'dimensions are dependent dimensions and not marked as such' \
'.'.format(pos_dims, np.prod(pos_dims), h5_main.shape[0])
raise ValueError(mesg)
if np.prod(spec_dims) != h5_main.shape[1]:
mesg = 'Product of spectroscopic dimension sizes: {} = {} not matching ' \
'with size of second axis of main dataset: {}. One or more ' \
'dimensions are dependent dimensions and not marked as such' \
'.'.format(spec_dims, np.prod(spec_dims), h5_main.shape[1])
raise ValueError(mesg)
if verbose:
print('\nPosition dimensions (sort applied):', pos_labs[pos_sort])
print('Position dimensionality (sort applied):', pos_dims)
print('Spectroscopic dimensions (sort applied):', spec_labs[spec_sort])
print('Spectroscopic dimensionality (sort applied):', spec_dims)
if lazy:
ds_main = lazy_load_array(h5_main)
else:
ds_main = h5_main[()]
"""
Now we reshape the dataset based on those dimensions
numpy reshapes correctly when the dimensions are arranged from slowest to fastest.
Since the sort orders we have are from fastest to slowest, we need to reverse the orders
for both the position and spectroscopic dimensions
"""
if verbose:
print('Will attempt to reshape main dataset from:\n{} to {}'.format(ds_main.shape, pos_dims[::-1] + spec_dims[::-1]))
try:
ds_Nd = ds_main.reshape(pos_dims[::-1] + spec_dims[::-1])
except ValueError:
warn('Could not reshape dataset to full N-dimensional form. Attempting reshape based on position only.')
try:
ds_Nd = ds_main.reshape(pos_dims[::-1] + [-1])
except ValueError:
warn('Reshape by position only also failed. Will keep dataset in 2d form.')
if get_labels:
return ds_main, False, ['Position', 'Spectral Step']
else:
return ds_main, False
# No exception
else:
if get_labels:
return ds_Nd, 'Positions', ['Position'] + spec_labs
else:
return ds_Nd, 'Positions'
all_labels = np.hstack((pos_labs[pos_sort][::-1],
spec_labs[spec_sort][::-1]))
if verbose:
print('\nAfter reshaping, labels are', all_labels)
print('Data shape is', ds_Nd.shape)
"""
At this point, the data is arranged from slowest to fastest dimension in both pos and spec
"""
if sort_dims:
results = [ds_Nd, True]
if get_labels:
results.append(all_labels)
return results
if verbose:
print('\nGoing to put dimensions back in the same order as in the file:')
swap_axes = list()
# Compare the original order of the pos / spec labels with where these dimensions occur in the sorted labels
for lab in pos_labs:
swap_axes.append(np.argwhere(all_labels == lab).squeeze())
for lab in spec_labs:
swap_axes.append(np.argwhere(all_labels == lab).squeeze())
swap_axes = np.array(swap_axes)
if verbose:
print('Axes will permuted in this order:', swap_axes)
print('New labels ordering:', all_labels[swap_axes])
ds_Nd = ds_Nd.transpose(tuple(swap_axes))
results = [ds_Nd, True]
if verbose:
print('Dataset now of shape:', ds_Nd.shape)
if get_labels:
'''
Get the labels in the proper order
'''
results.append(all_labels[swap_axes])
return results
def reshape_from_n_dims(data_n_dim, h5_pos=None, h5_spec=None, verbose=False):
"""
Reshape the input 2D matrix to be N-dimensions based on the
position and spectroscopic datasets.
Parameters
----------
data_n_dim : numpy.array or dask.array.core.Array
N dimensional array arranged as [positions dimensions..., spectroscopic dimensions]
If h5_pos and h5_spec are not provided, this function will have to assume that the dimensions
are arranged as [positions slowest to fastest, spectroscopic slowest to fastest].
This restriction is removed if h5_pos and h5_spec are provided
h5_pos : HDF5 Dataset, numpy.array or dask.array.core.Array
Position indices corresponding to rows in the final 2d array
The dimensions should be arranged in terms of rate of change corresponding to data_n_dim.
In other words if data_n_dim had two position dimensions arranged as [pos_fast, pos_slow, spec_dim_1....],
h5_pos should be arranged as [pos_fast, pos_slow]
h5_spec : HDF5 Dataset, numpy. array or dask.array.core.Array
Spectroscopic indices corresponding to columns in the final 2d array
The dimensions should be arranged in terms of rate of change corresponding to data_n_dim.
In other words if data_n_dim had two spectral dimensions arranged as [pos_dim_1,..., spec_fast, spec_slow],
h5_spec should be arranged as [pos_slow, pos_fast]
verbose : bool, optional. Default = False
Whether or not to print log statements
Returns
-------
ds_2d : numpy.array
2 dimensional numpy array arranged as [positions, spectroscopic]
success : boolean or string
True if full reshape was successful
"Positions" if it was only possible to reshape by
the position dimensions
False if no reshape was possible
Notes
-----
If either `h5_pos` or `h5_spec` are not provided, the function will
assume the first dimension is position and the remaining are spectroscopic already
in order from fastest to slowest.
"""
if not isinstance(data_n_dim, (np.ndarray, da.core.Array)):
raise TypeError('data_n_dim is not a numpy or dask array')
if h5_spec is None and h5_pos is None:
raise ValueError('at least one of h5_pos or h5_spec must be specified for an attempt to reshape to 2D')
if data_n_dim.ndim < 2:
return data_n_dim, True
if h5_pos is None:
pass
elif isinstance(h5_pos, h5py.Dataset):
'''
Position Indices dataset was provided
'''
ds_pos = h5_pos[()]
elif isinstance(h5_pos, da.core.Array):
ds_pos = h5_pos.compute()
elif isinstance(h5_pos, np.ndarray):
ds_pos = h5_pos
else:
raise TypeError('Position Indices must be either h5py.Dataset or None')
if h5_spec is None:
pass
elif isinstance(h5_spec, h5py.Dataset):
'''
Spectroscopic Indices dataset was provided
'''
ds_spec = h5_spec[()]
elif isinstance(h5_spec, da.core.Array):
ds_spec = h5_spec.compute()
elif isinstance(h5_spec, np.ndarray):
ds_spec = h5_spec
else:
raise TypeError('Spectroscopic Indices must be either h5py.Dataset or None')
if h5_spec is None and h5_pos is not None:
if verbose:
print('Spectral indices not provided but position indices provided.\n'
'Building spectral indices assuming that dimensions are arranged as slow -> fast')
pos_dims = get_dimensionality(ds_pos, index_sort=get_sort_order(ds_pos))
if not np.all([x in data_n_dim.shape for x in pos_dims]):
raise ValueError('Dimension sizes in pos_dims: {} do not exist in data_n_dim shape: '
'{}'.format(pos_dims, data_n_dim.shape))
spec_dims = [col for col in list(data_n_dim.shape[len(pos_dims):])]
if verbose:
print('data has dimensions: {}. Provided position indices had dimensions of size: {}. Spectral dimensions '
'will built with dimensions: {}'.format(data_n_dim.shape, pos_dims, spec_dims))
ds_spec = make_indices_matrix(spec_dims, is_position=False)
elif h5_pos is None and h5_spec is not None:
if verbose:
print('Position indices not provided but spectral indices provided.\n'
'Building position indices assuming that dimensions are arranged as slow -> fast')
spec_dims = get_dimensionality(ds_spec, index_sort=get_sort_order(ds_spec))
if not np.all([x in data_n_dim.shape for x in spec_dims]):
raise ValueError('Dimension sizes in spec_dims: {} do not exist in data_n_dim shape: '
'{}'.format(spec_dims, data_n_dim.shape))
pos_dims = [col for col in list(data_n_dim.shape[:data_n_dim.ndim-len(spec_dims)])]
if verbose:
print('data has dimensions: {}. Spectroscopic position indices had dimensions of size: {}. Position '
'dimensions will built with dimensions: {}'.format(data_n_dim.shape, spec_dims, pos_dims))
ds_pos = make_indices_matrix(pos_dims, is_position=True)
elif h5_spec is not None and h5_pos is not None:
if ds_pos.shape[0] * ds_spec.shape[1] != np.product(data_n_dim.shape):
raise ValueError('The product ({}) of the number of positions ({}) and spectroscopic ({}) observations is '
'not equal to the product ({}) of the data shape ({})'
'.'.format(ds_pos.shape[0] * ds_spec.shape[1], ds_pos.shape[0], ds_spec.shape[1],
np.product(data_n_dim.shape), data_n_dim.shape))
if ds_pos.shape[1] + ds_spec.shape[0] != data_n_dim.ndim:
# This may mean that the dummy position or spectroscopic axes has been squeezed out!
# Dask does NOT allow singular dimensions apparently. So cannot do expand_dims. Handle later
if ds_pos.size == 1 or ds_spec.size == 1:
if verbose:
print('ALL Position dimensions squeezed: {}. ALL Spectroscopic dimensions squeezed: {}'
'.'.format(ds_pos.size == 1, ds_spec.size == 1))
else:
raise ValueError('The number of position ({}) and spectroscopic ({}) dimensions do not match with the '
'dimensionality of the N-dimensional dataset: {}'
'.'.format(ds_pos.shape[1], ds_spec.shape[0], data_n_dim.ndim))
'''
Sort the indices from fastest to slowest
'''
if ds_pos.size == 1:
# Position dimension squeezed out:
pos_sort = []
else:
pos_sort = get_sort_order(np.transpose(ds_pos))
if ds_spec.size == 1:
# Spectroscopic axis squeezed out:
spec_sort = []
else:
spec_sort = get_sort_order(ds_spec)
if h5_spec is None:
spec_sort = spec_sort[::-1]
if h5_pos is None:
pos_sort = pos_sort[::-1]
if verbose:
print('Position sort order: {}'.format(pos_sort))
print('Spectroscopic sort order: {}'.format(spec_sort))
'''
Now we transpose the axes associated with the spectroscopic dimensions
so that they are in the same order as in the index array
'''
swap_axes = np.uint16(np.append(pos_sort[::-1], spec_sort[::-1] + len(pos_sort)))
if verbose:
print('swap axes: {} to be applied to N dimensional data of shape {}'.format(swap_axes, data_n_dim.shape))
data_n_dim_2 = data_n_dim.transpose(tuple(swap_axes))
if verbose:
print('N dimensional data shape after axes swap: {}'.format(data_n_dim_2.shape))
'''
Now we reshape the dataset based on those dimensions
We must use the spectroscopic dimensions in reverse order
'''
try:
ds_2d = data_n_dim_2.reshape([ds_pos.shape[0], ds_spec.shape[1]])
except ValueError:
raise ValueError('Could not reshape dataset to full N-dimensional form')
return ds_2d, True
def get_dimensionality(ds_index, index_sort=None):
"""
Get the size of each index dimension in a specified sort order
Parameters
----------
ds_index : 2D HDF5 Dataset or numpy array
Row matrix of indices
index_sort : Iterable of unsigned integers (Optional)
Sort that can be applied to dimensionality.
For example - Order of rows sorted from fastest to slowest
Returns
-------
sorted_dims : list of unsigned integers
Dimensionality of each row in ds_index. If index_sort is supplied, it will be in the sorted order
"""
if isinstance(ds_index, da.core.Array):
ds_index = ds_index.compute()
if not isinstance(ds_index, (np.ndarray, h5py.Dataset)):
raise TypeError('ds_index should either be a numpy array or h5py.Dataset')
if ds_index.shape[0] > ds_index.shape[1]:
# must be spectroscopic like in shape (few rows, more cols)
ds_index = np.transpose(ds_index)
if index_sort is None:
index_sort = np.arange(ds_index.shape[0])
else:
if not contains_integers(index_sort, min_val=0):
raise ValueError('index_sort should contain integers > 0')
index_sort = np.array(index_sort)
if index_sort.ndim != 1:
raise ValueError('index_sort should be a 1D array')
if len(np.unique(index_sort)) > ds_index.shape[0]:
raise ValueError('length of index_sort ({}) should be smaller than number of dimensions in provided dataset'
' ({}'.format(len(np.unique(index_sort)), ds_index.shape[0]))
if set(np.arange(ds_index.shape[0])) != set(index_sort):
raise ValueError('Sort order of dimensions ({}) not matching with number of dimensions ({})'
''.format(index_sort, ds_index.shape[0]))
sorted_dims = [len(np.unique(row)) for row in np.array(ds_index, ndmin=2)[index_sort]]
return sorted_dims
def get_sort_order(ds_spec):
"""
Find how quickly the spectroscopic values are changing in each row
and the order of rows from fastest changing to slowest.
Parameters
----------
ds_spec : 2D HDF5 dataset or numpy array
Rows of indices to be sorted from fastest changing to slowest
Returns
-------
change_sort : List of unsigned integers
Order of rows sorted from fastest changing to slowest
"""
if isinstance(ds_spec, da.core.Array):
ds_spec = ds_spec.compute()
if not isinstance(ds_spec, (np.ndarray, h5py.Dataset)):
raise TypeError('ds_spec should either be a numpy array or h5py.Dataset')
if ds_spec.shape[0] > ds_spec.shape[1]:
# must be spectroscopic like in shape (few rows, more cols)
ds_spec = np.transpose(ds_spec)
change_count = [len(np.where([row[i] != row[i - 1] for i in range(len(row))])[0]) for row in ds_spec]
change_sort = np.argsort(change_count)[::-1]
return change_sort
def get_unit_values(ds_inds, ds_vals, dim_names=None, all_dim_names=None, is_spec=None, verbose=False):
"""
Gets the unit arrays of values that describe the spectroscopic dimensions
Parameters
----------
ds_inds : h5py.Dataset or numpy.ndarray
Spectroscopic or Position Indices dataset
ds_vals : h5py.Dataset or numpy.ndarray
Spectroscopic or Position Values dataset
dim_names : str, or list of str, Optional
Names of the dimensions of interest. Default = all
all_dim_names : list of str, Optional
Names of all the dimensions in these datasets. Use this if supplying numpy arrays instead of h5py.Dataset
objects for h5_inds, h5_vals since there is no other way of getting the dimension names.
is_spec : bool, optional
Whether or not the provided ancillary datasets are position or spectroscopic
The user is recommended to supply this parameter whenever it is known
By default, this function will attempt to recognize the answer based on the shape of the datasets.
verbose : bool, optional
Whether or not to print debugging statements. Default - off
Note - this function can be extended / modified for ancillary position dimensions as well
Returns
-------
unit_values : dict
Dictionary containing the unit array for each dimension. The name of the dimensions are the keys.
"""
if all_dim_names is None:
allowed_types = h5py.Dataset
else:
all_dim_names = validate_list_of_strings(all_dim_names, 'all_dim_names')
all_dim_names = np.array(all_dim_names)
allowed_types = (h5py.Dataset, np.ndarray)
for dset, dset_name in zip([ds_inds, ds_vals], ['ds_inds', 'ds_vals']):
if not isinstance(dset, allowed_types):
raise TypeError(dset_name + ' should be of type: {}'.format(allowed_types))
# For now, we will throw an error if even a single dimension is listed as an incomplete dimension:
if isinstance(ds_inds, h5py.Dataset):
if np.any(['incomplete_dimensions' in dset.attrs.keys() for dset in [ds_inds, ds_vals]]):
try:
incomp_dims_inds = get_attr(ds_inds, 'incomplete_dimensions')
except KeyError:
incomp_dims_inds = None
try:
incomp_dims_vals = get_attr(ds_vals, 'incomplete_dimensions')
except KeyError:
incomp_dims_vals = None
if incomp_dims_inds is None and incomp_dims_vals is not None:
incomp_dims = incomp_dims_vals
elif incomp_dims_inds is not None and incomp_dims_vals is None:
incomp_dims = incomp_dims_inds
else:
# ensure that both attributes are the same
if incomp_dims_vals != incomp_dims_inds:
raise ValueError('Provided indices ({}) and values ({}) datasets were marked with different values '
'for incomplete_datasets.'.format(incomp_dims_inds, incomp_dims_vals))
incomp_dims = incomp_dims_vals
all_dim_names = get_attr(ds_inds, 'labels')
raise ValueError('Among all dimensions: {}, These dimensions were marked as incomplete dimensions: {}'
'. You are recommended to find unit values manually'.format(all_dim_names, incomp_dims))
# Do we need to check that the provided inds and vals correspond to the same main dataset?
if ds_inds.shape != ds_vals.shape:
raise ValueError('h5_inds: {} and h5_vals: {} should have the same shapes'.format(ds_inds.shape, ds_vals.shape))
if all_dim_names is None:
all_dim_names = get_attr(ds_inds, 'labels')
if verbose:
print('All dimensions: {}'.format(all_dim_names))
# First load to memory
inds_mat = ds_inds[()]
vals_mat = ds_vals[()]
if is_spec is None:
# Attempt to recognize the type automatically
is_spec = False
if inds_mat.shape[0] < inds_mat.shape[1]:
is_spec = True
else:
if not isinstance(is_spec, bool):
raise TypeError('is_spec should be a boolean. Provided object is of type: {}'.format(type(is_spec)))
if verbose:
print(
'Ancillary matrices of shape: {}, hence determined to be Spectroscopic:{}'.format(inds_mat.shape, is_spec))
if not is_spec:
# Convert to spectral shape
inds_mat = np.transpose(inds_mat)
vals_mat = np.transpose(vals_mat)
if len(all_dim_names) != inds_mat.shape[0]:
raise ValueError('Length of dimension names list: {} not matching with shape of dataset: {}'
'.'.format(len(all_dim_names), inds_mat.shape[0]))
if dim_names is None:
dim_names = all_dim_names
if verbose:
print('Going to return unit values for all dimensions: {}'.format(all_dim_names))
else:
dim_names = validate_list_of_strings(dim_names, 'dim_names')
if verbose:
print('Checking to make sure that the target dimension names: {} exist in the datasets attributes: {}'
'.'.format(dim_names, all_dim_names))
# check to make sure that the dimension names exist in the datasets:
for dim_name in dim_names:
if dim_name not in all_dim_names:
raise KeyError('Dimension {} does not exist in the provided ancillary datasets'.format(dim_name))
unit_values = dict()
for dim_name in all_dim_names:
# Find the row in the spectroscopic indices that corresponds to the dimensions we want to slice:
if verbose:
print('Looking for dimension: {} in {}'.format(dim_name, dim_names))
desired_row_ind = np.where(all_dim_names == dim_name)[0][0]
inds_for_dim = inds_mat[desired_row_ind]
# Wherever this dimension goes to 0 - start of a new tile
starts = np.where(inds_for_dim == np.min(inds_for_dim))[0]
if starts[0] != 0:
raise ValueError('Spectroscopic Indices for dimension: "{}" not '
'starting with 0. Please fix this and try again'
'.'.format(dim_name))
# There may be repetitions in addition to tiling. Find how the the positions increase.
# 1 = repetition, > 1 = new tile
step_sizes = np.hstack(([1], np.diff(starts)))
# This array is of the same length as the full indices array
# We should expect only two values of step sizes for a regular dimension (tiles of the same size):
# 1 for same value repeating and a big jump in indices when the next tile starts
# If the repeats / tiles are of different lengths, then this is not a regular dimension.
# What does a Unit Values vector even mean in this case? Just raise an error for now
if np.where(np.unique(step_sizes) - 1)[0].size > 1:
raise ValueError('Non constant step sizes')
# Finding Start of a new tile
tile_starts = np.where(step_sizes > 1)[0]
# converting these indices to correct indices that can be mapped straight to
if len(tile_starts) < 1:
# Dimension(s) with no tiling at all
# Make it look as though the next tile starts at the end of the whole indices vector
tile_starts = np.array([0, len(inds_for_dim)])
else:
# Dimension with some form of repetition
tile_starts = np.hstack(([0], starts[tile_starts]))
# Verify that each tile is identical here
# Last tile will not be checked unless we add the length of the indices vector as the start of next tile
tile_starts = np.hstack((tile_starts, [len(inds_for_dim)]))
subsections = [inds_for_dim[tile_starts[ind]: tile_starts[ind + 1]] for ind in range(len(tile_starts) - 1)]
if np.max(np.diff(subsections, axis=0)) != 0:
# Should get unit values for ALL dimensions regardless of expectations to catch such scenarios.
raise ValueError('Values in each tile of dimension: {} are different'.format(dim_name))
# Now looking within the first tile:
subsection = inds_for_dim[tile_starts[0]:tile_starts[1]]
# remove all repetitions. ie - take indices only where jump == 1
step_inds = np.hstack(([0], np.where(np.hstack(([0], np.diff(subsection))))[0]))
# Finally, use these indices to get the values
if dim_name in dim_names:
# Only add this dimension to dictionary if requwested.
unit_values[dim_name] = vals_mat[desired_row_ind, step_inds]
return unit_values
def write_main_dataset(h5_parent_group, main_data, main_data_name, quantity, units, pos_dims, spec_dims,
main_dset_attrs=None, h5_pos_inds=None, h5_pos_vals=None, h5_spec_inds=None, h5_spec_vals=None,
aux_spec_prefix='Spectroscopic_', aux_pos_prefix='Position_', verbose=False,
slow_to_fast=False, **kwargs):
"""
Writes the provided data as a 'Main' dataset with all appropriate linking.
By default, the instructions for generating the ancillary datasets should be specified using the pos_dims and
spec_dims arguments as dictionary objects. Alternatively, if both the indices and values datasets are already
available for either/or the positions / spectroscopic, they can be specified using the keyword arguments. In this
case, fresh datasets will not be generated.
Parameters
----------
h5_parent_group : :class:`h5py.Group`
Parent group under which the datasets will be created
main_data : numpy.ndarray, dask.array.core.Array, list or tuple
2D matrix formatted as [position, spectral] or a list / tuple with the shape for an empty dataset.
If creating an empty dataset - the dtype must be specified via a kwarg.
main_data_name : String / Unicode
Name to give to the main dataset. This cannot contain the '-' character.
quantity : String / Unicode
Name of the physical quantity stored in the dataset. Example - 'Current'
units : String / Unicode
Name of units for the quantity stored in the dataset. Example - 'A' for amperes
pos_dims : Dimension or array-like of Dimension objects
Sequence of Dimension objects that provides all necessary instructions for constructing the indices and values
datasets
Object specifying the instructions necessary for building the Position indices and values datasets
spec_dims : Dimension or array-like of Dimension objects
Sequence of Dimension objects that provides all necessary instructions for constructing the indices and values
datasets
Object specifying the instructions necessary for building the Spectroscopic indices and values datasets
main_dset_attrs : dictionary, Optional
Dictionary of parameters that will be written to the main dataset. Do NOT include region references here.
h5_pos_inds : h5py.Dataset, Optional
Dataset that will be linked with the name "Position_Indices"
h5_pos_vals : h5py.Dataset, Optional
Dataset that will be linked with the name "Position_Values"
h5_spec_inds : h5py.Dataset, Optional
Dataset that will be linked with the name "Spectroscopic_Indices"
h5_spec_vals : h5py.Dataset, Optional
Dataset that will be linked with the name "Spectroscopic_Values"
aux_spec_prefix : str or unicode, Optional
Default prefix for Spectroscopic datasets. Default = "Spectroscopic"
aux_pos_prefix : str or unicode, Optional
Default prefix for Position datasets. Default = "Position"
verbose : bool, Optional, default=False
If set to true - prints debugging logs
slow_to_fast : bool, Optional. Default=False
Set to True if the dimensions are arranged from slowest varying to fastest varying.
Set to False otherwise.
kwargs will be passed onto the creation of the dataset. Please pass chunking, compression, dtype, and other
arguments this way
Returns
-------
h5_main : USIDataset
Reference to the main dataset
"""
def __check_anc_before_creation(aux_prefix, dim_type='pos'):
aux_prefix = validate_single_string_arg(aux_prefix, 'aux_' + dim_type + '_prefix')
if not aux_prefix.endswith('_'):
aux_prefix += '_'
if '-' in aux_prefix:
warn('aux_' + dim_type + ' should not contain the "-" character. Reformatted name from:{} to '
'{}'.format(aux_prefix, aux_prefix.replace('-', '_')))
aux_prefix = aux_prefix.replace('-', '_')
for dset_name in [aux_prefix + 'Indices', aux_prefix + 'Values']:
if dset_name in h5_parent_group.keys():
# TODO: What if the contained data was correct?
raise KeyError('Dataset named: ' + dset_name + ' already exists in group: '
'{}. Consider passing these datasets using kwargs (if they are correct) instead of providing the pos_dims and spec_dims arguments'.format(h5_parent_group.name))
return aux_prefix
def __ensure_anc_in_correct_file(h5_inds, h5_vals, prefix):
if h5_inds.file != h5_vals.file:
raise ValueError('Provided ' + prefix + ' datasets are present in different HDF5 files!')
if h5_inds.file != h5_parent_group.file:
# Need to copy over the anc datasets to the new group
if verbose:
print('Need to copy over ancillary datasets: {} and {} to '
'destination group: {} which is in a different HDF5 '
'file'.format(h5_inds, h5_vals, h5_parent_group))
ret_vals = [copy_dataset(x, h5_parent_group, verbose=verbose) for x in [h5_inds, h5_vals]]
else:
ret_vals = [h5_inds, h5_vals]
return tuple(ret_vals)
if not isinstance(h5_parent_group, (h5py.Group, h5py.File)):
raise TypeError('h5_parent_group should be a h5py.File or h5py.Group object')
if not is_editable_h5(h5_parent_group):
raise ValueError('The provided file is not editable')
if verbose:
print('h5 group and file OK')
quantity, units, main_data_name = validate_string_args([quantity, units, main_data_name],
['quantity', 'units', 'main_data_name'])
if verbose:
print('quantity, units, main_data_name all OK')
quantity = quantity.strip()
units = units.strip()
main_data_name = main_data_name.strip()
if '-' in main_data_name:
warn('main_data_name should not contain the "-" character. Reformatted name from:{} to '
'{}'.format(main_data_name, main_data_name.replace('-', '_')))
main_data_name = main_data_name.replace('-', '_')
if isinstance(main_data, (list, tuple)):
if not contains_integers(main_data, min_val=1):
raise ValueError('main_data if specified as a shape should be a list / tuple of integers >= 1')
if len(main_data) != 2:
raise ValueError('main_data if specified as a shape should contain 2 numbers')
if 'dtype' not in kwargs:
raise ValueError('dtype must be included as a kwarg when creating an empty dataset')
_ = validate_dtype(kwargs.get('dtype'))
main_shape = main_data
if verbose:
print('Selected empty dataset creation. OK so far')
elif isinstance(main_data, (np.ndarray, da.core.Array)):
if main_data.ndim != 2:
raise ValueError('main_data should be a 2D array')
main_shape = main_data.shape
if verbose:
print('Provided numpy or Dask array for main_data OK so far')
else:
raise TypeError('main_data should either be a numpy array or a tuple / list with the shape of the data')
if h5_pos_inds is not None and h5_pos_vals is not None:
# The provided datasets override fresh building instructions.
validate_anc_h5_dsets(h5_pos_inds, h5_pos_vals, main_shape, is_spectroscopic=False)
if verbose:
print('The shapes of the provided h5 position indices and values are OK')
h5_pos_inds, h5_pos_vals = __ensure_anc_in_correct_file(h5_pos_inds, h5_pos_vals, 'Position')
else:
aux_pos_prefix = __check_anc_before_creation(aux_pos_prefix, dim_type='pos')
pos_dims = validate_dimensions(pos_dims, dim_type='Position')
validate_dims_against_main(main_shape, pos_dims, is_spectroscopic=False)
if verbose:
print('Passed all pre-tests for creating position datasets')
h5_pos_inds, h5_pos_vals = write_ind_val_dsets(h5_parent_group, pos_dims, is_spectral=False, verbose=verbose,
slow_to_fast=slow_to_fast, base_name=aux_pos_prefix)
if verbose:
print('Created position datasets!')
if h5_spec_inds is not None and h5_spec_vals is not None:
# The provided datasets override fresh building instructions.
validate_anc_h5_dsets(h5_spec_inds, h5_spec_vals, main_shape, is_spectroscopic=True)
if verbose:
print('The shapes of the provided h5 position indices and values '
'are OK')
h5_spec_inds, h5_spec_vals = __ensure_anc_in_correct_file(h5_spec_inds, h5_spec_vals,
'Spectroscopic')
else:
aux_spec_prefix = __check_anc_before_creation(aux_spec_prefix, dim_type='spec')
spec_dims = validate_dimensions(spec_dims, dim_type='Spectroscopic')
validate_dims_against_main(main_shape, spec_dims, is_spectroscopic=True)
if verbose:
print('Passed all pre-tests for creating spectroscopic datasets')
h5_spec_inds, h5_spec_vals = write_ind_val_dsets(h5_parent_group, spec_dims, is_spectral=True, verbose=verbose,
slow_to_fast=slow_to_fast, base_name=aux_spec_prefix)
if verbose:
print('Created Spectroscopic datasets')
if h5_parent_group.file.driver == 'mpio':
if kwargs.pop('compression', None) is not None:
warn('This HDF5 file has been opened wth the "mpio" communicator. '
'mpi4py does not allow creation of compressed datasets. Compression kwarg has been removed')
if isinstance(main_data, np.ndarray):
# Case 1 - simple small dataset
h5_main = h5_parent_group.create_dataset(main_data_name, data=main_data, **kwargs)
if verbose:
print('Created main dataset with provided data')
elif isinstance(main_data, da.core.Array):
# Case 2 - Dask dataset
# step 0 - get rid of any automated dtype specification:
_ = kwargs.pop('dtype', None)
# step 1 - create the empty dataset:
h5_main = h5_parent_group.create_dataset(main_data_name, shape=main_data.shape, dtype=main_data.dtype,
**kwargs)
if verbose:
print('Created empty dataset: {} for writing Dask dataset: {}'.format(h5_main, main_data))
print('Dask array will be written to HDF5 dataset: "{}" in file: "{}"'.format(h5_main.name,
h5_main.file.filename))
# Step 2 - now ask Dask to dump data to disk
da.to_hdf5(h5_main.file.filename, {h5_main.name: main_data})
# main_data.to_hdf5(h5_main.file.filename, h5_main.name) # Does not work with python 2 for some reason
else:
# Case 3 - large empty dataset
h5_main = h5_parent_group.create_dataset(main_data_name, main_data, **kwargs)
if verbose:
print('Created empty dataset for Main')
write_simple_attrs(h5_main, {'quantity': quantity, 'units': units})
if verbose:
print('Wrote quantity and units attributes to main dataset')
if isinstance(main_dset_attrs, dict):
write_simple_attrs(h5_main, main_dset_attrs)
if verbose:
print('Wrote provided attributes to main dataset')
write_book_keeping_attrs(h5_main)
# make it main
link_as_main(h5_main, h5_pos_inds, h5_pos_vals, h5_spec_inds, h5_spec_vals)
if verbose:
print('Successfully linked datasets - dataset should be main now')
from ..usi_data import USIDataset
return USIDataset(h5_main)
def map_grid_to_cartesian(h5_main, grid_shape, mode='histogram', **kwargs):
"""
Map an incomplete measurement, such as a spiral scan, to a cartesian grid.
Parameters
----------
h5_main : :class:`pyUSID.USIDataset`
Dataset containing the sparse measurement
grid_shape : int or [int, int]
Shape of the output :class:`numpy.ndarray`.
mode : str, optional. Default = 'histogram'
Method used for building a cartesian grid.
Available methods = 'histogram', 'linear', 'nearest', 'cubic'
Use kwargs to pass onto each of the techniques
Note
----
UNDER DEVELOPMENT!
Currently only valid for 2 position dimensions
@author: Patrik Marschalik
Returns
-------
:class:`numpy.ndarray` but could be a h5py.Dataset or dask.array.core.Array object
"""
try:
from scipy.interpolate import griddata
except ImportError as expn:
griddata = None
warn('map_grid_to_cartesian() requires scipy')
raise expn
from ..usi_data import USIDataset
if not isinstance(h5_main, USIDataset):
raise TypeError('Provided object is not a pyUSID.USIDataset object')
if mode not in ['histogram', 'linear', 'nearest', 'cubic']:
raise ValueError('mode must be a string among["histogram", "cubic"]')
ds_main = h5_main[()].squeeze()
ds_pos_vals = h5_main.h5_pos_vals[()]
if ds_pos_vals.shape[1] != 2:
raise TypeError("Only working for 2 position dimensions.")
# Transform to row, col image format
rotation = np.array([[0, 1], [-1, 0]])
ds_pos_vals = np.dot(ds_pos_vals, rotation)
try:
grid_n = len(grid_shape)
except TypeError:
grid_n = 1
if grid_n != 1 and grid_n != 2:
raise ValueError("grid_shape must be of type int or [int, int].")
if grid_n == 1:
grid_shape = 2 * [grid_shape]
def interpolate(points, values, grid_shape, method):
grid_shape = list(map((1j).__mul__, grid_shape))
grid_x, grid_y = np.mgrid[
np.amin(points[:, 0]):np.amax(points[:, 0]):grid_shape[0],
np.amin(points[:, 1]):np.amax(points[:, 1]):grid_shape[1]
]
ndim_data = griddata(points, values, (grid_x, grid_y), method=method)
return ndim_data
if mode == "histogram":
histogram_weighted, _, _ = np.histogram2d(*ds_pos_vals.T, bins=grid_shape, weights=ds_main)
histogram, _, _ = np.histogram2d(*ds_pos_vals.T, bins=grid_shape)
cart_data = np.divide(histogram_weighted, histogram)
else:
cart_data = interpolate(ds_pos_vals, ds_main, grid_shape, method=mode)
return cart_data
def write_sidpy_dataset(si_dset, h5_parent_group, verbose=False,
**kwargs):
"""
Writes a sidpy.Dataset as a USID dataset in the provided HDF5 Group.
Please see notes about dimension types
Parameters
----------
si_dset: sidpy.Dataset
Dataset to be written to HDF5 in NSID format
h5_parent_group : class:`h5py.Group`
Parent group under which the datasets will be created
verbose : bool, Optional. Default = False
Whether or not to write logs to standard out
kwargs: dict
additional keyword arguments passed on to h5py when writing data
Returns
------
h5_main : USIDataset
Reference to the main dataset
Notes
-----
USID only has two dimension types - Position and Spectroscopic.
Consider changing the types of dimensions of all other dimensions to either
"SPATIAL" or "SPECTRAL".
"""
if not isinstance(si_dset, sid.Dataset):
raise TypeError('Data to write is not a sidpy dataset')
if not isinstance(h5_parent_group, (h5py.File, h5py.Group)):
raise TypeError('h5_parent_group is not a h5py.File or '
'h5py.Group object')
spatial_dims, spectral_dims, spatial_size, spectral_size = [], [], 1, 1
for dim_ind, dime in si_dset._axes.items():
if dime._dimension_type == sid.DimensionType.SPATIAL:
spatial_dims.append(Dimension(dime._name,
dime._units,
dime.values,
dime._quantity,
dime._dimension_type))
spatial_size *= np.size(dime.values)
else:
if not dime._dimension_type == sid.DimensionType.SPECTRAL:
warn('Will consider dimension: {} of type: {} as a '
'spectroscopic dimension'.format(dime._name,
dime._dimension_type))
spectral_dims.append(Dimension(dime._name,
dime._units,
dime.values,
dime._quantity,
dime._dimension_type))
spectral_size *= np.size(dime.values)
main_dataset = da.reshape(si_dset, [spatial_size, spectral_size])
# TODO : Consider writing this out as a separate group
main_dset_attr = {}
for attr_name in dir(si_dset):
attr_val = getattr(si_dset, attr_name)
if isinstance(attr_val, dict):
main_dset_attr.update(attr_val)
h5_main = write_main_dataset(h5_parent_group=h5_parent_group,
main_data=main_dataset,
main_data_name=si_dset.name,
quantity=si_dset.quantity,
units=si_dset.units,
pos_dims=spatial_dims,
spec_dims=spectral_dims,
main_dset_attrs=flatten_dict(main_dset_attr),
slow_to_fast=True,
verbose=verbose,
**kwargs)
return h5_main
| 45.303085 | 223 | 0.640834 |
b5558a699eab00ef65abc6b29a475f81abbddaa3 | 196 | kt | Kotlin | src/main/kotlin/com/github/rinacm/sayaka/common/message/error/TranslationException.kt | Rinacm/sayaka | f27998445fafc1cf0ee66fef2b8abc7a95efecca | [
"MIT"
] | 2 | 2020-09-29T03:08:17.000Z | 2020-09-30T22:01:05.000Z | src/main/kotlin/com/github/rinacm/sayaka/common/message/error/TranslationException.kt | Rinacm/sayaka | f27998445fafc1cf0ee66fef2b8abc7a95efecca | [
"MIT"
] | null | null | null | src/main/kotlin/com/github/rinacm/sayaka/common/message/error/TranslationException.kt | Rinacm/sayaka | f27998445fafc1cf0ee66fef2b8abc7a95efecca | [
"MIT"
] | null | null | null | package com.github.rinacm.sayaka.common.message.error
class TranslationException(cause: Exception) : PipelineException(cause) {
override val errorStage: ErrorStage = ErrorStage.TRANSLATION
}
| 32.666667 | 73 | 0.811224 |
fd93c05aa784c7ae38b086a7daf899940ccd7f93 | 139 | c | C | repository/linux/test393.c | ProgramRepair/SearchRepair | 10ce5c53afa0d287d52e821bc2abfad774b63d26 | [
"MIT"
] | 22 | 2016-02-03T21:49:53.000Z | 2021-12-21T19:18:13.000Z | repository/linux/test393.c | ProgramRepair/SearchRepair | 10ce5c53afa0d287d52e821bc2abfad774b63d26 | [
"MIT"
] | 3 | 2015-10-30T22:17:08.000Z | 2019-03-13T15:56:38.000Z | repository/linux/test393.c | ProgramRepair/SearchRepair | 10ce5c53afa0d287d52e821bc2abfad774b63d26 | [
"MIT"
] | 6 | 2015-11-12T16:57:02.000Z | 2019-08-07T10:27:11.000Z | void test(int error, int io, int BIO_UPTODATE){
if ( error ) clear_bit ( BIO_UPTODATE , io - > bi_flags ) ; } | 69.5 | 91 | 0.532374 |
0cc30cfdf180329d599ca631c45ea9d3d82bf57e | 81 | sql | SQL | resources/sql/autopatches/20140416.harbor.1.sql | Rob--W/phabricator | 8272f3f7fa92179931a2fc7ca33909492cfc644d | [
"Apache-2.0"
] | 8,840 | 2015-01-02T03:04:43.000Z | 2022-03-29T05:24:18.000Z | resources/sql/autopatches/20140416.harbor.1.sql | Rob--W/phabricator | 8272f3f7fa92179931a2fc7ca33909492cfc644d | [
"Apache-2.0"
] | 73 | 2015-01-06T11:05:32.000Z | 2021-12-02T17:50:10.000Z | resources/sql/autopatches/20140416.harbor.1.sql | Rob--W/phabricator | 8272f3f7fa92179931a2fc7ca33909492cfc644d | [
"Apache-2.0"
] | 1,335 | 2015-01-04T03:15:40.000Z | 2022-03-30T23:34:27.000Z | ALTER TABLE {$NAMESPACE}_harbormaster.harbormaster_buildable
DROP buildStatus;
| 27 | 60 | 0.851852 |
3578ae8799c98031c3d29c0ac27702a0c826de98 | 2,654 | swift | Swift | app/YARC/SwiftUI/SubRedditView/SubRedditView.swift | Tokko55v2/yarc | fcf33f2e6957b2cd0d2fb104686639f380ea3ab8 | [
"MIT"
] | 1 | 2021-02-25T21:50:42.000Z | 2021-02-25T21:50:42.000Z | app/YARC/SwiftUI/SubRedditView/SubRedditView.swift | Tokko55v2/YARC | 13cffe55ddb56c8785754e7ce86edb0cf5422a9d | [
"MIT"
] | 10 | 2021-02-06T22:25:48.000Z | 2021-05-15T14:03:19.000Z | app/YARC/SwiftUI/SubRedditView/SubRedditView.swift | Tokko55v2/yarc | fcf33f2e6957b2cd0d2fb104686639f380ea3ab8 | [
"MIT"
] | 1 | 2021-01-27T20:58:11.000Z | 2021-01-27T20:58:11.000Z | //
// SubRedditView.swift
// YARC
//
// Created by Michael Kroneder on 09/02/2021.
//
import SafariServices
import SwiftUI
struct SubRedditView: View {
@ObservedObject var viewModel: SubRedditViewModel
var body: some View {
ScrollView {
VStack {
HStack {
AsyncImageView(url: "",
placeholder: {
Text(R.string.localizable.isLoading_phrase())
})
.aspectRatio(contentMode: .fit)
Spacer()
}
.padding([.leading, .top], 10)
}
.frame(maxWidth: .infinity, alignment: .leading)
VStack(alignment: .leading) {
Text("displayNamePrefixed")
.font(.title3)
.padding(.bottom, 5)
.padding(.leading, 5)
.foregroundColor(Color.white)
Text("subscribers")
.font(.body)
.padding(.bottom, 5)
.padding(.leading, 5)
.foregroundColor(Color.gray)
Text("publicDescription")
.font(.footnote)
.padding(.leading, 5)
.foregroundColor(Color.white)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.bottom, 20)
Divider()
Spacer()
PostsView(viewModel: viewModel)
}
.onAppear {
viewModel.getPosts()
}
.modifier(LoadingModifier(isShowing: $viewModel.isLoading))
}
}
private struct ImageView: View {
@State var callSafari: Bool = false
var imageURL: String
var url: String
var body: some View {
Button(action: {
callSafari.toggle()
}, label: {
AsyncImageView(url: imageURL,
placeholder: {
Text(R.string.localizable.isLoading_phrase())
}).aspectRatio(contentMode: .fit)
}).sheet(isPresented: $callSafari) {
SafariView(url: URL(string: url)!)
}
}
}
struct SafariView: UIViewControllerRepresentable {
let url: URL
func makeUIViewController(context: UIViewControllerRepresentableContext<SafariView>) -> SFSafariViewController {
SFSafariViewController(url: url)
}
func updateUIViewController(_ uiViewController: SFSafariViewController, context: UIViewControllerRepresentableContext<SafariView>) {}
}
| 29.164835 | 137 | 0.508666 |
8137e91e33815f535f1891424b7aaf0cb94f3f2c | 193 | rs | Rust | chain-common/build.rs | DimensionDev/MaskWalletCore | b4525ab99ed2eb96553f5c2365b00848cee428be | [
"MIT"
] | 4 | 2021-07-16T02:09:05.000Z | 2022-03-09T03:52:17.000Z | chain-common/build.rs | DimensionDev/MaskWalletCore | b4525ab99ed2eb96553f5c2365b00848cee428be | [
"MIT"
] | 7 | 2021-06-07T12:05:42.000Z | 2022-03-19T12:26:50.000Z | chain-common/build.rs | DimensionDev/MaskWalletCore | b4525ab99ed2eb96553f5c2365b00848cee428be | [
"MIT"
] | 2 | 2021-06-07T07:58:31.000Z | 2022-02-07T01:25:27.000Z | use std::env;
extern crate prost_build;
fn main() {
env::set_var("OUT_DIR", "src/generated");
prost_build::compile_protos(&["proto/api.proto"], &["proto/sign/", "proto/"]).unwrap();
}
| 24.125 | 91 | 0.642487 |
7f24e65d30f8eb2174daf3b6a51b55bd6b9e1a99 | 237 | go | Go | analyzer/domain/testdata/analyzerproject/src/analyzerproject/domain/generator.go | keisuke-m123/gomoduler | b4098de8dc0a2c7864f9079854cdd79c075a2a15 | [
"MIT"
] | null | null | null | analyzer/domain/testdata/analyzerproject/src/analyzerproject/domain/generator.go | keisuke-m123/gomoduler | b4098de8dc0a2c7864f9079854cdd79c075a2a15 | [
"MIT"
] | null | null | null | analyzer/domain/testdata/analyzerproject/src/analyzerproject/domain/generator.go | keisuke-m123/gomoduler | b4098de8dc0a2c7864f9079854cdd79c075a2a15 | [
"MIT"
] | null | null | null | package domain
type (
OrderIDGenerator interface {
GenerateOrderID() OrderID
}
OrderNumberGenerator interface {
GenerateOrderNumber() OrderNumber
}
ShipmentCodeGenerator interface {
GenerateShipmentCode() ShipmentCode
}
)
| 14.8125 | 37 | 0.780591 |
6128b4620730d31f3ae9e66909e31713206ed627 | 2,547 | css | CSS | css/scrolling-nav.css | Waskalle/TPM-JMED | 83e1538847e9005d3b1d35315771d11509f3e9bf | [
"Apache-2.0"
] | null | null | null | css/scrolling-nav.css | Waskalle/TPM-JMED | 83e1538847e9005d3b1d35315771d11509f3e9bf | [
"Apache-2.0"
] | null | null | null | css/scrolling-nav.css | Waskalle/TPM-JMED | 83e1538847e9005d3b1d35315771d11509f3e9bf | [
"Apache-2.0"
] | null | null | null | /*!
* Start Bootstrap - Scrolling Nav HTML Template (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
body {
width: 100%;
height: 100%;
}
html {
width: 100%;
height: 100%;
}
@media(min-width:767px) {
.navbar {
padding: 20px 0;
-webkit-transition: background .5s ease-in-out,padding .5s ease-in-out;
-moz-transition: background .5s ease-in-out,padding .5s ease-in-out;
transition: background .5s ease-in-out,padding .5s ease-in-out;
}
.top-nav-collapse {
padding: 0;
}
}
/* Demo Sections - You can use these as guides or delete them - the scroller will work with any sort of height, fixed, undefined, or percentage based.
The padding is very important to make sure the scrollspy picks up the right area when scrolled to. Adjust the margin and padding of sections and children
of those sections to manage the look and feel of the site. */
@font-face {
font-family: titleBig;
src: url(fonts/SquadaOne-Regular.ttf);
}
@font-face {
font-family: subTit;
src: url(fonts/Orbitron-Bold.ttf);
}
.intro-section {
height: 100%;
padding-top: 150px;
text-align: center;
background: url(Images/TPM.png);
}
.about-section {
height: 100%;
padding-top: 150px;
text-align: center;
background: #0080FF;
}
.services-section {
height: 100%;
padding-top: 150px;
text-align: center;
background: #fff;
}
.contact-section {
height: 100%;
padding-top: 150px;
text-align: center;
background: #FF0040;
}
.subt
{
font-family: subTit;
font-size: 25px;
color: dimgray;
}
.title
{
font-family: titleBig;
font-size: 150px;
color: black;
}
.secTit
{
font-family: titleBig;
font-size: 40px;
color: black;
}
.mainmenu
{
font-family: titleBig;
font-size: 25px;
color: black;
}
.mbg
{
background-color: gainsboro;
}
p
{
font-family: subtit;
font-size: 20px;
color: white;
}
.enfasis
{
font-family: titleBig;
font-size: 25px;
color: dimgray;
}
.p1
{
font-family: subtit;
font-size: 20px;
color: black;
}
input[type='radio'] {
transform: scale(3);
}
input[type=checkbox]
{
width:20px; height:20px;
}
.tb
{
font-family: titleBig;
font-size: 20px;
color: black;
}
.logBg
{
background-color: #0080FF;
}
.lg{
margin-top: 50px;
box-shadow: 0 0 30px black;
padding:0 15px 0 15px;
} | 18.192857 | 154 | 0.625442 |
709607e08e6d78793fd7c2f07d353d07dc4d290e | 3,678 | h | C | ext/yiot-core/iotkit/sdk/modules/protocols/snap/include/virgil/iot/protocols/snap/cfg/cfg-structs.h | andr13/yiot-yocto-test | 1a0942318a2fb244c2a5a2ff086be7d0b7ea0deb | [
"BSD-2-Clause"
] | null | null | null | ext/yiot-core/iotkit/sdk/modules/protocols/snap/include/virgil/iot/protocols/snap/cfg/cfg-structs.h | andr13/yiot-yocto-test | 1a0942318a2fb244c2a5a2ff086be7d0b7ea0deb | [
"BSD-2-Clause"
] | null | null | null | ext/yiot-core/iotkit/sdk/modules/protocols/snap/include/virgil/iot/protocols/snap/cfg/cfg-structs.h | andr13/yiot-yocto-test | 1a0942318a2fb244c2a5a2ff086be7d0b7ea0deb | [
"BSD-2-Clause"
] | null | null | null | // Copyright (C) 2015-2020 Virgil Security, Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
#ifndef VS_SECURITY_SDK_SNAP_SERVICES_CFG_STRUCTS_H
#define VS_SECURITY_SDK_SNAP_SERVICES_CFG_STRUCTS_H
#include <virgil/iot/protocols/snap.h>
#include <virgil/iot/status_code/status_code.h>
#include <virgil/iot/trust_list/trust_list.h>
#include <virgil/iot/trust_list/tl_structs.h>
#include <virgil/iot/protocols/snap/snap-structs.h>
#ifdef __cplusplus
namespace VirgilIoTKit {
extern "C" {
#endif
#define VS_CFG_STR_MAX (64)
typedef struct {
uint8_t ssid[VS_CFG_STR_MAX];
uint8_t pass[VS_CFG_STR_MAX];
uint8_t account[VS_CFG_STR_MAX];
} vs_cfg_wifi_configuration_t;
#define VS_MESSENGER_CFG_VERSION (1) /**< Current version of messenger configuration */
#define VS_HOST_NAME_MAX_SZ (128) /**< Maximum size of string with host name */
#define VS_MESSENGER_CHANNEL_MAX_SZ (32) /**< Maximum size of Messenger's channel name */
#define VS_MESSENGER_CHANNEL_NUM_MAX (1) /**< Suported amount of channels */
/** Messenger's configuration */
typedef struct {
uint8_t version; /**< Version of #vs_messenger_config_t structure */
char enjabberd_host[VS_HOST_NAME_MAX_SZ]; /**< Enjabberd host */
uint16_t enjabberd_port; /**< Enjabberd port */
char messenger_base_url[VS_HOST_NAME_MAX_SZ]; /**< Virgil messenger service base URL */
} vs_cfg_messenger_config_t;
/** Messenger's channels to accept and connect to */
typedef struct {
uint8_t channels_num; /**< Amount of available XMPP channels */
char channel[VS_MESSENGER_CHANNEL_NUM_MAX][VS_MESSENGER_CHANNEL_MAX_SZ]; /**< Available XMPP channels */
} vs_cfg_messenger_channels_t;
/** User data configuration */
typedef struct {
uint8_t data_type; /**< User data type */
uint32_t data_sz; /**< User data size */
uint8_t data[]; /**< User data */
} vs_cfg_user_t;
#ifdef __cplusplus
} // extern "C"
} // namespace VirgilIoTKit
#endif
#endif // VS_SECURITY_SDK_SNAP_SERVICES_CFG_STRUCTS_H
| 40.866667 | 118 | 0.722132 |
cc0056787553d508dc21fc64d7c2be9ae5e3c23d | 1,865 | tab | SQL | CZ-9x9-CMR/4-16-ES-10STATES-70CMR04.tab | bidlom/Mendel2019-ES | 24632a8582e2b18bd8367ecb599c9d4b58e7d7da | [
"BSD-3-Clause"
] | null | null | null | CZ-9x9-CMR/4-16-ES-10STATES-70CMR04.tab | bidlom/Mendel2019-ES | 24632a8582e2b18bd8367ecb599c9d4b58e7d7da | [
"BSD-3-Clause"
] | null | null | null | CZ-9x9-CMR/4-16-ES-10STATES-70CMR04.tab | bidlom/Mendel2019-ES | 24632a8582e2b18bd8367ecb599c9d4b58e7d7da | [
"BSD-3-Clause"
] | null | null | null | 2 10
0 0 0 0 7 1
0 0 0 0 9 1
0 0 0 1 1 1
0 0 0 1 2 1
0 0 0 1 3 1
0 0 0 1 4 1
0 0 0 4 0 3
0 0 0 5 4 1
0 0 0 7 0 4
0 0 0 9 0 4
0 0 1 0 0 9
0 0 1 0 1 9
0 0 1 0 2 9
0 1 0 0 4 7
0 1 1 0 3 2
0 1 1 1 2 2
0 1 1 2 1 2
0 1 1 2 3 2
0 1 1 7 3 2
0 1 4 0 0 2
0 1 7 0 3 2
0 1 9 0 2 1
0 1 9 7 1 2
0 2 0 0 2 2
0 3 0 0 4 2
0 3 4 0 0 3
0 8 0 0 0 4
0 9 0 0 0 4
0 9 4 0 0 3
0 9 7 0 2 3
1 0 0 7 0 3
1 0 3 3 7 5
1 0 3 6 0 1
1 0 3 7 0 1
1 1 2 1 1 1
1 1 2 1 2 1
1 1 2 2 1 1
1 1 2 2 3 1
1 1 2 3 5 1
1 1 3 3 7 1
1 1 3 7 0 7
1 1 5 3 8 1
1 1 7 3 7 1
1 1 8 8 3 1
1 2 1 2 1 2
1 2 1 2 2 2
1 2 1 3 8 2
1 2 1 5 2 2
1 2 3 0 5 2
1 2 5 0 3 2
1 3 4 3 7 3
1 3 4 8 0 7
1 3 5 5 3 3
1 3 6 3 0 3
1 3 6 7 0 7
1 4 9 4 6 3
1 7 3 7 0 7
1 7 7 3 0 3
1 7 7 3 7 3
1 7 8 7 6 3
2 1 1 8 3 2
2 1 3 5 3 1
2 1 5 5 2 1
2 2 1 3 3 2
2 2 1 3 5 2
2 2 3 0 3 2
2 2 6 0 2 2
2 3 5 0 2 3
2 3 5 0 3 3
2 3 8 2 3 3
3 0 0 7 0 7
3 0 6 0 0 1
3 0 7 1 0 1
3 1 3 4 5 1
3 1 3 7 0 7
3 1 3 8 0 7
3 1 6 0 0 2
3 2 6 0 0 2
3 3 2 0 0 3
3 3 3 8 0 7
3 3 5 0 0 3
3 3 5 0 3 3
3 3 5 3 3 3
3 3 5 8 3 3
3 3 6 0 0 3
3 3 7 3 0 3
3 3 8 0 0 3
3 3 8 0 2 3
3 3 8 0 3 3
3 3 8 3 0 3
3 3 8 8 0 7
3 3 8 8 3 3
3 3 9 0 3 3
3 5 5 0 2 3
3 5 5 0 3 3
3 5 8 3 2 3
3 6 3 7 0 7
3 6 6 0 0 3
3 7 1 3 0 3
3 7 1 6 0 3
3 7 2 6 0 3
3 7 2 7 0 7
3 7 3 7 0 7
3 7 3 8 0 7
3 7 6 3 0 3
3 7 7 3 0 3
3 7 7 3 6 3
3 7 7 3 7 3
3 8 3 7 0 7
3 8 7 3 0 3
3 8 8 0 3 3
3 8 8 2 0 3
3 8 8 3 3 3
4 0 0 6 0 7
4 0 7 2 0 1
4 5 0 0 0 6
4 5 0 0 4 9
4 6 0 0 0 6
5 1 3 2 0 8
5 2 2 0 5 8
5 2 2 2 3 8
5 3 2 0 0 8
5 3 3 0 3 8
5 3 3 3 3 8
5 3 3 4 5 8
5 4 1 3 0 8
5 5 3 0 2 8
5 6 0 0 0 6
5 8 3 0 6 8
6 5 0 0 0 6
6 6 0 0 0 6
6 8 0 0 0 6
6 8 2 0 3 5
7 0 0 6 0 7
7 0 0 7 0 7
7 0 7 1 0 6
7 0 7 2 0 6
7 0 7 6 0 6
7 1 2 0 6 5
7 3 3 0 6 5
7 6 0 7 0 7
8 0 0 0 0 6
8 0 6 0 0 2
8 3 2 6 0 8
8 3 3 0 8 5
8 3 3 3 1 5
8 3 3 3 3 5
8 3 3 6 6 8
8 8 2 0 0 5
8 8 3 0 0 5
9 0 0 0 0 6
9 0 6 0 0 2
9 2 1 2 2 5
9 2 2 0 3 5
9 8 3 0 6 5
| 11.878981 | 11 | 0.500268 |
3e2e13635cdc1cf1deae32fc02eaa8532a1c0810 | 1,316 | kt | Kotlin | app/src/main/java/stan/androiddemo/project/petal/API/FollowAPI.kt | DuckDeck/AndroidDemo | 4d8d12c1f0ef821a252a2265ae46d7b8ff61729a | [
"MIT"
] | 128 | 2017-08-31T00:13:11.000Z | 2021-07-16T10:43:25.000Z | app/src/main/java/stan/androiddemo/project/petal/API/FollowAPI.kt | huaqianlee/AndroidDemo-Kotlin | c88e934f31566948cdb123613f4976684ca16cdf | [
"MIT"
] | 1 | 2017-09-11T10:12:52.000Z | 2017-09-25T04:38:44.000Z | app/src/main/java/stan/androiddemo/project/petal/API/FollowAPI.kt | huaqianlee/AndroidDemo-Kotlin | c88e934f31566948cdb123613f4976684ca16cdf | [
"MIT"
] | 44 | 2017-08-31T00:39:13.000Z | 2021-04-27T01:59:16.000Z | package stan.androiddemo.project.petal.API
import retrofit2.http.GET
import retrofit2.http.Header
import retrofit2.http.Query
import rx.Observable
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Module.Follow.FollowBoardListBean
import stan.androiddemo.project.petal.Module.Follow.FollowPinsBean
/**
* Created by stanhu on 17/8/2017.
*/
interface FollowAPI{
//https://api.huaban.com/following?limit=40
//我的关注图片 需要 报头 bearer getAccess_token
@GET("following")
fun httpsMyFollowingPinsRx(@Header(Config.Authorization) authorization: String,
@Query("limit") limit: Int): Observable<FollowPinsBean>
//https://api.huaban.com/following?limit=40&max=670619456
//我的关注图片的 后续滑动联网
@GET("following")
fun httpsMyFollowingPinsMaxRx(@Header(Config.Authorization) authorization: String,
@Query("max") max: Int, @Query("limit") limit: Int): Observable<FollowPinsBean>
//https://api.huaban.com/boards/following?page=1&per_page=20
//我的关注画板
@GET("boards/following")
fun httpsMyFollowingBoardRx(@Header(Config.Authorization) authorization: String,
@Query("page") page: Int, @Query("per_page") per_page: Int): Observable<FollowBoardListBean>
}
| 38.705882 | 124 | 0.707447 |
f034a4044c6267edb00bc843fa2e36be283bf707 | 744 | js | JavaScript | src/views/components/button/button.js | Metaburn/doocrate | 42dadee8a7e21c6df92d6220b8b9ce93f54ca5d0 | [
"MIT"
] | 20 | 2017-10-20T14:43:15.000Z | 2020-06-05T23:48:57.000Z | src/views/components/button/button.js | Metaburn/doocrate | 42dadee8a7e21c6df92d6220b8b9ce93f54ca5d0 | [
"MIT"
] | 65 | 2017-09-28T11:31:06.000Z | 2020-08-20T09:02:42.000Z | src/views/components/button/button.js | Metaburn/doocrate | 42dadee8a7e21c6df92d6220b8b9ce93f54ca5d0 | [
"MIT"
] | 8 | 2017-10-09T14:50:59.000Z | 2020-08-16T09:01:46.000Z | import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import './button.css';
const Button = ({
children,
className,
onClick,
type = 'button',
disabled,
dataTour,
}) => {
const cssClasses = classNames('button', className);
return (
<button
className={cssClasses}
onClick={onClick}
type={type}
disabled={disabled}
tabIndex={0}
data-tour={dataTour}
>
{children}
</button>
);
};
Button.propTypes = {
children: PropTypes.node,
dataTour: PropTypes.string,
className: PropTypes.string,
onClick: PropTypes.func,
disabled: PropTypes.bool,
type: PropTypes.oneOf(['button', 'reset', 'submit']),
};
export default Button;
| 18.6 | 55 | 0.645161 |
0b5a05b2b3ff689eda558db7efd7ba2b693f4a50 | 1,244 | py | Python | test.py | richisusiljacob/VideoTo360VR | 14c176cfbe90fd7cf113cbdd2d4edf447c001894 | [
"MIT"
] | 5 | 2021-08-06T11:26:56.000Z | 2022-03-17T09:06:07.000Z | test.py | richisusiljacob/VideoTo360VR | 14c176cfbe90fd7cf113cbdd2d4edf447c001894 | [
"MIT"
] | 8 | 2021-07-03T08:08:00.000Z | 2021-07-09T06:59:34.000Z | test.py | richisusiljacob/VideoTo360VR | 14c176cfbe90fd7cf113cbdd2d4edf447c001894 | [
"MIT"
] | 2 | 2021-07-02T09:19:09.000Z | 2021-07-04T13:34:30.000Z | from tkinter import *
import tkinter.ttk as ttk
from PIL import ImageTk,Image
""" root = Tk()
canvas = Canvas(root, width = 300, height = 300)
canvas.pack()
img = ImageTk.PhotoImage(Image.open("output/collage1/FinalCollage.jpg"))
canvas.create_image(0,0,anchor=NW, image=img)
root.mainloop() """
root = Tk()
root.title("Tab Widget")
tabControl = ttk.Notebook(root)
tab1 = ttk.Frame(tabControl)
tab2 = ttk.Frame(tabControl)
tabControl.add(tab1, text ='Tab 1')
tabControl.add(tab2, text ='Tab 2')
tabControl.pack(expand = 1, fill ="both")
ttk.Label(tab1,
text ="Welcome to \
GeeksForGeeks").grid(column = 0,
row = 0,
padx = 30,
pady = 30)
canvas = Canvas(tab1, width = 300, height = 300)
canvas.grid(column= 1, row =0)
img = ImageTk.PhotoImage(Image.open("output/collage1/FinalCollage.jpg"))
canvas.create_image(0,0,anchor=NW, image=img)
ttk.Label(tab2,
text ="Lets dive into the\
world of computers").grid(column = 0,
row = 0,
padx = 30,
pady = 30)
root.mainloop()
| 31.1 | 74 | 0.553859 |
606d9c958c400ae910ca8b8ecd6022c299df7577 | 7,780 | kt | Kotlin | tbs/src/main/java/com/hjhrq1991/library/tbs/BridgeWebViewClient.kt | angcyo/UICoreEx | eafede08fd1bb8811af2b35502bd5d5a17b3fdd6 | [
"MIT"
] | 2 | 2021-06-07T06:20:44.000Z | 2021-07-23T07:51:29.000Z | tbs/src/main/java/com/hjhrq1991/library/tbs/BridgeWebViewClient.kt | angcyo/UICoreEx | eafede08fd1bb8811af2b35502bd5d5a17b3fdd6 | [
"MIT"
] | null | null | null | tbs/src/main/java/com/hjhrq1991/library/tbs/BridgeWebViewClient.kt | angcyo/UICoreEx | eafede08fd1bb8811af2b35502bd5d5a17b3fdd6 | [
"MIT"
] | 2 | 2020-06-18T10:14:29.000Z | 2021-09-05T16:50:10.000Z | package com.hjhrq1991.library.tbs
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Message
import android.view.KeyEvent
import com.hjhrq1991.library.tbs.BridgeUtil.webViewLoadLocalJs
import com.tencent.smtt.export.external.interfaces.*
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
/**
* @author hjhrq1991 created at 8/22/16 14 41.
*/
class BridgeWebViewClient(val webView: TbsBridgeWebView) : WebViewClient() {
/**
* 是否重定向,避免web为渲染即跳转导致系统未调用onPageStarted就调用onPageFinished方法引起的js桥初始化失败
*/
private var isRedirected = false
/**
* onPageStarted连续调用次数,避免渲染立马跳转可能连续调用onPageStarted多次并且调用shouldOverrideUrlLoading后不调用onPageStarted引起的js桥未初始化问题
*/
private var onPageStartedCount = 0
private var bridgeWebViewClientListener: WebViewClient? = null
fun setBridgeWebViewClientListener(bridgeWebViewClientListener: WebViewClient?) {
this.bridgeWebViewClientListener = bridgeWebViewClientListener
}
fun removeListener() {
if (bridgeWebViewClientListener != null) {
bridgeWebViewClientListener = null
}
}
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
//modify:hjhrq1991,web为渲染即跳转导致系统未调用onPageStarted就调用onPageFinished方法引起的js桥初始化失败
var url = url
if (onPageStartedCount < 2) {
isRedirected = true
}
onPageStartedCount = 0
try {
url = URLDecoder.decode(url, "UTF-8")
} catch (e: UnsupportedEncodingException) {
e.printStackTrace()
}
return if (url?.startsWith(BridgeUtil.YY_RETURN_DATA) == true) { // 如果是返回数据
webView.handlerReturnData(url)
true
} else if (url?.startsWith(BridgeUtil.YY_OVERRIDE_SCHEMA) == true) { //
webView.flushMessageQueue()
true
} else {
bridgeWebViewClientListener?.shouldOverrideUrlLoading(view, url)
?: super.shouldOverrideUrlLoading(view, url)
}
}
override fun onPageStarted(
view: WebView?,
url: String?,
favicon: Bitmap?
) {
super.onPageStarted(view, url, favicon)
//modify:hjhrq1991,web为渲染即跳转导致系统未调用onPageStarted就调用onPageFinished方法引起的js桥初始化失败
isRedirected = false
onPageStartedCount++
bridgeWebViewClientListener?.onPageStarted(view, url, favicon)
}
override fun onPageFinished(view: WebView?, url: String?) {
if (view == null || url == null) {
return
}
//modify:hjhrq1991,web为渲染即跳转导致系统未调用onPageStarted就调用onPageFinished方法引起的js桥初始化失败
if (!url.contains("about:blank") && !isRedirected) {
webViewLoadLocalJs(
view,
BridgeConfig.toLoadJs,
BridgeConfig.defaultJs,
BridgeConfig.customJs
)
}
if (webView.startupMessage != null) {
for (m in webView.startupMessage!!) {
webView.dispatchMessage(m)
}
webView.startupMessage = null
}
bridgeWebViewClientListener?.onPageFinished(view, url)
}
override fun onReceivedError(
view: WebView?,
errorCode: Int,
description: String?,
failingUrl: String?
) {
bridgeWebViewClientListener?.onReceivedError(view, errorCode, description, failingUrl)
}
override fun onLoadResource(webView: WebView, s: String) {
bridgeWebViewClientListener?.onLoadResource(webView, s)
}
override fun onReceivedHttpError(
webView: WebView,
webResourceRequest: WebResourceRequest,
webResourceResponse: WebResourceResponse
) {
if (bridgeWebViewClientListener != null) {
bridgeWebViewClientListener!!.onReceivedHttpError(
webView,
webResourceRequest,
webResourceResponse
)
}
}
override fun shouldInterceptRequest(webView: WebView?, s: String?): WebResourceResponse? {
return bridgeWebViewClientListener?.shouldInterceptRequest(webView, s)
?: super.shouldInterceptRequest(webView, s)
}
override fun shouldInterceptRequest(
webView: WebView?,
webResourceRequest: WebResourceRequest?
): WebResourceResponse? {
return if (bridgeWebViewClientListener != null) {
bridgeWebViewClientListener!!.shouldInterceptRequest(webView, webResourceRequest)
} else {
super.shouldInterceptRequest(webView, webResourceRequest)
}
}
override fun shouldInterceptRequest(
webView: WebView?,
webResourceRequest: WebResourceRequest?,
bundle: Bundle?
): WebResourceResponse? {
return if (bridgeWebViewClientListener != null) {
bridgeWebViewClientListener!!.shouldInterceptRequest(
webView,
webResourceRequest,
bundle
)
} else {
super.shouldInterceptRequest(webView, webResourceRequest, bundle)
}
}
override fun doUpdateVisitedHistory(webView: WebView?, s: String?, b: Boolean) {
if (bridgeWebViewClientListener != null) {
bridgeWebViewClientListener!!.doUpdateVisitedHistory(webView, s, b)
}
}
override fun onFormResubmission(webView: WebView?, message: Message?, message1: Message?) {
bridgeWebViewClientListener?.onFormResubmission(webView, message, message1)
?: super.onFormResubmission(webView, message, message1)
}
override fun onReceivedHttpAuthRequest(
webView: WebView?,
httpAuthHandler: HttpAuthHandler?,
s: String?,
s1: String?
) {
bridgeWebViewClientListener?.onReceivedHttpAuthRequest(
webView,
httpAuthHandler,
s,
s1
) ?: super.onReceivedHttpAuthRequest(webView, httpAuthHandler, s, s1)
}
override fun onReceivedSslError(
webView: WebView?,
sslErrorHandler: SslErrorHandler?,
sslError: SslError?
) {
bridgeWebViewClientListener?.onReceivedSslError(webView, sslErrorHandler, sslError)
?: super.onReceivedSslError(webView, sslErrorHandler, sslError)
}
override fun onReceivedClientCertRequest(
webView: WebView,
clientCertRequest: ClientCertRequest
) {
bridgeWebViewClientListener?.onReceivedClientCertRequest(
webView,
clientCertRequest
) ?: super.onReceivedClientCertRequest(webView, clientCertRequest)
}
override fun onScaleChanged(webView: WebView, v: Float, v1: Float) {
bridgeWebViewClientListener?.onScaleChanged(webView, v, v1)
}
override fun onUnhandledKeyEvent(webView: WebView, keyEvent: KeyEvent) {
bridgeWebViewClientListener?.onUnhandledKeyEvent(webView, keyEvent)
}
override fun shouldOverrideKeyEvent(webView: WebView, keyEvent: KeyEvent): Boolean {
return bridgeWebViewClientListener?.shouldOverrideKeyEvent(webView, keyEvent)
?: super.shouldOverrideKeyEvent(webView, keyEvent)
}
override fun onTooManyRedirects(webView: WebView, message: Message, message1: Message) {
bridgeWebViewClientListener?.onTooManyRedirects(webView, message, message1)
}
override fun onReceivedLoginRequest(webView: WebView, s: String, s1: String, s2: String) {
bridgeWebViewClientListener?.onReceivedLoginRequest(webView, s, s1, s2)
}
override fun onDetectedBlankScreen(s: String, i: Int) {
bridgeWebViewClientListener?.onDetectedBlankScreen(s, i)
}
} | 34.273128 | 113 | 0.661825 |
f574b17d1c952795d3436541106b29e034e6d19d | 2,484 | rs | Rust | src/test/instruction_tests/instr_cvtsd2ss.rs | ftilde/rust-x86asm | f6584b8cfe8e75d978bf7b83a67c69444fd3f161 | [
"MIT"
] | null | null | null | src/test/instruction_tests/instr_cvtsd2ss.rs | ftilde/rust-x86asm | f6584b8cfe8e75d978bf7b83a67c69444fd3f161 | [
"MIT"
] | null | null | null | src/test/instruction_tests/instr_cvtsd2ss.rs | ftilde/rust-x86asm | f6584b8cfe8e75d978bf7b83a67c69444fd3f161 | [
"MIT"
] | null | null | null | use instruction_def::*;
use test::run_test;
use Operand::*;
use Reg::*;
use RegScale::*;
use RegType::*;
use {BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
#[test]
fn cvtsd2ss_1() {
run_test(
&Instruction {
mnemonic: Mnemonic::CVTSD2SS,
operand1: Some(Direct(XMM3)),
operand2: Some(Direct(XMM0)),
operand3: None,
operand4: None,
lock: false,
rounding_mode: None,
merge_mode: None,
sae: false,
mask: None,
broadcast: None,
},
&[242, 15, 90, 216],
OperandSize::Dword,
)
}
#[test]
fn cvtsd2ss_2() {
run_test(
&Instruction {
mnemonic: Mnemonic::CVTSD2SS,
operand1: Some(Direct(XMM3)),
operand2: Some(IndirectScaledDisplaced(
EDI,
Four,
2123315284,
Some(OperandSize::Qword),
None,
)),
operand3: None,
operand4: None,
lock: false,
rounding_mode: None,
merge_mode: None,
sae: false,
mask: None,
broadcast: None,
},
&[242, 15, 90, 28, 189, 84, 56, 143, 126],
OperandSize::Dword,
)
}
#[test]
fn cvtsd2ss_3() {
run_test(
&Instruction {
mnemonic: Mnemonic::CVTSD2SS,
operand1: Some(Direct(XMM0)),
operand2: Some(Direct(XMM2)),
operand3: None,
operand4: None,
lock: false,
rounding_mode: None,
merge_mode: None,
sae: false,
mask: None,
broadcast: None,
},
&[242, 15, 90, 194],
OperandSize::Qword,
)
}
#[test]
fn cvtsd2ss_4() {
run_test(
&Instruction {
mnemonic: Mnemonic::CVTSD2SS,
operand1: Some(Direct(XMM2)),
operand2: Some(IndirectDisplaced(
RBX,
1833285246,
Some(OperandSize::Qword),
None,
)),
operand3: None,
operand4: None,
lock: false,
rounding_mode: None,
merge_mode: None,
sae: false,
mask: None,
broadcast: None,
},
&[242, 15, 90, 147, 126, 182, 69, 109],
OperandSize::Qword,
)
}
| 24.116505 | 95 | 0.465378 |
7c943ad6482de1cb87596eab0a46b4b0d669bea5 | 3,738 | rs | Rust | src/main.rs | RottenFishbone/wpm | 8f5668fef0bff4be15ad19606ce68b728823dbaa | [
"MIT"
] | null | null | null | src/main.rs | RottenFishbone/wpm | 8f5668fef0bff4be15ad19606ce68b728823dbaa | [
"MIT"
] | 2 | 2022-01-18T23:57:03.000Z | 2022-03-02T02:21:41.000Z | src/main.rs | RottenFishbone/wpm | 8f5668fef0bff4be15ad19606ce68b728823dbaa | [
"MIT"
] | null | null | null | #![allow(dead_code)]
#![allow(unused_imports)]
mod app;
use app::{UIEvent, Controller};
use std::{
error::Error,
io::{ Write, stdout },
panic::{self, PanicInfo},
sync::mpsc::Sender,
thread,
time:: { Duration, SystemTime },
};
use crossterm::{
event::{ self, DisableMouseCapture, KeyModifiers,
EnableMouseCapture, Event, KeyCode },
terminal::{ EnterAlternateScreen, LeaveAlternateScreen,
enable_raw_mode, disable_raw_mode},
execute,
};
use tui::{Terminal, backend::CrosstermBackend};
type Result<T> = std::result::Result<T, UIError>;
type CrossTerminal = Terminal<CrosstermBackend<std::io::Stdout>>;
#[derive(Debug)]
enum UIError {}
fn main() {
panic::set_hook(Box::new(|info|{
panic_hook(info);
}));
enable_raw_mode().unwrap();
let mut stdout = stdout();
execute!(stdout, EnterAlternateScreen, EnableMouseCapture).unwrap();
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend).unwrap();
// Spawn a thread to handle UI events
let (event_tx, event_rx) = std::sync::mpsc::channel::<UIEvent>();
spawn_event_loop(event_tx, 250).unwrap();
// Main loop
let (mut controller, exit_rx) = Controller::new();
loop {
terminal.draw(|f| app::view::render(f, &controller.model)).unwrap();
// Blocking read on events, this causes a redraw on new UIEvents ONLY
if let UIEvent::Input(key_ev) = event_rx.recv().unwrap() {
// Handle <Ctrl+C>
if let KeyModifiers::CONTROL = key_ev.modifiers {
if key_ev.code == KeyCode::Char('c') { break; }
}
controller.handle_key_event(key_ev);
} else {
controller.update();
}
// Non-blocking read on exit signals
match exit_rx.try_recv() {
Ok(_) | Err(std::sync::mpsc::TryRecvError::Disconnected) => {
break;
},
_=> {}
}
}
kill_terminal();
}
/// Spawn a thread that hooks into user events as well as emits a tick event
/// at a given interval. In the event that the Reciever is dropped, the thread
/// will close itself, effectively acting as a kill command.
fn spawn_event_loop(event_tx: Sender<UIEvent>, tick_rate: u64) -> Result<()> {
thread::spawn(move || {
// Declare tick_rate as a Duration
let mut last_tick = SystemTime::now();
let tick_rate = Duration::from_millis(tick_rate);
loop {
let elapsed = last_tick.elapsed().unwrap();
// Poll for new events
if event::poll(tick_rate).unwrap() {
// Check for key events
if let Event::Key(key) = event::read().unwrap() {
// Send the key event through the channel, closing
// the thread on error
if let Err(_) = event_tx.send(UIEvent::Input(key)) {
break;
}
}
}
if elapsed >= tick_rate {
// Send the tick event, closing thread on error
if let Err(_) = event_tx.send(UIEvent::Tick) { break; }
last_tick = SystemTime::now();
}
}
});
Ok(())
}
/// Revert the terminal session to a normal, usable, state.
fn kill_terminal(){
execute!(stdout(),
LeaveAlternateScreen,
DisableMouseCapture).unwrap();
disable_raw_mode().unwrap();
}
/// Provides a hook that allows the program to return the terminal
/// to a usable state before exiting.
fn panic_hook(info: &PanicInfo<'_>) {
kill_terminal();
eprintln!("Caught panic hook: {:?}", info);
}
| 30.145161 | 78 | 0.578384 |
7231f7c389f42f1a47be6e4ac6ff875fcbbc0d98 | 16,601 | rs | Rust | qvisor/src/runc/cmd/exec.rs | abel-von/Quark | 7bbba67ee1105e3b7df751a278cbad9b2af666a1 | [
"Apache-2.0"
] | null | null | null | qvisor/src/runc/cmd/exec.rs | abel-von/Quark | 7bbba67ee1105e3b7df751a278cbad9b2af666a1 | [
"Apache-2.0"
] | null | null | null | qvisor/src/runc/cmd/exec.rs | abel-von/Quark | 7bbba67ee1105e3b7df751a278cbad9b2af666a1 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use clap::{App, AppSettings, SubCommand, ArgMatches, Arg};
use alloc::string::String;
use alloc::vec::Vec;
use alloc::collections::btree_map::BTreeMap;
use tempfile::Builder;
use std::fs::File;
use std::path::Path;
use std::io::prelude::*;
use std::{thread, time};
use std::os::unix::io::FromRawFd;
use std::os::unix::io::AsRawFd;
use std::process::{Stdio};
use super::super::super::qlib::common::*;
use super::super::super::qlib::auth::id::*;
use super::super::super::qlib::auth::cap_set::*;
use super::super::super::qlib::linux::time::*;
use super::super::cmd::config::*;
use super::super::oci::*;
use super::super::specutils::specutils::*;
use super::super::oci::serialize::*;
use super::super::container::container::*;
use super::command::*;
use super::super::super::console::pty::*;
use super::super::super::console::unix_socket::*;
#[derive(Default, Debug)]
pub struct User {
kuid: KUID,
kgid: KGID,
}
#[derive(Default, Debug)]
pub struct ExecCmd {
pub id: String,
pub cwd: String,
pub user: String,
pub envv: Vec<String>,
pub extraKGIDs: Vec<String>,
pub caps: Vec<String>,
pub detach: bool,
pub processPath: String,
pub pid: String,
pub internalPidFile: String,
pub consoleSocket: String,
pub argv: Vec<String>,
pub clearStatus: bool,
pub terminal: bool,
}
impl ExecCmd {
pub fn Init(cmd_matches: &ArgMatches) -> Result<Self> {
let ret = Self {
id: cmd_matches.value_of("id").unwrap().to_string(),
cwd: cmd_matches.value_of("cwd").unwrap().to_string(),
user: cmd_matches.value_of("user").unwrap().to_string(),
envv: match cmd_matches.values_of("env") {
None => Vec::new(),
Some(iter) => iter.map(|s| s.to_string()).collect(),
},
extraKGIDs: match cmd_matches.values_of("additional-gids") {
None => Vec::new(),
Some(iter) => iter.map(|s| s.to_string()).collect(),
},
caps: match cmd_matches.values_of("cap") {
None => Vec::new(),
Some(iter) => iter.map(|s| s.to_string()).collect(),
},
detach: cmd_matches.is_present("detach"),
processPath: cmd_matches.value_of("process").unwrap().to_string(),
pid: cmd_matches.value_of("p").unwrap().to_string(),
internalPidFile: cmd_matches.value_of("internal-pid-file").unwrap().to_string(),
consoleSocket: cmd_matches.value_of("console-socket").unwrap().to_string(),
argv: match cmd_matches.values_of("command") {
None => Vec::new(),
Some(iter) => iter.map(|s| s.to_string()).collect(),
},
clearStatus: cmd_matches.value_of("clear-status").unwrap() == "true",
terminal: cmd_matches.is_present("terminal"),
};
if ret.processPath.len() == 0 && ret.argv.len() == 0 {
println!("{}", cmd_matches.usage());
return Err(Error::Common(format!("either process or command is required")))
}
return Ok(ret)
}
pub fn SubCommand<'a, 'b>(common: &CommonArgs<'a, 'b>) -> App<'a, 'b> {
return SubCommand::with_name("exec")
.setting(AppSettings::ColoredHelp)
.arg(&common.id_arg)
.arg(
Arg::with_name("cwd")
.help("current working directory")
.default_value("")
.takes_value(true)
.long("cwd"),
)
.arg(
Arg::with_name("env")
.help("set environment variables (e.g. '--env PATH=/bin --env TERM=xterm')")
.takes_value(true)
.multiple(true)
.long("env")
.short("e"),
)
.arg(
Arg::with_name("terminal")
.help("allocate a pseudo-TTY")
.long("tty")
.short("t"),
)
.arg(
Arg::with_name("user")
.help("UID (format: <uid>[:<gid>])")
.takes_value(true)
.default_value("")
.long("user")
.short("u"),
)
.arg(
Arg::with_name("additional-gids")
.help("additional gids")
.takes_value(true)
.multiple(true)
.long("additional-gids")
.short("g"),
)
.arg(
Arg::with_name("cap")
.help("add a capability to the bounding set for the process")
.takes_value(true)
.multiple(true)
.long("cap"),
)
.arg(&common.detach_arg)
.arg(
Arg::with_name("process")
.help("path to the process.json")
.default_value("")
.takes_value(true)
.long("process")
.short("p"),
)
.arg(
Arg::with_name("p")
.takes_value(true)
.default_value("")
.long("pid-file")
.help("specify the file to write the container pid to"),
)
.arg(
Arg::with_name("internal-pid-file")
.takes_value(true)
.default_value("")
.long("internal-pid-file")
.help("filename that the container-internal pid will be written to"),
)
.arg(&common.consoleSocket_arg)
.arg(
Arg::with_name("clear-status")
.takes_value(true)
.default_value("true")
.long("clear-status")
.help("clear the status of the exec'd process upon completion"),
)
.setting(AppSettings::TrailingVarArg)
.arg(
Arg::with_name("command")
.multiple(true),
)
.about("Run a container") ;
}
pub fn ArgsFromCLI(&mut self) -> Result<ExecArgs> {
let mut extraKGIDs = Vec::new();
for g in &self.extraKGIDs {
let kgid = match g.parse::<u32>() {
Err(e) => panic!("parsing gid: {} fail, err is {:?}", g, e),
Ok(id) => id,
};
extraKGIDs.push(KGID(kgid));
};
//todo: handle capacities
let caps = TaskCaps::default();
let mut argv = Vec::new();
argv.append(&mut self.argv);
let mut envv = Vec::new();
envv.append(&mut self.envv);
let ids : Vec<&str> = self.user.split(':').collect();
let uid = match ids[0].parse::<u32>() {
Err(e) => panic!("parsing uid: {} fail, err is {:?}", ids[1], e),
Ok(id) => id,
};
let gid = if ids.len() > 2 {
panic!("user's format should be <uid>[:<gid>]");
} else if ids.len() == 2 {
match ids[1].parse::<u32>() {
Err(e) => panic!("parsing gid: {} fail, err is {:?}", ids[1], e),
Ok(id) => id,
}
} else {
0
};
if self.detach && self.terminal && self.consoleSocket.len() == 0 {
return Err(Error::Common("cannot allocate tty if runc will detach without setting console socket".to_string()));
}
if (!self.detach || !self.terminal) && self.consoleSocket.len() > 0 {
return Err(Error::Common("annot use console socket if runc will not detach or allocate tty".to_string()));
}
return Ok(ExecArgs {
Argv: argv,
Envv: envv,
Root: "".to_string(),
WorkDir: self.cwd.to_string(),
KUID: KUID(uid),
KGID: KGID(gid),
ExtraKGIDs: extraKGIDs,
Capabilities: caps,
Terminal: self.terminal,
Detach: self.detach,
ContainerID: self.id.to_string(),
ConsoleSocket: self.consoleSocket.to_string(),
ExecId: "".to_string(),
Fds: Vec::new(),
})
}
pub fn ArgsFromProcess(&self) -> Result<ExecArgs> {
let mut process : Process = deserialize(&self.processPath)
.map_err(|e| Error::Common(format!("deserialize process with error {:?}", e)))?;
//todo: handle caps
let caps = TaskCaps::default();
let mut extraKGIDs : Vec<KGID> = Vec::with_capacity(process.user.additional_gids.len());
extraKGIDs.append(&mut process.user.additional_gids.iter().map(|id| KGID(*id)).collect());
let mut argv = Vec::new();
argv.append(&mut process.args);
let mut envv = Vec::new();
envv.append(&mut process.env);
return Ok(ExecArgs {
Argv: argv,
Envv: envv,
Root: "".to_string(),
WorkDir: process.cwd.to_string(),
KUID: KUID(process.user.uid),
KGID: KGID(process.user.gid),
ExtraKGIDs: extraKGIDs,
Capabilities: caps,
Terminal: process.terminal,
ContainerID: self.id.to_string(),
Detach: self.detach,
ConsoleSocket: self.consoleSocket.to_string(),
ExecId: "".to_string(),
Fds: Vec::new(),
})
}
pub fn ParseArgs(&mut self) -> Result<ExecArgs> {
if self.processPath.len() == 0 {
return self.ArgsFromCLI();
} else {
return self.ArgsFromProcess();
}
}
pub fn Run(&mut self, gCfg: &GlobalConfig) -> Result<()> {
info!("Container:: Exec ....");
if self.detach {
let ret = self.ExecAndWait(gCfg);
error!("exec return .....");
return ret;
}
if !self.clearStatus {
let sid = unsafe {
//signal (SIGHUP, SIG_IGN);
libc::setsid()
};
if sid < 0 {
panic!("Exec process setsid fail");
}
}
let mut execArgs = self.ParseArgs()?;
let mut container = Container::Load(&gCfg.RootDir, &self.id)?;
if execArgs.WorkDir.len() == 0 {
execArgs.WorkDir = container.Spec.process.cwd.to_string();
}
if execArgs.Envv.len() == 0 {
execArgs.Envv = ResolveEnvs(&[&container.Spec.process.env, &self.envv])?;
}
//todo: handle caps
let _pid = container.Execute(execArgs, self)?;
return Ok(())
}
pub fn ExecAndWait(&self, gCfg: &GlobalConfig) -> Result<()> {
let mut cmd = std::process::Command::new(&ReadLink(EXE_PATH)?);
cmd.arg("--root");
cmd.arg(&gCfg.RootDir);
cmd.arg("--log");
cmd.arg(&gCfg.DebugLog);
cmd.arg("exec");
cmd.arg(&self.id);
if self.cwd.len() > 0 {
cmd.arg("--cwd");
cmd.arg(&self.cwd);
}
if self.user.len() > 0{
cmd.arg("--user");
cmd.arg(&self.user);
}
if self.envv.len() > 0 {
cmd.arg("--env");
for e in &self.envv {
cmd.arg(e);
}
}
if self.terminal {
cmd.arg("--tty");
}
if self.extraKGIDs.len() > 0 {
cmd.arg("--additional-gids");
for g in &self.extraKGIDs {
cmd.arg(g);
}
}
if self.caps.len() > 0 {
cmd.arg("--cap");
for cap in &self.caps {
cmd.arg(cap);
}
}
if self.detach {
cmd.arg("--clear-status");
cmd.arg("false");
}
if self.processPath.len() > 0 {
cmd.arg("--process");
cmd.arg(&self.processPath);
}
// The command needs to write a pid file so that execAndWait can tell
// when it has started. If no pid-file was provided, we should use a
// filename in a temp directory.
let mut pidFile = self.pid.to_string();
cmd.arg("--pid-file");
if pidFile.len() == 0{
let tmpDir = Builder::new().prefix("exec-pid-").tempdir()
.expect("create temp folder exec-pid- fail ");
pidFile = tmpDir.path().join("pid").to_str().unwrap().to_string();
cmd.arg(&pidFile);
} else {
cmd.arg(&pidFile);
}
if self.internalPidFile.len() > 0 {
cmd.arg("--internal-pid-file");
cmd.arg(&self.internalPidFile);
}
cmd.stdin(Stdio::inherit());
cmd.stdout(Stdio::inherit());
cmd.stderr(Stdio::inherit());
if self.consoleSocket.len() > 0 {
cmd.arg("--console-socket");
cmd.arg(&self.consoleSocket);
let (master, slave) = NewPty()?;
unsafe {
let tty = slave.dup()?;
cmd.stdin(Stdio::from_raw_fd(tty));
cmd.stdout(Stdio::from_raw_fd(tty));
cmd.stderr(Stdio::from_raw_fd(tty));
}
let client = UnixSocket::NewClient(&self.consoleSocket)?;
client.SendFd(master.as_raw_fd())?;
}
for a in &self.argv {
cmd.arg(a);
}
let child = cmd.spawn().unwrap();
info!("quark exec: before wait for ready");
WaitForReady(&pidFile, child.id() as i32, 10 * SECOND)?;
info!("quark exec: after wait for ready");
return Ok(())
}
}
pub fn WaitForReady(pidfile: &str, pid: i32, timeout: i64) -> Result<()> {
let count = timeout / 1 * 100 * MILLISECOND;
for _i in 0..count as usize {
let period = time::Duration::from_millis(100);
thread::sleep(period);
if !Path::new(pidfile).exists() {
continue;
}
error!("{} exist", pidfile);
let mut f = match File::open(pidfile) {
Err(e) => {
return Err(Error::Common(format!("WaitForReady fail to open {} with error {:?}", pidfile, e)));
}
Ok(f) => f,
};
let mut pidstr = String::new();
f.read_to_string(&mut pidstr).map_err(|e| Error::Common(format!("WaitForReady fail to read {} with error {:?}", pidfile, e)))?;
let pidInt = pidstr.parse::<i32>().map_err(|_e| Error::Common(format!("WaitForReady cant covert {} to i32", pidstr)))?;
if pidInt == pid {
return Ok(())
}
let mut ws : i32 = 0;
let child = unsafe {
libc::wait4(pid, &mut ws, libc::WNOHANG, 0 as *mut libc::rusage)
};
if child < 0 {
return Err(Error::SysError(errno::errno().0))
}
if child == pid {
return Err(Error::Common(format!("process {} has terminated", pid)))
}
}
return Err(Error::Common(format!("wait process {} timeout", pid)))
}
// resolveEnvs transforms lists of environment variables into a single list of
// environment variables. If a variable is defined multiple times, the last
// value is used.
pub fn ResolveEnvs(envs: &[&[String]]) -> Result<Vec<String>> {
let mut envMap = BTreeMap::new();
for env in envs {
for str in *env {
let parts : Vec<&str> = str.split('=').collect();
if parts.len() != 2 {
return Err(Error::Common(format!("invlid env {}", str)));
}
envMap.insert(parts[0].to_string(), parts[1].to_string());
}
}
let mut ret = Vec::with_capacity(envMap.len());
for (key, val) in envMap {
ret.push(format!("{}={}", key, val))
}
return Ok(ret);
} | 32.55098 | 135 | 0.500271 |
dd90880347b3f9e0843a16393df5a642532db774 | 1,928 | asm | Assembly | programs/oeis/130/A130129.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/130/A130129.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/130/A130129.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A130129: (3*n+1)*2^n.
; 1,8,28,80,208,512,1216,2816,6400,14336,31744,69632,151552,327680,704512,1507328,3211264,6815744,14417920,30408704,63963136,134217728,281018368,587202560,1224736768,2550136832,5301600256,11005853696,22817013760,47244640256,97710505984,201863462912,416611827712,858993459200,1769526525952,3642132267008,7490422964224,15393162788864,31610959298560,64871186038784,133040906960896,272678883688448,558551906910208,1143492092887040,2339760743907328,4785074604081152,9781255440695296,19984723346456576,40813871623045120,83316593106354176,170010885933236224,346777171307528192,707065141497167872,1441151880758558720,2936346957045563392,5980780305148018688,12177733392409821184,24787812349047209984,50440315826549555200,102610013910009380864,208678792333839302656,424275113695319687168,862385285445921538048,1752440687002407403520,3560221606225943461888,7231123676894144233472,14683608282672803086336,29809938423114635411456,60505320561767329300480,122781528554610775556096,249104831971373785022464,505293213667052037865472,1024753526782713011372032,2077841252462643894026240,4212350902719723530616832,8538038601028318546362368,17302750793234380062982144,35058848768824246066479104,71024391902359464013987840,143862172534140871790034944,291351122527125631104188416,589955799971939037256613888,1194418709779253624609701888,2417851639229258349412352000,4893731717800018899210600448,9903520314283042199192993792,20039154385932093199929573376,40542536286596204002946318336,82013527602656443212066979840,165883965264240956836482646016,335481750646338054497662664704,678391141528388390644720074752,1371637563528201344588229640192,2772985687999251815774038261760,5605392497884201884743234486272,11329627239539800275876784898048,22896938966622393564534201647104,46269246908330373154629666996224,93489231766831918360381861396480,188879939434006180823008777601024
mov $1,$0
mul $0,3
add $0,1
mov $2,2
pow $2,$1
mul $0,$2
| 192.8 | 1,845 | 0.926349 |
fb1a4d5a61ceafa023bda39460f9836b2c1ca179 | 1,761 | go | Go | util/config_dump/port_forwarder.go | mlbiam/kiali | 75723d5d1b6fc0b65c47d48f5ee7f552e3ea76eb | [
"Apache-2.0"
] | 7 | 2021-10-31T09:29:45.000Z | 2022-02-21T18:52:17.000Z | util/config_dump/port_forwarder.go | mlbiam/kiali | 75723d5d1b6fc0b65c47d48f5ee7f552e3ea76eb | [
"Apache-2.0"
] | 2 | 2020-08-11T20:00:58.000Z | 2022-03-06T20:52:09.000Z | util/config_dump/port_forwarder.go | mlbiam/kiali | 75723d5d1b6fc0b65c47d48f5ee7f552e3ea76eb | [
"Apache-2.0"
] | 1 | 2021-08-24T09:16:54.000Z | 2021-08-24T09:16:54.000Z | package config_dump
import (
"io"
"net/http"
"os"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/transport/spdy"
"github.com/kiali/kiali/log"
)
type PortForwarder interface {
Start() error
Stop()
}
type forwarder struct {
forwarder *portforward.PortForwarder
ReadyCh chan struct{}
StopCh chan struct{}
}
func (f forwarder) Start() error {
// It starts the port-forward
errCh := make(chan error, 1)
go func() {
errCh <- f.forwarder.ForwardPorts()
}()
// Waiting until the ReadyChan has a value
select {
case err := <-errCh:
log.Errorf("Failing starting the port forwarding")
return err
case <-f.ReadyCh:
// Ready to forward requests
return nil
}
}
func (f forwarder) Stop() {
// Closing the StopCh channel is closing the forwarding
close(f.StopCh)
}
func NewPortForwarder(client rest.Interface, clientConfig *rest.Config, namespace, pod, address, portMap string, writer io.Writer) (forwarder, error) {
stopCh := make(chan struct{})
readyCh := make(chan struct{})
forwarderUrl := client.Post().
Namespace(namespace).
Resource("pods").
Name(pod).
SubResource("portforward").URL()
transport, upgrader, err := spdy.RoundTripperFor(clientConfig)
if err != nil {
log.Errorf("Error creating a RoundTripper: %v", err)
return forwarder{}, err
}
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, http.MethodPost, forwarderUrl)
fwer, err := portforward.NewOnAddresses(dialer, []string{address}, []string{portMap},
stopCh, readyCh, writer, os.Stderr)
if err != nil {
log.Errorf("Error creating the port-forwarder: %v", err)
return forwarder{}, err
}
return forwarder{
forwarder: fwer,
ReadyCh: readyCh,
StopCh: stopCh,
}, nil
}
| 22.0125 | 151 | 0.698467 |
8ed70d1e4794f45621d84f2b6edfcc92f79bd365 | 98 | rb | Ruby | realm-core/lib/realm/query_handler.rb | realm-rb/realm | d30646d0823a391a3ce2b12f102653fbb4901c8a | [
"MIT"
] | 1 | 2022-03-25T14:00:00.000Z | 2022-03-25T14:00:00.000Z | realm-core/lib/realm/query_handler.rb | realm-rb/realm | d30646d0823a391a3ce2b12f102653fbb4901c8a | [
"MIT"
] | null | null | null | realm-core/lib/realm/query_handler.rb | realm-rb/realm | d30646d0823a391a3ce2b12f102653fbb4901c8a | [
"MIT"
] | null | null | null | # frozen_string_literal: true
module Realm
class QueryHandler < Realm::ActionHandler
end
end
| 14 | 43 | 0.785714 |
ceef32e4cc6ae98082a11697f6ba5408e2fc8ced | 13,712 | sql | SQL | wallet_db.sql | Jim-github-s/wallet | b572766c97c8ad50a825cead6145207ea30a8658 | [
"Apache-2.0"
] | null | null | null | wallet_db.sql | Jim-github-s/wallet | b572766c97c8ad50a825cead6145207ea30a8658 | [
"Apache-2.0"
] | null | null | null | wallet_db.sql | Jim-github-s/wallet | b572766c97c8ad50a825cead6145207ea30a8658 | [
"Apache-2.0"
] | null | null | null | /*
SQLyog Ultimate v11.11 (64 bit)
MySQL - 5.5.53 : Database - wallet
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`wallet` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `wallet`;
/*Table structure for table `admin` */
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
`aid` int(10) NOT NULL AUTO_INCREMENT,
`username` bigint(20) NOT NULL,
`password` int(10) NOT NULL,
PRIMARY KEY (`aid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
/*Data for the table `admin` */
insert into `admin`(`aid`,`username`,`password`) values (1,15915719715,123);
/*Table structure for table `bankcard` */
DROP TABLE IF EXISTS `bankcard`;
CREATE TABLE `bankcard` (
`cid` int(10) NOT NULL AUTO_INCREMENT,
`card_number` varchar(20) COLLATE utf8_bin NOT NULL DEFAULT '6222600260001072444',
`card_balance` float NOT NULL DEFAULT '10000',
`card_username` varchar(20) COLLATE utf8_bin NOT NULL DEFAULT '张三',
`card_bank` varchar(10) COLLATE utf8_bin NOT NULL DEFAULT '交通银行',
`uid` int(10) NOT NULL,
PRIMARY KEY (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
/*Data for the table `bankcard` */
insert into `bankcard`(`cid`,`card_number`,`card_balance`,`card_username`,`card_bank`,`uid`) values (1,'6222600260001072444',10000,'张三','交通银行',2147483647),(2,'6222600260001072444',10000,'张三','交通银行',0),(3,'6222600260001072444',10000,'张三','交通银行',113),(4,'6222600260001072444',4687,'张三','交通银行',114),(5,'6222021001116245702',-495000,'风神股','工商银行',24),(6,'6222021001116245702',-501300,'疯疯疯','工商银行',24);
/*Table structure for table `sitedata` */
DROP TABLE IF EXISTS `sitedata`;
CREATE TABLE `sitedata` (
`did` int(10) NOT NULL AUTO_INCREMENT,
`login_number` int(10) NOT NULL,
`user_number` int(10) NOT NULL,
`transfer_number` int(10) NOT NULL,
PRIMARY KEY (`did`),
KEY `uid` (`user_number`),
KEY `tid` (`transfer_number`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='网站数据统计表';
/*Data for the table `sitedata` */
insert into `sitedata`(`did`,`login_number`,`user_number`,`transfer_number`) values (1,74,39,0);
/*Table structure for table `transfer` */
DROP TABLE IF EXISTS `transfer`;
CREATE TABLE `transfer` (
`tid` int(10) NOT NULL,
`fid` int(10) NOT NULL,
`shou_name` varchar(10) COLLATE utf8_bin NOT NULL,
`uid` int(10) NOT NULL,
`fa_name` varchar(10) COLLATE utf8_bin NOT NULL,
`amount` float NOT NULL,
`shou_card_munber` int(50) NOT NULL,
`fa_card_munber` int(50) NOT NULL,
`time` int(20) NOT NULL,
PRIMARY KEY (`tid`),
KEY `uid` (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='转账数据表';
/*Data for the table `transfer` */
insert into `transfer`(`tid`,`fid`,`shou_name`,`uid`,`fa_name`,`amount`,`shou_card_munber`,`fa_card_munber`,`time`) values (0,1,'你好',24,'',200,45464,4566666,4444444),(1,1,'你好',1,'',200,45464,4566666,4444444);
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`uid` int(10) NOT NULL AUTO_INCREMENT,
`username` bigint(20) NOT NULL,
`password` varchar(20) COLLATE utf8_bin NOT NULL,
`name` varchar(20) COLLATE utf8_bin NOT NULL,
`email` varchar(20) COLLATE utf8_bin NOT NULL,
`phone` bigint(20) NOT NULL,
`region` varchar(10) CHARACTER SET utf8 NOT NULL,
`imageUrl` varchar(60) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=115 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
/*Data for the table `user` */
insert into `user`(`uid`,`username`,`password`,`name`,`email`,`phone`,`region`,`imageUrl`) values (14,2147483647,'123','好人','15915713526@qq.com',2147483647,'广州市',NULL),(15,2147483647,'123','好人','15915713526@qq.com',2147483647,'广州市',NULL),(16,2147483647,'123','好人','15915713526@qq.com',2147483647,'广州市',NULL),(17,111111,'11111','15915713526','15915716542@qq.com',2147483647,'深圳市',NULL),(18,111111,'11111','15915713526','15915716542@qq.com',2147483647,'深圳市',NULL),(19,546,'546','2222222','111111@qq.com',15915713526,'深圳市',NULL),(20,546,'546','2222222','111111@qq.com',2147483647,'深圳市',NULL),(22,2147483647,'123','好人','15915716542@qq.com',2147483647,'广州市',NULL),(23,333333,'3333332','东方红','333333@qq.com',15915712654,'上海市',NULL),(24,123,'123','55555555','123@qq.com',15915719777,'上海市','G:\\xampp\\www\\Wallet\\public/..\\public/upload/24.jpg'),(25,15915719777,'15915719777','15915719777','15915719777@qq.com',15915719777,'海北藏族自治州',NULL),(26,15915719777,'15915719777','15915719777','15915719777@qq.com',15915719777,'海北藏族自治州',NULL),(27,15915719777,'15915719777','15915719777','15915719777@qq.com',15915719777,'海北藏族自治州',NULL),(28,15915719777,'15915719777','15915719777','15915719777@qq.com',15915719777,'海北藏族自治州',NULL),(29,1591571999,'1591571999','好人','15915716542@qq.com',15915719799,'广州市',NULL),(30,1591571999,'1591571999','好人','15915716542@qq.com',15915719799,'广州市',NULL),(31,15915799998,'15915799998','15915799998','15915713526@qq.com',15915799998,'沈阳市',NULL),(32,15915799998,'15915799998','15915799998','15915713526@qq.com',15915799998,'沈阳市',NULL),(33,789,'789','789','15915716542@qq.com',15915716542,'北京市',NULL),(34,789,'789','789','15915716542@qq.com',15915716542,'北京市',NULL),(35,789,'789','789','15915716542@qq.com',15915716542,'北京市',NULL),(36,789,'789','789','15915716542@qq.com',15915716542,'北京市',NULL),(37,789,'789','789','15915716542@qq.com',15915716542,'上海市',NULL),(38,789,'789','789','15915716542@qq.com',15915716542,'上海市',NULL),(39,789,'789','789','15915716542@qq.com',15915716542,'广州市',NULL),(40,789,'789','789','15915716542@qq.com',15915716542,'广州市',NULL),(41,789,'789','789','15915716542@qq.com',15915716542,'广州市',NULL),(42,789,'789','789','15915716542@qq.com',15915716542,'广州市',NULL),(43,789,'789','789','15915716542@qq.com',15915716542,'广州市',NULL),(44,789,'789','789','15915716542@qq.com',15915716542,'广州市',NULL),(45,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(46,456789456,'456789456','456789456','15915716542@qq.com',15915716542,'深圳市',NULL),(47,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(48,456789456,'456789456','456789456','15915716542@qq.com',15915716542,'广州市',NULL),(49,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(50,44646489,'44646489','44646489','15915716542@qq.com',15915716542,'广州市',NULL),(51,12345679,'12345679','12345679','12345679@qq.com',15915719159,'北京市',NULL),(52,44444444,'44444444','44444444','15915716542@qq.com',15915716542,'广州市',NULL),(53,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(54,4545545454,'4545545454','4545545454','15915716542@qq.com',15915716542,'广州市',NULL),(55,55555555555555,'123','55555555555555','15915716542@qq.com',15915716542,'广州市',NULL),(56,55555555555555,'123','55555555555555','15915716542@qq.com',15915716542,'广州市',NULL),(57,66666666,'123','66666666','15915716542@qq.com',15915716542,'广州市',NULL),(58,66666666,'123','66666666','15915716542@qq.com',15915716542,'广州市',NULL),(59,66666666,'123','66666666','15915716542@qq.com',15915716542,'北京市',NULL),(60,159157197177,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(61,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(62,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(63,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(64,66666,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(65,666666666666,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(66,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(67,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(68,77777777777777,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(69,7777,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(70,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(71,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(72,7777,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(73,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(74,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(75,88888888888,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(76,999999999999999,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(77,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(78,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(79,333,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(80,987654321,'123','987654321','15915716542@qq.com',15915716542,'广州市',NULL),(81,987654321,'123','15915713526','15915716542@qq.com',15915716542,'广州市',NULL),(82,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(83,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(84,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(85,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(86,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(87,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(88,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(89,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(90,15915719715,'123','15915713526','15915716542@qq.com',15915716542,'广州市',NULL),(91,15915719715,'123','好人','15915713526@qq.com',15915716542,'深圳市',NULL),(92,15915719715,'123','好人','15915713526@qq.com',15915713526,'广州市',NULL),(93,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(94,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(95,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(96,15915719715,'123','好人','15915716542@qq.com',15915716542,'深圳市',NULL),(97,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(98,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(99,15915719715,'123','15915713526','15915716542@qq.com',15915716542,'广州市',NULL),(100,15915719715,'123','15915713526','15915713526@qq.com',15915716542,'深圳市',NULL),(101,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(102,15915719715,'123','好人','15915716542@qq.com',15915716542,'深圳市',NULL),(103,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(104,123456,'123456','好人','15915716542@qq.com',15915716542,'广州市','G:\\xampp\\www\\Wallet\\public/..\\public/upload/104.jpg'),(105,55555555,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(106,15915719711,'123','15915713526','15915716542@qq.com',15915716542,'广州市',NULL),(107,15915719711,'123','东方学学自傲','15915713526@qq.com',15915713526,'深圳市',NULL),(108,15915719715,'123','15915713526','15915716542@qq.com',15915716542,'广州市',NULL),(109,15915719715,'123','好人','15915716542@qq.com',15915716542,'广州市',NULL),(110,15915719715,'123','15915713526','15915716542@qq.com',15915716542,'广州市',NULL),(111,5555555555,'5555555555','源码','5555555555@qq.com',15915719711,'北京市',NULL),(112,666666,'666666','666666','666666@qq.com',15915719711,'北京市',NULL),(113,44444444,'44444444','44444444','44444444@qq.com',15915719711,'南京市',NULL),(114,13044055454,'13044055454','13044055454','13044055454@qq.com',13044055454,'北京市',NULL);
/*Table structure for table `userexpend` */
DROP TABLE IF EXISTS `userexpend`;
CREATE TABLE `userexpend` (
`acid` int(10) NOT NULL AUTO_INCREMENT,
`uid` int(10) NOT NULL,
`type` varchar(10) COLLATE utf8_bin NOT NULL,
`description` varchar(20) COLLATE utf8_bin NOT NULL,
`account` int(10) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`acid`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='支出表的数据';
/*Data for the table `userexpend` */
insert into `userexpend`(`acid`,`uid`,`type`,`description`,`account`,`date`) values (8,114,'餐饮','沙发大概',5,'2018-12-04'),(9,114,'日用','电风扇',60,'2018-12-03'),(11,114,'1','股票',500,'2018-12-05'),(12,114,'1','发过火',500,'2018-12-03'),(13,114,'1','愉快',600,'2018-12-03'),(15,114,'餐饮','富商大贾',500,'2018-12-04'),(17,114,'餐饮','建行卡',100,'2018-12-03'),(18,24,'餐饮','牛肉',500,'2019-02-12'),(19,24,'餐饮','10000',10000,'2019-03-13'),(20,24,'购物','500000',500000,'2019-03-13');
/*Table structure for table `userincome` */
DROP TABLE IF EXISTS `userincome`;
CREATE TABLE `userincome` (
`iid` int(10) NOT NULL AUTO_INCREMENT,
`uid` int(10) NOT NULL,
`type` varchar(10) COLLATE utf8_bin NOT NULL,
`description` varchar(20) COLLATE utf8_bin NOT NULL,
`account` int(10) NOT NULL,
`date` date NOT NULL,
PRIMARY KEY (`iid`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='收入表数据';
/*Data for the table `userincome` */
insert into `userincome`(`iid`,`uid`,`type`,`description`,`account`,`date`) values (1,12,'工资','工资',2000,'2018-12-04'),(2,12,'工资','工资',2000,'2018-12-04'),(3,114,'1','炒股票',1000,'2018-12-03'),(5,114,'理财','也同样',500,'2018-12-03'),(7,114,'理财','一会让他',500,'2018-12-03'),(8,114,'理财','是的法规',456,'2018-12-07'),(10,114,'理财','换个',100,'2018-12-06'),(11,24,'工资','工资',2000,'2019-02-12'),(12,24,'理财','答复',500,'2019-03-13'),(13,24,'其他','大师傅',8000,'2019-03-13');
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
| 90.210526 | 7,604 | 0.700408 |
610fff90d9032ddb6d70e8374365bcda90658b82 | 274 | css | CSS | src/client/js/otp/widgets/widget-style.css | skjolber/r5 | 380340bbff8258e83d84d5007c9386765fc0d3da | [
"MIT"
] | 3 | 2018-12-21T11:40:03.000Z | 2020-09-14T06:49:22.000Z | src/client/js/otp/widgets/widget-style.css | skjolber/r5 | 380340bbff8258e83d84d5007c9386765fc0d3da | [
"MIT"
] | 29 | 2018-09-07T13:52:29.000Z | 2019-11-18T15:36:43.000Z | src/client/js/otp/widgets/widget-style.css | skjolber/r5 | 380340bbff8258e83d84d5007c9386765fc0d3da | [
"MIT"
] | 2 | 2018-10-24T17:53:36.000Z | 2020-01-24T13:16:28.000Z | .otp-dialogContent {
position: absolute;
top: 10px;
bottom: 45px;
left: 10px;
right: 10px;
}
.otp-dialogButtonRow {
position: absolute;
bottom: 5px;
left: 0px;
right: 0px;
height: 30px;
text-align: center;
margin-top: 8px;
}
| 15.222222 | 23 | 0.587591 |
167307c7540581aa7a1083d34f6397c4e59b807e | 103 | h | C | src/z80_xgm.h | Megadrive-Vault/SGDK | 63e95c0267f66badacc266a55c3c939472b708f1 | [
"MIT"
] | 1 | 2019-09-16T10:24:36.000Z | 2019-09-16T10:24:36.000Z | src/z80_xgm.h | Megadrive-Vault/SGDK | 63e95c0267f66badacc266a55c3c939472b708f1 | [
"MIT"
] | null | null | null | src/z80_xgm.h | Megadrive-Vault/SGDK | 63e95c0267f66badacc266a55c3c939472b708f1 | [
"MIT"
] | 1 | 2019-10-23T16:41:06.000Z | 2019-10-23T16:41:06.000Z | #ifndef _Z80_XGM_H_
#define _Z80_XGM_H_
extern const u8 z80_xgm[0x1700];
#endif // _Z80_XGM_H_
| 14.714286 | 33 | 0.737864 |
a30da014b7337b54c5e1781c3bd56ff89e472ee7 | 3,438 | sql | SQL | src/test/resources/test-data.sql | ifqthenp/otus-spring-hw-06-spring-data-jpa | 0094e8363e1b32173c458060d5a520c0085940ac | [
"MIT"
] | null | null | null | src/test/resources/test-data.sql | ifqthenp/otus-spring-hw-06-spring-data-jpa | 0094e8363e1b32173c458060d5a520c0085940ac | [
"MIT"
] | null | null | null | src/test/resources/test-data.sql | ifqthenp/otus-spring-hw-06-spring-data-jpa | 0094e8363e1b32173c458060d5a520c0085940ac | [
"MIT"
] | null | null | null | INSERT INTO `authors` VALUES (1, 'Lewis', 'Carrol');
INSERT INTO `authors` VALUES (2, 'Charlotte', 'Bronte');
INSERT INTO `authors` VALUES (3, 'Miguel', 'de Cervantes');
INSERT INTO `authors` VALUES (4, 'Herbert', 'Wells');
INSERT INTO `authors` VALUES (5, 'Leo', 'Tolstoy');
INSERT INTO `authors` VALUES (6, 'Jane', 'Austen');
INSERT INTO `authors` VALUES (7, 'Gabriel', 'García Márquez');
INSERT INTO `authors` VALUES (8, 'Leonardo', 'Fibonacci');
INSERT INTO `authors` VALUES (9, 'Ilya', 'Ilf');
INSERT INTO `authors` VALUES (10, 'Yevgeni', 'Petrov');
INSERT INTO `books` VALUES (1, 'Alice in Wonderland', '1865');
INSERT INTO `books` VALUES (2, 'Jane Eyre', '1847');
INSERT INTO `books` VALUES (3,'Don Quixote', '1615');
INSERT INTO `books` VALUES (4, 'The Time Machine', '1895');
INSERT INTO `books` VALUES (5, 'Anna Karenina', '1878');
INSERT INTO `books` VALUES (6, 'Pride and Prejudice', '1813');
INSERT INTO `books` VALUES (7, 'Childhood', '1852');
INSERT INTO `books` VALUES (8, 'Boyhood', '1854');
INSERT INTO `books` VALUES (9, 'Love in the Time of Cholera', '1985');
INSERT INTO `books` VALUES (10, 'The Book of Calculation', '1202');
INSERT INTO `books` VALUES (11, 'The Twelve Chairs', '1928');
INSERT INTO `books` VALUES (12, 'The Little Golden Calf', '1931');
INSERT INTO `genres` VALUES (1, 'Literary realism');
INSERT INTO `genres` VALUES (2, 'Fantasy');
INSERT INTO `genres` VALUES (3, 'Autobiography');
INSERT INTO `genres` VALUES (4, 'Novel');
INSERT INTO `genres` VALUES (5, 'Science-fiction');
INSERT INTO `genres` VALUES (6, 'Romance');
INSERT INTO `genres` VALUES (7, 'Mathematics');
INSERT INTO `genres` VALUES (8, 'Children''s Literature');
INSERT INTO `genres` VALUES (9, 'Satire');
INSERT INTO `comments` VALUES (1, 'excellent', 1);
INSERT INTO `comments` VALUES (2, 'nice', 2);
INSERT INTO `comments` VALUES (3, 'awesome book', 2);
INSERT INTO `comments` VALUES (4, 'pretty good', 3);
INSERT INTO `comments` VALUES (5, 'very good', 5);
INSERT INTO `book_genre` VALUES (1, 2);
INSERT INTO `book_genre` VALUES (1, 8);
INSERT INTO `book_genre` VALUES (2, 4);
INSERT INTO `book_genre` VALUES (2, 6);
INSERT INTO `book_genre` VALUES (3, 4);
INSERT INTO `book_genre` VALUES (4, 5);
INSERT INTO `book_genre` VALUES (5, 1);
INSERT INTO `book_genre` VALUES (5, 4);
INSERT INTO `book_genre` VALUES (2, 3);
INSERT INTO `book_genre` VALUES (6, 6);
INSERT INTO `book_genre` VALUES (7, 3);
INSERT INTO `book_genre` VALUES (7, 1);
INSERT INTO `book_genre` VALUES (7, 4);
INSERT INTO `book_genre` VALUES (8, 3);
INSERT INTO `book_genre` VALUES (8, 1);
INSERT INTO `book_genre` VALUES (8, 4);
INSERT INTO `book_genre` VALUES (9, 4);
INSERT INTO `book_genre` VALUES (10, 7);
INSERT INTO `book_genre` VALUES (11, 4);
INSERT INTO `book_genre` VALUES (11, 9);
INSERT INTO `book_genre` VALUES (12, 4);
INSERT INTO `book_genre` VALUES (12, 9);
INSERT INTO `book_author` VALUES (1, 1);
INSERT INTO `book_author` VALUES (2, 2);
INSERT INTO `book_author` VALUES (3, 3);
INSERT INTO `book_author` VALUES (4, 4);
INSERT INTO `book_author` VALUES (5, 5);
INSERT INTO `book_author` VALUES (6, 6);
INSERT INTO `book_author` VALUES (7, 5);
INSERT INTO `book_author` VALUES (8, 5);
INSERT INTO `book_author` VALUES (9, 7);
INSERT INTO `book_author` VALUES (10, 8);
INSERT INTO `book_author` VALUES (11, 9);
INSERT INTO `book_author` VALUES (11, 10);
INSERT INTO `book_author` VALUES (12, 9);
INSERT INTO `book_author` VALUES (12, 10);
| 44.076923 | 70 | 0.688773 |
91f2ed80b29630ea71f6500c1d444bebaf692182 | 276 | kt | Kotlin | neumorphic/src/main/java/com/gandiva/neumorphic/NeuStyle.kt | sridhar-sp/compose-neumorphism | 8deff9e97c429024fbb970d5ca168c49d9b17ed7 | [
"Apache-2.0"
] | 20 | 2022-01-04T14:19:53.000Z | 2022-03-29T11:56:26.000Z | neumorphic/src/main/java/com/gandiva/neumorphic/NeuStyle.kt | sridhar-sp/compose-neumorphism | 8deff9e97c429024fbb970d5ca168c49d9b17ed7 | [
"Apache-2.0"
] | 1 | 2022-01-07T04:31:32.000Z | 2022-01-10T05:05:11.000Z | neumorphic/src/main/java/com/gandiva/neumorphic/NeuStyle.kt | sridhar-sp/compose-neumorphism | 8deff9e97c429024fbb970d5ca168c49d9b17ed7 | [
"Apache-2.0"
] | 1 | 2022-02-02T22:21:56.000Z | 2022-02-02T22:21:56.000Z | package com.gandiva.neumorphic
import androidx.compose.ui.unit.Dp
data class NeuStyle(
val lightShadowColor: androidx.compose.ui.graphics.Color,
val darkShadowColor: androidx.compose.ui.graphics.Color,
val shadowElevation: Dp,
val lightSource: LightSource
)
| 25.090909 | 61 | 0.778986 |
f0476c6057fe6e189aeed8a5c7b88b67234d582d | 78 | py | Python | svae/__init__.py | APodolskiy/SentenceVAE | afe82504922de700810b24638f7df0dbf1d8fa11 | [
"MIT"
] | null | null | null | svae/__init__.py | APodolskiy/SentenceVAE | afe82504922de700810b24638f7df0dbf1d8fa11 | [
"MIT"
] | null | null | null | svae/__init__.py | APodolskiy/SentenceVAE | afe82504922de700810b24638f7df0dbf1d8fa11 | [
"MIT"
] | null | null | null | import torch.nn as nn
RNN_TYPES = {
'lstm': nn.LSTM,
'gru': nn.GRU
}
| 11.142857 | 21 | 0.564103 |
7096668b9dafc530c3cae4e03524e0d1dc16960b | 11,213 | go | Go | internal/partition/partition.go | go-sif/sif | e29587869c5d8d3fcacb518551e28ffbbac06fd3 | [
"Apache-2.0"
] | 31 | 2020-02-19T13:21:26.000Z | 2022-03-10T06:44:12.000Z | internal/partition/partition.go | go-sif/sif | e29587869c5d8d3fcacb518551e28ffbbac06fd3 | [
"Apache-2.0"
] | 20 | 2020-03-10T03:13:31.000Z | 2022-03-16T19:35:39.000Z | internal/partition/partition.go | go-sif/sif | e29587869c5d8d3fcacb518551e28ffbbac06fd3 | [
"Apache-2.0"
] | 2 | 2020-04-24T02:50:09.000Z | 2021-10-31T12:19:27.000Z | package partition
import (
"bytes"
"encoding/gob"
"fmt"
"io"
"log"
"github.com/go-sif/sif"
pb "github.com/go-sif/sif/internal/rpc"
iutil "github.com/go-sif/sif/internal/util"
uuid "github.com/gofrs/uuid"
)
const defaultCapacity = 2
// partitionImpl is Sif's internal implementation of Partition
type partitionImpl struct {
compressor sif.Compressor
schema sif.Schema
internalData *partitionData
colIsDirty map[string]bool
activeColData map[string][]byte // uncompressed fixed-width column data
activeVarLengthData map[string][]interface{} // uncompressed variable-length column data which has been deserialized by the column's deserializer
}
// createPartitionImpl initializes a new Partition, with an initial row capacity, a maximum row capacity, and a particular Schema
func createPartitionImpl(maxRows int, initialCapacity int, schema sif.Schema) *partitionImpl {
id, err := uuid.NewV4()
if err != nil {
log.Fatalf("failed to generate UUID for Partition: %v", err)
}
if initialCapacity > maxRows {
initialCapacity = maxRows
}
if initialCapacity < 0 {
panic("initial capacity for partition cannot be negative")
}
// initialize underlying column data
colData := make(map[string]*columnData)
colIsDirty := make(map[string]bool)
activeColData := make(map[string][]byte)
activeVarLengthData := make(map[string][]interface{})
schema.ForEachColumn(func(name string, col sif.Column) error {
isVarLength := sif.IsVariableLength(col.Type())
colIsDirty[name] = true // initially, there is no serialized, compressed data for this column. everything starts as active data
colData[name] = &columnData{
IsVariableLength: isVarLength,
Meta: make([]byte, initialCapacity),
Data: nil, // initially, there is no serialized, compressed data for this column. everything starts as active data
}
if isVarLength {
activeVarLengthData[name] = make([]interface{}, initialCapacity)
} else {
activeColData[name] = make([]byte, initialCapacity*col.Type().Size())
}
return nil
})
internalData := &partitionData{
Id: id.String(),
MaxRows: int32(maxRows),
NumRows: 0,
Capacity: int32(initialCapacity),
Keys: nil,
ColData: colData,
}
return &partitionImpl{
internalData: internalData,
colIsDirty: colIsDirty,
activeColData: activeColData,
activeVarLengthData: activeVarLengthData,
schema: schema,
compressor: nil,
}
}
// CreatePartition creates a new Partition containing an empty byte array and a schema
func CreatePartition(maxRows int, initialCapacity int, schema sif.Schema) sif.Partition {
return createPartitionImpl(maxRows, initialCapacity, schema)
}
// sync writes any Partition modifications to the underlying compressed data,
// returning true iff there were any changes to write
func (p *partitionImpl) sync() (bool, error) {
// returns error if compressor has not been set
if p.compressor == nil {
return true, fmt.Errorf("cannot sync Partition modifications for partition %s because no Compressor has been set", p.internalData.Id)
}
anyChanges := false
for _, colName := range p.schema.ColumnNames() {
if p.colIsDirty[colName] {
changed, err := p.serializeColumn(colName)
if err != nil {
return anyChanges, err
}
anyChanges = anyChanges || changed
}
}
return anyChanges, nil
}
func (p *partitionImpl) columnIsDeserialized(colName string) bool {
_, isFixedDeserialized := p.activeColData[colName]
_, isVarDeserialized := p.activeVarLengthData[colName]
return isFixedDeserialized || isVarDeserialized
}
func (p *partitionImpl) columnIsDirty(colName string) bool {
isDirty, isKnown := p.colIsDirty[colName]
return isKnown && isDirty
}
func (p *partitionImpl) deserializeColumn(colName string) error {
// no-op if already deserialized
if p.columnIsDeserialized(colName) {
return nil
}
// returns error if decompressor has not been set
if p.compressor == nil {
return fmt.Errorf("cannot deserialize column data for column %s because no Compressor has been set", colName)
}
col, err := p.schema.GetColumn(colName)
if err != nil {
return err
}
colData := p.internalData.ColData[colName]
compressedColData := colData.Data
// decompress, if there is data to decompress
var decompressedColData *bytes.Buffer
if compressedColData != nil {
decompressedColData = new(bytes.Buffer)
err = p.compressor.Decompress(bytes.NewBuffer(compressedColData), decompressedColData)
if err != nil {
return err
}
}
// Copy decompressed data into active buffers
if colData.IsVariableLength {
// make room for active variable-length data
p.activeVarLengthData[colName] = make([]interface{}, p.internalData.Capacity)
// if there's no rows, we're done
if p.internalData.NumRows == 0 {
return nil
}
// if there's no decompressed data we're done
if decompressedColData == nil {
return nil
}
// decode data from internalData proto
var decodedSerializedRowData [][]byte
d := gob.NewDecoder(decompressedColData)
err := d.Decode(&decodedSerializedRowData)
if err != nil {
return err
}
if !sif.IsVariableLength(col.Type()) {
return fmt.Errorf("serialized column data for %s is variable-length, but schema indicates column is fixed-length", colName)
}
vcol := col.Type().(sif.VarColumnType)
dest := p.activeVarLengthData[colName]
for i, sRowVal := range decodedSerializedRowData {
// we don't need to copy deserialized data past our current partition size
if i >= p.GetNumRows() {
break
}
if sRowVal != nil {
dest[i], err = vcol.Deserialize(sRowVal)
if err != nil {
return err
}
}
}
} else {
// make room for active fixed-width data
p.activeColData[colName] = make([]byte, int(p.internalData.Capacity)*col.Type().Size())
// if there's no rows, we're done
if p.internalData.NumRows == 0 {
return nil
}
// if there's no decompressed data we're done
if decompressedColData == nil {
return nil
}
decompressedBytes := decompressedColData.Bytes()
if len(decompressedBytes) > len(p.activeColData[colName]) {
return fmt.Errorf("cannot deserialize column data. Size of deserialized column data is larger than partition capacity")
}
// we don't need to copy deserialized data past our current partition size
copy(p.activeColData[colName], decompressedBytes[0:col.Type().Size()*p.GetNumRows()])
}
// done, data is ready to be used
return nil
}
func (p *partitionImpl) serializeColumn(colName string) (bool, error) {
// no-op if never deserialized
if !p.columnIsDeserialized(colName) {
return false, nil
} else if _, ok := p.internalData.ColData[colName]; ok && !p.columnIsDirty(colName) {
// nearly a no-op if valid serialized data still exists (discards any deserialized data)
delete(p.activeColData, colName)
delete(p.activeVarLengthData, colName)
return false, nil
}
// returns error if compressor has not been set
if p.compressor == nil {
return true, fmt.Errorf("cannot serialize column data for column %s because no Compressor has been set", colName)
}
if p.internalData.NumRows > 0 {
toCompress := new(bytes.Buffer)
colData := p.internalData.ColData[colName]
col, err := p.schema.GetColumn(colName)
if err != nil {
return true, err
}
if colData.IsVariableLength {
// if the data is variable length, we first have to
// serialize each row value using the Column's Serialize
// method, then Gob encode the resulting [][]byte into a []byte.
// Finally, we compress and store in the proto.
if !sif.IsVariableLength(col.Type()) {
return true, fmt.Errorf("serialized column data for %s is variable-length, but schema indicates column is fixed-length", colName)
}
vcol := col.Type().(sif.VarColumnType)
activeData := p.activeVarLengthData[colName]
serializedActiveData := make([][]byte, p.internalData.NumRows)
for i := 0; i < int(p.internalData.NumRows); i++ {
rowVal := activeData[i]
if rowVal != nil {
serializedActiveData[i], err = vcol.Serialize(rowVal)
if err != nil {
return true, err
}
}
}
e := gob.NewEncoder(toCompress)
err = e.Encode(serializedActiveData)
if err != nil {
return true, err
}
} else {
if sif.IsVariableLength(col.Type()) {
return true, fmt.Errorf("serialized column data for %s is fixed-length, but schema indicates column is variable-length", colName)
}
toCompress.Write(p.activeColData[colName][0 : p.internalData.NumRows*int32(col.Type().Size())])
}
// compress data
compressed := new(bytes.Buffer)
err = p.compressor.Compress(toCompress, compressed)
if err != nil {
return true, err
}
// store in proto
colData.Data = compressed.Bytes()
}
// column is no longer dirty
p.colIsDirty[colName] = false
// discard deserialized data
delete(p.activeColData, colName)
delete(p.activeVarLengthData, colName)
return true, nil
}
// setColumnDirty indicates that a column has been written to and needs to be reserialized via sync()
func (p *partitionImpl) setColumnDirty(colName string) {
p.colIsDirty[colName] = true
// remove internal, serialized data for column because it's no longer useful
p.internalData.ColData[colName].Data = nil
}
// ID retrieves the ID of this Partition
func (p *partitionImpl) ID() string {
return p.internalData.Id
}
// GetMaxRows retrieves the maximum number of rows in this Partition
func (p *partitionImpl) GetMaxRows() int {
return int(p.internalData.MaxRows)
}
// GetNumRows retrieves the number of rows in this Partition
func (p *partitionImpl) GetNumRows() int {
return int(p.internalData.NumRows)
}
// getRowInternal retrieves a specific row from this Partition, without allocation
func (p *partitionImpl) getRow(row *rowImpl, rowNum int) sif.Row {
row.rowNum = rowNum
row.partition = p
return row
}
// GetRow retrieves a specific row from this Partition
func (p *partitionImpl) GetRow(rowNum int) sif.Row {
return &rowImpl{rowNum, p}
}
func (p *partitionImpl) GetSchema() sif.Schema {
return p.schema
}
// FromStreamedData loads data from a protobuf stream into this Partition
func FromStreamedData(stream pb.PartitionsService_TransferPartitionDataClient, partitionMeta *pb.MPartitionMeta, schema sif.Schema, compressor sif.Compressor) (sif.Partition, error) {
// stream data for Partition
dataOffset := 0
buff := make([]byte, partitionMeta.GetBytes())
for chunk, err := stream.Recv(); err != io.EOF; chunk, err = stream.Recv() {
if err != nil {
// not an EOF, but something else
return nil, err
}
switch chunk.DataType {
case iutil.SerializedPartitionDataType:
copy(buff[dataOffset:dataOffset+len(chunk.Data)], chunk.Data)
dataOffset += len(chunk.Data)
default:
return nil, fmt.Errorf("unknown chunk data type encountered: %d", chunk.DataType)
}
}
// confirm we received the correct amount of data
if uint32(dataOffset) != partitionMeta.GetBytes() {
return nil, fmt.Errorf("streamed %d bytes for SerializedPartition %s. Expected %d", dataOffset, partitionMeta.GetId(), partitionMeta.GetBytes())
}
// decompress and deserialize
return FromBytes(buff, schema, compressor)
}
| 34.185976 | 183 | 0.71756 |
1871215b95db7064d348bc17e7099b6d4125c1b5 | 786 | sql | SQL | SEIDR.Database/SEIDR/Tables/Operation.sql | maron6/SEIDR | cb422681994b81d7e28149acc5676f859f4fa93b | [
"MIT"
] | 1 | 2018-02-16T16:47:07.000Z | 2018-02-16T16:47:07.000Z | SEIDR.Database/SEIDR/Tables/Operation.sql | maron6/SEIDR | cb422681994b81d7e28149acc5676f859f4fa93b | [
"MIT"
] | null | null | null | SEIDR.Database/SEIDR/Tables/Operation.sql | maron6/SEIDR | cb422681994b81d7e28149acc5676f859f4fa93b | [
"MIT"
] | null | null | null | CREATE TABLE [SEIDR].[Operation] (
[OperationID] INT IDENTITY (1, 1) NOT NULL,
[Operation] VARCHAR (128) NOT NULL,
[OperationSchema] VARCHAR (128) NOT NULL,
[Description] VARCHAR (300) NULL,
[Version] INT NOT NULL,
[ThreadID] TINYINT NULL,
[ParameterSelect] VARCHAR (140) NULL,
[DD] SMALLDATETIME NULL,
[Active] AS (CONVERT([bit],case when [DD] IS NULL then (1) else (0) end)) PERSISTED NOT NULL,
CONSTRAINT [PK_Operation] PRIMARY KEY CLUSTERED ([OperationID] ASC)
);
GO
CREATE UNIQUE NONCLUSTERED INDEX [UQ_Operation_Op_Sch_V]
ON [SEIDR].[Operation]([Operation] ASC, [OperationSchema] ASC, [Version] ASC)
INCLUDE([ThreadID], [ParameterSelect]);
| 39.3 | 117 | 0.609415 |
e9bedf6379a6acaa0d2717c221dde3c3cce763ee | 3,282 | rs | Rust | src/parse.rs | ironthree/fedora-update-feedback | 9352fa50bb03926e74d4ab316f306172f14d5414 | [
"Apache-2.0",
"MIT"
] | 2 | 2020-03-12T10:41:00.000Z | 2020-03-29T11:09:36.000Z | src/parse.rs | ironthree/fedora-update-feedback | 9352fa50bb03926e74d4ab316f306172f14d5414 | [
"Apache-2.0",
"MIT"
] | 5 | 2020-01-26T22:04:10.000Z | 2021-10-11T11:19:36.000Z | src/parse.rs | ironthree/fedora-update-feedback | 9352fa50bb03926e74d4ab316f306172f14d5414 | [
"Apache-2.0",
"MIT"
] | null | null | null | /// This helper function parses a NEVRA string into its components.
#[allow(clippy::many_single_char_names)]
pub fn parse_nevra(nevra: &str) -> Result<(&str, &str, &str, &str, &str), String> {
let mut nevr_a: Vec<&str> = nevra.rsplitn(2, '.').collect();
if nevr_a.len() != 2 {
return Err(format!("Unexpected error when parsing NEVRAs: {}", nevra));
};
// rsplitn returns things in reverse order
let a = nevr_a.remove(0);
let nevr = nevr_a.remove(0);
let mut n_ev_r: Vec<&str> = nevr.rsplitn(3, '-').collect();
if n_ev_r.len() != 3 {
return Err(format!("Unexpected error when parsing NEVRAs: {}", nevr));
};
// rsplitn returns things in reverse order
let r = n_ev_r.remove(0);
let ev = n_ev_r.remove(0);
let n = n_ev_r.remove(0);
let (e, v) = if ev.contains(':') {
let mut e_v: Vec<&str> = ev.split(':').collect();
let e = e_v.remove(0);
let v = e_v.remove(0);
(e, v)
} else {
("0", ev)
};
Ok((n, e, v, r, a))
}
/// This helper function parses a NEVRA.rpm string into its components.
#[allow(clippy::many_single_char_names)]
pub fn parse_filename(nevrax: &str) -> Result<(&str, &str, &str, &str, &str), String> {
let mut nevra_x: Vec<&str> = nevrax.rsplitn(2, '.').collect();
if nevra_x.len() != 2 {
return Err(format!("Unexpected error when parsing dnf output: {}", nevrax));
};
// rsplitn returns things in reverse order
let _x = nevra_x.remove(0);
let nevra = nevra_x.remove(0);
let (n, e, v, r, a) = parse_nevra(nevra)?;
Ok((n, e, v, r, a))
}
/// This helper function parses an NVR string into its components.
#[allow(clippy::many_single_char_names)]
pub fn parse_nvr(nvr: &str) -> Result<(&str, &str, &str), String> {
let mut n_v_r: Vec<&str> = nvr.rsplitn(3, '-').collect();
if n_v_r.len() != 3 {
return Err(format!("Unexpected error when parsing NEVRAs: {}", nvr));
};
// rsplitn returns things in reverse order
let r = n_v_r.remove(0);
let v = n_v_r.remove(0);
let n = n_v_r.remove(0);
Ok((n, v, r))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nevra() {
let string = "maven-1:3.6.1-5.fc32.noarch";
let value = ("maven", "1", "3.6.1", "5.fc32", "noarch");
assert_eq!(parse_nevra(string).unwrap(), value);
let string = "dnf-4.2.18-2.fc32.noarch";
let value = ("dnf", "0", "4.2.18", "2.fc32", "noarch");
assert_eq!(parse_nevra(string).unwrap(), value);
}
#[test]
fn filename() {
let string = "maven-1:3.6.1-5.fc32.noarch.rpm";
let value = ("maven", "1", "3.6.1", "5.fc32", "noarch");
assert_eq!(parse_filename(string).unwrap(), value);
let string = "dnf-4.2.18-2.fc32.src.rpm";
let value = ("dnf", "0", "4.2.18", "2.fc32", "src");
assert_eq!(parse_filename(string).unwrap(), value);
}
#[test]
fn nvr() {
let string = "maven-3.6.1-5.fc32";
let value = ("maven", "3.6.1", "5.fc32");
assert_eq!(parse_nvr(string).unwrap(), value);
let string = "dnf-4.2.18-2.fc32";
let value = ("dnf", "4.2.18", "2.fc32");
assert_eq!(parse_nvr(string).unwrap(), value);
}
}
| 28.789474 | 87 | 0.560938 |
15dd30ce30174b9a1907439036cd7743209c3b51 | 311 | rb | Ruby | log-if-nginx-module.rb | LTD-Beget/homebrew-nginx | 39a79396961abe79ad3c786e4afa0fe2a6d8edb5 | [
"MIT"
] | null | null | null | log-if-nginx-module.rb | LTD-Beget/homebrew-nginx | 39a79396961abe79ad3c786e4afa0fe2a6d8edb5 | [
"MIT"
] | null | null | null | log-if-nginx-module.rb | LTD-Beget/homebrew-nginx | 39a79396961abe79ad3c786e4afa0fe2a6d8edb5 | [
"MIT"
] | null | null | null | require "formula"
class LogIfNginxModule < Formula
homepage "https://github.com/cfsego/ngx_log_if"
url "https://github.com/cfsego/ngx_log_if/archive/master.tar.gz"
sha1 "8dfb8c0f9358821377c0dea810a49a026aecd405"
version "0.1"
def install
(share+"log-if-nginx-module").install Dir["*"]
end
end
| 23.923077 | 66 | 0.742765 |
572adc3da4357103fd7ffce28de0c9211c45f290 | 6,481 | h | C | examples/xma/decode_only/include/xlnx_decoder.h | jmouroux/video-sdk | ae3430c8cb0553bbcfc097b8e36ee9e08ac32c35 | [
"Apache-2.0",
"BSD-3-Clause"
] | 11 | 2021-06-01T06:16:50.000Z | 2022-02-16T16:19:20.000Z | examples/xma/decode_only/include/xlnx_decoder.h | jmouroux/video-sdk | ae3430c8cb0553bbcfc097b8e36ee9e08ac32c35 | [
"Apache-2.0",
"BSD-3-Clause"
] | 19 | 2021-08-31T03:31:06.000Z | 2022-02-16T22:35:39.000Z | examples/xma/decode_only/include/xlnx_decoder.h | jmouroux/video-sdk | ae3430c8cb0553bbcfc097b8e36ee9e08ac32c35 | [
"Apache-2.0",
"BSD-3-Clause"
] | 5 | 2021-07-09T21:31:27.000Z | 2022-03-08T00:44:54.000Z | /*
* Copyright (C) 2021, Xilinx Inc - All rights reserved
* Xilinx SDAccel Media Accelerator API
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#ifndef _INCLUDED_XMDECODER_H_
#define _INCLUDED_XMDECODER_H_
#include <unistd.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <memory.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <errno.h>
#include <signal.h>
#include <xmaplugin.h>
#include <xrm.h>
#include <xma.h>
#include <xvbm.h>
#include "xlnx_dec_h264_parser.h"
#include "xlnx_dec_h265_parser.h"
#include "xlnx_dec_arg_parse.h"
#include "xlnx_dec_xma_props.h"
#include "xlnx_dec_xrm_interface.h"
#include "xlnx_app_utils.h"
#include "xlnx_dec_common.h"
#define XLNX_DEC_APP_MODULE "xlnx_decoder_app"
typedef struct XlnxDecoderInputCtx
{
struct XlnxStateInfo input_file_info;
XmaDataBuffer xbuffer;
XlnxDecFrameParseData parse_data;
} XlnxDecoderInputCtx;
typedef struct XlnxDecoderChannelCtx
{
FILE* out_fp;
size_t num_frames_to_decode;
XmaFrame* xframe;
} XlnxDecoderChannelCtx;
typedef struct XlnxDecoderCtx
{
int32_t pts;
bool is_flush_sent;
size_t num_frames_sent;
size_t num_frames_decoded;
XmaDecoderSession* xma_dec_session;
XmaDecoderProperties dec_xma_props;
XlnxDecoderProperties dec_params;
XlnxDecoderInputCtx input_ctx;
XlnxDecoderChannelCtx channel_ctx;
XlnxDecoderXrmCtx dec_xrm_ctx;
XlnxAppTimeTracker timer;
} XlnxDecoderCtx;
/*------------------------------------------------------------------------------
xlnx_dec_cleanup_ctx: Cleanup the context - free resources, close files.
Parameters:
ctx: The decoder context
------------------------------------------------------------------------------*/
void xlnx_dec_cleanup_ctx(XlnxDecoderCtx* ctx);
/*------------------------------------------------------------------------------
xlnx_dec_fpga_init: Get/allocate xrm resources, xma initialize.
Parameters:
ctx: The decoder context
Return:
DEC_APP_SUCCESS on success
DEC_APP_ERROR on error
------------------------------------------------------------------------------*/
int32_t xlnx_dec_fpga_init(XlnxDecoderCtx* ctx);
/*------------------------------------------------------------------------------
xlnx_dec_create_decoder_context: Creates the context based on user arguments. It
parses the header of the input file to get relevant codec info. This does
not create the xma session. Nor does it initialize the fpga.
Parameters:
arguments: The argument struct containing decoder param, input, output file
info
ctx: A pointer to the decoder context
Return:
DEC_APP_SUCCESS on success
------------------------------------------------------------------------------*/
int32_t xlnx_dec_create_decoder_context(XlnxDecoderArguments arguments,
XlnxDecoderCtx* ctx);
/*------------------------------------------------------------------------------
xlnx_dec_scan_next_au: Scans the next access unit from the input file into
ctx->input_ctx.input_file_info.buffer. This should not be used for initial
setup.
Parameters:
ctx: The decoder context
input_ctx.input_file_info: Contains the input file and input buffer
input_ctx.parse_data: Contains the parse data
offset: Pointer to the offset which is set by the decoder parser.
Return:
RET_SUCCESS on success
RET_EOS on end of stream
RET_EOF on end of file
------------------------------------------------------------------------------*/
int xlnx_dec_scan_next_au(XlnxDecoderCtx* ctx, int* offset);
/*------------------------------------------------------------------------------
xlnx_dec_get_buffer_from_fpga: Transfer the buffers stored on fpga into the
host.
Parameters:
ctx: The decoder context
buffer_size: A pointer to the size of the buffer.
Return:
A pointer to the host buffer of size * buffer_size
------------------------------------------------------------------------------*/
uint8_t* xlnx_dec_get_buffer_from_fpga(XlnxDecoderCtx* ctx, size_t*
buffer_size);
/*------------------------------------------------------------------------------
xlnx_dec_send_null_data: Send null data to flush the remaining frames out of
the fpga
Parameters:
ctx: The decoder context
Return:
XMA_SUCCESS on success
XMA_ERROR on error
------------------------------------------------------------------------------*/
int xlnx_dec_send_null_data(XlnxDecoderCtx* ctx);
/*------------------------------------------------------------------------------
xlnx_dec_send_data: sends data to the decoder for processing
Parameters:
ctx: ctx for the decoder.
session: Used to send data to xma plugin
input_buffer: Contains the data to send
end: amount of data to send
Return:
RET_SUCCESS on success, otherwise RET_ERROR
------------------------------------------------------------------------------*/
int xlnx_dec_send_data(XlnxDecoderCtx* ctx, int end);
/*------------------------------------------------------------------------------
xlnx_dec_print_segment_performance: Print the performance since the last
segment.
Parameters:
ctx: The decoder context
------------------------------------------------------------------------------*/
void xlnx_dec_print_segment_performance(XlnxDecoderCtx* ctx);
/*------------------------------------------------------------------------------
xlnx_dec_print_total_performance: Print the total performance of the decoder.
Parameters:
ctx: The decoder context
------------------------------------------------------------------------------*/
void xlnx_dec_print_total_performance(XlnxDecoderCtx* ctx);
#endif | 36.615819 | 81 | 0.570591 |
85ab73960556af7ed1fa81a5f637166003fb5d9c | 707 | js | JavaScript | problems/147.js | iamnapo/project-euler | 27ef2df52341f7f7f94f7d73dab852099fa72db5 | [
"MIT"
] | 3 | 2017-11-27T13:13:28.000Z | 2018-02-08T22:24:11.000Z | problems/147.js | iamnapo/ProjectEuler | f36b89a1d2642f7b96b190259a6b2a892c204b8d | [
"MIT"
] | 1 | 2020-07-20T19:15:34.000Z | 2020-07-20T19:15:51.000Z | problems/147.js | iamnapo/ProjectEuler | f36b89a1d2642f7b96b190259a6b2a892c204b8d | [
"MIT"
] | 1 | 2018-07-21T16:51:36.000Z | 2018-07-21T16:51:36.000Z | export default () => {
let count = 0;
const [M, N] = [47, 43];
for (let pX = 0; pX < N; pX += 1) {
for (let pY = 0; pY < M; pY += 1) {
for (let sN = 1; pX + sN <= N; sN += 1) {
for (let sM = 1; pY + sM <= M; sM += 1) {
count += (N - pX - sN + 1) * (M - pY - sM + 1);
}
}
}
}
for (let pX = 0.5; pX < N; pX += 0.5) {
for (let pY = 0; pY < M; pY += 0.5) {
if ((pX + pY) % 1 === 0) {
for (let sN = 0.5; pX + sN <= N; sN += 0.5) {
for (let sM = 0.5; pX - sM >= 0; sM += 0.5) {
if (pY + sN + sM > M) break;
count += (N - Math.round(pX + sN) + 1) * (M - Math.round(pY + sN + sM) + 1);
}
}
}
}
}
return `Problem 147 solution is: ${count}`;
};
| 24.37931 | 82 | 0.388967 |
604579b27b3e8245afaa02673a32e31e0f15a656 | 2,845 | html | HTML | energy-chain/src/index.html | sigmoid3/blockchain-energy | 7b7abed5127e048afc92ff1f2f5c6b2491101bdf | [
"MIT"
] | null | null | null | energy-chain/src/index.html | sigmoid3/blockchain-energy | 7b7abed5127e048afc92ff1f2f5c6b2491101bdf | [
"MIT"
] | null | null | null | energy-chain/src/index.html | sigmoid3/blockchain-energy | 7b7abed5127e048afc92ff1f2f5c6b2491101bdf | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HDU-CHAINLAB</title>
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link rel="icon" type="image/x-icon" href="public/images/icon16.ico">
<link rel="stylesheet" href="public/layui/css/layui.css">
<link rel="stylesheet" href="public/css/global.css">
</head>
<body class="site-home">
<div class="layui-header header header-index" winter>
<div class="layui-main">
<a class="logo" href="index.html">
<img src="public/images/logo.png" alt="hdu-chainlab">
</a>
<ul class="layui-nav">
<li class="layui-nav-item ">
<a href="">技术产品</a>
</li>
<li class="layui-nav-item ">
<a href="">行业动态</a>
</li>
<li class="layui-nav-item ">
<a href="signIn.html">登录</a>
</li>
<span class="layui-nav-bar" style="left: 34px; top: 55px; width: 0px; opacity:0;"></span>
</ul>
</div>
</div>
<div class="site-banner">
<div id="particles-js">
<div class="slider-fixed-text">
<h1>基于区块链的HDU-CHAINLAB管理系统</h1>
<p><font size="5">杭链实验室——让学术研究更专业</font></p>
</div>
</div>
</div>
<div class="layui-main">
<ul class="site-idea">
<li>
<fieldset class="layui-elem-field layui-field-title">
<legend>匿名账户监管</legend>
<p style="text-align: center">不可信环境下高鲁棒性、强匿名、易监管的账户管理技术</p>
</fieldset>
</li>
<li>
<fieldset class="layui-elem-field layui-field-title">
<legend>混合共识技术</legend>
<p style="text-align: center">基于Algorand的CAP博弈网络协议、高效节能的拜占庭解决方案</p>
</fieldset>
</li>
<li>
<fieldset class="layui-elem-field layui-field-title">
<legend>强化数据分析</legend>
<p style="text-align: center">面向企业级产销者的可扩展用电解决方案</p>
</fieldset>
</li>
</ul>
</div>
<div class="layui-footer footer footer-index">
<div class="layui-main">
<p>COPYRIGHT HDU-CHAINLAB © 2018</p>
</div>
</div>
<script src="public/layui/layui.js"></script>
<script src="public/particles/particles.js"></script>
<script src="public/particles/app.js"></script>
</body>
</html> | 38.972603 | 139 | 0.51529 |
71f6bb2feb581ec1b3bbd8af89935dbe07be970e | 4,741 | ts | TypeScript | src/entities/Job/manager.ts | ncomerci/decentraland-gatsby | 0d07cd1b1894f7777067f94c6140292d9546fc0d | [
"Apache-2.0"
] | 8 | 2021-04-08T15:08:28.000Z | 2022-02-24T10:34:46.000Z | src/entities/Job/manager.ts | ncomerci/decentraland-gatsby | 0d07cd1b1894f7777067f94c6140292d9546fc0d | [
"Apache-2.0"
] | 171 | 2020-03-12T18:58:01.000Z | 2022-03-31T17:41:16.000Z | src/entities/Job/manager.ts | ncomerci/decentraland-gatsby | 0d07cd1b1894f7777067f94c6140292d9546fc0d | [
"Apache-2.0"
] | 10 | 2020-10-21T11:50:44.000Z | 2022-03-29T07:46:54.000Z | import { CronJob } from 'cron'
import { v4 as uuid } from 'uuid'
import { JobSettings, TimePresets, CronTime } from './types'
import JobContext from './context'
import { createVoidPool, Pool } from '../Pool/utils'
import MemoryModel from './model/memory'
import DatabaseModel from './model/model'
import { job_manager_duration_seconds, job_manager_pool_size } from './metrics'
import logger from '../Development/logger'
import type { Job } from './job'
export default class JobManager {
memory: boolean = false
runningJobs = new Set<string>()
jobs: Map<string, Job<any>> = new Map()
crons: CronJob[] = []
pool: Pool<any>
interval: NodeJS.Timeout
initialInterval: NodeJS.Timeout
queue: Job[]
running: boolean = false
constructor(settings: JobSettings) {
const max = settings.concurrency || Infinity
this.pool = createVoidPool({ min: 0, max })
this.memory = !!settings.memory
this.cron(this.time(settings.cron || '@minutely'), () => this.check())
}
time(cronTime: CronTime): string | Date {
if (typeof cronTime === 'string' && TimePresets[cronTime]) {
return TimePresets[cronTime]
}
return cronTime
}
getModel() {
if (this.memory) {
return MemoryModel
}
return DatabaseModel
}
stats() {
return {
size: this.pool.size,
available: this.pool.available,
running: this.pool.borrowed,
pending: this.pool.pending,
ids: Array.from(this.runningJobs.values()),
}
}
define(handler: string, job: Job<any>) {
return this.use(job, { handler })
}
cron(cron: CronTime, job: Job<any>) {
return this.use(job, { cron })
}
use(
job: Job<any>,
options: Partial<{ handler: string; cron: CronTime }> = {}
) {
const handler = options.handler || job.jobName || job.name
if (this.jobs.has(handler)) {
logger.warning(`replacing job "${handler}"`, { handler, type: 'job' })
}
this.jobs.set(handler, job)
if (options.cron) {
this.crons.push(
new CronJob(this.time(options.cron), () => {
this.runJobs(uuid(), handler, {}, job)
})
)
}
return this
}
start() {
this.crons.forEach((cron) => cron.start())
this.running = true
}
stop() {
this.crons.forEach((cron) => cron.stop())
this.running = false
}
async check() {
if (!this.running) {
return
}
const jobs = await this.getModel().getPending()
const pendingJobs = jobs.filter((job) => !this.runningJobs.has(job.id))
if (pendingJobs.length) {
Promise.all(
pendingJobs.map((job) => this.run(job.id, job.name, job.payload))
)
}
}
updatePayload = async (id: string, payload: object = {}) => {
await this.getModel().updatePayload(id, payload)
}
schedule = async (
handler: string | Job<any>,
date: Date,
payload: object = {}
) => {
const name =
typeof handler === 'string' ? handler : handler.jobName || handler.name
const job = await this.getModel().schedule(uuid(), name, date, payload)
if (this.running && job.run_at.getTime() < Date.now()) {
this.run(job.id, job.name, job.payload)
}
}
async run(id: string, handler: string, payload: any): Promise<void> {
const context = { type: 'job', id, name: handler, payload }
if (!this.jobs.has(handler)) {
logger.error(`Missing job: ${handler} (id: "${id}")`, context)
return
}
if (this.runningJobs.has(id)) {
logger.log(`Job ${handler} (id: "${id}") is already running`, context)
return
}
await this.runJobs(id, handler, payload, this.jobs.get(handler)!)
}
async runJobs(
id: string,
handler: string,
payload: any,
job: Job<any>
): Promise<void> {
if (!this.running) {
return
}
const context = new JobContext(
id,
handler || job.name,
payload || {},
this.schedule,
this.updatePayload
)
if (id) {
this.runningJobs.add(id)
}
let error = 0
const labels = { job: handler || 'uknown' }
job_manager_pool_size.inc(labels)
const completeJob = job_manager_duration_seconds.startTimer(labels)
const resource = await this.pool.acquire()
try {
await job(context)
if (id) {
await this.getModel().complete(id)
}
} catch (err) {
logger.error(`Error running job "${handler}"`, {
type: 'cron',
id,
handler,
payload,
message: err.message,
stack: err.stack,
...err,
})
error = 1
}
await this.pool.release(resource)
completeJob({ error })
job_manager_pool_size.dec(labels)
if (id) {
this.runningJobs.delete(id)
}
}
}
| 23.705 | 79 | 0.596288 |
83df384c6cdc8e52d3342d4a82780ffbe72d0984 | 7,034 | rs | Rust | src/sys/component_manager/src/model/testing/memfs.rs | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 1 | 2019-04-21T18:02:26.000Z | 2019-04-21T18:02:26.000Z | src/sys/component_manager/src/model/testing/memfs.rs | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | src/sys/component_manager/src/model/testing/memfs.rs | ZVNexus/fuchsia | c5610ad15208208c98693618a79c705af935270c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
fidl_fuchsia_io::{DirectoryProxy, CLONE_FLAG_SAME_RIGHTS},
fuchsia_async as fasync,
fuchsia_zircon::{self as zx, HandleBased},
io_util,
std::os::raw,
std::ptr,
std::sync::atomic::AtomicPtr,
std::thread,
};
/// This will create a new thread on which it will run the C++ implementation of Memfs. Once
/// running, the `clone_root_hadle` function can be used to get new handles to the root of this
/// memfs. The Memfs thread will be destroyed when this struct is dropped. This memfs wrapper will
/// panic on errors.
pub struct Memfs {
root_handle: DirectoryProxy,
fs_handle: *mut MemfsFilesystem,
async_loop: *mut AsyncLoop,
}
impl Memfs {
/// Starts up a new memfs on a new thread
pub fn new() -> Memfs {
// Create async loop
let config = AsyncLoopConfig {
make_default_for_current_thread: true,
prologue: ptr::null_mut(),
epilogue: ptr::null_mut(),
data: ptr::null_mut(),
};
let mut async_loop: *mut AsyncLoop = ptr::null_mut();
let status = unsafe {
async_loop_create(
&config as *const AsyncLoopConfig,
&mut async_loop as *mut *mut AsyncLoop,
)
};
assert_eq!(zx::Status::from_raw(status), zx::Status::OK, "failed to create async loop");
let async_dispatcher = unsafe { async_loop_get_dispatcher(async_loop) };
// Create memfs with new async loop
let mut memfs_filesystem: *mut MemfsFilesystem = ptr::null_mut();
let mut root_handle: zx::sys::zx_handle_t = zx::sys::ZX_HANDLE_INVALID;
let status = unsafe {
memfs_create_filesystem(
async_dispatcher,
&mut memfs_filesystem as *mut *mut MemfsFilesystem,
&mut root_handle as *mut zx::sys::zx_handle_t,
)
};
assert_eq!(zx::Status::from_raw(status), zx::Status::OK, "failed to create memfs");
// Put it in a mutex so Rust is willing to move it between threads
let mut async_loop_ptr = AtomicPtr::new(async_loop);
thread::spawn(move || {
unsafe { async_loop_run(*async_loop_ptr.get_mut(), zx::sys::ZX_TIME_INFINITE, false) };
});
Memfs {
root_handle: DirectoryProxy::new(
fasync::Channel::from_channel(zx::Channel::from_handle(unsafe {
zx::Handle::from_raw(root_handle)
}))
.unwrap(),
),
fs_handle: memfs_filesystem,
async_loop,
}
}
/// Returns a new handle to the root directory of this memfs
pub fn clone_root_handle(&self) -> DirectoryProxy {
io_util::clone_directory(&self.root_handle, CLONE_FLAG_SAME_RIGHTS)
.expect("failed to clone root handle")
}
}
impl Drop for Memfs {
/// Tears down memfs, waits for memfs to be torn down, and then tears down the async loop that
/// was running memfs
fn drop(&mut self) {
let mut sync = SyncCompletion::new();
unsafe {
memfs_free_filesystem(self.fs_handle, &mut sync as *mut SyncCompletion);
let status =
sync_completion_wait(&mut sync as *mut SyncCompletion, zx::sys::ZX_TIME_INFINITE);
assert_eq!(
zx::Status::from_raw(status),
zx::Status::OK,
"sync_completion_wait returned with non-ok status"
);
async_loop_destroy(self.async_loop);
}
}
}
type MemfsFilesystem = raw::c_void;
#[link(name = "memfs")]
extern "C" {
fn memfs_create_filesystem(
dispatcher: *mut AsyncDispatcher,
out_fs: *mut *mut MemfsFilesystem,
out_root: *mut zx::sys::zx_handle_t,
) -> zx::sys::zx_status_t;
fn memfs_free_filesystem(fs: *mut MemfsFilesystem, unmounted: *mut SyncCompletion);
}
#[repr(C)]
#[derive(Debug, Clone)]
struct AsyncLoopConfig {
make_default_for_current_thread: bool,
prologue: *mut raw::c_void,
epilogue: *mut raw::c_void,
data: *mut raw::c_void,
}
type AsyncLoop = raw::c_void;
#[link(name = "async-loop")]
extern "C" {
fn async_loop_create(
config: *const AsyncLoopConfig,
out_loop: *mut *mut AsyncLoop,
) -> zx::sys::zx_status_t;
fn async_loop_get_dispatcher(loop_: *mut AsyncLoop) -> *mut AsyncDispatcher;
fn async_loop_destroy(loop_: *mut AsyncLoop);
fn async_loop_run(
loop_: *mut AsyncLoop,
deadline: zx::sys::zx_time_t,
once: bool,
) -> zx::sys::zx_status_t;
}
type AsyncDispatcher = raw::c_void;
// This `#[allow(dead_code)]` is load bearing because without it the program will fail to link
// against the following symbols, which are needed by the async-loop library.
#[allow(dead_code)]
#[link(name = "async-default")]
#[link(name = "async")]
extern "C" {
fn async_get_default_dispatcher() -> *mut AsyncDispatcher;
fn async_set_default_dispatcher(dispatcher: *mut AsyncDispatcher);
}
#[repr(C)]
#[derive(Debug, Clone)]
struct SyncCompletion {
futex: zx::sys::zx_futex_t,
}
impl SyncCompletion {
fn new() -> SyncCompletion {
SyncCompletion { futex: 0 }
}
}
#[link(name = "sync")]
extern "C" {
fn sync_completion_wait(
completion: *mut SyncCompletion,
timeout: zx::sys::zx_duration_t,
) -> zx::sys::zx_status_t;
}
#[cfg(test)]
mod tests {
use {
super::*,
fidl_fuchsia_io::{OPEN_FLAG_CREATE, OPEN_RIGHT_READABLE, OPEN_RIGHT_WRITABLE},
std::path::PathBuf,
};
#[fasync::run_singlethreaded(test)]
async fn use_a_file() {
let memfs = Memfs::new();
let root_of_memfs = memfs.clone_root_handle();
let file_name = PathBuf::from("myfile");
let file_contents = "hippos are just really neat".to_string();
// Create a file and write some contents
let file_proxy =
io_util::open_file(&root_of_memfs, &file_name, OPEN_RIGHT_WRITABLE | OPEN_FLAG_CREATE)
.expect("failed to open file");
let (s, _) =
await!(file_proxy.write(&mut file_contents.clone().as_bytes().to_vec().drain(..)))
.expect("failed to write to file");
assert_eq!(zx::Status::OK, zx::Status::from_raw(s));
let s = await!(file_proxy.close()).expect("failed to close file");
assert_eq!(zx::Status::OK, zx::Status::from_raw(s));
// Open the same file and read the contents back
let file_proxy =
io_util::open_file(&root_of_memfs, &file_name, OPEN_RIGHT_READABLE | OPEN_FLAG_CREATE)
.expect("failed to open file");
let read_contents = await!(io_util::read_file(&file_proxy)).expect("failed to read file");
assert_eq!(file_contents, read_contents);
//drop(memfs);
}
}
| 33.655502 | 99 | 0.621979 |
e73cd242869367b354ad04e77fe84776e6687894 | 5,297 | js | JavaScript | src/components/about-page/compliance-dashboard.component.test.js | ghhifr6v/code-gov-front-end | d25c2cc938371ff1e9cbc83d449f6feccae2a99b | [
"CC0-1.0"
] | null | null | null | src/components/about-page/compliance-dashboard.component.test.js | ghhifr6v/code-gov-front-end | d25c2cc938371ff1e9cbc83d449f6feccae2a99b | [
"CC0-1.0"
] | null | null | null | src/components/about-page/compliance-dashboard.component.test.js | ghhifr6v/code-gov-front-end | d25c2cc938371ff1e9cbc83d449f6feccae2a99b | [
"CC0-1.0"
] | null | null | null | import React from 'react'
import { shallow } from 'enzyme'
import { config } from 'components/about-page/compliance-dashboard.container'
import ComplianceDashboard from 'components/about-page/compliance-dashboard.component'
const props = {
config,
data: [
{
acronym: 'USDA',
img: '/assets/img/logos/agencies/USDA-50x50.png',
name: 'Department of Agriculture',
requirements: {
overall: 0.25,
sub: {
agencyWidePolicy: 0.75,
inventoryRequirement: 0,
openSourceRequirement: 0,
schemaFormat: 0.5
}
}
}
]
}
let wrapper
describe('components - ComplianceDashboard', () => {
beforeEach(() => {
wrapper = shallow(<ComplianceDashboard {...props} />)
})
it('should render correctly', () => {
expect(wrapper).toMatchSnapshot()
})
it('should render proper number of cards', () => {
wrapper.setProps({
data: [
...props.data,
{
acronym: 'DOD',
img: '/assets/img/logos/agencies/DOD-50x50.png',
name: 'Department of Defense',
requirements: {
overall: 0,
sub: {
agencyWidePolicy: 0,
inventoryRequirement: 0,
openSourceRequirement: 0,
schemaFormat: 0.5
}
}
}
]
})
expect(wrapper.find('.card')).toHaveLength(2)
})
describe('card', () => {
it('should render an image', () => {
expect(wrapper.find('img').prop('alt')).toEqual('Department of Agriculture logo')
expect(wrapper.find('img').prop('src')).toEqual('/assets/img/logos/agencies/USDA-50x50.png')
})
it('should render agency name', () => {
expect(wrapper.find('h3').text()).toEqual('Department of Agriculture')
})
it('should render proper number of requirement lines', () => {
expect(wrapper.find('.req')).toHaveLength(config.text.length)
})
it('should render properly for compliant status', () => {
wrapper.setProps({
data: [
{
...props.data[0],
requirements: {
...props.data[0].requirements,
overall: 1
}
}
]
})
expect(wrapper.find('h4').text()).toEqual('Fully compliant')
expect(wrapper.find('h4').prop('className')).toContain('compliant')
expect(wrapper.find('.card').prop('className')).toContain('compliant')
})
it('should render properly for partial status', () => {
wrapper.setProps({
data: [
{
...props.data[0],
requirements: {
...props.data[0].requirements,
overall: 0.25
}
}
]
})
expect(wrapper.find('h4').text()).toEqual('Partially compliant')
expect(wrapper.find('h4').prop('className')).toContain('partial')
expect(wrapper.find('.card').prop('className')).toContain('partial')
})
it('should render properly for noncompliant status', () => {
wrapper.setProps({
data: [
{
...props.data[0],
requirements: {
...props.data[0].requirements,
overall: 0
}
}
]
})
expect(wrapper.find('h4').text()).toEqual('Non-compliant')
expect(wrapper.find('h4').prop('className')).toContain('noncompliant')
expect(wrapper.find('.card').prop('className')).toContain('noncompliant')
})
it('should render requirement properly for compliant status', () => {
wrapper.setProps({
data: [
{
...props.data[0],
requirements: {
...props.data[0].requirements,
sub: {
...props.data[0].requirements.sub,
agencyWidePolicy: 1
}
}
}
]
})
const element = wrapper.find('.req').first()
expect(element.prop('className')).toContain('compliant')
expect(element.text()).toEqual(config.text[0].variants.compliant)
})
it('should render requirement properly for partial status', () => {
wrapper.setProps({
data: [
{
...props.data[0],
requirements: {
...props.data[0].requirements,
sub: {
...props.data[0].requirements.sub,
agencyWidePolicy: 0.25
}
}
}
]
})
const element = wrapper.find('.req').first()
expect(element.prop('className')).toContain('partial')
expect(element.text()).toEqual(config.text[0].variants.partial)
})
it('should render requirement properly for noncompliant status', () => {
wrapper.setProps({
data: [
{
...props.data[0],
requirements: {
...props.data[0].requirements,
sub: {
...props.data[0].requirements.sub,
agencyWidePolicy: 0
}
}
}
]
})
const element = wrapper.find('.req').first()
expect(element.prop('className')).toContain('noncompliant')
expect(element.text()).toEqual(config.text[0].variants.noncompliant)
})
})
})
| 28.026455 | 98 | 0.520483 |
744dfbd71771fee9b92d83ba54bf72c0991ae606 | 750 | h | C | ports/zephyr/ncs/include/memfault/nrfconnect_port/http.h | elliot-wdtl/memfault-firmware-sdk | 99f20240d93792391583b46b7a74e3eb3046295c | [
"BSD-3-Clause"
] | 79 | 2019-07-05T15:53:31.000Z | 2022-03-25T13:17:19.000Z | ports/zephyr/ncs/include/memfault/nrfconnect_port/http.h | elliot-wdtl/memfault-firmware-sdk | 99f20240d93792391583b46b7a74e3eb3046295c | [
"BSD-3-Clause"
] | 17 | 2019-11-04T15:35:54.000Z | 2022-03-17T18:43:41.000Z | ports/zephyr/ncs/include/memfault/nrfconnect_port/http.h | elliot-wdtl/memfault-firmware-sdk | 99f20240d93792391583b46b7a74e3eb3046295c | [
"BSD-3-Clause"
] | 41 | 2019-07-07T23:18:32.000Z | 2022-03-22T09:31:41.000Z | #pragma once
//! @file
//!
//! Copyright (c) Memfault, Inc.
//! See License.txt for details
//!
//! @brief
//! Zephyr specific http utility for interfacing with Memfault HTTP utilities
#include <stddef.h>
#include <stdbool.h>
#include "memfault/ports/zephyr/http.h"
#ifdef __cplusplus
extern "C" {
#endif
//! memfault_nrfconnect_port_* names are now deprecated.
//!
//! This is a temporary change to map to the appropriate name but will be removed in
//! future releases
#define memfault_nrfconnect_port_install_root_certs memfault_zephyr_port_install_root_certs
#define memfault_nrfconnect_port_post_data memfault_zephyr_port_post_data
#define memfault_nrfconnect_port_ota_update memfault_zephyr_port_ota_update
#ifdef __cplusplus
}
#endif
| 23.4375 | 91 | 0.788 |
16c9c23745f990a3e1fbe502323b532fab463a56 | 161 | tsx | TypeScript | client/src/components/NotFound/NotFound.tsx | DesertoRaposa/The-social-life-of-Pets | f25f8ccdec0529a6585889d059ef8dbc1bf335be | [
"MIT"
] | null | null | null | client/src/components/NotFound/NotFound.tsx | DesertoRaposa/The-social-life-of-Pets | f25f8ccdec0529a6585889d059ef8dbc1bf335be | [
"MIT"
] | null | null | null | client/src/components/NotFound/NotFound.tsx | DesertoRaposa/The-social-life-of-Pets | f25f8ccdec0529a6585889d059ef8dbc1bf335be | [
"MIT"
] | null | null | null | import React from 'react';
const NotFound = (): JSX.Element => (
<div className="contaier">
<h1> Page Not Found</h1>
</div>
);
export default NotFound; | 17.888889 | 37 | 0.639752 |
18c5585fc97e0c50441a64f466bd2b63603dc352 | 454 | css | CSS | deploy/files/terms.css | duhnnie/3-dreams-of-black | 15aded97f57a82e5a4c95c4e74bcd603b3fc6e1e | [
"Apache-2.0"
] | 475 | 2015-01-02T07:49:46.000Z | 2022-03-17T04:01:47.000Z | deploy/files/terms.css | duhnnie/3-dreams-of-black | 15aded97f57a82e5a4c95c4e74bcd603b3fc6e1e | [
"Apache-2.0"
] | 3 | 2015-03-06T10:51:03.000Z | 2019-09-10T19:39:39.000Z | deploy/files/terms.css | duhnnie/3-dreams-of-black | 15aded97f57a82e5a4c95c4e74bcd603b3fc6e1e | [
"Apache-2.0"
] | 130 | 2015-01-15T02:08:21.000Z | 2021-12-20T19:15:22.000Z | * {
margin: 0;
padding: 0;
}
body {
width: 300px;
margin: 0 auto;
font: 500 11px/20px "FuturaBT-Medium", Arial, sans-serif;
background: url('/files/footer/clouds-trans.png') center;
background-attachment: fixed;
}
h1, h2, h3, h4, h5, h6 {
text-align: center;
}
a {
color: #000;
}
li, p {
margin: 7.5px 0;
}
ol ul, ol ol, ul ul, ul ol {
padding: 0 0 0 15px;
}
ul li {
list-style: none;
}
blockquote {
padding: 5px 15px;
} | 12.611111 | 59 | 0.601322 |
e8accb828752dc6d9ad9ded46902a3d69b86dc4b | 12,093 | swift | Swift | App/Feed/FeedViewController.swift | anosidium/Hackers | 7b9fd6785d5a63869afd7ffa13cab7d6bf0cfea0 | [
"MIT"
] | null | null | null | App/Feed/FeedViewController.swift | anosidium/Hackers | 7b9fd6785d5a63869afd7ffa13cab7d6bf0cfea0 | [
"MIT"
] | null | null | null | App/Feed/FeedViewController.swift | anosidium/Hackers | 7b9fd6785d5a63869afd7ffa13cab7d6bf0cfea0 | [
"MIT"
] | null | null | null | //
// FeedViewController.swift
// Hackers
//
// Created by Weiran Zhang on 07/06/2014.
// Copyright (c) 2014 Weiran Zhang. All rights reserved.
//
import Foundation
import UIKit
import SwiftUI
import SafariServices
import PromiseKit
import Loaf
import SwipeCellKit
class FeedViewController: UIViewController {
var authenticationUIService: AuthenticationUIService?
var swipeCellKitActions: SwipeCellKitActions?
private var posts = [Post]()
private var dataSource: UITableViewDiffableDataSource<Section, Post>?
var postType: PostType = .news
@IBOutlet var tableView: UITableView!
private var peekedIndexPath: IndexPath?
private var pageIndex = 1
private var isFetching = false
private var refreshToken: NotificationToken?
override func viewDidLoad() {
super.viewDidLoad()
registerForPreviewing(with: self, sourceView: tableView)
setupTheming()
setupNotificationObservers()
setupTableView()
setupTitle()
fetchPosts()
showOnboarding()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if UIScreen.main.traitCollection.horizontalSizeClass == .compact {
// only deselect in compact size where the view isn't split
smoothlyDeselectRows()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowCommentsSegue",
let navigationController = segue.destination as? UINavigationController,
let commentsViewController = navigationController.viewControllers.first as? CommentsViewController,
let indexPath = tableView.indexPathForSelectedRow {
commentsViewController.post = posts[indexPath.row]
}
}
private func navigateToComments() {
performSegue(withIdentifier: "ShowCommentsSegue", sender: self)
}
private func setupTableView() {
tableView.refreshControl?.addTarget(
self,
action: #selector(fetchPostsWithReset),
for: UIControl.Event.valueChanged
)
tableView.tableFooterView = UIView(frame: .zero) // remove cell separators on empty table
dataSource = makeDataSource()
tableView.dataSource = dataSource
tableView.backgroundView = TableViewBackgroundView.loadingBackgroundView()
}
private func setupTitle() {
let button = TitleButton()
button.setTitleText(postType.title)
button.setupMenu()
button.handler = { postType in
self.postType = postType
// haptic feedback
let generator = UINotificationFeedbackGenerator()
generator.prepare()
generator.notificationOccurred(.success)
// update title
self.setupTitle()
// reset tableview
self.posts = [Post]()
self.update(with: self.posts, animate: false)
self.fetchPostsWithReset()
}
navigationItem.titleView = button
title = postType.title
}
private func showOnboarding() {
if let onboardingVC = OnboardingService.onboardingViewController() {
present(onboardingVC, animated: true)
}
}
private func setupNotificationObservers() {
refreshToken = NotificationCenter.default.observe(
name: Notification.Name.refreshRequired,
object: nil,
queue: .main) { [weak self] _ in
self?.fetchPostsWithReset()
}
}
func smoothlyDeselectRows() {
// Get the initially selected index paths, if any
let selectedIndexPaths = tableView.indexPathsForSelectedRows ?? []
// Grab the transition coordinator responsible for the current transition
if let coordinator = transitionCoordinator {
// Animate alongside the master view controller's view
coordinator.animateAlongsideTransition(in: parent?.view, animation: { context in
// Deselect the cells, with animations enabled if this is an animated transition
selectedIndexPaths.forEach {
self.tableView.deselectRow(at: $0, animated: context.isAnimated)
}
}, completion: { context in
// If the transition was cancel, reselect the rows that were selected before,
// so they are still selected the next time the same animation is triggered
if context.isCancelled {
selectedIndexPaths.forEach {
self.tableView.selectRow(at: $0, animated: false, scrollPosition: .none)
}
}
})
} else { // If this isn't a transition coordinator, just deselect the rows without animating
selectedIndexPaths.forEach {
self.tableView.deselectRow(at: $0, animated: false)
}
}
}
@IBAction func showNewSettings(_ sender: Any) {
let settingsStore = SettingsStore()
let hostingVC = UIHostingController(
rootView: SettingsView()
.environmentObject(settingsStore))
present(hostingVC, animated: true)
}
}
extension FeedViewController { // post fetching
@objc private func fetchPosts() {
guard !isFetching else { return }
isFetching = true
let isFirstPage = pageIndex == 1
firstly {
HackersKit.shared.getPosts(type: postType, page: pageIndex)
}.done { posts in
if isFirstPage {
self.posts = [Post]()
}
self.posts.append(contentsOf: posts)
self.update(with: self.posts, animate: !isFirstPage)
}.catch { error in
Loaf("Error connecting to Hacker News", state: .error, sender: self).show()
}.finally {
self.isFetching = false
self.tableView.refreshControl?.endRefreshing()
self.pageIndex += 1
}
}
@objc private func fetchPostsWithReset() {
pageIndex = 1
fetchPosts()
}
}
extension FeedViewController { // table view data source
enum Section: CaseIterable {
case main
}
func makeDataSource() -> UITableViewDiffableDataSource<Section, Post> {
let reuseIdentifier = "PostCell"
return UITableViewDiffableDataSource(tableView: tableView) { (tableView, indexPath, post) in
guard let cell = tableView.dequeueReusableCell(
withIdentifier: reuseIdentifier,
for: indexPath
) as? PostCell else { return nil }
cell.postDelegate = self
cell.delegate = self
cell.postTitleView.post = post
cell.setImageWithPlaceholder(
url: UserDefaults.standard.showThumbnails ? post.url : nil
)
return cell
}
}
func update(with posts: [Post], animate: Bool = true) {
var snapshot = NSDiffableDataSourceSnapshot<Section, Post>()
snapshot.appendSections(Section.allCases)
snapshot.appendItems(posts)
self.dataSource?.apply(snapshot, animatingDifferences: animate)
}
}
extension FeedViewController: UITableViewDelegate { // table view delegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let buffer: CGFloat = 200
let scrollPosition = scrollView.contentOffset.y
let bottomPosition = scrollView.contentSize.height - scrollView.frame.size.height
if scrollPosition > bottomPosition - buffer {
fetchPosts()
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let post = posts[indexPath.row]
if postType == .jobs {
didPressLinkButton(post)
} else {
navigateToComments()
}
}
}
extension FeedViewController: SwipeTableViewCellDelegate { // swipe cell delegate
func tableView(_ tableView: UITableView,
editActionsForRowAt indexPath: IndexPath,
for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
let post = posts[indexPath.row]
guard orientation == .left,
post.postType != .jobs else {
return nil
}
return swipeCellKitActions?.voteAction(post: post, tableView: tableView,
indexPath: indexPath, viewController: self)
}
func tableView(_ tableView: UITableView,
editActionsOptionsForRowAt indexPath: IndexPath,
for orientation: SwipeActionsOrientation) -> SwipeOptions {
let expansionStyle = SwipeExpansionStyle(target: .percentage(0.2),
elasticOverscroll: false,
completionAnimation: .bounce)
var options = SwipeOptions()
options.expansionStyle = expansionStyle
options.expansionDelegate = BounceExpansion()
options.transitionStyle = .drag
return options
}
}
extension FeedViewController: PostCellDelegate { // cell actions
func didPressLinkButton(_ post: Post) {
openURL(url: post.url) {
if let safariViewController = SFSafariViewController.instance(
for: post.url,
previewActionItemsDelegate: self
) {
navigationController?.present(safariViewController, animated: true)
}
}
}
func didTapThumbnail(_ sender: Any) {
guard let tapGestureRecognizer = sender as? UITapGestureRecognizer else { return }
let point = tapGestureRecognizer.location(in: tableView)
if let indexPath = tableView.indexPathForRow(at: point) {
let post = posts[indexPath.row]
didPressLinkButton(post)
}
}
}
extension FeedViewController: UIViewControllerPreviewingDelegate, SFSafariViewControllerPreviewActionItemsDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing,
viewControllerForLocation location: CGPoint) -> UIViewController? {
guard
let indexPath = tableView.indexPathForRow(at: location),
posts.count > indexPath.row else {
return nil
}
let post = posts[indexPath.row]
peekedIndexPath = indexPath
previewingContext.sourceRect = tableView.rectForRow(at: indexPath)
return SFSafariViewController.instance(for: post.url, previewActionItemsDelegate: self)
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing,
commit viewControllerToCommit: UIViewController) {
present(viewControllerToCommit, animated: true, completion: nil)
}
func safariViewControllerPreviewActionItems(_ controller: SFSafariViewController) -> [UIPreviewActionItem] {
guard let indexPath = peekedIndexPath else {
return [UIPreviewActionItem]()
}
let post = posts[indexPath.row]
let commentsPreviewActionTitle = post.commentsCount > 0 ?
"View \(post.commentsCount) comments" : "View comments"
let viewCommentsPreviewAction =
UIPreviewAction(title: commentsPreviewActionTitle,
style: .default) { [unowned self, indexPath = indexPath] (_, _) -> Void in
self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
self.navigateToComments()
}
return [viewCommentsPreviewAction]
}
}
extension FeedViewController: Themed {
func applyTheme(_ theme: AppTheme) {
view.backgroundColor = theme.backgroundColor
tableView.backgroundColor = theme.backgroundColor
tableView.separatorColor = theme.separatorColor
tableView.refreshControl?.tintColor = theme.appTintColor
overrideUserInterfaceStyle = theme.userInterfaceStyle
}
}
| 35.672566 | 116 | 0.632101 |
7f45984e87a4a7b850ca1f6d3e4bef171f29049c | 4,949 | rs | Rust | advent2018/src/day8.rs | kesyog/adventofrust | ee35652a5f2a2cead8781e2b0e405282f77973d9 | [
"Apache-2.0"
] | null | null | null | advent2018/src/day8.rs | kesyog/adventofrust | ee35652a5f2a2cead8781e2b0e405282f77973d9 | [
"Apache-2.0"
] | null | null | null | advent2018/src/day8.rs | kesyog/adventofrust | ee35652a5f2a2cead8781e2b0e405282f77973d9 | [
"Apache-2.0"
] | null | null | null | //! Solution to [AoC YEAR Day DAY](https://adventofcode.com/YEAR/day/DAY)
mod part1 {
enum ParseState {
Header,
Metadata,
}
/// Minimally parse the input to find the metadata fields
/// Return the sum of all metadata fields
pub fn solve(tree: &[i32]) -> i32 {
let mut stack = vec![ParseState::Header];
let mut metadata_sum = 0;
let mut tree = tree.iter();
loop {
match stack.pop() {
Some(ParseState::Header) => {
let n_child_nodes = *tree.next().unwrap();
let n_metadata = *tree.next().unwrap();
for _ in 0..n_metadata {
stack.push(ParseState::Metadata);
}
for _ in 0..n_child_nodes {
stack.push(ParseState::Header);
}
}
Some(ParseState::Metadata) => metadata_sum += tree.next().unwrap(),
None => break,
}
}
metadata_sum
}
}
mod part2 {
/// A node in the tree structure defined in the problem.
#[derive(Default, Debug)]
pub struct Node {
/// The children of the given node, given as indices into some other data structure
children: Vec<usize>,
/// Metadata attached to the given node
metadata: Vec<i32>,
}
/// Calculate the "value" of the node at index idx using the definition in the problem
/// statement. The root node is at index 0.
fn value(tree: &[Node], idx: usize) -> i32 {
let head = &tree[idx];
if head.children.is_empty() {
return head.metadata.iter().sum();
}
let mut sum = 0;
for child_idx in &head.metadata {
// Need to subtract 1 as the data provided is 1-indexed
let child_idx = usize::try_from(*child_idx).unwrap() - 1;
if let Some(node) = head.children.get(child_idx) {
sum += value(tree, *node);
}
}
sum
}
enum ParseState {
/// The parser is at the start of a header belonging to a node at the given index
Header(usize),
/// The parser is at a single piece of metadata belonging to a node at the given index
Metadata(usize),
}
/// Parse the input into a tree represented by a `Vec<Node>`
pub fn parse_nodes(tree: &[i32]) -> Vec<Node> {
let mut nodes = vec![Node::default()];
let mut stack = vec![ParseState::Header(0)];
let mut tree = tree.iter();
loop {
match stack.pop() {
Some(ParseState::Header(idx)) => {
let n_child_nodes = *tree.next().unwrap();
let n_metadata = *tree.next().unwrap();
for _ in 0..n_metadata {
stack.push(ParseState::Metadata(idx));
}
for _ in 0..n_child_nodes {
nodes.push(Node::default());
let child_idx = nodes.len() - 1;
nodes[idx].children.push(child_idx);
stack.push(ParseState::Header(child_idx));
}
// Because of the LIFO nature of the stack, the children end up in reverse
// order
nodes[idx].children.reverse();
}
Some(ParseState::Metadata(idx)) => nodes[idx].metadata.push(*tree.next().unwrap()),
None => break,
}
}
nodes
}
pub fn part1(tree: &[Node]) -> i32 {
tree.iter().flat_map(|node| &node.metadata).sum()
}
pub fn part2(tree: &[Node]) -> i32 {
value(tree, 0)
}
}
fn parse_input(input: &str) -> Vec<i32> {
input
.trim()
.split_whitespace()
.map(|i| i.parse::<i32>().unwrap())
.collect()
}
fn main() {
let input = include_str!("../inputs/day8.txt");
let input = parse_input(input);
let tree = part2::parse_nodes(&input);
// Part 1 is solved in two different ways. `part1::solve` is simpler in isolation, but
// `part2::part1` is simpler once we've already parsed the tree structure out of the input for
// part 2.
println!("Part 1: {}", part1::solve(&input));
println!("Part 1: {}", part2::part1(&tree));
println!("Part 2: {}", part2::part2(&tree));
}
#[cfg(test)]
mod tests {
use super::*;
const TEST_INPUT: &str = r#"
2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2
"#;
#[test]
fn given_part1_input() {
let input = parse_input(TEST_INPUT);
assert_eq!(part1::solve(&input), 138);
}
#[test]
fn given_part2_input() {
let input = parse_input(TEST_INPUT);
let tree = part2::parse_nodes(&input);
assert_eq!(part2::part1(&tree), 138);
assert_eq!(part2::part2(&tree), 66);
}
}
| 32.346405 | 99 | 0.515862 |
746cbece16520bddb049eb23d8fa6f7f432ae0dd | 2,693 | h | C | compiler/semantic/sym_tbl.h | Engineev/mocker | 9d3006419ea04683d0b2e6f5ccd21d464e6704e3 | [
"MIT"
] | 14 | 2019-02-18T01:41:50.000Z | 2021-08-11T00:27:51.000Z | compiler/semantic/sym_tbl.h | Engineev/mocker | 9d3006419ea04683d0b2e6f5ccd21d464e6704e3 | [
"MIT"
] | null | null | null | compiler/semantic/sym_tbl.h | Engineev/mocker | 9d3006419ea04683d0b2e6f5ccd21d464e6704e3 | [
"MIT"
] | 1 | 2021-08-11T00:28:39.000Z | 2021-08-11T00:28:39.000Z | #ifndef MOCKER_SYM_TBL_H
#define MOCKER_SYM_TBL_H
#include <memory>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
#include "ast/ast_node.h"
#include "ast/visitor.h"
namespace mocker {
class ScopeID {
public:
ScopeID() = default;
ScopeID(const ScopeID &) = default;
ScopeID(ScopeID &&) noexcept = default;
ScopeID &operator=(const ScopeID &) = default;
ScopeID &operator=(ScopeID &&) noexcept = default;
~ScopeID() = default;
bool operator==(const ScopeID &rhs) const {
if (rhs.ids.size() != ids.size())
return false;
for (std::size_t i = 0; i < ids.size(); ++i)
if (ids[i] != rhs.ids[i])
return false;
return true;
}
bool operator!=(const ScopeID &rhs) const { return !(*this == rhs); }
std::string fmt() const {
std::string res;
for (std::size_t id : ids)
res += std::to_string(id) + "-";
res.pop_back();
return res;
}
private:
friend class SymTbl;
ScopeID(std::vector<std::size_t> ids) : ids(std::move(ids)) {}
std::vector<std::size_t> ids;
};
class SymTbl {
public:
SymTbl();
SymTbl(const SymTbl &) = delete;
SymTbl(SymTbl &&) noexcept = default;
SymTbl &operator=(const SymTbl &) = delete;
SymTbl &operator=(SymTbl &&) noexcept = default;
~SymTbl() = default;
// return the scope ID of the global scope
ScopeID global() const;
// Create a subscope in the scope provided and return the ID of the new scope.
// If the scope provided does not exists, throw std::out_of_range
ScopeID createSubscope(const ScopeID &pntID);
// Try to find the given symbol in the given scope AND it parent scopes.
// If the symbol does not exist, then the returned shared_ptr is empty.
std::shared_ptr<ast::Declaration> lookUp(const ScopeID &scopeID,
const std::string &identifier) const;
// If the identifier has already exists in the CURRENT scope, no addition will
// be perform and the return value is false. Otherwise add the symbol into the
// current scope, symbols from outer scopes may be covered, and return true.
bool addSymbol(const ScopeID &scopeID, const std::string &identifier,
std::shared_ptr<ast::Declaration> decl);
private:
struct Scope {
explicit Scope(const std::shared_ptr<Scope> &pnt);
std::unordered_map<std::string, std::shared_ptr<ast::Declaration>> syms;
std::vector<std::shared_ptr<Scope>> subscopes;
std::weak_ptr<Scope> pnt;
};
// Just a helper function. Some asserts are performed.
std::shared_ptr<Scope> getScope(const ScopeID &id) const;
std::shared_ptr<Scope> root;
};
} // namespace mocker
#endif // MOCKER_SYM_TBL_H
| 28.648936 | 80 | 0.6684 |
ddf400ac49b2b8ada2f9c0557122c8602c23a4af | 921 | h | C | LSUtils/Category/UIView+LSFrame.h | SandroLiu/SAKit | 3162d59da8404f0f210064f82bc0441a0bd24e1c | [
"MIT"
] | null | null | null | LSUtils/Category/UIView+LSFrame.h | SandroLiu/SAKit | 3162d59da8404f0f210064f82bc0441a0bd24e1c | [
"MIT"
] | null | null | null | LSUtils/Category/UIView+LSFrame.h | SandroLiu/SAKit | 3162d59da8404f0f210064f82bc0441a0bd24e1c | [
"MIT"
] | null | null | null | //
// UIView+LSFrame.h
// LSUtilsDemo
//
// Created by 刘帅 on 2018/12/25.
// Copyright © 2018年 刘帅. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIView (LSFrame)
/**
* x轴坐标
*/
@property (nonatomic, assign) CGFloat frame_x;
/**
* y轴坐标
*/
@property (nonatomic, assign) CGFloat frame_y;
/**
* x轴最大值 x+width
*/
@property (nonatomic, assign) CGFloat frame_maxX;
/**
* y轴最大值 y+height
*/
@property (nonatomic, assign) CGFloat frame_maxY;
/**
* 原点
*/
@property (nonatomic, assign) CGPoint frame_origin;
/**
* 中心点x
*/
@property (nonatomic, assign) CGFloat frame_centerX;
/**
* 中心点y
*/
@property (nonatomic, assign) CGFloat frame_centerY;
/**
* 宽
*/
@property (nonatomic, assign) CGFloat frame_width;
/**
* 高
*/
@property (nonatomic, assign) CGFloat frame_height;
/**
* 尺寸
*/
@property (nonatomic, assign) CGSize frame_size;
@end
NS_ASSUME_NONNULL_END
| 14.854839 | 52 | 0.666667 |
511167c28b6b0dc9dc706f89e11d07a4b29a9ed2 | 2,041 | h | C | drace-client/include/symbol/Symbols.h | siemens/drace | 2679067783b1d8f39e4c370cd72a7626ebf5f8e8 | [
"MIT",
"MIT-0",
"BSD-3-Clause"
] | 32 | 2019-02-19T11:37:14.000Z | 2022-01-07T16:09:27.000Z | drace-client/include/symbol/Symbols.h | siemens/drace | 2679067783b1d8f39e4c370cd72a7626ebf5f8e8 | [
"MIT",
"MIT-0",
"BSD-3-Clause"
] | 86 | 2019-03-29T08:57:37.000Z | 2021-06-30T16:13:06.000Z | drace-client/include/symbol/Symbols.h | siemens/drace | 2679067783b1d8f39e4c370cd72a7626ebf5f8e8 | [
"MIT",
"MIT-0",
"BSD-3-Clause"
] | 4 | 2019-04-16T18:35:02.000Z | 2021-06-17T16:49:48.000Z | #pragma once
/*
* DRace, a dynamic data race detector
*
* Copyright 2018 Siemens AG
*
* Authors:
* Felix Moessbauer <felix.moessbauer@siemens.com>
*
* SPDX-License-Identifier: MIT
*/
#include <sstream>
#include <string>
#ifndef TESTING
#include <dr_api.h>
#include <drsyms.h>
#endif
#include "symbol/SymbolLocation.h"
#ifdef TESTING
class drsym_info_t {};
class module_data_t;
#endif
namespace drace {
namespace symbol {
/// Symbol Access Lib Functions
class Symbols {
/* Maximum distance between a pc and the first found symbol */
static constexpr std::ptrdiff_t max_distance = 32;
/* Maximum length of file pathes and sym names */
static constexpr int buffer_size = 256;
drsym_info_t syminfo{};
public:
explicit Symbols();
~Symbols();
/** Get last known symbol near the given location
* Internally a reverse-search is performed starting at the given pc.
* When the first symbol lookup was successful, the search is stopped.
*
* \warning If no debug information is available the returned symbol might
* be misleading, as the search stops at the first imported or
*exported function.
*/
std::string get_bb_symbol(app_pc pc);
/** Get last known symbol including as much information as possible.
* Internally a reverse-search is performed starting at the given pc.
* When the first symbol lookup was successful, the search is stopped.
*
* \warning If no debug information is available the returned symbol might
* be misleading, as the search stops at the first imported or
* exported function.
*/
SymbolLocation get_symbol_info(app_pc pc);
/** Returns true if debug info is available for this module
* Returns false if only exports are available
*/
bool debug_info_available(const module_data_t *mod) const;
private:
/** Create global symbol lookup data structures */
void create_drsym_info();
/** Cleanup global symbol lookup data structures */
void free_drsmy_info();
};
} // namespace symbol
} // namespace drace
| 26.166667 | 76 | 0.718275 |
f36bbd47db78394b814632e201f48a2d4fe4e452 | 230 | sql | SQL | sql/basic_select/weather_observation_station_1/mysql_source.sql | arthurdysart/HackerRank | 2835603c3da78ca85a963069b754b8cc7aedd5df | [
"Unlicense"
] | null | null | null | sql/basic_select/weather_observation_station_1/mysql_source.sql | arthurdysart/HackerRank | 2835603c3da78ca85a963069b754b8cc7aedd5df | [
"Unlicense"
] | null | null | null | sql/basic_select/weather_observation_station_1/mysql_source.sql | arthurdysart/HackerRank | 2835603c3da78ca85a963069b754b8cc7aedd5df | [
"Unlicense"
] | null | null | null | /*
HackerRank SQL: Weather Observation Station 1
https://www.hackerrank.com/challenges/weather-observation-station-1
Difficulty: easy
Created on Sun Oct 28 16:11:51 2018
@author: Arthur Dysart
*/
SELECT CITY, STATE
FROM STATION; | 20.909091 | 67 | 0.786957 |
0edc1945b73791121c4e39ec9068c090a1f54900 | 9,853 | h | C | src/art/art/Framework/Services/Registry/detail/helper_macros.h | JeffersonLab/ARIEL | 49054ac62a84d48e269f7171daabb98e12a0be90 | [
"BSD-3-Clause"
] | null | null | null | src/art/art/Framework/Services/Registry/detail/helper_macros.h | JeffersonLab/ARIEL | 49054ac62a84d48e269f7171daabb98e12a0be90 | [
"BSD-3-Clause"
] | null | null | null | src/art/art/Framework/Services/Registry/detail/helper_macros.h | JeffersonLab/ARIEL | 49054ac62a84d48e269f7171daabb98e12a0be90 | [
"BSD-3-Clause"
] | 2 | 2020-09-26T01:37:11.000Z | 2021-05-03T13:02:24.000Z | #ifndef art_Framework_Services_Registry_detail_helper_macros_h
#define art_Framework_Services_Registry_detail_helper_macros_h
// vim: set sw=2 expandtab :
#include "art/Framework/Services/Registry/ServiceScope.h"
#include "art/Framework/Services/Registry/detail/ServiceHandleAllowed.h"
#include "art/Framework/Services/Registry/detail/ServiceHelper.h"
#include "art/Framework/Services/Registry/detail/ServiceWrapper.h"
#include "art/Framework/Services/Registry/detail/ServiceWrapperBase.h"
#include "art/Framework/Services/Registry/detail/ensure_only_one_thread.h"
#include "art/Utilities/SharedResourcesRegistry.h"
////////////////////////////////////////////////////////////////////////
// Utility for including the service type in a static_assert
#define ART_DETAIL_STRINGIZED_VALUE(value) #value
#define ART_DETAIL_STRINGIZED_TYPE(svc) ART_DETAIL_STRINGIZED_VALUE(svc)
// Define a member function returning the typeid of the service.
#define DEFINE_ART_SERVICE_TYPEID(svc) \
art::TypeID get_typeid() const override { return TypeID{typeid(svc)}; }
// Define a member function to return the scope of the service, and a
// static to provide compile-time help when we have the concrete helper
// class instead of a base.
#define DEFINE_ART_SERVICE_SCOPE(scopeArg) \
ServiceScope scope() const override { return scope_val; } \
static constexpr ServiceScope scope_val{ServiceScope::scopeArg};
#define DEFINE_ART_SERVICE_RETRIEVER(svc) \
void* retrieve(std::shared_ptr<ServiceWrapperBase>& swb) \
const final override \
{ \
return &std::dynamic_pointer_cast<ServiceWrapper<svc>>(swb)->get(); \
}
#define DEFINE_ART_SERVICE_MAKER(svc, scopeArg) \
std::unique_ptr<ServiceWrapperBase> make(fhicl::ParameterSet const& pset, \
ActivityRegistry& reg) \
const final override \
{ \
if constexpr (is_shared(ServiceScope::scopeArg) && \
detail::handle_allowed_v<svc>) { \
SharedResourcesRegistry::instance()->registerSharedResource( \
SharedResource<svc>); \
} else if constexpr (is_legacy(ServiceScope::scopeArg)) { \
ensure_only_one_thread(pset); \
} \
return std::make_unique<ServiceWrapper<svc>>(pset, reg); \
}
// CreateHelper.
#define DEFINE_ART_SERVICE_HELPER_CREATE(svc) \
static std::unique_ptr<ServiceHelperBase> createHelper() \
{ \
return std::make_unique<ServiceHelper<svc>>(); \
}
// Declare a service with scope.
#define ART_DETAIL_DECLARE_SERVICE(svc, scopeArg) \
namespace art::detail { \
template <> \
struct ServiceHelper<svc> : public ServiceImplHelper, \
public ServiceLGMHelper, \
public ServiceLGRHelper { \
DEFINE_ART_SERVICE_TYPEID(svc) \
DEFINE_ART_SERVICE_SCOPE(scopeArg) \
DEFINE_ART_SERVICE_RETRIEVER(svc) \
DEFINE_ART_SERVICE_MAKER(svc, scopeArg) \
bool \
is_interface_impl() const override \
{ \
return false; \
} \
}; \
}
// Declare an interface for a service with scope.
#define ART_DETAIL_DECLARE_SERVICE_INTERFACE(iface, scopeArg) \
namespace art::detail { \
template <> \
struct ServiceHelper<iface> : public ServiceInterfaceHelper, \
public ServiceLGRHelper { \
DEFINE_ART_SERVICE_TYPEID(iface) \
DEFINE_ART_SERVICE_SCOPE(scopeArg) \
DEFINE_ART_SERVICE_RETRIEVER(iface) \
}; \
}
// Define a service with scope implementing an interface.
#define ART_DETAIL_DECLARE_SERVICE_INTERFACE_IMPL(svc, iface, scopeArg) \
namespace art::detail { \
template <> \
struct ServiceHelper<svc> : public ServiceInterfaceImplHelper, \
public ServiceLGMHelper, \
public ServiceLGRHelper { \
DEFINE_ART_SERVICE_TYPEID(svc) \
DEFINE_ART_SERVICE_SCOPE(scopeArg) \
DEFINE_ART_SERVICE_RETRIEVER(svc) \
DEFINE_ART_SERVICE_MAKER(svc, scopeArg) \
art::TypeID \
get_interface_typeid() const final override \
{ \
return TypeID{typeid(iface)}; \
} \
std::unique_ptr<ServiceWrapperBase> \
convert( \
std::shared_ptr<ServiceWrapperBase> const& swb) const final override \
{ \
return std::dynamic_pointer_cast<ServiceWrapper<svc>>(swb) \
->getAs<iface>(); \
} \
static_assert(is_shared(ServiceHelper<iface>::scope_val) || \
is_legacy(ServiceHelper<svc>::scope_val), \
"\n\nart error: An implementation that inherits from a " \
"LEGACY interface\n" \
" must be a LEGACY service\n\n"); \
}; \
}
// Declare a system service (requires support code in Event Processor)
// since system services have no maker function.
#define ART_DETAIL_DECLARE_SYSTEM_SERVICE(svc, scopeArg) \
namespace art::detail { \
template <> \
struct ServiceHelper<svc> : public ServiceImplHelper, \
public ServiceLGRHelper { \
DEFINE_ART_SERVICE_TYPEID(svc) \
DEFINE_ART_SERVICE_SCOPE(scopeArg) \
bool \
is_interface_impl() const override \
{ \
return false; \
} \
DEFINE_ART_SERVICE_RETRIEVER(svc) \
}; \
}
// Define the C-linkage function to create the helper.
#define DEFINE_ART_SH_CREATE(svc) DEFINE_ART_SH_CREATE_DETAIL(svc, service)
#define DEFINE_ART_SIH_CREATE(svc) DEFINE_ART_SH_CREATE_DETAIL(svc, iface)
#define DEFINE_ART_SH_CREATE_DETAIL(svc, type) \
EXTERN_C_FUNC_DECLARE_START \
std::unique_ptr<art::detail::ServiceHelperBase> create_##type##_helper() \
{ \
return std::make_unique<art::detail::ServiceHelper<svc>>(); \
} \
EXTERN_C_FUNC_DECLARE_END
#endif /* art_Framework_Services_Registry_detail_helper_macros_h */
// Local Variables:
// mode: c++
// End:
| 63.160256 | 80 | 0.403532 |
98523857c35638f7b4b831415c5a47dea8f66576 | 298 | kt | Kotlin | core/usecases/src/main/kotlin/theme/compareCharacterValues/CompareCharacterValues.kt | Soyle-Productions/soyle-stories | 1a110536865250dcd8d29270d003315062f2b032 | [
"Apache-2.0"
] | 7 | 2021-08-10T18:20:25.000Z | 2022-03-31T07:23:18.000Z | core/usecases/src/main/kotlin/theme/compareCharacterValues/CompareCharacterValues.kt | Soyle-Productions/soyle-stories | 1a110536865250dcd8d29270d003315062f2b032 | [
"Apache-2.0"
] | 37 | 2021-08-04T22:51:02.000Z | 2022-02-10T21:29:55.000Z | core/usecases/src/main/kotlin/theme/compareCharacterValues/CompareCharacterValues.kt | Soyle-Productions/soyle-stories | 1a110536865250dcd8d29270d003315062f2b032 | [
"Apache-2.0"
] | null | null | null | package com.soyle.stories.usecase.theme.compareCharacterValues
import java.util.*
interface CompareCharacterValues {
suspend operator fun invoke(themeId: UUID, output: OutputPort)
interface OutputPort {
suspend fun charactersCompared(response: CharacterValueComparison)
}
} | 22.923077 | 74 | 0.775168 |
36a3f530909ac0bb134bd44dbe921d455306e111 | 22 | rs | Rust | src/physics/mod.rs | kachark/mads | bcbb9d2d199c7cf67f1e7cef932dfaaf6ac396ae | [
"MIT"
] | null | null | null | src/physics/mod.rs | kachark/mads | bcbb9d2d199c7cf67f1e7cef932dfaaf6ac396ae | [
"MIT"
] | null | null | null | src/physics/mod.rs | kachark/mads | bcbb9d2d199c7cf67f1e7cef932dfaaf6ac396ae | [
"MIT"
] | null | null | null |
pub mod collisions;
| 5.5 | 19 | 0.727273 |
ceceab83803e09fc77cedb8b5aa8c26bc04c0fa1 | 8,524 | asm | Assembly | Transynther/x86/_processed/AVXALIGN/_st_4k_/i9-9900K_12_0xa0.log_21829_1084.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 9 | 2020-08-13T19:41:58.000Z | 2022-03-30T12:22:51.000Z | Transynther/x86/_processed/AVXALIGN/_st_4k_/i9-9900K_12_0xa0.log_21829_1084.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 1 | 2021-04-29T06:29:35.000Z | 2021-05-13T21:02:30.000Z | Transynther/x86/_processed/AVXALIGN/_st_4k_/i9-9900K_12_0xa0.log_21829_1084.asm | ljhsiun2/medusa | 67d769b8a2fb42c538f10287abaf0e6dbb463f0c | [
"MIT"
] | 3 | 2020-07-14T17:07:07.000Z | 2022-03-21T01:12:22.000Z | .global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r14
push %r8
push %r9
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x1bcd6, %rsi
lea addresses_UC_ht+0x14ad6, %rdi
clflush (%rsi)
nop
nop
add $46527, %r14
mov $87, %rcx
rep movsq
sub $21669, %r8
lea addresses_normal_ht+0xb856, %rsi
lea addresses_normal_ht+0x15fd2, %rdi
nop
nop
nop
nop
and $13443, %r11
mov $65, %rcx
rep movsq
nop
nop
nop
nop
inc %r8
lea addresses_UC_ht+0xe97e, %rsi
lea addresses_UC_ht+0xae7f, %rdi
clflush (%rsi)
nop
nop
and $44165, %r9
mov $3, %rcx
rep movsb
nop
nop
nop
nop
cmp %r11, %r11
lea addresses_WC_ht+0x1b8b2, %rsi
nop
nop
nop
nop
nop
add %r8, %r8
movb (%rsi), %r9b
and $51480, %r9
lea addresses_UC_ht+0x11ad6, %r8
nop
nop
nop
nop
and %rdi, %rdi
mov $0x6162636465666768, %rsi
movq %rsi, (%r8)
nop
nop
nop
nop
nop
sub %rcx, %rcx
lea addresses_UC_ht+0xe2d6, %r11
nop
nop
nop
nop
cmp $36467, %rsi
movl $0x61626364, (%r11)
nop
nop
xor %r14, %r14
lea addresses_WT_ht+0x1c782, %r8
nop
nop
nop
nop
nop
xor %rsi, %rsi
movl $0x61626364, (%r8)
nop
nop
nop
mfence
lea addresses_normal_ht+0xee16, %r11
nop
nop
nop
nop
nop
xor %r9, %r9
mov (%r11), %rdi
nop
nop
xor $26322, %r14
lea addresses_D_ht+0x16dfa, %r14
clflush (%r14)
nop
nop
nop
and $54116, %rcx
mov $0x6162636465666768, %r9
movq %r9, (%r14)
nop
nop
nop
xor %r14, %r14
lea addresses_A_ht+0x11086, %r14
nop
nop
sub %rcx, %rcx
movw $0x6162, (%r14)
nop
sub %r8, %r8
lea addresses_WT_ht+0x3016, %rdi
sub %rcx, %rcx
mov (%rdi), %r11
cmp %rdi, %rdi
lea addresses_normal_ht+0x11480, %r8
nop
nop
xor %r14, %r14
mov (%r8), %ecx
nop
sub $44522, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %r9
pop %r8
pop %r14
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r8
push %rbx
push %rcx
push %rdx
push %rsi
// Load
lea addresses_WC+0x1aad6, %rdx
nop
nop
nop
nop
nop
dec %rsi
vmovntdqa (%rdx), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $1, %xmm5, %r10
nop
nop
nop
xor %r8, %r8
// Load
lea addresses_WC+0x3ed6, %r8
nop
nop
nop
nop
add %rcx, %rcx
mov (%r8), %si
nop
nop
nop
xor $19219, %rsi
// Store
lea addresses_A+0x866e, %rsi
nop
nop
sub $4151, %r12
mov $0x5152535455565758, %r8
movq %r8, %xmm6
movups %xmm6, (%rsi)
nop
sub $35035, %rsi
// Store
lea addresses_PSE+0x19ad6, %rdx
and $56117, %rbx
mov $0x5152535455565758, %r10
movq %r10, %xmm2
movups %xmm2, (%rdx)
nop
nop
nop
nop
cmp $3309, %rsi
// Store
lea addresses_RW+0x3ad6, %r12
nop
nop
nop
nop
nop
sub $46268, %r10
movl $0x51525354, (%r12)
nop
inc %r12
// Store
lea addresses_UC+0x1f396, %rdx
add %r8, %r8
mov $0x5152535455565758, %r12
movq %r12, %xmm6
movups %xmm6, (%rdx)
// Exception!!!
mov (0), %r8
nop
nop
nop
nop
nop
inc %r10
// Faulty Load
lea addresses_WC+0x1aad6, %rbx
nop
nop
nop
nop
nop
inc %rdx
mov (%rbx), %r12
lea oracles, %rbx
and $0xff, %r12
shlq $12, %r12
mov (%rbx,%r12,1), %r12
pop %rsi
pop %rdx
pop %rcx
pop %rbx
pop %r8
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WC', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'}
{'src': {'NT': True, 'same': True, 'congruent': 0, 'type': 'addresses_WC', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_WC', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_A', 'AVXalign': False, 'size': 16}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 16}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_RW', 'AVXalign': False, 'size': 4}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 6, 'type': 'addresses_UC', 'AVXalign': False, 'size': 16}}
[Faulty Load]
{'src': {'NT': True, 'same': True, 'congruent': 0, 'type': 'addresses_WC', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'same': False, 'congruent': 9, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_UC_ht'}}
{'src': {'same': False, 'congruent': 6, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 2, 'type': 'addresses_normal_ht'}}
{'src': {'same': False, 'congruent': 2, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_UC_ht'}}
{'src': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 10, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 4}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 4}}
{'src': {'NT': False, 'same': True, 'congruent': 6, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 8}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 2}}
{'src': {'NT': False, 'same': True, 'congruent': 5, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'}
{'54': 21829}
54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54
*/
| 30.33452 | 2,999 | 0.652863 |
700a38ec5004584048d3a76fc4b2e846a71398bc | 1,762 | lua | Lua | oop/image.lua | warcraft-iii/lib-stdlib | 4d98971a2755ba72dd855cf070068f85a0c56e55 | [
"MIT"
] | 3 | 2019-12-14T00:23:13.000Z | 2021-07-06T08:55:07.000Z | oop/image.lua | warcraft-iii/lib-stdlib | 4d98971a2755ba72dd855cf070068f85a0c56e55 | [
"MIT"
] | null | null | null | oop/image.lua | warcraft-iii/lib-stdlib | 4d98971a2755ba72dd855cf070068f85a0c56e55 | [
"MIT"
] | null | null | null | ---@type Image
local Image = require('lib.stdlib.oop._generated._image')
---<static> create
---@overload fun(file: string, size: Vector3, pos: Vector3, origin: Vector3, imageType: integer): Image
---@param file string
---@param sizeX float
---@param sizeY float
---@param sizeZ float
---@param posX float
---@param posY float
---@param posZ float
---@param originX float
---@param originY float
---@param originZ float
---@param imageType integer
---@return Image
function Image:create(file, sizeX, sizeY, sizeZ, posX, posY, posZ, originX, originY, originZ, imageType)
if type(sizeX) == 'table' and type(sizeY) == 'table' and type(sizeZ) == 'table' then
imageType = posX
originX, originY, originZ = table.unpack(sizeZ)
posX, posY, posZ = table.unpack(sizeY)
sizeX, sizeY, sizeZ = table.unpack(sizeZ)
end
-- @debug@
checkclass(self, Image, 'create', 'self')
checktype(file, 'string', 'create', 1)
checktype(sizeX, 'float', 'create', 2)
checktype(sizeY, 'float', 'create', 3)
checktype(sizeZ, 'float', 'create', 4)
checktype(posX, 'float', 'create', 5)
checktype(posY, 'float', 'create', 6)
checktype(posZ, 'float', 'create', 7)
checktype(originX, 'float', 'create', 8)
checktype(originY, 'float', 'create', 9)
checktype(originZ, 'float', 'create', 10)
checktype(imageType, 'integer', 'create', 11)
-- @end-debug@
return Image:fromUd(Native.CreateImage(file, sizeX, sizeY, sizeZ, posX, posY, posZ, originX, originY, originZ,
imageType))
end
---show
---@return void
function Image:show()
return self:setShown(true)
end
---hide
---@return void
function Image:hide()
return self:setShown(false)
end
return Image
| 31.464286 | 114 | 0.643587 |
140557749d7fcb44a64f95db57c80820a7e8226a | 2,561 | css | CSS | conteudo/contatos.css | Andreziin00/Menu-Responsivo | 780ea0f99f336bcb7e47317c1e599bb13619168b | [
"MIT"
] | null | null | null | conteudo/contatos.css | Andreziin00/Menu-Responsivo | 780ea0f99f336bcb7e47317c1e599bb13619168b | [
"MIT"
] | null | null | null | conteudo/contatos.css | Andreziin00/Menu-Responsivo | 780ea0f99f336bcb7e47317c1e599bb13619168b | [
"MIT"
] | null | null | null | @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800;900&display=swap');
.footer * {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Oswald', sans-serif;
}
.footer {
display: flex;
justify-content: space-around;
align-items: center;
min-height: 60vh;
}
.contatos * {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Oswald', sans-serif;
}
.contatos {
display: flex;
justify-content: right;
align-items: center;
min-height: 30vh;
}
.contatos ul {
position: relative;
transform: skewY(-15deg);
}
.contatos ul li {
position: relative;
list-style: none;
width: 200px;
background: #0d194b;
padding: 15px;
z-index: var(--i);
transition: 0.5s;
margin-right: 4em;
}
.contatos ul li:hover {
background: #283e96;
transform: translateX(50px);
transition: 0.5s;
}
.contatos ul li::before {
content: '';
position: absolute;
top: 0;
left: -40px;
width: 40px;
height: 100%;
background: #060c25;
transform-origin: right;
transform: skewY(45deg);
transition: 0.5s;
}
.contatos ul li:hover::before {
background: #152561;
}
.contatos ul li::after {
content: '';
position: absolute;
top: -40px;
left: 0;
width: 100%;
height: 40px;
background: #0b1642;
transform-origin: bottom;
transform: skewX(45deg);
transition: 0.5s;
}
.contatos ul li:hover::after {
background: #1b379b;
}
.contatos ul li a {
text-decoration: none;
color: #fff;
display: block;
text-transform: uppercase;
letter-spacing: 0.05em;
transition: 0.5s;
}
.contatos lu li a:hover {
color: rgb(201, 201, 201);
}
.contatos ul li:last-child::after {
box-shadow: -100px 100px 20px rgba(0,0,0,0.25);
}
.class_copyright{
font-family: Arial Bold, Helvetica, sans-serif;
font-size: 15px;
margin-top: 20vh;
margin-bottom: 1em;
opacity: 0.7;
margin-left: 2vh;
color: #bcbcdf;
}
.apresentacao{
font-family: Arial Bold, Helvetica, sans-serif;
font-size: 15px;
margin-right: 50em;
opacity: 0.5;
margin-left: 2vh;
color: #bcbcdf;
position: relative;
}
.informacoes img {
width: 70px;
height: 70px;
margin-left: 7em;
margin-top: 2em;
}
footer img:hover {
opacity: 0.6;
transition: 1s;
}
.informacoes {
align-items: center;
justify-content: space-around;
width: 575px;
padding: 0;
position: relative;
}
.logo_footer {
letter-spacing: 10px;
position: center;
font-size: 40px;
letter-spacing: 20px;
}
.logo_final {
margin-right: 10em;
align-items: center;
} | 16.416667 | 118 | 0.656775 |
97be7afea19dabb858225c5f84c7514cde638172 | 1,574 | kt | Kotlin | jvm/src/main/kotlin/org/ionproject/core/userApi/klass/repr/UserKlassSectionListRepresentation.kt | i-on-project/core | 339407d56e66ec164ecdc4172347272d97cc26b3 | [
"Apache-2.0"
] | 7 | 2020-02-24T14:20:55.000Z | 2021-03-13T17:59:37.000Z | jvm/src/main/kotlin/org/ionproject/core/userApi/klass/repr/UserKlassSectionListRepresentation.kt | i-on-project/core | 339407d56e66ec164ecdc4172347272d97cc26b3 | [
"Apache-2.0"
] | 201 | 2020-02-22T16:11:44.000Z | 2022-02-28T01:49:15.000Z | jvm/src/main/kotlin/org/ionproject/core/userApi/klass/repr/UserKlassSectionListRepresentation.kt | i-on-project/core | 339407d56e66ec164ecdc4172347272d97cc26b3 | [
"Apache-2.0"
] | 1 | 2021-03-15T14:59:29.000Z | 2021-03-15T14:59:29.000Z | package org.ionproject.core.userApi.klass.repr
import org.ionproject.core.common.SirenBuilder
import org.ionproject.core.common.Uri
import org.ionproject.core.common.argumentResolvers.parameters.Pagination
import org.ionproject.core.userApi.klass.model.UserKlassSection
private data class ShortUserKlassSectionProps(
val id: String,
val classId: Int,
val courseId: Int,
val courseAcr: String,
val courseName: String,
val calendarTerm: String
)
private fun UserKlassSection.toShortProps() = ShortUserKlassSectionProps(
id,
classId,
courseId,
courseAcr,
courseName,
calendarTerm
)
private fun UserKlassSection.toEmbedRepresentation() =
SirenBuilder(toShortProps())
.klass("user", "class", "section")
.rel("item")
.link("self", href = Uri.forUserClassSection(classId, id))
.link(Uri.relClassSection, href = Uri.forClassSectionById(courseId, calendarTerm, id))
.toEmbed()
fun Iterable<UserKlassSection>.toSirenRepresentation(pagination: Pagination) =
SirenBuilder(pagination)
.klass("user", "class", "section", "collection")
.entities(map { it.toEmbedRepresentation() })
.link("self", href = Uri.forPagingUserClassSections(pagination.page, pagination.limit))
.link("next", href = Uri.forPagingUserClassSections(pagination.page + 1, pagination.limit))
.apply {
if (pagination.page > 0)
link("previous", href = Uri.forPagingUserClassSections(pagination.page - 1, pagination.limit))
}
.toSiren()
| 34.977778 | 110 | 0.701398 |
5f1410e66518e2b1c00aee6be11eb38dfdacf80f | 8,408 | ts | TypeScript | panel/models/tabs.ts | sthagen/holoviz-panel | 9abae5ac78e55857ed209de06feae3439f2f533b | [
"BSD-3-Clause"
] | 601 | 2018-08-25T20:01:22.000Z | 2019-11-19T19:37:08.000Z | panel/models/tabs.ts | sthagen/holoviz-panel | 9abae5ac78e55857ed209de06feae3439f2f533b | [
"BSD-3-Clause"
] | 626 | 2018-08-27T16:30:33.000Z | 2019-11-20T17:02:00.000Z | panel/models/tabs.ts | sthagen/holoviz-panel | 9abae5ac78e55857ed209de06feae3439f2f533b | [
"BSD-3-Clause"
] | 73 | 2018-09-28T07:46:05.000Z | 2019-11-18T22:45:36.000Z | import {Grid, ContentBox, Sizeable} from "@bokehjs/core/layout"
import {div, size, children, display, undisplay, position, scroll_size} from "@bokehjs/core/dom"
import {sum, remove_at} from "@bokehjs/core/util/array"
import * as p from "@bokehjs/core/properties"
import {Tabs as BkTabs, TabsView as BkTabsView} from "@bokehjs/models/layouts/tabs"
import {LayoutDOMView} from "@bokehjs/models/layouts/layout_dom"
import * as tabs from "@bokehjs/styles/tabs.css"
import * as buttons from "@bokehjs/styles/buttons.css"
import * as menus from "@bokehjs/styles/menus.css"
function show(element: HTMLElement): void {
element.style.visibility = ""
element.style.opacity = ""
}
function hide(element: HTMLElement): void {
element.style.visibility = "hidden"
element.style.opacity = "0"
}
export class TabsView extends BkTabsView {
model: Tabs
connect_signals(): void {
super.connect_signals()
let view: any = this
while (view != null) {
if (view.model.type.endsWith('Tabs')) {
view.connect(view.model.properties.active.change, () => this.update_zindex())
}
view = view.parent || view._parent // Handle ReactiveHTML
}
}
get is_visible(): boolean {
let parent: any = this.parent
let current_view: any = this
while (parent != null) {
if (parent.model.type.endsWith('Tabs')) {
if (parent.child_views.indexOf(current_view) !== parent.model.active) {
return false
}
}
current_view = parent
parent = parent.parent || parent._parent // Handle ReactiveHTML
}
return true
}
override _update_layout(): void {
const loc = this.model.tabs_location
const vertical = loc == "above" || loc == "below"
// XXX: this is a hack, this should be handled by "fit" policy in grid layout
const {scroll_el, headers_el} = this
this.header = new class extends ContentBox {
protected override _measure(viewport: Sizeable) {
const min_headers = 3
const scroll = size(scroll_el)
const headers = children(headers_el).slice(0, min_headers).map((el) => size(el))
const {width, height} = super._measure(viewport)
if (vertical) {
const min_width = scroll.width + sum(headers.map((size) => size.width))
return {width: viewport.width != Infinity ? viewport.width : min_width, height}
} else {
const min_height = scroll.height + sum(headers.map((size) => size.height))
return {width, height: viewport.height != Infinity ? viewport.height : min_height}
}
}
}(this.header_el)
let {width_policy, height_policy} = this.model
if (width_policy == "auto")
width_policy = this._width_policy()
if (height_policy == "auto")
height_policy = this._height_policy()
const {sizing_mode} = this.model
if (sizing_mode != null) {
if (sizing_mode == "fixed")
width_policy = height_policy = "fixed"
else if (sizing_mode == "stretch_both")
width_policy = height_policy = "max"
else if (sizing_mode == "stretch_width")
width_policy = "max"
else if (sizing_mode == "stretch_height")
height_policy = "max"
}
if (vertical)
this.header.set_sizing({width_policy: width_policy, height_policy: "fixed"})
else
this.header.set_sizing({width_policy: "fixed", height_policy: height_policy})
let row = 1
let col = 1
switch (loc) {
case "above": row -= 1; break
case "below": row += 1; break
case "left": col -= 1; break
case "right": col += 1; break
}
const header = {layout: this.header, row, col}
const panels = this.child_views.map((child_view) => {
return {layout: child_view.layout, row: 1, col: 1}
})
this.layout = new Grid([header, ...panels])
this.layout.set_sizing(this.box_sizing())
}
update_zindex(): void {
const {child_views} = this
for (const child_view of child_views) {
if (child_view != null && child_view.el != null)
child_view.el.style.zIndex = ""
}
if (this.is_visible) {
const active = child_views[this.model.active]
if (active != null && active.el != null)
active.el.style.zIndex = "1"
}
}
override update_position(): void {
super.update_position()
this.header_el.style.position = "absolute" // XXX: do it in position()
position(this.header_el, this.header.bbox)
const loc = this.model.tabs_location
const vertical = loc == "above" || loc == "below"
const scroll_el_size = size(this.scroll_el)
const headers_el_size = scroll_size(this.headers_el)
if (vertical) {
const {width} = this.header.bbox
if (headers_el_size.width > width) {
this.wrapper_el.style.maxWidth = `${width - scroll_el_size.width}px`
display(this.scroll_el)
this.do_scroll(this.model.active)
} else {
this.headers_el.style.left = '0px'
this.wrapper_el.style.maxWidth = ""
undisplay(this.scroll_el)
}
} else {
const {height} = this.header.bbox
if (headers_el_size.height > height) {
this.wrapper_el.style.maxHeight = `${height - scroll_el_size.height}px`
display(this.scroll_el)
this.do_scroll(this.model.active)
} else {
this.headers_el.style.top = '0px'
this.wrapper_el.style.maxHeight = ""
undisplay(this.scroll_el)
}
}
const {child_views} = this
for (const child_view of child_views) {
hide(child_view.el)
child_view.el.style.removeProperty('zIndex');
}
const tab = child_views[this.model.active]
if (tab != null)
show(tab.el)
}
override render(): void {
LayoutDOMView.prototype.render.call(this)
let {active} = this.model
const headers = this.model.tabs.map((tab, i) => {
const el = div({class: [tabs.tab, i == active ? tabs.active : null]}, tab.title)
el.addEventListener("click", (event) => {
if (this.model.disabled)
return
if (event.target == event.currentTarget)
this.change_active(i)
})
if (tab.closable) {
const close_el = div({class: tabs.close})
close_el.addEventListener("click", (event) => {
if (event.target == event.currentTarget) {
this.model.tabs = remove_at(this.model.tabs, i)
const ntabs = this.model.tabs.length
if (this.model.active > ntabs - 1)
this.model.active = ntabs - 1
}
})
el.appendChild(close_el)
}
if (this.model.disabled || tab.disabled) {
el.classList.add(tabs.disabled)
}
return el
})
this.headers_el = div({class: [tabs.headers]}, headers)
this.wrapper_el = div({class: tabs.headers_wrapper}, this.headers_el)
this.left_el = div({class: [buttons.btn, buttons.btn_default], disabled: ""}, div({class: [menus.caret, tabs.left]}))
this.right_el = div({class: [buttons.btn, buttons.btn_default]}, div({class: [menus.caret, tabs.right]}))
this.left_el.addEventListener("click", () => this.do_scroll("left"))
this.right_el.addEventListener("click", () => this.do_scroll("right"))
this.scroll_el = div({class: buttons.btn_group}, this.left_el, this.right_el)
const loc = this.model.tabs_location
this.header_el = div({class: [tabs.tabs_header, tabs[loc]]}, this.scroll_el, this.wrapper_el)
this.el.appendChild(this.header_el)
this.update_zindex()
if (active === -1 && this.model.tabs.length)
this.model.active = 0
}
on_active_change(): void {
const i = this.model.active
const headers = children(this.headers_el)
for (const el of headers)
el.classList.remove(tabs.active)
headers[i].classList.add(tabs.active)
const {child_views} = this
for (const child_view of child_views) {
hide(child_view.el)
}
show(child_views[i].el)
}
}
export namespace Tabs {
export type Attrs = p.AttrsOf<Props>
export type Props = BkTabs.Props & {
}
}
export interface Tabs extends BkTabs.Attrs {}
export class Tabs extends BkTabs {
properties: Tabs.Props
constructor(attrs?: Partial<Tabs.Attrs>) {
super(attrs)
}
static __module__ = "panel.models.tabs"
static init_Tabs(): void {
this.prototype.default_view = TabsView
this.define<Tabs.Props>(({}) => ({
}))
}
}
| 30.911765 | 121 | 0.633206 |
fe2be417f7d927bfb1deca81f53dd1df8d2dd802 | 413 | c | C | examples/arguments.c | mogenson/async.h | 41d45217019c4e1d12c986c36240d733c0d52a0c | [
"MIT"
] | 4 | 2021-02-07T15:20:36.000Z | 2022-02-20T01:43:31.000Z | examples/arguments.c | mogenson/async.h | 41d45217019c4e1d12c986c36240d733c0d52a0c | [
"MIT"
] | null | null | null | examples/arguments.c | mogenson/async.h | 41d45217019c4e1d12c986c36240d733c0d52a0c | [
"MIT"
] | null | null | null | #include "../async.h"
#include <stdio.h>
/* define an async task named print that takes two arguments */
ASYNC(print, char c, int i) {
BEGIN();
while (1) {
printf("c is '%c' and i is %d\n", c, i); // print arguments
YIELD();
}
END();
}
int main() {
char c = 'a';
int i = 0;
while (i < 10) {
AWAIT(print, c, i); // run print task with arguments
c++;
i++;
}
return 0;
}
| 14.241379 | 63 | 0.527845 |
e784a1ad6a5ce3cea22a0e580fb3988a29399573 | 28,875 | js | JavaScript | packages/forms/src/UIForm/fields/Enumeration/EnumerationWidget.js | Gby56/ui | a0cbbb9685e559a841b391ad5c4b3e9fa58d022d | [
"Apache-2.0"
] | 140 | 2017-01-24T15:52:42.000Z | 2022-03-23T10:29:07.000Z | packages/forms/src/UIForm/fields/Enumeration/EnumerationWidget.js | Gby56/ui | a0cbbb9685e559a841b391ad5c4b3e9fa58d022d | [
"Apache-2.0"
] | 3,451 | 2017-01-24T16:31:50.000Z | 2022-03-31T15:35:10.000Z | packages/forms/src/UIForm/fields/Enumeration/EnumerationWidget.js | Gby56/ui | a0cbbb9685e559a841b391ad5c4b3e9fa58d022d | [
"Apache-2.0"
] | 61 | 2017-01-26T08:59:42.000Z | 2022-03-16T04:44:51.000Z | import PropTypes from 'prop-types';
import React from 'react';
import keycode from 'keycode';
import _isEmpty from 'lodash/isEmpty';
import Enumeration from '@talend/react-components/lib/Enumeration';
import classNames from 'classnames';
import { withTranslation } from 'react-i18next';
import FocusManager from '@talend/react-components/lib/FocusManager';
import { manageCtrlKey, manageShiftKey, deleteSelectedItems, resetItems } from './utils/utils';
import { I18N_DOMAIN_FORMS } from '../../../constants';
import getDefaultT from '../../../translate';
import FieldTemplate from '../FieldTemplate';
export const enumerationStates = {
DISPLAY_MODE_DEFAULT: 'DISPLAY_MODE_DEFAULT',
DISPLAY_MODE_ADD: 'DISPLAY_MODE_ADD',
DISPLAY_MODE_SEARCH: 'DISPLAY_MODE_SEARCH',
DISPLAY_MODE_EDIT: 'DISPLAY_MODE_EDIT',
DISPLAY_MODE_SELECTED: 'DISPLAY_MODE_SELECTED',
IMPORT_MODE_APPEND: 'IMPORT_MODE_APPEND',
IMPORT_MODE_OVERWRITE: 'IMPORT_MODE_OVERWRITE',
};
const ENUMERATION_SEARCH_ACTION = 'ENUMERATION_SEARCH_ACTION';
const ENUMERATION_NEXT_PAGE_ACTION = 'ENUMERATION_NEXT_PAGE_ACTION';
const ENUMERATION_ADD_ACTION = 'ENUMERATION_ADD_ACTION';
const ENUMERATION_REMOVE_ACTION = 'ENUMERATION_REMOVE_ACTION';
const ENUMERATION_RENAME_ACTION = 'ENUMERATION_RENAME_ACTION';
const ITEMS_DEFAULT_HEIGHT = 33;
const ENUMERATION_IMPORT_FILE_ACTION = 'ENUMERATION_IMPORT_FILE_ACTION';
/*
For this widget we distinguish 2 modes :
- Connected mode. All items are passed via props by callee
There are no computation of items here, all computation is done by the callee application
- Non-connected Mode :
Note: The item's index retrieved on event is different than the one in the global state list
The items display is computed on frontend-side
Add, Remove, Edit, Submit, Search actions imply a computation on frontend side.
This is the case for story book for example.
There is a special method isConnectedMode() indicating in what mode we are
*/
class EnumerationForm extends React.Component {
static getItemHeight() {
return ITEMS_DEFAULT_HEIGHT;
}
static parseStringValueToArray(values) {
return values.split(',').map(value => value.trim());
}
static updateItemValidateDisabled(value, valueExist) {
return {
currentEdit: {
validate: {
disabled: value.value === '' || !!valueExist,
},
},
};
}
constructor(props) {
super(props);
const t = props.t;
this.timerSearch = null;
this.allowDuplicate = false;
this.allowImport = false;
const disabledAction = props.schema ? props.schema.disabled : false;
this.importFileHandler = this.importFileHandler.bind(this);
if (props.schema) {
this.allowDuplicate = !!props.schema.allowDuplicates;
this.allowImport = !!props.schema.allowImport;
}
this.addInputs = [
{
disabled: true,
label: t('ENUMERATION_WIDGET_VALIDATE_AND_ADD', {
defaultValue: 'Validate and Add',
}),
icon: 'talend-check-plus',
id: 'validate-and-add',
key: 'validateAdd',
onClick: this.onValidateAndAddHandler.bind(this),
},
{
disabled: true,
label: t('ENUMERATION_WIDGET_VALIDATE', { defaultValue: 'Validate' }),
icon: 'talend-check',
id: 'validate',
key: 'validate',
onClick: this.onSingleAddHandler.bind(this),
},
{
label: t('ENUMERATION_WIDGET_ABORT', { defaultValue: 'Abort' }),
icon: 'talend-cross',
id: 'abort',
key: 'abort',
onClick: this.onAbortHandler.bind(this),
},
];
this.searchInputsActions = [
{
label: t('ENUMERATION_WIDGET_ABORT', { defaultValue: 'Abort' }),
icon: 'talend-cross',
id: 'abort',
key: 'abort',
onClick: this.onAbortHandler.bind(this),
},
];
this.loadingInputsActions = [
{
label: t('ENUMERATION_WIDGET_LOADING', { defaultValue: 'Loading' }),
icon: 'talend-cross',
inProgress: true,
id: 'loading',
},
];
this.itemEditActions = [
{
disabled: true,
label: t('ENUMERATION_WIDGET_VALIDATE', { defaultValue: 'Validate' }),
icon: 'talend-check',
id: 'validate',
onClick: this.onSubmitItem.bind(this),
},
{
disabled: false,
label: t('ENUMERATION_WIDGET_ABORT', { defaultValue: 'Abort' }),
icon: 'talend-cross',
id: 'abort',
onClick: this.onAbortItem.bind(this),
},
];
this.defaultActions = [
{
disabled: disabledAction,
label: t('ENUMERATION_WIDGET_EDIT', { defaultValue: 'Edit' }),
icon: 'talend-pencil',
id: 'edit',
onClick: this.onEnterEditModeItem.bind(this),
},
{
disabled: disabledAction,
label: t('ENUMERATION_WIDGET_REMOVE_VALUE', { defaultValue: 'Remove value' }),
icon: 'talend-trash',
id: 'delete',
onClick: this.onDeleteItem.bind(this),
},
];
this.defaultHeaderActions = [
{
disabled: false,
label: t('ENUMERATION_WIDGET_SEARCH_VALUES', {
defaultValue: 'Search for specific values',
}),
icon: 'talend-search',
id: 'search',
onClick: this.changeDisplayToSearchMode.bind(this),
},
];
if (this.allowImport) {
const dataFeature = this.props.schema['data-feature'];
this.defaultHeaderActions.push({
disabled: disabledAction,
label: t('ENUMERATION_WIDGET_IMPORT_FROM_FILE', {
defaultValue: 'Import values from a file',
}),
icon: 'talend-download',
id: 'upload',
onClick: this.onImportButtonClick.bind(this),
'data-feature': dataFeature ? dataFeature.importFile : undefined,
displayMode: 'dropdown',
items: [
{
label: t('ENUMERATION_WIDGET_ADD_FROM_FILE', {
defaultValue: 'Add values from a file',
}),
id: 'append-uploading',
onClick: this.onImportAppendClick.bind(this),
'data-feature': dataFeature ? dataFeature.addFromFile : undefined,
},
{
label: t('ENUMERATION_WIDGET_OVERWRITE_VALUES', {
defaultValue: 'Overwrite existing values',
}),
id: 'overwrite-uploading',
onClick: this.onImportOverwriteClick.bind(this),
'data-feature': dataFeature ? dataFeature.overwriteExisting : undefined,
},
],
});
}
this.defaultHeaderActions.push({
label: t('ENUMERATION_WIDGET_ADD_ITEM', { defaultValue: 'Add item' }),
icon: 'talend-plus',
id: 'add',
disabled: disabledAction,
onClick: this.changeDisplayToAddMode.bind(this),
});
this.selectedHeaderActions = [
{
disabled: disabledAction,
label: t('ENUMERATION_WIDGET_REMOVE_SELECTED_VALUES', {
defaultValue: 'Remove selected values',
}),
icon: 'talend-trash',
id: 'delete',
onClick: this.onDeleteItems.bind(this),
},
];
let defaultDisplayMode = enumerationStates.DISPLAY_MODE_DEFAULT;
if (props.schema && props.schema.displayMode) {
defaultDisplayMode = props.schema.displayMode;
}
this.state = {
inputRef: this.setInputRef.bind(this),
displayMode: defaultDisplayMode,
searchCriteria: '',
required: (props.schema && props.schema.required) || false,
headerDefault: this.defaultHeaderActions,
headerSelected: this.selectedHeaderActions,
headerInput: this.addInputs,
items: (props.value || []).map(item => ({
id: item.id,
values: item.values,
})),
itemsProp: {
key: 'values',
getItemHeight: EnumerationForm.getItemHeight,
onSubmitItem: this.onSubmitItem.bind(this),
onAbortItem: this.onAbortItem.bind(this),
onChangeItem: this.onChangeItem.bind(this),
onSelectItem: !disabledAction ? this.onSelectItem.bind(this) : () => {},
onLoadData: this.onLoadData.bind(this),
actionsDefault: this.defaultActions,
actionsEdit: this.itemEditActions,
},
onInputChange: this.onInputChange.bind(this),
onAddKeyDown: this.onAddKeyDown.bind(this),
};
this.onBlur = this.onBlur.bind(this);
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.value) {
this.setState(prevState => ({ ...prevState, items: nextProps.value }));
}
}
onBlur(event) {
const { schema, onFinish } = this.props;
onFinish(event, { schema });
}
onChange(event, payload) {
const { schema, onFinish, onChange } = this.props;
onChange(event, payload);
onFinish(event, { schema });
}
onImportAppendClick() {
this.setState(
state => ({ ...state, importMode: enumerationStates.IMPORT_MODE_APPEND }),
this.simulateClickInputFile.bind(this),
);
}
onImportOverwriteClick() {
this.setState(
state => ({ ...state, importMode: enumerationStates.IMPORT_MODE_OVERWRITE }),
this.simulateClickInputFile.bind(this),
);
}
// default mode
onEnterEditModeItem(event, value) {
this.setState(prevState => {
let items = resetItems([...prevState.items]);
let item = items[value.index];
// if there is a search criteria, retrieve correct item from state in non-connected mode
if (prevState.searchCriteria && !this.isConnectedMode()) {
item = this.getItemInSearchMode(prevState.searchCriteria, value.index, items);
}
item.displayMode = enumerationStates.DISPLAY_MODE_EDIT;
// resetting errors
items[value.index].error = '';
// reset selection
items = items.map(currentItem => ({ ...currentItem, isSelected: false }));
// exit from selected mode to not display 0 values selected
let displayMode = prevState.displayMode;
if (displayMode === enumerationStates.DISPLAY_MODE_SELECTED) {
displayMode = enumerationStates.DISPLAY_MODE_DEFAULT;
}
const validation = EnumerationForm.updateItemValidateDisabled(item.values[0]);
return { items, displayMode, ...validation };
});
}
onSearchEditModeItem(event, value) {
this.setState(prevState => {
let items = resetItems([...prevState.items]);
const item = items[value.index];
item.displayMode = enumerationStates.DISPLAY_MODE_EDIT;
// reset selection
items = items.map(currentItem => ({ ...currentItem, isSelected: false }));
const validation = EnumerationForm.updateItemValidateDisabled(item.values[0]);
return { items, displayMode: enumerationStates.DISPLAY_MODE_EDIT, ...validation };
});
}
onDeleteItem(event, value) {
// dont want to fire select item on icon click
event.stopPropagation();
const { schema } = this.props;
if (this.isConnectedMode()) {
// loading
this.setState(prevState => ({
itemsProp: {
...prevState.itemsProp,
actionsDefault: this.loadingInputsActions,
},
}));
this.props
.onTrigger(event, {
trigger: { ids: [this.state.items[value.index].id], action: ENUMERATION_REMOVE_ACTION },
schema,
})
.then(() => {
const payload = {
schema,
value: this.state.items.filter((item, index) => index !== value.index),
};
this.onChange(event, payload);
})
.finally(() => {
this.onDeleteItemHandler();
});
} else {
this.setState(prevState => {
const items = resetItems([...prevState.items]);
let indexToRemove = value.index;
const sc = prevState.searchCriteria;
if (sc) {
// retrieve correct item when in non-connected mode
indexToRemove = this.getIndexToRemoveInSearchMode(sc, value.index, items);
}
items[indexToRemove].displayMode = enumerationStates.DISPLAY_MODE_DEFAULT;
items.splice(indexToRemove, 1);
const countItems = items.filter(item => item.isSelected).length;
let displayMode = prevState.displayMode;
if (countItems === 0 && displayMode === enumerationStates.DISPLAY_MODE_SELECTED) {
displayMode = enumerationStates.DISPLAY_MODE_DEFAULT;
}
const payload = {
schema,
value: items,
};
this.onChange(event, payload);
return { displayMode };
});
}
}
onDeleteItemHandler() {
this.setState(prevState => {
const newState = {
itemsProp: {
...prevState.itemsProp,
actionsDefault: this.defaultActions,
},
};
if (prevState.displayMode !== enumerationStates.DISPLAY_MODE_SEARCH) {
newState.displayMode = enumerationStates.DISPLAY_MODE_DEFAULT;
}
return newState;
});
}
onAbortItem(event, value) {
this.setState(prevState => {
const items = [...prevState.items];
items[value.index].displayMode = enumerationStates.DISPLAY_MODE_DEFAULT;
// resetting error as it was not saved
items[value.index].error = '';
return { items, displayMode: enumerationStates.DISPLAY_MODE_DEFAULT };
});
}
onChangeItem(event, value) {
const t = this.props.t;
// if the value exist add an error
this.setState(prevState => {
const valueExist = this.valueAlreadyExist(value.value, prevState, value.index);
const items = [...prevState.items];
items[value.index].error = '';
if (valueExist) {
items[value.index].error = t('ENUMERATION_WIDGET_DUPLICATION_ERROR', {
defaultValue: 'This term is already in the list',
});
}
const validation = EnumerationForm.updateItemValidateDisabled(value, valueExist);
return { items, ...validation };
});
}
onSubmitItem(event, value) {
// dont want to fire select item on icon click
event.preventDefault();
event.stopPropagation();
const { schema } = this.props;
if (this.isConnectedMode()) {
this.setState(prevState => ({
itemsProp: {
...prevState.itemsProp,
actionsEdit: this.loadingInputsActions,
},
}));
const formattedValue = EnumerationForm.parseStringValueToArray(value.value);
this.props
.onTrigger(event, {
trigger: {
id: this.state.items[value.index].id,
index: value.index,
value: formattedValue,
action: ENUMERATION_RENAME_ACTION,
},
schema,
})
.then(() => {
const payload = {
schema,
value: this.state.items.map((item, index) => {
if (index === value.index) {
return { ...item, values: formattedValue };
}
return item;
}),
};
this.onChange(event, payload);
})
.finally(() => {
this.itemSubmitHandler();
});
} else {
const items = [...this.state.items];
let item = items[value.index];
if (this.state.searchCriteria) {
// retrieve correct item when in non-connected mode
item = this.getItemInSearchMode(this.state.searchCriteria, value.index, items);
}
item.displayMode = enumerationStates.DISPLAY_MODE_DEFAULT;
const valueExist = this.valueAlreadyExist(value.value, this.state);
// if the value is empty, no value update is done
if (value.value && !valueExist) {
item.values = EnumerationForm.parseStringValueToArray(value.value);
}
if (valueExist) {
item.error = this.props.t('ENUMERATION_WIDGET_DUPLICATION_ERROR', {
defaultValue: 'This term is already in the list',
});
}
const payload = {
schema,
value: items,
};
this.onChange(event, payload);
}
}
onInputChange(event, value) {
if (this.state.displayMode === enumerationStates.DISPLAY_MODE_ADD) {
this.updateHeaderInputDisabled(value.value);
}
if (this.state.displayMode === enumerationStates.DISPLAY_MODE_SEARCH) {
if (this.timerSearch !== null) {
clearTimeout(this.timerSearch);
}
this.timerSearch = setTimeout(() => {
const { schema } = this.props;
this.timerSearch = null;
if (this.isConnectedMode()) {
this.setState({
headerInput: this.loadingInputsActions,
});
this.props
.onTrigger(event, {
trigger: { value: value.value, action: ENUMERATION_SEARCH_ACTION },
schema,
})
.then(items => {
const payload = {
schema,
value: items.map(item => ({ id: item.id, values: item.values })),
};
this.onChange(event, payload);
this.onSearchHandler(value.value);
});
} else {
this.setState({
searchCriteria: value.value,
});
}
}, 400);
}
}
onLazyHandler() {
let headerActions;
if (this.state.searchCriteria) {
headerActions = this.searchInputsActions;
} else {
headerActions = this.defaultHeaderActions;
}
this.setState({
headerDefault: this.defaultHeaderActions,
headerInput: headerActions,
});
}
onSearchHandler(value) {
this.setState(prevState => ({
headerInput: this.searchInputsActions,
searchCriteria: value,
// since onSearchHandler() is processed asynchronously,
// the line below is mandatory to refresh the items (highlight them)
items: [...prevState.items],
}));
}
onAbortHandler() {
if (this.state.displayMode === enumerationStates.DISPLAY_MODE_ADD) {
this.updateHeaderInputDisabled('');
}
const { schema } = this.props;
if (this.isConnectedMode()) {
this.setState({
headerDefault: this.loadingInputsActions,
});
this.props
.onTrigger(event, {
trigger: { value: '', action: ENUMERATION_SEARCH_ACTION },
schema,
})
.then(items => {
const payload = {
schema,
value: items.map(item => ({ id: item.id, values: item.values })),
};
this.onChange(event, payload);
this.onConnectedAbortHandler();
});
} else {
this.onConnectedAbortHandler();
}
}
onConnectedAbortHandler() {
this.setState({
headerDefault: this.defaultHeaderActions,
searchCriteria: null,
displayMode: enumerationStates.DISPLAY_MODE_DEFAULT,
});
}
onAddKeyDown(event, value) {
if (event.keyCode === keycode('enter')) {
event.stopPropagation();
event.preventDefault();
if (this.state.displayMode === enumerationStates.DISPLAY_MODE_ADD) {
this.onValidateAndAddHandler(event, value);
}
}
if (event.keyCode === keycode('escape')) {
event.stopPropagation();
event.preventDefault();
this.onAbortHandler();
}
}
onSelectItem(item, event) {
// needed to access to the original event in a asynchronous way
// https://fb.me/react-event-pooling
event.persist();
this.setState(prevState => {
let itemsSelected = resetItems([...prevState.items]);
if (event.ctrlKey || event.metaKey) {
itemsSelected = manageCtrlKey(item.index, itemsSelected);
} else if (event.shiftKey) {
itemsSelected = manageShiftKey(item.index, itemsSelected);
} else if (!itemsSelected[item.index].isSelected) {
itemsSelected = itemsSelected.map(currentItem => ({
...currentItem,
isSelected: false,
}));
itemsSelected[item.index].isSelected = true;
} else {
// deselect the given items
itemsSelected[item.index].isSelected = !itemsSelected[item.index].isSelected;
}
const countItems = itemsSelected.filter(currentItem => currentItem.isSelected).length;
// if unselect all, return to default mode
if (countItems === 0) {
return {
items: itemsSelected,
displayMode: enumerationStates.DISPLAY_MODE_DEFAULT,
};
}
return {
items: itemsSelected,
displayMode: enumerationStates.DISPLAY_MODE_SELECTED,
itemsProp: {
...prevState.itemsProp,
actionsDefault: this.defaultActions,
},
};
});
}
onDeleteItems(event) {
const { schema } = this.props;
const itemsToDelete = [];
this.state.items.forEach(item => {
if (item.isSelected) {
itemsToDelete.push(item.id);
}
});
if (this.isConnectedMode()) {
// loading
this.setState({
headerSelected: this.loadingInputsActions,
});
this.props
.onTrigger(event, {
trigger: { ids: itemsToDelete, action: ENUMERATION_REMOVE_ACTION },
schema,
})
.then(() => {
const payload = {
schema,
value: this.state.items.filter(item => !item.isSelected),
};
this.onChange(event, payload);
this.onDeleteItemsHandler();
});
} else {
this.setState(prevState => {
const result = deleteSelectedItems([...prevState.items]);
const payload = {
schema,
value: result,
};
this.onChange(event, payload);
return {
displayMode: enumerationStates.DISPLAY_MODE_DEFAULT,
};
});
}
}
onDeleteItemsHandler() {
this.setState({
displayMode: enumerationStates.DISPLAY_MODE_DEFAULT,
headerSelected: this.selectedHeaderActions,
});
}
onAddHandler(event, value, successHandler, failHandler, isSingleAdd = false) {
const { schema } = this.props;
if (!value.value) {
this.setState({
displayMode: enumerationStates.DISPLAY_MODE_DEFAULT,
});
return;
}
if (this.isConnectedMode()) {
this.setState({
headerInput: this.loadingInputsActions,
});
this.props
.onTrigger(event, {
trigger: {
value: EnumerationForm.parseStringValueToArray(value.value),
action: ENUMERATION_ADD_ACTION,
},
schema,
})
.then(
newDocument => {
const payload = {
schema: this.props.schema,
value: this.props.value.concat(newDocument),
};
this.onChange(event, payload);
this.input.focus();
successHandler();
},
() => {
failHandler();
},
);
} else if (!this.valueAlreadyExist(value.value, this.state)) {
const payload = {
schema,
value: this.state.items.concat([
{
values: EnumerationForm.parseStringValueToArray(value.value),
},
]),
};
this.onChange(event, payload);
this.input.focus();
if (isSingleAdd) {
successHandler();
}
this.updateHeaderInputDisabled('');
}
}
onValidateAndAddHandler(event, value) {
this.onAddHandler(
event,
value,
this.validateAndAddSuccessHandler.bind(this),
this.addFailHandler.bind(this),
);
}
onSingleAddHandler(event, value) {
this.onAddHandler(
event,
value,
this.addSuccessHandler.bind(this),
this.addFailHandler.bind(this),
true,
);
}
// lazy loading
onLoadData() {
if (this.isConnectedMode()) {
const { schema } = this.props;
this.setState({
headerDefault: this.loadingInputsActions,
headerInput: this.loadingInputsActions,
});
this.props
.onTrigger(event, {
trigger: {
value: this.state.searchCriteria,
action: ENUMERATION_NEXT_PAGE_ACTION,
numberItems: this.state.items.length,
},
schema,
})
.then(items => {
const payload = {
schema,
value: this.props.value.concat(
items.map(item => ({ id: item.id, values: item.values })),
),
};
this.onChange(event, payload);
})
.finally(() => {
this.onLazyHandler();
});
}
}
onImportButtonClick() {
if (this.state.items.length === 0) {
this.setState(
state => ({ ...state, importMode: enumerationStates.IMPORT_MODE_APPEND }),
this.simulateClickInputFile.bind(this),
);
}
}
setInputRef(input) {
this.input = input;
}
getItemSelectedInSearchMode(searchCriteria, index) {
const searchedItems = this.searchItems(searchCriteria);
return searchedItems[index];
}
getItemInSearchMode(searchCriteria, index, items) {
const selectedItem = this.getItemSelectedInSearchMode(searchCriteria, index);
return items.find(currentItem => currentItem.values[0] === selectedItem.values[0]);
}
getIndexToRemoveInSearchMode(searchCriteria, index, items) {
const selectedItem = this.getItemSelectedInSearchMode(searchCriteria, index);
return items.findIndex(currentItem => currentItem.values[0] === selectedItem.values[0]);
}
isConnectedMode() {
return !!(this.props.properties && this.props.properties.connectedMode);
}
itemSubmitHandler() {
this.setState(prevState => ({
itemsProp: {
...prevState.itemsProp,
actionsEdit: this.itemEditActions,
},
items: resetItems([...prevState.items]),
}));
}
addSuccessHandler() {
this.setState({
displayMode: enumerationStates.DISPLAY_MODE_DEFAULT,
});
}
validateAndAddSuccessHandler() {
this.setState({
inputValue: '',
headerInput: this.addInputs,
});
this.input.focus();
}
addFailHandler() {
this.setState({
headerInput: this.addInputs,
});
}
/**
* simulateClickInputFile - simulate the click on the hidden input
*
*/
simulateClickInputFile() {
if (this.state.importMode) {
// timeout to allow to lost the focus on the dropdown
setTimeout(() => {
this.inputFile.click();
// when we close the file dialog focus is still on the import icon.
// The tooltip still appears.
// we force to remove the current focus on the icon
document.activeElement.blur();
});
}
}
/**
* importFile - importFile
*
* @param {Event} event Event trigger when the user change the input file
*/
importFile(event) {
const { schema } = this.props;
if (this.isConnectedMode()) {
this.setState({
headerDefault: this.loadingInputsActions,
});
return this.props
.onTrigger(event, {
trigger: {
value: event.target.files[0],
action: ENUMERATION_IMPORT_FILE_ACTION,
importMode: this.state.importMode,
label: this.props.properties.label,
},
schema,
})
.then(items => {
if (!_isEmpty(items)) {
const payload = {
schema,
value: items.map(item => ({ id: item.id, values: item.values })),
};
this.onChange(event, payload);
}
})
.finally(() => {
this.resetInputFile();
this.importFileHandler();
});
}
return Promise.resolve();
}
resetInputFile() {
// reinit the input file
this.inputFile.value = '';
}
/**
* importFileHandler - Action after the upload
*
*/
importFileHandler() {
this.setState({
headerDefault: this.defaultHeaderActions,
importMode: '',
});
}
searchItems(searchCriteria) {
if (!searchCriteria) {
return this.state.items;
}
const searchedItems = [];
this.state.items.forEach(item => {
if (
item.values &&
item.values[0] &&
item.values[0].toLowerCase().includes(searchCriteria.toLowerCase())
) {
searchedItems.push(item);
}
});
return searchedItems;
}
changeDisplayToAddMode() {
this.setState(prevState => ({
items: resetItems([...prevState.items]),
headerInput: this.addInputs,
displayMode: enumerationStates.DISPLAY_MODE_ADD,
}));
}
changeDisplayToSearchMode() {
this.setState(prevState => ({
items: resetItems([...prevState.items]),
headerInput: this.searchInputsActions,
displayMode: enumerationStates.DISPLAY_MODE_SEARCH,
}));
}
valueAlreadyExist(value, state, index) {
const foundIndex = state.items.findIndex(
item => item.values[0] === value && item.values.toString() === value,
);
const indexCheck = index > -1 ? foundIndex !== index : true;
return !this.allowDuplicate && foundIndex > -1 && indexCheck;
}
updateHeaderInputDisabled(value) {
const t = this.props.t;
this.setState(prevState => {
// checking if the value already exist
const valueExist = this.valueAlreadyExist(value, prevState);
const [validateAndAddAction, validateAction, abortAction] = prevState.headerInput;
// in this case, we could have the loading state that implied we have just one icon
if (!validateAction && !abortAction) {
// returning null in setState prevent re-rendering
// see here for documentation https://reactjs.org/blog/2017/09/26/react-v16.0.html#breaking-changes
return null;
}
validateAndAddAction.disabled = value === '' || valueExist;
validateAction.disabled = value === '' || valueExist;
let headerError = '';
if (valueExist) {
headerError = t('ENUMERATION_WIDGET_DUPLICATION_ERROR', {
defaultValue: 'This term is already in the list',
});
}
return {
headerInput: [validateAndAddAction, validateAction, abortAction],
headerError,
inputValue: value,
};
});
}
renderImportFile() {
return (
<input
type="file"
ref={element => {
this.inputFile = element;
}}
onChange={event => {
this.importFile(event);
}}
className={classNames('hidden')}
/>
);
}
render() {
let items = this.state.items;
// filter items only in non-connected mode, since in connected mode items are up-to-date
if (!this.isConnectedMode()) {
items = this.searchItems(this.state.searchCriteria);
}
const stateToShow = { ...this.state, items };
const { description, required, title, labelProps } = this.props.schema;
const { errorMessage, isValid } = this.props;
return (
<FieldTemplate
description={description}
label={title}
labelProps={labelProps}
required={required}
isValid={isValid}
errorMessage={errorMessage}
>
{this.allowImport && this.renderImportFile()}
<FocusManager onFocusOut={this.onBlur}>
<Enumeration {...stateToShow} />
</FocusManager>
</FieldTemplate>
);
}
}
if (process.env.NODE_ENV !== 'production') {
EnumerationForm.propTypes = {
errorMessage: PropTypes.string,
isValid: PropTypes.bool,
onChange: PropTypes.func.isRequired,
onFinish: PropTypes.func.isRequired,
onTrigger: PropTypes.func.isRequired,
properties: PropTypes.object,
schema: PropTypes.object,
t: PropTypes.func,
value: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string,
values: PropTypes.arrayOf(PropTypes.string),
}),
),
};
}
EnumerationForm.defaultProps = {
t: getDefaultT(),
};
export { EnumerationForm };
export default withTranslation(I18N_DOMAIN_FORMS)(EnumerationForm);
| 27.163688 | 103 | 0.667671 |
b646368a3ada00a16191f2ae9605e9740e6ccabe | 249 | rb | Ruby | spec/controller/new/new_spec.rb | TurkeyLeg0403/my_help | b235e7bef2759b4c9bffb71d8f84b6f498c53717 | [
"MIT"
] | 7 | 2019-12-11T06:40:18.000Z | 2021-03-31T23:56:02.000Z | spec/controller/new/new_spec.rb | TurkeyLeg0403/my_help | b235e7bef2759b4c9bffb71d8f84b6f498c53717 | [
"MIT"
] | 93 | 2016-11-11T01:22:53.000Z | 2021-12-07T23:57:24.000Z | spec/controller/new/new_spec.rb | TurkeyLeg0403/my_help | b235e7bef2759b4c9bffb71d8f84b6f498c53717 | [
"MIT"
] | 67 | 2016-11-02T04:52:47.000Z | 2021-12-07T04:01:44.000Z | require 'spec_helper'
require 'my_help'
RSpec.describe 'new option sample' do
context "#new" do
it "make file sample_new.yml" do
expect(command_line((MyHelp::Control.new.init_help('sample')).to_s).success?).to be true
end
end
end
| 22.636364 | 94 | 0.706827 |
72a8ffc67f7015463b7a403698ccd3393e8284ee | 2,736 | kt | Kotlin | app/src/main/java/pl/jergro/shopinglist/ui/dialogs/AddOrUpdateProductDialog.kt | DeLaiT/Shopping-List-Android | 1e99a2b6a8889e4defb3f3bf85e101593fd15723 | [
"MIT"
] | 2 | 2019-05-19T16:13:39.000Z | 2019-06-23T17:20:27.000Z | app/src/main/java/pl/jergro/shopinglist/ui/dialogs/AddOrUpdateProductDialog.kt | DeLaiT/Shopping-List-Android | 1e99a2b6a8889e4defb3f3bf85e101593fd15723 | [
"MIT"
] | 7 | 2019-06-30T16:29:11.000Z | 2019-07-26T17:31:30.000Z | app/src/main/java/pl/jergro/shopinglist/ui/dialogs/AddOrUpdateProductDialog.kt | DeLaiT/Shopping-List-Android | 1e99a2b6a8889e4defb3f3bf85e101593fd15723 | [
"MIT"
] | 1 | 2019-07-01T19:43:56.000Z | 2019-07-01T19:43:56.000Z | package pl.jergro.shopinglist.ui.dialogs
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import pl.jergro.shopinglist.R
import pl.jergro.shopinglist.databinding.DialogAddProductBinding
import pl.jergro.shopinglist.models.Product
import pl.jergro.shopinglist.viewmodels.ShoppingListViewModel
import java.util.*
class AddOrUpdateProductDialog(private val viewModel: ShoppingListViewModel, context: Context) :
BottomSheetDialog(context) {
private var binding = DialogAddProductBinding.inflate(layoutInflater, null, false)
private var editedProduct: Product? = null
override fun getView(): View {
return binding.root
}
override fun onCreated() {
binding.addButton.setOnClickListener {
tryToAddOrUpdateProduct()
}
}
private fun updateUI() {
binding.isEditing = editedProduct != null
if (binding.isEditing) {
binding.newProductNameEditText.setText(editedProduct?.name)
if (editedProduct?.price != 0.0) {
binding.newProductPriceEditText.setText(editedProduct?.price.toString())
} else {
binding.newProductPriceEditText.text?.clear()
}
} else {
binding.newProductNameEditText.text?.clear()
binding.newProductPriceEditText.text?.clear()
}
}
override fun show() {
updateUI()
super.show()
}
private fun tryToAddOrUpdateProduct() {
val productName = binding.newProductNameEditText.text.toString()
val productPrice = if (binding.newProductPriceEditText.text.isNullOrBlank()) {
"0.0"
} else {
binding.newProductPriceEditText.text.toString()
}
if (productName.isBlank())
Toast.makeText(
context,
"Please enter correct shopping list name",
Toast.LENGTH_SHORT
).show()
else {
if (editedProduct != null) {
val product =
Product(editedProduct?.id!!, productName, false, productPrice.toDouble(), 0)
viewModel.updateProduct(product)
} else {
val product = Product(
UUID.randomUUID().toString(),
productName,
false,
productPrice.toDouble(),
0
)
viewModel.addProductToSelectedShoppingList(product)
}
dismiss()
}
}
fun setProduct(product: Product?) {
editedProduct = product
}
} | 31.448276 | 96 | 0.60636 |
992941e52b0d46b1257504d4364056527105fdfc | 3,434 | h | C | Projects/NUCLEO-WL55JC/Applications/SBSFU_2_Images_DualCore/2_Images_SBSFU/CM0PLUS/SBSFU/App/sfu_interface_crypto_scheme.h | 0hotpotman0/RoLa_STM32Cube | fe09ff4db46d31582b8fc06cf63b560f8543f2cc | [
"MIT"
] | 1 | 2022-03-30T09:53:52.000Z | 2022-03-30T09:53:52.000Z | cores/STM32WLE/external/STM32CubeWL/Projects/NUCLEO-WL55JC/Applications/Sigfox_SBSFU_1_Slot_DualCore/2_Images_SBSFU/CM0PLUS/SBSFU/App/sfu_interface_crypto_scheme.h | RAKWireless/RAK-STM32-RUI | 1b39ae89d3cb90a54d6bf71c7bf8da7ea5db0f4f | [
"BSD-3-Clause"
] | null | null | null | cores/STM32WLE/external/STM32CubeWL/Projects/NUCLEO-WL55JC/Applications/Sigfox_SBSFU_1_Slot_DualCore/2_Images_SBSFU/CM0PLUS/SBSFU/App/sfu_interface_crypto_scheme.h | RAKWireless/RAK-STM32-RUI | 1b39ae89d3cb90a54d6bf71c7bf8da7ea5db0f4f | [
"BSD-3-Clause"
] | 1 | 2021-09-25T16:44:11.000Z | 2021-09-25T16:44:11.000Z | /**
******************************************************************************
* @file sfu_interface_crypto_scheme.c
* @author MCD Application Team
* @brief Secure Engine Interface module.
* This file provides set of firmware functions to manage SE Interface
* functionalities. These services are used by the bootloader.
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2017 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef SFU_KMS_H
#define SFU_KMS_H
#ifdef __cplusplus
extern "C" {
#endif
/* Exported functions ------------------------------------------------------- */
SE_ErrorStatus SFU_Decrypt_Init(SE_StatusTypeDef *peSE_Status, SE_FwRawHeaderTypeDef *pxSE_Metadata,
uint32_t SE_FwType);
SE_ErrorStatus SFU_Decrypt_Append(SE_StatusTypeDef *peSE_Status, const uint8_t *pInputBuffer, int32_t InputSize,
uint8_t *pOutputBuffer, int32_t *pOutputSize);
SE_ErrorStatus SFU_Decrypt_Finish(SE_StatusTypeDef *peSE_Status, uint8_t *pOutputBuffer, int32_t *pOutputSize);
SE_ErrorStatus SFU_AuthenticateFW_Init(SE_StatusTypeDef *peSE_Status, SE_FwRawHeaderTypeDef *pxSE_Metadata,
uint32_t SE_FwType);
SE_ErrorStatus SFU_AuthenticateFW_Append(SE_StatusTypeDef *peSE_Status, const uint8_t *pInputBuffer, int32_t InputSize,
uint8_t *pOutputBuffer, int32_t *pOutputSize);
SE_ErrorStatus SFU_AuthenticateFW_Finish(SE_StatusTypeDef *peSE_Status, uint8_t *pOutputBuffer, int32_t *pOutputSize);
SE_ErrorStatus SFU_VerifyHeaderSignature(SE_StatusTypeDef *peSE_Status, SE_FwRawHeaderTypeDef *pxFwRawHeader);
#define SE_Decrypt_Init( peSE_Status, pxSE_Metadata, SE_FwType ) \
SFU_Decrypt_Init( peSE_Status, pxSE_Metadata, SE_FwType )
#define SE_Decrypt_Append( peSE_Status, pInputBuffer, InputSize, pOutputBuffer, pOutputSize ) \
SFU_Decrypt_Append( peSE_Status, pInputBuffer, InputSize, pOutputBuffer, pOutputSize )
#define SE_Decrypt_Finish( peSE_Status, pOutputBuffer, pOutputSize ) \
SFU_Decrypt_Finish( peSE_Status, pOutputBuffer, pOutputSize )
#define SE_AuthenticateFW_Init( peSE_Status, pxSE_Metadata, SE_FwType ) \
SFU_AuthenticateFW_Init( peSE_Status, pxSE_Metadata, SE_FwType )
#define SE_AuthenticateFW_Append( peSE_Status, pInputBuffer, InputSize, pOutputBuffer, pOutputSize ) \
SFU_AuthenticateFW_Append( peSE_Status, pInputBuffer, InputSize, pOutputBuffer, pOutputSize )
#define SE_AuthenticateFW_Finish( peSE_Status, pOutputBuffer, pOutputSize ) \
SFU_AuthenticateFW_Finish( peSE_Status, pOutputBuffer, pOutputSize )
#define SE_VerifyHeaderSignature( peSE_Status, pxFwRawHeader ) \
SFU_VerifyHeaderSignature( peSE_Status, pxFwRawHeader )
#ifdef __cplusplus
}
#endif
#endif /* SFU_KMS_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 46.405405 | 119 | 0.67385 |
91f56f833ee1b7d1f5a6ae522a2a40a6a3a2a2a9 | 390 | sql | SQL | src/main/resources/org/docksidestage/compilespeed/dbflute/exbhv/whitebox/pmcomment/MemberBhv_selectPmCommentOrderByIf.sql | dbflute-test/dbflute-test-env-compilespeed | 6f8742c804f3b6fed43c172fc6450c70a21348d3 | [
"Apache-2.0"
] | null | null | null | src/main/resources/org/docksidestage/compilespeed/dbflute/exbhv/whitebox/pmcomment/MemberBhv_selectPmCommentOrderByIf.sql | dbflute-test/dbflute-test-env-compilespeed | 6f8742c804f3b6fed43c172fc6450c70a21348d3 | [
"Apache-2.0"
] | null | null | null | src/main/resources/org/docksidestage/compilespeed/dbflute/exbhv/whitebox/pmcomment/MemberBhv_selectPmCommentOrderByIf.sql | dbflute-test/dbflute-test-env-compilespeed | 6f8742c804f3b6fed43c172fc6450c70a21348d3 | [
"Apache-2.0"
] | null | null | null | /*
[df:title]
IF comment for order-by
[df:description]
see you tomorrowB
*/
-- #df:entity#
-- !df:pmb!
-- !!AutoDetect!!
select member.MEMBER_ID
, member.MEMBER_NAME
, member.MEMBER_ACCOUNT
from MEMBER member
/*BEGIN*/
order by
/*IF pmb.orderByMemberId*/
member.MEMBER_ID asc
/*END*/
/*IF pmb.orderByMemberAccount*/
, member.MEMBER_Account asc
/*END*/
/*END*/
| 15 | 32 | 0.661538 |
761d573eab4d4a62118be3471b1c49ef2ee5578e | 294 | sql | SQL | group-work-2/phase.7.sql | yuetsin/SE-223 | 76c932d2cd296a752256fcaeaf3c3f7873e520ea | [
"MIT"
] | null | null | null | group-work-2/phase.7.sql | yuetsin/SE-223 | 76c932d2cd296a752256fcaeaf3c3f7873e520ea | [
"MIT"
] | null | null | null | group-work-2/phase.7.sql | yuetsin/SE-223 | 76c932d2cd296a752256fcaeaf3c3f7873e520ea | [
"MIT"
] | null | null | null | DELIMITER //
DROP PROCEDURE IF EXISTS `add_balance`;
CREATE PROCEDURE `add_balance` (
`check_username` VARCHAR(50),
`add_balance_count` DECIMAL(20, 2)
)
BEGIN
UPDATE user_attributes
SET `balance` = `balance` + `add_balance_count`
WHERE `username` = `check_username`;
END //
DELIMITER ; | 19.6 | 48 | 0.734694 |
9a3b93bf01eecfc0605b287baa2cda44bde5a2f4 | 574 | css | CSS | src/Devices.css | TonyLuque/front_manage_tool | c14c45efe4a8b98dc2c1a32d17cbf28f513d49f5 | [
"MIT"
] | null | null | null | src/Devices.css | TonyLuque/front_manage_tool | c14c45efe4a8b98dc2c1a32d17cbf28f513d49f5 | [
"MIT"
] | null | null | null | src/Devices.css | TonyLuque/front_manage_tool | c14c45efe4a8b98dc2c1a32d17cbf28f513d49f5 | [
"MIT"
] | null | null | null | .container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
padding-top: 60px;
}
.listContainer {
border: 2px solid #fff;
border-radius: 8px;
width: 90%;
margin-bottom: 40px;
}
.listItem {
display: grid;
grid-template-columns: 200px 200px 200px 200px 200px 200px;
border-bottom: 0.5px solid #c8c8c8;
width: 100%;
justify-content: center;
}
.titles {
background-color: #fff;
color: black;
}
.link {
position: absolute;
top: 10px;
right: 60px;
cursor: pointer;
}
| 15.513514 | 61 | 0.662021 |
4588308a2efff32edc03d40aca1bb690de7b1505 | 956 | swift | Swift | Sources/DocuSignAPI/Models/BrandRequest.swift | myhealthily/DocuSignAPI.swift | f08d5bf7114d1dfb6bd801d19e6f0c968d783397 | [
"Apache-2.0"
] | null | null | null | Sources/DocuSignAPI/Models/BrandRequest.swift | myhealthily/DocuSignAPI.swift | f08d5bf7114d1dfb6bd801d19e6f0c968d783397 | [
"Apache-2.0"
] | null | null | null | Sources/DocuSignAPI/Models/BrandRequest.swift | myhealthily/DocuSignAPI.swift | f08d5bf7114d1dfb6bd801d19e6f0c968d783397 | [
"Apache-2.0"
] | null | null | null | //
// BrandRequest.swift
//
// Generated by openapi-generator
// https://openapi-generator.tech
//
import AnyCodable
import Foundation
import Vapor
/** This request object contains information about a specific brand. */
public final class BrandRequest: Content, Hashable {
/** The id of the brand. */
public var brandId: String?
public init(brandId: String? = nil) {
self.brandId = brandId
}
public enum CodingKeys: String, CodingKey, CaseIterable {
case brandId
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(brandId, forKey: .brandId)
}
public static func == (lhs: BrandRequest, rhs: BrandRequest) -> Bool {
lhs.brandId == rhs.brandId
}
public func hash(into hasher: inout Hasher) {
hasher.combine(brandId?.hashValue)
}
}
| 23.9 | 74 | 0.670502 |
994ba3ff8bf1656d864db0e59690ad3447d18438 | 66,764 | h | C | bsp/TC264D/Libraries/infineon_libraries/Infra/Sfr/TC26B/_Reg/IfxCan_bf.h | GorgonMeducer/pikascript | fefe9afb17d14c1a3bbe75c4c6a83d65831f451e | [
"MIT"
] | 228 | 2021-09-11T06:09:43.000Z | 2022-03-30T08:09:01.000Z | bsp/TC264D/Libraries/infineon_libraries/Infra/Sfr/TC26B/_Reg/IfxCan_bf.h | GorgonMeducer/pikascript | fefe9afb17d14c1a3bbe75c4c6a83d65831f451e | [
"MIT"
] | 48 | 2021-09-25T01:23:43.000Z | 2022-03-31T07:34:43.000Z | bsp/TC264D/Libraries/infineon_libraries/Infra/Sfr/TC26B/_Reg/IfxCan_bf.h | GorgonMeducer/pikascript | fefe9afb17d14c1a3bbe75c4c6a83d65831f451e | [
"MIT"
] | 31 | 2021-09-17T12:06:45.000Z | 2022-03-19T16:10:11.000Z | /**
* \file IfxCan_bf.h
* \brief
* \copyright Copyright (c) 2015 Infineon Technologies AG. All rights reserved.
*
* Version: TC26XB_UM_V1.2.R0
* Specification: tc26xB_um_v1.2_MCSFR.xml (Revision: UM_V1.2)
* MAY BE CHANGED BY USER [yes/no]: No
*
* IMPORTANT NOTICE
*
* Infineon Technologies AG (Infineon) is supplying this file for use
* exclusively with Infineon's microcontroller products. This file can be freely
* distributed within development tools that are supporting such microcontroller
* products.
*
* THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
* INFINEON SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL,
* OR CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
*
* \defgroup IfxLld_Can_BitfieldsMask Bitfields mask and offset
* \ingroup IfxLld_Can
*
*/
#ifndef IFXCAN_BF_H
#define IFXCAN_BF_H 1
/******************************************************************************/
/******************************************************************************/
/** \addtogroup IfxLld_Can_BitfieldsMask
* \{ */
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN0 */
#define IFX_CAN_ACCEN0_EN0_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN0 */
#define IFX_CAN_ACCEN0_EN0_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN0 */
#define IFX_CAN_ACCEN0_EN0_OFF (0u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN10 */
#define IFX_CAN_ACCEN0_EN10_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN10 */
#define IFX_CAN_ACCEN0_EN10_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN10 */
#define IFX_CAN_ACCEN0_EN10_OFF (10u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN11 */
#define IFX_CAN_ACCEN0_EN11_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN11 */
#define IFX_CAN_ACCEN0_EN11_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN11 */
#define IFX_CAN_ACCEN0_EN11_OFF (11u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN12 */
#define IFX_CAN_ACCEN0_EN12_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN12 */
#define IFX_CAN_ACCEN0_EN12_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN12 */
#define IFX_CAN_ACCEN0_EN12_OFF (12u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN13 */
#define IFX_CAN_ACCEN0_EN13_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN13 */
#define IFX_CAN_ACCEN0_EN13_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN13 */
#define IFX_CAN_ACCEN0_EN13_OFF (13u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN14 */
#define IFX_CAN_ACCEN0_EN14_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN14 */
#define IFX_CAN_ACCEN0_EN14_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN14 */
#define IFX_CAN_ACCEN0_EN14_OFF (14u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN15 */
#define IFX_CAN_ACCEN0_EN15_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN15 */
#define IFX_CAN_ACCEN0_EN15_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN15 */
#define IFX_CAN_ACCEN0_EN15_OFF (15u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN16 */
#define IFX_CAN_ACCEN0_EN16_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN16 */
#define IFX_CAN_ACCEN0_EN16_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN16 */
#define IFX_CAN_ACCEN0_EN16_OFF (16u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN17 */
#define IFX_CAN_ACCEN0_EN17_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN17 */
#define IFX_CAN_ACCEN0_EN17_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN17 */
#define IFX_CAN_ACCEN0_EN17_OFF (17u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN18 */
#define IFX_CAN_ACCEN0_EN18_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN18 */
#define IFX_CAN_ACCEN0_EN18_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN18 */
#define IFX_CAN_ACCEN0_EN18_OFF (18u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN19 */
#define IFX_CAN_ACCEN0_EN19_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN19 */
#define IFX_CAN_ACCEN0_EN19_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN19 */
#define IFX_CAN_ACCEN0_EN19_OFF (19u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN1 */
#define IFX_CAN_ACCEN0_EN1_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN1 */
#define IFX_CAN_ACCEN0_EN1_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN1 */
#define IFX_CAN_ACCEN0_EN1_OFF (1u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN20 */
#define IFX_CAN_ACCEN0_EN20_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN20 */
#define IFX_CAN_ACCEN0_EN20_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN20 */
#define IFX_CAN_ACCEN0_EN20_OFF (20u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN21 */
#define IFX_CAN_ACCEN0_EN21_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN21 */
#define IFX_CAN_ACCEN0_EN21_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN21 */
#define IFX_CAN_ACCEN0_EN21_OFF (21u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN22 */
#define IFX_CAN_ACCEN0_EN22_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN22 */
#define IFX_CAN_ACCEN0_EN22_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN22 */
#define IFX_CAN_ACCEN0_EN22_OFF (22u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN23 */
#define IFX_CAN_ACCEN0_EN23_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN23 */
#define IFX_CAN_ACCEN0_EN23_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN23 */
#define IFX_CAN_ACCEN0_EN23_OFF (23u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN24 */
#define IFX_CAN_ACCEN0_EN24_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN24 */
#define IFX_CAN_ACCEN0_EN24_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN24 */
#define IFX_CAN_ACCEN0_EN24_OFF (24u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN25 */
#define IFX_CAN_ACCEN0_EN25_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN25 */
#define IFX_CAN_ACCEN0_EN25_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN25 */
#define IFX_CAN_ACCEN0_EN25_OFF (25u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN26 */
#define IFX_CAN_ACCEN0_EN26_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN26 */
#define IFX_CAN_ACCEN0_EN26_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN26 */
#define IFX_CAN_ACCEN0_EN26_OFF (26u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN27 */
#define IFX_CAN_ACCEN0_EN27_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN27 */
#define IFX_CAN_ACCEN0_EN27_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN27 */
#define IFX_CAN_ACCEN0_EN27_OFF (27u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN28 */
#define IFX_CAN_ACCEN0_EN28_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN28 */
#define IFX_CAN_ACCEN0_EN28_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN28 */
#define IFX_CAN_ACCEN0_EN28_OFF (28u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN29 */
#define IFX_CAN_ACCEN0_EN29_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN29 */
#define IFX_CAN_ACCEN0_EN29_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN29 */
#define IFX_CAN_ACCEN0_EN29_OFF (29u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN2 */
#define IFX_CAN_ACCEN0_EN2_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN2 */
#define IFX_CAN_ACCEN0_EN2_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN2 */
#define IFX_CAN_ACCEN0_EN2_OFF (2u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN30 */
#define IFX_CAN_ACCEN0_EN30_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN30 */
#define IFX_CAN_ACCEN0_EN30_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN30 */
#define IFX_CAN_ACCEN0_EN30_OFF (30u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN31 */
#define IFX_CAN_ACCEN0_EN31_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN31 */
#define IFX_CAN_ACCEN0_EN31_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN31 */
#define IFX_CAN_ACCEN0_EN31_OFF (31u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN3 */
#define IFX_CAN_ACCEN0_EN3_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN3 */
#define IFX_CAN_ACCEN0_EN3_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN3 */
#define IFX_CAN_ACCEN0_EN3_OFF (3u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN4 */
#define IFX_CAN_ACCEN0_EN4_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN4 */
#define IFX_CAN_ACCEN0_EN4_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN4 */
#define IFX_CAN_ACCEN0_EN4_OFF (4u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN5 */
#define IFX_CAN_ACCEN0_EN5_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN5 */
#define IFX_CAN_ACCEN0_EN5_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN5 */
#define IFX_CAN_ACCEN0_EN5_OFF (5u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN6 */
#define IFX_CAN_ACCEN0_EN6_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN6 */
#define IFX_CAN_ACCEN0_EN6_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN6 */
#define IFX_CAN_ACCEN0_EN6_OFF (6u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN7 */
#define IFX_CAN_ACCEN0_EN7_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN7 */
#define IFX_CAN_ACCEN0_EN7_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN7 */
#define IFX_CAN_ACCEN0_EN7_OFF (7u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN8 */
#define IFX_CAN_ACCEN0_EN8_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN8 */
#define IFX_CAN_ACCEN0_EN8_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN8 */
#define IFX_CAN_ACCEN0_EN8_OFF (8u)
/** \brief Length for Ifx_CAN_ACCEN0_Bits.EN9 */
#define IFX_CAN_ACCEN0_EN9_LEN (1u)
/** \brief Mask for Ifx_CAN_ACCEN0_Bits.EN9 */
#define IFX_CAN_ACCEN0_EN9_MSK (0x1u)
/** \brief Offset for Ifx_CAN_ACCEN0_Bits.EN9 */
#define IFX_CAN_ACCEN0_EN9_OFF (9u)
/** \brief Length for Ifx_CAN_CLC_Bits.DISR */
#define IFX_CAN_CLC_DISR_LEN (1u)
/** \brief Mask for Ifx_CAN_CLC_Bits.DISR */
#define IFX_CAN_CLC_DISR_MSK (0x1u)
/** \brief Offset for Ifx_CAN_CLC_Bits.DISR */
#define IFX_CAN_CLC_DISR_OFF (0u)
/** \brief Length for Ifx_CAN_CLC_Bits.DISS */
#define IFX_CAN_CLC_DISS_LEN (1u)
/** \brief Mask for Ifx_CAN_CLC_Bits.DISS */
#define IFX_CAN_CLC_DISS_MSK (0x1u)
/** \brief Offset for Ifx_CAN_CLC_Bits.DISS */
#define IFX_CAN_CLC_DISS_OFF (1u)
/** \brief Length for Ifx_CAN_CLC_Bits.EDIS */
#define IFX_CAN_CLC_EDIS_LEN (1u)
/** \brief Mask for Ifx_CAN_CLC_Bits.EDIS */
#define IFX_CAN_CLC_EDIS_MSK (0x1u)
/** \brief Offset for Ifx_CAN_CLC_Bits.EDIS */
#define IFX_CAN_CLC_EDIS_OFF (3u)
/** \brief Length for Ifx_CAN_FDR_Bits.DM */
#define IFX_CAN_FDR_DM_LEN (2u)
/** \brief Mask for Ifx_CAN_FDR_Bits.DM */
#define IFX_CAN_FDR_DM_MSK (0x3u)
/** \brief Offset for Ifx_CAN_FDR_Bits.DM */
#define IFX_CAN_FDR_DM_OFF (14u)
/** \brief Length for Ifx_CAN_FDR_Bits.STEP */
#define IFX_CAN_FDR_STEP_LEN (10u)
/** \brief Mask for Ifx_CAN_FDR_Bits.STEP */
#define IFX_CAN_FDR_STEP_MSK (0x3ffu)
/** \brief Offset for Ifx_CAN_FDR_Bits.STEP */
#define IFX_CAN_FDR_STEP_OFF (0u)
/** \brief Length for Ifx_CAN_ID_Bits.MODNUMBER */
#define IFX_CAN_ID_MODNUMBER_LEN (16u)
/** \brief Mask for Ifx_CAN_ID_Bits.MODNUMBER */
#define IFX_CAN_ID_MODNUMBER_MSK (0xffffu)
/** \brief Offset for Ifx_CAN_ID_Bits.MODNUMBER */
#define IFX_CAN_ID_MODNUMBER_OFF (16u)
/** \brief Length for Ifx_CAN_ID_Bits.MODREV */
#define IFX_CAN_ID_MODREV_LEN (8u)
/** \brief Mask for Ifx_CAN_ID_Bits.MODREV */
#define IFX_CAN_ID_MODREV_MSK (0xffu)
/** \brief Offset for Ifx_CAN_ID_Bits.MODREV */
#define IFX_CAN_ID_MODREV_OFF (0u)
/** \brief Length for Ifx_CAN_ID_Bits.MODTYPE */
#define IFX_CAN_ID_MODTYPE_LEN (8u)
/** \brief Mask for Ifx_CAN_ID_Bits.MODTYPE */
#define IFX_CAN_ID_MODTYPE_MSK (0xffu)
/** \brief Offset for Ifx_CAN_ID_Bits.MODTYPE */
#define IFX_CAN_ID_MODTYPE_OFF (8u)
/** \brief Length for Ifx_CAN_KRST0_Bits.RST */
#define IFX_CAN_KRST0_RST_LEN (1u)
/** \brief Mask for Ifx_CAN_KRST0_Bits.RST */
#define IFX_CAN_KRST0_RST_MSK (0x1u)
/** \brief Offset for Ifx_CAN_KRST0_Bits.RST */
#define IFX_CAN_KRST0_RST_OFF (0u)
/** \brief Length for Ifx_CAN_KRST0_Bits.RSTSTAT */
#define IFX_CAN_KRST0_RSTSTAT_LEN (1u)
/** \brief Mask for Ifx_CAN_KRST0_Bits.RSTSTAT */
#define IFX_CAN_KRST0_RSTSTAT_MSK (0x1u)
/** \brief Offset for Ifx_CAN_KRST0_Bits.RSTSTAT */
#define IFX_CAN_KRST0_RSTSTAT_OFF (1u)
/** \brief Length for Ifx_CAN_KRST1_Bits.RST */
#define IFX_CAN_KRST1_RST_LEN (1u)
/** \brief Mask for Ifx_CAN_KRST1_Bits.RST */
#define IFX_CAN_KRST1_RST_MSK (0x1u)
/** \brief Offset for Ifx_CAN_KRST1_Bits.RST */
#define IFX_CAN_KRST1_RST_OFF (0u)
/** \brief Length for Ifx_CAN_KRSTCLR_Bits.CLR */
#define IFX_CAN_KRSTCLR_CLR_LEN (1u)
/** \brief Mask for Ifx_CAN_KRSTCLR_Bits.CLR */
#define IFX_CAN_KRSTCLR_CLR_MSK (0x1u)
/** \brief Offset for Ifx_CAN_KRSTCLR_Bits.CLR */
#define IFX_CAN_KRSTCLR_CLR_OFF (0u)
/** \brief Length for Ifx_CAN_LIST_Bits.BEGIN */
#define IFX_CAN_LIST_BEGIN_LEN (8u)
/** \brief Mask for Ifx_CAN_LIST_Bits.BEGIN */
#define IFX_CAN_LIST_BEGIN_MSK (0xffu)
/** \brief Offset for Ifx_CAN_LIST_Bits.BEGIN */
#define IFX_CAN_LIST_BEGIN_OFF (0u)
/** \brief Length for Ifx_CAN_LIST_Bits.EMPTY */
#define IFX_CAN_LIST_EMPTY_LEN (1u)
/** \brief Mask for Ifx_CAN_LIST_Bits.EMPTY */
#define IFX_CAN_LIST_EMPTY_MSK (0x1u)
/** \brief Offset for Ifx_CAN_LIST_Bits.EMPTY */
#define IFX_CAN_LIST_EMPTY_OFF (24u)
/** \brief Length for Ifx_CAN_LIST_Bits.END */
#define IFX_CAN_LIST_END_LEN (8u)
/** \brief Mask for Ifx_CAN_LIST_Bits.END */
#define IFX_CAN_LIST_END_MSK (0xffu)
/** \brief Offset for Ifx_CAN_LIST_Bits.END */
#define IFX_CAN_LIST_END_OFF (8u)
/** \brief Length for Ifx_CAN_LIST_Bits.SIZE */
#define IFX_CAN_LIST_SIZE_LEN (8u)
/** \brief Mask for Ifx_CAN_LIST_Bits.SIZE */
#define IFX_CAN_LIST_SIZE_MSK (0xffu)
/** \brief Offset for Ifx_CAN_LIST_Bits.SIZE */
#define IFX_CAN_LIST_SIZE_OFF (16u)
/** \brief Length for Ifx_CAN_MCR_Bits.CLKSEL */
#define IFX_CAN_MCR_CLKSEL_LEN (4u)
/** \brief Mask for Ifx_CAN_MCR_Bits.CLKSEL */
#define IFX_CAN_MCR_CLKSEL_MSK (0xfu)
/** \brief Offset for Ifx_CAN_MCR_Bits.CLKSEL */
#define IFX_CAN_MCR_CLKSEL_OFF (0u)
/** \brief Length for Ifx_CAN_MCR_Bits.MPSEL */
#define IFX_CAN_MCR_MPSEL_LEN (4u)
/** \brief Mask for Ifx_CAN_MCR_Bits.MPSEL */
#define IFX_CAN_MCR_MPSEL_MSK (0xfu)
/** \brief Offset for Ifx_CAN_MCR_Bits.MPSEL */
#define IFX_CAN_MCR_MPSEL_OFF (12u)
/** \brief Length for Ifx_CAN_MECR_Bits.ANYED */
#define IFX_CAN_MECR_ANYED_LEN (1u)
/** \brief Mask for Ifx_CAN_MECR_Bits.ANYED */
#define IFX_CAN_MECR_ANYED_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MECR_Bits.ANYED */
#define IFX_CAN_MECR_ANYED_OFF (24u)
/** \brief Length for Ifx_CAN_MECR_Bits.CAPEIE */
#define IFX_CAN_MECR_CAPEIE_LEN (1u)
/** \brief Mask for Ifx_CAN_MECR_Bits.CAPEIE */
#define IFX_CAN_MECR_CAPEIE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MECR_Bits.CAPEIE */
#define IFX_CAN_MECR_CAPEIE_OFF (25u)
/** \brief Length for Ifx_CAN_MECR_Bits.DEPTH */
#define IFX_CAN_MECR_DEPTH_LEN (3u)
/** \brief Mask for Ifx_CAN_MECR_Bits.DEPTH */
#define IFX_CAN_MECR_DEPTH_MSK (0x7u)
/** \brief Offset for Ifx_CAN_MECR_Bits.DEPTH */
#define IFX_CAN_MECR_DEPTH_OFF (27u)
/** \brief Length for Ifx_CAN_MECR_Bits.INP */
#define IFX_CAN_MECR_INP_LEN (4u)
/** \brief Mask for Ifx_CAN_MECR_Bits.INP */
#define IFX_CAN_MECR_INP_MSK (0xfu)
/** \brief Offset for Ifx_CAN_MECR_Bits.INP */
#define IFX_CAN_MECR_INP_OFF (16u)
/** \brief Length for Ifx_CAN_MECR_Bits.NODE */
#define IFX_CAN_MECR_NODE_LEN (3u)
/** \brief Mask for Ifx_CAN_MECR_Bits.NODE */
#define IFX_CAN_MECR_NODE_MSK (0x7u)
/** \brief Offset for Ifx_CAN_MECR_Bits.NODE */
#define IFX_CAN_MECR_NODE_OFF (20u)
/** \brief Length for Ifx_CAN_MECR_Bits.SOF */
#define IFX_CAN_MECR_SOF_LEN (1u)
/** \brief Mask for Ifx_CAN_MECR_Bits.SOF */
#define IFX_CAN_MECR_SOF_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MECR_Bits.SOF */
#define IFX_CAN_MECR_SOF_OFF (30u)
/** \brief Length for Ifx_CAN_MECR_Bits.TH */
#define IFX_CAN_MECR_TH_LEN (16u)
/** \brief Mask for Ifx_CAN_MECR_Bits.TH */
#define IFX_CAN_MECR_TH_MSK (0xffffu)
/** \brief Offset for Ifx_CAN_MECR_Bits.TH */
#define IFX_CAN_MECR_TH_OFF (0u)
/** \brief Length for Ifx_CAN_MESTAT_Bits.CAPE */
#define IFX_CAN_MESTAT_CAPE_LEN (1u)
/** \brief Mask for Ifx_CAN_MESTAT_Bits.CAPE */
#define IFX_CAN_MESTAT_CAPE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MESTAT_Bits.CAPE */
#define IFX_CAN_MESTAT_CAPE_OFF (17u)
/** \brief Length for Ifx_CAN_MESTAT_Bits.CAPRED */
#define IFX_CAN_MESTAT_CAPRED_LEN (1u)
/** \brief Mask for Ifx_CAN_MESTAT_Bits.CAPRED */
#define IFX_CAN_MESTAT_CAPRED_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MESTAT_Bits.CAPRED */
#define IFX_CAN_MESTAT_CAPRED_OFF (16u)
/** \brief Length for Ifx_CAN_MESTAT_Bits.CAPT */
#define IFX_CAN_MESTAT_CAPT_LEN (16u)
/** \brief Mask for Ifx_CAN_MESTAT_Bits.CAPT */
#define IFX_CAN_MESTAT_CAPT_MSK (0xffffu)
/** \brief Offset for Ifx_CAN_MESTAT_Bits.CAPT */
#define IFX_CAN_MESTAT_CAPT_OFF (0u)
/** \brief Length for Ifx_CAN_MITR_Bits.IT */
#define IFX_CAN_MITR_IT_LEN (16u)
/** \brief Mask for Ifx_CAN_MITR_Bits.IT */
#define IFX_CAN_MITR_IT_MSK (0xffffu)
/** \brief Offset for Ifx_CAN_MITR_Bits.IT */
#define IFX_CAN_MITR_IT_OFF (0u)
/** \brief Length for Ifx_CAN_MO_AMR_Bits.AM */
#define IFX_CAN_MO_AMR_AM_LEN (29u)
/** \brief Mask for Ifx_CAN_MO_AMR_Bits.AM */
#define IFX_CAN_MO_AMR_AM_MSK (0x1fffffffu)
/** \brief Offset for Ifx_CAN_MO_AMR_Bits.AM */
#define IFX_CAN_MO_AMR_AM_OFF (0u)
/** \brief Length for Ifx_CAN_MO_AMR_Bits.MIDE */
#define IFX_CAN_MO_AMR_MIDE_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_AMR_Bits.MIDE */
#define IFX_CAN_MO_AMR_MIDE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_AMR_Bits.MIDE */
#define IFX_CAN_MO_AMR_MIDE_OFF (29u)
/** \brief Length for Ifx_CAN_MO_AR_Bits.ID */
#define IFX_CAN_MO_AR_ID_LEN (29u)
/** \brief Mask for Ifx_CAN_MO_AR_Bits.ID */
#define IFX_CAN_MO_AR_ID_MSK (0x1fffffffu)
/** \brief Offset for Ifx_CAN_MO_AR_Bits.ID */
#define IFX_CAN_MO_AR_ID_OFF (0u)
/** \brief Length for Ifx_CAN_MO_AR_Bits.IDE */
#define IFX_CAN_MO_AR_IDE_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_AR_Bits.IDE */
#define IFX_CAN_MO_AR_IDE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_AR_Bits.IDE */
#define IFX_CAN_MO_AR_IDE_OFF (29u)
/** \brief Length for Ifx_CAN_MO_AR_Bits.PRI */
#define IFX_CAN_MO_AR_PRI_LEN (2u)
/** \brief Mask for Ifx_CAN_MO_AR_Bits.PRI */
#define IFX_CAN_MO_AR_PRI_MSK (0x3u)
/** \brief Offset for Ifx_CAN_MO_AR_Bits.PRI */
#define IFX_CAN_MO_AR_PRI_OFF (30u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESDIR */
#define IFX_CAN_MO_CTR_RESDIR_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESDIR */
#define IFX_CAN_MO_CTR_RESDIR_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESDIR */
#define IFX_CAN_MO_CTR_RESDIR_OFF (11u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESMSGLST */
#define IFX_CAN_MO_CTR_RESMSGLST_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESMSGLST */
#define IFX_CAN_MO_CTR_RESMSGLST_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESMSGLST */
#define IFX_CAN_MO_CTR_RESMSGLST_OFF (4u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESMSGVAL */
#define IFX_CAN_MO_CTR_RESMSGVAL_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESMSGVAL */
#define IFX_CAN_MO_CTR_RESMSGVAL_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESMSGVAL */
#define IFX_CAN_MO_CTR_RESMSGVAL_OFF (5u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESNEWDAT */
#define IFX_CAN_MO_CTR_RESNEWDAT_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESNEWDAT */
#define IFX_CAN_MO_CTR_RESNEWDAT_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESNEWDAT */
#define IFX_CAN_MO_CTR_RESNEWDAT_OFF (3u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESRTSEL */
#define IFX_CAN_MO_CTR_RESRTSEL_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESRTSEL */
#define IFX_CAN_MO_CTR_RESRTSEL_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESRTSEL */
#define IFX_CAN_MO_CTR_RESRTSEL_OFF (6u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESRXEN */
#define IFX_CAN_MO_CTR_RESRXEN_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESRXEN */
#define IFX_CAN_MO_CTR_RESRXEN_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESRXEN */
#define IFX_CAN_MO_CTR_RESRXEN_OFF (7u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESRXPND */
#define IFX_CAN_MO_CTR_RESRXPND_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESRXPND */
#define IFX_CAN_MO_CTR_RESRXPND_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESRXPND */
#define IFX_CAN_MO_CTR_RESRXPND_OFF (0u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESRXUPD */
#define IFX_CAN_MO_CTR_RESRXUPD_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESRXUPD */
#define IFX_CAN_MO_CTR_RESRXUPD_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESRXUPD */
#define IFX_CAN_MO_CTR_RESRXUPD_OFF (2u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESTXEN0 */
#define IFX_CAN_MO_CTR_RESTXEN0_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESTXEN0 */
#define IFX_CAN_MO_CTR_RESTXEN0_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESTXEN0 */
#define IFX_CAN_MO_CTR_RESTXEN0_OFF (9u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESTXEN1 */
#define IFX_CAN_MO_CTR_RESTXEN1_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESTXEN1 */
#define IFX_CAN_MO_CTR_RESTXEN1_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESTXEN1 */
#define IFX_CAN_MO_CTR_RESTXEN1_OFF (10u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESTXPND */
#define IFX_CAN_MO_CTR_RESTXPND_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESTXPND */
#define IFX_CAN_MO_CTR_RESTXPND_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESTXPND */
#define IFX_CAN_MO_CTR_RESTXPND_OFF (1u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.RESTXRQ */
#define IFX_CAN_MO_CTR_RESTXRQ_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.RESTXRQ */
#define IFX_CAN_MO_CTR_RESTXRQ_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.RESTXRQ */
#define IFX_CAN_MO_CTR_RESTXRQ_OFF (8u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETDIR */
#define IFX_CAN_MO_CTR_SETDIR_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETDIR */
#define IFX_CAN_MO_CTR_SETDIR_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETDIR */
#define IFX_CAN_MO_CTR_SETDIR_OFF (27u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETMSGLST */
#define IFX_CAN_MO_CTR_SETMSGLST_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETMSGLST */
#define IFX_CAN_MO_CTR_SETMSGLST_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETMSGLST */
#define IFX_CAN_MO_CTR_SETMSGLST_OFF (20u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETMSGVAL */
#define IFX_CAN_MO_CTR_SETMSGVAL_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETMSGVAL */
#define IFX_CAN_MO_CTR_SETMSGVAL_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETMSGVAL */
#define IFX_CAN_MO_CTR_SETMSGVAL_OFF (21u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETNEWDAT */
#define IFX_CAN_MO_CTR_SETNEWDAT_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETNEWDAT */
#define IFX_CAN_MO_CTR_SETNEWDAT_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETNEWDAT */
#define IFX_CAN_MO_CTR_SETNEWDAT_OFF (19u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETRTSEL */
#define IFX_CAN_MO_CTR_SETRTSEL_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETRTSEL */
#define IFX_CAN_MO_CTR_SETRTSEL_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETRTSEL */
#define IFX_CAN_MO_CTR_SETRTSEL_OFF (22u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETRXEN */
#define IFX_CAN_MO_CTR_SETRXEN_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETRXEN */
#define IFX_CAN_MO_CTR_SETRXEN_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETRXEN */
#define IFX_CAN_MO_CTR_SETRXEN_OFF (23u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETRXPND */
#define IFX_CAN_MO_CTR_SETRXPND_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETRXPND */
#define IFX_CAN_MO_CTR_SETRXPND_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETRXPND */
#define IFX_CAN_MO_CTR_SETRXPND_OFF (16u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETRXUPD */
#define IFX_CAN_MO_CTR_SETRXUPD_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETRXUPD */
#define IFX_CAN_MO_CTR_SETRXUPD_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETRXUPD */
#define IFX_CAN_MO_CTR_SETRXUPD_OFF (18u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETTXEN0 */
#define IFX_CAN_MO_CTR_SETTXEN0_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETTXEN0 */
#define IFX_CAN_MO_CTR_SETTXEN0_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETTXEN0 */
#define IFX_CAN_MO_CTR_SETTXEN0_OFF (25u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETTXEN1 */
#define IFX_CAN_MO_CTR_SETTXEN1_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETTXEN1 */
#define IFX_CAN_MO_CTR_SETTXEN1_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETTXEN1 */
#define IFX_CAN_MO_CTR_SETTXEN1_OFF (26u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETTXPND */
#define IFX_CAN_MO_CTR_SETTXPND_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETTXPND */
#define IFX_CAN_MO_CTR_SETTXPND_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETTXPND */
#define IFX_CAN_MO_CTR_SETTXPND_OFF (17u)
/** \brief Length for Ifx_CAN_MO_CTR_Bits.SETTXRQ */
#define IFX_CAN_MO_CTR_SETTXRQ_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_CTR_Bits.SETTXRQ */
#define IFX_CAN_MO_CTR_SETTXRQ_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_CTR_Bits.SETTXRQ */
#define IFX_CAN_MO_CTR_SETTXRQ_OFF (24u)
/** \brief Length for Ifx_CAN_MO_DATAH_Bits.DB4 */
#define IFX_CAN_MO_DATAH_DB4_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_DATAH_Bits.DB4 */
#define IFX_CAN_MO_DATAH_DB4_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_DATAH_Bits.DB4 */
#define IFX_CAN_MO_DATAH_DB4_OFF (0u)
/** \brief Length for Ifx_CAN_MO_DATAH_Bits.DB5 */
#define IFX_CAN_MO_DATAH_DB5_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_DATAH_Bits.DB5 */
#define IFX_CAN_MO_DATAH_DB5_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_DATAH_Bits.DB5 */
#define IFX_CAN_MO_DATAH_DB5_OFF (8u)
/** \brief Length for Ifx_CAN_MO_DATAH_Bits.DB6 */
#define IFX_CAN_MO_DATAH_DB6_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_DATAH_Bits.DB6 */
#define IFX_CAN_MO_DATAH_DB6_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_DATAH_Bits.DB6 */
#define IFX_CAN_MO_DATAH_DB6_OFF (16u)
/** \brief Length for Ifx_CAN_MO_DATAH_Bits.DB7 */
#define IFX_CAN_MO_DATAH_DB7_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_DATAH_Bits.DB7 */
#define IFX_CAN_MO_DATAH_DB7_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_DATAH_Bits.DB7 */
#define IFX_CAN_MO_DATAH_DB7_OFF (24u)
/** \brief Length for Ifx_CAN_MO_DATAL_Bits.DB0 */
#define IFX_CAN_MO_DATAL_DB0_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_DATAL_Bits.DB0 */
#define IFX_CAN_MO_DATAL_DB0_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_DATAL_Bits.DB0 */
#define IFX_CAN_MO_DATAL_DB0_OFF (0u)
/** \brief Length for Ifx_CAN_MO_DATAL_Bits.DB1 */
#define IFX_CAN_MO_DATAL_DB1_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_DATAL_Bits.DB1 */
#define IFX_CAN_MO_DATAL_DB1_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_DATAL_Bits.DB1 */
#define IFX_CAN_MO_DATAL_DB1_OFF (8u)
/** \brief Length for Ifx_CAN_MO_DATAL_Bits.DB2 */
#define IFX_CAN_MO_DATAL_DB2_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_DATAL_Bits.DB2 */
#define IFX_CAN_MO_DATAL_DB2_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_DATAL_Bits.DB2 */
#define IFX_CAN_MO_DATAL_DB2_OFF (16u)
/** \brief Length for Ifx_CAN_MO_DATAL_Bits.DB3 */
#define IFX_CAN_MO_DATAL_DB3_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_DATAL_Bits.DB3 */
#define IFX_CAN_MO_DATAL_DB3_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_DATAL_Bits.DB3 */
#define IFX_CAN_MO_DATAL_DB3_OFF (24u)
/** \brief Length for Ifx_CAN_MO_EDATA0_Bits.DB0 */
#define IFX_CAN_MO_EDATA0_DB0_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA0_Bits.DB0 */
#define IFX_CAN_MO_EDATA0_DB0_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA0_Bits.DB0 */
#define IFX_CAN_MO_EDATA0_DB0_OFF (0u)
/** \brief Length for Ifx_CAN_MO_EDATA0_Bits.DB1 */
#define IFX_CAN_MO_EDATA0_DB1_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA0_Bits.DB1 */
#define IFX_CAN_MO_EDATA0_DB1_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA0_Bits.DB1 */
#define IFX_CAN_MO_EDATA0_DB1_OFF (8u)
/** \brief Length for Ifx_CAN_MO_EDATA0_Bits.DB2 */
#define IFX_CAN_MO_EDATA0_DB2_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA0_Bits.DB2 */
#define IFX_CAN_MO_EDATA0_DB2_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA0_Bits.DB2 */
#define IFX_CAN_MO_EDATA0_DB2_OFF (16u)
/** \brief Length for Ifx_CAN_MO_EDATA0_Bits.DB3 */
#define IFX_CAN_MO_EDATA0_DB3_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA0_Bits.DB3 */
#define IFX_CAN_MO_EDATA0_DB3_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA0_Bits.DB3 */
#define IFX_CAN_MO_EDATA0_DB3_OFF (24u)
/** \brief Length for Ifx_CAN_MO_EDATA1_Bits.DB0 */
#define IFX_CAN_MO_EDATA1_DB0_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA1_Bits.DB0 */
#define IFX_CAN_MO_EDATA1_DB0_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA1_Bits.DB0 */
#define IFX_CAN_MO_EDATA1_DB0_OFF (0u)
/** \brief Length for Ifx_CAN_MO_EDATA1_Bits.DB1 */
#define IFX_CAN_MO_EDATA1_DB1_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA1_Bits.DB1 */
#define IFX_CAN_MO_EDATA1_DB1_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA1_Bits.DB1 */
#define IFX_CAN_MO_EDATA1_DB1_OFF (8u)
/** \brief Length for Ifx_CAN_MO_EDATA1_Bits.DB2 */
#define IFX_CAN_MO_EDATA1_DB2_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA1_Bits.DB2 */
#define IFX_CAN_MO_EDATA1_DB2_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA1_Bits.DB2 */
#define IFX_CAN_MO_EDATA1_DB2_OFF (16u)
/** \brief Length for Ifx_CAN_MO_EDATA1_Bits.DB3 */
#define IFX_CAN_MO_EDATA1_DB3_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA1_Bits.DB3 */
#define IFX_CAN_MO_EDATA1_DB3_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA1_Bits.DB3 */
#define IFX_CAN_MO_EDATA1_DB3_OFF (24u)
/** \brief Length for Ifx_CAN_MO_EDATA2_Bits.DB0 */
#define IFX_CAN_MO_EDATA2_DB0_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA2_Bits.DB0 */
#define IFX_CAN_MO_EDATA2_DB0_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA2_Bits.DB0 */
#define IFX_CAN_MO_EDATA2_DB0_OFF (0u)
/** \brief Length for Ifx_CAN_MO_EDATA2_Bits.DB1 */
#define IFX_CAN_MO_EDATA2_DB1_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA2_Bits.DB1 */
#define IFX_CAN_MO_EDATA2_DB1_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA2_Bits.DB1 */
#define IFX_CAN_MO_EDATA2_DB1_OFF (8u)
/** \brief Length for Ifx_CAN_MO_EDATA2_Bits.DB2 */
#define IFX_CAN_MO_EDATA2_DB2_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA2_Bits.DB2 */
#define IFX_CAN_MO_EDATA2_DB2_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA2_Bits.DB2 */
#define IFX_CAN_MO_EDATA2_DB2_OFF (16u)
/** \brief Length for Ifx_CAN_MO_EDATA2_Bits.DB3 */
#define IFX_CAN_MO_EDATA2_DB3_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA2_Bits.DB3 */
#define IFX_CAN_MO_EDATA2_DB3_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA2_Bits.DB3 */
#define IFX_CAN_MO_EDATA2_DB3_OFF (24u)
/** \brief Length for Ifx_CAN_MO_EDATA3_Bits.DB0 */
#define IFX_CAN_MO_EDATA3_DB0_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA3_Bits.DB0 */
#define IFX_CAN_MO_EDATA3_DB0_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA3_Bits.DB0 */
#define IFX_CAN_MO_EDATA3_DB0_OFF (0u)
/** \brief Length for Ifx_CAN_MO_EDATA3_Bits.DB1 */
#define IFX_CAN_MO_EDATA3_DB1_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA3_Bits.DB1 */
#define IFX_CAN_MO_EDATA3_DB1_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA3_Bits.DB1 */
#define IFX_CAN_MO_EDATA3_DB1_OFF (8u)
/** \brief Length for Ifx_CAN_MO_EDATA3_Bits.DB2 */
#define IFX_CAN_MO_EDATA3_DB2_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA3_Bits.DB2 */
#define IFX_CAN_MO_EDATA3_DB2_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA3_Bits.DB2 */
#define IFX_CAN_MO_EDATA3_DB2_OFF (16u)
/** \brief Length for Ifx_CAN_MO_EDATA3_Bits.DB3 */
#define IFX_CAN_MO_EDATA3_DB3_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA3_Bits.DB3 */
#define IFX_CAN_MO_EDATA3_DB3_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA3_Bits.DB3 */
#define IFX_CAN_MO_EDATA3_DB3_OFF (24u)
/** \brief Length for Ifx_CAN_MO_EDATA4_Bits.DB0 */
#define IFX_CAN_MO_EDATA4_DB0_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA4_Bits.DB0 */
#define IFX_CAN_MO_EDATA4_DB0_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA4_Bits.DB0 */
#define IFX_CAN_MO_EDATA4_DB0_OFF (0u)
/** \brief Length for Ifx_CAN_MO_EDATA4_Bits.DB1 */
#define IFX_CAN_MO_EDATA4_DB1_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA4_Bits.DB1 */
#define IFX_CAN_MO_EDATA4_DB1_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA4_Bits.DB1 */
#define IFX_CAN_MO_EDATA4_DB1_OFF (8u)
/** \brief Length for Ifx_CAN_MO_EDATA4_Bits.DB2 */
#define IFX_CAN_MO_EDATA4_DB2_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA4_Bits.DB2 */
#define IFX_CAN_MO_EDATA4_DB2_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA4_Bits.DB2 */
#define IFX_CAN_MO_EDATA4_DB2_OFF (16u)
/** \brief Length for Ifx_CAN_MO_EDATA4_Bits.DB3 */
#define IFX_CAN_MO_EDATA4_DB3_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA4_Bits.DB3 */
#define IFX_CAN_MO_EDATA4_DB3_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA4_Bits.DB3 */
#define IFX_CAN_MO_EDATA4_DB3_OFF (24u)
/** \brief Length for Ifx_CAN_MO_EDATA5_Bits.DB0 */
#define IFX_CAN_MO_EDATA5_DB0_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA5_Bits.DB0 */
#define IFX_CAN_MO_EDATA5_DB0_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA5_Bits.DB0 */
#define IFX_CAN_MO_EDATA5_DB0_OFF (0u)
/** \brief Length for Ifx_CAN_MO_EDATA5_Bits.DB1 */
#define IFX_CAN_MO_EDATA5_DB1_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA5_Bits.DB1 */
#define IFX_CAN_MO_EDATA5_DB1_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA5_Bits.DB1 */
#define IFX_CAN_MO_EDATA5_DB1_OFF (8u)
/** \brief Length for Ifx_CAN_MO_EDATA5_Bits.DB2 */
#define IFX_CAN_MO_EDATA5_DB2_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA5_Bits.DB2 */
#define IFX_CAN_MO_EDATA5_DB2_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA5_Bits.DB2 */
#define IFX_CAN_MO_EDATA5_DB2_OFF (16u)
/** \brief Length for Ifx_CAN_MO_EDATA5_Bits.DB3 */
#define IFX_CAN_MO_EDATA5_DB3_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA5_Bits.DB3 */
#define IFX_CAN_MO_EDATA5_DB3_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA5_Bits.DB3 */
#define IFX_CAN_MO_EDATA5_DB3_OFF (24u)
/** \brief Length for Ifx_CAN_MO_EDATA6_Bits.DB0 */
#define IFX_CAN_MO_EDATA6_DB0_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA6_Bits.DB0 */
#define IFX_CAN_MO_EDATA6_DB0_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA6_Bits.DB0 */
#define IFX_CAN_MO_EDATA6_DB0_OFF (0u)
/** \brief Length for Ifx_CAN_MO_EDATA6_Bits.DB1 */
#define IFX_CAN_MO_EDATA6_DB1_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA6_Bits.DB1 */
#define IFX_CAN_MO_EDATA6_DB1_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA6_Bits.DB1 */
#define IFX_CAN_MO_EDATA6_DB1_OFF (8u)
/** \brief Length for Ifx_CAN_MO_EDATA6_Bits.DB2 */
#define IFX_CAN_MO_EDATA6_DB2_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA6_Bits.DB2 */
#define IFX_CAN_MO_EDATA6_DB2_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA6_Bits.DB2 */
#define IFX_CAN_MO_EDATA6_DB2_OFF (16u)
/** \brief Length for Ifx_CAN_MO_EDATA6_Bits.DB3 */
#define IFX_CAN_MO_EDATA6_DB3_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_EDATA6_Bits.DB3 */
#define IFX_CAN_MO_EDATA6_DB3_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_EDATA6_Bits.DB3 */
#define IFX_CAN_MO_EDATA6_DB3_OFF (24u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.BRS */
#define IFX_CAN_MO_FCR_BRS_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.BRS */
#define IFX_CAN_MO_FCR_BRS_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.BRS */
#define IFX_CAN_MO_FCR_BRS_OFF (5u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.DATC */
#define IFX_CAN_MO_FCR_DATC_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.DATC */
#define IFX_CAN_MO_FCR_DATC_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.DATC */
#define IFX_CAN_MO_FCR_DATC_OFF (11u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.DLC */
#define IFX_CAN_MO_FCR_DLC_LEN (4u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.DLC */
#define IFX_CAN_MO_FCR_DLC_MSK (0xfu)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.DLC */
#define IFX_CAN_MO_FCR_DLC_OFF (24u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.DLCC */
#define IFX_CAN_MO_FCR_DLCC_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.DLCC */
#define IFX_CAN_MO_FCR_DLCC_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.DLCC */
#define IFX_CAN_MO_FCR_DLCC_OFF (10u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.FDF */
#define IFX_CAN_MO_FCR_FDF_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.FDF */
#define IFX_CAN_MO_FCR_FDF_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.FDF */
#define IFX_CAN_MO_FCR_FDF_OFF (6u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.FRREN */
#define IFX_CAN_MO_FCR_FRREN_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.FRREN */
#define IFX_CAN_MO_FCR_FRREN_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.FRREN */
#define IFX_CAN_MO_FCR_FRREN_OFF (20u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.GDFS */
#define IFX_CAN_MO_FCR_GDFS_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.GDFS */
#define IFX_CAN_MO_FCR_GDFS_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.GDFS */
#define IFX_CAN_MO_FCR_GDFS_OFF (8u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.IDC */
#define IFX_CAN_MO_FCR_IDC_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.IDC */
#define IFX_CAN_MO_FCR_IDC_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.IDC */
#define IFX_CAN_MO_FCR_IDC_OFF (9u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.MMC */
#define IFX_CAN_MO_FCR_MMC_LEN (4u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.MMC */
#define IFX_CAN_MO_FCR_MMC_MSK (0xfu)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.MMC */
#define IFX_CAN_MO_FCR_MMC_OFF (0u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.OVIE */
#define IFX_CAN_MO_FCR_OVIE_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.OVIE */
#define IFX_CAN_MO_FCR_OVIE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.OVIE */
#define IFX_CAN_MO_FCR_OVIE_OFF (18u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.RMM */
#define IFX_CAN_MO_FCR_RMM_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.RMM */
#define IFX_CAN_MO_FCR_RMM_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.RMM */
#define IFX_CAN_MO_FCR_RMM_OFF (21u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.RXIE */
#define IFX_CAN_MO_FCR_RXIE_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.RXIE */
#define IFX_CAN_MO_FCR_RXIE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.RXIE */
#define IFX_CAN_MO_FCR_RXIE_OFF (16u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.RXTOE */
#define IFX_CAN_MO_FCR_RXTOE_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.RXTOE */
#define IFX_CAN_MO_FCR_RXTOE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.RXTOE */
#define IFX_CAN_MO_FCR_RXTOE_OFF (4u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.SDT */
#define IFX_CAN_MO_FCR_SDT_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.SDT */
#define IFX_CAN_MO_FCR_SDT_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.SDT */
#define IFX_CAN_MO_FCR_SDT_OFF (22u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.STT */
#define IFX_CAN_MO_FCR_STT_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.STT */
#define IFX_CAN_MO_FCR_STT_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.STT */
#define IFX_CAN_MO_FCR_STT_OFF (23u)
/** \brief Length for Ifx_CAN_MO_FCR_Bits.TXIE */
#define IFX_CAN_MO_FCR_TXIE_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_FCR_Bits.TXIE */
#define IFX_CAN_MO_FCR_TXIE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_FCR_Bits.TXIE */
#define IFX_CAN_MO_FCR_TXIE_OFF (17u)
/** \brief Length for Ifx_CAN_MO_FGPR_Bits.BOT */
#define IFX_CAN_MO_FGPR_BOT_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_FGPR_Bits.BOT */
#define IFX_CAN_MO_FGPR_BOT_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_FGPR_Bits.BOT */
#define IFX_CAN_MO_FGPR_BOT_OFF (0u)
/** \brief Length for Ifx_CAN_MO_FGPR_Bits.CUR */
#define IFX_CAN_MO_FGPR_CUR_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_FGPR_Bits.CUR */
#define IFX_CAN_MO_FGPR_CUR_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_FGPR_Bits.CUR */
#define IFX_CAN_MO_FGPR_CUR_OFF (16u)
/** \brief Length for Ifx_CAN_MO_FGPR_Bits.SEL */
#define IFX_CAN_MO_FGPR_SEL_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_FGPR_Bits.SEL */
#define IFX_CAN_MO_FGPR_SEL_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_FGPR_Bits.SEL */
#define IFX_CAN_MO_FGPR_SEL_OFF (24u)
/** \brief Length for Ifx_CAN_MO_FGPR_Bits.TOP */
#define IFX_CAN_MO_FGPR_TOP_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_FGPR_Bits.TOP */
#define IFX_CAN_MO_FGPR_TOP_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_FGPR_Bits.TOP */
#define IFX_CAN_MO_FGPR_TOP_OFF (8u)
/** \brief Length for Ifx_CAN_MO_IPR_Bits.CFCVAL */
#define IFX_CAN_MO_IPR_CFCVAL_LEN (16u)
/** \brief Mask for Ifx_CAN_MO_IPR_Bits.CFCVAL */
#define IFX_CAN_MO_IPR_CFCVAL_MSK (0xffffu)
/** \brief Offset for Ifx_CAN_MO_IPR_Bits.CFCVAL */
#define IFX_CAN_MO_IPR_CFCVAL_OFF (16u)
/** \brief Length for Ifx_CAN_MO_IPR_Bits.MPN */
#define IFX_CAN_MO_IPR_MPN_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_IPR_Bits.MPN */
#define IFX_CAN_MO_IPR_MPN_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_IPR_Bits.MPN */
#define IFX_CAN_MO_IPR_MPN_OFF (8u)
/** \brief Length for Ifx_CAN_MO_IPR_Bits.RXINP */
#define IFX_CAN_MO_IPR_RXINP_LEN (4u)
/** \brief Mask for Ifx_CAN_MO_IPR_Bits.RXINP */
#define IFX_CAN_MO_IPR_RXINP_MSK (0xfu)
/** \brief Offset for Ifx_CAN_MO_IPR_Bits.RXINP */
#define IFX_CAN_MO_IPR_RXINP_OFF (0u)
/** \brief Length for Ifx_CAN_MO_IPR_Bits.TXINP */
#define IFX_CAN_MO_IPR_TXINP_LEN (4u)
/** \brief Mask for Ifx_CAN_MO_IPR_Bits.TXINP */
#define IFX_CAN_MO_IPR_TXINP_MSK (0xfu)
/** \brief Offset for Ifx_CAN_MO_IPR_Bits.TXINP */
#define IFX_CAN_MO_IPR_TXINP_OFF (4u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.DIR */
#define IFX_CAN_MO_STAT_DIR_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.DIR */
#define IFX_CAN_MO_STAT_DIR_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.DIR */
#define IFX_CAN_MO_STAT_DIR_OFF (11u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.LIST */
#define IFX_CAN_MO_STAT_LIST_LEN (4u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.LIST */
#define IFX_CAN_MO_STAT_LIST_MSK (0xfu)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.LIST */
#define IFX_CAN_MO_STAT_LIST_OFF (12u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.MSGLST */
#define IFX_CAN_MO_STAT_MSGLST_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.MSGLST */
#define IFX_CAN_MO_STAT_MSGLST_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.MSGLST */
#define IFX_CAN_MO_STAT_MSGLST_OFF (4u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.MSGVAL */
#define IFX_CAN_MO_STAT_MSGVAL_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.MSGVAL */
#define IFX_CAN_MO_STAT_MSGVAL_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.MSGVAL */
#define IFX_CAN_MO_STAT_MSGVAL_OFF (5u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.NEWDAT */
#define IFX_CAN_MO_STAT_NEWDAT_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.NEWDAT */
#define IFX_CAN_MO_STAT_NEWDAT_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.NEWDAT */
#define IFX_CAN_MO_STAT_NEWDAT_OFF (3u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.PNEXT */
#define IFX_CAN_MO_STAT_PNEXT_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.PNEXT */
#define IFX_CAN_MO_STAT_PNEXT_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.PNEXT */
#define IFX_CAN_MO_STAT_PNEXT_OFF (24u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.PPREV */
#define IFX_CAN_MO_STAT_PPREV_LEN (8u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.PPREV */
#define IFX_CAN_MO_STAT_PPREV_MSK (0xffu)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.PPREV */
#define IFX_CAN_MO_STAT_PPREV_OFF (16u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.RTSEL */
#define IFX_CAN_MO_STAT_RTSEL_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.RTSEL */
#define IFX_CAN_MO_STAT_RTSEL_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.RTSEL */
#define IFX_CAN_MO_STAT_RTSEL_OFF (6u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.RXEN */
#define IFX_CAN_MO_STAT_RXEN_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.RXEN */
#define IFX_CAN_MO_STAT_RXEN_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.RXEN */
#define IFX_CAN_MO_STAT_RXEN_OFF (7u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.RXPND */
#define IFX_CAN_MO_STAT_RXPND_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.RXPND */
#define IFX_CAN_MO_STAT_RXPND_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.RXPND */
#define IFX_CAN_MO_STAT_RXPND_OFF (0u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.RXUPD */
#define IFX_CAN_MO_STAT_RXUPD_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.RXUPD */
#define IFX_CAN_MO_STAT_RXUPD_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.RXUPD */
#define IFX_CAN_MO_STAT_RXUPD_OFF (2u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.TXEN0 */
#define IFX_CAN_MO_STAT_TXEN0_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.TXEN0 */
#define IFX_CAN_MO_STAT_TXEN0_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.TXEN0 */
#define IFX_CAN_MO_STAT_TXEN0_OFF (9u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.TXEN1 */
#define IFX_CAN_MO_STAT_TXEN1_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.TXEN1 */
#define IFX_CAN_MO_STAT_TXEN1_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.TXEN1 */
#define IFX_CAN_MO_STAT_TXEN1_OFF (10u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.TXPND */
#define IFX_CAN_MO_STAT_TXPND_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.TXPND */
#define IFX_CAN_MO_STAT_TXPND_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.TXPND */
#define IFX_CAN_MO_STAT_TXPND_OFF (1u)
/** \brief Length for Ifx_CAN_MO_STAT_Bits.TXRQ */
#define IFX_CAN_MO_STAT_TXRQ_LEN (1u)
/** \brief Mask for Ifx_CAN_MO_STAT_Bits.TXRQ */
#define IFX_CAN_MO_STAT_TXRQ_MSK (0x1u)
/** \brief Offset for Ifx_CAN_MO_STAT_Bits.TXRQ */
#define IFX_CAN_MO_STAT_TXRQ_OFF (8u)
/** \brief Length for Ifx_CAN_MSID_Bits.INDEX */
#define IFX_CAN_MSID_INDEX_LEN (6u)
/** \brief Mask for Ifx_CAN_MSID_Bits.INDEX */
#define IFX_CAN_MSID_INDEX_MSK (0x3fu)
/** \brief Offset for Ifx_CAN_MSID_Bits.INDEX */
#define IFX_CAN_MSID_INDEX_OFF (0u)
/** \brief Length for Ifx_CAN_MSIMASK_Bits.IM */
#define IFX_CAN_MSIMASK_IM_LEN (32u)
/** \brief Mask for Ifx_CAN_MSIMASK_Bits.IM */
#define IFX_CAN_MSIMASK_IM_MSK (0xffffffffu)
/** \brief Offset for Ifx_CAN_MSIMASK_Bits.IM */
#define IFX_CAN_MSIMASK_IM_OFF (0u)
/** \brief Length for Ifx_CAN_MSPND_Bits.PND */
#define IFX_CAN_MSPND_PND_LEN (32u)
/** \brief Mask for Ifx_CAN_MSPND_Bits.PND */
#define IFX_CAN_MSPND_PND_MSK (0xffffffffu)
/** \brief Offset for Ifx_CAN_MSPND_Bits.PND */
#define IFX_CAN_MSPND_PND_OFF (0u)
/** \brief Length for Ifx_CAN_N_BTEVR_Bits.BRP */
#define IFX_CAN_N_BTEVR_BRP_LEN (6u)
/** \brief Mask for Ifx_CAN_N_BTEVR_Bits.BRP */
#define IFX_CAN_N_BTEVR_BRP_MSK (0x3fu)
/** \brief Offset for Ifx_CAN_N_BTEVR_Bits.BRP */
#define IFX_CAN_N_BTEVR_BRP_OFF (0u)
/** \brief Length for Ifx_CAN_N_BTEVR_Bits.DIV8 */
#define IFX_CAN_N_BTEVR_DIV8_LEN (1u)
/** \brief Mask for Ifx_CAN_N_BTEVR_Bits.DIV8 */
#define IFX_CAN_N_BTEVR_DIV8_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_BTEVR_Bits.DIV8 */
#define IFX_CAN_N_BTEVR_DIV8_OFF (15u)
/** \brief Length for Ifx_CAN_N_BTEVR_Bits.SJW */
#define IFX_CAN_N_BTEVR_SJW_LEN (4u)
/** \brief Mask for Ifx_CAN_N_BTEVR_Bits.SJW */
#define IFX_CAN_N_BTEVR_SJW_MSK (0xfu)
/** \brief Offset for Ifx_CAN_N_BTEVR_Bits.SJW */
#define IFX_CAN_N_BTEVR_SJW_OFF (8u)
/** \brief Length for Ifx_CAN_N_BTEVR_Bits.TSEG1 */
#define IFX_CAN_N_BTEVR_TSEG1_LEN (6u)
/** \brief Mask for Ifx_CAN_N_BTEVR_Bits.TSEG1 */
#define IFX_CAN_N_BTEVR_TSEG1_MSK (0x3fu)
/** \brief Offset for Ifx_CAN_N_BTEVR_Bits.TSEG1 */
#define IFX_CAN_N_BTEVR_TSEG1_OFF (22u)
/** \brief Length for Ifx_CAN_N_BTEVR_Bits.TSEG2 */
#define IFX_CAN_N_BTEVR_TSEG2_LEN (5u)
/** \brief Mask for Ifx_CAN_N_BTEVR_Bits.TSEG2 */
#define IFX_CAN_N_BTEVR_TSEG2_MSK (0x1fu)
/** \brief Offset for Ifx_CAN_N_BTEVR_Bits.TSEG2 */
#define IFX_CAN_N_BTEVR_TSEG2_OFF (16u)
/** \brief Length for Ifx_CAN_N_BTR_Bits.BRP */
#define IFX_CAN_N_BTR_BRP_LEN (6u)
/** \brief Mask for Ifx_CAN_N_BTR_Bits.BRP */
#define IFX_CAN_N_BTR_BRP_MSK (0x3fu)
/** \brief Offset for Ifx_CAN_N_BTR_Bits.BRP */
#define IFX_CAN_N_BTR_BRP_OFF (0u)
/** \brief Length for Ifx_CAN_N_BTR_Bits.DIV8 */
#define IFX_CAN_N_BTR_DIV8_LEN (1u)
/** \brief Mask for Ifx_CAN_N_BTR_Bits.DIV8 */
#define IFX_CAN_N_BTR_DIV8_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_BTR_Bits.DIV8 */
#define IFX_CAN_N_BTR_DIV8_OFF (15u)
/** \brief Length for Ifx_CAN_N_BTR_Bits.SJW */
#define IFX_CAN_N_BTR_SJW_LEN (2u)
/** \brief Mask for Ifx_CAN_N_BTR_Bits.SJW */
#define IFX_CAN_N_BTR_SJW_MSK (0x3u)
/** \brief Offset for Ifx_CAN_N_BTR_Bits.SJW */
#define IFX_CAN_N_BTR_SJW_OFF (6u)
/** \brief Length for Ifx_CAN_N_BTR_Bits.TSEG1 */
#define IFX_CAN_N_BTR_TSEG1_LEN (4u)
/** \brief Mask for Ifx_CAN_N_BTR_Bits.TSEG1 */
#define IFX_CAN_N_BTR_TSEG1_MSK (0xfu)
/** \brief Offset for Ifx_CAN_N_BTR_Bits.TSEG1 */
#define IFX_CAN_N_BTR_TSEG1_OFF (8u)
/** \brief Length for Ifx_CAN_N_BTR_Bits.TSEG2 */
#define IFX_CAN_N_BTR_TSEG2_LEN (3u)
/** \brief Mask for Ifx_CAN_N_BTR_Bits.TSEG2 */
#define IFX_CAN_N_BTR_TSEG2_MSK (0x7u)
/** \brief Offset for Ifx_CAN_N_BTR_Bits.TSEG2 */
#define IFX_CAN_N_BTR_TSEG2_OFF (12u)
/** \brief Length for Ifx_CAN_N_CR_Bits.ALIE */
#define IFX_CAN_N_CR_ALIE_LEN (1u)
/** \brief Mask for Ifx_CAN_N_CR_Bits.ALIE */
#define IFX_CAN_N_CR_ALIE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_CR_Bits.ALIE */
#define IFX_CAN_N_CR_ALIE_OFF (3u)
/** \brief Length for Ifx_CAN_N_CR_Bits.CALM */
#define IFX_CAN_N_CR_CALM_LEN (1u)
/** \brief Mask for Ifx_CAN_N_CR_Bits.CALM */
#define IFX_CAN_N_CR_CALM_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_CR_Bits.CALM */
#define IFX_CAN_N_CR_CALM_OFF (7u)
/** \brief Length for Ifx_CAN_N_CR_Bits.CANDIS */
#define IFX_CAN_N_CR_CANDIS_LEN (1u)
/** \brief Mask for Ifx_CAN_N_CR_Bits.CANDIS */
#define IFX_CAN_N_CR_CANDIS_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_CR_Bits.CANDIS */
#define IFX_CAN_N_CR_CANDIS_OFF (4u)
/** \brief Length for Ifx_CAN_N_CR_Bits.CCE */
#define IFX_CAN_N_CR_CCE_LEN (1u)
/** \brief Mask for Ifx_CAN_N_CR_Bits.CCE */
#define IFX_CAN_N_CR_CCE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_CR_Bits.CCE */
#define IFX_CAN_N_CR_CCE_OFF (6u)
/** \brief Length for Ifx_CAN_N_CR_Bits.FDEN */
#define IFX_CAN_N_CR_FDEN_LEN (1u)
/** \brief Mask for Ifx_CAN_N_CR_Bits.FDEN */
#define IFX_CAN_N_CR_FDEN_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_CR_Bits.FDEN */
#define IFX_CAN_N_CR_FDEN_OFF (9u)
/** \brief Length for Ifx_CAN_N_CR_Bits.INIT */
#define IFX_CAN_N_CR_INIT_LEN (1u)
/** \brief Mask for Ifx_CAN_N_CR_Bits.INIT */
#define IFX_CAN_N_CR_INIT_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_CR_Bits.INIT */
#define IFX_CAN_N_CR_INIT_OFF (0u)
/** \brief Length for Ifx_CAN_N_CR_Bits.LECIE */
#define IFX_CAN_N_CR_LECIE_LEN (1u)
/** \brief Mask for Ifx_CAN_N_CR_Bits.LECIE */
#define IFX_CAN_N_CR_LECIE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_CR_Bits.LECIE */
#define IFX_CAN_N_CR_LECIE_OFF (2u)
/** \brief Length for Ifx_CAN_N_CR_Bits.SUSEN */
#define IFX_CAN_N_CR_SUSEN_LEN (1u)
/** \brief Mask for Ifx_CAN_N_CR_Bits.SUSEN */
#define IFX_CAN_N_CR_SUSEN_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_CR_Bits.SUSEN */
#define IFX_CAN_N_CR_SUSEN_OFF (8u)
/** \brief Length for Ifx_CAN_N_CR_Bits.TRIE */
#define IFX_CAN_N_CR_TRIE_LEN (1u)
/** \brief Mask for Ifx_CAN_N_CR_Bits.TRIE */
#define IFX_CAN_N_CR_TRIE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_CR_Bits.TRIE */
#define IFX_CAN_N_CR_TRIE_OFF (1u)
/** \brief Length for Ifx_CAN_N_CR_Bits.TXDIS */
#define IFX_CAN_N_CR_TXDIS_LEN (1u)
/** \brief Mask for Ifx_CAN_N_CR_Bits.TXDIS */
#define IFX_CAN_N_CR_TXDIS_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_CR_Bits.TXDIS */
#define IFX_CAN_N_CR_TXDIS_OFF (5u)
/** \brief Length for Ifx_CAN_N_ECNT_Bits.EWRNLVL */
#define IFX_CAN_N_ECNT_EWRNLVL_LEN (8u)
/** \brief Mask for Ifx_CAN_N_ECNT_Bits.EWRNLVL */
#define IFX_CAN_N_ECNT_EWRNLVL_MSK (0xffu)
/** \brief Offset for Ifx_CAN_N_ECNT_Bits.EWRNLVL */
#define IFX_CAN_N_ECNT_EWRNLVL_OFF (16u)
/** \brief Length for Ifx_CAN_N_ECNT_Bits.LEINC */
#define IFX_CAN_N_ECNT_LEINC_LEN (1u)
/** \brief Mask for Ifx_CAN_N_ECNT_Bits.LEINC */
#define IFX_CAN_N_ECNT_LEINC_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_ECNT_Bits.LEINC */
#define IFX_CAN_N_ECNT_LEINC_OFF (25u)
/** \brief Length for Ifx_CAN_N_ECNT_Bits.LETD */
#define IFX_CAN_N_ECNT_LETD_LEN (1u)
/** \brief Mask for Ifx_CAN_N_ECNT_Bits.LETD */
#define IFX_CAN_N_ECNT_LETD_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_ECNT_Bits.LETD */
#define IFX_CAN_N_ECNT_LETD_OFF (24u)
/** \brief Length for Ifx_CAN_N_ECNT_Bits.REC */
#define IFX_CAN_N_ECNT_REC_LEN (8u)
/** \brief Mask for Ifx_CAN_N_ECNT_Bits.REC */
#define IFX_CAN_N_ECNT_REC_MSK (0xffu)
/** \brief Offset for Ifx_CAN_N_ECNT_Bits.REC */
#define IFX_CAN_N_ECNT_REC_OFF (0u)
/** \brief Length for Ifx_CAN_N_ECNT_Bits.TEC */
#define IFX_CAN_N_ECNT_TEC_LEN (8u)
/** \brief Mask for Ifx_CAN_N_ECNT_Bits.TEC */
#define IFX_CAN_N_ECNT_TEC_MSK (0xffu)
/** \brief Offset for Ifx_CAN_N_ECNT_Bits.TEC */
#define IFX_CAN_N_ECNT_TEC_OFF (8u)
/** \brief Length for Ifx_CAN_N_FBTR_Bits.FBRP */
#define IFX_CAN_N_FBTR_FBRP_LEN (6u)
/** \brief Mask for Ifx_CAN_N_FBTR_Bits.FBRP */
#define IFX_CAN_N_FBTR_FBRP_MSK (0x3fu)
/** \brief Offset for Ifx_CAN_N_FBTR_Bits.FBRP */
#define IFX_CAN_N_FBTR_FBRP_OFF (0u)
/** \brief Length for Ifx_CAN_N_FBTR_Bits.FSJW */
#define IFX_CAN_N_FBTR_FSJW_LEN (2u)
/** \brief Mask for Ifx_CAN_N_FBTR_Bits.FSJW */
#define IFX_CAN_N_FBTR_FSJW_MSK (0x3u)
/** \brief Offset for Ifx_CAN_N_FBTR_Bits.FSJW */
#define IFX_CAN_N_FBTR_FSJW_OFF (6u)
/** \brief Length for Ifx_CAN_N_FBTR_Bits.FTSEG1 */
#define IFX_CAN_N_FBTR_FTSEG1_LEN (4u)
/** \brief Mask for Ifx_CAN_N_FBTR_Bits.FTSEG1 */
#define IFX_CAN_N_FBTR_FTSEG1_MSK (0xfu)
/** \brief Offset for Ifx_CAN_N_FBTR_Bits.FTSEG1 */
#define IFX_CAN_N_FBTR_FTSEG1_OFF (8u)
/** \brief Length for Ifx_CAN_N_FBTR_Bits.FTSEG2 */
#define IFX_CAN_N_FBTR_FTSEG2_LEN (3u)
/** \brief Mask for Ifx_CAN_N_FBTR_Bits.FTSEG2 */
#define IFX_CAN_N_FBTR_FTSEG2_MSK (0x7u)
/** \brief Offset for Ifx_CAN_N_FBTR_Bits.FTSEG2 */
#define IFX_CAN_N_FBTR_FTSEG2_OFF (12u)
/** \brief Length for Ifx_CAN_N_FCR_Bits.CFC */
#define IFX_CAN_N_FCR_CFC_LEN (16u)
/** \brief Mask for Ifx_CAN_N_FCR_Bits.CFC */
#define IFX_CAN_N_FCR_CFC_MSK (0xffffu)
/** \brief Offset for Ifx_CAN_N_FCR_Bits.CFC */
#define IFX_CAN_N_FCR_CFC_OFF (0u)
/** \brief Length for Ifx_CAN_N_FCR_Bits.CFCIE */
#define IFX_CAN_N_FCR_CFCIE_LEN (1u)
/** \brief Mask for Ifx_CAN_N_FCR_Bits.CFCIE */
#define IFX_CAN_N_FCR_CFCIE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_FCR_Bits.CFCIE */
#define IFX_CAN_N_FCR_CFCIE_OFF (22u)
/** \brief Length for Ifx_CAN_N_FCR_Bits.CFCOV */
#define IFX_CAN_N_FCR_CFCOV_LEN (1u)
/** \brief Mask for Ifx_CAN_N_FCR_Bits.CFCOV */
#define IFX_CAN_N_FCR_CFCOV_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_FCR_Bits.CFCOV */
#define IFX_CAN_N_FCR_CFCOV_OFF (23u)
/** \brief Length for Ifx_CAN_N_FCR_Bits.CFMOD */
#define IFX_CAN_N_FCR_CFMOD_LEN (2u)
/** \brief Mask for Ifx_CAN_N_FCR_Bits.CFMOD */
#define IFX_CAN_N_FCR_CFMOD_MSK (0x3u)
/** \brief Offset for Ifx_CAN_N_FCR_Bits.CFMOD */
#define IFX_CAN_N_FCR_CFMOD_OFF (19u)
/** \brief Length for Ifx_CAN_N_FCR_Bits.CFSEL */
#define IFX_CAN_N_FCR_CFSEL_LEN (3u)
/** \brief Mask for Ifx_CAN_N_FCR_Bits.CFSEL */
#define IFX_CAN_N_FCR_CFSEL_MSK (0x7u)
/** \brief Offset for Ifx_CAN_N_FCR_Bits.CFSEL */
#define IFX_CAN_N_FCR_CFSEL_OFF (16u)
/** \brief Length for Ifx_CAN_N_IPR_Bits.ALINP */
#define IFX_CAN_N_IPR_ALINP_LEN (4u)
/** \brief Mask for Ifx_CAN_N_IPR_Bits.ALINP */
#define IFX_CAN_N_IPR_ALINP_MSK (0xfu)
/** \brief Offset for Ifx_CAN_N_IPR_Bits.ALINP */
#define IFX_CAN_N_IPR_ALINP_OFF (0u)
/** \brief Length for Ifx_CAN_N_IPR_Bits.CFCINP */
#define IFX_CAN_N_IPR_CFCINP_LEN (4u)
/** \brief Mask for Ifx_CAN_N_IPR_Bits.CFCINP */
#define IFX_CAN_N_IPR_CFCINP_MSK (0xfu)
/** \brief Offset for Ifx_CAN_N_IPR_Bits.CFCINP */
#define IFX_CAN_N_IPR_CFCINP_OFF (12u)
/** \brief Length for Ifx_CAN_N_IPR_Bits.LECINP */
#define IFX_CAN_N_IPR_LECINP_LEN (4u)
/** \brief Mask for Ifx_CAN_N_IPR_Bits.LECINP */
#define IFX_CAN_N_IPR_LECINP_MSK (0xfu)
/** \brief Offset for Ifx_CAN_N_IPR_Bits.LECINP */
#define IFX_CAN_N_IPR_LECINP_OFF (4u)
/** \brief Length for Ifx_CAN_N_IPR_Bits.TEINP */
#define IFX_CAN_N_IPR_TEINP_LEN (4u)
/** \brief Mask for Ifx_CAN_N_IPR_Bits.TEINP */
#define IFX_CAN_N_IPR_TEINP_MSK (0xfu)
/** \brief Offset for Ifx_CAN_N_IPR_Bits.TEINP */
#define IFX_CAN_N_IPR_TEINP_OFF (16u)
/** \brief Length for Ifx_CAN_N_IPR_Bits.TRINP */
#define IFX_CAN_N_IPR_TRINP_LEN (4u)
/** \brief Mask for Ifx_CAN_N_IPR_Bits.TRINP */
#define IFX_CAN_N_IPR_TRINP_MSK (0xfu)
/** \brief Offset for Ifx_CAN_N_IPR_Bits.TRINP */
#define IFX_CAN_N_IPR_TRINP_OFF (8u)
/** \brief Length for Ifx_CAN_N_PCR_Bits.LBM */
#define IFX_CAN_N_PCR_LBM_LEN (1u)
/** \brief Mask for Ifx_CAN_N_PCR_Bits.LBM */
#define IFX_CAN_N_PCR_LBM_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_PCR_Bits.LBM */
#define IFX_CAN_N_PCR_LBM_OFF (8u)
/** \brief Length for Ifx_CAN_N_PCR_Bits.RXSEL */
#define IFX_CAN_N_PCR_RXSEL_LEN (3u)
/** \brief Mask for Ifx_CAN_N_PCR_Bits.RXSEL */
#define IFX_CAN_N_PCR_RXSEL_MSK (0x7u)
/** \brief Offset for Ifx_CAN_N_PCR_Bits.RXSEL */
#define IFX_CAN_N_PCR_RXSEL_OFF (0u)
/** \brief Length for Ifx_CAN_N_SR_Bits.ALERT */
#define IFX_CAN_N_SR_ALERT_LEN (1u)
/** \brief Mask for Ifx_CAN_N_SR_Bits.ALERT */
#define IFX_CAN_N_SR_ALERT_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_SR_Bits.ALERT */
#define IFX_CAN_N_SR_ALERT_OFF (5u)
/** \brief Length for Ifx_CAN_N_SR_Bits.BOFF */
#define IFX_CAN_N_SR_BOFF_LEN (1u)
/** \brief Mask for Ifx_CAN_N_SR_Bits.BOFF */
#define IFX_CAN_N_SR_BOFF_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_SR_Bits.BOFF */
#define IFX_CAN_N_SR_BOFF_OFF (7u)
/** \brief Length for Ifx_CAN_N_SR_Bits.EWRN */
#define IFX_CAN_N_SR_EWRN_LEN (1u)
/** \brief Mask for Ifx_CAN_N_SR_Bits.EWRN */
#define IFX_CAN_N_SR_EWRN_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_SR_Bits.EWRN */
#define IFX_CAN_N_SR_EWRN_OFF (6u)
/** \brief Length for Ifx_CAN_N_SR_Bits.FLEC */
#define IFX_CAN_N_SR_FLEC_LEN (3u)
/** \brief Mask for Ifx_CAN_N_SR_Bits.FLEC */
#define IFX_CAN_N_SR_FLEC_MSK (0x7u)
/** \brief Offset for Ifx_CAN_N_SR_Bits.FLEC */
#define IFX_CAN_N_SR_FLEC_OFF (12u)
/** \brief Length for Ifx_CAN_N_SR_Bits.LEC */
#define IFX_CAN_N_SR_LEC_LEN (3u)
/** \brief Mask for Ifx_CAN_N_SR_Bits.LEC */
#define IFX_CAN_N_SR_LEC_MSK (0x7u)
/** \brief Offset for Ifx_CAN_N_SR_Bits.LEC */
#define IFX_CAN_N_SR_LEC_OFF (0u)
/** \brief Length for Ifx_CAN_N_SR_Bits.LLE */
#define IFX_CAN_N_SR_LLE_LEN (1u)
/** \brief Mask for Ifx_CAN_N_SR_Bits.LLE */
#define IFX_CAN_N_SR_LLE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_SR_Bits.LLE */
#define IFX_CAN_N_SR_LLE_OFF (8u)
/** \brief Length for Ifx_CAN_N_SR_Bits.LOE */
#define IFX_CAN_N_SR_LOE_LEN (1u)
/** \brief Mask for Ifx_CAN_N_SR_Bits.LOE */
#define IFX_CAN_N_SR_LOE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_SR_Bits.LOE */
#define IFX_CAN_N_SR_LOE_OFF (9u)
/** \brief Length for Ifx_CAN_N_SR_Bits.RESI */
#define IFX_CAN_N_SR_RESI_LEN (1u)
/** \brief Mask for Ifx_CAN_N_SR_Bits.RESI */
#define IFX_CAN_N_SR_RESI_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_SR_Bits.RESI */
#define IFX_CAN_N_SR_RESI_OFF (11u)
/** \brief Length for Ifx_CAN_N_SR_Bits.RXOK */
#define IFX_CAN_N_SR_RXOK_LEN (1u)
/** \brief Mask for Ifx_CAN_N_SR_Bits.RXOK */
#define IFX_CAN_N_SR_RXOK_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_SR_Bits.RXOK */
#define IFX_CAN_N_SR_RXOK_OFF (4u)
/** \brief Length for Ifx_CAN_N_SR_Bits.SUSACK */
#define IFX_CAN_N_SR_SUSACK_LEN (1u)
/** \brief Mask for Ifx_CAN_N_SR_Bits.SUSACK */
#define IFX_CAN_N_SR_SUSACK_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_SR_Bits.SUSACK */
#define IFX_CAN_N_SR_SUSACK_OFF (10u)
/** \brief Length for Ifx_CAN_N_SR_Bits.TXOK */
#define IFX_CAN_N_SR_TXOK_LEN (1u)
/** \brief Mask for Ifx_CAN_N_SR_Bits.TXOK */
#define IFX_CAN_N_SR_TXOK_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_SR_Bits.TXOK */
#define IFX_CAN_N_SR_TXOK_OFF (3u)
/** \brief Length for Ifx_CAN_N_TCCR_Bits.TPSC */
#define IFX_CAN_N_TCCR_TPSC_LEN (4u)
/** \brief Mask for Ifx_CAN_N_TCCR_Bits.TPSC */
#define IFX_CAN_N_TCCR_TPSC_MSK (0xfu)
/** \brief Offset for Ifx_CAN_N_TCCR_Bits.TPSC */
#define IFX_CAN_N_TCCR_TPSC_OFF (8u)
/** \brief Length for Ifx_CAN_N_TCCR_Bits.TRIGSRC */
#define IFX_CAN_N_TCCR_TRIGSRC_LEN (3u)
/** \brief Mask for Ifx_CAN_N_TCCR_Bits.TRIGSRC */
#define IFX_CAN_N_TCCR_TRIGSRC_MSK (0x7u)
/** \brief Offset for Ifx_CAN_N_TCCR_Bits.TRIGSRC */
#define IFX_CAN_N_TCCR_TRIGSRC_OFF (18u)
/** \brief Length for Ifx_CAN_N_TDCR_Bits.TDC */
#define IFX_CAN_N_TDCR_TDC_LEN (1u)
/** \brief Mask for Ifx_CAN_N_TDCR_Bits.TDC */
#define IFX_CAN_N_TDCR_TDC_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_TDCR_Bits.TDC */
#define IFX_CAN_N_TDCR_TDC_OFF (15u)
/** \brief Length for Ifx_CAN_N_TDCR_Bits.TDCO */
#define IFX_CAN_N_TDCR_TDCO_LEN (4u)
/** \brief Mask for Ifx_CAN_N_TDCR_Bits.TDCO */
#define IFX_CAN_N_TDCR_TDCO_MSK (0xfu)
/** \brief Offset for Ifx_CAN_N_TDCR_Bits.TDCO */
#define IFX_CAN_N_TDCR_TDCO_OFF (8u)
/** \brief Length for Ifx_CAN_N_TDCR_Bits.TDCV */
#define IFX_CAN_N_TDCR_TDCV_LEN (5u)
/** \brief Mask for Ifx_CAN_N_TDCR_Bits.TDCV */
#define IFX_CAN_N_TDCR_TDCV_MSK (0x1fu)
/** \brief Offset for Ifx_CAN_N_TDCR_Bits.TDCV */
#define IFX_CAN_N_TDCR_TDCV_OFF (0u)
/** \brief Length for Ifx_CAN_N_TRTR_Bits.RELOAD */
#define IFX_CAN_N_TRTR_RELOAD_LEN (16u)
/** \brief Mask for Ifx_CAN_N_TRTR_Bits.RELOAD */
#define IFX_CAN_N_TRTR_RELOAD_MSK (0xffffu)
/** \brief Offset for Ifx_CAN_N_TRTR_Bits.RELOAD */
#define IFX_CAN_N_TRTR_RELOAD_OFF (0u)
/** \brief Length for Ifx_CAN_N_TRTR_Bits.TE */
#define IFX_CAN_N_TRTR_TE_LEN (1u)
/** \brief Mask for Ifx_CAN_N_TRTR_Bits.TE */
#define IFX_CAN_N_TRTR_TE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_TRTR_Bits.TE */
#define IFX_CAN_N_TRTR_TE_OFF (23u)
/** \brief Length for Ifx_CAN_N_TRTR_Bits.TEIE */
#define IFX_CAN_N_TRTR_TEIE_LEN (1u)
/** \brief Mask for Ifx_CAN_N_TRTR_Bits.TEIE */
#define IFX_CAN_N_TRTR_TEIE_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_TRTR_Bits.TEIE */
#define IFX_CAN_N_TRTR_TEIE_OFF (22u)
/** \brief Length for Ifx_CAN_N_TTTR_Bits.RELOAD */
#define IFX_CAN_N_TTTR_RELOAD_LEN (16u)
/** \brief Mask for Ifx_CAN_N_TTTR_Bits.RELOAD */
#define IFX_CAN_N_TTTR_RELOAD_MSK (0xffffu)
/** \brief Offset for Ifx_CAN_N_TTTR_Bits.RELOAD */
#define IFX_CAN_N_TTTR_RELOAD_OFF (0u)
/** \brief Length for Ifx_CAN_N_TTTR_Bits.STRT */
#define IFX_CAN_N_TTTR_STRT_LEN (1u)
/** \brief Mask for Ifx_CAN_N_TTTR_Bits.STRT */
#define IFX_CAN_N_TTTR_STRT_MSK (0x1u)
/** \brief Offset for Ifx_CAN_N_TTTR_Bits.STRT */
#define IFX_CAN_N_TTTR_STRT_OFF (24u)
/** \brief Length for Ifx_CAN_N_TTTR_Bits.TXMO */
#define IFX_CAN_N_TTTR_TXMO_LEN (8u)
/** \brief Mask for Ifx_CAN_N_TTTR_Bits.TXMO */
#define IFX_CAN_N_TTTR_TXMO_MSK (0xffu)
/** \brief Offset for Ifx_CAN_N_TTTR_Bits.TXMO */
#define IFX_CAN_N_TTTR_TXMO_OFF (16u)
/** \brief Length for Ifx_CAN_OCS_Bits.SUS */
#define IFX_CAN_OCS_SUS_LEN (4u)
/** \brief Mask for Ifx_CAN_OCS_Bits.SUS */
#define IFX_CAN_OCS_SUS_MSK (0xfu)
/** \brief Offset for Ifx_CAN_OCS_Bits.SUS */
#define IFX_CAN_OCS_SUS_OFF (24u)
/** \brief Length for Ifx_CAN_OCS_Bits.SUS_P */
#define IFX_CAN_OCS_SUS_P_LEN (1u)
/** \brief Mask for Ifx_CAN_OCS_Bits.SUS_P */
#define IFX_CAN_OCS_SUS_P_MSK (0x1u)
/** \brief Offset for Ifx_CAN_OCS_Bits.SUS_P */
#define IFX_CAN_OCS_SUS_P_OFF (28u)
/** \brief Length for Ifx_CAN_OCS_Bits.SUSSTA */
#define IFX_CAN_OCS_SUSSTA_LEN (1u)
/** \brief Mask for Ifx_CAN_OCS_Bits.SUSSTA */
#define IFX_CAN_OCS_SUSSTA_MSK (0x1u)
/** \brief Offset for Ifx_CAN_OCS_Bits.SUSSTA */
#define IFX_CAN_OCS_SUSSTA_OFF (29u)
/** \brief Length for Ifx_CAN_OCS_Bits.TG_P */
#define IFX_CAN_OCS_TG_P_LEN (1u)
/** \brief Mask for Ifx_CAN_OCS_Bits.TG_P */
#define IFX_CAN_OCS_TG_P_MSK (0x1u)
/** \brief Offset for Ifx_CAN_OCS_Bits.TG_P */
#define IFX_CAN_OCS_TG_P_OFF (3u)
/** \brief Length for Ifx_CAN_OCS_Bits.TGB */
#define IFX_CAN_OCS_TGB_LEN (1u)
/** \brief Mask for Ifx_CAN_OCS_Bits.TGB */
#define IFX_CAN_OCS_TGB_MSK (0x1u)
/** \brief Offset for Ifx_CAN_OCS_Bits.TGB */
#define IFX_CAN_OCS_TGB_OFF (2u)
/** \brief Length for Ifx_CAN_OCS_Bits.TGS */
#define IFX_CAN_OCS_TGS_LEN (2u)
/** \brief Mask for Ifx_CAN_OCS_Bits.TGS */
#define IFX_CAN_OCS_TGS_MSK (0x3u)
/** \brief Offset for Ifx_CAN_OCS_Bits.TGS */
#define IFX_CAN_OCS_TGS_OFF (0u)
/** \brief Length for Ifx_CAN_PANCTR_Bits.BUSY */
#define IFX_CAN_PANCTR_BUSY_LEN (1u)
/** \brief Mask for Ifx_CAN_PANCTR_Bits.BUSY */
#define IFX_CAN_PANCTR_BUSY_MSK (0x1u)
/** \brief Offset for Ifx_CAN_PANCTR_Bits.BUSY */
#define IFX_CAN_PANCTR_BUSY_OFF (8u)
/** \brief Length for Ifx_CAN_PANCTR_Bits.PANAR1 */
#define IFX_CAN_PANCTR_PANAR1_LEN (8u)
/** \brief Mask for Ifx_CAN_PANCTR_Bits.PANAR1 */
#define IFX_CAN_PANCTR_PANAR1_MSK (0xffu)
/** \brief Offset for Ifx_CAN_PANCTR_Bits.PANAR1 */
#define IFX_CAN_PANCTR_PANAR1_OFF (16u)
/** \brief Length for Ifx_CAN_PANCTR_Bits.PANAR2 */
#define IFX_CAN_PANCTR_PANAR2_LEN (8u)
/** \brief Mask for Ifx_CAN_PANCTR_Bits.PANAR2 */
#define IFX_CAN_PANCTR_PANAR2_MSK (0xffu)
/** \brief Offset for Ifx_CAN_PANCTR_Bits.PANAR2 */
#define IFX_CAN_PANCTR_PANAR2_OFF (24u)
/** \brief Length for Ifx_CAN_PANCTR_Bits.PANCMD */
#define IFX_CAN_PANCTR_PANCMD_LEN (8u)
/** \brief Mask for Ifx_CAN_PANCTR_Bits.PANCMD */
#define IFX_CAN_PANCTR_PANCMD_MSK (0xffu)
/** \brief Offset for Ifx_CAN_PANCTR_Bits.PANCMD */
#define IFX_CAN_PANCTR_PANCMD_OFF (0u)
/** \brief Length for Ifx_CAN_PANCTR_Bits.RBUSY */
#define IFX_CAN_PANCTR_RBUSY_LEN (1u)
/** \brief Mask for Ifx_CAN_PANCTR_Bits.RBUSY */
#define IFX_CAN_PANCTR_RBUSY_MSK (0x1u)
/** \brief Offset for Ifx_CAN_PANCTR_Bits.RBUSY */
#define IFX_CAN_PANCTR_RBUSY_OFF (9u)
/** \} */
/******************************************************************************/
/******************************************************************************/
#endif /* IFXCAN_BF_H */
| 30.141761 | 80 | 0.762027 |
ab6672693c1560059a1e5e900b01f074b9720404 | 1,412 | swift | Swift | Examples/Sample-SwiftUI/iOS/Views/LoggedOutView.swift | radupurdea/intercom-ios | 1c323236d2538511059c3f950a2dda0227430704 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Examples/Sample-SwiftUI/iOS/Views/LoggedOutView.swift | radupurdea/intercom-ios | 1c323236d2538511059c3f950a2dda0227430704 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Examples/Sample-SwiftUI/iOS/Views/LoggedOutView.swift | radupurdea/intercom-ios | 1c323236d2538511059c3f950a2dda0227430704 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | //
// LoggedOutView.swift
// Sample-SwiftUI (iOS)
//
// Created by Michael McNamara on 08/09/2020.
//
import SwiftUI
import Intercom
struct LoggedOutView: View {
@Binding var userHash: String
@Binding var userId: String
@Binding var loggedIn: Bool
var body: some View {
VStack(spacing: 25) {
StylizedTextField(title: "User HMAC", text: $userHash, onCommit: loginToIntercom)
.frame(maxWidth: 350)
StylizedTextField(title: "User ID", text: $userId, onCommit: loginToIntercom)
.frame(maxWidth: 350)
StylizedButton("Login", action: loginToIntercom)
.disabled(userHash.isEmpty && userId.isEmpty)
}
}
func loginToIntercom() {
// Start tracking the user with Intercom
Intercom.setUserHash(userHash)
Intercom.registerUser(withUserId: userId)
let defaults = UserDefaults.standard
defaults.set(userHash, forKey: hashKey)
defaults.set(userId, forKey: userIdKey)
loggedIn = true
}
}
struct LoggedOutView_Previews: PreviewProvider {
@State static private var userHash = "my user hmac"
@State static private var userId = "my user id"
@State static private var loggedIn = true
static var previews: some View {
LoggedOutView(userHash: $userHash, userId: $userId, loggedIn: $loggedIn)
}
}
| 28.816327 | 93 | 0.639518 |