identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/TRANTANKHOA/pptx-template/blob/master/test/test_xlsx_model.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
pptx-template
|
TRANTANKHOA
|
Python
|
Code
| 165
| 995
|
#
# coding=utf-8
import unittest
import sys
import os
from io import open
import openpyxl as xl
from pptx_template.xlsx_model import _build_tsv, _format_cell_value, generate_whole_model
class Cell:
def __init__(self, value, number_format):
self.value = value
self.number_format = number_format
def _to_cells(list_of_list):
return [[Cell(value, '') for value in list] for list in list_of_list]
class MyTest(unittest.TestCase):
def test_build_tsv(self):
tsv = _build_tsv([_to_cells([["Year","A","B"],["2016",100,200]])])
self.assertEqual([["Year","A","B"],["2016",100,200]], tsv)
def test_build_tsv_tranapose(self):
tsv = _build_tsv([_to_cells([["Year","A","B"],["2016",100,200]])], transpose=True)
self.assertEqual([["Year","2016"],["A",100],["B",200]], tsv)
def test_build_tsv_side_by_side(self):
tsv = _build_tsv([_to_cells([["Year","A"],["2016",100]]), _to_cells([["B"],[200]])], side_by_side=True)
self.assertEqual([["Year","A","B"],["2016",100,200]], tsv)
def test_format_cell_value(self):
self.assertEqual(123.45678, _format_cell_value(Cell(123.45678, '')))
self.assertEqual("123", _format_cell_value(Cell(123.45678, '0')))
self.assertEqual("123.46", _format_cell_value(Cell(123.45678, '0.00')))
self.assertEqual("123.5", _format_cell_value(Cell(123.45678, '0.0_')))
self.assertEqual("12345.7%", _format_cell_value(Cell(123.45678, '0.0%_')))
self.assertEqual("12345%", _format_cell_value(Cell(123.45678, '0%_')))
def test_generate_whole_model(self):
def read_expect(name):
file_name = os.path.join(os.path.dirname(__file__), 'data2', name)
f = open(file_name, mode = 'r', encoding = 'utf-8')
result = f.read()
f.close()
return result
xls_file = os.path.join(os.path.dirname(__file__), 'data2', 'in.xlsx')
slides = generate_whole_model(xls_file, {})
self.assertEqual(u'Hello!', slides['p01']['greeting']['en'])
self.assertEqual(u'こんにちは!', slides['p01']['greeting']['ja'])
self.assertEqual([
['Season', u'売り上げ', u'利益', u'利益率'],
[u'春', 100, 50, 0.5],
[u'夏', 110, 60, 0.5],
[u'秋', 120, 70, 0.5],
[u'冬', 130, 0, 0.6],
], slides['p02']['array'])
self.assertEqual(read_expect('p02-normal.tsv'), slides['p02']['normal']['tsv_body'])
self.assertEqual(read_expect('p02-transpose.tsv'), slides['p02']['transpose']['tsv_body'])
self.assertEqual(read_expect('p02-sidebyside.tsv'), slides['p02']['sidebyside']['tsv_body'])
if __name__ == '__main__':
unittest.main()
| 17,271
|
https://github.com/IsmanArman/emonevppg/blob/master/app/Http/Controllers/Admin/QuestionnaireController.php
|
Github Open Source
|
Open Source
|
MIT
| null |
emonevppg
|
IsmanArman
|
PHP
|
Code
| 229
| 709
|
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Answer;
use App\Models\Question;
use App\Models\Questionnaire;
use App\Models\User;
use Illuminate\Http\Request;
class QuestionnaireController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.questionnaires.index', [
'questionnaires' => Questionnaire::paginate(10)
]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.questionnaires.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|max:255',
'purpose' => 'required|max:255'
]);
$validatedData['user_id'] = auth()->user()->id;
Questionnaire::create($validatedData);
$request->session()->flash('success', 'You have created the questionnaire.');
return redirect(route('questionnaire.index'));
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Questionnaire $questionnaire)
{
return view('admin.questionnaires.show', [
'questionnaire' => $questionnaire
]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id, Request $request)
{
Questionnaire::destroy($id);
$request->session()->flash('success', 'You have deleted the questionnaire');
return redirect(route('questionnaire.index'));
}
}
| 6,000
|
https://github.com/ramprasath25/react-mobile-app/blob/master/screens/Onboarding.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
react-mobile-app
|
ramprasath25
|
JavaScript
|
Code
| 173
| 563
|
import React from 'react';
import { ImageBackground, StyleSheet, StatusBar, Dimensions, Platform } from 'react-native';
import { Block, Button, Text, theme } from 'galio-framework';
const { height, width } = Dimensions.get('screen');
import materialTheme from '../constants/Theme';
import Images from '../constants/Images';
export default class Onboarding extends React.Component {
render() {
const { navigation } = this.props;
return (
<Block flex style={styles.container}>
<ImageBackground source={require('../assets/images/splash.png')} style={{ width: '100%', height: '100%' }}>
<StatusBar barStyle="dark-content" />
<Block flex center>
<ImageBackground
source={{ uri: Images.Onboarding }}
style={{ height: 350, width: 350, marginTop: '30%', zIndex: 1 }}
/>
</Block>
<Block flex space="between" style={styles.padded}>
<Block flex space="around" style={{ zIndex: 2 }}>
<Block center>
<Block>
<Text color="white" size={32}>Niru Home Foods</Text>
</Block>
<Text size={16} color='rgba(255,255,255,0.6)'>
Mother’s love unconditionally
</Text>
</Block>
<Block center>
<Button
shadowless
style={styles.button}
color={materialTheme.COLORS.BUTTON_COLOR}
onPress={() => navigation.navigate('Home')}>
GET STARTED
</Button>
</Block>
</Block>
</Block>
</ImageBackground>
</Block>
);
}
}
const styles = StyleSheet.create({
container: {
},
padded: {
paddingHorizontal: theme.SIZES.BASE * 2,
position: 'relative',
bottom: theme.SIZES.BASE,
},
button: {
width: width - theme.SIZES.BASE * 4,
height: theme.SIZES.BASE * 3,
shadowRadius: 0,
shadowOpacity: 0,
},
});
| 1,353
|
https://github.com/LReinel/SMA2/blob/master/app/src/main/java/com/sma2/sma2/Ex_mov_hands.java
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
SMA2
|
LReinel
|
Java
|
Code
| 152
| 789
|
package com.sma2.sma2;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class Ex_mov_hands extends AppCompatActivity implements View.OnClickListener {
private String exercise_mov_hands;
private int x;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
x= (int)(Math.random()*((4))+1);
switch (x) {
case 1:
exercise_mov_hands = getApplicationContext().getString(R.string.rest_tremor);
break;
case 2:
exercise_mov_hands = getApplicationContext().getString(R.string.kinetic_tremor);
break;
case 3:
exercise_mov_hands = getApplicationContext().getString(R.string.pronation_supination);
break;
case 4:
exercise_mov_hands = getApplicationContext().getString(R.string.ball_balance);
}
setContentView(R.layout.activity_record_hand_tremor);
setListeners();
}
private void setListeners() {
final TextView mTextView = findViewById(R.id.textView_hand_name);
findViewById(R.id.button_instructions_hand).setOnClickListener(this);
findViewById(R.id.button_record_hand).setOnClickListener(this);
mTextView.setText(exercise_mov_hands);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button_instructions_hand:
//TODO: Implement method to play the audio or visual instructions
break;
case R.id.button_record_hand:
open_exercise();
break;
}
}
public void open_exercise(){
Intent intent_ex1;
switch (x) {
case 1:
intent_ex1 =new Intent(this, Record_movement.class);
intent_ex1.putExtra("EXERCISE","rest_tremor");
startActivity(intent_ex1);
break;
case 2:
intent_ex1 =new Intent(this, Record_movement.class);
intent_ex1.putExtra("EXERCISE","kinetic_tremor");
startActivity(intent_ex1);
break;
case 3:
intent_ex1 =new Intent(this, Record_movement.class);
intent_ex1.putExtra("EXERCISE","pronation_supination");
startActivity(intent_ex1);
break;
case 4:
intent_ex1 =new Intent(this, Record_mov_ball_balance.class);
intent_ex1.putExtra("EXERCISE","ball_balance");
startActivity(intent_ex1);
break;
}
}
}
| 24,563
|
https://github.com/aws/aws-sdk-go-v2/blob/master/service/devicefarm/types/errors.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
aws-sdk-go-v2
|
aws
|
Go
|
Code
| 1,010
| 2,634
|
// Code generated by smithy-go-codegen DO NOT EDIT.
package types
import (
"fmt"
smithy "github.com/aws/smithy-go"
)
// An invalid argument was specified.
type ArgumentException struct {
Message *string
ErrorCodeOverride *string
noSmithyDocumentSerde
}
func (e *ArgumentException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *ArgumentException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *ArgumentException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "ArgumentException"
}
return *e.ErrorCodeOverride
}
func (e *ArgumentException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The requested object could not be deleted.
type CannotDeleteException struct {
Message *string
ErrorCodeOverride *string
noSmithyDocumentSerde
}
func (e *CannotDeleteException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *CannotDeleteException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *CannotDeleteException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "CannotDeleteException"
}
return *e.ErrorCodeOverride
}
func (e *CannotDeleteException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// An entity with the same name already exists.
type IdempotencyException struct {
Message *string
ErrorCodeOverride *string
noSmithyDocumentSerde
}
func (e *IdempotencyException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *IdempotencyException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *IdempotencyException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "IdempotencyException"
}
return *e.ErrorCodeOverride
}
func (e *IdempotencyException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// An internal exception was raised in the service. Contact
// aws-devicefarm-support@amazon.com (mailto:aws-devicefarm-support@amazon.com) if
// you see this error.
type InternalServiceException struct {
Message *string
ErrorCodeOverride *string
noSmithyDocumentSerde
}
func (e *InternalServiceException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *InternalServiceException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *InternalServiceException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "InternalServiceException"
}
return *e.ErrorCodeOverride
}
func (e *InternalServiceException) ErrorFault() smithy.ErrorFault { return smithy.FaultServer }
// There was an error with the update request, or you do not have sufficient
// permissions to update this VPC endpoint configuration.
type InvalidOperationException struct {
Message *string
ErrorCodeOverride *string
noSmithyDocumentSerde
}
func (e *InvalidOperationException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *InvalidOperationException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *InvalidOperationException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "InvalidOperationException"
}
return *e.ErrorCodeOverride
}
func (e *InvalidOperationException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// A limit was exceeded.
type LimitExceededException struct {
Message *string
ErrorCodeOverride *string
noSmithyDocumentSerde
}
func (e *LimitExceededException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *LimitExceededException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *LimitExceededException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "LimitExceededException"
}
return *e.ErrorCodeOverride
}
func (e *LimitExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// Exception gets thrown when a user is not eligible to perform the specified
// transaction.
type NotEligibleException struct {
Message *string
ErrorCodeOverride *string
noSmithyDocumentSerde
}
func (e *NotEligibleException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *NotEligibleException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *NotEligibleException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "NotEligibleException"
}
return *e.ErrorCodeOverride
}
func (e *NotEligibleException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The specified entity was not found.
type NotFoundException struct {
Message *string
ErrorCodeOverride *string
noSmithyDocumentSerde
}
func (e *NotFoundException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *NotFoundException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *NotFoundException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "NotFoundException"
}
return *e.ErrorCodeOverride
}
func (e *NotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// There was a problem with the service account.
type ServiceAccountException struct {
Message *string
ErrorCodeOverride *string
noSmithyDocumentSerde
}
func (e *ServiceAccountException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *ServiceAccountException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *ServiceAccountException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "ServiceAccountException"
}
return *e.ErrorCodeOverride
}
func (e *ServiceAccountException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The operation was not successful. Try again.
type TagOperationException struct {
Message *string
ErrorCodeOverride *string
ResourceName *string
noSmithyDocumentSerde
}
func (e *TagOperationException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *TagOperationException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *TagOperationException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "TagOperationException"
}
return *e.ErrorCodeOverride
}
func (e *TagOperationException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The request doesn't comply with the AWS Identity and Access Management (IAM)
// tag policy. Correct your request and then retry it.
type TagPolicyException struct {
Message *string
ErrorCodeOverride *string
ResourceName *string
noSmithyDocumentSerde
}
func (e *TagPolicyException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *TagPolicyException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *TagPolicyException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "TagPolicyException"
}
return *e.ErrorCodeOverride
}
func (e *TagPolicyException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The list of tags on the repository is over the limit. The maximum number of
// tags that can be applied to a repository is 50.
type TooManyTagsException struct {
Message *string
ErrorCodeOverride *string
ResourceName *string
noSmithyDocumentSerde
}
func (e *TooManyTagsException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *TooManyTagsException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *TooManyTagsException) ErrorCode() string {
if e == nil || e.ErrorCodeOverride == nil {
return "TooManyTagsException"
}
return *e.ErrorCodeOverride
}
func (e *TooManyTagsException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
| 4,107
|
https://github.com/beagles/tripleo-ansible/blob/master/tripleo_ansible/ansible_plugins/modules/tripleo_composable_network.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
tripleo-ansible
|
beagles
|
Python
|
Code
| 1,280
| 5,152
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2020 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import yaml
try:
from ansible.module_utils import network_data_v2
except ImportError:
from tripleo_ansible.ansible_plugins.module_utils import network_data_v2
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack import openstack_full_argument_spec
from ansible.module_utils.openstack import openstack_module_kwargs
from ansible.module_utils.openstack import openstack_cloud_from_module
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: tripleo_composable_network
short_description: Create a TripleO Composable network
version_added: "2.8"
description:
- Create a TripleO Composable network, a network,
one or more segments and one or more subnets
options:
net_data:
description:
- Structure describing a TripleO composable network
type: dict
idx:
description:
- TripleO network index number
type: int
author:
- Harald Jensås <hjensas@redhat.com>
'''
RETURN = '''
'''
EXAMPLES = '''
- name: Create composable networks
default_network:
description:
- Default control plane network
type: string
default: ctlplane
tripleo_composable_network:
net_data:
name: Storage
name_lower: storage
dns_domain: storage.localdomain.
mtu: 1442
subnets:
storage_subnet:
ip_subnet: 172.18.0.0/24
gateway_ip: 172.18.0.254
allocation_pools:
- start: 172.18.0.10
end: 172.18.0.250
routes:
- destination: 172.18.1.0/24
nexthop: 172.18.0.254
vip: true
vlan: 20
storage_leaf1:
ip_subnet: 172.18.1.0/24
gateway_ip: 172.18.1.254
allocation_pools:
- start: 172.18.1.10
end: 172.18.1.250
routes:
- destination: 172.18.0.0/24
nexthop: 172.18.1.254
vip: false
vlan: 21
idx: 1
'''
DEFAULT_NETWORK = 'ctlplane'
DEFAULT_ADMIN_STATE = False
DEFAULT_SHARED = False
DEFAULT_DOMAIN = 'localdomain.'
DEFAULT_NETWORK_TYPE = 'flat'
DEFAULT_MTU = 1500
DEFAULT_VLAN_ID = 1
def get_overcloud_domain_name(conn, default_network):
network = conn.network.find_network(default_network)
if network is not None and network.dns_domain:
return network.dns_domain.partition('.')[-1]
else:
return DEFAULT_DOMAIN
def build_network_tag_field(net_data, idx):
tags = ['='.join(['tripleo_network_name', net_data['name']]),
'='.join(['tripleo_net_idx', str(idx)])]
service_net_map_replace = net_data.get('service_net_map_replace')
vip = net_data.get('vip')
if service_net_map_replace:
tags.append('='.join(['tripleo_service_net_map_replace',
service_net_map_replace]))
if vip:
tags.append('='.join(['tripleo_vip', 'true']))
return tags
def build_subnet_tag_field(subnet_data):
tags = []
vlan_id = subnet_data.get('vlan')
vlan_id = str(vlan_id) if vlan_id is not None else str(DEFAULT_VLAN_ID)
tags.append('='.join(['tripleo_vlan_id', vlan_id]))
return tags
def create_net_spec(net_data, overcloud_domain_name, idx):
name_lower = net_data.get('name_lower', net_data['name'].lower())
net_spec = {
'admin_state_up': net_data.get('admin_state_up', DEFAULT_ADMIN_STATE),
'dns_domain': net_data.get(
'dns_domain', '.'.join([net_data['name'].lower(),
overcloud_domain_name])
),
'mtu': net_data.get('mtu', DEFAULT_MTU),
'name': name_lower,
'shared': net_data.get('shared', DEFAULT_SHARED),
'provider:physical_network': name_lower,
'provider:network_type': DEFAULT_NETWORK_TYPE,
}
net_spec.update({'tags': build_network_tag_field(net_data, idx)})
return net_spec
def validate_network_update(module, network, net_spec):
# Fail if updating read-only attributes
if (network.provider_network_type != net_spec.pop(
'provider:network_type')
and network.provider_network_type is not None):
module.fail_json(
msg='Cannot update provider:network_type in existing network')
# NOTE(hjensas): When a network have multiple segments,
# attributes provider:network_type, provider:physical_network is None
# for the network.
if (net_spec.pop('provider:physical_network')
not in [network.provider_physical_network, net_spec['name']]
and network.provider_physical_network is not None):
module.fail_json(
msg='Cannot update provider:physical_network in existing network')
# Remove fields that don't need update from spec
if network.is_admin_state_up == net_spec['admin_state_up']:
net_spec.pop('admin_state_up')
if network.dns_domain == net_spec['dns_domain']:
net_spec.pop('dns_domain')
if network.mtu == net_spec['mtu']:
net_spec.pop('mtu')
if network.name == net_spec['name']:
net_spec.pop('name')
if network.is_shared == net_spec['shared']:
net_spec.pop('shared')
return net_spec
def create_or_update_network(conn, module, net_spec, project_id=None):
changed = False
# Need to use set_tags for the tags ...
tags = net_spec.pop('tags')
network = conn.network.find_network(net_spec['name'])
if not network:
network = conn.network.create_network(project_id=project_id,
**net_spec)
changed = True
else:
net_spec = validate_network_update(module, network, net_spec)
if net_spec:
network = conn.network.update_network(network.id, **net_spec)
changed = True
if network.tags != tags:
conn.network.set_tags(network, tags)
changed = True
return changed, network
def create_segment_spec(net_id, net_name, subnet_name, physical_network=None):
name = '_'.join([net_name, subnet_name])
if physical_network is None:
physical_network = name
else:
physical_network = physical_network
return {'network_id': net_id,
'physical_network': physical_network,
'name': name,
'network_type': DEFAULT_NETWORK_TYPE}
def validate_segment_update(module, segment, segment_spec):
# Fail if updating read-only attributes
if segment.network_id != segment_spec.pop('network_id'):
module.fail_json(
msg='Cannot update network_id in existing segment')
if segment.network_type != segment_spec.pop('network_type'):
module.fail_json(
msg='Cannot update network_type in existing segment')
if segment.physical_network != segment_spec.pop('physical_network'):
module.fail_json(
msg='Cannot update physical_network in existing segment')
# Remove fields that don't need update from spec
if segment.name == segment_spec['name']:
segment_spec.pop('name')
return segment_spec
def create_or_update_segment(conn, module, segment_spec,
segment_id=None, project_id=None):
changed = False
if segment_id:
segment = conn.network.find_segment(segment_id)
else:
segment = conn.network.find_segment(
segment_spec['name'], network_id=segment_spec['network_id'])
if not segment:
segment = conn.network.create_segment(project_id=project_id,
**segment_spec)
changed = True
else:
segment_spec = validate_segment_update(module, segment, segment_spec)
if segment_spec:
segment = conn.network.update_segment(segment.id, **segment_spec)
changed = True
return changed, segment
def create_subnet_spec(net_id, name, subnet_data,
ipv6_enabled=False):
tags = build_subnet_tag_field(subnet_data)
subnet_v4_spec = None
subnet_v6_spec = None
if not ipv6_enabled and subnet_data.get('ip_subnet'):
subnet_v4_spec = {
'ip_version': 4,
'name': name,
'network_id': net_id,
'enable_dhcp': subnet_data.get('enable_dhcp', False),
'gateway_ip': subnet_data.get('gateway_ip', None),
'cidr': subnet_data['ip_subnet'],
'allocation_pools': subnet_data.get('allocation_pools', []),
'host_routes': subnet_data.get('routes', []),
'tags': tags,
}
if ipv6_enabled and subnet_data.get('ipv6_subnet'):
subnet_v6_spec = {
'ip_version': 6,
'name': name,
'network_id': net_id,
'enable_dhcp': subnet_data.get('enable_dhcp', False),
'ipv6_address_mode': subnet_data.get('ipv6_address_mode', None),
'ipv6_ra_mode': subnet_data.get('ipv6_ra_mode', None),
'gateway_ip': subnet_data.get('gateway_ipv6', None),
'cidr': subnet_data['ipv6_subnet'],
'allocation_pools': subnet_data.get('ipv6_allocation_pools', []),
'host_routes': subnet_data.get('routes_ipv6', []),
'tags': tags,
}
return subnet_v4_spec, subnet_v6_spec
def validate_subnet_update(module, subnet, subnet_spec):
# Fail if updating read-only attributes
if subnet.ip_version != subnet_spec.pop('ip_version'):
module.fail_json(
msg='Cannot update ip_version in existing subnet')
if subnet.network_id != subnet_spec.pop('network_id'):
module.fail_json(
msg='Cannot update network_id in existing subnet')
if subnet.cidr != subnet_spec.pop('cidr'):
module.fail_json(
msg='Cannot update cidr in existing subnet')
segment_id = subnet_spec.pop('segment_id')
if subnet.segment_id != segment_id:
module.fail_json(
msg='Cannot update segment_id in existing subnet, '
'Current segment_id: {} Update segment_id: {}'.format(
subnet.segment_id, segment_id))
# Remove fields that don't need update from spec
if subnet.name == subnet_spec['name']:
subnet_spec.pop('name')
if subnet.is_dhcp_enabled == subnet_spec['enable_dhcp']:
subnet_spec.pop('enable_dhcp')
if subnet.ipv6_address_mode == subnet_spec.get('ipv6_address_mode'):
try:
subnet_spec.pop('ipv6_address_mode')
except KeyError:
pass
if subnet.ipv6_ra_mode == subnet_spec.get('ipv6_ra_mode'):
try:
subnet_spec.pop('ipv6_ra_mode')
except KeyError:
pass
if subnet.gateway_ip == subnet_spec['gateway_ip']:
subnet_spec.pop('gateway_ip')
if subnet.allocation_pools == subnet_spec['allocation_pools']:
subnet_spec.pop('allocation_pools')
if subnet.host_routes == subnet_spec['host_routes']:
subnet_spec.pop('host_routes')
return subnet_spec
def create_or_update_subnet(conn, module, subnet_spec, project_id=None):
changed = False
# Need to use set_tags for the tags ...
tags = subnet_spec.pop('tags')
subnet = conn.network.find_subnet(subnet_spec['name'],
ip_version=subnet_spec['ip_version'],
network_id=subnet_spec['network_id'])
if not subnet:
subnet = conn.network.create_subnet(project_id=project_id,
**subnet_spec)
changed = True
else:
subnet_spec = validate_subnet_update(module, subnet, subnet_spec)
if subnet_spec:
subnet = conn.network.update_subnet(subnet.id, **subnet_spec)
changed = True
if subnet.tags != tags:
conn.network.set_tags(subnet, tags)
changed = True
return changed
def adopt_the_implicit_segment(conn, module, segments, subnets, network,
project_id=None):
changed = False
# Check for implicit segment
implicit_segment = [s for s in segments if s['name'] is None]
if not implicit_segment:
return changed
if len(implicit_segment) > 1:
module.fail_json(msg='Multiple segments with no name attribute exist '
'on network {}, unable to reliably adopt the '
'implicit segment.'.format(network.id))
else:
implicit_segment = implicit_segment[0]
if implicit_segment and subnets:
subnet_associated = [s for s in subnets
if s.segment_id == implicit_segment.id][0]
segment_spec = create_segment_spec(
network.id, network.name, subnet_associated.name,
physical_network=implicit_segment.physical_network)
create_or_update_segment(conn, module, segment_spec,
segment_id=implicit_segment.id,
project_id=project_id)
changed = True
return changed
elif implicit_segment and not subnets:
conn.network.delete_segment(implicit_segment.id)
changed = True
return changed
module.fail_json(msg='ERROR: Unable to reliably adopt the implicit '
'segment.')
def run_module():
result = dict(
success=False,
changed=False,
error="",
)
argument_spec = openstack_full_argument_spec(
**yaml.safe_load(DOCUMENTATION)['options']
)
module = AnsibleModule(
argument_spec,
supports_check_mode=False,
**openstack_module_kwargs()
)
default_network = module.params.get('default_network', DEFAULT_NETWORK)
net_data = module.params['net_data']
idx = module.params['idx']
error_messages = network_data_v2.validate_json_schema(net_data)
if error_messages:
module.fail_json(msg='\n\n'.join(error_messages))
try:
_, conn = openstack_cloud_from_module(module)
project_id = network_data_v2.get_project_id(conn)
ipv6_enabled = net_data.get('ipv6', False)
# Create or update the network
net_spec = create_net_spec(
net_data, get_overcloud_domain_name(conn, default_network), idx)
changed, network = create_or_update_network(conn, module,
net_spec, project_id)
result['changed'] = changed if changed else result['changed']
# Get current segments and subnets on the network
segments = list(conn.network.segments(network_id=network.id))
subnets = list(conn.network.subnets(network_id=network.id))
changed = adopt_the_implicit_segment(conn, module, segments,
subnets, network, project_id)
result['changed'] = changed if changed else result['changed']
for subnet_name, subnet_data in net_data.get('subnets', {}).items():
segment_spec = create_segment_spec(
network.id, network.name, subnet_name,
physical_network=subnet_data.get('physical_network'))
subnet_v4_spec, subnet_v6_spec = create_subnet_spec(
network.id, subnet_name, subnet_data, ipv6_enabled)
changed, segment = create_or_update_segment(
conn, module, segment_spec, project_id=project_id)
result['changed'] = changed if changed else result['changed']
if subnet_v4_spec:
subnet_v4_spec.update({'segment_id': segment.id})
changed = create_or_update_subnet(conn, module, subnet_v4_spec,
project_id)
result['changed'] = changed if changed else result['changed']
if subnet_v6_spec:
subnet_v6_spec.update({'segment_id': segment.id})
changed = create_or_update_subnet(conn, module, subnet_v6_spec,
project_id)
result['changed'] = changed if changed else result['changed']
result['success'] = True
module.exit_json(**result)
except Exception as err:
result['error'] = str(err)
result['msg'] = ("Error overcloud network provision failed!")
module.fail_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()
| 31,089
|
https://github.com/jimv39/qvcsos/blob/master/testFiles/TestKeywordExpansion.contracted.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
qvcsos
|
jimv39
|
C++
|
Code
| 3,115
| 10,127
|
// $Log$
// $FilePath$
//
// $Log3$
//
// $Filename$
// $Logfile$
// $Author$
// $Owner$
// $Date$
// $Revision$
// $Version$
// $Label$
// $Header$
// $HeaderPath$
// $VER$
// $Project$
//
// $Copyright$
#include "stdafx.h"
#include <ctype.h>
#include <time.h>
#include <string.h>
#include <mem.h>
#include <qvcs.h>
#include <qvcsMsg.h>
#include <afx.h>
#include "qTime.h"
#include "qProject.h"
#include "qPrjSet.h"
#include <get.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/*
* The one extern needed here
*/
char *pcgWorkFileName = NULL; /* Used by put to give us the name of the workfile */
/*
* Local routine templates
*/
static int locBuildRevList
(
FILE *ptLogFile,
struct qvcsRevList *psRevList,
struct qvcsRevListHead *psRevListHead,
struct qvcsCommandRevDesc *psFetchDesc
);
static void locConvertToUnixPathSeparators
(
char *pcStringToConvert
);
static int locDecideToShow
(
struct qvcsCommandRevDesc *psCurrentDesc, /* the revision we're testing */
struct qvcsCommandRevDesc *psFetchDesc /* the revision we're fetching */
);
static int locExpandCopyright
(
char *pcBuf,
FILE *ptOutFile,
char *pcCopyrightMsg,
int iBinaryFile
);
static void locExpandDescription
(
char *pcDescription,
struct qvcsRevisionInfo *psRevInfo,
char *pcRevDesc,
FILE *ptOutFile,
char *pcAccessList,
char *pcCommentPrefix,
struct getCommandArgs *psCommandArgs
);
static int locExpandKeyWords
(
char *pcLineBuf,
struct qvcsRevisionInfo *psRevInfo,
struct getCommandArgs *psCommandArgs,
struct qvcsCommandRevDesc *psFetchDesc,
FILE *ptLogFile,
long lRevStart,
long lAllRevsStart,
FILE *ptOutFile,
struct qvcsHeaderInfo *psHeaderInfo
);
static void locExpandLog
(
FILE *ptLogFile,
struct qvcsCommandRevDesc *psFetchDesc,
long lRevStart,
long lAllRevsStart,
FILE *ptOutFile,
char *pcCommentPrefix,
struct qvcsHeaderInfo *psHeaderInfo,
int iRevCount,
struct getCommandArgs *psCommandArgs
);
static int locExpandWord
(
char *pcLineBuf,
FILE *ptOutFile,
char *pcInsert,
int iBinaryFileFlag
);
/*
* g e t E x p a n d K e y W o r d s
*/
void getExpandKeyWords
(
struct qvcsRevisionInfo *psRevInfo,
char *pcFileName,
struct getCommandArgs *psCommandArgs,
FILE *ptLogFile,
long lRevStart,
long lAllRevsStart,
struct qvcsCommandRevDesc *psFetchDesc,
struct qvcsHeaderInfo *psHeaderInfo
)
{
FILE *ptOutFile; /* Expanded file */
FILE *ptInFile; /* File to be expanded */
long lBufSize; /* Size of buffer we read into */
long l; /* A long counter */
long lCount; /* Number of bytes to write */
char *pcLineBuf; /* Read into here */
char *pc;
char *pcStart; /* The start of a buffer we write */
char pcTmpFileNameBuf[qvcsFILENAME_SIZE];
/*
* Try to come up with a unique name for this guy yet another temporary
* file that we expand stuff into.
*/
if ((libCreateTempFileName (pcTmpFileNameBuf,
psCommandArgs->psEnvironVars)) != qvcsSUCCESS)
{
return;
}
/*
* Open expanded file.
*/
if ((ptOutFile = fopen (pcTmpFileNameBuf, "wb")) == NULL)
{
return;
}
/*
* Open input file. (file to be expanded).
*/
if ((ptInFile = fopen (pcFileName, "rb")) == NULL)
{
fclose (ptOutFile);
remove (pcTmpFileNameBuf);
return;
}
/*
* Find out how big the input file is, so we can allocate a worst
* case buffer for it (a buffer as big as the file itself).
*/
fseek (ptInFile, 0L, SEEK_END);
lBufSize = ftell (ptInFile);
fseek (ptInFile, 0L, SEEK_SET);
/*
* Allocate our buffer that we read into.
*/
if ((pcLineBuf = (char*)mem_malloc (lBufSize + 1)) == NULL)
{
fclose (ptOutFile);
fclose (ptInFile);
remove (pcTmpFileNameBuf);
return;
}
/*
* NULL terminate the buffer we read into. This guards against
* a possible memory protect that can occur in sscanf, since
* sscanf takes a NULL terminated string as an argument.
*/
pcLineBuf[lBufSize] = '\0';
/*
* Read the input file into the buffer we just alloced
*/
if ((fread (pcLineBuf, (size_t) lBufSize, 1, ptInFile)) != 1)
{
mem_free (pcLineBuf);
fclose (ptOutFile);
fclose (ptInFile);
remove (pcTmpFileNameBuf);
return;
}
/*
* Copy the buffer to the output file, expanding keywords as we find
* them.
*/
for (l = 0L, pc = pcLineBuf, pcStart = pcLineBuf, lCount = 1L; l < lBufSize;
l++, pc++, lCount++)
{
/*
* Check for the keyword prefix character
*/
if (*pc == qvcsKEYWORD_PREFIX)
{
/*
* Write what we've looked at so far (including the keyword prefix)
*/
if ((fwrite (pcStart, (size_t) lCount, 1, ptOutFile)) != 1)
{
mem_free (pcLineBuf);
fclose (ptOutFile);
fclose (ptInFile);
remove (pcTmpFileNameBuf);
return;
}
else
{
lCount = 0L;
}
if (locExpandKeyWords (pc,
psRevInfo,
psCommandArgs,
psFetchDesc,
ptLogFile,
lRevStart,
lAllRevsStart,
ptOutFile,
psHeaderInfo) == TRUE)
{
/*
* We found a keyword. locExpandKeyWords expanded it for us,
* and wrote it out. Look for the terminating character so
* we can start copying the rest of the file from there.
*/
do
{
pc++;
l++;
} while (*pc != qvcsKEYWORD_PREFIX);
}
pcStart = &pc[1];
}
}
/*
* Write out what's left of the file.
*/
if (lCount > 1L)
{
if ((fwrite (pcStart, (size_t) (lCount - 1L), 1, ptOutFile)) != 1)
{
fclose (ptOutFile);
fclose (ptInFile);
mem_free (pcLineBuf);
remove (pcTmpFileNameBuf);
return;
}
}
mem_free (pcLineBuf);
fclose (ptInFile);
fclose (ptOutFile);
remove (pcFileName);
rename (pcTmpFileNameBuf, pcFileName);
return;
}
/*
* l o c B u i l d R e v L i s t
*
* Build a list of revisions that are appropriate for the psFetchDesc revision.
* Return the number of revisions that we'll need to expand.
*/
static int locBuildRevList
(
FILE *ptLogFile,
struct qvcsRevList *psRevList,
struct qvcsRevListHead *psRevListHead,
struct qvcsCommandRevDesc *psFetchDesc
)
{
int iCount = 0;
long lRevStart;
struct qvcsCommandRevDesc *psRevDesc = NULL;
struct qvcsRevisionInfo sRevInfo;
for (iCount = 0 ;;)
{
lRevStart = ftell (ptLogFile);
if ((fread (&sRevInfo, sizeof (sRevInfo), 1, ptLogFile)) != 1)
{
break;
}
else
{
libConstructEffectiveRevision (&psRevDesc, &sRevInfo);
/*
* Decide whether this revision should show up in the log
*/
if (locDecideToShow (psRevDesc, psFetchDesc))
{
if (iCount == 0)
{
psRevListHead->iFirstIndex = iCount;
psRevListHead->iLastIndex = iCount;
psRevList[iCount].iNextIndex = -1;
psRevList[iCount].lRevSeek = lRevStart;
}
else
{
if (sRevInfo.siDepthCount == 0)
{
/*
* Trunks get added to the end.
*/
psRevList[psRevListHead->iLastIndex].iNextIndex = iCount;
psRevListHead->iLastIndex = iCount;
psRevList[iCount].iNextIndex = -1;
psRevList[iCount].lRevSeek = lRevStart;
}
else
{
/*
* Branches get added to the beginning.
*/
psRevList[iCount].iNextIndex = psRevListHead->iFirstIndex;
psRevListHead->iFirstIndex = iCount;
psRevList[iCount].lRevSeek = lRevStart;
}
}
libFormatRevision (psRevList[iCount].pcRevDesc, psRevDesc);
iCount++;
}
/*
* Now seek to the next qvcsRevisionInfo structure.
*/
fseek (ptLogFile, (long) sRevInfo.iDescSize, SEEK_CUR);
if ((fseek (ptLogFile, sRevInfo.lRevSize, SEEK_CUR)) != 0)
{
sprintf (pcgFmtBuf, libMsgGet (genSEEK_ERROR),
pcgProgramName, __FILE__, __LINE__);
libDisplayMsg (pcgFmtBuf, qvcsERROR_MSG_CLASS);
break;
}
}
}
if (psRevDesc) mem_free (psRevDesc);
return (iCount);
}
/*
* l o c D e c i d e T o S h o w
*
* Decide whether to show a given revision in the log keyword expansion.
* Return TRUE if the revision should be shown, FALSE if not.
*/
static int locDecideToShow
(
struct qvcsCommandRevDesc *psCurrentDesc, /* the revision we're testing */
struct qvcsCommandRevDesc *psFetchDesc /* the revision we're fetching */
)
{
int iRetVal = FALSE;
if (psFetchDesc->iElementCount == 1)
{
/*
* We're interested in a revision that's on the TRUNK.
*/
if (psCurrentDesc->iElementCount == 1)
{
char fmtFetchBuf[130];
char fmtCurrentBuf[130];
sprintf (fmtFetchBuf, "%04d%04d", psFetchDesc->sRevDesc[0].iMajorNumber, psFetchDesc->sRevDesc[0].iMinorNumber);
sprintf (fmtCurrentBuf, "%04d%04d", psCurrentDesc->sRevDesc[0].iMajorNumber, psCurrentDesc->sRevDesc[0].iMinorNumber);
if (strcmp(fmtFetchBuf, fmtCurrentBuf) >= 0)
{
iRetVal = TRUE;
}
}
}
else
{
/*
* We're interested in a revision that's on a BRANCH.
*/
if (psCurrentDesc->iElementCount == 1)
{
/*
* The current revision is on the TRUNK. See if it's
* one that preceeds the revision that we're "fetching".
*/
char fmtFetchBuf[130];
char fmtCurrentBuf[130];
sprintf (fmtFetchBuf, "%04d%04d", psFetchDesc->sRevDesc[0].iMajorNumber, psFetchDesc->sRevDesc[0].iMinorNumber);
sprintf (fmtCurrentBuf, "%04d%04d", psCurrentDesc->sRevDesc[0].iMajorNumber, psCurrentDesc->sRevDesc[0].iMinorNumber);
if (strcmp(fmtFetchBuf, fmtCurrentBuf) >= 0)
{
iRetVal = TRUE;
}
}
else
{
int i;
if (psCurrentDesc->iElementCount <= psFetchDesc->iElementCount)
{
/*
* Current revision is closer to trunk or at same depth as the
* requested revision. Make sure it's on the same branch or on
* the trunk before the requested revision.
*/
iRetVal = TRUE;
/*
* All segments before the last must match exactly
*/
for (i = 0; i < (psCurrentDesc->iElementCount - 1); i++)
{
if ((psCurrentDesc->sRevDesc[i].iMajorNumber !=
psFetchDesc->sRevDesc[i].iMajorNumber) ||
(psCurrentDesc->sRevDesc[i].iMinorNumber !=
psFetchDesc->sRevDesc[i].iMinorNumber))
{
iRetVal = FALSE;
break;
}
}
/*
* The last segment, the major numbers must match, and the minor
* number must be less than or equal to the fetched revision.
*/
if (iRetVal == TRUE)
{
if ((psCurrentDesc->sRevDesc[i].iMajorNumber !=
psFetchDesc->sRevDesc[i].iMajorNumber) ||
(psCurrentDesc->sRevDesc[i].iMinorNumber >
psFetchDesc->sRevDesc[i].iMinorNumber))
{
iRetVal = FALSE;
}
}
}
}
}
return iRetVal;
}
/*
* l o c E x p a n d K e y W o r d s
*
* Check for the presence of keywords. If we find one, expand it and write
* it to the output file and return TRUE. If we don't find one, return FALSE.
* When called, the buffer pointer points to the qvcsKEYWORD_PREFIX character.
* This routine doesn't write that character out, but writes all expanded
* characters after that (including the ending qvcsKEYWORD_PREFIX character).
*/
static int locExpandKeyWords
(
char *pcBuf,
struct qvcsRevisionInfo *psRevInfo,
struct getCommandArgs *psCommandArgs,
struct qvcsCommandRevDesc *psFetchDesc,
FILE *ptLogFile,
long lRevStart,
long lAllRevsStart,
FILE *ptOutFile,
struct qvcsHeaderInfo *psHeaderInfo
)
{
static char pcExpandPath[_MAX_PATH];
int iRetVal = TRUE;
int iRevCount;
char *pc;
char *pc1;
char pcFmtBuf [(4 * qvcsMAX_BRANCH_DEPTH) + 2];
char pcFmtBuf1[(4 * qvcsMAX_BRANCH_DEPTH) + 2];
int iBinaryFile = FALSE;
char cSearchTerminator = qvcsKEYWORD_PREFIX;
pc = pcBuf;
pc++;
if (psHeaderInfo->sDifFileHdr.iAttributes & qvcsBINARYFILE_BIT)
{
iBinaryFile = TRUE;
cSearchTerminator = qvcsKEYWORD_EXPREFIX;
}
/*
* Pointing to the keyword candidate... See if it's a keyword we know.
*/
if ((strncmp (pc, libMsgGet (keyVERSION), strlen (libMsgGet (keyVERSION))) == 0) &&
(pc [strlen (libMsgGet (keyVERSION))] == cSearchTerminator))
{
iRetVal = locExpandWord (pc, ptOutFile, psCommandArgs->pcVersion, iBinaryFile);
}
else if ((strncmp (pc, libMsgGet (keyAUTHOR), strlen (libMsgGet (keyAUTHOR))) == 0) &&
(pc [strlen (libMsgGet (keyAUTHOR))] == cSearchTerminator))
{
char *pcLocAccessList;
pcLocAccessList = (char*)mem_malloc (strlen (psHeaderInfo->pcModifierList) + 1);
strcpy (pcLocAccessList, psHeaderInfo->pcModifierList);
iRetVal = locExpandWord (pc, ptOutFile,
libConvertAccessIndex (pcLocAccessList, psRevInfo->iCreatorIndex), iBinaryFile);
mem_free (pcLocAccessList);
}
else if ((strncmp (pc, libMsgGet (keyREVISION), strlen (libMsgGet (keyREVISION))) == 0) &&
(pc [strlen (libMsgGet (keyREVISION))] == cSearchTerminator))
{
libFormatRevision (pcFmtBuf, psFetchDesc);
iRetVal = locExpandWord (pc, ptOutFile, pcFmtBuf, iBinaryFile);
}
else if ((strncmp (pc, libMsgGet (keyDATE), strlen (libMsgGet (keyDATE))) == 0) &&
(pc [strlen (libMsgGet (keyDATE))] == cSearchTerminator))
{
CQTime lastEditTime(psRevInfo->tFileDate);
CString lastEditString(lastEditTime.LongDateTimeFormatForCurrentLocale(psCommandArgs->psEnvironVars));
strcpy (pcFmtBuf, LPCTSTR(lastEditString));
iRetVal = locExpandWord (pc, ptOutFile, pcFmtBuf, iBinaryFile);
}
else if ((strncmp (pc, libMsgGet (keyOWNER), strlen (libMsgGet (keyOWNER))) == 0) &&
(pc [strlen (libMsgGet (keyOWNER))] == cSearchTerminator))
{
iRetVal = locExpandWord (pc, ptOutFile, psHeaderInfo->pcOwner, iBinaryFile);
}
else if ((strncmp (pc, libMsgGet (keyHEADER), strlen (libMsgGet (keyHEADER))) == 0) &&
(pc [strlen (libMsgGet (keyHEADER))] == cSearchTerminator))
{
char* pcFullWorkfileName;
char* pcShowWorkfileName;
libFormatRevision (pcFmtBuf, psFetchDesc);
CQTime lastEditTime(psRevInfo->tFileDate);
CString lastEditString(lastEditTime.LongDateTimeFormatForCurrentLocale(psCommandArgs->psEnvironVars));
strcpy (pcFmtBuf1, LPCTSTR(lastEditString));
/* Show just the last portion of the workfile name */
pcFullWorkfileName = pcgWorkFileName == NULL ? psCommandArgs->pcOutFileName : pcgWorkFileName;
pcShowWorkfileName = strrchr(pcFullWorkfileName, '\\');
if (pcShowWorkfileName)
{
pcShowWorkfileName++;
}
else
{
pcShowWorkfileName = pcFullWorkfileName;
}
sprintf (pcExpandPath, "%s %s:%s %s %s",
pcShowWorkfileName,
libMsgGet (keyREVISION),
pcFmtBuf,
pcFmtBuf1,
psHeaderInfo->pcOwner);
iRetVal = locExpandWord (pc, ptOutFile, pcExpandPath, iBinaryFile);
}
else if ((strncmp (pc, libMsgGet (keyLOGFILE), strlen (libMsgGet (keyLOGFILE))) == 0) &&
(pc [strlen (libMsgGet (keyLOGFILE))] == cSearchTerminator))
{
if (libExpandPath (psCommandArgs->pcLogFileName, pcExpandPath)
== qvcsSUCCESS)
{
if (psCommandArgs->psEnvironVars->iUseUnixPathSeparator)
{
locConvertToUnixPathSeparators(pcExpandPath);
}
iRetVal = locExpandWord (pc, ptOutFile, pcExpandPath, iBinaryFile);
}
else
{
if (psCommandArgs->psEnvironVars->iUseUnixPathSeparator)
{
locConvertToUnixPathSeparators(psCommandArgs->pcLogFileName);
}
iRetVal = locExpandWord (pc, ptOutFile, psCommandArgs->pcLogFileName, iBinaryFile);
}
}
else if ((strncmp (pc, libMsgGet (keyLOG), strlen (libMsgGet (keyLOG))) == 0) &&
(pc [strlen (libMsgGet (keyLOG))] == qvcsKEYWORD_PREFIX) &&
(iBinaryFile == FALSE))
{
if (libExpandPath (psCommandArgs->pcLogFileName, pcExpandPath)
== qvcsSUCCESS)
{
if (psCommandArgs->psEnvironVars->iUseUnixPathSeparator)
{
locConvertToUnixPathSeparators(pcExpandPath);
}
iRetVal = locExpandWord (pc, ptOutFile, pcExpandPath, iBinaryFile);
}
else
{
if (psCommandArgs->psEnvironVars->iUseUnixPathSeparator)
{
locConvertToUnixPathSeparators(psCommandArgs->pcLogFileName);
}
iRetVal = locExpandWord (pc, ptOutFile, psCommandArgs->pcLogFileName, iBinaryFile);
}
iRevCount = psHeaderInfo->sDifFileHdr.iRevisionCount;
locExpandLog (ptLogFile,
psFetchDesc,
lRevStart,
lAllRevsStart,
ptOutFile,
psCommandArgs->pcCommentPrefix,
psHeaderInfo,
iRevCount,
psCommandArgs);
fprintf (ptOutFile, "%s$%s$",
psCommandArgs->pcCommentPrefix,
libMsgGet (keyENDLOG));
}
else if (strncmp (pc, libMsgGet (keyLOG), strlen (libMsgGet (keyLOG))) == 0)
{
/*
* Make sure we have just numbers between the keyword and the
* qvcsKEYWORD_PREFIX character.
*/
for (pc1 = &pc[strlen (libMsgGet (keyLOG))]; isdigit (*pc1); pc1++)
{
;
}
if ((*pc1 == qvcsKEYWORD_PREFIX) && (iBinaryFile == FALSE))
{
if (libExpandPath (psCommandArgs->pcLogFileName, pcExpandPath)
== qvcsSUCCESS)
{
if (psCommandArgs->psEnvironVars->iUseUnixPathSeparator)
{
locConvertToUnixPathSeparators(pcExpandPath);
}
iRetVal = locExpandWord (pc, ptOutFile, pcExpandPath, iBinaryFile);
}
else
{
if (psCommandArgs->psEnvironVars->iUseUnixPathSeparator)
{
locConvertToUnixPathSeparators(psCommandArgs->pcLogFileName);
}
iRetVal = locExpandWord (pc, ptOutFile, psCommandArgs->pcLogFileName, iBinaryFile);
}
iRevCount = psHeaderInfo->sDifFileHdr.iRevisionCount;
sscanf (&pc [strlen (libMsgGet (keyLOG))], "%d", &iRevCount);
locExpandLog (ptLogFile,
psFetchDesc,
lRevStart,
lAllRevsStart,
ptOutFile,
psCommandArgs->pcCommentPrefix,
psHeaderInfo,
iRevCount,
psCommandArgs);
fprintf (ptOutFile, "%s$%s$",
psCommandArgs->pcCommentPrefix,
libMsgGet (keyENDLOG));
}
else
{
iRetVal = FALSE;
}
}
else if ((strncmp (pc, libMsgGet (keyFILENAME), strlen (libMsgGet (keyFILENAME))) == 0) &&
(pc [strlen (libMsgGet (keyFILENAME))] == cSearchTerminator))
{
if (pcgWorkFileName != NULL)
{
if (psCommandArgs->psEnvironVars->iUseUnixPathSeparator)
{
locConvertToUnixPathSeparators(pcgWorkFileName);
}
iRetVal = locExpandWord (pc, ptOutFile, pcgWorkFileName, iBinaryFile);
}
else
{
if (psCommandArgs->psEnvironVars->iUseUnixPathSeparator)
{
locConvertToUnixPathSeparators(psCommandArgs->pcOutFileName);
}
iRetVal = locExpandWord (pc, ptOutFile, psCommandArgs->pcOutFileName, iBinaryFile);
}
}
else if ((strncmp (pc, libMsgGet (keyVER), strlen (libMsgGet (keyVER))) == 0) &&
(pc [strlen (libMsgGet (keyVER))] == cSearchTerminator))
{
char *pcTmpFileName;
char *pc1;
pcTmpFileName = (char*)mem_malloc (strlen (psCommandArgs->pcFileName) + 1);
if (pcTmpFileName)
{
strcpy (pcTmpFileName, psCommandArgs->pcFileName);
pc1 = strrchr (pcTmpFileName, '.');
if (pc1)
{
*pc1 = '\0';
}
pc1 = strrchr (pcTmpFileName, '\\');
if (pc1)
{
pc1++;
}
else
{
pc1 = pcTmpFileName;
}
sprintf (pcExpandPath, "%s %s", pc1, psCommandArgs->pcVersion);
iRetVal = locExpandWord (pc, ptOutFile, pcExpandPath, iBinaryFile);
mem_free (pcTmpFileName);
}
}
else if ((strncmp (pc, libMsgGet (keyCOPYRIGHT), strlen (libMsgGet (keyCOPYRIGHT))) == 0) &&
(pc [strlen (libMsgGet (keyCOPYRIGHT))] == cSearchTerminator))
{
char* pcCopyrightMessage = psCommandArgs->psEnvironVars->m_pProject->projectSettings()->getCopyrightString();
iRetVal = locExpandCopyright (pc, ptOutFile, pcCopyrightMessage, iBinaryFile);
}
else
{
iRetVal = FALSE;
}
return (iRetVal);
}
/*
* l o c E x p a n d C o p y r i g h t
*
* Expand the copyright keyword by translating the ending '$' to its expanded
* value.
*/
static int locExpandCopyright
(
char *pcBuf,
FILE *ptOutFile,
char *pcCopyrightMsg,
int iBinaryFile
)
{
char *pc;
int iRetVal = TRUE;
if (iBinaryFile == FALSE)
{
/*
* Find the ending qvcsKEYWORD_PREFIX character.
*/
pc = strchr (pcBuf, qvcsKEYWORD_PREFIX);
*pc = '\0';
fprintf (ptOutFile, "%s %c %s $", pcBuf, qvcsCOPYRIGHT_EXPREFIX,
pcCopyrightMsg);
*pc = qvcsKEYWORD_PREFIX;
}
else
{
// Handle copyright expansion for binary files.
char *pcTmpBuf = (char*)mem_malloc(strlen(pcCopyrightMsg) + 3);
sprintf (pcTmpBuf, "%c %s", qvcsCOPYRIGHT_EXPREFIX, pcCopyrightMsg);
iRetVal = locExpandWord(pcBuf, ptOutFile, pcTmpBuf, iBinaryFile);
mem_free(pcTmpBuf);
}
return iRetVal;
}
/*
* l o c E x p a n d W o r d
*
* Expand a single keyword by translating the ending '$' to its expanded
* value.
*/
static int locExpandWord
(
char *pcBuf,
FILE *ptOutFile,
char *pcInsert,
int iBinaryFile
)
{
int iRetVal = TRUE;
char *pc;
char *pc1;
char *pc2;
if (iBinaryFile == FALSE)
{
/*
* Find the ending qvcsKEYWORD_PREFIX character.
*/
pc = strchr (pcBuf, qvcsKEYWORD_PREFIX);
*pc = '\0';
fprintf (ptOutFile, "%s: %s $", pcBuf, pcInsert);
*pc = qvcsKEYWORD_PREFIX;
}
else
{
/*
* Expand a keyword within a binary file. Be careful to use only the space
* the user has allocated for our use.
*/
int iInputLength = strlen(pcInsert);
int iUserDefinedSpaceLength;
char *pcUserBuf = NULL;
/*
* Look for the ':'
*/
pc = strchr(pcBuf, qvcsKEYWORD_EXPREFIX);
*pc = '\0'; // pc points to the ':' character
pc1 = pc;
pc1++; // pc1 points to the stuff following the keyword
pc2 = strchr(pc1, qvcsKEYWORD_PREFIX);
if (pc2)
{
*pc2 = '\0';
// fill the user-defined area with spaces.
iUserDefinedSpaceLength = strlen(pc1);
if (iUserDefinedSpaceLength > 1)
{
int iBytesToCopy = iInputLength < iUserDefinedSpaceLength - 2 ? iInputLength : iUserDefinedSpaceLength - 2;
pcUserBuf = (char*)mem_malloc(iUserDefinedSpaceLength);
memset(pcUserBuf, ' ', iUserDefinedSpaceLength);
memcpy(&pcUserBuf[1], pcInsert, iBytesToCopy);
fwrite(pcBuf, strlen(pcBuf), 1, ptOutFile);
fwrite(":", 1, 1, ptOutFile);
fwrite(pcUserBuf, iUserDefinedSpaceLength, 1, ptOutFile);
fwrite("$", 1, 1, ptOutFile);
mem_free(pcUserBuf);
}
else
{
// The user didn't provide any space to expand into. Bail out without
// expanding anything.
iRetVal = FALSE;
}
*pc2 = qvcsKEYWORD_PREFIX;
}
else
{
// The user didn't terminate a user area with the '$' character. Bail out
// of here without expanding anything.
iRetVal = FALSE;
}
*pc = qvcsKEYWORD_EXPREFIX;
}
return iRetVal;
}
/*
* l o c E x p a n d L o g
*
* Expand the revision info into comment lines in the source code.
*/
static void locExpandLog
(
FILE *ptLogFile,
struct qvcsCommandRevDesc *psFetchDesc,
long lRevStart,
long lAllRevsStart,
FILE *ptOutFile,
char *pcCommentPrefix,
struct qvcsHeaderInfo *psHeaderInfo,
int iRevCount,
struct getCommandArgs *psCommandArgs
)
{
char *pcDescription;
char *pcModDescription;
char *pc;
int iExpandedRevs;
int i;
struct qvcsRevisionInfo sRevInfo;
struct qvcsRevListHead sRevListHead;
struct qvcsRevList *psRevList;
struct qvcsRevList *psRevToExpand;
char *pcEOL;
// Figure out what we'll use for end-of-line.
if (psCommandArgs->psEnvironVars->iUseUnixEOL)
{
pcEOL = "\n";
}
else
{
pcEOL = "\r\n";
}
fprintf (ptOutFile, "%s%s%s", pcEOL, pcCommentPrefix, pcEOL);
/*
* Report the Module description
*/
pcModDescription = psHeaderInfo->pcModDesc;
while (pc = strchr (pcModDescription, '\n'))
{
*pc = '\0';
fprintf (ptOutFile, "%s %s%s",
pcCommentPrefix,
pcModDescription,
pcEOL);
*pc = '\n'; /* So we don't change the string */
pc++;
pcModDescription = pc;
}
fprintf (ptOutFile, "%s %s%s%s%s",
pcCommentPrefix,
pcModDescription,
pcEOL,
pcCommentPrefix,
pcEOL);
/*
* Build a list of revisions to report on.
*/
sRevListHead.iFirstIndex = -1;
sRevListHead.iLastIndex = -1;
if ((psRevList = (struct qvcsRevList*)mem_calloc (psHeaderInfo->sDifFileHdr.iRevisionCount *
sizeof (struct qvcsRevList))) == NULL)
{
return;
}
fseek (ptLogFile, lAllRevsStart, SEEK_SET);
iExpandedRevs = locBuildRevList (ptLogFile, psRevList,
&sRevListHead, psFetchDesc);
/*
* Report on requested revisions.
*/
for (i = 0, psRevToExpand = &psRevList[sRevListHead.iFirstIndex];
(i < iExpandedRevs) && (i < iRevCount);
i++, psRevToExpand = &psRevList[psRevToExpand->iNextIndex])
{
fseek (ptLogFile, psRevToExpand->lRevSeek, SEEK_SET);
if ((fread (&sRevInfo, sizeof (sRevInfo), 1, ptLogFile)) != 1)
{
break;
}
else
{
pcDescription = (char*)mem_malloc (sRevInfo.iDescSize);
fread (pcDescription, 1, sRevInfo.iDescSize, ptLogFile);
locExpandDescription (pcDescription,
&sRevInfo,
psRevToExpand->pcRevDesc,
ptOutFile,
psHeaderInfo->pcModifierList,
pcCommentPrefix,
psCommandArgs);
mem_free (pcDescription);
}
}
mem_free (psRevList);
return;
}
/*
* l o c E x p a n d D e s c r i p t i o n
*/
static void locExpandDescription
(
char *pcDescription,
struct qvcsRevisionInfo *psRevInfo,
char *pcRevDesc,
FILE *ptOutFile,
char *pcModifierList,
char *pcCommentPrefix,
struct getCommandArgs *psCommandArgs
)
{
char *pcLocModifierList;
char *pc;
char pcFormattedTime[128]; /* A buffer to fix the \r\n at end */
char *pcEOL;
// Figure out what we'll use for end-of-line.
if (psCommandArgs->psEnvironVars->iUseUnixEOL)
{
pcEOL = "\n";
}
else
{
pcEOL = "\r\n";
}
/*
* Make a local copy of the modifier list 'cuz it gets clobbered here
*/
pcLocModifierList = (char*)mem_malloc (strlen (pcModifierList) + 1);
strcpy (pcLocModifierList, pcModifierList);
/*
* Fix format of the time stamp.
*/
CQTime revisionCreationTime(psRevInfo->tPutDate);
CString revisionCreationTimeString(revisionCreationTime.FormatForCurrentLocale(psCommandArgs->psEnvironVars));
strcpy (pcFormattedTime, LPCTSTR(revisionCreationTimeString));
strcat (pcFormattedTime, pcEOL);
fprintf (ptOutFile, libMsgGet (getREV_DESC_MSG),
pcCommentPrefix,
pcRevDesc,
libConvertAccessIndex (pcLocModifierList, psRevInfo->iCreatorIndex),
pcFormattedTime);
while (pc = strchr (pcDescription, '\n'))
{
*pc = '\0';
pc++;
fprintf (ptOutFile, "%s %s%s",
pcCommentPrefix,
pcDescription,
pcEOL);
pcDescription = pc;
}
fprintf (ptOutFile, "%s %s%s%s%s",
pcCommentPrefix,
pcDescription,
pcEOL,
pcCommentPrefix,
pcEOL);
mem_free (pcLocModifierList);
return;
}
/*
* l o c C o n v e r t T o U n i x P a t h S e p a r a t o r s
*/
static void locConvertToUnixPathSeparators
(
char *pcStringToConvert
)
{
char *pc;
// Do the conversion in place.
for (pc = pcStringToConvert; *pc; pc++)
{
if (*pc == '\\')
{
*pc = '/';
}
}
return;
}
//
// 5 dollars: $$$$$
/* End of File */
| 2,823
|
https://github.com/girleffect/core-authentication-service/blob/master/authentication_service/tests/test_tasks.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
core-authentication-service
|
girleffect
|
Python
|
Code
| 566
| 2,962
|
import datetime
import logging
import uuid
from unittest.mock import MagicMock
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from django.core import mail
from django.core.management import call_command
from django.test import override_settings, TestCase
from django.utils import timezone
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from oidc_provider.models import Token, UserConsent, Code
import access_control
import user_data_store
from access_control import PurgedInvitations
from authentication_service import tasks, models
# TODO we need more test functions, for now only actual use cases are covered.
from authentication_service.models import Organisation, UserSite, UserSecurityQuestion
class SendMailCase(TestCase):
@classmethod
def setUpTestData(cls):
cls.user = get_user_model().objects.create(
username="leaving_task_user", email="awol@id.com",
birth_date=datetime.date(2001, 1, 1)
)
cls.user.set_password("atleast_its_not_1234")
cls.user.save()
def test_no_recipient(self):
test_output = "ERROR:authentication_service.tasks:Attempted to send an email of " \
"type 'unknown' without recipients"
with self.assertLogs(level=logging.ERROR) as cm:
tasks.send_mail(
{"a": "b"},
"unknown"
)
output = cm.output
self.assertIn(test_output, output[0])
self.assertEqual(len(mail.outbox), 0)
def test_account_deletion_mail(self):
tasks.send_mail(
{"reason": "The theme is ugly"},
"delete_account",
objects_to_fetch=[{
"app_label": "authentication_service",
"model": "coreuser",
"id": self.user.id,
"context_key": "user"
}]
)
self.assertEqual(
mail.outbox[0].to, tasks.MAIL_TYPE_DATA["delete_account"]["recipients"]
)
self.assertEqual(
mail.outbox[0].subject,
tasks.MAIL_TYPE_DATA["delete_account"]["subject"]
)
self.assertEqual(mail.outbox[0].body,
"The following user would "\
"like to delete their Girl Effect account."\
"\nid: %s"
"\nusername: %s"
"\nemail: %s"\
"\nmsisdn: %s"\
"\nreason: The theme is ugly\n" % (
self.user.id,
self.user.username,
self.user.email,
self.user.msisdn
)
)
def test_reset_password_mail(self):
uid = urlsafe_base64_encode(force_bytes(self.user.pk))
token = default_token_generator.make_token(self.user)
context = {
"email": self.user.email,
"domain": "test:8000",
"site_name": "test_site",
"uid": uid,
"token": token,
"protocol": "http",
}
extra = {"recipients": [self.user.email]}
user = {
"app_label": self.user._meta.app_label,
"model": self.user._meta.model_name,
"id": self.user.id,
"context_key": "user",
}
context["uid"] = context["uid"].decode("utf-8")
tasks.send_mail(
context,
"password_reset",
objects_to_fetch=[user],
extra=extra
)
self.assertEqual(
mail.outbox[0].to,
[self.user.email]
)
self.assertEqual(
mail.outbox[0].subject,
tasks.MAIL_TYPE_DATA["password_reset"]["subject"]
)
self.assertEqual(mail.outbox[0].body,
"\nYou're receiving this email because you requested a password "\
"reset for your user account at test_site.\n\nPlease go to the "\
"following page and choose a new password:\n\n"\
"http://test:8000/en/reset/"\
"%s/"\
"%s/\n\n"\
"Your username, in case you've forgotten: %s\n\n"\
"Thanks for using our site!\n\nThe test_site team\n\n\n" % (
context["uid"],
token,
self.user.username,
)
)
class SendInvitationMail(TestCase):
@classmethod
def setUpTestData(cls):
cls.organisation = Organisation.objects.create(
id=1,
name="test unit",
description="Description"
)
cls.user = get_user_model().objects.create(
username="test_user_1",
first_name="Firstname",
last_name="Lastname",
email="firstname@example.com",
is_superuser=1,
is_staff=1,
birth_date=datetime.date(2000, 1, 1)
)
def test_send_invitation_mail(self):
test_invitation_id = uuid.uuid4()
invitation = access_control.Invitation(
id=test_invitation_id.hex,
invitor_id=self.user.id,
first_name="Thename",
last_name="Thesurname",
email="thename.thesurname@example.com",
organisation_id=self.organisation.id,
expires_at=timezone.now() + datetime.timedelta(minutes=10),
created_at=timezone.now(),
updated_at=timezone.now()
)
with self.assertLogs(level=logging.INFO) as cm:
tasks.send_invitation_email(invitation.to_dict(), "http://test.me/register")
self.assertEquals(len(mail.outbox), 1)
# Check part of the email
self.assertIn("Dear Thename Thesurname", mail.outbox[0].body)
# Check log line
self.assertEqual(cm.output[0], "INFO:authentication_service.tasks:Sent invitation from "
"test_user_1 to Thename Thesurname")
class PurgeExpiredInvitations(TestCase):
@override_settings(AC_OPERATIONAL_API=MagicMock(
purge_expired_invitations=MagicMock())
)
def test_purge_expired_invitation_task(self):
settings.AC_OPERATIONAL_API.purge_expired_invitations.return_value = \
PurgedInvitations(amount=4)
with self.assertLogs(level=logging.INFO) as logs:
tasks.purge_expired_invitations(
cutoff_date=str(datetime.datetime.now().date())
)
self.assertEqual(logs.output, ["INFO:authentication_service.tasks:Purged 4 invitations."])
class DeleteUserAndData(TestCase):
@classmethod
def setUpTestData(cls):
user_model = get_user_model()
cls.organisation = Organisation.objects.create(
id=1,
name="test unit",
description="Description"
)
cls.deleter = user_model.objects.create(
username="deleter",
first_name="Del",
last_name="Eter",
email="deleter@example.com",
birth_date=datetime.date(2000, 1, 1)
)
cls.user = user_model.objects.create(
username="Username",
first_name="Us",
last_name="Er",
email="user@example.com",
birth_date=datetime.date(2000, 1, 1)
)
cls.user_site = models.UserSite.objects.create(
user=cls.user,
site_id=1
)
cls.user_site.save()
call_command("load_security_questions")
cls.user_security_question = models.UserSecurityQuestion.objects.create(
user=cls.user,
question_id=1
)
@override_settings(
AC_OPERATIONAL_API=MagicMock(
delete_user_data=MagicMock(
return_value=access_control.UserDeletionData(amount=10)
)
),
USER_DATA_STORE_API=MagicMock(
deleteduser_read=MagicMock(return_value=None),
deleteduser_create=MagicMock(return_value={}),
deleteduser_update=MagicMock(return_value={}),
deletedusersite_read=MagicMock(return_value=None),
deletedusersite_create=MagicMock(return_value={}),
deletedusersite_update=MagicMock(return_value={}),
delete_user_data=MagicMock(
return_value=user_data_store.UserDeletionData(amount=5)
)
)
)
def test_delete_user_and_data_task(self):
with self.assertLogs(level=logging.DEBUG) as logger:
tasks.delete_user_and_data_task(
user_id=self.user.id,
deleter_id=self.deleter.id,
reason="Because this is a test"
)
self.assertEquals(
logger.output, [
"DEBUG:authentication_service.tasks:10 rows deleted from Access Control",
"DEBUG:authentication_service.tasks:5 rows deleted from User Data Store",
"INFO:authentication_service.tasks:Queued deletion confirmation for Username"
f" ({self.user.id}) to Del Eter (deleter@example.com)",
])
self.assertFalse(Token.objects.filter(user=self.user).exists())
self.assertFalse(UserConsent.objects.filter(user=self.user).exists())
self.assertFalse(Code.objects.filter(user=self.user).exists())
self.assertFalse(UserSite.objects.filter(user=self.user).exists())
self.assertFalse(UserSecurityQuestion.objects.filter(user=self.user).exists())
with self.assertRaises(models.UserSite.DoesNotExist):
models.UserSite.objects.get(id=self.user_site.id)
user_model = get_user_model()
with self.assertRaises(user_model.DoesNotExist):
user_model.objects.get(id=self.user.id)
def test_delete_user_and_data_task_nonexistent_user(self):
user_id = uuid.uuid4()
with self.assertLogs(level=logging.DEBUG) as logger:
tasks.delete_user_and_data_task(
user_id=user_id,
deleter_id=self.deleter.id,
reason="Because this is a test"
)
self.assertEquals(
logger.output, [
f"ERROR:authentication_service.tasks:User {user_id} cannot be deleted "
"because it does not exist."
])
| 13,964
|
https://github.com/floriandonhauser/TeBaG-RL/blob/master/tests/__init__.py
|
Github Open Source
|
Open Source
|
MIT
| null |
TeBaG-RL
|
floriandonhauser
|
Python
|
Code
| 4
| 15
|
from tests.test_environment import test_environment_creation
| 45,136
|
https://github.com/Countly/countly-sdk-java/blob/master/sdk-java/src/test/java/ly/count/sdk/java/internal/LogTests.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
countly-sdk-java
|
Countly
|
Java
|
Code
| 484
| 2,340
|
package ly.count.sdk.java.internal;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.powermock.reflect.Whitebox;
import ly.count.sdk.java.Config;
import static ly.count.sdk.java.Config.LoggingLevel.DEBUG;
import static ly.count.sdk.java.Config.LoggingLevel.ERROR;
import static ly.count.sdk.java.Config.LoggingLevel.INFO;
import static ly.count.sdk.java.Config.LoggingLevel.OFF;
import static ly.count.sdk.java.Config.LoggingLevel.WARN;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@RunWith(JUnit4.class)
public class LogTests {
private static final String message = "message";
private static final Throwable exception = new IllegalStateException("IAS");
private InternalConfig config;
@Before
public void setupEveryTest() {
String serverUrl = "http://www.serverurl.com";
String serverAppKey = "1234";
config = new InternalConfig(new Config(serverUrl, serverAppKey));
}
@After
public void cleanupEveryTests(){
config = null;
}
@Test(expected = NullPointerException.class)
public void logInit_null(){
Log log = new Log();
log.init(null);
}
/*
@Test
public void logInit_enableTestMode() {
config.enableTestMode();
Log log = new Log();
log.init(config);
Assert.assertTrue(Whitebox.<Boolean>getInternalState(log, "testMode"));
Assert.assertEquals(INFO, Whitebox.getInternalState(log, "level"));
Log.Logger logger = mock(Log.Logger.class);
Whitebox.setInternalState(Log.class, "logger", logger);
Log.d(message, exception);
Log.i(message, exception);
Log.w(message, exception);
Log.e(message, exception);
verify(logger, never()).d(message, exception);
verify(logger, times(1)).i(message, exception);
verify(logger, times(1)).w(message, exception);
verify(logger, times(1)).e(message, exception);
}
@Test
public void logInit_setLevelDebug() {
config.setLoggingLevel(DEBUG)
.enableTestMode();
Log log = new Log();
log.init(config);
Assert.assertTrue(Whitebox.<Boolean>getInternalState(log, "testMode"));
Assert.assertEquals(DEBUG, Whitebox.getInternalState(log, "level"));
Log.Logger logger = mock(Log.Logger.class);
Whitebox.setInternalState(Log.class, "logger", logger);
Log.d(message);
Log.i(message);
Log.w(message);
Log.e(message);
verify(logger, times(1)).d(message);
verify(logger, times(1)).i(message);
verify(logger, times(1)).w(message);
verify(logger, times(1)).e(message);
}
@Test
public void logInit_setLevelInfo() {
config.setLoggingLevel(INFO)
.enableTestMode();
Log log = new Log();
log.init(config);
Assert.assertTrue(Whitebox.<Boolean>getInternalState(log, "testMode"));
Assert.assertEquals(INFO, Whitebox.getInternalState(log, "level"));
Log.Logger logger = mock(Log.Logger.class);
Whitebox.setInternalState(Log.class, "logger", logger);
Log.d(message);
Log.i(message);
Log.w(message);
Log.e(message);
verify(logger, never()).d(message);
verify(logger, times(1)).i(message);
verify(logger, times(1)).w(message);
verify(logger, times(1)).e(message);
}
@Test
public void logInit_setLevelWarn() {
config.setLoggingLevel(WARN)
.enableTestMode();
Log log = new Log();
log.init(config);
Assert.assertTrue(Whitebox.<Boolean>getInternalState(log, "testMode"));
Assert.assertEquals(WARN, Whitebox.getInternalState(log, "level"));
Log.Logger logger = mock(Log.Logger.class);
Whitebox.setInternalState(Log.class, "logger", logger);
Log.d(message, exception);
Log.i(message, exception);
Log.w(message, exception);
Log.e(message, exception);
verify(logger, never()).d(message, exception);
verify(logger, never()).i(message, exception);
verify(logger, times(1)).w(message, exception);
verify(logger, times(1)).e(message, exception);
}
@Test
public void logInit_setLevelError() {
config.setLoggingLevel(ERROR);
Log log = new Log();
log.init(config);
Assert.assertFalse(Whitebox.<Boolean>getInternalState(log, "testMode"));
Assert.assertEquals(ERROR, Whitebox.getInternalState(log, "level"));
Log.Logger logger = mock(Log.Logger.class);
Whitebox.setInternalState(Log.class, "logger", logger);
Log.d(message, exception);
Log.i(message, exception);
Log.w(message, exception);
Log.e(message, exception);
verify(logger, never()).d(message, exception);
verify(logger, never()).i(message, exception);
verify(logger, never()).w(message, exception);
verify(logger, times(1)).e(message, exception);
}
@Test
public void logInit_setLevelOff() {
config.setLoggingLevel(OFF);
Log log = new Log();
log.init(config);
Assert.assertFalse(Whitebox.<Boolean>getInternalState(log, "testMode"));
Assert.assertEquals(OFF, Whitebox.getInternalState(log, "level"));
Log.Logger logger = mock(Log.Logger.class);
Whitebox.setInternalState(Log.class, "logger", logger);
Log.d(message, exception);
Log.i(message, exception);
Log.w(message, exception);
Log.e(message, exception);
verify(logger, never()).d(message, exception);
verify(logger, never()).i(message, exception);
verify(logger, never()).w(message, exception);
verify(logger, never()).e(message, exception);
}
@Test
public void logInit_noLevel() {
Log log = new Log();
log.init(config);
Assert.assertFalse(Whitebox.<Boolean>getInternalState(log, "testMode"));
Assert.assertEquals(OFF, Whitebox.getInternalState(log, "level"));
Log.Logger logger = mock(Log.Logger.class);
Whitebox.setInternalState(Log.class, "logger", logger);
Log.d(message, exception);
Log.i(message, exception);
Log.w(message, exception);
Log.e(message, exception);
verify(logger, never()).d(message, exception);
verify(logger, never()).i(message, exception);
verify(logger, never()).w(message, exception);
verify(logger, never()).e(message, exception);
}
@Test
public void logInit_wtf_noLevel() {
Log log = new Log();
log.init(config);
Assert.assertFalse(Whitebox.<Boolean>getInternalState(log, "testMode"));
Assert.assertEquals(OFF, Whitebox.getInternalState(log, "level"));
Log.Logger logger = mock(Log.Logger.class);
Whitebox.setInternalState(Log.class, "logger", logger);
Log.d(message, exception);
Log.i(message, exception);
Log.w(message, exception);
Log.e(message, exception);
Log.wtf(message, exception);
verify(logger, never()).d(message, exception);
verify(logger, never()).i(message, exception);
verify(logger, never()).w(message, exception);
verify(logger, never()).e(message, exception);
verify(logger, never()).wtf(message, exception);
}
@Test(expected = IllegalStateException.class)
public void logInit_wtf_testMode() {
config.enableTestMode();
Log log = new Log();
log.init(config);
Assert.assertTrue(Whitebox.<Boolean>getInternalState(log, "testMode"));
Assert.assertEquals(INFO, Whitebox.getInternalState(log, "level"));
Log.wtf(message, exception);
}
*/
}
| 20,628
|
https://github.com/fz6m/commit-verify/blob/master/src/interface.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
commit-verify
|
fz6m
|
TypeScript
|
Code
| 164
| 519
|
export enum EEmojiPos {
start = 'start',
end = 'end',
}
export interface IConfig {
/**
* whether auto add emoji to commit msg
* @default false
*/
emoji?: boolean
/**
* will add random emoji list
* @default ['🍓', '🍉', '🍇', '🍒', '🍡', '🍥', '🍩', '🍰', '🍭', '🌸', '🌈']
*/
emojiList?: string[]
/**
* will add emoji position in commit msg
* @enum start 'feat(scope): some' => 'feat(scope)🍓: some'
* @enum end 'feat(scope): some' => 'feat(scope): some 🍓'
* @default start
*/
emojiPos?: EEmojiPos
/**
* allow commit msg format
*/
format?: RegExp | false
/**
* custom commit msg transoform on format regex check after
*/
transformer?: (commitMsg: string) => string
}
export const DEFAULT_CONFIG_NAME = 'cv'
export const DEFAULT_CONFIG: Required<IConfig> = {
emoji: false,
emojiList: ['🍓', '🍉', '🍇', '🍒', '🍡', '🍥', '🍩', '🍰', '🍭', '🌸', '🌈'],
emojiPos: EEmojiPos.start,
/**
* Merge: for github
* Revert: for github
* Version Packages: for changesets
*/
format:
/^(((feat|fix|docs|style|refactor|perf|test|workflow|build|ci|chore|types|wip|release|deps?|merge|examples?|revert)(\(.+\))?:)|(Merge|Revert|Version)) .{1,50}$/i,
transformer: (c) => c,
}
| 30,083
|
https://github.com/code-distortion/be-prepared-for-tests/blob/master/src/Adapters/LaravelPostgreSQL/LaravelPostgreSQLBuild.php
|
Github Open Source
|
Open Source
|
MIT
| null |
be-prepared-for-tests
|
code-distortion
|
PHP
|
Code
| 370
| 1,162
|
<?php
namespace CodeDistortion\Adapt\Adapters\LaravelPostgreSQL;
use CodeDistortion\Adapt\Adapters\Interfaces\BuildInterface;
use CodeDistortion\Adapt\Adapters\Traits\InjectTrait;
use CodeDistortion\Adapt\Adapters\Traits\Laravel\LaravelBuildTrait;
use CodeDistortion\Adapt\Adapters\Traits\Laravel\LaravelHelperTrait;
use CodeDistortion\Adapt\Exceptions\AdaptBuildException;
use Throwable;
/**
* Database-adapter methods related to building a Laravel/PostgreSQL database.
*/
class LaravelPostgreSQLBuild implements BuildInterface
{
use InjectTrait;
use LaravelBuildTrait;
use LaravelHelperTrait;
/**
* Check if this database will disappear after use.
*
* @return boolean
*/
public function databaseIsEphemeral(): bool
{
return false;
}
/**
* Check if this database type supports database re-use.
*
* @return boolean
*/
public function supportsReuse(): bool
{
return true;
}
/**
* Check if this database type supports the use of scenario-databases.
*
* @return boolean
*/
public function supportsScenarios(): bool
{
return true;
}
/**
* Check if this database type can be built remotely.
*
* @return boolean
*/
public function canBeBuiltRemotely(): bool
{
return true;
}
/**
* Check if this database type can be used when browser testing.
*
* @return boolean
*/
public function isCompatibleWithBrowserTests(): bool
{
return true;
}
/**
* Create the database if it doesn't exist, and wipe the database clean if it does.
*
* @return void
*/
public function resetDB()
{
if ($this->di->db->currentDatabaseExists()) {
$this->dropDB();
}
$this->createDB();
}
/**
* Create a new database.
*
* @return void
* @throws AdaptBuildException When the database couldn't be created.
*/
private function createDB()
{
$logTimer = $this->di->log->newTimer();
try {
$this->di->db->newPDO()->createDatabase("CREATE DATABASE \"{$this->configDTO->database}\"");
} catch (Throwable $e) {
throw AdaptBuildException::couldNotCreateDatabase(
(string) $this->configDTO->database,
(string) $this->configDTO->driver,
$e
);
}
$this->di->log->debug('Created a new database', $logTimer);
}
/**
* Drop the database.
*
* @return void
*/
private function dropDB()
{
$logTimer = $this->di->log->newTimer();
// disconnect so that connection isn't sitting around
$this->di->db->purge();
$database = (string) $this->configDTO->database;
try {
// (FORCE) was introduced in PostgreSQL 13
// https://dba.stackexchange.com/questions/11893/force-drop-db-while-others-may-be-connected
$this->di->db->newPDO()->dropDatabase("DROP DATABASE IF EXISTS \"$database\" (FORCE)", $database);
} catch (AdaptBuildException $e) {
// so fall-back to this if the (FORCE) query fails
$this->di->db->newPDO()->dropDatabase("DROP DATABASE IF EXISTS \"$database\"", $database);
}
$this->di->log->debug('Dropped the existing database', $logTimer);
}
/**
* Migrate the database.
*
* @param string|null $migrationsPath The location of the migrations.
* @return void
*/
public function migrate($migrationsPath)
{
$this->laravelMigrate($migrationsPath);
}
/**
* Run the given seeders.
*
* @param string[] $seeders The seeders to run.
* @return void
*/
public function seed($seeders)
{
$this->laravelSeed($seeders);
}
}
| 34,280
|
https://github.com/IreneGinani/twu-biblioteca-ireneginani/blob/master/biblioteca_queries/q5.sql
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
twu-biblioteca-ireneginani
|
IreneGinani
|
SQL
|
Code
| 15
| 39
|
SELECT name, COUNT(name) FROM member INNER JOIN checkout_item ON member.id = checkout_item.member_id
GROUP BY name;
| 24,452
|
https://github.com/weizai118/zstack/blob/master/search/src/main/java/org/zstack/zql/ast/parser/visitors/OrderByVisitor.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
zstack
|
weizai118
|
Java
|
Code
| 31
| 178
|
package org.zstack.zql.ast.parser.visitors;
import org.zstack.header.zql.ASTNode;
import org.zstack.zql.antlr4.ZQLBaseVisitor;
import org.zstack.zql.antlr4.ZQLParser;
public class OrderByVisitor extends ZQLBaseVisitor<ASTNode.OrderBy> {
@Override
public ASTNode.OrderBy visitOrderBy(ZQLParser.OrderByContext ctx) {
ASTNode.OrderBy o = new ASTNode.OrderBy();
o.setDirection(ctx.ORDER_BY_VALUE().getText());
o.setField(ctx.ID().getText());
return o;
}
}
| 48,459
|
https://github.com/jvmendesavila/knockout-tournament/blob/master/components/Player/List/Field/style.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
knockout-tournament
|
jvmendesavila
|
TypeScript
|
Code
| 32
| 90
|
import { makeStyles, Theme } from '@material-ui/core'
const useStyles = makeStyles((theme: Theme) => ({
infoContainer: {
padding: 12
},
infoTitle: {
marginBottom: 8,
fontWeight: 600,
color: theme.palette.primary.main
}
}))
export default useStyles
| 22,207
|
https://github.com/jadob/container/blob/master/Event/ContainerRelatedEventInterface.php
|
Github Open Source
|
Open Source
|
MIT
| null |
container
|
jadob
|
PHP
|
Code
| 8
| 33
|
<?php
declare(strict_types=1);
namespace Jadob\Container\Event;
interface ContainerRelatedEventInterface
{
}
| 22,212
|
https://github.com/navikt/aktivitetsplan/blob/master/src/moduler/aktivitet/ny-aktivitet/NyAktivitetForm.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
aktivitetsplan
|
navikt
|
TSX
|
Code
| 340
| 1,649
|
import { PayloadAction, isFulfilled } from '@reduxjs/toolkit';
import React, { MouseEventHandler, useRef } from 'react';
import { useSelector } from 'react-redux';
import { Route, Routes, useNavigate } from 'react-router-dom';
import { AktivitetStatus } from '../../../datatypes/aktivitetTypes';
import { VeilarbAktivitet, VeilarbAktivitetType } from '../../../datatypes/internAktivitetTypes';
import useAppDispatch from '../../../felles-komponenter/hooks/useAppDispatch';
import { CONFIRM, useConfirmOnBeforeUnload } from '../../../felles-komponenter/hooks/useConfirmOnBeforeUnload';
import Modal from '../../../felles-komponenter/modal/Modal';
import ModalHeader from '../../../felles-komponenter/modal/ModalHeader';
import { useRoutes } from '../../../routes';
import { removeEmptyKeysFromObject } from '../../../utils/object';
import { selectLagNyAktivitetFeil } from '../../feilmelding/feil-selector';
import Feilmelding from '../../feilmelding/Feilmelding';
import { selectErUnderOppfolging } from '../../oppfolging-status/oppfolging-selector';
import { lagNyAktivitet } from '../aktivitet-actions';
import MedisinskBehandlingForm from '../aktivitet-forms/behandling/MedisinskBehandlingForm';
import EgenAktivitetForm from '../aktivitet-forms/egen/AktivitetEgenForm';
import IJobbAktivitetForm from '../aktivitet-forms/ijobb/AktivitetIjobbForm';
import MoteAktivitetForm from '../aktivitet-forms/mote/MoteAktivitetForm';
import SamtalereferatForm from '../aktivitet-forms/samtalereferat/SamtalereferatForm';
import SokeAvtaleAktivitetForm from '../aktivitet-forms/sokeavtale/AktivitetSokeavtaleForm';
import StillingAktivitetForm from '../aktivitet-forms/stilling/AktivitetStillingForm';
import { AktivitetFormValues } from '../rediger/EndreAktivitet';
const NyAktivitetForm = () => {
const navigate = useNavigate();
const dispatch = useAppDispatch();
const { aktivitetRoute, hovedsideRoute, nyAktivitetRoute } = useRoutes();
const opprettFeil = useSelector(selectLagNyAktivitetFeil);
const underOppfolging = useSelector(selectErUnderOppfolging);
const dirtyRef = useRef(false);
useConfirmOnBeforeUnload(dirtyRef);
const onSubmitFactory = (aktivitetsType: VeilarbAktivitetType) => {
return (aktivitet: AktivitetFormValues) => {
const filteredAktivitet = removeEmptyKeysFromObject(aktivitet);
const nyAktivitet: VeilarbAktivitet = {
status: AktivitetStatus.PLANLAGT,
type: aktivitetsType,
...filteredAktivitet,
} as VeilarbAktivitet;
return dispatch(lagNyAktivitet(nyAktivitet)).then((action) => {
if (isFulfilled(action)) {
navigate(aktivitetRoute((action as PayloadAction<VeilarbAktivitet>).payload.id));
}
});
};
};
function onRequestClose() {
const isItReallyDirty = dirtyRef.current;
if (!isItReallyDirty || window.confirm(CONFIRM)) {
navigate(hovedsideRoute());
}
}
const onReqBack: MouseEventHandler = (e) => {
e.preventDefault();
const isItReallyDirty = dirtyRef.current;
if (!isItReallyDirty || window.confirm(CONFIRM)) {
navigate(nyAktivitetRoute());
}
};
const header = <ModalHeader tilbakeTekst="Tilbake til kategorier" onTilbakeClick={onReqBack} />;
if (!underOppfolging) {
return null;
}
return (
<Modal header={header} onRequestClose={onRequestClose} contentLabel="Ny aktivitetstype">
<article>
<Routes>
<Route
path={`mote`}
element={
<MoteAktivitetForm
onSubmit={onSubmitFactory(VeilarbAktivitetType.MOTE_TYPE)}
dirtyRef={dirtyRef}
/>
}
/>
<Route
path={`samtalereferat`}
element={
<SamtalereferatForm
onSubmit={onSubmitFactory(VeilarbAktivitetType.SAMTALEREFERAT_TYPE)}
dirtyRef={dirtyRef}
/>
}
/>
<Route
path={`stilling`}
element={
<StillingAktivitetForm
onSubmit={onSubmitFactory(VeilarbAktivitetType.STILLING_AKTIVITET_TYPE)}
dirtyRef={dirtyRef}
/>
}
/>
<Route
path={`sokeavtale`}
element={
<SokeAvtaleAktivitetForm
onSubmit={onSubmitFactory(VeilarbAktivitetType.SOKEAVTALE_AKTIVITET_TYPE)}
dirtyRef={dirtyRef}
/>
}
/>
<Route
path={`behandling`}
element={
<MedisinskBehandlingForm
onSubmit={onSubmitFactory(VeilarbAktivitetType.BEHANDLING_AKTIVITET_TYPE)}
dirtyRef={dirtyRef}
/>
}
/>
<Route
path={`egen`}
element={
<EgenAktivitetForm
onSubmit={onSubmitFactory(VeilarbAktivitetType.EGEN_AKTIVITET_TYPE)}
dirtyRef={dirtyRef}
/>
}
/>
<Route
path={`ijobb`}
element={
<IJobbAktivitetForm
onSubmit={onSubmitFactory(VeilarbAktivitetType.IJOBB_AKTIVITET_TYPE)}
dirtyRef={dirtyRef}
/>
}
/>
</Routes>
</article>
<Feilmelding feilmeldinger={opprettFeil} />
</Modal>
);
};
export default NyAktivitetForm;
| 25,154
|
https://github.com/Kelsiii/Gaze/blob/master/gaze/nodes/core.py
|
Github Open Source
|
Open Source
|
MIT
| null |
Gaze
|
Kelsiii
|
Python
|
Code
| 97
| 430
|
import cv2 as cv
from ..engine.base_node import Node
class EdgeDetection(Node):
def __init__(self, **kwargs):
super(EdgeDetection, self).__init__(**kwargs)
def call(self, inputs, **kwargs):
gray = cv.cvtColor(inputs, cv.COLOR_BGR2GRAY)
laplacian = cv.Laplacian(gray, cv.CV_8U)
output = cv.cvtColor(laplacian, cv.COLOR_GRAY2RGB)
return output
class FaceDetection(Node):
def __init__(self, **kwargs):
super(FaceDetection, self).__init__(**kwargs)
def call(self, inputs, **kwargs):
from ..nodes.face_detection_utils import process_one_frame
return process_one_frame(inputs)
class FaceRecognition(Node):
def __init__(self, **kwargs):
super(FaceRecognition, self).__init__(**kwargs)
def call(self, inputs, **kwargs):
from ..nodes.face_recognition_utils import process_one_frame
return process_one_frame(inputs)
class WinFileSink(Sink):
def __init__(self, **kwargs):
super(WinFileSink, self).__init__(**kwargs)
fourcc = cv.VideoWriter_fourcc(*'MJPG')
self.out = cv.VideoWriter(filename='output.avi', fourcc=fourcc, fps=20.0, frameSize=(960, 720), isColor=True)
def call(self, inputs, **kwargs):
if inputs is not None:
self.out.write(inputs)
return None
| 15,289
|
https://github.com/linmuxi/AndroidTV/blob/master/src/com/jxjr/tv/PropertiesUtil.java
|
Github Open Source
|
Open Source
|
MIT
| null |
AndroidTV
|
linmuxi
|
Java
|
Code
| 78
| 325
|
/*
* Copyright 2015 the original author or phly.
* 鏈粡姝e紡涔﹂潰鍚屾剰锛屽叾浠栦换浣曚釜浜恒�鍥綋涓嶅緱浣跨敤銆佸鍒躲�淇敼鎴栧彂甯冩湰杞欢.
*/
package com.jxjr.tv;
import java.io.IOException;
import java.util.Properties;
public class PropertiesUtil {
private static final Properties prop = new Properties();
private static final PropertiesUtil util = new PropertiesUtil();
private PropertiesUtil() {
try {
prop.load(PropertiesUtil.class.getClassLoader()
.getResourceAsStream("config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static PropertiesUtil getInstance() {
return util;
}
/**
*
* @param key
* @return
*/
public String getValue(String key) {
return prop.getProperty(key);
}
}
| 16,440
|
https://github.com/entone/brood/blob/master/priv/ui/src/types.js
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
brood
|
entone
|
JavaScript
|
Code
| 75
| 222
|
export const SEND_MESSAGE = 'SEND_MESSAGE';
export const UPDATE_UI = 'UPDATE_UI';
export const RECEIVE_ACTION = 'ACTION';
export const RECEIVE_DATA_POINT = 'DATA_POINT';
export const RECEIVE_DATA = 'DATA';
export const RECEIVE_IMAGE = 'IMAGE';
export const RECEIVE_CHANNEL_SETTINGS = 'CHANNEL_SETTINGS';
export const RECEIVE_AUTHENTICATION = 'AUTHENTICATION';
export const CHANGE_KIT = 'CHANGE_KIT';
export const KIT_ADDED = 'KIT_ADDED';
export const UPDATE_DATA = 'UPDATE_DATA';
export const LOGIN = 'LOGIN';
export const LOGOUT = 'LOGOUT';
export const AUTHENTICATED = 'AUTHENTICATED';
export const AUTH_ERROR = 'AUTH_ERROR';
| 37,488
|
https://github.com/wj596/fastboot/blob/master/plugs/security/src/main/java/org/jsets/fastboot/security/config/SecurityCustomizer.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
fastboot
|
wj596
|
Java
|
Code
| 367
| 1,276
|
/*
* Copyright 2021-2022 the original author(https://github.com/wj596)
*
* <p>
* 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.
* </p>
*/
package org.jsets.fastboot.security.config;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.jsets.fastboot.security.IAccountProvider;
import org.jsets.fastboot.security.IAuthRuleProvider;
import org.jsets.fastboot.security.IAuthenticator;
import org.jsets.fastboot.security.IAuthorizer;
import org.jsets.fastboot.security.ICaptchaProvider;
import org.jsets.fastboot.security.IEncryptProvider;
import org.jsets.fastboot.security.filter.InnerFilter;
import org.jsets.fastboot.security.listener.AuthcListener;
import org.jsets.fastboot.security.listener.AuthzListener;
import org.jsets.fastboot.security.listener.PasswordRetryListener;
import org.jsets.fastboot.security.realm.Realm;
import java.util.List;
import java.util.Map;
public class SecurityCustomizer {
private IAccountProvider accountProvider;
private IEncryptProvider encryptProvider;
private ICaptchaProvider captchaProvider;
private IAuthRuleProvider authRuleProvider;
private IAuthenticator authenticator;
private IAuthorizer authorizer;
private Map<String, InnerFilter> filters = Maps.newLinkedHashMap();
private List<Realm> realms = Lists.newLinkedList();
private List<AuthcListener> authcListeners = Lists.newLinkedList();
private List<AuthzListener> authzListeners = Lists.newLinkedList();
private PasswordRetryListener passwordRetryListener;
public IAccountProvider getAccountProvider() {
return accountProvider;
}
public void setAccountProvider(IAccountProvider accountProvider) {
this.accountProvider = accountProvider;
}
public IEncryptProvider getEncryptProvider() {
return encryptProvider;
}
public void setEncryptProvider(IEncryptProvider encryptProvider) {
this.encryptProvider = encryptProvider;
}
public ICaptchaProvider getCaptchaProvider() {
return captchaProvider;
}
public void setCaptchaProvider(ICaptchaProvider captchaProvider) {
this.captchaProvider = captchaProvider;
}
public IAuthRuleProvider getAuthRuleProvider() {
return authRuleProvider;
}
public void setAuthRuleProvider(IAuthRuleProvider authRuleProvider) {
this.authRuleProvider = authRuleProvider;
}
public Map<String, InnerFilter> getFilters() {
return filters;
}
public void addFilter(String name, InnerFilter filter) {
this.filters.put(name, filter);
}
public List<Realm> getRealms() {
return realms;
}
public void addRealm(Realm realm) {
this.realms.add(realm);
}
public List<AuthcListener> getAuthcListeners() {
return authcListeners;
}
public void setAuthcListeners(List<AuthcListener> authcListeners) {
this.authcListeners = authcListeners;
}
public void setFilters(Map<String, InnerFilter> filters) {
this.filters = filters;
}
public List<AuthzListener> getAuthzListeners() {
return authzListeners;
}
public void setAuthzListeners(List<AuthzListener> authzListeners) {
this.authzListeners = authzListeners;
}
public PasswordRetryListener getPasswordRetryListener() {
return passwordRetryListener;
}
public void setPasswordRetryListener(PasswordRetryListener passwordRetryListener) {
this.passwordRetryListener = passwordRetryListener;
}
public IAuthenticator getAuthenticator() {
return authenticator;
}
public void setAuthenticator(IAuthenticator authenticator) {
this.authenticator = authenticator;
}
public IAuthorizer getAuthorizer() {
return authorizer;
}
public void setAuthorizer(IAuthorizer authorizer) {
this.authorizer = authorizer;
}
}
| 38,176
|
https://github.com/Thavarajan/koia/blob/master/src/app/shared/utils/string-utils.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
koia
|
Thavarajan
|
TypeScript
|
Code
| 215
| 487
|
export class StringUtils {
static readonly EMPTY = '';
/**
* @return abbreviated string using ellipses or specified string if it doesn't exceed [[maxWidth]]
*/
static abbreviate(str: string, maxWidth: number): string {
if (!str || str.length <= maxWidth) {
return str;
}
return str.substr(0, maxWidth - 3) + '...';
}
/**
* capitalizes a string changing the first letter to uppercase; no other letters are changed
*/
static capitalize(s: string): string {
if (s && s.length > 0) {
return s[0].toUpperCase() + s.slice(1);
}
return s;
}
/**
* quote the given string with single quotes
*
* @param the quoted string (e.g. "'mystring'"), or "''" if the input was null
*/
static quote(s: string): string {
return '\'' + (s || StringUtils.EMPTY) + '\'';
}
static insertAt(baseString: string, stringToInsert: string, position: number): string {
if (position === 0) {
return stringToInsert + baseString;
} else if (position === baseString.length) {
return baseString + stringToInsert;
} else {
return baseString.substring(0, position) + stringToInsert + baseString.substring(position);
}
}
static removeCharAt(s: string, position: number): string {
return s.slice(0, position) + s.slice(position + 1);
}
/**
* @returns a number that indicates how many times the 'word' is contained in the 'baseString' (no overlapping)
*/
static occurrences(baseString: string, word: string): number {
return baseString.split(word).length - 1;
}
}
| 31,964
|
https://github.com/bobbyangers/XrmUnitTest/blob/master/DLaB.Xrm.Entities/msdyn_workhourtemplate.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
XrmUnitTest
|
bobbyangers
|
C#
|
Code
| 1,904
| 13,036
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DLaB.Xrm.Entities
{
[System.Runtime.Serialization.DataContractAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9369")]
public enum msdyn_workhourtemplateState
{
[System.Runtime.Serialization.EnumMemberAttribute()]
Active = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
Inactive = 1,
}
/// <summary>
/// Template where resource working hours can be saved and reused.
/// </summary>
[System.Runtime.Serialization.DataContractAttribute()]
[Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute("msdyn_workhourtemplate")]
[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9369")]
public partial class msdyn_workhourtemplate : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged
{
public static class Fields
{
public const string CreatedBy = "createdby";
public const string CreatedOn = "createdon";
public const string CreatedOnBehalfBy = "createdonbehalfby";
public const string ImportSequenceNumber = "importsequencenumber";
public const string ModifiedBy = "modifiedby";
public const string ModifiedOn = "modifiedon";
public const string ModifiedOnBehalfBy = "modifiedonbehalfby";
public const string msdyn_bookableresourceid = "msdyn_bookableresourceid";
public const string msdyn_calendarid = "msdyn_calendarid";
public const string msdyn_description = "msdyn_description";
public const string msdyn_name = "msdyn_name";
public const string msdyn_workhourtemplateId = "msdyn_workhourtemplateid";
public const string Id = "msdyn_workhourtemplateid";
public const string OverriddenCreatedOn = "overriddencreatedon";
public const string OwnerId = "ownerid";
public const string OwningBusinessUnit = "owningbusinessunit";
public const string OwningTeam = "owningteam";
public const string OwningUser = "owninguser";
public const string StateCode = "statecode";
public const string StatusCode = "statuscode";
public const string TimeZoneRuleVersionNumber = "timezoneruleversionnumber";
public const string UTCConversionTimeZoneCode = "utcconversiontimezonecode";
public const string VersionNumber = "versionnumber";
public const string business_unit_msdyn_workhourtemplate = "business_unit_msdyn_workhourtemplate";
public const string lk_msdyn_workhourtemplate_createdby = "lk_msdyn_workhourtemplate_createdby";
public const string lk_msdyn_workhourtemplate_createdonbehalfby = "lk_msdyn_workhourtemplate_createdonbehalfby";
public const string lk_msdyn_workhourtemplate_modifiedby = "lk_msdyn_workhourtemplate_modifiedby";
public const string lk_msdyn_workhourtemplate_modifiedonbehalfby = "lk_msdyn_workhourtemplate_modifiedonbehalfby";
public const string msdyn_bookableresource_msdyn_workhourtemplate_bookableresourceid = "msdyn_bookableresource_msdyn_workhourtemplate_bookableresourceid";
public const string team_msdyn_workhourtemplate = "team_msdyn_workhourtemplate";
public const string user_msdyn_workhourtemplate = "user_msdyn_workhourtemplate";
}
/// <summary>
/// Default Constructor.
/// </summary>
[System.Diagnostics.DebuggerNonUserCode()]
public msdyn_workhourtemplate() :
base(EntityLogicalName)
{
}
public const string EntityLogicalName = "msdyn_workhourtemplate";
public const string PrimaryIdAttribute = "msdyn_workhourtemplateid";
public const string PrimaryNameAttribute = "msdyn_name";
public const int EntityTypeCode = 10027;
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging;
[System.Diagnostics.DebuggerNonUserCode()]
private void OnPropertyChanged(string propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
[System.Diagnostics.DebuggerNonUserCode()]
private void OnPropertyChanging(string propertyName)
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName));
}
}
/// <summary>
/// Unique identifier of the user who created the record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")]
public Microsoft.Xrm.Sdk.EntityReference CreatedBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdby");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("CreatedBy");
this.SetAttributeValue("createdby", value);
this.OnPropertyChanged("CreatedBy");
}
}
/// <summary>
/// Date and time when the record was created.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdon")]
public System.Nullable<System.DateTime> CreatedOn
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.DateTime>>("createdon");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("CreatedOn");
this.SetAttributeValue("createdon", value);
this.OnPropertyChanged("CreatedOn");
}
}
/// <summary>
/// Unique identifier of the delegate user who created the record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")]
public Microsoft.Xrm.Sdk.EntityReference CreatedOnBehalfBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("createdonbehalfby");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("CreatedOnBehalfBy");
this.SetAttributeValue("createdonbehalfby", value);
this.OnPropertyChanged("CreatedOnBehalfBy");
}
}
/// <summary>
/// Sequence number of the import that created this record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("importsequencenumber")]
public System.Nullable<int> ImportSequenceNumber
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<int>>("importsequencenumber");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("ImportSequenceNumber");
this.SetAttributeValue("importsequencenumber", value);
this.OnPropertyChanged("ImportSequenceNumber");
}
}
/// <summary>
/// Unique identifier of the user who modified the record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")]
public Microsoft.Xrm.Sdk.EntityReference ModifiedBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedby");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("ModifiedBy");
this.SetAttributeValue("modifiedby", value);
this.OnPropertyChanged("ModifiedBy");
}
}
/// <summary>
/// Date and time when the record was modified.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedon")]
public System.Nullable<System.DateTime> ModifiedOn
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.DateTime>>("modifiedon");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("ModifiedOn");
this.SetAttributeValue("modifiedon", value);
this.OnPropertyChanged("ModifiedOn");
}
}
/// <summary>
/// Unique identifier of the delegate user who modified the record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")]
public Microsoft.Xrm.Sdk.EntityReference ModifiedOnBehalfBy
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("modifiedonbehalfby");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("ModifiedOnBehalfBy");
this.SetAttributeValue("modifiedonbehalfby", value);
this.OnPropertyChanged("ModifiedOnBehalfBy");
}
}
/// <summary>
/// Shows the bookable resource from which calendar needs to be copied
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_bookableresourceid")]
public Microsoft.Xrm.Sdk.EntityReference msdyn_bookableresourceid
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("msdyn_bookableresourceid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_bookableresourceid");
this.SetAttributeValue("msdyn_bookableresourceid", value);
this.OnPropertyChanged("msdyn_bookableresourceid");
}
}
/// <summary>
/// Shows the calendar that the work hour template uses.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_calendarid")]
public string msdyn_calendarid
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("msdyn_calendarid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_calendarid");
this.SetAttributeValue("msdyn_calendarid", value);
this.OnPropertyChanged("msdyn_calendarid");
}
}
/// <summary>
/// Type an entity description.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_description")]
public string msdyn_description
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("msdyn_description");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_description");
this.SetAttributeValue("msdyn_description", value);
this.OnPropertyChanged("msdyn_description");
}
}
/// <summary>
/// The name of the custom entity.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_name")]
public string msdyn_name
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<string>("msdyn_name");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_name");
this.SetAttributeValue("msdyn_name", value);
this.OnPropertyChanged("msdyn_name");
}
}
/// <summary>
/// Unique identifier for entity instances
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_workhourtemplateid")]
public System.Nullable<System.Guid> msdyn_workhourtemplateId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.Guid>>("msdyn_workhourtemplateid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplateId");
this.SetAttributeValue("msdyn_workhourtemplateid", value);
if (value.HasValue)
{
base.Id = value.Value;
}
else
{
base.Id = System.Guid.Empty;
}
this.OnPropertyChanged("msdyn_workhourtemplateId");
}
}
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_workhourtemplateid")]
public override System.Guid Id
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return base.Id;
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.msdyn_workhourtemplateId = value;
}
}
/// <summary>
/// Date and time that the record was migrated.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("overriddencreatedon")]
public System.Nullable<System.DateTime> OverriddenCreatedOn
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<System.DateTime>>("overriddencreatedon");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("OverriddenCreatedOn");
this.SetAttributeValue("overriddencreatedon", value);
this.OnPropertyChanged("OverriddenCreatedOn");
}
}
/// <summary>
/// Owner Id
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("ownerid")]
public Microsoft.Xrm.Sdk.EntityReference OwnerId
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("ownerid");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("OwnerId");
this.SetAttributeValue("ownerid", value);
this.OnPropertyChanged("OwnerId");
}
}
/// <summary>
/// Unique identifier for the business unit that owns the record
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owningbusinessunit")]
public Microsoft.Xrm.Sdk.EntityReference OwningBusinessUnit
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("owningbusinessunit");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("OwningBusinessUnit");
this.SetAttributeValue("owningbusinessunit", value);
this.OnPropertyChanged("OwningBusinessUnit");
}
}
/// <summary>
/// Unique identifier for the team that owns the record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owningteam")]
public Microsoft.Xrm.Sdk.EntityReference OwningTeam
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("owningteam");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("OwningTeam");
this.SetAttributeValue("owningteam", value);
this.OnPropertyChanged("OwningTeam");
}
}
/// <summary>
/// Unique identifier for the user that owns the record.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owninguser")]
public Microsoft.Xrm.Sdk.EntityReference OwningUser
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.EntityReference>("owninguser");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("OwningUser");
this.SetAttributeValue("owninguser", value);
this.OnPropertyChanged("OwningUser");
}
}
/// <summary>
/// Status of the Work Template
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statecode")]
public System.Nullable<DLaB.Xrm.Entities.msdyn_workhourtemplateState> StateCode
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
Microsoft.Xrm.Sdk.OptionSetValue optionSet = this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>("statecode");
if ((optionSet != null))
{
return ((DLaB.Xrm.Entities.msdyn_workhourtemplateState)(System.Enum.ToObject(typeof(DLaB.Xrm.Entities.msdyn_workhourtemplateState), optionSet.Value)));
}
else
{
return null;
}
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("StateCode");
if ((value == null))
{
this.SetAttributeValue("statecode", null);
}
else
{
this.SetAttributeValue("statecode", new Microsoft.Xrm.Sdk.OptionSetValue(((int)(value))));
}
this.OnPropertyChanged("StateCode");
}
}
/// <summary>
/// Reason for the status of the Work Template
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statuscode")]
public Microsoft.Xrm.Sdk.OptionSetValue StatusCode
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<Microsoft.Xrm.Sdk.OptionSetValue>("statuscode");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("StatusCode");
this.SetAttributeValue("statuscode", value);
this.OnPropertyChanged("StatusCode");
}
}
/// <summary>
/// For internal use only.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("timezoneruleversionnumber")]
public System.Nullable<int> TimeZoneRuleVersionNumber
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<int>>("timezoneruleversionnumber");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("TimeZoneRuleVersionNumber");
this.SetAttributeValue("timezoneruleversionnumber", value);
this.OnPropertyChanged("TimeZoneRuleVersionNumber");
}
}
/// <summary>
/// Time zone code that was in use when the record was created.
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("utcconversiontimezonecode")]
public System.Nullable<int> UTCConversionTimeZoneCode
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<int>>("utcconversiontimezonecode");
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("UTCConversionTimeZoneCode");
this.SetAttributeValue("utcconversiontimezonecode", value);
this.OnPropertyChanged("UTCConversionTimeZoneCode");
}
}
/// <summary>
/// Version Number
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("versionnumber")]
public System.Nullable<long> VersionNumber
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetAttributeValue<System.Nullable<long>>("versionnumber");
}
}
/// <summary>
/// 1:N msdyn_msdyn_workhourtemplate_msdyn_project_workhourtemplate
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_msdyn_workhourtemplate_msdyn_project_workhourtemplate")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.msdyn_project> msdyn_msdyn_workhourtemplate_msdyn_project_workhourtemplate
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.msdyn_project>("msdyn_msdyn_workhourtemplate_msdyn_project_workhourtemplate", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_msdyn_workhourtemplate_msdyn_project_workhourtemplate");
this.SetRelatedEntities<DLaB.Xrm.Entities.msdyn_project>("msdyn_msdyn_workhourtemplate_msdyn_project_workhourtemplate", null, value);
this.OnPropertyChanged("msdyn_msdyn_workhourtemplate_msdyn_project_workhourtemplate");
}
}
/// <summary>
/// 1:N msdyn_msdyn_workhourtemplate_msdyn_projectparameter_defaultWorkTemplate
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_msdyn_workhourtemplate_msdyn_projectparameter_defaultWorkTemplate")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.msdyn_projectparameter> msdyn_msdyn_workhourtemplate_msdyn_projectparameter_defaultWorkTemplate
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.msdyn_projectparameter>("msdyn_msdyn_workhourtemplate_msdyn_projectparameter_defaultWorkTemplate", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_msdyn_workhourtemplate_msdyn_projectparameter_defaultWorkTemplate");
this.SetRelatedEntities<DLaB.Xrm.Entities.msdyn_projectparameter>("msdyn_msdyn_workhourtemplate_msdyn_projectparameter_defaultWorkTemplate", null, value);
this.OnPropertyChanged("msdyn_msdyn_workhourtemplate_msdyn_projectparameter_defaultWorkTemplate");
}
}
/// <summary>
/// 1:N msdyn_msdyn_workhourtemplate_msdyn_projectteam_worktemplate
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_msdyn_workhourtemplate_msdyn_projectteam_worktemplate")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.msdyn_projectteam> msdyn_msdyn_workhourtemplate_msdyn_projectteam_worktemplate
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.msdyn_projectteam>("msdyn_msdyn_workhourtemplate_msdyn_projectteam_worktemplate", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_msdyn_workhourtemplate_msdyn_projectteam_worktemplate");
this.SetRelatedEntities<DLaB.Xrm.Entities.msdyn_projectteam>("msdyn_msdyn_workhourtemplate_msdyn_projectteam_worktemplate", null, value);
this.OnPropertyChanged("msdyn_msdyn_workhourtemplate_msdyn_projectteam_worktemplate");
}
}
/// <summary>
/// 1:N msdyn_workhourtemplate_Annotations
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_workhourtemplate_Annotations")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.Annotation> msdyn_workhourtemplate_Annotations
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.Annotation>("msdyn_workhourtemplate_Annotations", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplate_Annotations");
this.SetRelatedEntities<DLaB.Xrm.Entities.Annotation>("msdyn_workhourtemplate_Annotations", null, value);
this.OnPropertyChanged("msdyn_workhourtemplate_Annotations");
}
}
/// <summary>
/// 1:N msdyn_workhourtemplate_AsyncOperations
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_workhourtemplate_AsyncOperations")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.AsyncOperation> msdyn_workhourtemplate_AsyncOperations
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.AsyncOperation>("msdyn_workhourtemplate_AsyncOperations", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplate_AsyncOperations");
this.SetRelatedEntities<DLaB.Xrm.Entities.AsyncOperation>("msdyn_workhourtemplate_AsyncOperations", null, value);
this.OnPropertyChanged("msdyn_workhourtemplate_AsyncOperations");
}
}
/// <summary>
/// 1:N msdyn_workhourtemplate_BulkDeleteFailures
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_workhourtemplate_BulkDeleteFailures")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.BulkDeleteFailure> msdyn_workhourtemplate_BulkDeleteFailures
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.BulkDeleteFailure>("msdyn_workhourtemplate_BulkDeleteFailures", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplate_BulkDeleteFailures");
this.SetRelatedEntities<DLaB.Xrm.Entities.BulkDeleteFailure>("msdyn_workhourtemplate_BulkDeleteFailures", null, value);
this.OnPropertyChanged("msdyn_workhourtemplate_BulkDeleteFailures");
}
}
/// <summary>
/// 1:N msdyn_workhourtemplate_DuplicateBaseRecord
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_workhourtemplate_DuplicateBaseRecord")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.DuplicateRecord> msdyn_workhourtemplate_DuplicateBaseRecord
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.DuplicateRecord>("msdyn_workhourtemplate_DuplicateBaseRecord", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplate_DuplicateBaseRecord");
this.SetRelatedEntities<DLaB.Xrm.Entities.DuplicateRecord>("msdyn_workhourtemplate_DuplicateBaseRecord", null, value);
this.OnPropertyChanged("msdyn_workhourtemplate_DuplicateBaseRecord");
}
}
/// <summary>
/// 1:N msdyn_workhourtemplate_DuplicateMatchingRecord
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_workhourtemplate_DuplicateMatchingRecord")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.DuplicateRecord> msdyn_workhourtemplate_DuplicateMatchingRecord
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.DuplicateRecord>("msdyn_workhourtemplate_DuplicateMatchingRecord", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplate_DuplicateMatchingRecord");
this.SetRelatedEntities<DLaB.Xrm.Entities.DuplicateRecord>("msdyn_workhourtemplate_DuplicateMatchingRecord", null, value);
this.OnPropertyChanged("msdyn_workhourtemplate_DuplicateMatchingRecord");
}
}
/// <summary>
/// 1:N msdyn_workhourtemplate_MailboxTrackingFolders
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_workhourtemplate_MailboxTrackingFolders")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.MailboxTrackingFolder> msdyn_workhourtemplate_MailboxTrackingFolders
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.MailboxTrackingFolder>("msdyn_workhourtemplate_MailboxTrackingFolders", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplate_MailboxTrackingFolders");
this.SetRelatedEntities<DLaB.Xrm.Entities.MailboxTrackingFolder>("msdyn_workhourtemplate_MailboxTrackingFolders", null, value);
this.OnPropertyChanged("msdyn_workhourtemplate_MailboxTrackingFolders");
}
}
/// <summary>
/// 1:N msdyn_workhourtemplate_msdyn_resourcerequirement_workhourtemplate
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_workhourtemplate_msdyn_resourcerequirement_workhourtemplate")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.msdyn_resourcerequirement> msdyn_workhourtemplate_msdyn_resourcerequirement_workhourtemplate
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.msdyn_resourcerequirement>("msdyn_workhourtemplate_msdyn_resourcerequirement_workhourtemplate", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplate_msdyn_resourcerequirement_workhourtemplate");
this.SetRelatedEntities<DLaB.Xrm.Entities.msdyn_resourcerequirement>("msdyn_workhourtemplate_msdyn_resourcerequirement_workhourtemplate", null, value);
this.OnPropertyChanged("msdyn_workhourtemplate_msdyn_resourcerequirement_workhourtemplate");
}
}
/// <summary>
/// 1:N msdyn_workhourtemplate_PrincipalObjectAttributeAccesses
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_workhourtemplate_PrincipalObjectAttributeAccesses")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.PrincipalObjectAttributeAccess> msdyn_workhourtemplate_PrincipalObjectAttributeAccesses
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.PrincipalObjectAttributeAccess>("msdyn_workhourtemplate_PrincipalObjectAttributeAccesses", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplate_PrincipalObjectAttributeAccesses");
this.SetRelatedEntities<DLaB.Xrm.Entities.PrincipalObjectAttributeAccess>("msdyn_workhourtemplate_PrincipalObjectAttributeAccesses", null, value);
this.OnPropertyChanged("msdyn_workhourtemplate_PrincipalObjectAttributeAccesses");
}
}
/// <summary>
/// 1:N msdyn_workhourtemplate_ProcessSession
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_workhourtemplate_ProcessSession")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.ProcessSession> msdyn_workhourtemplate_ProcessSession
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.ProcessSession>("msdyn_workhourtemplate_ProcessSession", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplate_ProcessSession");
this.SetRelatedEntities<DLaB.Xrm.Entities.ProcessSession>("msdyn_workhourtemplate_ProcessSession", null, value);
this.OnPropertyChanged("msdyn_workhourtemplate_ProcessSession");
}
}
/// <summary>
/// 1:N msdyn_workhourtemplate_SyncErrors
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_workhourtemplate_SyncErrors")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.SyncError> msdyn_workhourtemplate_SyncErrors
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.SyncError>("msdyn_workhourtemplate_SyncErrors", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplate_SyncErrors");
this.SetRelatedEntities<DLaB.Xrm.Entities.SyncError>("msdyn_workhourtemplate_SyncErrors", null, value);
this.OnPropertyChanged("msdyn_workhourtemplate_SyncErrors");
}
}
/// <summary>
/// 1:N msdyn_workhourtemplate_UserEntityInstanceDatas
/// </summary>
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_workhourtemplate_UserEntityInstanceDatas")]
public System.Collections.Generic.IEnumerable<DLaB.Xrm.Entities.UserEntityInstanceData> msdyn_workhourtemplate_UserEntityInstanceDatas
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntities<DLaB.Xrm.Entities.UserEntityInstanceData>("msdyn_workhourtemplate_UserEntityInstanceDatas", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_workhourtemplate_UserEntityInstanceDatas");
this.SetRelatedEntities<DLaB.Xrm.Entities.UserEntityInstanceData>("msdyn_workhourtemplate_UserEntityInstanceDatas", null, value);
this.OnPropertyChanged("msdyn_workhourtemplate_UserEntityInstanceDatas");
}
}
/// <summary>
/// N:1 business_unit_msdyn_workhourtemplate
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owningbusinessunit")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("business_unit_msdyn_workhourtemplate")]
public DLaB.Xrm.Entities.BusinessUnit business_unit_msdyn_workhourtemplate
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<DLaB.Xrm.Entities.BusinessUnit>("business_unit_msdyn_workhourtemplate", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("business_unit_msdyn_workhourtemplate");
this.SetRelatedEntity<DLaB.Xrm.Entities.BusinessUnit>("business_unit_msdyn_workhourtemplate", null, value);
this.OnPropertyChanged("business_unit_msdyn_workhourtemplate");
}
}
/// <summary>
/// N:1 lk_msdyn_workhourtemplate_createdby
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_msdyn_workhourtemplate_createdby")]
public DLaB.Xrm.Entities.SystemUser lk_msdyn_workhourtemplate_createdby
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_workhourtemplate_createdby", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("lk_msdyn_workhourtemplate_createdby");
this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_workhourtemplate_createdby", null, value);
this.OnPropertyChanged("lk_msdyn_workhourtemplate_createdby");
}
}
/// <summary>
/// N:1 lk_msdyn_workhourtemplate_createdonbehalfby
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_msdyn_workhourtemplate_createdonbehalfby")]
public DLaB.Xrm.Entities.SystemUser lk_msdyn_workhourtemplate_createdonbehalfby
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_workhourtemplate_createdonbehalfby", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("lk_msdyn_workhourtemplate_createdonbehalfby");
this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_workhourtemplate_createdonbehalfby", null, value);
this.OnPropertyChanged("lk_msdyn_workhourtemplate_createdonbehalfby");
}
}
/// <summary>
/// N:1 lk_msdyn_workhourtemplate_modifiedby
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_msdyn_workhourtemplate_modifiedby")]
public DLaB.Xrm.Entities.SystemUser lk_msdyn_workhourtemplate_modifiedby
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_workhourtemplate_modifiedby", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("lk_msdyn_workhourtemplate_modifiedby");
this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_workhourtemplate_modifiedby", null, value);
this.OnPropertyChanged("lk_msdyn_workhourtemplate_modifiedby");
}
}
/// <summary>
/// N:1 lk_msdyn_workhourtemplate_modifiedonbehalfby
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("lk_msdyn_workhourtemplate_modifiedonbehalfby")]
public DLaB.Xrm.Entities.SystemUser lk_msdyn_workhourtemplate_modifiedonbehalfby
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_workhourtemplate_modifiedonbehalfby", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("lk_msdyn_workhourtemplate_modifiedonbehalfby");
this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("lk_msdyn_workhourtemplate_modifiedonbehalfby", null, value);
this.OnPropertyChanged("lk_msdyn_workhourtemplate_modifiedonbehalfby");
}
}
/// <summary>
/// N:1 msdyn_bookableresource_msdyn_workhourtemplate_bookableresourceid
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("msdyn_bookableresourceid")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("msdyn_bookableresource_msdyn_workhourtemplate_bookableresourceid")]
public DLaB.Xrm.Entities.BookableResource msdyn_bookableresource_msdyn_workhourtemplate_bookableresourceid
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<DLaB.Xrm.Entities.BookableResource>("msdyn_bookableresource_msdyn_workhourtemplate_bookableresourceid", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("msdyn_bookableresource_msdyn_workhourtemplate_bookableresourceid");
this.SetRelatedEntity<DLaB.Xrm.Entities.BookableResource>("msdyn_bookableresource_msdyn_workhourtemplate_bookableresourceid", null, value);
this.OnPropertyChanged("msdyn_bookableresource_msdyn_workhourtemplate_bookableresourceid");
}
}
/// <summary>
/// N:1 team_msdyn_workhourtemplate
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owningteam")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("team_msdyn_workhourtemplate")]
public DLaB.Xrm.Entities.Team team_msdyn_workhourtemplate
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<DLaB.Xrm.Entities.Team>("team_msdyn_workhourtemplate", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("team_msdyn_workhourtemplate");
this.SetRelatedEntity<DLaB.Xrm.Entities.Team>("team_msdyn_workhourtemplate", null, value);
this.OnPropertyChanged("team_msdyn_workhourtemplate");
}
}
/// <summary>
/// N:1 user_msdyn_workhourtemplate
/// </summary>
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("owninguser")]
[Microsoft.Xrm.Sdk.RelationshipSchemaNameAttribute("user_msdyn_workhourtemplate")]
public DLaB.Xrm.Entities.SystemUser user_msdyn_workhourtemplate
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return this.GetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("user_msdyn_workhourtemplate", null);
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
this.OnPropertyChanging("user_msdyn_workhourtemplate");
this.SetRelatedEntity<DLaB.Xrm.Entities.SystemUser>("user_msdyn_workhourtemplate", null, value);
this.OnPropertyChanged("user_msdyn_workhourtemplate");
}
}
/// <summary>
/// Constructor for populating via LINQ queries given a LINQ anonymous type
/// <param name="anonymousType">LINQ anonymous type.</param>
/// </summary>
[System.Diagnostics.DebuggerNonUserCode()]
public msdyn_workhourtemplate(object anonymousType) :
this()
{
foreach (var p in anonymousType.GetType().GetProperties())
{
var value = p.GetValue(anonymousType, null);
var name = p.Name.ToLower();
if (name.EndsWith("enum") && value.GetType().BaseType == typeof(System.Enum))
{
value = new Microsoft.Xrm.Sdk.OptionSetValue((int) value);
name = name.Remove(name.Length - "enum".Length);
}
switch (name)
{
case "id":
base.Id = (System.Guid)value;
Attributes["msdyn_workhourtemplateid"] = base.Id;
break;
case "msdyn_workhourtemplateid":
var id = (System.Nullable<System.Guid>) value;
if(id == null){ continue; }
base.Id = id.Value;
Attributes[name] = base.Id;
break;
case "formattedvalues":
// Add Support for FormattedValues
FormattedValues.AddRange((Microsoft.Xrm.Sdk.FormattedValueCollection)value);
break;
default:
Attributes[name] = value;
break;
}
}
}
[Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("statuscode")]
public virtual msdyn_workhourtemplate_StatusCode? StatusCodeEnum
{
[System.Diagnostics.DebuggerNonUserCode()]
get
{
return ((msdyn_workhourtemplate_StatusCode?)(EntityOptionSetEnum.GetEnum(this, "statuscode")));
}
[System.Diagnostics.DebuggerNonUserCode()]
set
{
StatusCode = value.HasValue ? new Microsoft.Xrm.Sdk.OptionSetValue((int)value) : null;
}
}
}
}
| 2,364
|
https://github.com/studydheena/tradeapp/blob/master/libraries/book/src/test/java/com/paritytrading/parity/book/MarketEvents.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
tradeapp
|
studydheena
|
Java
|
Code
| 242
| 500
|
/*
* Copyright 2014 Parity 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.
*/
package com.paritytrading.parity.book;
import java.util.ArrayList;
import java.util.List;
class MarketEvents implements MarketListener {
private List<Event> events;
public MarketEvents() {
this.events = new ArrayList<>();
}
public List<Event> collect() {
return events;
}
@Override
public void update(OrderBook book, boolean bbo) {
events.add(new Update(book.getInstrument(), bbo));
}
@Override
public void trade(OrderBook book, Side side, long price, long size) {
events.add(new Trade(book.getInstrument(), side, price, size));
}
public interface Event {
}
public static class Update extends Value implements Event {
public final long instrument;
public final boolean bbo;
public Update(long instrument, boolean bbo) {
this.instrument = instrument;
this.bbo = bbo;
}
}
public static class Trade extends Value implements Event {
public final long instrument;
public final Side side;
public final long price;
public final long size;
public Trade(long instrument, Side side, long price, long size) {
this.instrument = instrument;
this.side = side;
this.price = price;
this.size = size;
}
}
}
| 32,603
|
https://github.com/SteveWaweru/mfl_admin_web/blob/master/src/app/facility_mgmt/tests/controllers/regulate.spec.js
|
Github Open Source
|
Open Source
|
MIT, Unlicense, OFL-1.1
| 2,022
|
mfl_admin_web
|
SteveWaweru
|
JavaScript
|
Code
| 414
| 2,166
|
(function () {
"use strict";
describe("Test facility regulation controllers", function () {
var rootScope, ctrl, httpBackend, server_url, log, state;
beforeEach(function () {
module("mflAdminAppConfig");
module("mfl.auth.services");
module("mfl.facility_mgmt.controllers");
inject(["$controller", "$rootScope", "$httpBackend", "SERVER_URL", "$log", "$state",
function (c, r, h, s, lg, st) {
ctrl = function (name, data) {
return c("mfl.facility_mgmt.controllers."+name, data);
};
rootScope = r;
httpBackend = h;
server_url = s;
log = lg;
state = st;
spyOn(state, "go");
spyOn(log, "error");
}
]);
});
describe("test regulation list", function () {
it("should load", function () {
var scope = rootScope.$new();
ctrl("facilities_regulation", {"$scope": scope});
expect(scope.filters.regulated).toEqual(false);
});
});
describe("test regulate detail", function () {
beforeEach(function () {
httpBackend
.expectGET(server_url+"api/facilities/facilities/3/")
.respond(200, {
latest_update: 3
});
httpBackend
.expectGET(server_url+"api/facilities/regulation_status/?ordering=name")
.respond(200, {
results: []
});
});
it("should show error on fail to load facility details", function () {
var data = {
"$scope": rootScope.$new(),
"$stateParams": {
facility_id: 3
},
"$log": log
};
httpBackend.resetExpectations();
httpBackend
.expectGET(server_url+"api/facilities/facilities/3/")
.respond(400, {});
httpBackend
.expectGET(server_url+"api/facilities/regulation_status/?ordering=name")
.respond(500);
ctrl("facility_regulate", data);
httpBackend.flush();
httpBackend.verifyNoOutstandingRequest();
httpBackend.verifyNoOutstandingExpectation();
expect(data.$scope.facility).toBe(undefined);
expect(data.$scope.regulation_status).toBe(undefined);
expect(log.error).toHaveBeenCalled();
});
it("should regulate a facility", function () {
var data = {
"$scope": rootScope.$new(),
"$state": state,
"$stateParams": {facility_id: 3}
};
ctrl("facility_regulate", data);
httpBackend.flush();
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
httpBackend.resetExpectations();
httpBackend
.expectPOST(server_url+"api/facilities/facility_regulation_status/")
.respond(200);
data.$scope.regulateFacility();
httpBackend.flush();
httpBackend.verifyNoOutstandingRequest();
httpBackend.verifyNoOutstandingExpectation();
expect(state.go).toHaveBeenCalled();
});
it("should show eror on fail to regulate a facility", function () {
var data = {
"$scope": rootScope.$new(),
"$state": state,
"$stateParams": {facility_id: 3},
"$log": log
};
ctrl("facility_regulate", data);
httpBackend.flush();
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
httpBackend.resetExpectations();
httpBackend
.expectPOST(server_url+"api/facilities/facility_regulation_status/")
.respond(500);
data.$scope.regulateFacility();
httpBackend.flush();
httpBackend.verifyNoOutstandingRequest();
httpBackend.verifyNoOutstandingExpectation();
expect(state.go).not.toHaveBeenCalled();
expect(log.error).toHaveBeenCalled();
});
});
describe("test regulator sync update", function () {
it("should load the sync object", function () {
httpBackend.expectGET(
server_url+"api/facilities/regulator_sync/431/?fields=" +
"name,registration_number,"+
"regulatory_body_name,owner_name,facility_type_name,"+
"probable_matches,mfl_code"
).respond(200, {});
var scope = rootScope.$new();
ctrl("regulator_sync.update", {
"$scope": scope,
"$stateParams": {"sync_id": "431"}
});
httpBackend.flush();
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
expect(scope.sync_obj).toEqual({});
});
it("should handle failure to load the sync object", function () {
httpBackend.expectGET(
server_url+"api/facilities/regulator_sync/431/?fields=" +
"name,registration_number,"+
"regulatory_body_name,owner_name,facility_type_name,"+
"probable_matches,mfl_code"
).respond(500, {});
var scope = rootScope.$new();
ctrl("regulator_sync.update", {
"$scope": scope,
"$stateParams": {"sync_id": "431"}
});
httpBackend.flush();
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
expect(scope.sync_obj).toBe(undefined);
});
it("should update the sync object", function () {
httpBackend.expectGET(
server_url+"api/facilities/regulator_sync/431/?fields=" +
"name,registration_number,"+
"regulatory_body_name,owner_name,facility_type_name,"+
"probable_matches,mfl_code"
).respond(200, {});
var scope = rootScope.$new();
ctrl("regulator_sync.update", {
"$scope": scope,
"$stateParams": {"sync_id": "431"},
"$state": state
});
httpBackend.flush();
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
httpBackend.resetExpectations();
httpBackend
.expectPOST(
server_url+"api/facilities/regulator_sync_update/431/",
{"mfl_code": 783}
)
.respond(200, {});
scope.updateSyncObject(783);
httpBackend.flush();
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
expect(state.go).toHaveBeenCalledWith("facilities_regulator_sync");
});
it("should handle failure to update the sync object", function () {
httpBackend.expectGET(
server_url+"api/facilities/regulator_sync/431/?fields=" +
"name,registration_number,"+
"regulatory_body_name,owner_name,facility_type_name,"+
"probable_matches,mfl_code"
).respond(200, {});
var scope = rootScope.$new();
ctrl("regulator_sync.update", {
"$scope": scope,
"$stateParams": {"sync_id": "431"},
"$state": state
});
httpBackend.flush();
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
httpBackend.resetExpectations();
httpBackend
.expectPOST(
server_url+"api/facilities/regulator_sync_update/431/",
{"mfl_code": 783}
)
.respond(500, {});
scope.updateSyncObject(783);
httpBackend.flush();
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
expect(state.go).not.toHaveBeenCalledWith("facilities_regulator_sync");
});
});
});
})();
| 2,223
|
https://github.com/MTES-MCT/trackdechets-dasri-proto/blob/master/back/src/dasris/resolvers/mutations/createDraftBsdasri.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
trackdechets-dasri-proto
|
MTES-MCT
|
TypeScript
|
Code
| 40
| 146
|
import {
MutationCreateBsdasriArgs,
ResolversParentTypes
} from "../../../generated/graphql/types";
import { GraphQLContext } from "../../../types";
import createBsdasri from "./create";
const createDraftBsdasriResolver = async (
parent: ResolversParentTypes["Mutation"],
bsdasriCreateInput: MutationCreateBsdasriArgs,
context: GraphQLContext
) => {
return createBsdasri(parent, bsdasriCreateInput, context, true);
};
export default createDraftBsdasriResolver;
| 50,499
|
https://github.com/xiayuu/chord/blob/master/chord/test.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
chord
|
xiayuu
|
Python
|
Code
| 40
| 160
|
#!/usr/bin/env python
# encoding: utf-8
from hashlib import sha1
from rpcudp.rpcserver import RPCServer, rpccall
RING_SIZE = 4
class ChordProtocol(RPCServer):
@rpccall
def rdict(self, dest):
pass
@rpccall
def find_successor(self, dest, ident):
pass
def rpc_rdict(self):
return self.dict()
node = ChordProtocol()
print(node.find_successor(('192.168.1.4', 9001), 10))
| 17,059
|
https://github.com/SergeWilfried/rave-android/blob/master/rave_presentation/src/main/java/com/flutterwave/raveandroid/rave_presentation/RavePayManager.java
|
Github Open Source
|
Open Source
|
Unlicense
| 2,019
|
rave-android
|
SergeWilfried
|
Java
|
Code
| 247
| 597
|
package com.flutterwave.raveandroid.rave_presentation;
abstract public class RavePayManager {
protected String email;
protected double amount = -1;
protected String publicKey;
protected String encryptionKey;
protected String txRef;
protected String narration = "";
protected String currency = "NGN";
protected String country = "NG";
protected String fName = "";
protected String lName = "";
protected String meta = "";
protected String subAccounts = "";
protected String payment_plan;
protected boolean isPreAuth = false;
protected String phoneNumber = "";
protected boolean showStagingLabel = true;
protected boolean displayFee = true;
protected boolean staging = true;
protected boolean isPermanent = false;
protected int duration = 0;
protected int frequency = 0;
public abstract RavePayManager initialize();
public String getEmail() {
return email;
}
public double getAmount() {
return amount;
}
public String getPublicKey() {
return publicKey;
}
public String getEncryptionKey() {
return encryptionKey;
}
public String getTxRef() {
return txRef;
}
public String getNarration() {
return narration;
}
public String getCurrency() {
return currency;
}
public String getCountry() {
return country;
}
public String getfName() {
return fName;
}
public String getlName() {
return lName;
}
public String getMeta() {
return meta;
}
public String getSubAccounts() {
return subAccounts;
}
public String getPayment_plan() {
return payment_plan;
}
public boolean isPreAuth() {
return isPreAuth;
}
public String getPhoneNumber() {
return phoneNumber;
}
public boolean isDisplayFee() {
return displayFee;
}
public boolean isStaging() {
return staging;
}
public boolean isPermanent() {
return isPermanent;
}
public int getDuration() {
return duration;
}
public int getFrequency() {
return frequency;
}
}
| 4,590
|
https://github.com/irmoralesb/SVG/blob/master/Source/SvgDocument.Drawing.cs
|
Github Open Source
|
Open Source
|
MS-PL
| 2,022
|
SVG
|
irmoralesb
|
C#
|
Code
| 884
| 2,313
|
#if !NO_SDC
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml;
using Svg.Exceptions;
namespace Svg
{
public partial class SvgDocument : SvgFragment, ITypeDescriptorContext
{
/// <summary>
/// Skip check whether the GDI+ can be loaded.
/// </summary>
/// <remarks>
/// Set to true on systems that do not support GDI+ like UWP.
/// </remarks>
public static bool SkipGdiPlusCapabilityCheck { get; set; }
internal SvgFontManager FontManager { get; private set; }
/// <summary>
/// Validate whether the system has GDI+ capabilities (non Windows related).
/// </summary>
/// <returns>Boolean whether the system is capable of using GDI+</returns>
public static bool SystemIsGdiPlusCapable()
{
try
{
EnsureSystemIsGdiPlusCapable();
}
catch (SvgGdiPlusCannotBeLoadedException)
{
return false;
}
catch (Exception)
{
// If somehow another type of exception is raised by the ensure function we will let it bubble up, since that might indicate other issues/problems
throw;
}
return true;
}
/// <summary>
/// Ensure that the running system is GDI capable, if not this will yield a
/// SvgGdiPlusCannotBeLoadedException exception.
/// </summary>
public static void EnsureSystemIsGdiPlusCapable()
{
try
{
using (var matrix = new Matrix(0f, 0f, 0f, 0f, 0f, 0f)) { }
}
// GDI+ loading errors will result in TypeInitializationExceptions,
// for readability we will catch and wrap the error
catch (Exception e)
{
if (ExceptionCaughtIsGdiPlusRelated(e))
{
// Throw only the customized exception if we are sure GDI+ is causing the problem
throw new SvgGdiPlusCannotBeLoadedException(e);
}
// If the Matrix creation is causing another type of exception we should just raise that one
throw;
}
}
/// <summary>
/// Check if the current exception or one of its children is the targeted GDI+ exception.
/// It can be hidden in one of the InnerExceptions, so we need to iterate over them.
/// </summary>
/// <param name="e">The exception to validate against the GDI+ check</param>
private static bool ExceptionCaughtIsGdiPlusRelated(Exception e)
{
var currE = e;
int cnt = 0; // Keep track of depth to prevent endless-loops
while (currE != null && cnt < 10)
{
var typeException = currE as DllNotFoundException;
if (typeException?.Message?.LastIndexOf("libgdiplus", StringComparison.OrdinalIgnoreCase) > -1)
{
return true;
}
currE = currE.InnerException;
cnt++;
}
return false;
}
public static Bitmap OpenAsBitmap(string path)
{
return null;
}
public static Bitmap OpenAsBitmap(XmlDocument document)
{
return null;
}
private void Draw(ISvgRenderer renderer, ISvgBoundable boundable)
{
using (FontManager = new SvgFontManager())
{
renderer.SetBoundable(boundable);
Render(renderer);
FontManager = null;
}
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> to the specified <see cref="ISvgRenderer"/>.
/// </summary>
/// <param name="renderer">The <see cref="ISvgRenderer"/> to render the document with.</param>
/// <exception cref="ArgumentNullException">The <paramref name="renderer"/> parameter cannot be <c>null</c>.</exception>
public void Draw(ISvgRenderer renderer)
{
if (renderer == null)
{
throw new ArgumentNullException("renderer");
}
this.Draw(renderer, this);
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> to the specified <see cref="Graphics"/>.
/// </summary>
/// <param name="graphics">The <see cref="Graphics"/> to be rendered to.</param>
/// <exception cref="ArgumentNullException">The <paramref name="graphics"/> parameter cannot be <c>null</c>.</exception>
public void Draw(Graphics graphics)
{
this.Draw(graphics, null);
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> to the specified <see cref="Graphics"/>.
/// </summary>
/// <param name="graphics">The <see cref="Graphics"/> to be rendered to.</param>
/// <param name="size">The <see cref="SizeF"/> to render the document. If <c>null</c> document is rendered at the default document size.</param>
/// <exception cref="ArgumentNullException">The <paramref name="graphics"/> parameter cannot be <c>null</c>.</exception>
public void Draw(Graphics graphics, SizeF? size)
{
if (graphics == null)
{
throw new ArgumentNullException("graphics");
}
using (var renderer = SvgRenderer.FromGraphics(graphics))
{
var boundable = size.HasValue ? (ISvgBoundable)new GenericBoundable(0, 0, size.Value.Width, size.Value.Height) : this;
this.Draw(renderer, boundable);
}
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> and returns the image as a <see cref="Bitmap"/>.
/// </summary>
/// <returns>A <see cref="Bitmap"/> containing the rendered document.</returns>
public virtual Bitmap Draw()
{
//Trace.TraceInformation("Begin Render");
var size = Size.Round(GetDimensions());
if (size.Width <= 0 || size.Height <= 0)
return null;
Bitmap bitmap = null;
try
{
try
{
bitmap = new Bitmap(size.Width, size.Height);
}
catch (ArgumentException e)
{
// When processing too many files at one the system can run out of memory
throw new SvgMemoryException("Cannot process SVG file, cannot allocate the required memory", e);
}
//bitmap.SetResolution(300, 300);
this.Draw(bitmap);
}
catch
{
bitmap?.Dispose();
throw;
}
//Trace.TraceInformation("End Render");
return bitmap;
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> into a given Bitmap <see cref="Bitmap"/>.
/// </summary>
public virtual void Draw(Bitmap bitmap)
{
//Trace.TraceInformation("Begin Render");
using (var renderer = SvgRenderer.FromImage(bitmap))
{
var boundable = new GenericBoundable(0, 0, bitmap.Width, bitmap.Height);
this.Draw(renderer, boundable);
}
//Trace.TraceInformation("End Render");
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> in given size and returns the image as a <see cref="Bitmap"/>.
/// If one of rasterWidth and rasterHeight is zero, the image is scaled preserving aspect ratio,
/// otherwise the aspect ratio is ignored.
/// </summary>
/// <returns>A <see cref="Bitmap"/> containing the rendered document.</returns>
public virtual Bitmap Draw(int rasterWidth, int rasterHeight)
{
var svgSize = GetDimensions();
var imageSize = svgSize;
this.RasterizeDimensions(ref imageSize, rasterWidth, rasterHeight);
var bitmapSize = Size.Round(imageSize);
if (bitmapSize.Width <= 0 || bitmapSize.Height <= 0)
return null;
Bitmap bitmap = null;
try
{
try
{
bitmap = new Bitmap(bitmapSize.Width, bitmapSize.Height);
}
catch (ArgumentException e)
{
// When processing too many files at one the system can run out of memory
throw new SvgMemoryException("Cannot process SVG file, cannot allocate the required memory", e);
}
using (var renderer = SvgRenderer.FromImage(bitmap))
{
renderer.ScaleTransform(imageSize.Width / svgSize.Width, imageSize.Height / svgSize.Height);
var boundable = new GenericBoundable(0, 0, svgSize.Width, svgSize.Height);
this.Draw(renderer, boundable);
}
}
catch
{
bitmap?.Dispose();
throw;
}
return bitmap;
}
}
}
#endif
| 29,345
|
https://github.com/pshoben/devutils/blob/master/tagwire/EmapiTagwireWrapper.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
devutils
|
pshoben
|
C++
|
Code
| 150
| 559
|
#include <string>
#include <memory>
#include <typeinfo>
#include "MessageDataIf.h"
#include "emapi.h"
#include "EmapiTypes.h"
//#include "MessageTrace.h"
#include "TagwireDecoder.h"
#include "EmapiTagwireWrapper.h"
using std::string;
namespace emapi {
EmapiTagwireWrapper::EmapiTagwireWrapper(){}
//EmapiTagwireWrapper::EmapiTagwireWrapper(ByteArray& pByteArray){}
EmapiTagwireWrapper::~EmapiTagwireWrapper(){}
EmapiTagwireWrapper * EmapiTagwireWrapper::clone() const
{
EmapiTagwireWrapper* tClone = new EmapiTagwireWrapper();
tClone->mMessage = mMessage;
return tClone;
}
void EmapiTagwireWrapper::unpack( TagwireDecoder& pDecoder)
{
mMessage = pDecoder.parseMessage();
}
void EmapiTagwireWrapper::pack( TagwireEncoder& pEncoder) const
{
mMessage->pack(pEncoder);
}
const int EmapiTagwireWrapper::getClassId() const
{
return 0 ; //trick
}
const string EmapiTagwireWrapper::getMessageName() const
{
return "EmapiTagwireWrapper";
}
void EmapiTagwireWrapper::setWrappedMessage( MessageDataIf * pMessage)
{
mMessage = pMessage;
}
MessageDataIf * EmapiTagwireWrapper::getWrappedMessage()
{
return mMessage;
}
const string EmapiTagwireWrapper::to_string( string indent ) const
{
if( mMessage )
return mMessage->to_string( indent );
else
return indent + string("EmapiTagwireWrapper::null");
}
const int EmapiTagwireWrapper::getMessageType() const
{
if( mMessage ) {
return mMessage->getMessageType() ; //trick
} else {
return 1;
}
}
//void EmapiTagwireWrapper::traceMessage( MessageTrace * pTrace, int pLevel) const
//{
// // TODO
//}
}
| 10,617
|
https://github.com/guardian/source/blob/master/packages/@guardian/source-react-components/src/tiles/Tiles.tsx
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
source
|
guardian
|
TSX
|
Code
| 295
| 987
|
import type { SerializedStyles } from '@emotion/react';
import type { EmotionJSX } from '@emotion/react/types/jsx-namespace';
import type { Breakpoint } from '@guardian/source-foundations';
import type { HTMLAttributes } from 'react';
import type { Props } from '../@types/Props';
import {
collapseUntilDesktopTiles,
collapseUntilLeftColTiles,
collapseUntilTabletTiles,
collapseUntilWideTiles,
tileGridColumns,
tilesCollapseUntilDesktop,
tilesCollapseUntilleftCol,
tilesCollapseUntilTablet,
tilesCollapseUntilWide,
tilesGridContainer,
} from './styles';
import type { Columns } from './types';
type GridBreakpoint = Extract<
Breakpoint,
'mobile' | 'tablet' | 'desktop' | 'leftCol' | 'wide'
>;
type CollapseBreakpoint = Extract<
GridBreakpoint,
'tablet' | 'desktop' | 'leftCol' | 'wide'
>;
const collapseUntilMap: { [key in CollapseBreakpoint]: SerializedStyles } = {
tablet: tilesCollapseUntilTablet,
desktop: tilesCollapseUntilDesktop,
leftCol: tilesCollapseUntilleftCol,
wide: tilesCollapseUntilWide,
};
const collapseUntilColumnsMap: {
[key in CollapseBreakpoint]: SerializedStyles;
} = {
tablet: collapseUntilTabletTiles,
desktop: collapseUntilDesktopTiles,
leftCol: collapseUntilLeftColTiles,
wide: collapseUntilWideTiles,
};
export interface TilesProps extends HTMLAttributes<HTMLDivElement>, Props {
/**
* The number of columns you want.
*/
columns: Columns;
/**
* Child components will be stacked in a single column at viewport widths narrower than the
* specified breakpoint (they will always be collapsed into a single column if the viewport is narrower than `mobileLandscape`).
*/
collapseUntil?: CollapseBreakpoint;
/**
* **Deprecated**
*
* Use `collapseUntil` instead.
*
* @deprecated Use `collapseUntil` instead.
*/
collapseBelow?: CollapseBreakpoint;
}
/**
* [Storybook](https://guardian.github.io/source/?path=/docs/packages-source-react-components-tiles) •
* [Design System](https://theguardian.design/2a1e5182b/p/00e9f5-tiles) •
* [GitHub](https://github.com/guardian/source/tree/main/packages/@guardian/source-react-components/src/layout/Tiles.tsx) •
* [NPM](https://www.npmjs.com/package/@guardian/source-react-components)
*
* Child components will be arranged with equal width and spacing with the specified number of columns,
* wrapping onto a new row as necessary.
*
* Until `mobileLandscape`, child components will be collapsed into a single column.
*/
export const Tiles = ({
columns,
collapseBelow, // deprecated
collapseUntil = collapseBelow,
cssOverrides,
children,
...props
}: TilesProps): EmotionJSX.Element => {
return (
<div
css={[
tilesGridContainer,
tileGridColumns[columns],
collapseUntil ? collapseUntilColumnsMap[collapseUntil] : '',
collapseUntil ? collapseUntilMap[collapseUntil] : '',
cssOverrides,
]}
{...props}
>
{children}
</div>
);
};
| 49,622
|
https://github.com/1217720084/EnergyModels.jl/blob/master/test/io.jl
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
EnergyModels.jl
|
1217720084
|
Julia
|
Code
| 30
| 95
|
# Test I/O
module Mock
type MockGenerator <: Component
model::EnergyModel
end
@testset "NetCDF" begin
model = EnergyModel()
MockGenerator(model)
naming(model, :)
defVar()
io = EM.NcIO("test.nc")
@test EM.get(io, :generator) == nothing
end
| 45,402
|
https://github.com/gwonhyeong/tlabs/blob/master/tlab/src/ext/live555/rtsp_client.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
tlabs
|
gwonhyeong
|
C++
|
Code
| 888
| 3,472
|
/**
* @file rtsp_client.cpp
* @author ghtak
* @brief
* @version 0.1
* @date 2019-01-28
*
* @copyright Copyright (c) 2019
*
*/
#include <map>
#include <tlab/ext/live555/rtsp_client.hpp>
#include <tlab/util.hpp>
// check https://github.com/mpromonet
namespace tlab::ext::live555 {
template <typename string_type>
static string_type to_upper(const string_type &msg) {
string_type out;
out.reserve(msg.length());
for (typename string_type::size_type idx = 0; idx < msg.length(); ++idx) {
if (msg[idx] < 0xff && isalpha(msg[idx]) && islower(msg[idx])) {
out.push_back(_toupper(msg[idx]));
} else {
out.push_back(msg[idx]);
}
}
return out;
}
std::map<RTSPClient *, rtsp_client *> _clients;
void rtsp_client::continueAfterDESCRIBE(RTSPClient *rtspClient, int resultCode,
char *resultString) {
rtsp_client *pthis = _clients[rtspClient];
pthis->continueAfterDESCRIBE(resultCode, resultString);
}
void rtsp_client::continueAfterSETUP(RTSPClient *rtspClient, int resultCode,
char *resultString) {
rtsp_client *pthis = _clients[rtspClient];
pthis->continueAfterSETUP(resultCode, resultString);
}
void rtsp_client::continueAfterPLAY(RTSPClient *rtspClient, int resultCode,
char *resultString) {
rtsp_client *pthis = _clients[rtspClient];
pthis->continueAfterPLAY(resultCode, resultString);
}
void rtsp_client::subsessionAfterPlaying(void *clientData) {
MediaSubsession *subsession = (MediaSubsession *)clientData;
rtsp_client *pthis = static_cast<rtsp_client *>(subsession->miscPtr);
pthis->subsessionAfterPlaying(subsession);
}
void rtsp_client::subsessionByeHandler(void *clientData) {
MediaSubsession *subsession = (MediaSubsession *)clientData;
rtsp_client *pthis = static_cast<rtsp_client *>(subsession->miscPtr);
pthis->subsessionByeHandler(subsession);
}
void rtsp_client::handle_timer(void *ctx) {
rtsp_client *c = static_cast<rtsp_client *>(ctx);
c->handle_timer();
}
rtsp_client::rtsp_client(envir_loop &env)
: _envir(env), _session(nullptr), _iter(nullptr), _subsession(nullptr),
_timer_task(nullptr), _stream_using_tcp(false), _flag(0),
_keep_session_time(0), _sps(""), _pps("") {}
rtsp_client::~rtsp_client(void) {}
bool rtsp_client::open(const rtsp_handler_ptr &handler, const std::string &url,
const std::string &user, const std::string &pw,
const bool stream_using_tcp,
const std::size_t keep_session_time) {
_handler_ptr = handler;
_authenticator.setUsernameAndPassword(user.c_str(), pw.c_str());
_stream_using_tcp = stream_using_tcp;
_keep_session_time = keep_session_time;
_client = RTSPClient::createNew(_envir.envir(), url.c_str());
if (_flag.exchange(1) == 0) {
_envir.run([&] {
_clients[_client] = this;
_client->sendDescribeCommand(&rtsp_client::continueAfterDESCRIBE,
&_authenticator);
});
return true;
}
return false;
}
void rtsp_client::close(void) {
if (_flag.exchange(0) == 1) {
_envir.run([this] {
if (_timer_task != nullptr) {
_envir.envir().taskScheduler().unscheduleDelayedTask(
_timer_task);
_timer_task = nullptr;
}
// First, check whether any subsessions have still to be closed:
if (_session != nullptr) {
Boolean someSubsessionsWereActive = False;
MediaSubsessionIterator iter(*_session);
MediaSubsession *subsession;
while ((subsession = iter.next()) != nullptr) {
if (subsession->sink != nullptr) {
Medium::close(subsession->sink);
subsession->sink = nullptr;
if (subsession->rtcpInstance() != nullptr) {
subsession->rtcpInstance()->setByeHandler(nullptr,
nullptr);
}
someSubsessionsWereActive = True;
}
}
if (someSubsessionsWereActive) {
_client->sendTeardownCommand(*_session, nullptr,
&_authenticator);
}
}
if (_iter) {
delete _iter;
}
_iter = nullptr;
if (_session != nullptr) {
Medium::close(_session);
}
_session = nullptr;
_clients.erase(_client);
Medium::close(_client);
delete this;
});
}
}
void rtsp_client::setupNextSubsession(void) {
_subsession = _iter->next();
if (_subsession != NULL) {
if (!_subsession->initiate()) {
// env << *rtspClient << "Failed to initiate the \"" <<
// *scs.subsession << "\" subsession: " << env.getResultMsg() <<
// "\n";
setupNextSubsession(); // give up on this subsession; go to the next
// one
} else {
// env << *rtspClient << "Initiated the \"" << *scs.subsession
// << "\" subsession (client ports " <<
// scs.subsession->clientPortNum() << "-" <<
// scs.subsession->clientPortNum()+1 << ")\n";
// Continue setting up this subsession, by sending a RTSP "SETUP"
// command:
_client->sendSetupCommand(
*_subsession, rtsp_client::continueAfterSETUP, false,
_stream_using_tcp, false, &_authenticator);
}
return;
}
// We've finished setting up all of the subsessions. Now, send a RTSP
// "PLAY" command to start the streaming:
if (_session->absStartTime() != NULL) {
// Special case: The stream is indexed by 'absolute' time, so send an
// appropriate "PLAY" command:
_client->sendPlayCommand(*_session, rtsp_client::continueAfterPLAY,
_session->absStartTime(),
_session->absEndTime(), 1.0f, &_authenticator);
} else {
//_duration = _session->playEndTime() - _session->playStartTime();
_client->sendPlayCommand(*_session, rtsp_client::continueAfterPLAY, 0,
-1.0, 1.0f, &_authenticator);
}
}
void rtsp_client::continueAfterDESCRIBE(int resultCode, char *resultString) {
if (resultCode != 0) {
return;
}
char *const sdpDescription = resultString;
_session = MediaSession::createNew(_envir.envir(), sdpDescription);
if (_session != nullptr) {
parse_sdp(sdpDescription);
_iter = new MediaSubsessionIterator(*_session);
setupNextSubsession();
}
delete[] sdpDescription;
}
void rtsp_client::continueAfterSETUP(int resultCode, char *resultString) {
if (resultCode != 0) {
return;
}
_subsession->sink =
sink::createNew(_envir.envir(), *_subsession, _client->url(),this);
if (_subsession->sink == NULL) {
return;
}
_subsession->miscPtr = this; // a hack to let subsession handle functions
// get the "RTSPClient" from the subsession
_subsession->sink->startPlaying(*(_subsession->readSource()),
rtsp_client::subsessionAfterPlaying,
_subsession);
// Also set a handler to be called if a RTCP "BYE" arrives for this
// subsession:
if (_subsession->rtcpInstance() != NULL) {
_subsession->rtcpInstance()->setByeHandler(subsessionByeHandler,
_subsession);
}
// Set up the next subsession, if any:
setupNextSubsession();
}
void rtsp_client::continueAfterPLAY(int resultCode, char *resultString) {
if (resultCode != 0) {
return;
}
handle_timer();
}
void rtsp_client::handle_timer(void) {
if (_keep_session_time != 0) {
_client->sendOptionsCommand(nullptr, &_authenticator);
_timer_task = _envir.envir().taskScheduler().scheduleDelayedTask(
_keep_session_time * 1000 * 1000, rtsp_client::handle_timer, this);
}
}
void rtsp_client::subsessionAfterPlaying(MediaSubsession *subsession) {
//(*this)(rtsp_events::RTP_SESSION_END, (void
//*)subsession->savedSDPLines());
// Begin by closing this subsession's stream:
Medium::close(subsession->sink);
subsession->sink = NULL;
// Next, check whether *all* subsessions' streams have now been closed:
MediaSession &session = subsession->parentSession();
MediaSubsessionIterator iter(session);
while ((subsession = iter.next()) != NULL) {
if (subsession->sink != NULL)
return; // this subsession is still active
}
//
}
void rtsp_client::subsessionByeHandler(MediaSubsession *subsession) {
//(*this)(rtsp_events::RTP_SESSION_BYE, (void
//*)subsession->savedSDPLines());
subsessionAfterPlaying(subsession);
}
void rtsp_client::parse_sdp(const char *sdp) {
if (std::string(sdp).find("H264") == std::string::npos)
return;
/*
v=0
o=- 946684803590602 1 IN IP4 192.168.1.150
s=Session streamed by "rtspServerForJovision"
i=live0.264
t=0 0
a=tool:LIVE555 Streaming Media v2013.09.18
a=type:broadcast
a=control:*
a=range:npt=0-
a=x-qt-text-nam:Session streamed by "rtspServerForJovision"
a=x-qt-text-inf:live0.264
m=video 0 RTP/AVP 96
c=IN IP4 0.0.0.0
b=AS:3072
a=rtpmap:96 H264/90000
a=fmtp:96
packetization-mode=1;profile-level-id=4D001F;sprop-parameter-sets=Z00AH5WoEsFWQA==,aO48gA==
a=control:track1
m=audio 0 RTP/AVP 97
c=IN IP4 0.0.0.0
b=AS:40
a=rtpmap:97 PCMU/8000
a=control:track2
*/
std::vector<std::string> values;
tlab::split(std::string(sdp), std::string("\r\n"),
std::back_inserter(values));
std::string fmtp = "";
for (const std::string &line : values) {
if (line.find("a=fmtp") != std::string::npos) {
fmtp = line.substr(2, line.length() - 2);
}
}
if (fmtp == "")
return;
values.clear();
split(fmtp, std::string(";"), std::back_inserter(values));
std::string sps_set = "";
std::string sps_key = "sprop-parameter-sets=";
for (const std::string &sps : values) {
if (sps.find(sps_key) != std::string::npos) {
sps_set =
sps.substr(sps_key.length(), sps.length() - sps_key.length());
}
}
if (sps_set == "")
return;
values.clear();
tlab::split(sps_set, std::string(","), std::back_inserter(values));
if (values.size() != 2)
return;
_sps = values[0];
_pps = values[1];
return;
}
} // namespace tlab::ext::live555
| 50,984
|
https://github.com/maskhb/bbbbb/blob/master/src/utils/attr/repair.js
|
Github Open Source
|
Open Source
|
MIT
| null |
bbbbb
|
maskhb
|
JavaScript
|
Code
| 164
| 546
|
/**
* 维修状态
*/
export const repairStatusOptions = [
{
value: 1,
label: '待维修',
},
{
value: 2,
label: '维修完成',
},
{
value: 3,
label: '已取消',
},
];
/**
* 维修类型
*/
export const repairTypeOptions = [
{
value: 1,
label: '防水漏水',
},
{
value: 2,
label: '墙面地面',
},
{
value: 3,
label: '供电照明',
},
{
value: 4,
label: '龙头卫浴',
},
{
value: 5,
label: '门窗维修',
},
{
value: 6,
label: '家具维修',
},
{
value: 7,
label: '家电维修',
},
{
value: 8,
label: '供暖制冷',
},
];
/**
* 维修地点类型
*/
export const repairAreaTypeOptions = [
{
value: 1,
label: '房间',
},
{
value: 2,
label: '公共区域',
},
{
value: 3,
label: '其他',
},
];
/**
* 房间列表
*/
export const roomListOptions = [
{
value: 1,
label: '707',
},
];
/**
* 证件类型
*/
export const IDTypeOptions = [
{
value: 1,
label: '身份证',
},
{
value: 2,
label: '护照',
},
{
value: 3,
label: '军官证',
},
{
value: 4,
label: '回乡证',
},
];
| 48,397
|
https://github.com/subaochen/TetrisMina/blob/master/src/main/java/tetrismina/client/ui/game/Block.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
TetrisMina
|
subaochen
|
Java
|
Code
| 258
| 563
|
package tetrismina.client.ui.game;
public enum Block {
T(3, 2, new byte[][] { { 1, 1, 1 }, { 0, 1, 0 } }), L(2, 3, new byte[][] {
{ 1, 0 }, { 1, 0 }, { 1, 1 } }), I(1, 4, new byte[][] { { 1 },
{ 1 }, { 1 }, { 1 } }), TIAN(2, 2, new byte[][] { { 1, 1 },
{ 1, 1 } }), AL(2, 3, new byte[][] { { 0, 1 }, { 0, 1 }, { 1, 1 } }), YU(
2, 3, new byte[][] { { 1, 0 }, { 1, 1 }, { 0, 1 } }), AYU(2, 3,
new byte[][] { { 0, 1 }, { 1, 1 }, { 1, 0 } });
private int width = 0;
private int height = 0;
private byte[][] position;
Block(int width, int height, byte[][] position) {
this.width = width;
this.height = height;
this.position = position;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public byte[][] getPosition() {
return position;
}
public byte[][] getTransformedPosition() {
byte[][] newPos = new byte[width][height];
for (int i = height - 1; i >= 0; i--) {
for (int j = 0; j < width; j++) {
newPos[j][height - 1 - i] = position[i][j];
}
}
return newPos;
}
public int getTransformedHeight() {
return width;
}
public int getTransformedWidth() {
return height;
}
public void transform() {
byte[][] newPos = getTransformedPosition();
int tmp = height;
height = width;
width = tmp;
position = newPos;
}
}
| 18,659
|
https://github.com/gx1997/chrome-loongson/blob/master/chrome/browser/ui/views/simple_message_box_views.h
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,012
|
chrome-loongson
|
gx1997
|
C++
|
Code
| 249
| 818
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_VIEWS_SIMPLE_MESSAGE_BOX_VIEWS_H_
#define CHROME_BROWSER_UI_VIEWS_SIMPLE_MESSAGE_BOX_VIEWS_H_
#pragma once
#include "base/basictypes.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/window/dialog_delegate.h"
namespace views {
class MessageBoxView;
}
// Simple message box implemented in Views.
class SimpleMessageBoxViews : public views::DialogDelegate,
public MessageLoop::Dispatcher,
public base::RefCounted<SimpleMessageBoxViews> {
public:
static void ShowWarningMessageBox(gfx::NativeWindow parent_window,
const string16& title,
const string16& message);
static bool ShowQuestionMessageBox(gfx::NativeWindow parent_window,
const string16& title,
const string16& message);
// Returns true if the Accept button was clicked.
bool accepted() const { return disposition_ == DISPOSITION_OK; }
private:
friend class base::RefCounted<SimpleMessageBoxViews>;
// The state of the dialog when closing.
enum DispositionType {
DISPOSITION_UNKNOWN,
DISPOSITION_CANCEL,
DISPOSITION_OK
};
enum DialogType {
DIALOG_TYPE_WARNING,
DIALOG_TYPE_QUESTION,
};
// Overridden from views::DialogDelegate:
virtual int GetDialogButtons() const OVERRIDE;
virtual string16 GetDialogButtonLabel(ui::DialogButton button) const OVERRIDE;
virtual bool Cancel() OVERRIDE;
virtual bool Accept() OVERRIDE;
// Overridden from views::WidgetDelegate:
virtual string16 GetWindowTitle() const OVERRIDE;
virtual void DeleteDelegate() OVERRIDE;
virtual ui::ModalType GetModalType() const OVERRIDE;
virtual views::View* GetContentsView() OVERRIDE;
virtual views::Widget* GetWidget() OVERRIDE;
virtual const views::Widget* GetWidget() const OVERRIDE;
SimpleMessageBoxViews(gfx::NativeWindow parent_window,
DialogType dialog_type,
const string16& title,
const string16& message);
virtual ~SimpleMessageBoxViews();
// MessageLoop::Dispatcher implementation.
// Dispatcher method. This returns true if the menu was canceled, or
// if the message is such that the menu should be closed.
virtual bool Dispatch(const base::NativeEvent& event) OVERRIDE;
const DialogType dialog_type_;
DispositionType disposition_;
const string16 window_title_;
views::MessageBoxView* message_box_view_;
DISALLOW_COPY_AND_ASSIGN(SimpleMessageBoxViews);
};
#endif // CHROME_BROWSER_UI_VIEWS_SIMPLE_MESSAGE_BOX_VIEWS_H_
| 651
|
https://github.com/firstsano/prikormka/blob/master/frontend/modules/cab/controllers/OrderController.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
prikormka
|
firstsano
|
PHP
|
Code
| 294
| 1,068
|
<?php
namespace frontend\modules\cab\controllers;
use Yii;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\web\BadRequestHttpException;
use frontend\models\OrderForm;
use common\models\Order;
use yii\filters\AccessControl;
use yii\data\Pagination;
class OrderController extends Controller
{
const ORDERS_PER_PAGE = 10;
/**
* @var string
*/
public $defaultAction = 'new';
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'create' => ['post'],
],
],
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@']
]
]
]
];
}
/**
* @inheritdoc
*/
public function actionIndex()
{
$query = Order::find()
->orderBy(['created_at' => SORT_DESC])
->where(['user_id' => Yii::$app->user->identity->id]);
$count = $query->count();
$pagination = new Pagination([
'totalCount' => $count,
'pageSize' => self::ORDERS_PER_PAGE
]);
$orders = $query->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('index', [
'orders' => $orders,
'pagination' => $pagination
]);
}
/**
* @inheritdoc
*/
public function actionView($id)
{
$order = Order::findOne([
'user_id' => Yii::$app->user->identity,
'id' => $id
]);
if (!$order) {
throw new NotFoundHttpException();
}
return $this->render('view', [
'model' => $order
]);
}
/**
* @inheritdoc
*/
public function actionNew()
{
$model = new OrderForm();
$user = Yii::$app->user->identity;
$model->setAttributes([
'name' => $user->publicIdentity,
'phone' => $user->userProfile->phone,
'address' => $user->userProfile->address,
'email' => $user->email
]);
return $this->render('new', $this->orderFormParams([
'model' => $model,
]));
}
/**
* @inheritdoc
*/
public function actionCreate()
{
$app = Yii::$app;
$cart = $app->cart;
$model = new OrderForm();
if (!$model->load($app->request->post())) {
throw new BadRequestHttpException();
}
$orderCreated = $model->createOrder([
'total' => $cart->cost,
'user' => ['id' => $app->user->identity->id],
'products' => $cart->positionsWithQuantities
]);
if ($orderCreated === false) {
$app->session->setFlash('alert', [
'type' => 'warning',
'title' => Yii::t('frontend/site', 'order-activate.title'),
'message' => Yii::t('frontend/site', 'order-activate-error.message'),
]);
return $this->render('new', $this->orderFormParams([
'model' => $model,
]));
}
$cart->removeAll();
return $this->redirect(['order/view', 'id' => $orderCreated->id]);
}
/**
* @inheritdoc
*/
protected function orderFormParams($params = [])
{
return ArrayHelper::merge([
'products' => Yii::$app->cart->positions,
], $params);
}
}
| 4,815
|
https://github.com/ufabdyop/coralapiserver/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
coralapiserver
|
ufabdyop
|
Ignore List
|
Code
| 24
| 50
|
# Eclipse generated directories
.classpath
.project
.settings
# Maven generated files
target
# Temporary files or swap files generated by Vim
*~
*.swp
*.swo
| 16,261
|
https://github.com/reiform/celix/blob/master/libs/framework/src/bundle_archive.c
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
celix
|
reiform
|
C
|
Code
| 2,257
| 8,410
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include "celix_utils_api.h"
#include "bundle_archive.h"
#include "linked_list_iterator.h"
struct bundleArchive {
long id;
char * location;
DIR *archiveRootDir;
char * archiveRoot;
linked_list_pt revisions;
long refreshCount;
time_t lastModified;
bundle_state_e persistentState;
};
static celix_status_t bundleArchive_getRevisionLocation(bundle_archive_pt archive, long revNr, char **revision_location);
static celix_status_t bundleArchive_setRevisionLocation(bundle_archive_pt archive, const char * location, long revNr);
static celix_status_t bundleArchive_initialize(bundle_archive_pt archive);
static celix_status_t bundleArchive_deleteTree(bundle_archive_pt archive, const char * directory);
static celix_status_t bundleArchive_createRevisionFromLocation(bundle_archive_pt archive, const char *location, const char *inputFile, long revNr, bundle_revision_pt *bundle_revision);
static celix_status_t bundleArchive_reviseInternal(bundle_archive_pt archive, bool isReload, long revNr, const char * location, const char *inputFile);
static celix_status_t bundleArchive_readLastModified(bundle_archive_pt archive, time_t *time);
static celix_status_t bundleArchive_writeLastModified(bundle_archive_pt archive);
celix_status_t bundleArchive_createSystemBundleArchive(bundle_archive_pt *bundle_archive) {
celix_status_t status = CELIX_SUCCESS;
char *error = NULL;
bundle_archive_pt archive = NULL;
if (*bundle_archive != NULL) {
status = CELIX_ILLEGAL_ARGUMENT;
error = "Missing required arguments and/or incorrect values";
} else {
archive = (bundle_archive_pt) calloc(1,sizeof(*archive));
if (archive == NULL) {
status = CELIX_ENOMEM;
} else {
status = linkedList_create(&archive->revisions);
if (status == CELIX_SUCCESS) {
archive->id = 0L;
archive->location = strndup("System Bundle", 1024);
archive->archiveRoot = NULL;
archive->archiveRootDir = NULL;
archive->refreshCount = -1;
archive->persistentState = OSGI_FRAMEWORK_BUNDLE_UNKNOWN;
time(&archive->lastModified);
*bundle_archive = archive;
}
}
}
if(status != CELIX_SUCCESS && archive != NULL){
bundleArchive_destroy(archive);
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, error, "Could not create archive");
return status;
}
celix_status_t bundleArchive_create(const char *archiveRoot, long id, const char * location, const char *inputFile, bundle_archive_pt *bundle_archive) {
celix_status_t status = CELIX_SUCCESS;
char *error = NULL;
bundle_archive_pt archive = NULL;
if (*bundle_archive != NULL) {
status = CELIX_ILLEGAL_ARGUMENT;
error = "bundle_archive_pt must be NULL";
} else {
archive = (bundle_archive_pt) calloc(1,sizeof(*archive));
if (archive == NULL) {
status = CELIX_ENOMEM;
} else {
status = linkedList_create(&archive->revisions);
if (status == CELIX_SUCCESS) {
archive->id = id;
archive->location = strdup(location);
archive->archiveRootDir = NULL;
archive->archiveRoot = strdup(archiveRoot);
archive->refreshCount = -1;
time(&archive->lastModified);
status = bundleArchive_initialize(archive);
if (status == CELIX_SUCCESS) {
status = bundleArchive_revise(archive, location, inputFile);
if (status == CELIX_SUCCESS) {
*bundle_archive = archive;
}
else{
bundleArchive_closeAndDelete(archive);
}
}
}
}
}
if(status != CELIX_SUCCESS && archive != NULL){
bundleArchive_destroy(archive);
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, error, "Could not create archive");
return status;
}
celix_status_t bundleArchive_destroy(bundle_archive_pt archive) {
celix_status_t status = CELIX_SUCCESS;
if(archive != NULL){
if (archive->revisions != NULL) {
linked_list_iterator_pt iter = linkedListIterator_create(archive->revisions, 0);
while(linkedListIterator_hasNext(iter)) {
bundle_revision_pt rev = linkedListIterator_next(iter);
bundleRevision_destroy(rev);
}
linkedListIterator_destroy(iter);
linkedList_destroy(archive->revisions);
}
if (archive->archiveRoot != NULL) {
free(archive->archiveRoot);
}
if (archive->location != NULL) {
free(archive->location);
}
free(archive);
archive = NULL;
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not create archive");
return status;
}
celix_status_t bundleArchive_recreate(const char * archiveRoot, bundle_archive_pt *bundle_archive) {
celix_status_t status = CELIX_SUCCESS;
bundle_archive_pt archive = NULL;
archive = (bundle_archive_pt) calloc(1,sizeof(*archive));
if (archive == NULL) {
status = CELIX_ENOMEM;
} else {
status = linkedList_create(&archive->revisions);
if (status == CELIX_SUCCESS) {
archive->archiveRoot = strdup(archiveRoot);
archive->archiveRootDir = NULL;
archive->id = -1;
archive->persistentState = -1;
archive->location = NULL;
archive->refreshCount = -1;
archive->lastModified = (time_t) NULL;
archive->archiveRootDir = opendir(archiveRoot);
if (archive->archiveRootDir == NULL) {
status = CELIX_FRAMEWORK_EXCEPTION;
} else {
long idx = 0;
long highestId = -1;
char *location = NULL;
struct dirent *dent = NULL;
struct stat st;
errno = 0;
dent = readdir(archive->archiveRootDir);
while (errno == 0 && dent != NULL) {
char subdir[512];
snprintf(subdir, 512, "%s/%s", archiveRoot, dent->d_name);
int rv = stat(subdir, &st);
if (rv == 0 && S_ISDIR(st.st_mode) && (strncmp(dent->d_name, "version", 7) == 0)) {
sscanf(dent->d_name, "version%*d.%ld", &idx);
if (idx > highestId) {
highestId = idx;
}
}
errno = 0;
dent = readdir(archive->archiveRootDir);
}
status = CELIX_DO_IF(status, bundleArchive_getRevisionLocation(archive, 0, &location));
status = CELIX_DO_IF(status, bundleArchive_reviseInternal(archive, true, highestId, location, NULL));
if (location) {
free(location);
}
if (status == CELIX_SUCCESS) {
*bundle_archive = archive;
}
closedir(archive->archiveRootDir);
}
}
}
if(status != CELIX_SUCCESS && archive != NULL){
bundleArchive_destroy(archive);
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not create archive");
return status;
}
celix_status_t bundleArchive_getId(bundle_archive_pt archive, long *id) {
celix_status_t status = CELIX_SUCCESS;
if (archive->id < 0) {
FILE *bundleIdFile;
char id[256];
char bundleId[512];
snprintf(bundleId, sizeof(bundleId), "%s/bundle.id", archive->archiveRoot);
bundleIdFile = fopen(bundleId, "r");
if(bundleIdFile!=NULL){
fgets(id, sizeof(id), bundleIdFile);
fclose(bundleIdFile);
sscanf(id, "%ld", &archive->id);
}
else{
status = CELIX_FILE_IO_EXCEPTION;
}
}
if (status == CELIX_SUCCESS) {
*id = archive->id;
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not get archive id");
return status;
}
celix_status_t bundleArchive_getLocation(bundle_archive_pt archive, const char **location) {
celix_status_t status = CELIX_SUCCESS;
if (archive->location == NULL) {
FILE *bundleLocationFile;
char bundleLocation[512];
char loc[256];
snprintf(bundleLocation, sizeof(bundleLocation), "%s/bundle.location", archive->archiveRoot);
bundleLocationFile = fopen(bundleLocation, "r");
if(bundleLocationFile!=NULL){
fgets(loc, sizeof(loc), bundleLocationFile);
fclose(bundleLocationFile);
archive->location = strdup(loc);
}
else{
status = CELIX_FILE_IO_EXCEPTION;
}
}
if (status == CELIX_SUCCESS) {
*location = archive->location;
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not get archive location");
return status;
}
celix_status_t bundleArchive_getArchiveRoot(bundle_archive_pt archive, const char **archiveRoot) {
*archiveRoot = archive->archiveRoot;
return CELIX_SUCCESS;
}
celix_status_t bundleArchive_getCurrentRevisionNumber(bundle_archive_pt archive, long *revisionNumber) {
celix_status_t status = CELIX_SUCCESS;
bundle_revision_pt revision;
*revisionNumber = -1;
status = CELIX_DO_IF(status, bundleArchive_getCurrentRevision(archive, &revision));
status = CELIX_DO_IF(status, bundleRevision_getNumber(revision, revisionNumber));
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not get current revision number");
return status;
}
celix_status_t bundleArchive_getCurrentRevision(bundle_archive_pt archive, bundle_revision_pt *revision) {
*revision = linkedList_isEmpty(archive->revisions) ? NULL : linkedList_getLast(archive->revisions);
return CELIX_SUCCESS;
}
celix_status_t bundleArchive_getRevision(bundle_archive_pt archive, long revNr, bundle_revision_pt *revision) {
*revision = linkedList_get(archive->revisions, revNr);
return CELIX_SUCCESS;
}
celix_status_t bundleArchive_getPersistentState(bundle_archive_pt archive, bundle_state_e *state) {
celix_status_t status = CELIX_SUCCESS;
if (archive->persistentState != OSGI_FRAMEWORK_BUNDLE_UNKNOWN) {
*state = archive->persistentState;
} else {
FILE *persistentStateLocationFile;
char persistentStateLocation[512];
char stateString[256];
snprintf(persistentStateLocation, sizeof(persistentStateLocation), "%s/bundle.state", archive->archiveRoot);
persistentStateLocationFile = fopen(persistentStateLocation, "r");
if (persistentStateLocationFile == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
} else {
if (fgets(stateString, sizeof(stateString), persistentStateLocationFile) == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
}
fclose(persistentStateLocationFile);
}
if (status == CELIX_SUCCESS) {
if (strncmp(stateString, "active", 256) == 0) {
archive->persistentState = OSGI_FRAMEWORK_BUNDLE_ACTIVE;
} else if (strncmp(stateString, "starting", 256) == 0) {
archive->persistentState = OSGI_FRAMEWORK_BUNDLE_STARTING;
} else if (strncmp(stateString, "uninstalled", 256) == 0) {
archive->persistentState = OSGI_FRAMEWORK_BUNDLE_UNINSTALLED;
} else {
archive->persistentState = OSGI_FRAMEWORK_BUNDLE_INSTALLED;
}
*state = archive->persistentState;
}
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not get persistent state");
return status;
}
celix_status_t bundleArchive_setPersistentState(bundle_archive_pt archive, bundle_state_e state) {
celix_status_t status = CELIX_SUCCESS;
char persistentStateLocation[512];
FILE *persistentStateLocationFile;
snprintf(persistentStateLocation, sizeof(persistentStateLocation), "%s/bundle.state", archive->archiveRoot);
persistentStateLocationFile = fopen(persistentStateLocation, "w");
if (persistentStateLocationFile == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
} else {
char * s;
switch (state) {
case OSGI_FRAMEWORK_BUNDLE_ACTIVE:
s = "active";
break;
case OSGI_FRAMEWORK_BUNDLE_STARTING:
s = "starting";
break;
case OSGI_FRAMEWORK_BUNDLE_UNINSTALLED:
s = "uninstalled";
break;
default:
s = "installed";
break;
}
fprintf(persistentStateLocationFile, "%s", s);
if (fclose(persistentStateLocationFile) == 0) {
archive->persistentState = state;
}
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not set persistent state");
return status;
}
celix_status_t bundleArchive_getRefreshCount(bundle_archive_pt archive, long *refreshCount) {
celix_status_t status = CELIX_SUCCESS;
if (archive->refreshCount == -1) {
FILE *refreshCounterFile;
char refreshCounter[512];
snprintf(refreshCounter, sizeof(refreshCounter), "%s/refresh.counter", archive->archiveRoot);
refreshCounterFile = fopen(refreshCounter, "r");
if (refreshCounterFile == NULL) {
archive->refreshCount = 0;
} else {
char counterStr[256];
if (fgets(counterStr, sizeof(counterStr), refreshCounterFile) == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
}
fclose(refreshCounterFile);
if (status == CELIX_SUCCESS) {
sscanf(counterStr, "%ld", &archive->refreshCount);
}
}
}
if (status == CELIX_SUCCESS) {
*refreshCount = archive->refreshCount;
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not get refresh count");
return status;
}
celix_status_t bundleArchive_setRefreshCount(bundle_archive_pt archive) {
FILE *refreshCounterFile;
celix_status_t status = CELIX_SUCCESS;
char refreshCounter[512];
snprintf(refreshCounter, sizeof(refreshCounter), "%s/refresh.counter", archive->archiveRoot);
refreshCounterFile = fopen(refreshCounter, "w");
if (refreshCounterFile == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
} else {
fprintf(refreshCounterFile, "%ld", archive->refreshCount);
if (fclose(refreshCounterFile) == 0) {
}
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not set refresh count");
return status;
}
celix_status_t bundleArchive_getLastModified(bundle_archive_pt archive, time_t *lastModified) {
celix_status_t status = CELIX_SUCCESS;
if (archive->lastModified == (time_t) NULL) {
status = CELIX_DO_IF(status, bundleArchive_readLastModified(archive, &archive->lastModified));
}
if (status == CELIX_SUCCESS) {
*lastModified = archive->lastModified;
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not get last modified");
return status;
}
celix_status_t bundleArchive_setLastModified(bundle_archive_pt archive, time_t lastModifiedTime) {
celix_status_t status = CELIX_SUCCESS;
archive->lastModified = lastModifiedTime;
status = CELIX_DO_IF(status, bundleArchive_writeLastModified(archive));
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not set last modified");
return status;
}
static celix_status_t bundleArchive_readLastModified(bundle_archive_pt archive, time_t *time) {
FILE *lastModifiedFile;
char lastModified[512];
celix_status_t status = CELIX_SUCCESS;
snprintf(lastModified, sizeof(lastModified), "%s/bundle.lastmodified", archive->archiveRoot);
lastModifiedFile = fopen(lastModified, "r");
if (lastModifiedFile == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
} else {
char timeStr[20];
int year, month, day, hours, minutes, seconds;
struct tm tm_time;
memset(&tm_time,0,sizeof(struct tm));
if (fgets(timeStr, sizeof(timeStr), lastModifiedFile) == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
}
fclose(lastModifiedFile);
if (status == CELIX_SUCCESS) {
sscanf(timeStr, "%d %d %d %d:%d:%d", &year, &month, &day, &hours, &minutes, &seconds);
tm_time.tm_year = year - 1900;
tm_time.tm_mon = month - 1;
tm_time.tm_mday = day;
tm_time.tm_hour = hours;
tm_time.tm_min = minutes;
tm_time.tm_sec = seconds;
*time = mktime(&tm_time);
}
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not read last modified");
return status;
}
static celix_status_t bundleArchive_writeLastModified(bundle_archive_pt archive) {
celix_status_t status = CELIX_SUCCESS;
FILE *lastModifiedFile;
char lastModified[512];
snprintf(lastModified, sizeof(lastModified), "%s/bundle.lastmodified", archive->archiveRoot);
lastModifiedFile = fopen(lastModified, "w");
if (lastModifiedFile == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
} else {
char timeStr[20];
strftime(timeStr, 20, "%Y %m %d %H:%M:%S", localtime(&archive->lastModified));
fprintf(lastModifiedFile, "%s", timeStr);
fclose(lastModifiedFile);
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not write last modified");
return status;
}
celix_status_t bundleArchive_revise(bundle_archive_pt archive, const char * location, const char *inputFile) {
celix_status_t status = CELIX_SUCCESS;
long revNr = 0l;
if (!linkedList_isEmpty(archive->revisions)) {
long revisionNr;
status = bundleRevision_getNumber(linkedList_getLast(archive->revisions), &revisionNr);
revNr = revisionNr + 1;
}
if (status == CELIX_SUCCESS) {
status = bundleArchive_reviseInternal(archive, false, revNr, location, inputFile);
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not revise bundle archive");
return status;
}
static celix_status_t bundleArchive_reviseInternal(bundle_archive_pt archive, bool isReload, long revNr, const char * location, const char *inputFile) {
celix_status_t status = CELIX_SUCCESS;
bundle_revision_pt revision = NULL;
if (inputFile != NULL) {
location = "inputstream:";
}
status = bundleArchive_createRevisionFromLocation(archive, location, inputFile, revNr, &revision);
if (status == CELIX_SUCCESS) {
if (!isReload) {
status = bundleArchive_setRevisionLocation(archive, location, revNr);
}
linkedList_addElement(archive->revisions, revision);
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not revise bundle archive");
return status;
}
celix_status_t bundleArchive_rollbackRevise(bundle_archive_pt archive, bool *rolledback) {
*rolledback = true;
return CELIX_SUCCESS;
}
static celix_status_t bundleArchive_createRevisionFromLocation(bundle_archive_pt archive, const char *location, const char *inputFile, long revNr, bundle_revision_pt *bundle_revision) {
celix_status_t status = CELIX_SUCCESS;
char root[256];
long refreshCount;
status = bundleArchive_getRefreshCount(archive, &refreshCount);
if (status == CELIX_SUCCESS) {
bundle_revision_pt revision = NULL;
sprintf(root, "%s/version%ld.%ld", archive->archiveRoot, refreshCount, revNr);
status = bundleRevision_create(root, location, revNr, inputFile, &revision);
if (status == CELIX_SUCCESS) {
*bundle_revision = revision;
}
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Could not create revision [location=%s,inputFile=%s]", location, inputFile);
return status;
}
static celix_status_t bundleArchive_getRevisionLocation(bundle_archive_pt archive, long revNr, char **revision_location) {
celix_status_t status = CELIX_SUCCESS;
char revisionLocation[256];
long refreshCount;
status = bundleArchive_getRefreshCount(archive, &refreshCount);
if (status == CELIX_SUCCESS) {
FILE *revisionLocationFile;
snprintf(revisionLocation, sizeof(revisionLocation), "%s/version%ld.%ld/revision.location", archive->archiveRoot, refreshCount, revNr);
revisionLocationFile = fopen(revisionLocation, "r");
if (revisionLocationFile != NULL) {
char location[256];
fgets(location , sizeof(location) , revisionLocationFile);
fclose(revisionLocationFile);
*revision_location = strdup(location);
status = CELIX_SUCCESS;
} else {
// revision file not found
printf("Failed to open revision file at: %s\n", revisionLocation);
status = CELIX_FILE_IO_EXCEPTION;
}
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Failed to get revision location");
return status;
}
static celix_status_t bundleArchive_setRevisionLocation(bundle_archive_pt archive, const char * location, long revNr) {
celix_status_t status = CELIX_SUCCESS;
char revisionLocation[256];
long refreshCount;
status = bundleArchive_getRefreshCount(archive, &refreshCount);
if (status == CELIX_SUCCESS) {
FILE * revisionLocationFile;
snprintf(revisionLocation, sizeof(revisionLocation), "%s/version%ld.%ld/revision.location", archive->archiveRoot, refreshCount, revNr);
revisionLocationFile = fopen(revisionLocation, "w");
if (revisionLocationFile == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
} else {
fprintf(revisionLocationFile, "%s", location);
fclose(revisionLocationFile);
}
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Failed to set revision location");
return status;
}
celix_status_t bundleArchive_close(bundle_archive_pt archive) {
// close revision
// not yet needed/possible
return CELIX_SUCCESS;
}
celix_status_t bundleArchive_closeAndDelete(bundle_archive_pt archive) {
celix_status_t status = CELIX_SUCCESS;
status = bundleArchive_close(archive);
if (status == CELIX_SUCCESS) {
status = bundleArchive_deleteTree(archive, archive->archiveRoot);
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Failed to close and delete archive");
return status;
}
static celix_status_t bundleArchive_initialize(bundle_archive_pt archive) {
celix_status_t status = CELIX_SUCCESS;
if (archive->archiveRootDir == NULL) {
int err = mkdir(archive->archiveRoot, S_IRWXU) ;
if (err != 0) {
char *errmsg = strerror(errno);
fw_log(celix_frameworkLogger_globalLogger(), CELIX_LOG_LEVEL_ERROR, "Error mkdir: %s\n", errmsg);
status = CELIX_FILE_IO_EXCEPTION;
} else {
archive->archiveRootDir = opendir(archive->archiveRoot);
if (archive->archiveRootDir == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
} else {
FILE *bundleIdFile;
char bundleId[512];
snprintf(bundleId, sizeof(bundleId), "%s/bundle.id", archive->archiveRoot);
bundleIdFile = fopen(bundleId, "w");
if (bundleIdFile == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
} else {
FILE *bundleLocationFile;
char bundleLocation[512];
fprintf(bundleIdFile, "%ld", archive->id);
// Ignore close status, let it fail if needed again
fclose(bundleIdFile);
snprintf(bundleLocation, sizeof(bundleLocation), "%s/bundle.location", archive->archiveRoot);
bundleLocationFile = fopen(bundleLocation, "w");
if (bundleLocationFile == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
} else {
fprintf(bundleLocationFile, "%s", archive->location);
// Ignore close status, let it fail if needed again
fclose(bundleLocationFile);
status = bundleArchive_writeLastModified(archive);
}
}
closedir(archive->archiveRootDir);
}
}
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Failed to initialize archive");
return status;
}
static celix_status_t bundleArchive_deleteTree(bundle_archive_pt archive, const char * directory) {
DIR *dir;
celix_status_t status = CELIX_SUCCESS;
dir = opendir(directory);
if (dir == NULL) {
status = CELIX_FILE_IO_EXCEPTION;
} else {
struct dirent* dent = NULL;
errno = 0;
dent = readdir(dir);
while (errno == 0 && dent != NULL) {
if ((strcmp((dent->d_name), ".") != 0) && (strcmp((dent->d_name), "..") != 0)) {
char subdir[512];
snprintf(subdir, 512, "%s/%s", directory, dent->d_name);
struct stat st;
if (stat(subdir, &st) == 0) {
if (S_ISDIR (st.st_mode)) {
status = bundleArchive_deleteTree(archive, subdir);
} else {
if (remove(subdir) != 0) {
status = CELIX_FILE_IO_EXCEPTION;
break;
}
}
}
}
errno = 0;
dent = readdir(dir);
}
if (errno != 0) {
status = CELIX_FILE_IO_EXCEPTION;
} else if (closedir(dir) != 0) {
status = CELIX_FILE_IO_EXCEPTION;
} else if (status == CELIX_SUCCESS) {
if (rmdir(directory) != 0) {
status = CELIX_FILE_IO_EXCEPTION;
}
}
}
framework_logIfError(celix_frameworkLogger_globalLogger(), status, NULL, "Failed to delete tree");
return status;
}
| 14,576
|
https://github.com/chenpenghui93/tutorial/blob/master/tutorial-java-basic/src/main/java/com/example/javabasic/sample/exception/example2/Annoyance.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
tutorial
|
chenpenghui93
|
Java
|
Code
| 16
| 51
|
package com.example.javabasic.sample.exception.example2;
/**
* @author chenpenghui
* @date 2021-4-4
*/
public class Annoyance extends Exception{
}
| 34,502
|
https://github.com/ngirard/directwrite-rs/blob/master/src/font_file/loader/set_loader.rs
|
Github Open Source
|
Open Source
|
MIT
| null |
directwrite-rs
|
ngirard
|
Rust
|
Code
| 198
| 530
|
use crate::error::DWResult;
use crate::descriptions::key::FontKey;
use crate::font_file::loader::{FontFileLoader, FontFileStream};
use std::borrow::Borrow;
use std::collections::HashMap;
use std::hash::Hash;
use std::marker::PhantomData;
use winapi::shared::winerror::{HRESULT_FROM_WIN32, ERROR_FILE_NOT_FOUND};
/// Represents a loader from a set of preloaded streams which may be cloned.
pub struct SetLoader<K, S, Key>
where
K: Hash + Eq + Borrow<Key> + Send + Sync + 'static,
S: FontFileStream + Clone,
Key: FontKey + Hash + Eq + ?Sized,
{
/// The streams from which this loader loads requested resources.
pub streams: HashMap<K, S>,
_marker: PhantomData<Key>,
}
impl<K, S, Key> SetLoader<K, S, Key>
where
K: Hash + Eq + Borrow<Key> + Send + Sync + 'static,
S: FontFileStream + Clone,
Key: FontKey + Hash + Eq + ?Sized,
{
/// Initialize the loader from a set of streams.
pub fn new(streams: HashMap<K, S>) -> Self {
SetLoader {
streams,
_marker: PhantomData,
}
}
}
impl<K, S, Key> FontFileLoader for SetLoader<K, S, Key>
where
K: Hash + Eq + Borrow<Key> + Send + Sync + 'static,
S: FontFileStream + Clone,
Key: FontKey + Hash + Eq + ?Sized,
{
type Key = Key;
type Stream = S;
fn create_stream(&self, key: &Key) -> DWResult<S> {
match self.streams.get(key) {
Some(stream) => Ok(stream.clone()),
None => Err(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND).into())
}
}
}
| 41,283
|
https://github.com/MajorCooke/Doom4Doom/blob/master/shaders/glorykill.shader
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Doom4Doom
|
MajorCooke
|
GLSL
|
Code
| 120
| 482
|
uniform float timer;
vec4 Process(vec4 color)
{
vec2 texCoord = gl_TexCoord[0].st;
vec4 orgColor = getTexel(texCoord) * color;
float cp = (sin(pixelpos.y/4-timer*8)+1)/2;
vec2 fragCoord = gl_FragCoord.xy/2;
// polkadot alpha
float cpd = float(int(fragCoord.x)%2 == 0 && int(fragCoord.y)%2 == 0);
cp = clamp((cp*cpd)-0.2, 0.0, 1.0);
// RGB color of glow, components from 0.0 to 1.0.
vec3 glowColor = vec3(2.0, 0.75, 0.15);
vec3 dkColor = ((orgColor.rgb-0.5)*1.8)+0.5;
return vec4(mix(dkColor, glowColor, cp*cpd), orgColor.a);
}
/*
uniform float timer;
vec4 Process(vec4 color)
{
vec2 texCoord = gl_TexCoord[0].st;
vec4 orgColor = getTexel(texCoord) * color;
float cp = (sin(pixelpos.y/4-timer*4)+1)/2;
vec2 fragCoord = gl_FragCoord.xy/2;
float cpd = float(int(fragCoord.x)%2==0 && int(fragCoord.y)%2==0);
cp = (cp*cpd)/2+0.5;
vec3 glowColor = vec3(0.8, 0.8, 1.0);
vec3 dkColor = ((orgColor.rgb-0.7)*1.5)+0.5;
return vec4(mix(dkColor, glowColor, cp*cpd), orgColor.a);
}*/
| 24,185
|
https://github.com/GabrielJSuarez/JS-library/blob/master/js/dom.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
JS-library
|
GabrielJSuarez
|
JavaScript
|
Code
| 239
| 737
|
// DOM variables
// Get the form for new books
const addForm = document.forms['add-book'];
// Prevent page from reloading when submitting a new book
addForm.addEventListener('submit', function (e) {
e.preventDefault();
});
// DOM Modification
const library = (() => {
// Create new book objects from UI and adding it to the Library Array
const addBookToLibrary = () => {
const author = addForm.querySelector('#bookAuthor').value;
const title = addForm.querySelector('#bookTitle').value;
const pages = addForm.querySelector('#bookPages').value;
const bookRead = addForm.querySelector('#bookRead').checked;
const newBook = new Book(author, title, pages, bookRead);
const errors = document.querySelector('#error');
errors.innerHTML = '';
if (author === '') {
errors.innerHTML += "Author can't be blank";
return;
}
if (title === '') {
errors.innerHTML += "Title can't be blank";
return;
}
if (pages === '') {
errors.innerHTML += "Number of Pages can't be blank";
return;
}
myLibrary.push(newBook);
booksList();
};
// Add the book arrays to the UI
const booksList = () => {
const bookDisplay = document.querySelector('#book-display');
bookDisplay.innerHTML = '';
for (let i = 0; i < myLibrary.length; i += 1) {
bookDisplay.innerHTML += `
<div class="card border-${((myLibrary[i].read) ? 'success' : 'danger')} m-3 text-center" style="width: 23rem;">
<div class="card-header text-${((myLibrary[i].read) ? 'success' : 'danger')}">${myLibrary[i].author}</div>
<div class="card-body text-${((myLibrary[i].read) ? 'success' : 'danger')}">
<h3 class="card-title">${myLibrary[i].title}</h3>
<p class="card-text">${myLibrary[i].pages}</p>
<p class="card-text">Did you read it?: <strong class="text-capitalize">${(myLibrary[i].read) ? 'Yes!' : 'No...'}</strong></p>
<div class="d-flex">
<button type="button" class="btn btn-danger mx-3" onClick="Book.deleteBook(${i})">Delete Book</button>
<button type="button" class="btn btn-info mx-3 text-light" onClick="Book.readBook(${i})">Change Read</button>
</div>
</div>
</div>`
document.querySelector('#add-book').reset();
}
};
return {
addBookToLibrary, booksList
}
})();
| 4,979
|
https://github.com/chrisstephenmiller/spotifolio/blob/master/server/auth/spotify_client.js
|
Github Open Source
|
Open Source
|
MIT
| null |
spotifolio
|
chrisstephenmiller
|
JavaScript
|
Code
| 196
| 539
|
const SpotifyWebApi = require('spotify-web-api-node')
module.exports = ({ session, graphql, user }) => {
const spotifyWebApi = new SpotifyWebApi({
clientId: process.env.SPOTIFY_CLIENT_ID,
clientSecret: process.env.SPOTIFY_CLIENT_SECRET
})
const refreshToken = async sessionData => {
spotifyWebApi.setRefreshToken(sessionData.refreshToken)
const { body } = await spotifyWebApi.refreshAccessToken()
sessionData.accessToken = body.access_token
sessionData.expiresAt = body.expires_in * 1000 + Date.now()
return sessionData
}
const validateUserSession = userSession => userSession.accessToken
const getUserToken = async userSession => {
if (userSession.expiresAt < Date.now()) await refreshToken(userSession)
return userSession.accessToken
}
const getGraphQLToken = async graphqlSession => {
const data = JSON.parse(graphqlSession.data)
if (data.expiresAt < Date.now()) {
const newData = await refreshToken(data)
graphqlSession.data = JSON.stringify(newData)
graphqlSession.save()
return newData.accessToken
}
return data.accessToken
}
const getAppToken = async () => {
// TODO: access_token be peristed, used through expiration period
const { body } = await spotifyWebApi.clientCredentialsGrant()
return body.access_token
}
return async appAuth => {
const accessToken =
appAuth === null || !user // null passed for scopeless api (rate limiting)
? await getAppToken() // scopeless, no auth needed
: validateUserSession(session) // auth needed, confirm user or graphql session
? await getUserToken(session) // confirm userToken is current, refresh if necessary
: await getGraphQLToken(graphql) // confirm graphqlToken is current, refresh if necessary
spotifyWebApi.setAccessToken(accessToken)
return spotifyWebApi
}
}
| 21,170
|
https://github.com/MaxHillebrand/libnunchuk/blob/master/tests/src/nunchukutils_test.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
libnunchuk
|
MaxHillebrand
|
C++
|
Code
| 424
| 3,494
|
// Copyright (c) 2020 Enigmo
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <nunchuk.h>
#include <amount.h>
#include <doctest.h>
TEST_CASE("testing SanitizeBIP32Input") {
using namespace nunchuk;
std::string xpub =
"xpub6Gs9Gp1P7ov2Xy6XmVBawLUwRgifGMK93K6bYuMdi9PfmJ6y6e7ffzD"
"7JKCjWgJn71YGCQMozL1284Ywoaptv8UGRsua635k8yELEKk9nhh";
std::string ypub =
"ypub6bhQaUgJGVTWPGHebqyD9RaSbes7CyJdxRcpLJFX69mYpPvCMJHEJ3sFKXAKWaxhWef4"
"wsxNSzMa1MAWXHEuiN9sJDbzfwuEQhHycrWdgeH";
std::string Ypub =
"Ypub6nbVhiQjqT1soqT2YWSByVvFKSuNRKzEGhGVFZX4TvbxSaV77hfWPAjB8E7o52Bbk7j3"
"pTxVLCk58WnGpWPrrrGY8giQ5MNEJRZrCmSRoL4";
std::string zpub =
"zpub6vXft9MDRAzzEZUmSCkqMWfwmd1Z9bJ8sY937h9QUA9RsVjRbxSnv7XPLj7uWVccvHms"
"hMYvuei7tdn5EyevWbqUAZJRFriigRMd1QQKz7X";
std::string Zpub =
"Zpub77Rm1P5ez8ZMf8e9NsDpBb1kVR3pMwyjBoni2xQwqvyqVgJLNMq51EPK9S5P4vqX9kqr"
"ZwZ3ns6d1oPqYCosf5x912QpfGBia9dVbJBHr4f";
std::string tpub =
"tpubDHEmo3q4q5sUomHPDgAg9FpJkopKFjpCawgtuTQn449ZWamgArxkpRswYMHX3BG1tv5A"
"oysgXRq4pF3ZCSg8oZvZVUesmZjyivpjzGcUHhL";
std::string upub =
"upub5JNMMozdfmHaz5XBGQpiK5CRunHKSVLeHyXwCifya8G2bzfHLfcyooEhEhKyWxM1t6Bq"
"wya8cLwNUCiFeVarXRRTprpJLJdHKo3Q4YUZrZs";
std::string Upub =
"Upub5VGSV3j5EiqxQegZD5Hh99YEdaKaer2EcFBc7ywWwu6SEBEC751Ftv6d3QHT5PZv7ZFp"
"pZaFVZKsbNL1wijofuY8fKvhji6HDXKGeUuAykS";
std::string vpub =
"vpub5dCcfUfYpSq4qNiJ6mcLXAHw5kRmP7L9D649z7Zrx8duf6UWbKnYRrtqFuHZWrzwHjJe"
"hTAh51HvMVKpNBzsKf74hCWivDSmbX73T9rLCgP";
std::string Vpub =
"Vpub5p6hniPzPQPSFwsg3S5KMEdjoYU2bU1jXMhpuNqQKuUKHH3RMjApWykm4cF35JDqXCNd"
"a3AoxDgRUewafR9pU9DjXfd8KcumVFNv353acNH";
CHECK(Utils::SanitizeBIP32Input(xpub, "xpub") == xpub);
CHECK(Utils::SanitizeBIP32Input(ypub, "xpub") == xpub);
CHECK(Utils::SanitizeBIP32Input(Ypub, "xpub") == xpub);
CHECK(Utils::SanitizeBIP32Input(zpub, "xpub") == xpub);
CHECK(Utils::SanitizeBIP32Input(Zpub, "xpub") == xpub);
CHECK(Utils::SanitizeBIP32Input(tpub, "tpub") == tpub);
CHECK(Utils::SanitizeBIP32Input(upub, "tpub") == tpub);
CHECK(Utils::SanitizeBIP32Input(Upub, "tpub") == tpub);
CHECK(Utils::SanitizeBIP32Input(vpub, "tpub") == tpub);
CHECK(Utils::SanitizeBIP32Input(Vpub, "tpub") == tpub);
CHECK_THROWS(Utils::SanitizeBIP32Input("invalidxpub", "tpub"));
CHECK_THROWS(Utils::SanitizeBIP32Input("", "tpub"));
}
TEST_CASE("testing IsValid...") {
using namespace nunchuk;
Utils::SetChain(Chain::MAIN);
CHECK(Utils::IsValidXPub(
"xpub6Gs9Gp1P7ov2Xy6XmVBawLUwRgifGMK93K6bYuMdi9PfmJ6y6e7ffzD"
"7JKCjWgJn71YGCQMozL1284Ywoaptv8UGRsua635k8yELEKk9nhh"));
CHECK(Utils::IsValidPublicKey(
"0297da76f2b4ae426f41e617b4f13243716d1417d3acc3f8da7a54f301fc951741"));
CHECK(Utils::IsValidDerivationPath("m/44h/0h/1h"));
CHECK(Utils::IsValidDerivationPath("m/48'/0'/0'/7'"));
CHECK(Utils::IsValidFingerPrint("0b93c52e"));
CHECK_FALSE(Utils::IsValidXPub(
"tpubDHEmo3q4q5sUomHPDgAg9FpJkopKFjpCawgtuTQn449ZWamgArxkpRs"
"wYMHX3BG1tv5AoysgXRq4pF3ZCSg8oZvZVUesmZjyivpjzGcUHhL"));
CHECK_FALSE(Utils::IsValidFingerPrint("0b93c52j"));
CHECK_FALSE(Utils::IsValidFingerPrint("0b93c5"));
Utils::SetChain(Chain::TESTNET);
CHECK_FALSE(Utils::IsValidXPub(
"xpub6Gs9Gp1P7ov2Xy6XmVBawLUwRgifGMK93K6bYuMdi9PfmJ6y6e7ffzD"
"7JKCjWgJn71YGCQMozL1284Ywoaptv8UGRsua635k8yELEKk9nhh"));
CHECK(Utils::IsValidXPub(
"tpubDHEmo3q4q5sUomHPDgAg9FpJkopKFjpCawgtuTQn449ZWamgArxkpRs"
"wYMHX3BG1tv5AoysgXRq4pF3ZCSg8oZvZVUesmZjyivpjzGcUHhL"));
CHECK(Utils::IsValidDerivationPath("m/44h/1h/1h"));
CHECK(Utils::IsValidDerivationPath("m/48'/1'/0'/7'"));
}
TEST_CASE("testing Amount") {
using namespace nunchuk;
CHECK_THROWS(Utils::AmountFromValue("21000001"));
CHECK_THROWS(Utils::AmountFromValue("-21000001", true));
CHECK_NOTHROW(Utils::AmountFromValue("21000000"));
CHECK_NOTHROW(Utils::AmountFromValue("-21000000", true));
CHECK(Utils::AmountFromValue("0.00010000") == 10000);
CHECK(Utils::AmountFromValue("-0.00010000", true) == -10000);
CHECK(Utils::AmountFromValue("21000000") == 2100000000000000);
CHECK(Utils::AmountFromValue("-21000000", true) == -2100000000000000);
CHECK(Utils::AmountFromValue("0") == 0LL);
CHECK(Utils::AmountFromValue("0.00000000") == 0LL);
CHECK(Utils::AmountFromValue("0.00000001") == 1LL);
CHECK(Utils::AmountFromValue("0.17622195") == 17622195LL);
CHECK(Utils::AmountFromValue("0.5") == 50000000LL);
CHECK(Utils::AmountFromValue("0.50000000") == 50000000LL);
CHECK(Utils::AmountFromValue("0.89898989") == 89898989LL);
CHECK(Utils::AmountFromValue("1.00000000") == 100000000LL);
CHECK(Utils::AmountFromValue("20999999.9999999") == 2099999999999990LL);
CHECK(Utils::AmountFromValue("20999999.99999999") == 2099999999999999LL);
CHECK(Utils::AmountFromValue("1e-8") == COIN / 100000000);
CHECK(Utils::AmountFromValue("0.1e-7") == COIN / 100000000);
CHECK(Utils::AmountFromValue("0.01e-6") == COIN / 100000000);
CHECK(Utils::AmountFromValue(
"0."
"00000000000000000000000000000000000000000000000000000"
"00000000000000000000001e+68") == COIN / 100000000);
CHECK(Utils::AmountFromValue(
"10000000000000000000000000000000000000000000000000000"
"000000000000e-64") == COIN);
CHECK(Utils::AmountFromValue(
"0."
"000000000000000000000000000000000000000000000000000000000000000100"
"000000000000000000000000000000000000000000000000000e64") == COIN);
CHECK_THROWS(Utils::AmountFromValue("1e-9")); // should fail
CHECK_THROWS(Utils::AmountFromValue("0.000000019")); // should fail
CHECK(Utils::AmountFromValue("0.00000001000000") ==
1LL); // should pass == cut trailing 0
CHECK_THROWS(Utils::AmountFromValue("19e-9")); // should fail
CHECK(Utils::AmountFromValue("0.19e-6") ==
19); // should pass == leading 0 is present
CHECK_THROWS(
Utils::AmountFromValue("92233720368.54775808")); // overflow error
CHECK_THROWS(Utils::AmountFromValue("1e+11")); // overflow error
CHECK_THROWS(Utils::AmountFromValue("1e11")); // overflow error signless
CHECK_THROWS(Utils::AmountFromValue("93e+9")); // overflow error
CHECK(Utils::ValueFromAmount(0LL) == "0.00000000");
CHECK(Utils::ValueFromAmount(1LL) == "0.00000001");
CHECK(Utils::ValueFromAmount(17622195LL) == "0.17622195");
CHECK(Utils::ValueFromAmount(50000000LL) == "0.50000000");
CHECK(Utils::ValueFromAmount(89898989LL) == "0.89898989");
CHECK(Utils::ValueFromAmount(100000000LL) == "1.00000000");
CHECK(Utils::ValueFromAmount(2099999999999990LL) == "20999999.99999990");
CHECK(Utils::ValueFromAmount(2099999999999999LL) == "20999999.99999999");
CHECK(Utils::ValueFromAmount(0) == "0.00000000");
CHECK(Utils::ValueFromAmount((COIN / 10000) * 123456789) == "12345.67890000");
CHECK(Utils::ValueFromAmount(-COIN) == "-1.00000000");
CHECK(Utils::ValueFromAmount(-COIN / 10) == "-0.10000000");
CHECK(Utils::ValueFromAmount(COIN * 100000000) == "100000000.00000000");
CHECK(Utils::ValueFromAmount(COIN * 10000000) == "10000000.00000000");
CHECK(Utils::ValueFromAmount(COIN * 1000000) == "1000000.00000000");
CHECK(Utils::ValueFromAmount(COIN * 100000) == "100000.00000000");
CHECK(Utils::ValueFromAmount(COIN * 10000) == "10000.00000000");
CHECK(Utils::ValueFromAmount(COIN * 1000) == "1000.00000000");
CHECK(Utils::ValueFromAmount(COIN * 100) == "100.00000000");
CHECK(Utils::ValueFromAmount(COIN * 10) == "10.00000000");
CHECK(Utils::ValueFromAmount(COIN) == "1.00000000");
CHECK(Utils::ValueFromAmount(COIN / 10) == "0.10000000");
CHECK(Utils::ValueFromAmount(COIN / 100) == "0.01000000");
CHECK(Utils::ValueFromAmount(COIN / 1000) == "0.00100000");
CHECK(Utils::ValueFromAmount(COIN / 10000) == "0.00010000");
CHECK(Utils::ValueFromAmount(COIN / 100000) == "0.00001000");
CHECK(Utils::ValueFromAmount(COIN / 1000000) == "0.00000100");
CHECK(Utils::ValueFromAmount(COIN / 10000000) == "0.00000010");
CHECK(Utils::ValueFromAmount(COIN / 100000000) == "0.00000001");
}
| 45,840
|
https://github.com/DeepManuPy/cat-dog-classifier/blob/master/gpu_config.py
|
Github Open Source
|
Open Source
|
MIT
| null |
cat-dog-classifier
|
DeepManuPy
|
Python
|
Code
| 30
| 77
|
"""
Optional, only for those who are training the model on GPU and facing "CUDA_error:ran_out_of_memory" problem.
"""
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config)
| 532
|
https://github.com/Frank-Mayer/MazeSolving/blob/master/closure-compiler.py
|
Github Open Source
|
Open Source
|
MIT
| null |
MazeSolving
|
Frank-Mayer
|
Python
|
Code
| 93
| 383
|
#!/usr/bin/python3
import http.client
import urllib.request
import urllib.parse
import urllib.error
import sys
import os
directory = r'./'
if (os.system("tsc -p " + directory + "tsconfig.json --pretty") == 0):
print("TypeScript compiled")
for filename in os.listdir(directory):
if filename.endswith(".js"):
print(filename)
file_path = (os.path.join(directory, filename))
file_object = open(file_path, "r")
code = file_object.read()
file_object.close()
params = urllib.parse.urlencode([
('js_code', code),
('compilation_level', 'ADVANCED_OPTIMIZATIONS'),
('output_format', 'text'),
('output_info', 'compiled_code'),
])
headers = {"Content-type": "application/x-www-form-urlencoded"}
conn = http.client.HTTPSConnection('closure-compiler.appspot.com')
conn.request('POST', '/compile', params, headers)
response = conn.getresponse()
data = response.read()
code = data.decode("utf-8")
print("Minified by closure-compiler")
file_object = open(file_path, "w")
file_object.write('"use strict";\n'+code)
file_object.close()
conn.close()
else:
continue
| 39,013
|
https://github.com/SvenKube/throwless/blob/master/tests/option.test.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
throwless
|
SvenKube
|
TypeScript
|
Code
| 591
| 1,799
|
import {err, none, ok, Option, some} from "../src";
describe("Tests for Some", () => {
let option: Option<number>;
beforeAll(() => {
option = some(773);
});
test("isSome() returns true", () => {
expect(option.isSome()).toBeTruthy();
});
test("isNone() returns false", () => {
expect(option.isNone()).toBeFalsy();
});
test("expect() returns value of some()", () => {
expect(option.expect(new Error("Could not get value")))
.toEqual(773);
});
test("unwrap() returns value of some()", () => {
expect(option.unwrap()).toEqual(773);
});
test("unwrapOr() returns value of some()", () => {
expect(option.unwrapOr(1337)).toEqual(773);
});
test("unwrapOrElse() returns value of some()", () => {
expect(option.unwrapOrElse(
() => 1337
)).toEqual(773);
});
test("map() returns the result of fn", () => {
expect(option.map(
(value => value * 2)
)).toEqual(some(773 * 2));
});
test("mapOr() returns the result of fn instead of passed value", () => {
expect(option.mapOr(1337,
(value => value * 2)
)).toEqual(773 * 2);
});
test("mapOrElse() returns the result of fnMap, not fnOrElse", () => {
expect(option.mapOrElse(
(value => value * 2),
(() => 1337)
)).toEqual(773 * 2);
});
test("okOr() returns Result<T, E> with the value of Some", () => {
expect(option.okOr(new Error("Some error")))
.toEqual(ok(773));
});
test("okOrElse() returns Result<T, E> with the value of Some", () => {
expect(option.okOrElse(
(() => new Error("Some Error"))
)).toEqual(ok(773));
});
test("and() returns the passed Option", () => {
expect(option.and(some(42))).toEqual(some(42));
});
test("andThen() returns the Option returned by fn", () => {
expect(option.andThen(
(value => some(value * 2))
)).toEqual(some(773 * 2));
});
test("filter() returns some() if fn returns true", () => {
expect(option.filter(
(_value => true)
)).toEqual(some(773));
});
test("filter() returns none() if fn returns false", () => {
expect(option.filter(
(_value => false)
)).toEqual(none());
});
test("or() returns this some()", () => {
expect(option.or(some(1337))).toEqual(some(773));
});
test("or() returns this some()", () => {
expect(option.orElse(
(() => some(1337))
)).toEqual(some(773));
});
test("xor() returns this some() if other is none()", () => {
expect(option.xor(none())).toEqual(some(773));
});
test("xor() returns this none() if other is also some()", () => {
expect(option.xor(some(1337))).toEqual(none());
});
});
describe("Tests for None", () => {
let option: Option<number>;
beforeAll(() => {
option = none();
});
test("isSome() returns false", () => {
expect(option.isSome()).toBeFalsy();
});
test("isNone() returns true", () => {
expect(option.isNone()).toBeTruthy();
});
test("expect() throws the passed error", () => {
expect(() =>
option.expect(new Error("Could not get value"))
).toThrow(new Error("Could not get value"));
});
test("unwrap() throws and error", () => {
expect(() =>
option.unwrap()
).toThrow();
});
test("unwrapOr() returns the passed value", () => {
expect(option.unwrapOr(1337)).toEqual(1337);
});
test("unwrapOrElse() returns value returned by fn", () => {
expect(option.unwrapOrElse(
() => 1337
)).toEqual(1337);
});
test("map() returns none()", () => {
expect(option.map(
(value => value * 2)
)).toEqual(none());
});
test("mapOr() returns the passed value", () => {
expect(option.mapOr(1337,
(value => value * 2)
)).toEqual(1337);
});
test("mapOrElse() returns the result of fnOrElse, not fnMap", () => {
expect(option.mapOrElse(
(value => value * 2),
(() => 1337)
)).toEqual(1337);
});
test("okOr() returns Result<T, E> with the passed error", () => {
expect(option.okOr(new Error("Some error")))
.toEqual(err(new Error("Some error")));
});
test("okOrElse() returns Result<T, E> with the error returned by fn", () => {
expect(option.okOrElse(
(() => new Error("Some error"))
)).toEqual(err(new Error("Some error")));
});
test("and() returns none()", () => {
expect(option.and(some(42))).toEqual(none());
});
test("andThen() returns none()", () => {
expect(option.andThen(
(value => some(value * 2))
)).toEqual(none());
});
test("filter() returns none() if fn return true", () => {
expect(option.filter(
(_value => true)
)).toEqual(none());
});
test("filter() returns none() if fn returns false", () => {
expect(option.filter(
(_value => false)
)).toEqual(none());
});
test("or() returns the passed value", () => {
expect(option.or(some(1337))).toEqual(some(1337));
});
test("or() returns value returned by fn", () => {
expect(option.orElse(
(() => some(1337))
)).toEqual(some(1337));
});
test("xor() returns none() if other is none()", () => {
expect(option.xor(none())).toEqual(none());
});
test("xor() returns some() if other is some()", () => {
expect(option.xor(some(1337))).toEqual(some(1337));
});
});
| 44,050
|
https://github.com/AllenInstitute/aics-fms-file-explorer-app/blob/master/packages/core/components/AnnotationSidebar/index.tsx
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,023
|
aics-fms-file-explorer-app
|
AllenInstitute
|
TSX
|
Code
| 282
| 723
|
import classNames from "classnames";
import * as React from "react";
import { DragDropContext, OnDragEndResponder, OnDragStartResponder } from "react-beautiful-dnd";
import { useDispatch } from "react-redux";
import AnnotationHierarchy from "../AnnotationHierarchy";
import AnnotationList, { DROPPABLE_ID as ANNOTATION_LIST_DROPPABLE_ID } from "../AnnotationList";
import { selection } from "../../state";
import styles from "./AnnotationSidebar.module.css";
interface AnnotationSidebarProps {
className?: string;
}
/**
* Container for features related to viewing available metadata annotations, selecting and ordering those annotations
* by which to group files by, and filtering/sorting those annotations.
*/
export default function AnnotationSidebar(props: AnnotationSidebarProps) {
const [highlightDropZone, setHighlightDropZone] = React.useState(false);
const dispatch = useDispatch();
// On drag start of any draggable item within this DragDropContext, if the draggable comes from the list of all
// available annotations, show indicator of where the user can drop it
const onDragStart: OnDragStartResponder = (start) => {
if (start.source.droppableId === ANNOTATION_LIST_DROPPABLE_ID) {
setHighlightDropZone(true);
}
};
// On drag end of any draggable item within this DragDropContext, if it was dropped on the hierarchy list, tell Redux about it
const onDragEnd: OnDragEndResponder = (result) => {
const { destination, draggableId, source } = result;
const { itemId } = JSON.parse(draggableId);
// dropped within drag and drop context
if (destination) {
if (source.droppableId === ANNOTATION_LIST_DROPPABLE_ID) {
// the draggable came from the list of all available annotations and was dropped on the hierarchy
dispatch(selection.actions.reorderAnnotationHierarchy(itemId, destination.index));
} else {
// in every other case, the draggable came from the hierarchy itself (i.e., the hierarchy was reordered)
dispatch(selection.actions.reorderAnnotationHierarchy(itemId, destination.index));
}
}
// drag is finished, so if showDropZone is true, toggle the flag
if (highlightDropZone) {
setHighlightDropZone(false);
}
};
return (
<div className={classNames(styles.root, props.className)}>
<DragDropContext onDragStart={onDragStart} onDragEnd={onDragEnd}>
<AnnotationHierarchy
className={styles.annotationHierarchy}
highlightDropZone={highlightDropZone}
/>
<AnnotationList className={styles.annotationList} />
</DragDropContext>
</div>
);
}
| 11,596
|
https://github.com/EasyAbp/Cms/blob/master/src/EasyAbp.Cms.Web/Pages/Cms/Articles/Article/EditModal.cshtml.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Cms
|
EasyAbp
|
C#
|
Code
| 78
| 271
|
using System;
using System.Threading.Tasks;
using EasyAbp.Cms.Articles;
using EasyAbp.Cms.Articles.Dtos;
using Microsoft.AspNetCore.Mvc;
namespace EasyAbp.Cms.Web.Pages.Cms.Articles.Article
{
public class EditModalModel : CmsPageModel
{
[HiddenInput]
[BindProperty(SupportsGet = true)]
public Guid Id { get; set; }
[BindProperty]
public CreateUpdateArticleDto Article { get; set; }
private readonly IArticleAppService _service;
public EditModalModel(IArticleAppService service)
{
_service = service;
}
public async Task OnGetAsync()
{
var dto = await _service.GetAsync(Id);
Article = ObjectMapper.Map<ArticleDto, CreateUpdateArticleDto>(dto);
}
public async Task<IActionResult> OnPostAsync()
{
await _service.UpdateAsync(Id, Article);
return NoContent();
}
}
}
| 25,972
|
https://github.com/audevbot/autorest.devops.debug/blob/master/generated/intermediate/examples_cli/apimanagement_service_apis_issues_comments_get_1.sh
|
Github Open Source
|
Open Source
|
MIT
| null |
autorest.devops.debug
|
audevbot
|
Shell
|
Code
| 14
| 129
|
# ApiManagementGetApiIssueComment
RESOURCE_GROUP="myresourcegroup"
SERVICE_NAME="myservice"
API_NAME="myapi"
ISSUE_NAME="myissue"
COMMENT_NAME="mycomment"
az resource show --id /subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.ApiManagement/service/$SERVICE_NAME/apis/$API_NAME/issues/$ISSUE_NAME/comments/$COMMENT_NAME --api-version 2019-01-01
| 21,911
|
https://github.com/jaholme/MSIX-PackageSupportFramework/blob/master/fixups/FileRedirectionFixup/CreateFileFixup.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
MSIX-PackageSupportFramework
|
jaholme
|
C++
|
Code
| 231
| 706
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "FunctionImplementations.h"
#include "PathRedirection.h"
template <typename CharT>
HANDLE __stdcall CreateFileFixup(
_In_ const CharT* fileName,
_In_ DWORD desiredAccess,
_In_ DWORD shareMode,
_In_opt_ LPSECURITY_ATTRIBUTES securityAttributes,
_In_ DWORD creationDisposition,
_In_ DWORD flagsAndAttributes,
_In_opt_ HANDLE templateFile) noexcept
{
auto guard = g_reentrancyGuard.enter();
try
{
if (guard)
{
// FUTURE: If 'creationDisposition' is something like 'CREATE_ALWAYS', we could get away with something
// cheaper than copy-on-read, but we'd also need to be mindful of ensuring the correct error if so
auto[shouldRedirect, redirectPath] = ShouldRedirect(fileName, redirect_flags::copy_on_read);
if (shouldRedirect)
{
return impl::CreateFile(redirectPath.c_str(), desiredAccess, shareMode, securityAttributes, creationDisposition, flagsAndAttributes, templateFile);
}
}
}
catch (...)
{
// Fall back to assuming no redirection is necessary
}
return impl::CreateFile(fileName, desiredAccess, shareMode, securityAttributes, creationDisposition, flagsAndAttributes, templateFile);
}
DECLARE_STRING_FIXUP(impl::CreateFile, CreateFileFixup);
HANDLE __stdcall CreateFile2Fixup(
_In_ LPCWSTR fileName,
_In_ DWORD desiredAccess,
_In_ DWORD shareMode,
_In_ DWORD creationDisposition,
_In_opt_ LPCREATEFILE2_EXTENDED_PARAMETERS createExParams) noexcept
{
auto guard = g_reentrancyGuard.enter();
try
{
if (guard)
{
// FUTURE: See comment in CreateFileFixup about using 'creationDisposition' to choose a potentially better
// redirect flags value
auto[shouldRedirect, redirectPath] = ShouldRedirect(fileName, redirect_flags::copy_on_read);
if (shouldRedirect)
{
return impl::CreateFile2(redirectPath.c_str(), desiredAccess, shareMode, creationDisposition, createExParams);
}
}
}
catch (...)
{
// Fall back to assuming no redirection is necessary
}
return impl::CreateFile2(fileName, desiredAccess, shareMode, creationDisposition, createExParams);
}
DECLARE_FIXUP(impl::CreateFile2, CreateFile2Fixup);
| 15,257
|
https://github.com/claudiocro/react-autowhatever/blob/master/test/plain-list/Autowhatever.test.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
react-autowhatever
|
claudiocro
|
JavaScript
|
Code
| 181
| 654
|
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { expect } from 'chai';
import {
init,
getStoredFocusedItemName,
getInputAttribute,
getItemsContainerAttribute,
getItems,
mouseEnterItem,
mouseLeaveItem,
mouseDownItem,
clickItem
} from '../helpers';
import AutowhateverApp, {
renderItem
} from './AutowhateverApp';
describe('Plain List Autowhatever', () => {
beforeEach(() => {
renderItem.reset();
init(TestUtils.renderIntoDocument(<AutowhateverApp />));
});
describe('initially', () => {
it('should set input\'s `aria-owns` to items container\'s `id`', () => {
expect(getInputAttribute('aria-owns')).to.equal(getItemsContainerAttribute('id'));
});
it('should render all items', () => {
expect(getItems()).to.be.of.length(5);
});
it('should call `renderItem` exactly `items.length` times', () => {
expect(renderItem).to.have.callCount(5);
});
});
describe('hovering items', () => {
it('should call `renderItem` once with the right parameters when item is entered', () => {
renderItem.reset();
mouseEnterItem(0);
expect(renderItem).to.have.been.calledOnce;
expect(renderItem).to.be.calledWith({ text: 'Apple' });
});
it('should call `renderItem` twice when the focused item is changed', () => {
mouseEnterItem(1);
renderItem.reset();
mouseLeaveItem(1);
mouseEnterItem(2);
expect(renderItem).to.have.been.calledTwice;
});
it('should call `renderItem` once when item is left', () => {
mouseEnterItem(3);
renderItem.reset();
mouseLeaveItem(3);
expect(renderItem).to.have.been.calledOnce;
});
it('should not call `renderItem` when item is clicked', () => {
renderItem.reset();
mouseDownItem(4);
clickItem(4);
expect(renderItem).not.to.have.been.called;
});
it('should store the focused item on the instance', () => {
mouseEnterItem(2);
expect(getStoredFocusedItemName()).to.equal('HTMLLIElement');
});
});
});
| 6,572
|
https://github.com/vgstation-coders/space-station-14/blob/master/Content.Shared/Suspicion/SuspicionMessages.cs
|
Github Open Source
|
Open Source
|
CC-BY-NC-SA-3.0, CC-BY-4.0, CC-BY-SA-3.0, MIT, LicenseRef-scancode-proprietary-license
| 2,022
|
space-station-14
|
vgstation-coders
|
C#
|
Code
| 25
| 81
|
using Robust.Shared.Serialization;
namespace Content.Shared.Suspicion
{
public static class SuspicionMessages
{
[Serializable, NetSerializable]
public sealed class SetSuspicionEndTimerMessage : EntityEventArgs
{
public TimeSpan? EndTime;
}
}
}
| 43,980
|
https://github.com/addeye/labadministrasi/blob/master/koneksi/koneksi.php
|
Github Open Source
|
Open Source
|
MIT
| null |
labadministrasi
|
addeye
|
PHP
|
Code
| 5
| 56
|
<?php
$db=mysql_connect("localhost","root","");
$sel=mysql_select_db("lab_unesa",$db);
date_default_timezone_set('Asia/Jakarta');
?>
| 29,309
|
https://github.com/Kcch91/MASAI-concierge-android-app/blob/master/app/src/main/java/solutions/masai/masai/android/core/model/travelfolder_user/Choice.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
MASAI-concierge-android-app
|
Kcch91
|
Java
|
Code
| 97
| 298
|
package solutions.masai.masai.android.core.model.travelfolder_user;
import java.util.Locale;
/**
* Created by cWahl on 25.08.2017.
*/
public class Choice {
private String value;
private String textDE;
private String textEN;
//region properties
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getTextDE() {
return textDE;
}
public void setTextDE(String text) {
this.textDE = text;
}
public String getTextEN() {
return textEN;
}
public void setTextEN(String text) {
this.textEN = text;
}
//endregion
public String toString() {
Locale currentLocale = Locale.getDefault();
if (currentLocale.getISO3Language().equalsIgnoreCase("deu")) {
return getTextDE();
} else {
return getTextEN();
}
}
}
| 12,405
|
https://github.com/integrify-group-3/iBudget/blob/master/client/src/components/IncomeExpensesYearChart/index.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
iBudget
|
integrify-group-3
|
TSX
|
Code
| 250
| 861
|
import React, { useState } from 'react'
import { Paper } from '@material-ui/core'
import {
ArgumentAxis,
ValueAxis,
Chart,
Legend,
SplineSeries,
BarSeries,
Tooltip,
Title,
} from '@devexpress/dx-react-chart-material-ui'
import { EventTracker, Animation } from '@devexpress/dx-react-chart'
import { scaleBand } from '@devexpress/dx-chart-core'
import { ArgumentScale, Stack } from '@devexpress/dx-react-chart'
import { useMediaQuery, useTheme } from '@material-ui/core'
import { IncomeExpensesYearChartProps } from '../../types'
import SwitchChartBtn from '../../components/SwitchChartBtn'
const chartLegendStyle = {
display: 'flex',
width: '10rem',
justifyContent: 'center',
}
const legendLabelComponent = (props: any) => (
<Legend.Item {...props} style={chartLegendStyle} />
)
export default function IncomeExpensesYearChart({
data,
year,
}: IncomeExpensesYearChartProps) {
const theme = useTheme()
const mobile = useMediaQuery(theme.breakpoints.down('sm'))
const [switchChart, setSwitchChart] = useState(false)
const switchChartView = () => {
setSwitchChart(!switchChart)
}
const lineChartText = 'Line Chart'
const barChartText = 'Bar Chart'
return (
<Paper className="chart-container">
{!switchChart ? (
<Chart data={data} height={mobile ? 336 : 450}>
<ArgumentScale factory={scaleBand} />
<ArgumentAxis />
<ValueAxis />
<BarSeries
valueField="income"
argumentField="month"
name="Income"
color="#2E5090"
/>
<BarSeries
valueField="expenses"
argumentField="month"
name="Expenses"
color="#FF6666"
/>
<Stack />
<EventTracker />
<Tooltip />
<Legend position="top" rootComponent={legendLabelComponent} />
{/* Title with year is for testing */}
{/* <Title text={`Expenses/Income for ${year}`} /> */}
<SwitchChartBtn
switchChartView={switchChartView}
btnText={lineChartText}
/>
{/* <Animation /> */}
</Chart>
) : (
<Chart data={data} height={450}>
<ArgumentAxis />
<ValueAxis />
<SplineSeries
valueField="income"
name="income"
argumentField={`month`}
color="#2E5090"
/>
<SplineSeries
valueField="expenses"
name="expenses"
argumentField={`month`}
color="#FF6666"
/>
<EventTracker />
<Tooltip />
<Legend position="top" rootComponent={legendLabelComponent} />
{/* title is only for testing */}
{/* <Title text={`Expenses/Income for ${year}`} /> */}
<SwitchChartBtn
switchChartView={switchChartView}
btnText={barChartText}
/>
{/* <Animation /> */}
</Chart>
)}
</Paper>
)
}
| 5,068
|
https://github.com/ericyd/generative-art/blob/master/nannou/examples/util/prism.rs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
generative-art
|
ericyd
|
Rust
|
Code
| 463
| 1,471
|
// A super-simple implementation of a 3D prism
// made by simply drawing the polygons that are
// shown when looking with perspective.
// The polygons are all quadrilaterals defined by the vertices
// which are labeled below
//
// B▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔C
// ▕ ╲ ╲
// ▕ ╲ ╲
// ▕ ╲ ╲
// ▕ ╲ top ╲
// ▕ ╲ ╲
// G A ▁▁▁▁▁▁▁▁▁▁▁▁▁▁D
// ╲ left▕ ▕
// ╲ ▕ ▕
// ╲ ▕ ▕
// ╲ ▕ right ▕
// ╲ ▕ ▕
// ╲▕ ▕
// ╲F▁▁▁▁▁▁▁▁▁▁▁▁▁▁E
use super::Line2;
use nannou::prelude::*;
pub struct Prism {
pub vertex: Point2,
width: f32,
height: f32,
depth: f32,
angle: f32, // in radians
left_color: Rgba,
top_color: Rgba,
right_color: Rgba,
}
impl Prism {
pub fn new(vertex: Point2) -> Self {
Prism {
vertex,
width: 1.,
height: 1.,
depth: 1.,
angle: PI / 7., // arbitrary
left_color: rgba(1., 1., 1., 1.), // white
top_color: rgba(1., 0.549, 0.412, 1.), // salmon
right_color: rgba(252. / 255., 181. / 255., 100. / 255., 1.), // orangy
}
}
fn a(&self) -> Point2 {
self.vertex
}
fn b(&self) -> Point2 {
pt2(
self.vertex.x + self.depth * (PI - self.angle).cos(),
self.vertex.y + self.depth * (PI - self.angle).sin(),
)
}
fn c(&self) -> Point2 {
pt2(
self.b().x + self.width * self.angle.cos(),
self.b().y + self.width * self.angle.sin(),
)
}
// titled d_ instead of `d` to avoid name conflict with public `d` function
fn d_(&self) -> Point2 {
pt2(
self.vertex.x + self.width * self.angle.cos(),
self.vertex.y + self.width * self.angle.sin(),
)
}
fn e(&self) -> Point2 {
pt2(self.d_().x, self.d_().y - self.height)
}
fn f(&self) -> Point2 {
pt2(self.vertex.x, self.vertex.y - self.height)
}
fn g(&self) -> Point2 {
pt2(self.b().x, self.b().y - self.height)
}
// all sides draw points in clockwise order starting with vertex
fn top(&self) -> Line2 {
vec![self.vertex, self.b(), self.c(), self.d_()]
}
fn left(&self) -> Line2 {
vec![self.vertex, self.f(), self.g(), self.b()]
}
fn right(&self) -> Line2 {
vec![self.vertex, self.d_(), self.e(), self.f()]
}
pub fn w(mut self, width: f32) -> Self {
self.width = width;
self
}
pub fn h(mut self, height: f32) -> Self {
self.height = height;
self
}
pub fn d(mut self, depth: f32) -> Self {
self.depth = depth;
self
}
pub fn top_color(mut self, color: Rgba) -> Self {
self.top_color = color;
self
}
pub fn right_color(mut self, color: Rgba) -> Self {
self.right_color = color;
self
}
pub fn left_color(mut self, color: Rgba) -> Self {
self.left_color = color;
self
}
pub fn angle(mut self, radians: f32) -> Self {
self.angle = radians;
self
}
pub fn draw(&self, draw: &Draw) {
let stroke_weight = 2.;
let stroke_color = BLACK;
draw
.polygon()
.caps_round()
.join_round()
.stroke_color(stroke_color)
.stroke_weight(stroke_weight)
.color(self.left_color)
.points(self.left());
draw
.polygon()
.caps_round()
.join_round()
.stroke_color(stroke_color)
.stroke_weight(stroke_weight)
.color(self.right_color)
.points(self.right());
draw
.polygon()
.caps_round()
.join_round()
.stroke_color(stroke_color)
.stroke_weight(stroke_weight)
.color(self.top_color)
.points(self.top());
}
}
| 50,710
|
https://github.com/3182779524qq/bk-vue-cec/blob/master/src/components/date-picker/base/mixin.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
bk-vue-cec
|
3182779524qq
|
JavaScript
|
Code
| 378
| 772
|
/*
* Tencent is pleased to support the open source community by making
* 科技内在设计(T-inside) available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* 科技内在设计(T-inside) is licensed under the MIT License.
*
* License for 科技内在设计(T-inside):
*
* ---------------------------------------------------
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/**
* @file all mixin
*
* Copyright © 2020-2021 T-inside Design. All Rights Reserved. T-inside 版权所有
*/
import { clearHours } from '@/utils/date'
export default {
name: 'PanelTable',
props: {
tableDate: {
type: Date,
required: true
},
disabledDate: {
type: Function
},
selectionMode: {
type: String,
required: true
},
value: {
type: Array,
required: true
},
rangeState: {
type: Object,
default: () => ({
from: null,
to: null,
selecting: false
})
},
focusedDate: {
type: Date,
required: true
}
},
computed: {
dates () {
const { selectionMode, value, rangeState } = this
const rangeSelecting = selectionMode === 'range' && rangeState.selecting
return rangeSelecting ? [rangeState.from] : value
}
},
methods: {
handleClick (cell) {
if (cell.disabled || cell.type === 'weekLabel') {
return
}
const newDate = new Date(clearHours(cell.date))
this.$emit('pick', newDate)
this.$emit('pick-click')
},
handleMouseMove (cell) {
if (!this.rangeState.selecting) {
return
}
if (cell.disabled) {
return
}
const newDate = cell.date
this.$emit('change-range', newDate)
}
}
}
| 7,987
|
https://github.com/uk-gov-mirror/hmrc.view-external-guidance-frontend/blob/master/test/mocks/MockGuidanceService.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
hmrc.view-external-guidance-frontend
|
uk-gov-mirror
|
Scala
|
Code
| 428
| 1,460
|
/*
* Copyright 2021 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package mocks
import models.{PageEvaluationContext, PageContext}
import core.models.RequestOutcome
import org.scalamock.handlers.CallHandler
import org.scalamock.scalatest.MockFactory
import services.{ErrorStrategy, GuidanceService}
import repositories.ProcessContext
import uk.gov.hmrc.http.HeaderCarrier
import core.models.ocelot.Labels
import scala.concurrent.{ExecutionContext, Future}
import play.api.i18n.Lang
trait MockGuidanceService extends MockFactory {
val mockGuidanceService: GuidanceService = mock[GuidanceService]
object MockGuidanceService {
def retrieveAndCacheScratch(uuid: String, sessionRepoId: String): CallHandler[Future[RequestOutcome[(String,String)]]] = {
(mockGuidanceService
.retrieveAndCacheScratch(_: String, _: String)(_: HeaderCarrier, _: ExecutionContext))
.expects(uuid, *, *, *)
}
def retrieveAndCachePublished(processId: String, sessionRepoId: String): CallHandler[Future[RequestOutcome[(String,String)]]] = {
(mockGuidanceService
.retrieveAndCachePublished(_: String, _: String)(_: HeaderCarrier, _: ExecutionContext))
.expects(processId, *, *, *)
}
def retrieveAndCacheApproval(processId: String, sessionRepoId: String): CallHandler[Future[RequestOutcome[(String, String)]]] = {
(mockGuidanceService
.retrieveAndCacheApproval(_: String, _: String)(_: HeaderCarrier, _: ExecutionContext))
.expects(processId, *, *, *)
}
def retrieveAndCacheApprovalByPageUrl(url: String)(processId: String, sessionRepoId: String): CallHandler[Future[RequestOutcome[(String, String)]]] = {
(mockGuidanceService
.retrieveAndCacheApprovalByPageUrl(_: String)(_: String, _: String)(_: HeaderCarrier, _: ExecutionContext))
.expects(url, processId, *, *, *)
}
def getProcessContext(sessionId: String, processCode: String, url: String, previousPageByLink: Boolean): CallHandler[Future[RequestOutcome[ProcessContext]]] = {
(mockGuidanceService
.getProcessContext(_: String, _: String, _: String, _: Boolean)(_: ExecutionContext))
.expects(sessionId, processCode, url, previousPageByLink, *)
}
def getProcessContext(sessionId: String): CallHandler[Future[RequestOutcome[ProcessContext]]] = {
(mockGuidanceService
.getProcessContext(_: String))
.expects(sessionId)
}
def sessionRestart(processCode: String, sessionId: String): CallHandler[Future[RequestOutcome[String]]] = {
(mockGuidanceService
.sessionRestart(_: String, _: String)(_: ExecutionContext))
.expects(processCode, sessionId, *)
}
def getPageContext(pec: PageEvaluationContext, errStrategy: ErrorStrategy): CallHandler[PageContext] = {
(mockGuidanceService
.getPageContext(_: PageEvaluationContext, _: ErrorStrategy)(_: Lang))
.expects(pec, errStrategy, *)
}
def getPageContext(processId: String, url: String, previousPageByLink: Boolean, sessionId: String): CallHandler[Future[RequestOutcome[PageContext]]] = {
(mockGuidanceService
.getPageContext(_: String, _: String, _: Boolean, _: String)(_: ExecutionContext, _: Lang))
.expects(processId, url, previousPageByLink, sessionId, *, *)
}
def getPageEvaluationContext(
processId: String,
url: String,
previousPageByLink: Boolean,
sessionId: String): CallHandler[Future[RequestOutcome[PageEvaluationContext]]] = {
(mockGuidanceService
.getPageEvaluationContext(_: String, _: String, _: Boolean, _: String)(_: ExecutionContext, _: Lang))
.expects(processId, url, previousPageByLink, sessionId, *, *)
}
def validateUserResponse(pec: PageEvaluationContext, response: String): CallHandler[Option[String]] = {
(mockGuidanceService
.validateUserResponse(_: PageEvaluationContext, _: String))
.expects(pec, response)
}
def submitPage(
ctx: PageEvaluationContext,
url: String,
validatedAnswer: String,
submittedAnswer: String): CallHandler[Future[RequestOutcome[(Option[String], Labels)]]] = {
(mockGuidanceService
.submitPage(_: PageEvaluationContext, _: String, _: String, _: String)(_: ExecutionContext))
.expects(ctx, url, validatedAnswer, submittedAnswer, *)
}
def savePageState(docId: String, labels: Labels): CallHandler[Future[RequestOutcome[Unit]]] = {
(mockGuidanceService
.savePageState(_: String, _: Labels))
.expects(docId, *)
}
}
}
| 18,790
|
https://github.com/RomashkinAndrew/TrulyRandom/blob/master/TrulyRandom/DirectShow/Structs.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
TrulyRandom
|
RomashkinAndrew
|
C#
|
Code
| 1,071
| 2,677
|
using System;
using System.Drawing;
using System.Runtime.InteropServices;
// Source: AForge library
namespace TrulyRandom.DirectShow
{
[StructLayout(LayoutKind.Sequential)]
class AMMediaType : IDisposable
{
/// <summary>
/// Globally unique identifier (GUID) that specifies the major type of the media sample.
/// </summary>
public Guid MajorType;
/// <summary>
/// GUID that specifies the subtype of the media sample.
/// </summary>
public Guid SubType;
/// <summary>
/// If <b>true</b>, samples are of a fixed size.
/// </summary>
[MarshalAs(UnmanagedType.Bool)]
public bool FixedSizeSamples = true;
/// <summary>
/// If <b>true</b>, samples are compressed using temporal (interframe) compression.
/// </summary>
[MarshalAs(UnmanagedType.Bool)]
public bool TemporalCompression;
/// <summary>
/// Size of the sample in bytes. For compressed data, the value can be zero.
/// </summary>
public int SampleSize = 1;
/// <summary>
/// GUID that specifies the structure used for the format block.
/// </summary>
public Guid FormatType;
/// <summary>
/// Not used.
/// </summary>
public IntPtr unkPtr;
/// <summary>
/// Size of the format block, in bytes.
/// </summary>
public int FormatSize;
/// <summary>
/// Pointer to the format block.
/// </summary>
public IntPtr FormatPtr;
/// <summary>
/// Destroys the instance of the <see cref="AMMediaType"/> class.
/// </summary>
~AMMediaType()
{
Dispose(false);
}
/// <summary>
/// Dispose the object.
/// </summary>
public void Dispose()
{
Dispose(true);
// remove me from the Finalization queue
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose the object
/// </summary>
///
/// <param name="disposing">Indicates if disposing was initiated manually.</param>
///
protected virtual void Dispose(bool disposing)
{
if ((FormatSize != 0) && (FormatPtr != IntPtr.Zero))
{
Marshal.FreeCoTaskMem(FormatPtr);
FormatSize = 0;
}
if (unkPtr != IntPtr.Zero)
{
Marshal.Release(unkPtr);
unkPtr = IntPtr.Zero;
}
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
struct PinInfo
{
/// <summary>
/// Owning filter.
/// </summary>
public IBaseFilter Filter;
/// <summary>
/// Direction of the pin.
/// </summary>
public PinDirection Direction;
/// <summary>
/// Name of the pin.
/// </summary>
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string Name;
}
[StructLayout(LayoutKind.Sequential)]
class VideoStreamConfigCaps // VIDEO_STREAM_CONFIG_CAPS
{
public Guid Guid;
public AnalogVideoStandard VideoStandard;
public Size InputSize;
public Size MinCroppingSize;
public Size MaxCroppingSize;
public int CropGranularityX;
public int CropGranularityY;
public int CropAlignX;
public int CropAlignY;
public Size MinOutputSize;
public Size MaxOutputSize;
public int OutputGranularityX;
public int OutputGranularityY;
public int StretchTapsX;
public int StretchTapsY;
public int ShrinkTapsX;
public int ShrinkTapsY;
public long MinFrameInterval;
public long MaxFrameInterval;
public int MinBitsPerSecond;
public int MaxBitsPerSecond;
}
[StructLayout(LayoutKind.Sequential)]
class AudioStreamConfigCaps // AUDIO_STREAM_CONFIG_CAPS
{
public Guid Guid;
public ulong MinimumChannels;
public ulong MaximumChannels;
public ulong ChannelsGranularity;
public ulong MinimumBitsPerSample;
public ulong MaximumBitsPerSample;
public ulong BitsPerSampleGranularity;
public ulong MinimumSampleFrequency;
public ulong MaximumSampleFrequency;
public ulong SampleFrequencyGranularity;
}
[StructLayout(LayoutKind.Sequential)]
struct RECT
{
/// <summary>
/// Specifies the x-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Left;
/// <summary>
/// Specifies the y-coordinate of the upper-left corner of the rectangle.
/// </summary>
public int Top;
/// <summary>
/// Specifies the x-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Right;
/// <summary>
/// Specifies the y-coordinate of the lower-right corner of the rectangle.
/// </summary>
public int Bottom;
}
[StructLayout(LayoutKind.Sequential, Pack = 2)]
struct BitmapInfoHeader
{
/// <summary>
/// Specifies the number of bytes required by the structure.
/// </summary>
public int Size;
/// <summary>
/// Specifies the width of the bitmap.
/// </summary>
public int Width;
/// <summary>
/// Specifies the height of the bitmap, in pixels.
/// </summary>
public int Height;
/// <summary>
/// Specifies the number of planes for the target device. This value must be set to 1.
/// </summary>
public short Planes;
/// <summary>
/// Specifies the number of bits per pixel.
/// </summary>
public short BitCount;
/// <summary>
/// If the bitmap is compressed, this member is a <b>FOURCC</b> the specifies the compression.
/// </summary>
public int Compression;
/// <summary>
/// Specifies the size, in bytes, of the image.
/// </summary>
public int ImageSize;
/// <summary>
/// Specifies the horizontal resolution, in pixels per meter, of the target device for the bitmap.
/// </summary>
public int XPelsPerMeter;
/// <summary>
/// Specifies the vertical resolution, in pixels per meter, of the target device for the bitmap.
/// </summary>
public int YPelsPerMeter;
/// <summary>
/// Specifies the number of color indices in the color table that are actually used by the bitmap.
/// </summary>
public int ColorsUsed;
/// <summary>
/// Specifies the number of color indices that are considered important for displaying the bitmap.
/// </summary>
public int ColorsImportant;
}
[StructLayout(LayoutKind.Sequential)]
struct VideoInfoHeader
{
/// <summary>
/// <see cref="RECT"/> structure that specifies the source video window.
/// </summary>
public RECT SrcRect;
/// <summary>
/// <see cref="RECT"/> structure that specifies the destination video window.
/// </summary>
public RECT TargetRect;
/// <summary>
/// Approximate data rate of the video stream, in bits per second.
/// </summary>
public int BitRate;
/// <summary>
/// Data error rate, in bit errors per second.
/// </summary>
public int BitErrorRate;
/// <summary>
/// The desired average display time of the video frames, in 100-nanosecond units.
/// </summary>
public long AverageTimePerFrame;
/// <summary>
/// <see cref="BitmapInfoHeader"/> structure that contains color and dimension information for the video image bitmap.
/// </summary>
public BitmapInfoHeader BmiHeader;
}
[StructLayout(LayoutKind.Sequential)]
struct VideoInfoHeader2
{
/// <summary>
/// <see cref="RECT"/> structure that specifies the source video window.
/// </summary>
public RECT SrcRect;
/// <summary>
/// <see cref="RECT"/> structure that specifies the destination video window.
/// </summary>
public RECT TargetRect;
/// <summary>
/// Approximate data rate of the video stream, in bits per second.
/// </summary>
public int BitRate;
/// <summary>
/// Data error rate, in bit errors per second.
/// </summary>
public int BitErrorRate;
/// <summary>
/// The desired average display time of the video frames, in 100-nanosecond units.
/// </summary>
public long AverageTimePerFrame;
/// <summary>
/// Flags that specify how the video is interlaced.
/// </summary>
public int InterlaceFlags;
/// <summary>
/// Flag set to indicate that the duplication of the stream should be restricted.
/// </summary>
public int CopyProtectFlags;
/// <summary>
/// The X dimension of picture aspect ratio.
/// </summary>
public int PictAspectRatioX;
/// <summary>
/// The Y dimension of picture aspect ratio.
/// </summary>
public int PictAspectRatioY;
/// <summary>
/// Reserved for future use.
/// </summary>
public int Reserved1;
/// <summary>
/// Reserved for future use.
/// </summary>
public int Reserved2;
/// <summary>
/// <see cref="BitmapInfoHeader"/> structure that contains color and dimension information for the video image bitmap.
/// </summary>
public BitmapInfoHeader BmiHeader;
}
[StructLayout(LayoutKind.Sequential)]
struct WaveFormatEx
{
public short wFormatTag;
public short nChannels;
public int nSamplesPerSec;
public int nAvgBytesPerSec;
public short nBlockAlign;
public short wBitsPerSample;
public short cbSize;
}
}
| 484
|
https://github.com/Zebra/iFactr-Android/blob/master/iFactr.Droid/Cells and Tiles/FooterView.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
iFactr-Android
|
Zebra
|
C#
|
Code
| 252
| 842
|
using Android.Content;
using Android.Graphics;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using iFactr.UI;
using System;
using System.ComponentModel;
using MonoCross.Utilities;
using Color = iFactr.UI.Color;
namespace iFactr.Droid
{
public class FooterView : TextView, ISectionFooter, INotifyPropertyChanged
{
#region Constructors
[Preserve]
public FooterView()
: base(DroidFactory.MainActivity)
{
Initialize();
}
public FooterView(Context context)
: base(context)
{
Initialize();
}
[Preserve]
public FooterView(Context context, Android.Util.IAttributeSet attrs)
: base(context, attrs)
{
Initialize();
}
[Preserve]
public FooterView(Context context, Android.Util.IAttributeSet attrs, int defStyle)
: base(context, attrs, defStyle)
{
Initialize();
}
public FooterView(IntPtr javaReference, JniHandleOwnership transfer)
: base(javaReference, transfer)
{
Initialize();
}
private void Initialize()
{
base.Gravity = GravityFlags.CenterHorizontal;
}
#endregion
#region Style
public Color BackgroundColor
{
get { return _backgroundColor; }
set
{
if (_backgroundColor == value || Handle == IntPtr.Zero) return;
SetBackgroundColor(value.IsDefaultColor ? Android.Graphics.Color.Transparent : value.ToColor());
_backgroundColor = value;
this.OnPropertyChanged();
}
}
private Color _backgroundColor;
public Color ForegroundColor
{
get { return _foregroundColor; }
set
{
if (_foregroundColor == value) return;
try
{
SetTextColor(value.IsDefaultColor ? Android.Graphics.Color.Black : value.ToColor());
_foregroundColor = value;
this.OnPropertyChanged();
}
catch (Exception e)
{
Device.Log.Warn($"SetTextColor threw an {e} exception");
}
}
}
private Color _foregroundColor;
public Font Font
{
get { return _font; }
set
{
if (_font == value) return;
_font = value;
if (_font.Size > 0)
SetTextSize(Android.Util.ComplexUnitType.Sp, (float)_font.Size);
if (!string.IsNullOrEmpty(_font.Name))
SetTypeface(Typeface.Create(_font.Name, (TypefaceStyle)_font.Formatting), (TypefaceStyle)_font.Formatting);
this.OnPropertyChanged();
}
}
private Font _font;
#endregion
public IPairable Pair
{
get { return _pair; }
set
{
if (_pair != null || value == null) return;
_pair = value;
_pair.Pair = this;
this.OnPropertyChanged();
}
}
private IPairable _pair;
public event PropertyChangedEventHandler PropertyChanged;
}
}
| 37,173
|
https://github.com/ethanstrominger/website/blob/master/_sass/components/_about.scss
|
Github Open Source
|
Open Source
|
GPL-2.0-only
| 2,022
|
website
|
ethanstrominger
|
SCSS
|
Code
| 1,688
| 6,129
|
/* This page is built using a mobile first method. Plain tags apply to mobile. Breakpoints below for larger sizes. */
.header-link--about {
text-decoration: none;
font-weight: 700;
&:link,
&:visited {
color: $color-black;
}
&:hover,
&:active,
&:focus {
color: $color-red;
}
}
.donation-gif-box-shadow {
box-shadow: 0px 8px 16px rgba(0,0,0,0.12);
}
// CSS Grid
.page-content-container-grid {
display: grid;
grid-template-columns: auto;
grid-template-rows: auto;
grid-template-areas:
"content";
align-items: start;
margin-top: 20px;
scroll-behavior: smooth;
}
.grid-2-column {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: repeat(4, 1fr);
column-gap: 10px;
row-gap: 26px;
justify-items: stretch;
align-content: space-between;
}
// Makes the sticky navigation stick
.stick-it {
position: fixed;
top:45px;
left: 1070px;
}
// Style the sticky nav links
.sticky-nav li {
list-style-type: none;
position: relative;
margin-bottom: 15px;
}
// Make the active link different
.is-active {
font-weight: 700;
color:$color-black !important;
a {
font-weight: 700;
&:link,
&:visited,
&:hover,
&:active,
&:focus {
color: $color-black;
}
}
}
.is-active::before {
position: absolute;
content: "\25C0";
font-size: 10px;
margin-left: -35px;
margin-top: 5px;
}
// This adjustment is so that the page scrolls to the correct place when you hit the nav links
a.anchor {
display: block;
position: relative;
top: -75px;
visibility: hidden;
}
.last-card {
margin-bottom: 2rem;
}
.sticky-nav {
grid-area: nav;
display: none;
background: $color-white;
border: 0px solid rgba(51, 51, 51, 0.06);
border-radius: 16px;
box-shadow: 0 0 8px 0 rgba(51, 51, 51, 0.2);
overflow: hidden;
width: 250px;
padding: 35px 30px 15px 18px;
margin-top: 30px;
}
.sticky-nav-inner-grid {
display: grid;
grid-template-columns: 15px auto;
grid-template-rows: auto;
grid-template-areas:
"content";
align-items: start;
margin-top: 20px;
scroll-behavior: smooth;
}
// The content container for pages with sticky nav
.sticky-nav-content-container {
grid-area: content;
}
.page-card--about {
overflow: hidden;
border: 0 solid rgba(51, 51, 51, 0.06);
border-radius: 16px;
margin: 12px;
padding: 22px;
height: fit-content;
}
// Make the Letter page card have square corners
.page-card--ed {
box-shadow: 0 0 8px 0 rgba(51, 51, 51, 0.2);
border-radius: 0;
}
.about-us-section-header {
font-weight: 900;
font-size: 1.25rem;
cursor: pointer;
transition: 0.4s;
display: flex;
justify-content: space-between;
text-align: center;
}
.about-us-section-header:after {
content: "\221F";
float: right;
transform: rotate(-45deg);
transition: transform 0.25s ease-in;
color: rgb(250, 17, 79);
font-weight: bolder;
font-size: 24px;
}
.about-us-section-header--ED {
font-weight: 900;
font-size: 1.25rem;
transition: 0.4s;
display: flex;
justify-content: space-between;
text-align: center;
padding-bottom: inherit;
}
// This is putting NOTHING after the header. It's necessary to align it the same as the other headers
.about-us-section-header--ED:after {
content: "\2000 \2000 \2000 \2000 \2000 \2000 \2000 \2000";
float: right;
transform: rotate(-45deg);
transition: transform 0.25s ease-in;
color: rgb(250, 17, 79);
font-weight: bolder;
font-size: 24px;
}
#letterBR {
padding-left: 30px;
}
.more-less {
display: none;
}
.sec-head-img-ed {
padding: 0 25 0 0;
}
.led-closed {
margin-top: 25px;
}
.read-more {
color: $color-red;
text-align: right;
margin-right: 30px;
cursor: pointer;
}
.read-more::after {
content: "\221F";
position: absolute;
margin-left: 10px;
transform: rotate(-45deg);
color: rgb(250, 17, 79);
font-weight: bolder;
font-size: 16px;
}
.read-less {
color: $color-red;
text-align: right;
margin-right: 30px;
cursor: pointer;
}
.read-less::after {
content: "\221F";
position: absolute;
margin-left: 10px;
transform: rotate(135deg);
color: rgb(250, 17, 79);
font-weight: bolder;
font-size: 16px;
}
.au_active::after {
content: "\221F";
transform: rotate(135deg);
transition: transform 0.25s ease-in;
}
.sub-card-head {
font-size: 1.2rem;
font-weight: 600;
padding: 15px 0 10px 0;
display: flex;
align-items: center;
}
.sub-head-image {
padding-right: 10px;
}
.sub-head-text {
padding-bottom: 5px;
}
.sub-card-content {
padding-left: 10px;
margin-left: 8px;
}
.flex-container--wins {
margin-top: 40px;
}
.flex-container-row {
@media only screen and (max-width: 350px) {
margin-top: 18px;
margin-bottom: 10px;
}
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
flex-wrap: wrap;
margin-bottom: 12px;
}
.flex-container-row--partners {
justify-content: space-between;
margin-top: 25px;
& .partner-logo{
width: 100px;
margin: 12px 15px;
}
}
.border-dodgerblue {
border-left-style: solid;
border-left-width: 5px;
border-left-color: $color-dodgerblue;
}
.border-lightseagreen {
border-left-style: solid;
border-left-width: 5px;
border-left-color: $color-lightseagreen;
}
.border-orange {
border-left-style: solid;
border-left-width: 5px;
border-left-color: $color-orange;
}
.border-chocolate {
border-left-style: solid;
border-left-width: 5px;
border-left-color: $color-chocolate;
}
.border-firebrick {
border-left-style: solid;
border-left-width: 5px;
border-left-color: $color-firebrick;
}
.border-deeppink {
border-left-style: solid;
border-left-width: 5px;
border-left-color: $color-deeppink;
}
.border-mediumvioletred {
border-left-style: solid;
border-left-width: 5px;
border-left-color: $color-mediumvioletred;
}
.border-darkorchid {
border-left-style: solid;
border-left-width: 5px;
border-left-color: $color-darkorchid;
}
.border-blueviolet {
border-left-style: solid;
border-left-width: 5px;
border-left-color: $color-blueviolet;
}
// SDG Colors
.color-goldenrod-2 {
color: $color-mustard;
font-weight: 700;
}
.color-orangered {
color: $color-orangered;
font-weight: 700;
}
.color-brown {
color: $color-redpurple;
font-weight: 700;
}
.color-goldenrod-11 {
color: $color-lightorange;
font-weight: 700;
}
.color-darkolivegreen {
color: $color-darkolive;
font-weight: 700;
}
.color-teal {
color: $color-darkroyalblue;
font-weight: 700;
}
.color-midnightblue {
color: $color-midnightblue;
font-weight: 700;
}
.bold-quote {
font-weight: 700;
font-style: italic;
text-align: center;
}
.sdg-images {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
align-content: space-between;
}
.small-text {
font-size: 8pt;
}
.grid-center {
place-self: center;
}
.sdg-groups {
margin-bottom: 20px;
}
/* Clear floats after the columns */
.sdg-groups:after {
content: "";
display: table;
clear: both;
}
.sdg-column {
float: left;
}
.sdg-left {
width: 15%;
}
.sdg-right {
width: 85%;
}
// Used for aligning contents of sdg left column
.sdg-left-flex-container {
display: flex;
flex-direction: column;
align-items: center;
}
.text-bold {
font-weight: 700;
}
.text-bold--sdg {
margin: 10px 0 20px 0;
}
.top-paragraph {
padding-top: 25px;
}
.sdg-title-mobile {
display: inline;
}
.sdg-title-full {
display: none;
}
.accomplishment-title {
color: $color-red;
text-decoration: underline;
margin: 25px 0 10px 0;
font-weight: 500;
}
.accomplishment-wins {
text-decoration: none;
margin: 25px 0 10px 0;
display: flex;
justify-content: center;
font-size: 24px;
}
.accomplishment-wins img {
padding-right: 20px;
}
.accomplishment-highlights {
margin: 30px 0 0 0;
}
.eliptical {
color: #959393;
text-align: right;
}
.align-left {
text-align: left;
}
.align-center {
text-align: center;
}
.wins-cup {
padding-right: 25px;
}
.wins-card-mobile {
display: block;
width: 308px;
height: 222px;
box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.15);
border-radius: 20px;
}
.wins-card-desktop {
display: none;
}
.coming-soon {
margin-top: 18px;
}
.garcetti-mobile {
display: block;
}
.garcetti-large {
display: none;
}
// Metrics section
.small-card p {
text-align: center;
}
.metrics-image-size {
@media only screen and (max-width: 445px) {
height: 35%;
width: 35%;
}
height: 110px;
width: 120px;
}
.metrics-title {
font-size: 2rem;
text-decoration: none;
font-weight: 700;
color: $color-red;
}
.metrics-vrms-title {
font-size: 2.2rem;
text-decoration: none;
font-weight: 900;
color: $color-black;
text-align: center;
padding: 40px 0 36px 0;
}
.metrics-vrms-links {
display: flex;
flex-flow: row nowrap;
justify-content: space-evenly;
align-content: space-between;
}
.list-container-no-indent ol {
margin: 10px;
padding: 10px;
}
.donation-spacing {
margin: 0 0 40px 20px;
font-size: 18px;
}
.text-small-italic {
font-size: 15px;
font-style: italic;
}
.news-cells {
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
width: 55.733vw;
padding-bottom: 45px;
}
.image-news-container{
height: 100px;
display: flex;
align-content: center;
margin-bottom: 30px;
}
.flex-container.news-container{
align-items: center;
}
/* Below are the breakpoints and adjustments for different size monitors */
// Below tablet - 768px
@media #{$bp-below-tablet} {
.page-content-container-grid {
margin-top: 0;
}
.wins-card-mobile{
margin-left: auto;
margin-right: auto;
}
} // End below tablet
// Bigger than mobile - 480px
// @media #{$bp-mobile-up} {}
// End mobile up
// Bigger than tablet - 768px
// @media #{$bp-tablet-up} {}
//Bigger than desktop - 960px
@media #{$bp-desktop-up} {
// The next two tags turn on and off the sticky nav sidebar
.page-content-container-grid {
grid-template-columns: 996px auto;
grid-template-rows: auto;
grid-gap: 75px;
grid-template-areas:
"content nav";
margin-top: 30px
}
.sticky-nav {
display: block;
margin-right: 20px;
}
.sticky-nav-spacer-div {
grid-area: nav;
width: 250px;
}
.sticky-nav-content-container {
margin-left: 100px;
grid-area: content;
justify-self: start;
margin-top: 20px;
}
.page-card--about {
margin: 12px 12px 40px;
max-width: 896px;
padding: 60px;
}
.page-card--platform {
padding: 60px;
}
.read-more {
display: none;
}
.read-less {
display: none;
}
.last-card {
margin-bottom: 150px;
}
.about-us-section-header {
font-size: 1.5rem;
margin: 0 0 40px;
cursor: default;
justify-content: center;
}
.about-us-section-header--ED {
justify-content: center;
cursor: default;
font-size: 1.5rem;
margin: 0 0 40px;
}
.about-us-section-content {
display: block;
transition: display 0s, opacity 2.5s linear;
}
.about-us-section-header:after {
display: none;
}
.sec-head-img {
display: none;
}
.sec-head-img-ed {
display: none;
}
.line-break {
display: none;
}
.sticky-nav a {
text-decoration: none;
}
.platform-mid-section{
display: grid;
grid-template-columns: auto auto;
grid-template-rows: auto auto auto auto auto auto auto auto auto;
grid-template-areas:
"top-left top-right"
"top-left top-right"
"top-left mid-right"
"mid-left mid-right"
"mid-left low-right"
"mid-left low-right"
"bottom-left bottom-right"
"bottom-left bottom-right"
"bottom-left bottom-right"
;
column-gap: 80px;
}
.platform-sec-impact {
grid-area: top-left;
}
.platform-sec-learning {
grid-area: top right;
}
.platform-sec-diversity {
grid-area: mid-left;
@media only screen and (min-width:1306px) {
grid-row-start: 2;
margin-top: 3rem;
}
}
.platform-sec-giving {
grid-area: mid-right;
}
.platform-sec-agility {
grid-area: low-right
}
.platform-sec-scalability {
grid-area: bottom-left;
@media only screen and (min-width:1316px) {
grid-row-start: 6;
margin-top: 8rem;
}
}
.platform-sec-sustainability {
grid-area: bottom-right;
}
.flex-container-reverse {
display: flex;
flex-direction: row-reverse;
}
.flex-container {
display: flex;
flex-direction: row;
}
.sdg-left-column {
width: 40%;
margin: 30px 25px 0 0;
}
.sdg-right-column {
width: 60%;
padding-left: 10px;
}
.bottom-right-column {
width: 50%;
padding-left: 10px;
}
.top-left-column {
width: 50%;
padding-right: 10px;
}
.top-left-column--acc {
padding-right: 25px;
}
.bottom-right-column--acc {
padding-left: 25px;
}
.top-left-column--donations {
width: 45%;
}
.bottom-right-column--donations {
width: 55%;
}
.sdg-title-mobile {
display: none;
}
.sdg-title-full {
display: inline;
}
.wins-card-mobile {
display: none;
}
.wins-card-desktop {
display: block;
}
.wins-column-width-left {
width: 30%;
padding-left: 30px;
}
.wins-column-width-right {
width: 70%;
padding-left: 25px;
}
.flex-container.news-container{
flex-basis: auto;
column-gap: 2.863vw;
align-items: baseline;
margin-bottom: 67px;
}
.image-news-container{
margin-bottom: 48px;
height: 100px;
}
.news-cells {
justify-content: unset;
padding-bottom: unset;
width: 33.3%;
}
.news-cells--govtech {
margin-bottom: 75px;
}
.garcetti-mobile {
display: none;
}
.garcetti-large {
display: block;
}
} // End desktop-up
// These are to control the responsive location of the sticky nav
@media only screen and (max-width: 1321px) {
.page-content-container-grid {
grid-template-columns: auto auto;
grid-gap: 75px;
}
.stick-it {
right: 0px;
left: auto;
}
}
@media only screen and (max-width: 1171px) {
.sticky-nav-content-container {
margin-left: 10px;
}
}
@media only screen and (max-width: 1000px) {
.page-content-container-grid {
grid-gap: 23px;
}
}
.entire-quote{
margin-top: 30px;
width: 90%;
}
.quote-marks{
position: relative;
width: 20px;
display: inline-block;
vertical-align: top;
bottom: 10px;
left:-10px
}
#quote-tmc{
border-radius: 100px;
position: relative;
right: -50px;
bottom: 10px;
height: 75px;
width: 75px;
}
.mayor-cite{
position: relative;
bottom: 50px;
left: 20px;
color: $color-cement;
font-style: normal;
}
.quote-text{
position: relative;
display: inline-block;
width: 88%;
}
@media only screen and (min-width:700px){
.quote-text{
font-weight: bold;
}
.entire-quote{
position: relative;
width:93%;
left:100px;
}
#quote-tmc{
bottom: 110px;
right: 180px;
height: 100px;
width: 100px;
}
.mayor-cite{
position: relative;
left:125px;
bottom: 90px;
color: $color-cement;
font-style: normal;
}
.garcetti-quote{
position: relative;
margin-bottom: -100px;
margin-left:3vw;
}
}
@media only screen and (max-width: 960px) {
.page-content-container-grid {
grid-template-columns: none;
}
.sticky-nav-content-container {
margin-left: 0px;
}
}
| 42,975
|
https://github.com/veil-os/frontend/blob/master/src/components/DistributeContainer/DistributeContainer.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
frontend
|
veil-os
|
TypeScript
|
Code
| 566
| 2,235
|
import React, { useState } from "react";
import { config } from "../../config";
import { ButtonLg } from "../Button";
import { DistributionDashboard } from "../DistributionDashboard";
import { LayoutDark } from "../Layout";
import { NavigationBar } from "../NavigationBar";
const { DEFAULT_EXTERNAL_NULLIFIER, DEFAULT_IDENTITY_GROUP, DEFAULT_MESSAGE } = config.defaults;
interface VoucherFormProps {
externalNullifier: string;
message: string;
identityGroup: string;
setExternalNullifier: (_val: string) => void;
setMessage: (_val: string) => void;
setIdentityGroup: (_val: string) => void;
submitDistributionForm: () => void;
}
export const VoucherForm: React.FunctionComponent<VoucherFormProps> = ({
message,
externalNullifier,
identityGroup,
setExternalNullifier,
setIdentityGroup,
setMessage,
submitDistributionForm,
}) => {
return (
<div>
<ul className="grid grid-cols-1 gap-6 md:grid-cols-3">
<li className="col-span-1 flex flex-col text-center bg-white rounded-md shadow divide-y divide-gray-200">
<div className="flex-1 flex flex-col p-8">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
className="w-48 m-auto text-gray-200"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z"
/>
</svg>
<h3 className="mt-4 text-gray-900 text-lg font-medium">Identity Group ID</h3>
<dd className="text-gray-500 text-sm mb-6 max-w-xs m-auto">
Group ID of users who can generate these vouchers.
</dd>
</div>
</li>
<li className="col-span-1 flex flex-col text-center bg-white rounded-md shadow divide-y divide-gray-200">
<div className="flex-1 flex flex-col p-8">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
className="w-48 m-auto text-gray-200"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z"
/>
</svg>
<h3 className="mt-4 text-gray-900 text-lg font-medium">Topic</h3>
<dd className="text-gray-500 text-sm mb-6 max-w-xs m-auto">
Users may submit only one voucher per topic (prevents multiple submission).
</dd>
</div>
</li>
<li className="col-span-1 flex flex-col text-center bg-white rounded-md shadow divide-y divide-gray-200">
<div className="flex-1 flex flex-col p-8">
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
className="w-48 m-auto text-gray-200"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z"
/>
</svg>
<h3 className="mt-4 text-gray-900 text-lg font-medium">Message</h3>
<dd className="text-gray-500 text-sm mb-6 max-w-xs m-auto">
Additional annotation on the voucher. You may use it to distinguish different vouchers of the same topic.
</dd>
</div>
</li>
</ul>
<div className="my-4">
<label htmlFor="identity-group" className="block text-sm font-medium text-gray-200">
Identity Group ID
</label>
<div className="mt-1">
<input
value={identityGroup}
onChange={(e) => setIdentityGroup(e.target.value)}
type="text"
name="identity-group"
id="identity-group"
className="focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"
/>
</div>
</div>
<div className="my-4">
<label htmlFor="identity-group" className="block text-sm font-medium text-gray-200">
Topic
</label>
<div className="mt-1">
<input
value={externalNullifier}
onChange={(e) => setExternalNullifier(e.target.value)}
type="text"
name="identity-group"
id="identity-group"
className="focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"
/>
</div>
</div>
<div className="my-4">
<label htmlFor="identity-group" className="block text-sm font-medium text-gray-200">
Message
</label>
<div className="mt-1">
<input
value={message}
onChange={(e) => setMessage(e.target.value)}
type="text"
name="identity-group"
id="identity-group"
className="focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md"
/>
</div>
</div>
<ButtonLg onClick={submitDistributionForm}>Go To Dashboard</ButtonLg>
</div>
);
};
export const DistributeContainer: React.FunctionComponent = () => {
const [identityGroup, setIdentityGroup] = useState(DEFAULT_IDENTITY_GROUP);
const [message, setMessage] = useState(DEFAULT_MESSAGE);
const [externalNullifier, setExternalNullifier] = useState(DEFAULT_EXTERNAL_NULLIFIER);
const [showForm, setShowForm] = useState(true);
const submitDistributionForm = () => {
setShowForm(false);
};
const renderedComponent = showForm ? (
<VoucherForm
{...{
identityGroup,
message,
externalNullifier,
setMessage,
setIdentityGroup,
setExternalNullifier,
submitDistributionForm,
}}
/>
) : (
<DistributionDashboard
onBack={() => setShowForm(true)}
identityGroup={identityGroup}
message={message}
externalNullifier={externalNullifier}
loadResults={!showForm}
/>
);
return (
<LayoutDark>
<NavigationBar />
<div className="max-w-7xl mx-auto py-16 px-4 sm:px-6 lg:px-8 lg:flex lg:justify-between">
<div className="max-w-xl">
<h2 className="text-4xl font-extrabold text-white sm:text-5xl sm:tracking-tight lg:text-6xl">
<span className="block xl:inline">VEIL</span>
<span className="block text-indigo-600 xl:inline">VOUCHER</span>
</h2>
<p className="mt-5 text-xl text-gray-400">Coordinate distribution of goods, services & rights</p>
</div>
</div>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">{renderedComponent}</div>
</LayoutDark>
);
};
| 4,387
|
https://github.com/gammasoft71/Examples_Win32/blob/master/Win32.Gui/Components/Timer/CMakeLists.txt
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Examples_Win32
|
gammasoft71
|
CMake
|
Code
| 18
| 149
|
cmake_minimum_required(VERSION 3.2)
project(Timer)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /ENTRY:mainCRTStartup")
add_definitions(-DUNICODE)
add_executable(${PROJECT_NAME} WIN32 Timer.cpp)
set_target_properties(${PROJECT_NAME} PROPERTIES FOLDER "Win32.Gui/Components")
| 11,007
|
https://github.com/timzatko/feebas/blob/master/packages/desktop_app/src/app/components/screenshot-item/screenshot-item.component.ts
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
feebas
|
timzatko
|
TypeScript
|
Code
| 135
| 585
|
import { Component, ElementRef, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { Screenshots } from '../../models/screenshots';
import { ProjectService } from '../../services/project.service';
import { getScreenshotClass } from '../../scripts/screenshot';
@Component({
selector: 'app-screenshot-item',
templateUrl: './screenshot-item.component.html',
styleUrls: ['./screenshot-item.component.scss'],
})
export class ScreenshotItemComponent implements OnInit {
@Input() screenshot: Screenshots.Screenshot;
@Input() highlight = false;
@Output() open = new EventEmitter<Screenshots.Screenshot>();
constructor(public projectService: ProjectService, public elementRef: ElementRef) {}
ngOnInit() {}
get gitStatusTitle() {
return `${this.screenshot.gitStatus} (git)`;
}
get gitStatusKey() {
return this.screenshot.gitStatus.toString().toUpperCase().charAt(0);
}
get image() {
const screenshot = this.screenshot.path.diff || this.screenshot.path.truth || this.screenshot.path.current;
return this.projectService.getLocalImageBase64(screenshot);
}
getScreenshotItemClass() {
return { ...getScreenshotClass(this.screenshot.status), caption: true };
}
onLabelClick() {
this.projectService._selected.value[this.screenshot.key] = !this.projectService._selected.value[
this.screenshot.key
];
this.onCheckboxChange();
}
onScreenshotClick() {
this.open.emit(this.screenshot);
}
onCheckboxChange() {
this.projectService._selected.next(this.projectService.selected);
}
scrollIntoView() {
this.elementRef.nativeElement.scrollIntoView({ block: 'center', inline: 'center' });
}
get isCheckboxVisible() {
return this.screenshot.status !== Screenshots.Status.match;
}
}
| 30,549
|
https://github.com/JoaoMotondon/MovieSearchDemoApp/blob/master/app/src/main/java/com/motondon/moviesearchdemoapp/presenter/movies/MovieDetailsPresenter.java
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
MovieSearchDemoApp
|
JoaoMotondon
|
Java
|
Code
| 15
| 60
|
package com.motondon.moviesearchdemoapp.presenter.movies;
public interface MovieDetailsPresenter {
void loadMovieDetails(final String movieIdr);
void loadMovieCast(final String movieId);
}
| 814
|
https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/LinkListSort.java
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
Java
|
TheAlgorithms
|
Java
|
Code
| 1,541
| 2,958
|
/**
* Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
/** Program description - To sort the LinkList as per sorting technique */
package com.thealgorithms.sorts;
import java.util.*;
public class LinkListSort {
public static boolean isSorted(int[] p, int option) {
try (Scanner sc = new Scanner(System.in)) {
}
int[] a = p;
// Array is taken as input from test class
int[] b = p;
// array similar to a
int ch = option;
// Choice is choosed as any number from 1 to 3 (So the linked list will be
// sorted by Merge sort technique/Insertion sort technique/Heap sort technique)
switch (ch) {
case 1:
Task nm = new Task();
Node start = null, prev = null, fresh, ptr;
for (int i = 0; i < a.length; i++) {
// New nodes are created and values are added
fresh = new Node(); // Node class is called
fresh.val = a[i]; // Node val is stored
if (start == null)
start = fresh;
else
prev.next = fresh;
prev = fresh;
}
start = nm.sortByMergeSort(start);
// method is being called
int i = 0;
for (ptr = start; ptr != null; ptr = ptr.next) {
a[i++] = ptr.val;
// storing the sorted values in the array
}
Arrays.sort(b);
// array b is sorted and it will return true when checked with sorted list
LinkListSort uu = new LinkListSort();
return uu.compare(a, b);
// The given array and the expected array is checked if both are same then true
// is displayed else false is displayed
case 2:
Node start1 = null, prev1 = null, fresh1, ptr1;
for (int i1 = 0; i1 < a.length; i1++) {
// New nodes are created and values are added
fresh1 = new Node(); // New node is created
fresh1.val = a[i1]; // Value is stored in the value part of the node
if (start1 == null)
start1 = fresh1;
else
prev1.next = fresh1;
prev1 = fresh1;
}
Task1 kk = new Task1();
start1 = kk.sortByInsertionSort(start1);
// method is being called
int i1 = 0;
for (ptr1 = start1; ptr1 != null; ptr1 = ptr1.next) {
a[i1++] = ptr1.val;
// storing the sorted values in the array
}
LinkListSort uu1 = new LinkListSort();
// array b is not sorted and it will return false when checked with sorted list
return uu1.compare(a, b);
// The given array and the expected array is checked if both are same then true
// is displayed else false is displayed
case 3:
Task2 mm = new Task2();
Node start2 = null, prev2 = null, fresh2, ptr2;
for (int i2 = 0; i2 < a.length; i2++) {
// New nodes are created and values are added
fresh2 = new Node(); // Node class is created
fresh2.val = a[i2]; // Value is stored in the value part of the Node
if (start2 == null)
start2 = fresh2;
else
prev2.next = fresh2;
prev2 = fresh2;
}
start2 = mm.sortByHeapSort(start2);
// method is being called
int i3 = 0;
for (ptr2 = start2; ptr2 != null; ptr2 = ptr2.next) {
a[i3++] = ptr2.val;
// storing the sorted values in the array
}
Arrays.sort(b);
// array b is sorted and it will return true when checked with sorted list
LinkListSort uu2 = new LinkListSort();
return uu2.compare(a, b);
// The given array and the expected array is checked if both are same then true
// is displayed else false is displayed
default:
// default is used incase user puts a unauthorized value
System.out.println("Wrong choice");
}
// Switch case is used to call the classes as per the user requirement
return false;
}
boolean compare(int[] a, int[] b) {
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
// Both the arrays are checked for equalness. If both are equal then true is
// returned else false is returned
}
/**
* OUTPUT :
* Input - {89,56,98,123,26,75,12,40,39,68,91} is same for all the 3 classes
* Output: [12 26 39 40 56 68 75 89 91 98 123] is same for all the 3 classes
* 1st approach Time Complexity : O(n logn)
* Auxiliary Space Complexity : O(n)
* 2nd approach Time Complexity : O(n^2)
* Auxiliary Space Complexity : O(n)
* 3rd approach Time Complexity : O(n logn)
* Auxiliary Space Complexity : O(n)
*/
}
class Node {
int val;
Node next;
// Node class for creation of linklist nodes
}
class Task {
static int[] a;
public Node sortByMergeSort(Node head) {
if (head == null || head.next == null) return head;
int c = count(head);
a = new int[c];
// Array of size c is created
int i = 0;
for (Node ptr = head; ptr != null; ptr = ptr.next) {
a[i++] = ptr.val;
}
// values are stored in the array
i = 0;
task(a, 0, c - 1);
// task method will be executed
for (Node ptr = head; ptr != null; ptr = ptr.next) {
ptr.val = a[i++];
// Value is stored in the linklist after being sorted
}
return head;
}
int count(Node head) {
int c = 0;
Node ptr;
for (ptr = head; ptr != null; ptr = ptr.next) {
c++;
}
return c;
// This Method is used to count number of elements/nodes present in the linklist
// It will return a integer type value denoting the number of nodes present
}
void task(int[] n, int i, int j) {
if (i < j) {
int m = (i + j) / 2;
task(n, i, m);
task(n, m + 1, j);
task1(n, i, m, j);
// Array is halved and sent for sorting
}
}
void task1(int[] n, int s, int m, int e) {
int i = s, k = 0, j = m + 1;
int[] b = new int[e - s + 1];
while (i <= m && j <= e) {
if (n[j] >= n[i])
b[k++] = n[i++];
else
b[k++] = n[j++];
}
// Smallest number is stored after checking from both the arrays
while (i <= m) {
b[k++] = n[i++];
}
while (j <= e) {
b[k++] = n[j++];
}
for (int p = s; p <= e; p++) {
a[p] = b[p - s];
}
}
// The method task and task1 is used to sort the linklist using merge sort
}
class Task1 {
public Node sortByInsertionSort(Node head) {
if (head == null || head.next == null) return head;
int c = count(head);
int[] a = new int[c];
// Array of size c is created
a[0] = head.val;
int i;
Node ptr;
for (ptr = head.next, i = 1; ptr != null; ptr = ptr.next, i++) {
int j = i - 1;
while (j >= 0 && a[j] > ptr.val) {
// values are stored in the array
a[j + 1] = a[j];
j--;
}
a[j + 1] = ptr.val;
}
i = 0;
for (ptr = head; ptr != null; ptr = ptr.next) {
ptr.val = a[i++];
// Value is stored in the linklist after being sorted
}
return head;
}
static int count(Node head) {
Node ptr;
int c = 0;
for (ptr = head; ptr != null; ptr = ptr.next) {
c++;
}
return c;
// This Method is used to count number of elements/nodes present in the linklist
// It will return a integer type value denoting the number of nodes present
}
// The method task and task1 is used to sort the linklist using insertion sort
}
class Task2 {
static int[] a;
public Node sortByHeapSort(Node head) {
if (head == null || head.next == null) return head;
int c = count(head);
a = new int[c];
// Array of size c is created
int i = 0;
for (Node ptr = head; ptr != null; ptr = ptr.next) {
a[i++] = ptr.val;
// values are stored in the array
}
i = 0;
task(a);
for (Node ptr = head; ptr != null; ptr = ptr.next) {
ptr.val = a[i++];
// Value is stored in the linklist after being sorted
}
return head;
}
int count(Node head) {
int c = 0;
Node ptr;
for (ptr = head; ptr != null; ptr = ptr.next) {
c++;
}
return c;
// This Method is used to count number of elements/nodes present in the linklist
// It will return a integer type value denoting the number of nodes present
}
void task(int[] n) {
int k = n.length;
for (int i = k / 2 - 1; i >= 0; i--) {
task1(n, k, i);
}
for (int i = k - 1; i > 0; i--) {
int d = n[0];
n[0] = n[i];
n[i] = d;
task1(n, i, 0);
// recursive calling of task1 method
}
}
void task1(int[] n, int k, int i) {
int p = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < k && n[l] > n[p]) p = l;
if (r < k && n[r] > n[p]) p = r;
if (p != i) {
int d = n[p];
n[p] = n[i];
n[i] = d;
task1(n, k, p);
}
}
// The method task and task1 is used to sort the linklist using heap sort
}
| 2,142
|
https://github.com/cafesao/Programas_Python/blob/master/Pagamento.py
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Programas_Python
|
cafesao
|
Python
|
Code
| 219
| 542
|
# Programa para pagamento, aceitando Á vista, cartão em 2x, 3x ou mais vezes.
# Mostrando no final o desconto ou o juros e o total
nom1 = str(input('Qual seu nome?: '))
val1 = float(input('Qual o valor do produto: '))
nom2 = nom1.split()
nom2 = nom2[0]
nom2 = nom2.capitalize()
print('Digite a opção desejada para a forma de pagamento correspondente:')
print('''
[1] Opção para Dinheiro/Cheque
[2] Opção para Cartão (À Vista)
[3] Opção para Cartão (Em 2x Vezes)
[4] Opção para Cartão (Em 3x Vezes ou mais)
''')
op1 = int(input('Digite o numero da opção desejada: '))
if op1 == 1:
val2 = val1- (val1 * 0.1)
print(f'Sr.(a) {nom2} escolheu a opção de Dinheiro/Cheque\n ')
print(f'Você ira receber um desconto de 10%, ficando o valor de R${val2:.2f}')
elif op1 == 2:
val2 = val1 - (val1 * 0.05)
print(f'Sr.(a) {nom2} escolheu a opção de Cartão (À vista)\n ')
print(f'Você ira receber um desconto de 5%, ficando o valor de R${val2:.2f}')
elif op1 == 3:
print(f'Sr.(a) {nom2} escolheu a opção de Cartão (2x Vezes)\n ')
print(f'Você ira pagar o valor normal, que no caso é R${val1}')
elif op1 == 4:
val2 = val1 + (val1 * 0.2)
print(f'Sr.(a) {nom2} escolheu a opção de Cartão (3x Vezes ou mais)\n ')
print(f'Você ira receber um juros de 20%, ficando o valor de R${val2:.2f}')
| 4,505
|
https://github.com/angeleenmcw/cartoon-collections-v-000/blob/master/cartoon_collections.rb
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-public-domain, LicenseRef-scancode-unknown-license-reference
| 2,020
|
cartoon-collections-v-000
|
angeleenmcw
|
Ruby
|
Code
| 40
| 199
|
def roll_call_dwarves(dwarves)
dwarves.each_with_index do |dwarf, index|
puts "#{index+1}.#{drarf}"
end
def summon_captain_planet(planeteer_calls)
puts planeteer_calls.collect{|call| call.capitalize + "!"}
end
def long_planeteer_calls(characters)
characters.any?{|call| call.length > 4)
end
def find_the_cheese(array)
cheddar_types = ["cheddar","soup","pepper jack","oranges"]
array.each do |cheese|
if cheese_types.includes?(array[cheese])
array[cheese]
else
nil
end
end
| 27,019
|
https://github.com/BorisLechev/Programming-Basics/blob/master/Documents/Github/Programming-Fundamentals/3. Data Types and Variables/Beer Kegs/Program.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Programming-Basics
|
BorisLechev
|
C#
|
Code
| 86
| 297
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Beer_Kegs // !!!!!!!!!!
{
class Program
{
static void Main(string[] args)
{
byte n = byte.Parse(Console.ReadLine());
double volumeOfTheBiggestKeg = 0;
double tempVolume = 0;
string modelAtTheBiggestKeg = string.Empty;
for (int i = 0; i < n; i++)
{
string modelOfTheCurrentKeg = Console.ReadLine();
double radiusOfTheCurrentKeg = double.Parse(Console.ReadLine());
int heightOfTheCurrentKeg = int.Parse(Console.ReadLine());
tempVolume = Math.PI * Math.Pow(radiusOfTheCurrentKeg, 2) * heightOfTheCurrentKeg;
if (volumeOfTheBiggestKeg < tempVolume)
{
volumeOfTheBiggestKeg = tempVolume;
modelAtTheBiggestKeg = modelOfTheCurrentKeg;
}
}
Console.WriteLine(modelAtTheBiggestKeg);
}
}
}
| 7,537
|
https://github.com/gniftygnome/ductwork/blob/master/src/main/java/net/gnomecraft/ductwork/mixin/RedstoneWireBlockMixin.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
ductwork
|
gniftygnome
|
Java
|
Code
| 60
| 324
|
package net.gnomecraft.ductwork.mixin;
import net.gnomecraft.ductwork.Ductwork;
import net.gnomecraft.ductwork.collector.CollectorBlock;
import net.minecraft.block.BlockState;
import net.minecraft.block.RedstoneWireBlock;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.world.BlockView;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
@Mixin(RedstoneWireBlock.class)
public class RedstoneWireBlockMixin {
@Inject(method = "canRunOnTop", at = @At("HEAD"), cancellable = true)
private void allowWireOnDownwardCollectors(BlockView world, BlockPos pos, BlockState floor, CallbackInfoReturnable<Boolean> ci) {
if (floor.isOf(Ductwork.COLLECTOR_BLOCK) && floor.get(CollectorBlock.INTAKE) == Direction.UP) {
ci.setReturnValue(true);
}
}
}
| 37,211
|
https://github.com/qq283335746/CustomProvider/blob/master/src/TygaSoft/LiteMembershipProvider/Entities/RolesInfo.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
CustomProvider
|
qq283335746
|
C#
|
Code
| 33
| 73
|
using System;
namespace Yibi.LiteMembershipProvider.Entities
{
public partial class RolesInfo
{
public Guid ApplicationId { get; set; }
public Guid Id { get; set; }
public string Name { get; set; }
}
}
| 14,068
|
https://github.com/schattian/seatable-api-python/blob/master/demo/dateutils_test.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
seatable-api-python
|
schattian
|
Python
|
Code
| 222
| 1,037
|
from seatable_api import dateutils
# test the functions of date utils
time_str = "2020-6-15"
time_str_s = "2020-6-15 15:23:21"
time_end = "2020-5-3 13:13:13"
time_start = "2019-6-3 20:1:12"
# 1. dateutils.date
print(dateutils.date(2020, 5, 16)) # 2020-05-16
# 2. dateutils.dateadd
print(dateutils.dateadd(time_str, -2, 'years')) # 2018-06-15T00:00:00
print(dateutils.dateadd(time_str, 3, 'months')) # 2020-09-15T00:00:00
print(dateutils.dateadd(time_str_s, 44, 'minutes')) # 2020-06-15T16:07:21
print(dateutils.dateadd(time_str_s, 1000, 'days')) # 2023-03-12T15:23:21
print(dateutils.dateadd(time_str_s, 3, 'weeks')) # 2020-07-06T15:23:21
print(dateutils.dateadd(time_str_s, -3, 'hours')) # 2020-06-15T12:23:21
print(dateutils.dateadd(time_str_s, 3, 'seconds')) # 2020-06-15T15:23:24
# 3. dateutils.datediff
print(dateutils.datediff(start=time_start, end=time_end, unit='S')) # seconds 28857600
print(dateutils.datediff(start=time_start, end=time_end, unit='Y')) # years 0
print(dateutils.datediff(start=time_start, end=time_end, unit='D')) # days 334
print(dateutils.datediff(start=time_start, end=time_end, unit='H')) # hours 8009
print(dateutils.datediff(start=time_start, end=time_end, unit='M')) # months 11
print(dateutils.datediff(start=time_start, end=time_end, unit='YM')) # relative-month -1
print(dateutils.datediff(start=time_start, end=time_end, unit='MD')) # relative-days 0
# 4. dateutils.day
print(dateutils.day(time_str_s)) # 15
# 5. dateutils.days
print(dateutils.days(time_start, time_end)) # 334
# 6. dateutils.hour
print(dateutils.hour(time_start)) # 20
# 7. dateutils.hours
print(dateutils.hours(time_start, time_end)) # 8009
# 8. dateutils.minute
print(dateutils.minute(time_start)) # 1
# 9. dateutils.month
print(dateutils.month(time_str_s)) # 6
# 10. dateutils.months
print(dateutils.months(time_start, time_end)) # 11
# 11. dateutils.second
print(dateutils.second(time_str_s)) # 21
# 12. dateutils.now
print(dateutils.now()) # 2021-06-28T15:22:39.995855
# 13. dateutils.today
print(dateutils.today()) # 2021-06-28
# 14. dateutils.year
print(dateutils.year(time_start)) # 2019
# 15. dateutils.weekday
print(dateutils.isoweekday(time_start)) #1
# 16. dateutils.weeknum
print(dateutils.weeknum(time_start)) # 23
# 17. dateutils.isoweeknum
print(dateutils.isoweeknum(time_end)) # 18
# 18. dateutils.emonth
print(dateutils.emonth('2020-3-25', direction=-1)) # 2021-02-29
print(dateutils.emonth('2021-3-25', direction=1)) # 2021-04-30
print(dateutils.isoweeknum('2012-1-2')) # 1, monday
print(dateutils.weeknum('2012-1-2')) # 2, monday
| 33,263
|
https://github.com/davidgisexpert420/babylogger/blob/master/modules/dailyreports/server/controllers/dailyreports.server.controller.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
babylogger
|
davidgisexpert420
|
JavaScript
|
Code
| 191
| 643
|
'use strict';
/**
* Module dependencies.
*/
require('moment-duration-format');
var path = require('path'),
moment = require('moment'),
mongoose = require('mongoose'),
Entry = mongoose.model('Entry'),
Child = mongoose.model('Child'),
EntryDetail = mongoose.model('EntryDetail'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
async = require('async'),
_ = require('lodash');
/**
* List of Dailyreports
*/
exports.list = function(req, res) {
var child = req.child;
var startDate = new Date(req.params.startDate);
var endDate = new Date(req.params.endDate);
var entryDetailsList = [];
Entry.find({ $and: [{ child: child }, { $and: [{ date: { $gte: startDate } }, { date: { $lte: endDate } }] }] }).sort({ date: 1, created: 1 }).exec(function(err, dailyreports) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
_.each(dailyreports, function(report) {
if (report.type === 'awake') {
entryDetailsList.push(function(cb) {
EntryDetail.findOne({ awakeEntry: report._id }).sort('-_id').populate('asleepEntry').exec(function (err, detail) {
cb(err, detail);
});
});
}
});
async.parallel(entryDetailsList, function(err, results) {
var returnData = [];
_.each(dailyreports, function(data) {
data = data.toObject();
var item = results.find(function(d) { return d && d.awakeEntry.toString() === data._id.toString(); });
if (item) {
data.date.setSeconds(1);
var ms = moment(data.date, 'DD/MM/YYYY HH:mm:ss').diff(moment(item.asleepEntry.date, 'DD/MM/YYYY HH:mm:ss'));
var d = moment.duration(ms);
data.duration = d.format('d [days] h [hr] m [min]');
data.asleepEntryId = item.asleepEntry._id;
}
returnData.push(data);
});
res.jsonp(returnData);
});
}
});
};
| 20,592
|
https://github.com/Pro-YY/ezouqi/blob/master/backend/services/ezq_core/ezq_core/dispatcher.py
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
ezouqi
|
Pro-YY
|
Python
|
Code
| 61
| 226
|
from ezq_core.accessor import store_event
import ezq_core.handlers as H
async def _noop_handler(*args, **kwargs):
pass
# event handlers registration
_HANDLERS = {
'CREATE_ACCOUNT_INIT': H.create_account,
'UPDATE_ACCOUNT_INIT': H.update_account,
'UPDATE_ACCOUNT_DONE': _noop_handler,
'DELETE_ACCOUNT_INIT': H.delete_account,
}
async def dispatch(event, params, *args, **kwargs):
if event not in _HANDLERS:
print('handler not found for event: {}'.format(event))
return
await store_event(event, params)
print('# {} [stored] dispatching...'.format(event))
result = await _HANDLERS[event](params)
print('# {} [done]'.format(event))
| 48,685
|
https://github.com/lchrennew/es-triggers/blob/master/src/core/domain/events/listener-internal-error.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
es-triggers
|
lchrennew
|
JavaScript
|
Code
| 12
| 28
|
import DomainEvent from "./domain-event.js";
export default class ListenerInternalError extends DomainEvent {
}
| 11,972
|
https://github.com/muellerzr/fastrelease/blob/master/fastrelease/__init__.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
fastrelease
|
muellerzr
|
Python
|
Code
| 7
| 21
|
__version__ = "0.1.13"
from .core import *
| 33,688
|
https://github.com/MateuszKubuszok/BackupDSL/blob/master/modules/psm/src/test/scala/pl/combosolutions/backup/psm/elevation/ElevationServerImplSpec.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
BackupDSL
|
MateuszKubuszok
|
Scala
|
Code
| 73
| 232
|
package pl.combosolutions.backup.psm.elevation
import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import pl.combosolutions.backup.{ Async, Result }
import pl.combosolutions.backup.psm.programs.GenericProgram
import pl.combosolutions.backup.test.Tags.UnitTest
class ElevationServerImplSpec extends Specification with Mockito {
val server: ElevationServer = new ElevationServerImpl
"ElevationServerImpl" should {
"execute GenericPrograms passed into it" in {
// given
val program = mock[GenericProgram]
val expected = Result[GenericProgram](0, List(), List())
program.run returns (Async some expected)
// when
val result = server runRemote program
// then
result must beSome(expected)
} tag UnitTest
}
}
| 6,754
|
https://github.com/kalasour/Coding-Virtual-Reality-Games-for-Kids/blob/master/CodingVR/Assets/Scripts/Interaction_System/IHoverable.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Coding-Virtual-Reality-Games-for-Kids
|
kalasour
|
C#
|
Code
| 30
| 85
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace VHS
{
public interface IHoverable
{
string Tooltip { get; set;}
Transform TooltipTransform { get; }
void OnHoverStart(Material _hoverMat);
void OnHoverEnd();
}
}
| 34,032
|
https://github.com/bayberryan/Fluent.Ribbon/blob/master/Fluent.Ribbon/Controls/GalleryItemPlaceholder.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
Fluent.Ribbon
|
bayberryan
|
C#
|
Code
| 263
| 592
|
using System.Windows;
// ReSharper disable once CheckNamespace
namespace Fluent
{
/// <summary>
/// Represents internal class to use it in
/// GalleryPanel as placeholder for GalleryItems
/// </summary>
internal class GalleryItemPlaceholder : UIElement
{
#region Properties
/// <summary>
/// Gets the target of the placeholder
/// </summary>
public UIElement Target { get; }
public Size ArrangedSize { get; private set; }
#endregion
#region Initialization
/// <summary>
/// Constructor
/// </summary>
/// <param name="target">Target</param>
public GalleryItemPlaceholder(UIElement target)
{
this.Target = target;
}
#endregion
#region Methods
/// <summary>
/// When overridden in a derived class, measures the size in layout
/// required for child elements and determines a size for the derived class.
/// </summary>
/// <returns>
/// The size that this element determines it needs during layout,
/// based on its calculations of child element sizes.
/// </returns>
/// <param name="availableSize">The available size that this element can
/// give to child elements. Infinity can be specified as a value to
/// indicate that the element will size to whatever content is available.</param>
protected override Size MeasureCore(Size availableSize)
{
this.Target.Measure(availableSize);
return this.Target.DesiredSize;
}
/// <summary>
/// Defines the template for WPF core-level arrange layout definition.
/// </summary>
/// <param name="finalRect">
/// The final area within the parent that element should use to
/// arrange itself and its child elements.</param>
protected override void ArrangeCore(Rect finalRect)
{
base.ArrangeCore(finalRect);
// Remember arranged size to arrange
// targets in GalleryPanel lately
this.ArrangedSize = finalRect.Size;
}
#endregion
#region Debug
/* FOR DEGUG */
//protected override void OnRender(DrawingContext drawingContext)
//{
// drawingContext.DrawRectangle(null, new Pen(Brushes.Red, 1), new Rect(RenderSize));
//}
#endregion
}
}
| 33,054
|
https://github.com/hrahmadi71/MultiRefactor/blob/master/data/ganttproject/ganttproject-1.11.1/src/net/sourceforge/ganttproject/roles/RoleManagerImpl.java
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
MultiRefactor
|
hrahmadi71
|
Java
|
Code
| 308
| 1,521
|
package net.sourceforge.ganttproject.roles;
import java.util.ArrayList;
import java.util.*;
import net.sourceforge.ganttproject.language.GanttLanguage;
/**
* @author athomas
*
*/
public class RoleManagerImpl implements RoleManager {
String [] defaultRoles;
//private ArrayList myDefaultRoles = new ArrayList();
//private final ArrayList myProjectLevelRoles = new ArrayList();
private RoleSetImpl myProjectRoleSet = new RoleSetImpl();
private ArrayList myRoleSets = new ArrayList();
public RoleManagerImpl () {
clear();
myRoleSets.add(DEFAULT_ROLE_SET);
myRoleSets.add(SOFTWARE_DEVELOPMENT_ROLE_SET);
myProjectRoleSet.setEnabled(true);
SOFTWARE_DEVELOPMENT_ROLE_SET.setEnabled(false);
}
public void clear(){
myProjectRoleSet = new RoleSetImpl();
for (int i=0; i<myRoleSets.size(); i++) {
RoleSet next = (RoleSet) myRoleSets.get(i);
next.setEnabled(false);
}
myProjectRoleSet.setEnabled(true);
DEFAULT_ROLE_SET.setEnabled(true);
SOFTWARE_DEVELOPMENT_ROLE_SET.setEnabled(false);
}
public Role[] getProjectLevelRoles() {
return myProjectRoleSet.getRoles();
}
/** Add a role on the list */
public void add (int ID, String roleName){
//myProjectLevelRoles.add(newRole(ID, role));
myProjectRoleSet.createRole(roleName, ID);
}
public RoleSet[] getRoleSets() {
return (RoleSet[]) myRoleSets.toArray(new RoleSet[0]);
}
public RoleSet createRoleSet(String name) {
RoleSet result = new RoleSetImpl(name);
myRoleSets.add(result);
//System.err.println("[RoleManagerImpl] createRoleSet(): created:"+name);
return result;
}
public RoleSet getProjectRoleSet() {
return myProjectRoleSet;
}
public RoleSet getRoleSet(String rolesetName) {
RoleSet result = null;
RoleSet[] roleSets = getRoleSets();
for (int i=0; i<roleSets.length; i++) {
if (roleSets[i].getName().equals(rolesetName)) {
result = roleSets[i];
break;
}
}
return result;
}
public Role[] getEnabledRoles() {
ArrayList result = new ArrayList();
RoleSet[] roleSets = getRoleSets();
for (int i=0; i<roleSets.length; i++) {
if (roleSets[i].isEnabled()) {
result.addAll(Arrays.asList(roleSets[i].getRoles()));
}
}
result.addAll(Arrays.asList(getProjectRoleSet().getRoles()));
return (Role[]) result.toArray(new Role[0]);
}
public Role getDefaultRole() {
return DEFAULT_ROLE_SET.findRole(0);
}
public void importData(RoleManager original) {
myProjectRoleSet.importData(original.getProjectRoleSet());
RoleSet[] originalRoleSets = original.getRoleSets();
HashSet thisNames = new HashSet();
for (int i=0; i<myRoleSets.size(); i++) {
RoleSet next = (RoleSet) myRoleSets.get(i);
thisNames.add(next.getName());
}
for (int i=0; i<originalRoleSets.length; i++) {
RoleSet next = originalRoleSets[i];
if (!thisNames.contains(next.getName())) {
myRoleSets.add(next);
}
}
//myRoleSets.addAll(Arrays.asList(originalRoleSets));
}
static final RoleSetImpl SOFTWARE_DEVELOPMENT_ROLE_SET;
static final RoleSetImpl DEFAULT_ROLE_SET;
static {
GanttLanguage language=GanttLanguage.getInstance();
SOFTWARE_DEVELOPMENT_ROLE_SET = new RoleSetImpl(RoleSet.SOFTWARE_DEVELOPMENT);
// SOFTWARE_DEVELOPMENT_ROLE_SET.createRole(language.getText("resUndefined"), 0);
// SOFTWARE_DEVELOPMENT_ROLE_SET.createRole(language.getText("resProjectManager"), 1);
SOFTWARE_DEVELOPMENT_ROLE_SET.createRole(language.getText("resDeveloper"), 2);
SOFTWARE_DEVELOPMENT_ROLE_SET.createRole(language.getText("resDocWriter"), 3);
SOFTWARE_DEVELOPMENT_ROLE_SET.createRole(language.getText("resTester"), 4);
SOFTWARE_DEVELOPMENT_ROLE_SET.createRole(language.getText("resGraphicDesigner"), 5);
SOFTWARE_DEVELOPMENT_ROLE_SET.createRole(language.getText("resDocTranslator"), 6);
SOFTWARE_DEVELOPMENT_ROLE_SET.createRole(language.getText("resPackager"), 7);
SOFTWARE_DEVELOPMENT_ROLE_SET.createRole(language.getText("resAnalysis"), 8);
SOFTWARE_DEVELOPMENT_ROLE_SET.createRole(language.getText("resWebDesigner"), 9);
SOFTWARE_DEVELOPMENT_ROLE_SET.createRole(language.getText("resNoSpecificRole"), 10);
DEFAULT_ROLE_SET = new RoleSetImpl(RoleSet.DEFAULT);
DEFAULT_ROLE_SET.createRole(language.getText("resUndefined"), 0);
DEFAULT_ROLE_SET.createRole(language.getText("resProjectManager"), 1);
DEFAULT_ROLE_SET.setEnabled(true);
}
}
| 13,600
|
https://github.com/jbw/hypertonic/blob/master/test/user.spec.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
hypertonic
|
jbw
|
JavaScript
|
Code
| 92
| 361
|
const chai = require('chai');
const expect = chai.expect;
const nock = require('nock');
const test = require('./common.js');
const api = test.api;
const fitbitDomain = test.fitbitDomain;
describe('#User', () => {
beforeEach(() => {
const userProfile = require('./fixtures/user-profile.json');
nock(fitbitDomain)
.get('/1/user/-/profile.json')
.reply(200, userProfile);
const userBadges = require('./fixtures/user-badges.json');
nock(fitbitDomain)
.get('/1/user/-/badges.json')
.reply(200, userBadges);
});
after(() => {
nock.cleanAll();
});
it('should get profile', (done) => {
api.getProfile().then(json => {
expect(json.user).to.not.be.undefined;
done();
}).catch(err => {
console.log(err);
done(new Error());
});
});
it('should get badges', (done) => {
api.getBadges().then(json => {
expect(json.badges).to.not.be.undefined;
done();
}).catch(err => {
console.log(err);
done(new Error());
});
});
});
| 46,054
|
https://github.com/tvd12/ezyfox-db/blob/master/src/main/java/com/tvd12/ezyfox/db/query/Load.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
ezyfox-db
|
tvd12
|
Java
|
Code
| 79
| 263
|
/**
*
*/
package com.tvd12.ezyfox.db.query;
import java.io.Serializable;
import org.hibernate.Session;
import com.tvd12.ezyfox.db.Query;
/**
* @author tavandung12
*
*/
public class Load implements Query {
private Serializable id;
private Class<?> entityClass;
public Load() {this(null, null);}
public Load(Serializable id, Class<?> entityClass) {
this.id = id;
this.entityClass = entityClass;
}
@SuppressWarnings("unchecked")
public <T> T execute(Session session) {
return (T)session.byId(entityClass).load(id);
}
public Load id(Serializable id) {
this.id = id;
return this;
}
public Load entityClass(Class<?> entityClass) {
this.entityClass = entityClass;
return this;
}
}
| 31,855
|
https://github.com/ratiotile/StardustDevEnvironment/blob/master/3rdparty/openbw/bwapi/bwapi/BWAPI/Source/BWAPI/BWtoBWAPI.h
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
StardustDevEnvironment
|
ratiotile
|
C
|
Code
| 18
| 86
|
#pragma once
#include <BWAPI/Order.h>
#include <BWAPI/UnitType.h>
namespace BWAPI
{
extern int BWtoBWAPI_Order[Orders::Enum::MAX];
extern int AttackAnimationRestFrame[UnitTypes::Enum::MAX];
void BWtoBWAPI_init();
}
| 11,764
|
https://github.com/ceti-dev/PhysX/blob/master/physx/documentation/PhysXAPI/files/structphysx_1_1Gu_1_1NarrowPhaseParams.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
PhysX
|
ceti-dev
|
JavaScript
|
Code
| 25
| 232
|
var structphysx_1_1Gu_1_1NarrowPhaseParams =
[
[ "NarrowPhaseParams", "structphysx_1_1Gu_1_1NarrowPhaseParams.html#a7e06ecf33181a9a53ea833ee097943be", null ],
[ "mContactDistance", "structphysx_1_1Gu_1_1NarrowPhaseParams.html#a2fa12b6a67441059365d7a9da301e326", null ],
[ "mMeshContactMargin", "structphysx_1_1Gu_1_1NarrowPhaseParams.html#acf07b4938183bd0c3fcd39ead1573afb", null ],
[ "mToleranceLength", "structphysx_1_1Gu_1_1NarrowPhaseParams.html#a34aa75d0c1663e9571a50b7f4b18e3f7", null ]
];
| 14,422
|
https://github.com/acritox/infrastructure-agent/blob/master/pkg/metrics/disk_linux.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
infrastructure-agent
|
acritox
|
Go
|
Code
| 414
| 1,151
|
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// +build linux
package metrics
import (
"fmt"
"runtime/debug"
"github.com/sirupsen/logrus"
)
func (m *DiskMonitor) Sample() (result *DiskSample, err error) {
defer func() {
if panicErr := recover(); panicErr != nil {
err = fmt.Errorf("Panic in DiskMonitor.Sample: %v\nStack: %s", panicErr, debug.Stack())
}
}()
if m.storageSampler == nil {
return nil, fmt.Errorf("DiskMonitor is not properly configured with a storage sampler")
}
// make sure we don't count the sample device more than once
samples := FilterStorageSamples(m.storageSampler.Samples())
var totalUsedBytes float64
var totalFreeBytes float64
var totalBytes float64
var totalIOTime uint64
var totalReadTime uint64
var totalWriteTime uint64
var totalReads uint64
var totalWrites uint64
var readsPerSec float64
var writesPerSec float64
var elapsedSeconds float64
var elapsedMs int64
for _, ss := range samples {
totalBytes += *ss.TotalBytes
totalUsedBytes += *ss.UsedBytes
totalFreeBytes += *ss.FreeBytes
// any delta value can be nil on first pass
if ss.HasDelta {
totalIOTime += ss.IOTimeDelta
totalReadTime += ss.ReadTimeDelta
totalWriteTime += ss.WriteTimeDelta
totalReads += ss.ReadCountDelta
totalWrites += ss.WriteCountDelta
}
// time fields _should_ all be the same for a give batch of
// samples, so just take the last one
elapsedMs = ss.ElapsedSampleDeltaMs
}
syslog.WithFieldsF(func() logrus.Fields {
return logrus.Fields{
"elapsedMs": elapsedMs,
"totalReadTime": totalReadTime,
"totalWriteTime": totalWriteTime,
"totalReads": totalReads,
"totalWrites": totalWrites,
}
}).Debug("Delta storage.")
elapsedSeconds = float64(elapsedMs) / 1000
if elapsedSeconds > 0 {
readsPerSec = float64(totalReads) / elapsedSeconds
writesPerSec = float64(totalWrites) / elapsedSeconds
}
// Calculate rough utilization across whole machine
var percentUtilized float64
var readPortion float64
var writePortion float64
numDevicesForIO := len(samples)
if numDevicesForIO > 0 && elapsedMs > 0 {
percentUtilized = float64(totalIOTime) / float64(int64(numDevicesForIO)*elapsedMs) * 100
readWriteTimeDelta := totalReadTime + totalWriteTime
// Estimate which portion of the IO time was spent reading or writing
// Basically, we break down how much time was spent reading and writing
// (total R/W time, different than IO wait time).
// If the disk spent 25% of the combined R/W time reading, that means we can
// guess that read activity accounted for 25% of the total utilization percentage.
if readWriteTimeDelta > 0 {
readPortion = float64(totalReadTime) / float64(readWriteTimeDelta)
writePortion = float64(totalWriteTime) / float64(readWriteTimeDelta)
}
}
// overall used/free percentage for machine
var diskUsedPercent float64
var diskFreePercent float64
if totalBytes > 0 {
diskUsedPercent = (totalUsedBytes / totalBytes) * 100
diskFreePercent = (totalFreeBytes / totalBytes) * 100
}
result = &DiskSample{
UsedBytes: totalUsedBytes,
UsedPercent: diskUsedPercent,
FreeBytes: totalFreeBytes,
FreePercent: diskFreePercent,
TotalBytes: totalBytes,
UtilizationPercent: percentUtilized,
ReadUtilizationPercent: percentUtilized * readPortion,
WriteUtilizationPercent: percentUtilized * writePortion,
ReadsPerSec: readsPerSec,
WritesPerSec: writesPerSec,
}
return
}
| 10,832
|
https://github.com/fossabot/codewars/blob/master/kata/7 kyu/testing-1-2-3/index.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
codewars
|
fossabot
|
TypeScript
|
Code
| 17
| 42
|
function number(array: string[]): string[] {
return array.map((line, index) => `${index + 1}: ${line}`);
}
export default number;
| 2,144
|
https://github.com/tiernanmartin/NeighborhoodChangeTypology/blob/master/man/export-model.Rd
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
NeighborhoodChangeTypology
|
tiernanmartin
|
R
|
Code
| 67
| 419
|
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/export-model.R
\name{export_model_all_csv}
\alias{export_model_all_csv}
\alias{export_model_all_rds}
\alias{export_model_all_gpkg}
\alias{export_model_pdx18_gpkg}
\alias{export_model_coo16_gpkg}
\alias{export_model_coo18_gpkg}
\alias{export_model_coorev18_gpkg}
\alias{export_model_typologies_csv}
\alias{export_model_typologies_rds}
\alias{export_model_typologies_gpkg}
\title{Export Model As Files}
\usage{
export_model_all_csv(model_all, path)
export_model_all_rds(model_all, path)
export_model_all_gpkg(model_all, path)
export_model_pdx18_gpkg(model_all, path)
export_model_coo16_gpkg(model_all, path)
export_model_coo18_gpkg(model_all, path)
export_model_coorev18_gpkg(model_all, path)
export_model_typologies_csv(model_all, path)
export_model_typologies_rds(model_all, path)
export_model_typologies_gpkg(model_all, path)
}
\arguments{
\item{model_all}{desc}
\item{path}{desc}
}
\description{
Thes functions write the model object as csv files.
}
| 18,799
|
https://github.com/kovdennik/TestEngine/blob/master/src/Engine/Renderer/Shaders/Parser.hpp
|
Github Open Source
|
Open Source
|
MIT
| null |
TestEngine
|
kovdennik
|
C++
|
Code
| 5,666
| 18,209
|
// A Bison parser, made by GNU Bison 3.0.4.
// Skeleton interface for Bison LALR(1) parsers in C++
// Copyright (C) 2002-2015 Free Software Foundation, Inc.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// As a special exception, you may create a larger work that contains
// part or all of the Bison parser skeleton and distribute that work
// under terms of your choice, so long as that work isn't itself a
// parser generator using the skeleton or a modified version thereof
// as a parser skeleton. Alternatively, if you modify or redistribute
// the parser skeleton itself, you may (at your option) remove this
// special exception, which will cause the skeleton and the resulting
// Bison output files to be licensed under the GNU General Public
// License without this special exception.
// This special exception was added by the Free Software Foundation in
// version 2.2 of Bison.
/**
** \file /cygdrive/c/Users/chiap/source/repos/fromasmtodisasm/TestEngine/src/Engine/Renderer/Shaders/Parser.hpp
** Define the yy::parser class.
*/
// C++ LALR(1) parser skeleton written by Akim Demaille.
#ifndef YY_YY_CYGDRIVE_C_USERS_CHIAP_SOURCE_REPOS_FROMASMTODISASM_TESTENGINE_SRC_ENGINE_RENDERER_SHADERS_PARSER_HPP_INCLUDED
# define YY_YY_CYGDRIVE_C_USERS_CHIAP_SOURCE_REPOS_FROMASMTODISASM_TESTENGINE_SRC_ENGINE_RENDERER_SHADERS_PARSER_HPP_INCLUDED
// // "%code requires" blocks.
#line 11 "/cygdrive/c/Users/chiap/source/repos/fromasmtodisasm/TestEngine/src/Engine/Renderer/Shaders/Parser.yy" // lalr1.cc:377
#include <string>
#ifdef VULKAN_SUPPORT
#include <vulkan/vulkan.h>
#endif
class Scanner;
class Driver;
#line 53 "/cygdrive/c/Users/chiap/source/repos/fromasmtodisasm/TestEngine/src/Engine/Renderer/Shaders/Parser.hpp" // lalr1.cc:377
# include <cassert>
# include <cstdlib> // std::abort
# include <iostream>
# include <stdexcept>
# include <string>
# include <vector>
# include "stack.hh"
# include "location.hh"
#include <typeinfo>
#ifndef YYASSERT
# include <cassert>
# define YYASSERT assert
#endif
#ifndef YY_ATTRIBUTE
# if (defined __GNUC__ \
&& (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \
|| defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
# define YY_ATTRIBUTE(Spec) __attribute__(Spec)
# else
# define YY_ATTRIBUTE(Spec) /* empty */
# endif
#endif
#ifndef YY_ATTRIBUTE_PURE
# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
#endif
#if !defined _Noreturn \
&& (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
# if defined _MSC_VER && 1200 <= _MSC_VER
# define _Noreturn __declspec (noreturn)
# else
# define _Noreturn YY_ATTRIBUTE ((__noreturn__))
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(E) ((void) (E))
#else
# define YYUSE(E) /* empty */
#endif
#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 1
#endif
namespace yy {
#line 130 "/cygdrive/c/Users/chiap/source/repos/fromasmtodisasm/TestEngine/src/Engine/Renderer/Shaders/Parser.hpp" // lalr1.cc:377
/// A char[S] buffer to store and retrieve objects.
///
/// Sort of a variant, but does not keep track of the nature
/// of the stored data, since that knowledge is available
/// via the current state.
template <size_t S>
struct variant
{
/// Type of *this.
typedef variant<S> self_type;
/// Empty construction.
variant ()
: yytypeid_ (YY_NULLPTR)
{}
/// Construct and fill.
template <typename T>
variant (const T& t)
: yytypeid_ (&typeid (T))
{
YYASSERT (sizeof (T) <= S);
new (yyas_<T> ()) T (t);
}
/// Destruction, allowed only if empty.
~variant ()
{
YYASSERT (!yytypeid_);
}
/// Instantiate an empty \a T in here.
template <typename T>
T&
build ()
{
YYASSERT (!yytypeid_);
YYASSERT (sizeof (T) <= S);
yytypeid_ = & typeid (T);
return *new (yyas_<T> ()) T;
}
/// Instantiate a \a T in here from \a t.
template <typename T>
T&
build (const T& t)
{
YYASSERT (!yytypeid_);
YYASSERT (sizeof (T) <= S);
yytypeid_ = & typeid (T);
return *new (yyas_<T> ()) T (t);
}
/// Accessor to a built \a T.
template <typename T>
T&
as ()
{
YYASSERT (*yytypeid_ == typeid (T));
YYASSERT (sizeof (T) <= S);
return *yyas_<T> ();
}
/// Const accessor to a built \a T (for %printer).
template <typename T>
const T&
as () const
{
YYASSERT (*yytypeid_ == typeid (T));
YYASSERT (sizeof (T) <= S);
return *yyas_<T> ();
}
/// Swap the content with \a other, of same type.
///
/// Both variants must be built beforehand, because swapping the actual
/// data requires reading it (with as()), and this is not possible on
/// unconstructed variants: it would require some dynamic testing, which
/// should not be the variant's responsability.
/// Swapping between built and (possibly) non-built is done with
/// variant::move ().
template <typename T>
void
swap (self_type& other)
{
YYASSERT (yytypeid_);
YYASSERT (*yytypeid_ == *other.yytypeid_);
std::swap (as<T> (), other.as<T> ());
}
/// Move the content of \a other to this.
///
/// Destroys \a other.
template <typename T>
void
move (self_type& other)
{
build<T> ();
swap<T> (other);
other.destroy<T> ();
}
/// Copy the content of \a other to this.
template <typename T>
void
copy (const self_type& other)
{
build<T> (other.as<T> ());
}
/// Destroy the stored \a T.
template <typename T>
void
destroy ()
{
as<T> ().~T ();
yytypeid_ = YY_NULLPTR;
}
private:
/// Prohibit blind copies.
self_type& operator=(const self_type&);
variant (const self_type&);
/// Accessor to raw memory as \a T.
template <typename T>
T*
yyas_ ()
{
void *yyp = yybuffer_.yyraw;
return static_cast<T*> (yyp);
}
/// Const accessor to raw memory as \a T.
template <typename T>
const T*
yyas_ () const
{
const void *yyp = yybuffer_.yyraw;
return static_cast<const T*> (yyp);
}
union
{
/// Strongest alignment constraints.
long double yyalign_me;
/// A buffer large enough to store any of the semantic values.
char yyraw[S];
} yybuffer_;
/// Whether the content is built: if defined, the name of the stored type.
const std::type_info *yytypeid_;
};
/// A Bison parser.
class parser
{
public:
#ifndef YYSTYPE
/// An auxiliary type to compute the largest semantic type.
union union_type
{
// TRUE
// FALSE
// BOOL
char dummy1[sizeof(bool)];
// FLOAT
char dummy2[sizeof(float)];
// INT
char dummy3[sizeof(int)];
// IDENTIFIER
// STR
// CODEBODY
// VARNAME
char dummy4[sizeof(std::string)];
};
/// Symbol semantic values.
typedef variant<sizeof(union_type)> semantic_type;
#else
typedef YYSTYPE semantic_type;
#endif
/// Symbol locations.
typedef location location_type;
/// Syntax errors thrown from user actions.
struct syntax_error : std::runtime_error
{
syntax_error (const location_type& l, const std::string& m);
location_type location;
};
/// Tokens.
struct token
{
enum yytokentype
{
TOK_END = 0,
TOK_ASSIGN = 258,
TOK_MINUS = 259,
TOK_PLUS = 260,
TOK_STAR = 261,
TOK_SLASH = 262,
TOK_LPAREN = 263,
TOK_RPAREN = 264,
TOK_LEFTSCOPE = 265,
TOK_RIGHTSCOPE = 266,
TOK_SEMICOLON = 267,
TOK_COMMA = 268,
TOK_IDENTIFIER = 269,
TOK_TRUE = 270,
TOK_FALSE = 271,
TOK_FLOAT = 272,
TOK_INT = 273,
TOK_BOOL = 274,
TOK_STR = 275,
TOK_GLSLSHADER = 276,
TOK_HLSL10SHADER = 277,
TOK_HLSL11SHADER = 278,
TOK_CGSHADER = 279,
TOK_SAMPLER_STATE = 280,
TOK_DST_STATE = 281,
TOK_PR_STATE = 282,
TOK_COLOR_SAMPLE_STATE = 283,
TOK_RASTERIZATION_STATE = 284,
TOK_TECHNIQUE = 285,
TOK_PASS = 286,
TOK_CODEBODY = 287,
TOK_VARNAME = 288,
TOK_TEXTURERESOURCE = 289,
TOK_TEXTURERESOURCE1D = 290,
TOK_TEXTURERESOURCE2D = 291,
TOK_TEXTURERESOURCE3D = 292,
TOK_TEXTURERESOURCERECT = 293,
TOK_TEXTURERESOURCECUBE = 294,
TOK_VOID_TYPE = 295,
TOK_UNSIGNED = 296,
TOK_HIGHP = 297,
TOK_MEDIUMP = 298,
TOK_LOWP = 299,
TOK_UNIFORM = 300,
TOK_CSTBUFFER = 301,
TOK_FLOAT_TYPE = 302,
TOK_FLOAT2_TYPE = 303,
TOK_FLOAT3_TYPE = 304,
TOK_FLOAT4_TYPE = 305,
TOK_MAT2_TYPE = 306,
TOK_MAT3_TYPE = 307,
TOK_MAT4_TYPE = 308,
TOK_BOOL_TYPE = 309,
TOK_BOOL2_TYPE = 310,
TOK_BOOL3_TYPE = 311,
TOK_BOOL4_TYPE = 312,
TOK_INT_TYPE = 313,
TOK_INT2_TYPE = 314,
TOK_INT3_TYPE = 315,
TOK_INT4_TYPE = 316,
TOK_TEXTURE1D_TYPE = 317,
TOK_TEXTURE2D_TYPE = 318,
TOK_TEXTURE2DSHADOW_TYPE = 319,
TOK_TEXTURE2DRECT_TYPE = 320,
TOK_TEXTURE3D_TYPE = 321,
TOK_TEXTURECUBE_TYPE = 322,
TOK_SAMPLER1D_TYPE = 323,
TOK_SAMPLER2D_TYPE = 324,
TOK_SAMPLER2DSHADOW_TYPE = 325,
TOK_SAMPLER2DRECT_TYPE = 326,
TOK_SAMPLER3D_TYPE = 327,
TOK_SAMPLERCUBE_TYPE = 328,
TOK_EXTENSION = 329,
TOK_SEPARATE_SHADER = 330,
TOK_VERTEXPROGRAM = 331,
TOK_FRAGMENTPROGRAM = 332,
TOK_GEOMETRYPROGRAM = 333,
TOK_HULLPROGRAM = 334,
TOK_EVALPROGRAM = 335,
TOK_SHDPROFILE = 336,
TOK_SAMPLERRESOURCE = 337,
TOK_SAMPLERTEXUNIT = 338,
TOK_SETSAMPLERSTATE = 339,
TOK_SETDSTSTATE = 340,
TOK_SETRASTERIZATIONSTATE = 341,
TOK_SETCOLORSAMPLESTATE = 342,
TOK_IMAGERESOURCE = 343,
TOK_IMAGEUNIT = 344,
TOK_IMAGEACCESS = 345,
TOK_IMAGELAYER = 346,
TOK_IMAGELAYERED = 347,
TOK_WRITE_ONLY = 348,
TOK_READ_ONLY = 349,
TOK_READ_WRITE = 350,
TOK_VERTEXFORMAT = 351
};
};
/// (External) token type, as returned by yylex.
typedef token::yytokentype token_type;
/// Symbol type: an internal symbol number.
typedef int symbol_number_type;
/// The symbol type number to denote an empty symbol.
enum { empty_symbol = -2 };
/// Internal symbol number for tokens (subsumed by symbol_number_type).
typedef unsigned char token_number_type;
/// A complete symbol.
///
/// Expects its Base type to provide access to the symbol type
/// via type_get().
///
/// Provide access to semantic value and location.
template <typename Base>
struct basic_symbol : Base
{
/// Alias to Base.
typedef Base super_type;
/// Default constructor.
basic_symbol ();
/// Copy constructor.
basic_symbol (const basic_symbol& other);
/// Constructor for valueless symbols, and symbols from each type.
basic_symbol (typename Base::kind_type t, const location_type& l);
basic_symbol (typename Base::kind_type t, const bool v, const location_type& l);
basic_symbol (typename Base::kind_type t, const float v, const location_type& l);
basic_symbol (typename Base::kind_type t, const int v, const location_type& l);
basic_symbol (typename Base::kind_type t, const std::string v, const location_type& l);
/// Constructor for symbols with semantic value.
basic_symbol (typename Base::kind_type t,
const semantic_type& v,
const location_type& l);
/// Destroy the symbol.
~basic_symbol ();
/// Destroy contents, and record that is empty.
void clear ();
/// Whether empty.
bool empty () const;
/// Destructive move, \a s is emptied into this.
void move (basic_symbol& s);
/// The semantic value.
semantic_type value;
/// The location.
location_type location;
private:
/// Assignment operator.
basic_symbol& operator= (const basic_symbol& other);
};
/// Type access provider for token (enum) based symbols.
struct by_type
{
/// Default constructor.
by_type ();
/// Copy constructor.
by_type (const by_type& other);
/// The symbol type as needed by the constructor.
typedef token_type kind_type;
/// Constructor from (external) token numbers.
by_type (kind_type t);
/// Record that this symbol is empty.
void clear ();
/// Steal the symbol type from \a that.
void move (by_type& that);
/// The (internal) type number (corresponding to \a type).
/// \a empty when empty.
symbol_number_type type_get () const;
/// The token.
token_type token () const;
/// The symbol type.
/// \a empty_symbol when empty.
/// An int, not token_number_type, to be able to store empty_symbol.
int type;
};
/// "External" symbols: returned by the scanner.
typedef basic_symbol<by_type> symbol_type;
// Symbol constructors declarations.
static inline
symbol_type
make_END (const location_type& l);
static inline
symbol_type
make_ASSIGN (const location_type& l);
static inline
symbol_type
make_MINUS (const location_type& l);
static inline
symbol_type
make_PLUS (const location_type& l);
static inline
symbol_type
make_STAR (const location_type& l);
static inline
symbol_type
make_SLASH (const location_type& l);
static inline
symbol_type
make_LPAREN (const location_type& l);
static inline
symbol_type
make_RPAREN (const location_type& l);
static inline
symbol_type
make_LEFTSCOPE (const location_type& l);
static inline
symbol_type
make_RIGHTSCOPE (const location_type& l);
static inline
symbol_type
make_SEMICOLON (const location_type& l);
static inline
symbol_type
make_COMMA (const location_type& l);
static inline
symbol_type
make_IDENTIFIER (const std::string& v, const location_type& l);
static inline
symbol_type
make_TRUE (const bool& v, const location_type& l);
static inline
symbol_type
make_FALSE (const bool& v, const location_type& l);
static inline
symbol_type
make_FLOAT (const float& v, const location_type& l);
static inline
symbol_type
make_INT (const int& v, const location_type& l);
static inline
symbol_type
make_BOOL (const bool& v, const location_type& l);
static inline
symbol_type
make_STR (const std::string& v, const location_type& l);
static inline
symbol_type
make_GLSLSHADER (const location_type& l);
static inline
symbol_type
make_HLSL10SHADER (const location_type& l);
static inline
symbol_type
make_HLSL11SHADER (const location_type& l);
static inline
symbol_type
make_CGSHADER (const location_type& l);
static inline
symbol_type
make_SAMPLER_STATE (const location_type& l);
static inline
symbol_type
make_DST_STATE (const location_type& l);
static inline
symbol_type
make_PR_STATE (const location_type& l);
static inline
symbol_type
make_COLOR_SAMPLE_STATE (const location_type& l);
static inline
symbol_type
make_RASTERIZATION_STATE (const location_type& l);
static inline
symbol_type
make_TECHNIQUE (const location_type& l);
static inline
symbol_type
make_PASS (const location_type& l);
static inline
symbol_type
make_CODEBODY (const std::string& v, const location_type& l);
static inline
symbol_type
make_VARNAME (const std::string& v, const location_type& l);
static inline
symbol_type
make_TEXTURERESOURCE (const location_type& l);
static inline
symbol_type
make_TEXTURERESOURCE1D (const location_type& l);
static inline
symbol_type
make_TEXTURERESOURCE2D (const location_type& l);
static inline
symbol_type
make_TEXTURERESOURCE3D (const location_type& l);
static inline
symbol_type
make_TEXTURERESOURCERECT (const location_type& l);
static inline
symbol_type
make_TEXTURERESOURCECUBE (const location_type& l);
static inline
symbol_type
make_VOID_TYPE (const location_type& l);
static inline
symbol_type
make_UNSIGNED (const location_type& l);
static inline
symbol_type
make_HIGHP (const location_type& l);
static inline
symbol_type
make_MEDIUMP (const location_type& l);
static inline
symbol_type
make_LOWP (const location_type& l);
static inline
symbol_type
make_UNIFORM (const location_type& l);
static inline
symbol_type
make_CSTBUFFER (const location_type& l);
static inline
symbol_type
make_FLOAT_TYPE (const location_type& l);
static inline
symbol_type
make_FLOAT2_TYPE (const location_type& l);
static inline
symbol_type
make_FLOAT3_TYPE (const location_type& l);
static inline
symbol_type
make_FLOAT4_TYPE (const location_type& l);
static inline
symbol_type
make_MAT2_TYPE (const location_type& l);
static inline
symbol_type
make_MAT3_TYPE (const location_type& l);
static inline
symbol_type
make_MAT4_TYPE (const location_type& l);
static inline
symbol_type
make_BOOL_TYPE (const location_type& l);
static inline
symbol_type
make_BOOL2_TYPE (const location_type& l);
static inline
symbol_type
make_BOOL3_TYPE (const location_type& l);
static inline
symbol_type
make_BOOL4_TYPE (const location_type& l);
static inline
symbol_type
make_INT_TYPE (const location_type& l);
static inline
symbol_type
make_INT2_TYPE (const location_type& l);
static inline
symbol_type
make_INT3_TYPE (const location_type& l);
static inline
symbol_type
make_INT4_TYPE (const location_type& l);
static inline
symbol_type
make_TEXTURE1D_TYPE (const location_type& l);
static inline
symbol_type
make_TEXTURE2D_TYPE (const location_type& l);
static inline
symbol_type
make_TEXTURE2DSHADOW_TYPE (const location_type& l);
static inline
symbol_type
make_TEXTURE2DRECT_TYPE (const location_type& l);
static inline
symbol_type
make_TEXTURE3D_TYPE (const location_type& l);
static inline
symbol_type
make_TEXTURECUBE_TYPE (const location_type& l);
static inline
symbol_type
make_SAMPLER1D_TYPE (const location_type& l);
static inline
symbol_type
make_SAMPLER2D_TYPE (const location_type& l);
static inline
symbol_type
make_SAMPLER2DSHADOW_TYPE (const location_type& l);
static inline
symbol_type
make_SAMPLER2DRECT_TYPE (const location_type& l);
static inline
symbol_type
make_SAMPLER3D_TYPE (const location_type& l);
static inline
symbol_type
make_SAMPLERCUBE_TYPE (const location_type& l);
static inline
symbol_type
make_EXTENSION (const location_type& l);
static inline
symbol_type
make_SEPARATE_SHADER (const location_type& l);
static inline
symbol_type
make_VERTEXPROGRAM (const location_type& l);
static inline
symbol_type
make_FRAGMENTPROGRAM (const location_type& l);
static inline
symbol_type
make_GEOMETRYPROGRAM (const location_type& l);
static inline
symbol_type
make_HULLPROGRAM (const location_type& l);
static inline
symbol_type
make_EVALPROGRAM (const location_type& l);
static inline
symbol_type
make_SHDPROFILE (const location_type& l);
static inline
symbol_type
make_SAMPLERRESOURCE (const location_type& l);
static inline
symbol_type
make_SAMPLERTEXUNIT (const location_type& l);
static inline
symbol_type
make_SETSAMPLERSTATE (const location_type& l);
static inline
symbol_type
make_SETDSTSTATE (const location_type& l);
static inline
symbol_type
make_SETRASTERIZATIONSTATE (const location_type& l);
static inline
symbol_type
make_SETCOLORSAMPLESTATE (const location_type& l);
static inline
symbol_type
make_IMAGERESOURCE (const location_type& l);
static inline
symbol_type
make_IMAGEUNIT (const location_type& l);
static inline
symbol_type
make_IMAGEACCESS (const location_type& l);
static inline
symbol_type
make_IMAGELAYER (const location_type& l);
static inline
symbol_type
make_IMAGELAYERED (const location_type& l);
static inline
symbol_type
make_WRITE_ONLY (const location_type& l);
static inline
symbol_type
make_READ_ONLY (const location_type& l);
static inline
symbol_type
make_READ_WRITE (const location_type& l);
static inline
symbol_type
make_VERTEXFORMAT (const location_type& l);
/// Build a parser object.
parser (Scanner &scanner_yyarg, Driver &driver_yyarg);
virtual ~parser ();
/// Parse.
/// \returns 0 iff parsing succeeded.
virtual int parse ();
#if YYDEBUG
/// The current debugging stream.
std::ostream& debug_stream () const YY_ATTRIBUTE_PURE;
/// Set the current debugging stream.
void set_debug_stream (std::ostream &);
/// Type for debugging levels.
typedef int debug_level_type;
/// The current debugging level.
debug_level_type debug_level () const YY_ATTRIBUTE_PURE;
/// Set the current debugging level.
void set_debug_level (debug_level_type l);
#endif
/// Report a syntax error.
/// \param loc where the syntax error is found.
/// \param msg a description of the syntax error.
virtual void error (const location_type& loc, const std::string& msg);
/// Report a syntax error.
void error (const syntax_error& err);
private:
/// This class is not copyable.
parser (const parser&);
parser& operator= (const parser&);
/// State numbers.
typedef int state_type;
/// Generate an error message.
/// \param yystate the state where the error occurred.
/// \param yyla the lookahead token.
virtual std::string yysyntax_error_ (state_type yystate,
const symbol_type& yyla) const;
/// Compute post-reduction state.
/// \param yystate the current state
/// \param yysym the nonterminal to push on the stack
state_type yy_lr_goto_state_ (state_type yystate, int yysym);
/// Whether the given \c yypact_ value indicates a defaulted state.
/// \param yyvalue the value to check
static bool yy_pact_value_is_default_ (int yyvalue);
/// Whether the given \c yytable_ value indicates a syntax error.
/// \param yyvalue the value to check
static bool yy_table_value_is_error_ (int yyvalue);
static const signed char yypact_ninf_;
static const signed char yytable_ninf_;
/// Convert a scanner token number \a t to a symbol number.
static token_number_type yytranslate_ (token_type t);
// Tables.
// YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
// STATE-NUM.
static const signed char yypact_[];
// YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
// Performed when YYTABLE does not specify something else to do. Zero
// means the default is an error.
static const unsigned char yydefact_[];
// YYPGOTO[NTERM-NUM].
static const signed char yypgoto_[];
// YYDEFGOTO[NTERM-NUM].
static const signed char yydefgoto_[];
// YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
// positive, shift that token. If negative, reduce the rule whose
// number is the opposite. If YYTABLE_NINF, syntax error.
static const signed char yytable_[];
static const signed char yycheck_[];
// YYSTOS[STATE-NUM] -- The (internal number of the) accessing
// symbol of state STATE-NUM.
static const unsigned char yystos_[];
// YYR1[YYN] -- Symbol number of symbol that rule YYN derives.
static const unsigned char yyr1_[];
// YYR2[YYN] -- Number of symbols on the right hand side of rule YYN.
static const unsigned char yyr2_[];
/// Convert the symbol name \a n to a form suitable for a diagnostic.
static std::string yytnamerr_ (const char *n);
/// For a symbol, its name in clear.
static const char* const yytname_[];
#if YYDEBUG
// YYRLINE[YYN] -- Source line where rule number YYN was defined.
static const unsigned short int yyrline_[];
/// Report on the debug stream that the rule \a r is going to be reduced.
virtual void yy_reduce_print_ (int r);
/// Print the state stack on the debug stream.
virtual void yystack_print_ ();
// Debugging.
int yydebug_;
std::ostream* yycdebug_;
/// \brief Display a symbol type, value and location.
/// \param yyo The output stream.
/// \param yysym The symbol.
template <typename Base>
void yy_print_ (std::ostream& yyo, const basic_symbol<Base>& yysym) const;
#endif
/// \brief Reclaim the memory associated to a symbol.
/// \param yymsg Why this token is reclaimed.
/// If null, print nothing.
/// \param yysym The symbol.
template <typename Base>
void yy_destroy_ (const char* yymsg, basic_symbol<Base>& yysym) const;
private:
/// Type access provider for state based symbols.
struct by_state
{
/// Default constructor.
by_state ();
/// The symbol type as needed by the constructor.
typedef state_type kind_type;
/// Constructor.
by_state (kind_type s);
/// Copy constructor.
by_state (const by_state& other);
/// Record that this symbol is empty.
void clear ();
/// Steal the symbol type from \a that.
void move (by_state& that);
/// The (internal) type number (corresponding to \a state).
/// \a empty_symbol when empty.
symbol_number_type type_get () const;
/// The state number used to denote an empty symbol.
enum { empty_state = -1 };
/// The state.
/// \a empty when empty.
state_type state;
};
/// "Internal" symbol: element of the stack.
struct stack_symbol_type : basic_symbol<by_state>
{
/// Superclass.
typedef basic_symbol<by_state> super_type;
/// Construct an empty symbol.
stack_symbol_type ();
/// Steal the contents from \a sym to build this.
stack_symbol_type (state_type s, symbol_type& sym);
/// Assignment, needed by push_back.
stack_symbol_type& operator= (const stack_symbol_type& that);
};
/// Stack type.
typedef stack<stack_symbol_type> stack_type;
/// The stack.
stack_type yystack_;
/// Push a new state on the stack.
/// \param m a debug message to display
/// if null, no trace is output.
/// \param s the symbol
/// \warning the contents of \a s.value is stolen.
void yypush_ (const char* m, stack_symbol_type& s);
/// Push a new look ahead token on the state on the stack.
/// \param m a debug message to display
/// if null, no trace is output.
/// \param s the state
/// \param sym the symbol (for its value and location).
/// \warning the contents of \a s.value is stolen.
void yypush_ (const char* m, state_type s, symbol_type& sym);
/// Pop \a n symbols the three stacks.
void yypop_ (unsigned int n = 1);
/// Constants.
enum
{
yyeof_ = 0,
yylast_ = 129, ///< Last index in yytable_.
yynnts_ = 28, ///< Number of nonterminal symbols.
yyfinal_ = 3, ///< Termination state number.
yyterror_ = 1,
yyerrcode_ = 256,
yyntokens_ = 113 ///< Number of tokens.
};
// User arguments.
Scanner &scanner;
Driver &driver;
};
// Symbol number corresponding to token number t.
inline
parser::token_number_type
parser::yytranslate_ (token_type t)
{
static
const token_number_type
translate_table[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 98,
99, 97, 100, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
95, 96, 101, 102, 103, 104, 105, 106, 107, 108,
109, 110, 111, 112
};
const unsigned int user_token_number_max_ = 363;
const token_number_type undef_token_ = 2;
if (static_cast<int>(t) <= yyeof_)
return yyeof_;
else if (static_cast<unsigned int> (t) <= user_token_number_max_)
return translate_table[t];
else
return undef_token_;
}
inline
parser::syntax_error::syntax_error (const location_type& l, const std::string& m)
: std::runtime_error (m)
, location (l)
{}
// basic_symbol.
template <typename Base>
inline
parser::basic_symbol<Base>::basic_symbol ()
: value ()
{}
template <typename Base>
inline
parser::basic_symbol<Base>::basic_symbol (const basic_symbol& other)
: Base (other)
, value ()
, location (other.location)
{
switch (other.type_get ())
{
case 15: // TRUE
case 16: // FALSE
case 19: // BOOL
value.copy< bool > (other.value);
break;
case 17: // FLOAT
value.copy< float > (other.value);
break;
case 18: // INT
value.copy< int > (other.value);
break;
case 14: // IDENTIFIER
case 20: // STR
case 32: // CODEBODY
case 33: // VARNAME
value.copy< std::string > (other.value);
break;
default:
break;
}
}
template <typename Base>
inline
parser::basic_symbol<Base>::basic_symbol (typename Base::kind_type t, const semantic_type& v, const location_type& l)
: Base (t)
, value ()
, location (l)
{
(void) v;
switch (this->type_get ())
{
case 15: // TRUE
case 16: // FALSE
case 19: // BOOL
value.copy< bool > (v);
break;
case 17: // FLOAT
value.copy< float > (v);
break;
case 18: // INT
value.copy< int > (v);
break;
case 14: // IDENTIFIER
case 20: // STR
case 32: // CODEBODY
case 33: // VARNAME
value.copy< std::string > (v);
break;
default:
break;
}
}
// Implementation of basic_symbol constructor for each type.
template <typename Base>
parser::basic_symbol<Base>::basic_symbol (typename Base::kind_type t, const location_type& l)
: Base (t)
, value ()
, location (l)
{}
template <typename Base>
parser::basic_symbol<Base>::basic_symbol (typename Base::kind_type t, const bool v, const location_type& l)
: Base (t)
, value (v)
, location (l)
{}
template <typename Base>
parser::basic_symbol<Base>::basic_symbol (typename Base::kind_type t, const float v, const location_type& l)
: Base (t)
, value (v)
, location (l)
{}
template <typename Base>
parser::basic_symbol<Base>::basic_symbol (typename Base::kind_type t, const int v, const location_type& l)
: Base (t)
, value (v)
, location (l)
{}
template <typename Base>
parser::basic_symbol<Base>::basic_symbol (typename Base::kind_type t, const std::string v, const location_type& l)
: Base (t)
, value (v)
, location (l)
{}
template <typename Base>
inline
parser::basic_symbol<Base>::~basic_symbol ()
{
clear ();
}
template <typename Base>
inline
void
parser::basic_symbol<Base>::clear ()
{
// User destructor.
symbol_number_type yytype = this->type_get ();
basic_symbol<Base>& yysym = *this;
(void) yysym;
switch (yytype)
{
default:
break;
}
// Type destructor.
switch (yytype)
{
case 15: // TRUE
case 16: // FALSE
case 19: // BOOL
value.template destroy< bool > ();
break;
case 17: // FLOAT
value.template destroy< float > ();
break;
case 18: // INT
value.template destroy< int > ();
break;
case 14: // IDENTIFIER
case 20: // STR
case 32: // CODEBODY
case 33: // VARNAME
value.template destroy< std::string > ();
break;
default:
break;
}
Base::clear ();
}
template <typename Base>
inline
bool
parser::basic_symbol<Base>::empty () const
{
return Base::type_get () == empty_symbol;
}
template <typename Base>
inline
void
parser::basic_symbol<Base>::move (basic_symbol& s)
{
super_type::move(s);
switch (this->type_get ())
{
case 15: // TRUE
case 16: // FALSE
case 19: // BOOL
value.move< bool > (s.value);
break;
case 17: // FLOAT
value.move< float > (s.value);
break;
case 18: // INT
value.move< int > (s.value);
break;
case 14: // IDENTIFIER
case 20: // STR
case 32: // CODEBODY
case 33: // VARNAME
value.move< std::string > (s.value);
break;
default:
break;
}
location = s.location;
}
// by_type.
inline
parser::by_type::by_type ()
: type (empty_symbol)
{}
inline
parser::by_type::by_type (const by_type& other)
: type (other.type)
{}
inline
parser::by_type::by_type (token_type t)
: type (yytranslate_ (t))
{}
inline
void
parser::by_type::clear ()
{
type = empty_symbol;
}
inline
void
parser::by_type::move (by_type& that)
{
type = that.type;
that.clear ();
}
inline
int
parser::by_type::type_get () const
{
return type;
}
inline
parser::token_type
parser::by_type::token () const
{
// YYTOKNUM[NUM] -- (External) token number corresponding to the
// (internal) symbol number NUM (which must be that of a token). */
static
const unsigned short int
yytoken_number_[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 272, 273, 274,
275, 276, 277, 278, 279, 280, 281, 282, 283, 284,
285, 286, 287, 288, 289, 290, 291, 292, 293, 294,
295, 296, 297, 298, 299, 300, 301, 302, 303, 304,
305, 306, 307, 308, 309, 310, 311, 312, 313, 314,
315, 316, 317, 318, 319, 320, 321, 322, 323, 324,
325, 326, 327, 328, 329, 330, 331, 332, 333, 334,
335, 336, 337, 338, 339, 340, 341, 342, 343, 344,
345, 346, 347, 348, 349, 350, 351, 61, 59, 60,
62, 352, 353, 354, 355, 356, 357, 358, 359, 360,
361, 362, 363
};
return static_cast<token_type> (yytoken_number_[type]);
}
// Implementation of make_symbol for each symbol type.
parser::symbol_type
parser::make_END (const location_type& l)
{
return symbol_type (token::TOK_END, l);
}
parser::symbol_type
parser::make_ASSIGN (const location_type& l)
{
return symbol_type (token::TOK_ASSIGN, l);
}
parser::symbol_type
parser::make_MINUS (const location_type& l)
{
return symbol_type (token::TOK_MINUS, l);
}
parser::symbol_type
parser::make_PLUS (const location_type& l)
{
return symbol_type (token::TOK_PLUS, l);
}
parser::symbol_type
parser::make_STAR (const location_type& l)
{
return symbol_type (token::TOK_STAR, l);
}
parser::symbol_type
parser::make_SLASH (const location_type& l)
{
return symbol_type (token::TOK_SLASH, l);
}
parser::symbol_type
parser::make_LPAREN (const location_type& l)
{
return symbol_type (token::TOK_LPAREN, l);
}
parser::symbol_type
parser::make_RPAREN (const location_type& l)
{
return symbol_type (token::TOK_RPAREN, l);
}
parser::symbol_type
parser::make_LEFTSCOPE (const location_type& l)
{
return symbol_type (token::TOK_LEFTSCOPE, l);
}
parser::symbol_type
parser::make_RIGHTSCOPE (const location_type& l)
{
return symbol_type (token::TOK_RIGHTSCOPE, l);
}
parser::symbol_type
parser::make_SEMICOLON (const location_type& l)
{
return symbol_type (token::TOK_SEMICOLON, l);
}
parser::symbol_type
parser::make_COMMA (const location_type& l)
{
return symbol_type (token::TOK_COMMA, l);
}
parser::symbol_type
parser::make_IDENTIFIER (const std::string& v, const location_type& l)
{
return symbol_type (token::TOK_IDENTIFIER, v, l);
}
parser::symbol_type
parser::make_TRUE (const bool& v, const location_type& l)
{
return symbol_type (token::TOK_TRUE, v, l);
}
parser::symbol_type
parser::make_FALSE (const bool& v, const location_type& l)
{
return symbol_type (token::TOK_FALSE, v, l);
}
parser::symbol_type
parser::make_FLOAT (const float& v, const location_type& l)
{
return symbol_type (token::TOK_FLOAT, v, l);
}
parser::symbol_type
parser::make_INT (const int& v, const location_type& l)
{
return symbol_type (token::TOK_INT, v, l);
}
parser::symbol_type
parser::make_BOOL (const bool& v, const location_type& l)
{
return symbol_type (token::TOK_BOOL, v, l);
}
parser::symbol_type
parser::make_STR (const std::string& v, const location_type& l)
{
return symbol_type (token::TOK_STR, v, l);
}
parser::symbol_type
parser::make_GLSLSHADER (const location_type& l)
{
return symbol_type (token::TOK_GLSLSHADER, l);
}
parser::symbol_type
parser::make_HLSL10SHADER (const location_type& l)
{
return symbol_type (token::TOK_HLSL10SHADER, l);
}
parser::symbol_type
parser::make_HLSL11SHADER (const location_type& l)
{
return symbol_type (token::TOK_HLSL11SHADER, l);
}
parser::symbol_type
parser::make_CGSHADER (const location_type& l)
{
return symbol_type (token::TOK_CGSHADER, l);
}
parser::symbol_type
parser::make_SAMPLER_STATE (const location_type& l)
{
return symbol_type (token::TOK_SAMPLER_STATE, l);
}
parser::symbol_type
parser::make_DST_STATE (const location_type& l)
{
return symbol_type (token::TOK_DST_STATE, l);
}
parser::symbol_type
parser::make_PR_STATE (const location_type& l)
{
return symbol_type (token::TOK_PR_STATE, l);
}
parser::symbol_type
parser::make_COLOR_SAMPLE_STATE (const location_type& l)
{
return symbol_type (token::TOK_COLOR_SAMPLE_STATE, l);
}
parser::symbol_type
parser::make_RASTERIZATION_STATE (const location_type& l)
{
return symbol_type (token::TOK_RASTERIZATION_STATE, l);
}
parser::symbol_type
parser::make_TECHNIQUE (const location_type& l)
{
return symbol_type (token::TOK_TECHNIQUE, l);
}
parser::symbol_type
parser::make_PASS (const location_type& l)
{
return symbol_type (token::TOK_PASS, l);
}
parser::symbol_type
parser::make_CODEBODY (const std::string& v, const location_type& l)
{
return symbol_type (token::TOK_CODEBODY, v, l);
}
parser::symbol_type
parser::make_VARNAME (const std::string& v, const location_type& l)
{
return symbol_type (token::TOK_VARNAME, v, l);
}
parser::symbol_type
parser::make_TEXTURERESOURCE (const location_type& l)
{
return symbol_type (token::TOK_TEXTURERESOURCE, l);
}
parser::symbol_type
parser::make_TEXTURERESOURCE1D (const location_type& l)
{
return symbol_type (token::TOK_TEXTURERESOURCE1D, l);
}
parser::symbol_type
parser::make_TEXTURERESOURCE2D (const location_type& l)
{
return symbol_type (token::TOK_TEXTURERESOURCE2D, l);
}
parser::symbol_type
parser::make_TEXTURERESOURCE3D (const location_type& l)
{
return symbol_type (token::TOK_TEXTURERESOURCE3D, l);
}
parser::symbol_type
parser::make_TEXTURERESOURCERECT (const location_type& l)
{
return symbol_type (token::TOK_TEXTURERESOURCERECT, l);
}
parser::symbol_type
parser::make_TEXTURERESOURCECUBE (const location_type& l)
{
return symbol_type (token::TOK_TEXTURERESOURCECUBE, l);
}
parser::symbol_type
parser::make_VOID_TYPE (const location_type& l)
{
return symbol_type (token::TOK_VOID_TYPE, l);
}
parser::symbol_type
parser::make_UNSIGNED (const location_type& l)
{
return symbol_type (token::TOK_UNSIGNED, l);
}
parser::symbol_type
parser::make_HIGHP (const location_type& l)
{
return symbol_type (token::TOK_HIGHP, l);
}
parser::symbol_type
parser::make_MEDIUMP (const location_type& l)
{
return symbol_type (token::TOK_MEDIUMP, l);
}
parser::symbol_type
parser::make_LOWP (const location_type& l)
{
return symbol_type (token::TOK_LOWP, l);
}
parser::symbol_type
parser::make_UNIFORM (const location_type& l)
{
return symbol_type (token::TOK_UNIFORM, l);
}
parser::symbol_type
parser::make_CSTBUFFER (const location_type& l)
{
return symbol_type (token::TOK_CSTBUFFER, l);
}
parser::symbol_type
parser::make_FLOAT_TYPE (const location_type& l)
{
return symbol_type (token::TOK_FLOAT_TYPE, l);
}
parser::symbol_type
parser::make_FLOAT2_TYPE (const location_type& l)
{
return symbol_type (token::TOK_FLOAT2_TYPE, l);
}
parser::symbol_type
parser::make_FLOAT3_TYPE (const location_type& l)
{
return symbol_type (token::TOK_FLOAT3_TYPE, l);
}
parser::symbol_type
parser::make_FLOAT4_TYPE (const location_type& l)
{
return symbol_type (token::TOK_FLOAT4_TYPE, l);
}
parser::symbol_type
parser::make_MAT2_TYPE (const location_type& l)
{
return symbol_type (token::TOK_MAT2_TYPE, l);
}
parser::symbol_type
parser::make_MAT3_TYPE (const location_type& l)
{
return symbol_type (token::TOK_MAT3_TYPE, l);
}
parser::symbol_type
parser::make_MAT4_TYPE (const location_type& l)
{
return symbol_type (token::TOK_MAT4_TYPE, l);
}
parser::symbol_type
parser::make_BOOL_TYPE (const location_type& l)
{
return symbol_type (token::TOK_BOOL_TYPE, l);
}
parser::symbol_type
parser::make_BOOL2_TYPE (const location_type& l)
{
return symbol_type (token::TOK_BOOL2_TYPE, l);
}
parser::symbol_type
parser::make_BOOL3_TYPE (const location_type& l)
{
return symbol_type (token::TOK_BOOL3_TYPE, l);
}
parser::symbol_type
parser::make_BOOL4_TYPE (const location_type& l)
{
return symbol_type (token::TOK_BOOL4_TYPE, l);
}
parser::symbol_type
parser::make_INT_TYPE (const location_type& l)
{
return symbol_type (token::TOK_INT_TYPE, l);
}
parser::symbol_type
parser::make_INT2_TYPE (const location_type& l)
{
return symbol_type (token::TOK_INT2_TYPE, l);
}
parser::symbol_type
parser::make_INT3_TYPE (const location_type& l)
{
return symbol_type (token::TOK_INT3_TYPE, l);
}
parser::symbol_type
parser::make_INT4_TYPE (const location_type& l)
{
return symbol_type (token::TOK_INT4_TYPE, l);
}
parser::symbol_type
parser::make_TEXTURE1D_TYPE (const location_type& l)
{
return symbol_type (token::TOK_TEXTURE1D_TYPE, l);
}
parser::symbol_type
parser::make_TEXTURE2D_TYPE (const location_type& l)
{
return symbol_type (token::TOK_TEXTURE2D_TYPE, l);
}
parser::symbol_type
parser::make_TEXTURE2DSHADOW_TYPE (const location_type& l)
{
return symbol_type (token::TOK_TEXTURE2DSHADOW_TYPE, l);
}
parser::symbol_type
parser::make_TEXTURE2DRECT_TYPE (const location_type& l)
{
return symbol_type (token::TOK_TEXTURE2DRECT_TYPE, l);
}
parser::symbol_type
parser::make_TEXTURE3D_TYPE (const location_type& l)
{
return symbol_type (token::TOK_TEXTURE3D_TYPE, l);
}
parser::symbol_type
parser::make_TEXTURECUBE_TYPE (const location_type& l)
{
return symbol_type (token::TOK_TEXTURECUBE_TYPE, l);
}
parser::symbol_type
parser::make_SAMPLER1D_TYPE (const location_type& l)
{
return symbol_type (token::TOK_SAMPLER1D_TYPE, l);
}
parser::symbol_type
parser::make_SAMPLER2D_TYPE (const location_type& l)
{
return symbol_type (token::TOK_SAMPLER2D_TYPE, l);
}
parser::symbol_type
parser::make_SAMPLER2DSHADOW_TYPE (const location_type& l)
{
return symbol_type (token::TOK_SAMPLER2DSHADOW_TYPE, l);
}
parser::symbol_type
parser::make_SAMPLER2DRECT_TYPE (const location_type& l)
{
return symbol_type (token::TOK_SAMPLER2DRECT_TYPE, l);
}
parser::symbol_type
parser::make_SAMPLER3D_TYPE (const location_type& l)
{
return symbol_type (token::TOK_SAMPLER3D_TYPE, l);
}
parser::symbol_type
parser::make_SAMPLERCUBE_TYPE (const location_type& l)
{
return symbol_type (token::TOK_SAMPLERCUBE_TYPE, l);
}
parser::symbol_type
parser::make_EXTENSION (const location_type& l)
{
return symbol_type (token::TOK_EXTENSION, l);
}
parser::symbol_type
parser::make_SEPARATE_SHADER (const location_type& l)
{
return symbol_type (token::TOK_SEPARATE_SHADER, l);
}
parser::symbol_type
parser::make_VERTEXPROGRAM (const location_type& l)
{
return symbol_type (token::TOK_VERTEXPROGRAM, l);
}
parser::symbol_type
parser::make_FRAGMENTPROGRAM (const location_type& l)
{
return symbol_type (token::TOK_FRAGMENTPROGRAM, l);
}
parser::symbol_type
parser::make_GEOMETRYPROGRAM (const location_type& l)
{
return symbol_type (token::TOK_GEOMETRYPROGRAM, l);
}
parser::symbol_type
parser::make_HULLPROGRAM (const location_type& l)
{
return symbol_type (token::TOK_HULLPROGRAM, l);
}
parser::symbol_type
parser::make_EVALPROGRAM (const location_type& l)
{
return symbol_type (token::TOK_EVALPROGRAM, l);
}
parser::symbol_type
parser::make_SHDPROFILE (const location_type& l)
{
return symbol_type (token::TOK_SHDPROFILE, l);
}
parser::symbol_type
parser::make_SAMPLERRESOURCE (const location_type& l)
{
return symbol_type (token::TOK_SAMPLERRESOURCE, l);
}
parser::symbol_type
parser::make_SAMPLERTEXUNIT (const location_type& l)
{
return symbol_type (token::TOK_SAMPLERTEXUNIT, l);
}
parser::symbol_type
parser::make_SETSAMPLERSTATE (const location_type& l)
{
return symbol_type (token::TOK_SETSAMPLERSTATE, l);
}
parser::symbol_type
parser::make_SETDSTSTATE (const location_type& l)
{
return symbol_type (token::TOK_SETDSTSTATE, l);
}
parser::symbol_type
parser::make_SETRASTERIZATIONSTATE (const location_type& l)
{
return symbol_type (token::TOK_SETRASTERIZATIONSTATE, l);
}
parser::symbol_type
parser::make_SETCOLORSAMPLESTATE (const location_type& l)
{
return symbol_type (token::TOK_SETCOLORSAMPLESTATE, l);
}
parser::symbol_type
parser::make_IMAGERESOURCE (const location_type& l)
{
return symbol_type (token::TOK_IMAGERESOURCE, l);
}
parser::symbol_type
parser::make_IMAGEUNIT (const location_type& l)
{
return symbol_type (token::TOK_IMAGEUNIT, l);
}
parser::symbol_type
parser::make_IMAGEACCESS (const location_type& l)
{
return symbol_type (token::TOK_IMAGEACCESS, l);
}
parser::symbol_type
parser::make_IMAGELAYER (const location_type& l)
{
return symbol_type (token::TOK_IMAGELAYER, l);
}
parser::symbol_type
parser::make_IMAGELAYERED (const location_type& l)
{
return symbol_type (token::TOK_IMAGELAYERED, l);
}
parser::symbol_type
parser::make_WRITE_ONLY (const location_type& l)
{
return symbol_type (token::TOK_WRITE_ONLY, l);
}
parser::symbol_type
parser::make_READ_ONLY (const location_type& l)
{
return symbol_type (token::TOK_READ_ONLY, l);
}
parser::symbol_type
parser::make_READ_WRITE (const location_type& l)
{
return symbol_type (token::TOK_READ_WRITE, l);
}
parser::symbol_type
parser::make_VERTEXFORMAT (const location_type& l)
{
return symbol_type (token::TOK_VERTEXFORMAT, l);
}
} // yy
#line 2058 "/cygdrive/c/Users/chiap/source/repos/fromasmtodisasm/TestEngine/src/Engine/Renderer/Shaders/Parser.hpp" // lalr1.cc:377
#endif // !YY_YY_CYGDRIVE_C_USERS_CHIAP_SOURCE_REPOS_FROMASMTODISASM_TESTENGINE_SRC_ENGINE_RENDERER_SHADERS_PARSER_HPP_INCLUDED
| 32,363
|
https://github.com/AgungPrabowo/Toko-Online/blob/master/application/views/user/view_contact.php
|
Github Open Source
|
Open Source
|
MIT
| null |
Toko-Online
|
AgungPrabowo
|
PHP
|
Code
| 236
| 957
|
<?php $this->load->view($header);?>
<?php $this->load->view($menu);?>
<!-- START Big Google Maps -->
<section class="maps">
<div id="gmaps-marker" style="height:360px;"></div>
</section>
<!--/ END Big Google Maps -->
<!-- START Contact Form + Infos -->
<section class="section bgcolor-white">
<div class="container">
<!-- START Row -->
<div class="row">
<!-- START Left Section -->
<div class="col-md-9">
<!-- Form -->
<h3 class="section-title font-alt mt0">Form Kontak</h3>
<form class="form-horizontal" role="form">
<div class="form-group">
<div class="col-sm-6">
<label for="contact_name" class="control-label">Nama <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="contact_name" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="contact_email" class="control-label">Email <span class="text-danger">*</span></label>
<input type="email" class="form-control" id="contact_email" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<label for="contact_email" class="control-label">Pesan Anda <span class="text-danger">*</span></label>
<textarea class="form-control" rows="6" id="contact_message" required></textarea>
</div>
</div>
<button type="submit" class="btn btn-primary">Kirim Pesan</button>
</form>
<!--/ Form -->
<div class="mb15 visible-xs visible-sm"></div>
</div>
<!--/ END Left Section -->
<!-- START Right Section -->
<div class="col-md-3">
<!-- Address -->
<div class="pt25 mb25">
<!-- Title -->
<h4 class="section-title font-alt mt0">Alamat</h4>
<!--/ Title -->
<address>
Jl. Bukit Barisan B2 No.7<br>
Perum Permata Puri, Ngaliyan<br>
Semarang - 50189 <br>
<abbr title="Phone">P:</abbr> 0857291111300
</address>
</div>
<!--/ Address -->
<!-- Business Hour -->
<div class="pt25 mb25">
<!-- Title -->
<h4 class="section-title font-alt mt0">Jam Kerja</h4>
<!--/ Title -->
<ul class="list-unstyled">
<li><strong>Senin - Sabtu:</strong> 08.00 - 17.00</li>
<li><strong>Minggu:</strong> Tutup</li>
</ul>
</div>
<!--/ Business Hour -->
</div>
<!--/ END Right Section -->
</div>
<!--/ END Row -->
</div>
</section>
<!--/ END Contact Form + Infos -->
<?php $this->load->view($footer);?>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="<?=base_url('assets/front-end/plugins/gmaps/js/gmaps.js');?>"></script>
<script type="text/javascript" src="<?=base_url('assets/front-end/javascript/frontend/pages/contact.js');?>"></script>
| 34,506
|
https://github.com/tor-legit/rural-crowdsourcing-toolkit/blob/master/server/frontend/src/store/apis/HttpUtils.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
rural-crowdsourcing-toolkit
|
tor-legit
|
TypeScript
|
Code
| 431
| 933
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* Helper functions to interact with the backend
*/
import axios, { AxiosError } from 'axios';
import { AuthHeader } from '../../components/auth/Auth.extra';
import { ErrorBody } from './HttpResponseTypes';
/** Set axios base server URL prefix from config */
const url = process.env.REACT_APP_SERVER_URL || '';
axios.defaults.baseURL = `${url}/api_user`;
/** Send credentials with all requests */
axios.defaults.withCredentials = true;
/**
* Send a backend POST request
* @param endpoint Request endpoint
* @param obj Object to be sent with the post request
* @param headers Headers to be included
* @param files Files to be attached
*/
export async function POST<RequestType = any, ResponseType = any>(
endpoint: string,
obj: RequestType,
headers: { [id: string]: string } = {},
files?: { [id: string]: File },
): Promise<ResponseType> {
if (files === undefined) {
// If no files, send directly
const response = await axios.post<ResponseType>(endpoint, obj, { headers });
return response.data;
} else {
// If files, send multipart request
const data = new FormData();
data.append('data', JSON.stringify(obj));
Object.entries(files).forEach(([name, file]) => {
data.append(name, file);
});
const response = await axios.post<ResponseType>(endpoint, data, {
headers: { 'Content-Type': 'multipart/form-data', ...headers },
});
return response.data;
}
}
/**
* Send a PUT request to the backend
* @param endpoint Request endpoint
* @param obj Object to be sent with request
* @param files Files to be attached
*/
export async function PUT<RequestType = any, ResponseType = any>(
endpoint: string,
obj: RequestType,
files?: { [id: string]: File },
headers?: AuthHeader,
): Promise<ResponseType> {
if (files === undefined) {
// If no files, send directly
const response = await axios.put<ResponseType>(endpoint, obj, { headers });
return response.data;
} else {
// If files, send multipart request
const data = new FormData();
data.append('data', JSON.stringify(obj));
Object.entries(files).forEach(([name, file]) => {
data.append(name, file);
});
const response = await axios.put<ResponseType>(endpoint, data, {
headers: { 'Content-Type': 'multipart/form-data' },
});
return response.data;
}
}
/**
* Send a GET request to the backend
* @param endpoint Request end point
* @param params Query parameters to be sent with the request
*/
export async function GET<ParamsType = any, ResponseType = any>(
endpoint: string,
params?: ParamsType,
headers?: AuthHeader,
): Promise<ResponseType> {
const response = await axios.get<ResponseType>(endpoint, { params, headers });
return response.data;
}
/**
* Handle error from axios request
* @param err Exception error object
*/
export function handleError(err: any) {
if (err.isAxiosError) {
const axiosErr = err as AxiosError<ErrorBody>;
const messages = axiosErr.response
? axiosErr.response.data.messages
: ['Your internet connection down or server down'];
return messages;
} else {
return ['Your internet connection down or server down'];
}
}
| 29,044
|
https://github.com/progressive-identity/ref-python/blob/master/src/py/test_00.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ref-python
|
progressive-identity
|
Python
|
Code
| 3
| 13
|
import test_datetime
test_datetime.patch()
| 11,733
|
https://github.com/NL628/USACO/blob/master/18JanS1.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
USACO
|
NL628
|
C++
|
Code
| 295
| 798
|
// COMPETITION: USACO
// NAME: 2018JanS1, Lifeguards
// DATE: November 30, 2018
// STATUS: Finished
#include <bits/stdc++.h>
using namespace std;
typedef pair<double, double> pd;
typedef pair<int, int> pi;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pi> vpi;
#define min3(a, b, c) min(a, min(b, c))
#define max3(a, b, c) max(a, max(b, c))
#define sz(x) (int)(x).size()
#define mp make_pair
#define pb push_back
#define f first
#define s second
const double PI = 4 * atan(1);
const int MOD = 1000000007;
const ll LINF = 1ll << 60;
const int INF = 1 << 30;
ofstream fout ("lifeguards.out");
ifstream fin ("lifeguards.in");
int N;
pair<ll, ll> g[100005];
void init()
{
fin >> N;
for (int i = 0; i < N; i++) {
fin >> g[i].f >> g[i].s;
}
sort(g, g + N);
}
ll total()
{
stack<pair<ll, ll>> s;
s.push(g[0]);
for (int i = 1; i < N; i++) {
pair<ll, ll> top = s.top();
if (top.s < g[i].f)
s.push(g[i]);
else if (top.s < g[i].s) {
top.s = g[i].s;
s.pop();
s.push(top);
}
}
ll tot = 0;
while (!s.empty()) {
pair<ll, ll> t = s.top();
tot += t.s - t.f;
s.pop();
}
return tot;
}
ll lose()
{
set<int> s;
map<int, vi> m;
for (int i = 0; i < N; i++) {
m[g[i].f].pb(i);
m[g[i].s].pb(i);
}
vector<int> ans(N, 0);
int pt = m.begin()->first;
for (auto a : m) {
int t = a.f;
if (s.size() == 1) {
ans[*s.begin()] += t - pt;
}
for (int i : a.s) {
auto it = s.find(i);
if (it == s.end()) {
s.insert(i);
}
else {
s.erase(it);
}
}
pt = t;
}
return *min_element(ans.begin(), ans.end());
}
int main()
{
init();
ll tot = total();
ll ans = lose();
fout << tot - ans << endl;
}
| 20,923
|
https://github.com/codierpro/vue_to_do_app/blob/master/src/components/ToDo.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
vue_to_do_app
|
codierpro
|
Vue
|
Code
| 294
| 1,034
|
<template>
<div id="app">
<div class="ToDo">
<img class="Logo" :src="logo" alt="Vue logo" />
<h1 class="ToDo-Header">Vue To Do</h1>
<div class="ToDo-Container">
<div class="ToDo-Content">
<ToDoItem v-for="item in list" :item="item" @delete="onDeleteItem" :key="item.id" />
</div>
<input type="text" v-model="todo" v-on:keyup.enter="createNewToDoItem" />
<div class="ToDo-Add" @click="createNewToDoItem()">+</div>
</div>
</div>
</div>
</template>
<script>
import ToDoItem from "./ToDoItem.vue";
import Logo from "../assets/logo.png";
export default {
name: "to-do",
components: {
ToDoItem
},
data() {
return {
list: [{ id: 1, text: "clean the house" }, { id: 2, text: "buy milk" }],
todo: "",
logo: Logo
};
},
methods: {
createNewToDoItem() {
//validate todo
if (!this.todo) {
alert("Please enter a todo!");
return;
}
const newId = Math.max.apply(null, this.list.map(t => t.id)) + 1;
this.list.push({ id: newId, text: this.todo });
this.todo = "";
},
onDeleteItem(todo) {
this.list = this.list.filter(item => item !== todo);
}
}
};
</script>
<style>
body {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, Helvetica,
Arial, sans-serif;
background: linear-gradient(#dcaeff, #ff6a3d);
height: auto;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.Logo {
width: 50px;
position: relative;
top: 50px;
}
.ToDo {
text-align: center;
border: 1px solid white;
width: 80vw;
height: auto;
box-shadow: 2px 2px 8px 0px rgba(0, 0, 0, 0.3);
background: #fdfdfd;
padding-bottom: 60px;
margin: 40px auto;
}
.ToDo-Header {
color: black;
font-family: -apple-system, BlinkMacSystemFont, Helvetica Neue, Helvetica,
Arial, sans-serif;
font-weight: 400;
text-transform: uppercase;
margin: 70px auto 30px;
}
.ToDo-Add {
color: white;
font-size: 2em;
width: 0.5em;
height: 0.5em;
display: flex;
justify-content: center;
align-items: center;
padding: 15px;
cursor: pointer;
background: #73ff73;
border-radius: 10px;
box-shadow: 1px 1px 1px #47a947;
margin: 20px auto 0;
}
.ToDo-Add:hover {
box-shadow: none;
margin-top: 21px;
margin-left: calc(auto + 1px);
}
.ToDo-Container {
width: 80%;
margin: 0 auto;
}
input {
width: 60%;
padding: 10px;
font-size: 1em;
margin: 10px auto;
box-shadow: 1px 3px 20px 0px rgba(0, 0, 0, 0.3);
}
</style>
| 50,073
|
https://github.com/hukl/rstats/blob/master/c_reference_sources/rtruncnorm.c
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
rstats
|
hukl
|
C
|
Code
| 872
| 2,351
|
/*
* rtruncnorm.c - Random truncated normal number generator.
*
* Authors:
* Björn Bornkamp <bornkamp@statistik.tu-dortmund.de>
* Olaf Mersmann <olafm@statistik.uni-dortmund.de>
*/
#include <R.h>
#include <Rdefines.h>
#include <Rmath.h>
#include <Rinternals.h>
#include <R_ext/Applic.h>
#include <float.h>
#include "sexp_macros.h"
#define ALLOC_REAL_VECTOR(S, D, N) \
SEXP S; \
PROTECT(S = allocVector(REALSXP, N)); \
double *D = REAL(S);
#ifndef MAX
#define MAX(A, B) ((A>B)?(A):(B))
#endif
#include <R.h>
#include <Rdefines.h>
#include <Rmath.h>
#include <Rinternals.h>
#include <R_ext/Lapack.h>
#include <R_ext/BLAS.h>
#include <R_ext/Applic.h>
#ifdef DEBUG
#define SAMPLER_DEBUG(N, A, B) Rprintf("%8s(%f, %f)\n", N, A, B)
#else
#define SAMPLER_DEBUG(N, A, B)
#endif
static const double t1 = 0.15;
static const double t2 = 2.18;
static const double t3 = 0.725;
static const double t4 = 0.45;
/* Exponential rejection sampling (a,inf) */
static R_INLINE double ers_a_inf(double a) {
SAMPLER_DEBUG("ers_a_inf", a, R_PosInf);
const double ainv = 1.0 / a;
double x, rho;
do{
x = rexp(ainv) + a; /* rexp works with 1/lambda */
rho = exp(-0.5 * pow((x - a), 2));
} while (runif(0, 1) > rho);
return x;
}
/* Exponential rejection sampling (a,b) */
static R_INLINE double ers_a_b(double a, double b) {
SAMPLER_DEBUG("ers_a_b", a, b);
const double ainv = 1.0 / a;
double x, rho;
do{
x = rexp(ainv) + a; /* rexp works with 1/lambda */
rho = exp(-0.5 * pow((x-a), 2));
} while (runif(0, 1) > rho || x > b);
return x;
}
/* Normal rejection sampling (a,b) */
static R_INLINE double nrs_a_b(double a, double b){
SAMPLER_DEBUG("nrs_a_b", a, b);
double x = -DBL_MAX;
while(x < a || x > b){
x = rnorm(0, 1);
}
return x;
}
/* Normal rejection sampling (a,inf) */
static R_INLINE double nrs_a_inf(double a){
SAMPLER_DEBUG("nrs_a_inf", a, R_PosInf);
double x = -DBL_MAX;
while(x < a){
x = rnorm(0, 1);
}
return x;
}
/* Half-normal rejection sampling */
double hnrs_a_b(double a, double b){
SAMPLER_DEBUG("hnrs_a_b", a, b);
double x = a - 1.0;
while(x < a || x > b) {
x = rnorm(0, 1);
x = fabs(x);
}
return x;
}
/* Uniform rejection sampling */
static R_INLINE double urs_a_b(double a, double b){
SAMPLER_DEBUG("urs_a_b", a, b);
const double phi_a = dnorm(a, 0.0, 1.0, FALSE);
double x = 0.0, u = 0.0;
/* Upper bound of normal density on [a, b] */
const double ub = a < 0 && b > 0 ? M_1_SQRT_2PI : phi_a;
do{
x = runif(a, b);
} while (runif(0, 1) * ub > dnorm(x,0,1,0));
return x;
}
/* Previously this was refered to as type 1 sampling: */
static inline double r_lefttruncnorm(double a, double mean, double sd) {
const double alpha = (a - mean) / sd;
if (alpha < t4) {
return mean + sd * nrs_a_inf(alpha);
} else {
return mean + sd * ers_a_inf(alpha);
}
}
static R_INLINE double r_righttruncnorm(double b, double mean, double sd) {
const double beta = (b - mean) / sd;
/* Exploit symmetry: */
return mean - sd * r_lefttruncnorm(-beta, 0.0, 1.0);
}
static R_INLINE double r_truncnorm(double a, double b, double mean, double sd) {
const double alpha = (a - mean) / sd;
const double beta = (b - mean) / sd;
const double phi_a = dnorm(alpha, 0.0, 1.0, FALSE);
const double phi_b = dnorm(beta, 0.0, 1.0, FALSE);
if (beta <= alpha) {
return NA_REAL;
} else if (alpha <= 0 && 0 <= beta) { /* 2 */
if (phi_a <= t1 || phi_b <= t1) { /* 2 (a) */
return mean + sd * nrs_a_b(alpha, beta);
} else { /* 2 (b) */
return mean + sd * urs_a_b(alpha, beta);
}
} else if (alpha > 0) { /* 3 */
if (phi_a / phi_b <= t2) { /* 3 (a) */
return mean + sd * urs_a_b(alpha, beta);
} else {
if (alpha < t3) { /* 3 (b) */
return mean + sd * hnrs_a_b(alpha, beta);
} else { /* 3 (c) */
return mean + sd * ers_a_b(alpha, beta);
}
}
} else { /* 3s */
if (phi_b / phi_a <= t2) { /* 3s (a) */
return mean - sd * urs_a_b(-beta, -alpha);
} else {
if (beta > -t3) { /* 3s (b) */
return mean - sd * hnrs_a_b(-beta, -alpha);
} else { /* 3s (c) */
return mean - sd * ers_a_b(-beta, -alpha);
}
}
}
}
SEXP do_rtruncnorm(SEXP s_n, SEXP s_a, SEXP s_b, SEXP s_mean, SEXP s_sd) {
R_len_t i, nn;
UNPACK_INT(s_n, n);
if (NA_INTEGER == n)
error("n is NA - aborting.");
UNPACK_REAL_VECTOR(s_a , a , n_a);
UNPACK_REAL_VECTOR(s_b , b , n_b);
UNPACK_REAL_VECTOR(s_mean, mean, n_mean);
UNPACK_REAL_VECTOR(s_sd , sd , n_sd);
nn = MAX(n, MAX(MAX(n_a, n_b), MAX(n_mean, n_sd)));
ALLOC_REAL_VECTOR(s_ret, ret, nn);
GetRNGstate();
for (i = 0; i < nn; ++i) {
const double ca = a[i % n_a];
const double cb = b[i % n_b];
const double cmean = mean[i % n_mean];
const double csd = sd[i % n_sd];
if (R_FINITE(ca) && R_FINITE(cb)) {
ret[i] = r_truncnorm(ca, cb, cmean, csd);
} else if (R_NegInf == ca && R_FINITE(cb)) {
ret[i] = r_righttruncnorm(cb, cmean, csd);
} else if (R_FINITE(ca) && R_PosInf == cb) {
ret[i] = r_lefttruncnorm(ca, cmean, csd);
} else if (R_NegInf == ca && R_PosInf == cb) {
ret[i] = rnorm(cmean, csd);
} else {
ret[i] = NA_REAL;
}
R_CheckUserInterrupt();
}
PutRNGstate();
UNPROTECT(1); /* s_ret */
return s_ret;
}
| 29,033
|
https://github.com/gjvanhalem/NetCICD-developer-toolbox/blob/master/runonce.sh
|
Github Open Source
|
Open Source
|
Apache-2.0, MIT
| 2,021
|
NetCICD-developer-toolbox
|
gjvanhalem
|
Shell
|
Code
| 1,097
| 3,082
|
#!/bin/bash
nexus_plugin="0.4.0"
echo "****************************************************************************************************************"
echo " Start clean"
echo "****************************************************************************************************************"
docker-compose down --remove-orphans
rm *_token
rm keycloak_create.log
echo " "
echo "****************************************************************************************************************"
echo " Cleaning Databases"
echo "****************************************************************************************************************"
sudo chown $USER:$USER netcicd-db/db
sudo rm -rf netcicd-db/db/*
sudo rm -rf netcicd-db/db/.*
echo " "
echo "****************************************************************************************************************"
echo " Cleaning Gitea"
echo "****************************************************************************************************************"
sudo rm -rf gitea/data/*
echo " "
echo "****************************************************************************************************************"
echo " Cleaning Jenkins"
echo "****************************************************************************************************************"
sudo rm -rf jenkins/jenkins_home/*
sudo rm -rf jenkins/jenkins_home/.*
echo " "
echo "****************************************************************************************************************"
echo " Cleaning Nexus"
echo "****************************************************************************************************************"
sudo rm -rf nexus/data/*
echo " "
echo "****************************************************************************************************************"
echo " Collecting Nexus Keycloak plugin jar files"
echo "****************************************************************************************************************"
if [ -f "nexus/nexus3-keycloak-plugin-$nexus_plugin-bundle.kar" ]; then
echo " Nexus plugin exists"
else
echo " Get Nexus plugin"
wget --directory-prefix=nexus https://github.com/flytreeleft/nexus3-keycloak-plugin/releases/download/v$nexus_plugin/nexus3-keycloak-plugin-$nexus_plugin-bundle.kar
fi
echo " "
echo "****************************************************************************************************************"
echo " Cleaning Argos"
echo "****************************************************************************************************************"
sudo rm -rf argos/config/*
sudo rm -rf argos/data/*
echo " "
echo "****************************************************************************************************************"
echo " Cleaning NodeRED"
echo "****************************************************************************************************************"
sudo chown $USER:$USER nodered/data
sudo rm -rf nodered/data/*
echo " "
echo "****************************************************************************************************************"
echo " Cleaning Jupyter Notebook"
echo "****************************************************************************************************************"
sudo chown $USER:$USER jupyter/data
sudo rm -rf jupyter/data/*
echo " "
echo "****************************************************************************************************************"
echo " Cleaning Portainer"
echo "****************************************************************************************************************"
sudo chown $USER:$USER portainer/data
sudo rm -rf portainer/data/*
echo " "
echo "****************************************************************************************************************"
echo " Making sure all containers are reachable locally with the name in the"
echo " hosts file."
echo " "
sudo chmod o+w /etc/hosts
if grep -q "gitea" /etc/hosts; then
echo " Gitea exists in /etc/hosts"
else
echo " Add Gitea to /etc/hosts"
sudo echo "172.16.11.3 gitea" >> /etc/hosts
fi
if grep -q "jenkins" /etc/hosts; then
echo " Jenkins exists in /etc/hosts"
else
echo " Add Jenkins to /etc/hosts"
sudo echo "172.16.11.8 jenkins" >> /etc/hosts
fi
if grep -q "nexus" /etc/hosts; then
echo " Nexus exists in /etc/hosts"
else
echo " Add Nexus to /etc/hosts"
sudo echo "172.16.11.9 nexus" >> /etc/hosts
fi
if grep -q "argos" /etc/hosts; then
echo " Argos exists in /etc/hosts"
else
echo " Add Argos to /etc/hosts"
sudo echo "172.16.11.10 argos" >> /etc/hosts
fi
if grep -q "keycloak" /etc/hosts; then
echo " Keycloak exists in /etc/hosts"
else
echo " Add Keycloak to /etc/hosts"
sudo echo "172.16.11.11 keycloak" >> /etc/hosts
fi
if grep -q "nodered" /etc/hosts; then
echo " Node Red exists in /etc/hosts"
else
echo " Add Node Red to /etc/hosts"
sudo echo "172.16.11.13 nodered" >> /etc/hosts
fi
if grep -q "jupyter" /etc/hosts; then
echo " Jupyter Notebook exists in /etc/hosts"
else
echo " Add Jupyter to /etc/hosts"
sudo echo "172.16.11.14 jupyter" >> /etc/hosts
fi
if grep -q "portainer" /etc/hosts; then
echo " Portainer exists in /etc/hosts"
else
echo " Add Portainer to /etc/hosts"
sudo echo "172.16.11.15 portainer" >> /etc/hosts
fi
if grep -q "cml" /etc/hosts; then
echo " cml exists in /etc/hosts"
else
echo " Add Cisco Modeling Labs to /etc/hosts"
sudo echo "192.168.32.148 cml" >> /etc/hosts
fi
sudo chmod o-w /etc/hosts
echo " "
echo "****************************************************************************************************************"
echo " git clone Nexus CasC plugin and build .kar file"
echo "****************************************************************************************************************"
git clone https://github.com/AdaptiveConsulting/nexus-casc-plugin.git
cd nexus-casc-plugin
mvn package
cp target/*.kar ../nexus/
cd ..
rm -rf nexus-casc-plugin/
echo " "
echo "****************************************************************************************************************"
echo " Creating containers"
echo "****************************************************************************************************************"
docker-compose up -d --build --remove-orphans
echo " "
echo "****************************************************************************************************************"
echo " Wait until keycloak is running"
echo "****************************************************************************************************************"
until $(curl --output /dev/null --silent --head --fail http://keycloak:8080); do
printf '.'
sleep 5
done
echo " "
echo "****************************************************************************************************************"
echo " Adding keycloak RADIUS plugin"
echo "****************************************************************************************************************"
docker exec -it keycloak sh -c "/opt/radius/scripts/keycloak.sh"
echo " "
echo "Reloading "
docker restart keycloak
until $(curl --output /dev/null --silent --head --fail http://keycloak:8080); do
printf '.'
sleep 5
done
echo " "
echo "****************************************************************************************************************"
echo " Creating keycloak setup"
echo "****************************************************************************************************************"
docker exec -it keycloak sh -c "/opt/jboss/keycloak/bin/create-realm.sh" > keycloak_create.log
echo " "
cat keycloak_create.log
echo " "
echo "****************************************************************************************************************"
echo " Creating gitea setup"
echo "****************************************************************************************************************"
gitea/gitea_install.sh
echo " "
echo "****************************************************************************************************************"
echo " Creating jenkins setup"
echo "****************************************************************************************************************"
#config for ioc_auth plugin: only need to replace secret in casc.yaml
jenkins_client_id=$(grep JENKINS_token keycloak_create.log | cut -d' ' -f3 | tr -d '\r' )
docker exec -it jenkins sh -c "sed -i -e 's/oic_secret/\"$jenkins_client_id\"/' /var/jenkins_conf/casc.yaml"
echo "Reloading "
docker restart jenkins
echo " "
echo "****************************************************************************************************************"
echo " Creating nexus setup"
echo "****************************************************************************************************************"
docker cp keycloak:/opt/jboss/keycloak/bin/keycloak-nexus.json nexus/keycloak-nexus.json
docker cp nexus/keycloak-nexus.json nexus:/opt/sonatype/nexus/etc/keycloak.json
echo "Reloading "
docker restart nexus
until $(curl --output /dev/null --silent --head --fail http://nexus:8081); do
printf '.'
sleep 5
done
echo " "
echo "****************************************************************************************************************"
echo " Saving Keycloak self-signed certificate"
openssl s_client -showcerts -connect keycloak:8443 </dev/null 2>/dev/null|openssl x509 -outform PEM >./jenkins/keystore/keycloak.pem
echo " "
echo " Copy certificate into Jenkins keystore"
echo "****************************************************************************************************************"
docker cp jenkins:/opt/java/openjdk/jre/lib/security/cacerts ./jenkins/keystore/cacerts
chmod +w ./jenkins/keystore/cacerts
keytool -import -alias Keycloak -keystore ./jenkins/keystore/cacerts -file ./jenkins/keystore/keycloak.pem -storepass changeit -noprompt
docker cp ./jenkins/keystore/cacerts jenkins:/opt/java/openjdk/jre/lib/security/cacerts
echo "Reloading "
docker restart jenkins
until $(curl --output /dev/null --silent --head --fail http://jenkins:8080/whoAmI); do
printf '.'
sleep 5
done
echo " "
echo "****************************************************************************************************************"
echo "NetCICD Toolkit install done "
echo " "
echo "You can reach the servers on:"
echo " "
echo " Gitea: http://gitea:3000"
echo " Jenkins: http://jenkins:8080"
echo " Nexus: http://nexus:8081"
echo " Argos: http://argos"
echo " Keycloak: http://keycloak:8443"
echo " Node-red: http://nodered:1880"
echo " Jupyter: http://jupyter:8888"
echo " Portainer: http://portainer:9000"
echo " "
echo "****************************************************************************************************************"
echo "Cleaning up"
echo "****************************************************************************************************************"
rm *_token
rm keycloak_create.log
echo " "
echo "****************************************************************************************************************"
echo " Manual steps..."
echo " "
echo " In order for Jenkins to be able to run the jenkinsfiles, jenkins needs the jenkins-jenkins user to have a token."
echo " "
echo " * Go to http://jenkins:8080/user/jenkins-jenkins/configure (jenkins-jenkins/netcicd). "
echo " "
echo " * Add the token. Copy this token, and paste it into a temporary file. Log out."
echo " "
echo " * Go to http://jenkins:8080/credentials/store/system/domain/_/credential/jenkins-jenkins/update (netcicd/netcicd)"
echo " "
echo " * Click Change Password and paste the token there. Delete the temporary file."
echo " "
echo " In order for Jenkins to be able to scan git, the git-jenkins users needs to log in once."
echo " "
echo " * Go to http://gitea:3000/user/login?redirect_to=%2f"
echo " "
echo " * Log in as (git-jenkins/netcicd) and set the password. You must use the same password as used in"
echo " Jenkins Credentials git-jenkins. Use something safe."
echo " "
echo " The pipeline uses guest/guest in order to log in to CML. Change this to your own credentials in "
echo " http://jenkins:8080/credentials/store/system/domain/_/credential/CML-SIM-CRED/update"
echo " "
echo " Due to limitations in Keycloak, do **not** use docker-compose down. Keycloak will no longer function after this."
echo " "
echo " Stop the environment with ./down, start with ./up"
echo " "
echo "****************************************************************************************************************"
| 10,598
|
https://github.com/ManuGar/objectDetectionAPI/blob/master/configs_slurm/tensorflow.sh
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
objectDetectionAPI
|
ManuGar
|
Shell
|
Code
| 47
| 357
|
#!/bin/sh
# Carga de librerías.
module load cuda/10.1.105
module load cudnn/7.6
module load python
# Configuración PYTHONPATH.
export PYTHONPATH=$PYTHONPATH:/home/jheras/ws/holms/models/research:/home/jheras/ws/holms/models/research/slim
# Configuración de parámetros para entrenar.
PIPELINE_CONFIG_PATH=/home/jheras/ws/holms/models/research/pets/faster_rcnn_resnet101_pets.config
MODEL_DIR=/home/jheras/ws/holms/models/research/pets/faster_rcnn_resnet101_coco_11_06_2017/
NUM_TRAIN_STEPS=50000
SAMPLE_1_OF_N_EVAL_EXAMPLES=1
# Instrucción que entrena modelo tensorflow.
#python3 object_detection/model_main.py --pipeline_config_path=${PIPELINE_CONFIG_PATH} --model_dir=${MODEL_DIR} --num_train_steps=${NUM_TRAIN_STEPS} --sample_1_of_n_eval_examples=$SAMPLE_1_OF_N_EVAL_EXAMPLES --alsologtostderr --worker_replicas=2 --num_clones=2 --ps_tasks=1
#exit 0
| 3,015
|
https://github.com/michaldomino/Voice-interface-optimization/blob/master/lib/data/DTOs/requests/refresh_token_request.dart
|
Github Open Source
|
Open Source
|
MIT
| null |
Voice-interface-optimization
|
michaldomino
|
Dart
|
Code
| 15
| 50
|
class RefreshTokenRequest {
String refresh;
RefreshTokenRequest(this.refresh);
Map<String, dynamic> toJson() => {
'refresh': refresh,
};
}
| 5,921
|
https://github.com/ishine/universal-data-tool/blob/master/src/components/Header/index.story.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
universal-data-tool
|
ishine
|
JavaScript
|
Code
| 45
| 147
|
// @flow
import React from "react"
import { storiesOf } from "@storybook/react"
import Header from "./"
storiesOf("Header", module)
.add("Tabs", () => (
<Header
title="Some Header"
tabs={["Setup", "Samples", "Label"]}
currentTab="Samples"
/>
))
.add("Sample Color", () => (
<Header
title="Some Header"
tabs={["Setup", "Samples", "Label"]}
currentTab="Samples"
/>
))
| 49,599
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.